index.ts

47.9 KB · raw

1import {2  detectCardForm,3  detectLoginFields,4  findOTPDigitBoxGroup,5  getDeepActiveInput,6  getPageDomain,7  isAnyCredentialForm,8  isEmailFirstForm,9  isLoginForm,10  isSignupForm,11  isTOTPField,12  isVisible,13} from "./detect";14import {15  CardSelectorEntry,16  injectFieldIcon,17  SelectorEntry,18  showAutofillSelector,19  showCardSelector,20  showPasskeyAvailable,21  showPasskeyProGate,22  showPasskeyRegistrationOffer,23  showRememberSiteToast,24  showTOTPSelector,25} from "./inject";26import { detectBrowser } from "../shared/browser";27import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";28import { fillCardForm, fillFields, fillOTPDigitBoxes, fillTOTPCode, setNativeValue } from "./fill";29import { resolveAutofillInteractionTargets } from "./interaction";30import { setupSaveDetection } from "./save";31import { contentMLDetector } from "./content-ml-detector";32import { detectPasswordPolicy } from "./policy";33import type { FieldPrediction } from "../shared/ml";34import type { SavedIdentity, VaultEntry } from "../shared/types";3536// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value37// so we can tear down listeners if we ever need to re-process the same field.38// When the input is GC'd (SPA nav, React re-render), the map entry goes with39// it and we can re-inject without leaking the old handler.40const processedInputs = new WeakMap<HTMLInputElement, () => void>();41const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4243let currentDismiss: (() => void) | null = null;44// Field whose selector is currently open — used to avoid dismiss+reopen flicker45let currentAnchorField: HTMLInputElement | null = null;46// Prevents two concurrent handleFieldInteraction calls for the same field47const pendingInteractions = new WeakSet<HTMLInputElement>();48// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).49// Suppresses spurious reopens until focus moves to a different field. Layer 150// of the dismissal model — see Projects.md §4.12.51let lastDismissedField: HTMLInputElement | null = null;5253// ── Dismissal lock (Layer 2) ────────────────────────────────────────54// After any user-initiated dismiss, briefly block ALL reopens regardless of55// which field is focused. Catches the case where a page rapidly moves focus56// between fields after Escape — without this, focus moving to a SECOND field57// in <100ms would re-trigger the popup before the user finished dismissing.58const DISMISS_LOCK_MS = 800;59let dismissLock = false;60let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;61// Set when the inline popup was summoned specifically for a passkey-unlock62// flow. The VAULT_UNLOCKED handler checks this to skip re-triggering autofill63// (the passkey toast handles the next step instead).64let passkeySummonActive = false;65// Set while the passkey approval toast is visible. Prevents handleFieldInteraction66// from opening the autofill selector alongside it. Cleared by a window message67// posted by inject.tsx when the toast closes (and by DISMISS_PASSKEY_TOAST).68let passkeyToastActive = false;69function startDismissLock(): void {70  dismissLock = true;71  if (dismissLockTimer) clearTimeout(dismissLockTimer);72  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);73}74function canOpen(): boolean { return !dismissLock; }7576// ── Fill-success lock ───────────────────────────────────────────────77// After Peach autofills a form, the popup must NOT reappear on the filled78// fields, on the submit button (some sites refocus it briefly), or on any79// field in that form — even when host-page DOM mutations or the form's own80// validation flow refocus an input. Implemented as a WeakSet of forms plus81// a page-level timestamp:82//   - filledForms: every form Peach has filled this page session. Survives83//     until the form leaves the DOM (WeakSet GC).84//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders85//     window for fields that aren't inside a <form> element (some SPAs).86// SPA navigation resets pageFilledAt via the urlObserver below; filledForms87// self-empties as old form elements get GC'd.88const filledForms = new WeakSet<HTMLFormElement>();89let pageFilledAt: number | null = null;90const PAGE_FILL_GRACE_MS = 3000;9192function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {93  for (const f of fields) {94    if (!f) continue;95    const form = f.closest("form");96    if (form) filledForms.add(form);97  }98  pageFilledAt = Date.now();99}100101function wasAlreadyFilled(field: HTMLInputElement): boolean {102  const form = field.closest("form");103  if (form && filledForms.has(form)) return true;104  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;105  return false;106}107108function clearFillStateForExplicitSummon(field: HTMLInputElement): void {109  const form = field.closest("form");110  if (form) filledForms.delete(form);111  pageFilledAt = null;112}113114// Some sites briefly focus the submit button when the user clicks it (visual115// feedback, blur/focus dance for validation animations). Catch those at the116// focusin layer so we don't re-trigger handleFieldInteraction for an event117// target that was never going to be a credential field anyway.118function isSubmitButton(el: EventTarget | null): boolean {119  if (!(el instanceof HTMLElement)) return false;120  if (el instanceof HTMLButtonElement && el.type !== "button") return true;121  if (el instanceof HTMLInputElement && el.type === "submit") return true;122  if (el.getAttribute("type") === "submit") return true;123  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();124  if (!text || text.length > 24) return false;125  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);126}127128function debounce<T extends (...args: unknown[]) => void>(129  fn: T,130  ms: number131): (...args: Parameters<T>) => void {132  let timer: ReturnType<typeof setTimeout>;133  return (...args: Parameters<T>) => {134    clearTimeout(timer);135    timer = setTimeout(() => fn(...args), ms);136  };137}138139function showToast(message: string): void {140  const toast = document.createElement("div");141  toast.style.cssText = `142    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);143    background: #131109; color: #F0E8D8; padding: 8px 16px;144    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;145    font-size: 11px; z-index: 2147483647; opacity: 0;146    transition: opacity 200ms ease;147    border: 1px solid rgba(240,232,216,0.07);148    pointer-events: none;149  `;150  toast.textContent = message;151  document.body.appendChild(toast);152  requestAnimationFrame(() => { toast.style.opacity = "1"; });153  setTimeout(() => {154    toast.style.opacity = "0";155    setTimeout(() => toast.remove(), 200);156  }, 2000);157}158159function showSearchPalette(): void {160  const host = document.createElement("div");161  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";162  document.body.appendChild(host);163  const shadow = host.attachShadow({ mode: "closed" });164165  const style = document.createElement("style");166  style.textContent = `167    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;168      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;169      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}170    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);171      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}172    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}173    .s{padding:8px 12px}174    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);175      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;176      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}177    .l{max-height:220px;overflow-y:auto}178    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}179    .e:hover{background:rgba(240,232,216,.06)}180    .et{font-size:12px}181    .eu{font-size:10px;color:rgba(240,232,216,.45)}182    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}183  `;184185  let allEntries: SelectorEntry[] = [];186  let query = "";187188  const panel = document.createElement("div");189  panel.className = "p";190191  const hdr = document.createElement("div");192  hdr.className = "h";193  const hdrText = document.createElement("span");194  hdrText.textContent = "No form detected — search your vault";195  const closeBtn = document.createElement("button");196  closeBtn.className = "x";197  closeBtn.textContent = "✕";198  hdr.appendChild(hdrText);199  hdr.appendChild(closeBtn);200201  const searchWrap = document.createElement("div");202  searchWrap.className = "s";203  const searchInput = document.createElement("input");204  searchInput.placeholder = "search...";205  searchWrap.appendChild(searchInput);206207  const list = document.createElement("div");208  list.className = "l";209210  panel.appendChild(hdr);211  panel.appendChild(searchWrap);212  panel.appendChild(list);213  shadow.appendChild(style);214  shadow.appendChild(panel);215216  function close() { host.remove(); }217218  closeBtn.onclick = close;219220  function onKeyDown(e: KeyboardEvent) {221    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }222  }223  document.addEventListener("keydown", onKeyDown, true);224225  function render() {226    const q = query.toLowerCase();227    const filtered = q228      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))229      : allEntries;230    list.innerHTML = "";231    if (filtered.length === 0) {232      const em = document.createElement("div");233      em.className = "em";234      em.textContent = query ? "no matches" : "vault is empty";235      list.appendChild(em);236      return;237    }238    for (const entry of filtered.slice(0, 20)) {239      const row = document.createElement("div");240      row.className = "e";241      const title = document.createElement("div");242      title.className = "et";243      title.textContent = entry.title;244      row.appendChild(title);245      if (entry.username) {246        const user = document.createElement("div");247        user.className = "eu";248        user.textContent = entry.username;249        row.appendChild(user);250      }251      row.onclick = async () => {252        // MV-1: vault-wide search list is a cross-domain summon — the user253        // explicitly picked this entry to fill on this page.254        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, explicitSummon: true } });255        const r = resp as { ok: boolean; data?: { password?: string } };256        if (r.ok && r.data?.password) {257          let alreadyWritten = false;258          try {259            await navigator.clipboard.writeText(r.data.password);260            alreadyWritten = true;261          } catch (err) {262            console.warn("[Peach] clipboard write denied:", err);263          }264          const copyResp = await chrome.runtime.sendMessage({265            type: "COPY",266            payload: { text: r.data.password, label: "Password", alreadyWritten },267          }) as { ok?: boolean } | undefined;268          if (alreadyWritten || copyResp?.ok) {269            showToast("Password copied");270          } else {271            showToast("Could not copy password — clipboard blocked");272          }273        } else {274          showToast("Could not copy password");275        }276        close();277        document.removeEventListener("keydown", onKeyDown, true);278      };279      list.appendChild(row);280    }281  }282283  searchInput.oninput = () => { query = searchInput.value; render(); };284285  // MV-2: the summon palette is an explicit user gesture (keyboard shortcut /286  // toolbar icon), so it may load the vault-wide inventory.287  fetchAutofillEntries(getPageDomain(), true, true).then(result => {288    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }289    allEntries = result.entries;290    render();291    searchInput.focus();292  });293}294295function findTOTPField(root: Document | Element = document): HTMLInputElement | null {296  const inputs = root.querySelectorAll<HTMLInputElement>("input");297  for (const input of inputs) {298    if (isTOTPField(input)) return input;299  }300  return null;301}302303function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {304  const form = passwordEl.closest("form");305  return findTOTPField(form ?? document);306}307308309async function handleAutofill(310  _field: HTMLInputElement,311  usernameEl: HTMLInputElement | null,312  passwordEl: HTMLInputElement | null,313  entry: VaultEntry,314  emailEl?: HTMLInputElement | null315): Promise<HTMLInputElement | null> {316  if (!entry.username && !entry.password && !entry.email) return null;317  const pageDomain = getPageDomain();318  const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;319  // Fill the email field with entry.email if set; fall back to entry.username when320  // it looks like an email address (sites that store email-as-username and have a321  // separate email field on signup forms).322  const emailValue = entry.email ?? (entry.username?.includes("@") ? entry.username : "");323  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain, emailEl, emailValue);324  let filledTOTPField: HTMLInputElement | null = null;325326  if (entry.canary) {327    chrome.runtime.sendMessage({328      type: "FIRE_CANARY_PING",329      payload: {330        webhookUrl: entry.canary.webhookUrl,331        entryTitle: entry.title,332        trigger: "autofilled",333      },334    }).catch(() => {});335    chrome.runtime.sendMessage({336      type: "UPDATE_ENTRY",337      payload: {338        id: entry.id,339        patch: {340          canary: {341            ...entry.canary,342            lastPinged: Date.now(),343            pingCount: (entry.canary.pingCount ?? 0) + 1,344          },345        },346      },347    }).catch(() => {});348  }349350  // The background sends a freshly-generated 6-digit code (totpCode), never the351  // base32 seed (SEV-3-C). Fill the code straight in.352  const totpCode = (entry as { totpCode?: string }).totpCode;353  if (totpCode) {354    const code = totpCode;355    const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;356    if (fillTOTPCode(totpField, code)) {357      filledTOTPField = totpField;358    }359    let alreadyWritten = false;360    try {361      await navigator.clipboard.writeText(code);362      alreadyWritten = true;363    } catch (err) {364      console.warn("[Peach] clipboard write denied:", err);365    }366    const response = await chrome.runtime.sendMessage({367      type: "COPY",368      payload: { text: code, label: "TOTP", alreadyWritten },369    });370    if (filledTOTPField) {371      showToast("2FA code filled");372    } else if (alreadyWritten || (response as { ok?: boolean }).ok) {373      // Don't render the live code into the light-DOM toast — the page can read374      // it from the DOM and consume the one-time code (audit LOW). The code is375      // already on the clipboard; just confirm.376      showToast("2FA code copied");377    } else {378      showToast("Could not copy TOTP — clipboard blocked");379    }380  }381382  return filledTOTPField;383}384385async function fetchAutofillEntries(386  domain: string,387  includeAll = false,388  userGesture = false389): Promise<{ entries: SelectorEntry[]; locked: boolean }> {390  const response = await chrome.runtime.sendMessage({391    type: "AUTOFILL_QUERY",392    payload: { domain, includeAll, userGesture },393  });394  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };395  if (!res.ok && res.error === "vault_locked") {396    return { entries: [], locked: true };397  }398  return { entries: res.data ?? [], locked: false };399}400401async function fetchTOTPEntries(402  domain: string403): Promise<{ entries: SelectorEntry[]; locked: boolean }> {404  const response = await chrome.runtime.sendMessage({405    type: "AUTOFILL_QUERY",406    payload: { domain, kind: "totp" },407  });408  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };409  if (!res.ok && res.error === "vault_locked") {410    return { entries: [], locked: true };411  }412  return { entries: res.data ?? [], locked: false };413}414415416function resolveAutofillFieldType(417  el: HTMLInputElement,418  predictedType?: FieldPrediction["type"] | null419): "password" | "username" | "email" | null {420  if (421    predictedType === "password" ||422    predictedType === "username" ||423    predictedType === "email"424  ) {425    return predictedType;426  }427428  const detected = detectLoginFields().find((field) => field.el === el)?.type;429  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {430    return detected;431  }432433  const htmlType = el.type.toLowerCase();434  if (htmlType === "password") return "password";435  if (htmlType === "email") return "email";436  return null;437}438439async function openAutofillSelector(440  anchorField: HTMLInputElement,441  usernameEl: HTMLInputElement | null,442  passwordEl: HTMLInputElement | null,443  domainEntries: SelectorEntry[],444  loadSearchableEntries: () => Promise<SelectorEntry[]>,445  domain: string,446  identityKind: "email" | "username",447  emailEl?: HTMLInputElement | null448): Promise<void> {449  // No saved entries for this site → signup/new-account mode.450  // Fetch vault identities for the identity-first surface and locate451  // the confirm-password field so "Copy & fill" can populate it too.452  const isSignup = domainEntries.length === 0;453  let savedIdentities: SavedIdentity[] | undefined;454  let confirmEl: HTMLInputElement | null = null;455  if (isSignup) {456    try {457      const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as458        { ok: boolean; data?: SavedIdentity[] } | null;459      if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;460    } catch { /* silent fallback */ }461462    const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;463    const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));464    confirmEl = allPwInputs.find(465      (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)466    ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);467  }468469  currentDismiss?.();470  currentAnchorField = anchorField;471  currentDismiss = showAutofillSelector(472    anchorField,473    domainEntries,474    async (id: string) => {475      currentDismiss = null;476      currentAnchorField = null;477      const entryResponse = await chrome.runtime.sendMessage({478        type: "GET_ENTRY_FOR_FILL",479        payload: { id },480      });481      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;482      if (entry) {483        const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry, emailEl);484        recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);485        // Offer to remember the current site for this entry only if none of486        // its known domains (primary + additional) match — otherwise the487        // user already mapped it and the prompt would be noise.488        const pageDomain = location.hostname.replace(/^www\./, "");489        const entryDomains = new Set<string>();490        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {491          try {492            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));493          } catch { /* ignore unparseable */ }494        }495        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {496          showRememberSiteToast(pageDomain, entry.id);497        }498      }499    },500    {501      domain,502      loadSearchableEntries,503      isSignup,504      identityKind,505      hasEmailField: !!emailEl,506      savedIdentities,507      onFillFields: (username, password, email) => {508        const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;509        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain(), emailEl, email);510        if (password && confirmEl) setNativeValue(confirmEl, password);511        recordFillSuccess(anchorField, usernameEl, passwordEl);512      },513      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },514    }515  );516}517518async function openTOTPSelector(anchorField: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[]): Promise<void> {519  if (!canOpen()) return;520  if (currentDismiss && currentAnchorField === anchorField) return;521  if (anchorField !== lastDismissedField) lastDismissedField = null;522  if (anchorField === lastDismissedField) return;523  if (wasAlreadyFilled(anchorField)) return;524525  const domain = getPageDomain();526  const result = await fetchTOTPEntries(domain);527528  if (result.locked) {529    currentDismiss?.();530    currentAnchorField = anchorField;531    currentDismiss = showAutofillSelector(532      anchorField,533      [],534      () => {},535      {536        domain,537        locked: true,538        onUnlocked: () => void openTOTPSelector(anchorField),539        onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },540      }541    );542    return;543  }544545  if (result.entries.length === 0) {546    lastDismissedField = anchorField;547    startDismissLock();548    showToast("No 2FA entries for this site — add a code in Peach first");549    return;550  }551552  currentDismiss?.();553  currentAnchorField = anchorField;554  currentDismiss = showTOTPSelector(555    anchorField,556    result.entries,557    async (id: string) => {558      try {559        const entryResponse = await chrome.runtime.sendMessage({560          type: "GET_ENTRY_FOR_FILL",561          payload: { id },562        }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;563        const entry = entryResponse?.ok ? entryResponse.data : undefined;564        const code = (entry as { totpCode?: string } | undefined)?.totpCode;565        if (!code) return;566        if (otpDigitBoxes && otpDigitBoxes.length > 1) {567          fillOTPDigitBoxes(otpDigitBoxes, code);568        } else {569          setNativeValue(anchorField, code);570        }571        recordFillSuccess(anchorField);572        showToast("2FA code filled");573      } finally {574        currentDismiss = null;575        currentAnchorField = null;576      }577    },578    {579      domain,580      onDismiss: () => {581        lastDismissedField = anchorField;582        startDismissLock();583        currentDismiss = null;584        currentAnchorField = null;585      },586    }587  );588}589590591async function handleFieldInteraction(592  anchorField?: HTMLInputElement | null,593  explicitSummon = false594): Promise<void> {595  const field = anchorField ?? getDeepActiveInput();596  if (!field) return;597  if (!isVisible(field)) return;598599  // Passkey toast is visible — don't open the credential selector alongside it.600  if (passkeyToastActive) return;601602  // Layer 2: post-dismiss global lock. Catches rapid focus moves between603  // fields immediately after Escape/click-outside.604  if (!canOpen()) return;605606  // If a selector is already open for this exact field, don't flicker it.607  if (currentDismiss && currentAnchorField === field) return;608609  // If focus moved to a different field, the previous per-field dismiss lock610  // no longer applies.611  if (field !== lastDismissedField) lastDismissedField = null;612  // Layer 1: the user explicitly dismissed this field's selector — don't613  // reopen it until focus has genuinely moved away and come back.614  if (field === lastDismissedField) return;615616  // Fill-success lock: Peach already filled this form (or fired a fill617  // anywhere on the page within the grace window). Sites often refocus an618  // input on submit click, on validation, or on a transition to a success619  // state — none of those should re-open the popup.620  if (wasAlreadyFilled(field)) return;621622  // Prevent two concurrent calls for the same field (e.g. focusin + icon click623  // firing simultaneously — the second call would dismiss the first's selector).624  if (pendingInteractions.has(field)) return;625  pendingInteractions.add(field);626627  try {628    // Multi-digit OTP entry: individual maxLength=1 boxes get no icon (too small)629    // but the TOTP selector opens on focus and fills every box at once.630    const otpGroup = findOTPDigitBoxGroup(field);631    if (otpGroup) {632      await openTOTPSelector(otpGroup[0]!, otpGroup);633      return;634    }635636    if (isTOTPField(field)) {637      const formFields = detectLoginFields();638      if (!isLoginForm(formFields) && !isSignupForm(formFields)) {639        await openTOTPSelector(field);640        return;641      }642    }643644    const fieldType = field.type.toLowerCase();645646    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {647      return preds[0] ?? null;648    });649650    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {651      const timeout = setTimeout(() => resolve(null), 150);652      mlPromise.then((pred) => {653        clearTimeout(timeout);654        resolve(pred);655      });656    });657658    if (passkeyToastActive) return;659660    if (!explicitSummon && fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {661      return;662    }663664    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);665    if (autofillFieldType) {666      reattachListeners(field, autofillFieldType);667    }668669    let fields = detectLoginFields();670    const targets = resolveAutofillInteractionTargets(field, fields, explicitSummon);671    if (!targets.shouldOpen) {672      return;673    }674675    const domain = getPageDomain();676    const firstResult = await fetchAutofillEntries(domain);677    if (passkeyToastActive) return;678679    // Vault is locked — show an inline unlock prompt.680    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so681    // there is no double-trigger race between onUnlocked and the broadcast.682    if (firstResult.locked) {683      currentDismiss?.();684      currentAnchorField = field;685      currentDismiss = showAutofillSelector(686        field,687        [],688        () => {},689        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }690      );691      return;692    }693694    const entries = firstResult.entries;695    // MV-2: the vault-wide list is NOT fetched here. It is loaded lazily,696    // only when the user activates the search affordance inside the inline697    // popup (an explicit gesture), via the thunk below. Passive form focus698    // never ships the full account inventory into the page's content-script699    // world — and never hands out the entry ids that made MV-1 a full-vault700    // primitive.701    const loadSearchableEntries = async (): Promise<SelectorEntry[]> =>702      (await fetchAutofillEntries(domain, true, true)).entries;703704    if (passkeyToastActive) return;705706    const pwField = fields.find((f) => f.type === "password");707    // For email-first flows there is no password field on this step — that is expected.708    if (!explicitSummon && !pwField && !isEmailFirstForm(fields)) return;709    const usernameEl = targets.usernameEl;710    const passwordEl = targets.passwordEl;711    const emailEl = targets.emailEl;712713    await openAutofillSelector(714      field,715      usernameEl,716      passwordEl,717      entries,718      loadSearchableEntries,719      domain,720      autofillFieldType === "email" ? "email" : "username",721      emailEl,722    );723  } finally {724    pendingInteractions.delete(field);725  }726}727728async function onFocusIn(e: Event): Promise<void> {729  // Submit-button focus: catch the brief refocus some sites do when the730  // user clicks the login/submit button. Without this guard, that focus731  // event reaches handleFieldInteraction → getDeepActiveInput, and on732  // pages where the button is also a labelled <input> we briefly attempt733  // to open the popup over the very button the user just clicked.734  if (isSubmitButton(e.target)) return;735  await handleFieldInteraction();736}737738function reattachListeners(739  el: HTMLInputElement,740  detectedType?: "password" | "username" | "email",741  contextFields?: ReturnType<typeof detectLoginFields>742): void {743  if (processedInputs.has(el)) return;744  if (!resolveAutofillFieldType(el, detectedType)) return;745  // Only inject icon when a credential form is present on the page746  const fields = contextFields ?? detectLoginFields();747  if (!isAnyCredentialForm(fields)) return;748749  const cleanup = injectFieldIcon(el, () => {750    currentDismiss?.();751    currentDismiss = null;752    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock753    dismissLock = false; // ...and the global lock754    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }755    clearFillStateForExplicitSummon(el);756    el.focus({ preventScroll: true });757    void handleFieldInteraction(el, true);758  });759  processedInputs.set(el, cleanup);760}761762const debouncedReattach = debounce(() => {763  const allFields = detectLoginFields();764  if (!isAnyCredentialForm(allFields)) return;765  const newFields = allFields.filter(766    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)767  );768  for (const f of newFields) {769    reattachListeners(f.el, f.type, allFields);770  }771  // 200ms debounce — below this, Peach and the host page's reactive layer772  // fight over the same layout properties every frame on React/Vue/Angular773  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.774}, 200);775776function setupMutationObserver(): void {777  const observer = new MutationObserver(debouncedReattach);778  observer.observe(document.body, {779    childList: true,780    subtree: true,781    attributes: true,782    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],783  });784}785786function initialScan(aggressionLevel = 0, isFinalPass = false) {787  const allFields = detectLoginFields();788  const hasKnownForm = isAnyCredentialForm(allFields);789790  if (aggressionLevel === 0 && !hasKnownForm) return;791792  const newFields = allFields.filter(793    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)794  );795796  for (const f of newFields) {797    reattachListeners(f.el, f.type, allFields);798  }799800  // Level 2, final pass: inject icon on any visible password field even if801  // the form-context gate in reattachListeners would normally skip it.802  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {803    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');804    for (const el of pwInputs) {805      if (isVisible(el) && !processedInputs.has(el)) {806        const cleanup = injectFieldIcon(el, () => {807          currentDismiss?.();808          currentDismiss = null;809          lastDismissedField = null;810          dismissLock = false;811          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }812          clearFillStateForExplicitSummon(el);813          el.focus({ preventScroll: true });814          void handleFieldInteraction(el, true);815        });816        processedInputs.set(el, cleanup);817      }818    }819  }820}821822// ── TOTP-only fields ───────────────────────────────────────────────────────823// After a username/password submission, many sites swap the whole form for a824// lone "verification code" input. The credential selector intentionally gates825// on login/signup forms, so TOTP fields need a narrow path of their own.826const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();827828function hasLoginOrSignupForm(): boolean {829  const fields = detectLoginFields();830  return isAnyCredentialForm(fields);831}832833function injectTOTPFieldIcon(field: HTMLInputElement): void {834  if (processedTOTPInputs.has(field)) return;835  const cleanup = injectFieldIcon(field, () => {836    currentDismiss?.();837    currentDismiss = null;838    currentAnchorField = null;839    lastDismissedField = null;840    dismissLock = false;841    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }842    clearFillStateForExplicitSummon(field);843    field.focus({ preventScroll: true });844    void openTOTPSelector(field);845  });846  processedTOTPInputs.set(field, cleanup);847}848849function scanTOTPFields(): void {850  if (hasLoginOrSignupForm()) return;851  const inputs = document.querySelectorAll<HTMLInputElement>("input");852  for (const input of inputs) {853    if (!isTOTPField(input)) continue;854    injectTOTPFieldIcon(input);855  }856}857858function setupTOTPAutofill(): void {859  setTimeout(scanTOTPFields, 0);860  setTimeout(scanTOTPFields, 500);861  setTimeout(scanTOTPFields, 1500);862863  const debouncedScan = debounce(scanTOTPFields, 200);864  new MutationObserver(debouncedScan).observe(document.body, {865    childList: true,866    subtree: true,867    attributes: true,868    attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],869  });870871  document.addEventListener("focusin", (e) => {872    const target = e.target;873    if (!(target instanceof HTMLInputElement)) return;874    if (hasLoginOrSignupForm()) return;875    if (!isTOTPField(target)) return;876    injectTOTPFieldIcon(target);877  }, true);878}879880document.addEventListener("focusin", onFocusIn);881882setupMutationObserver();883setupTOTPAutofill();884setupSaveDetection();885setupCardAutofill();886887// SPA navigation reset: the content script does not reload across in-app888// route changes (history.pushState, hash navigation, framework routers).889// When the URL changes we clear the page-level fill timestamp so the next890// page works normally; filledForms (a WeakSet) self-empties as old form891// elements leave the DOM. subtree:false because route swaps reliably892// mutate document.body's direct children — subtree:true would fire on893// every internal DOM update and cost us a re-check per mutation.894let lastObservedUrl = location.href;895new MutationObserver(() => {896  if (location.href !== lastObservedUrl) {897    lastObservedUrl = location.href;898    pageFilledAt = null;899  }900}).observe(document.body, { childList: true, subtree: false });901902// Async init: check recall map before running the initial scans so we can903// apply the right aggression level for domains the user has needed before.904(async () => {905  let aggressionLevel = 0;906  try {907    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });908    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;909    const domain = getPageDomain();910    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;911    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;912  } catch { /* SW may be starting up; proceed with normal scan */ }913914  setTimeout(() => initialScan(aggressionLevel, false), 0);915  setTimeout(() => initialScan(aggressionLevel, false), 500);916  setTimeout(() => initialScan(aggressionLevel, true), 1500);917})();918919// ── Card autofill (State 7) ─────────────────────────────────────────920// Card forms get a parallel injection path. The login icon-injection gate921// in reattachListeners deliberately skips non-text fields, so we wire922// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping923// card detection contained makes the boundary easy to follow.924const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();925let currentCardDismiss: (() => void) | null = null;926let currentCardAnchor: HTMLInputElement | null = null;927let lastDismissedCardField: HTMLInputElement | null = null;928929async function fetchSavedCards(): Promise<CardSelectorEntry[]> {930  const resp = await chrome.runtime.sendMessage({931    type: "AUTOFILL_QUERY",932    payload: { domain: getPageDomain(), kind: "card" },933  }).catch(() => null);934  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;935  return r?.ok ? (r.data ?? []) : [];936}937938async function openCardSelector(anchor: HTMLInputElement): Promise<void> {939  if (!canOpen()) return;940  if (currentCardDismiss && currentCardAnchor === anchor) return;941  if (anchor === lastDismissedCardField) return;942  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;943  if (wasAlreadyFilled(anchor)) return;944945  const cards = await fetchSavedCards();946  if (cards.length === 0) return; // no saved cards → nothing to offer947948  const cardForm = detectCardForm();949  if (!cardForm?.number) return;950951  currentCardDismiss?.();952  currentCardAnchor = anchor;953  currentCardDismiss = showCardSelector(954    anchor,955    cards,956    {957      domain: getPageDomain(),958      onFill: (entry) => {959        if (!cardForm) return;960        fillCardForm(cardForm, {961          cardNumber: entry.cardNumber ?? "",962          expMonth: entry.expMonth ?? "",963          expYear: entry.expYear ?? "",964          cvc: entry.cvc ?? "",965          cardholderName: entry.cardholderName ?? "",966        });967        // All four card field types share the same form — recording the968        // number field's form is sufficient to suppress reopens on any of969        // them via wasAlreadyFilled().970        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);971        currentCardDismiss = null;972        currentCardAnchor = null;973      },974      onDismiss: () => {975        lastDismissedCardField = anchor;976        startDismissLock();977        currentCardDismiss = null;978        currentCardAnchor = null;979      },980    }981  );982}983984function injectCardIcon(field: HTMLInputElement): void {985  if (processedCardInputs.has(field)) return;986  const cleanup = injectFieldIcon(field, () => {987    currentCardDismiss?.();988    currentCardDismiss = null;989    lastDismissedCardField = null;990    dismissLock = false;991    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }992    clearFillStateForExplicitSummon(field);993    field.focus({ preventScroll: true });994    void openCardSelector(field);995  });996  processedCardInputs.set(field, cleanup);997}998999function setupCardAutofill(): void {1000  function scan() {1001    const cardForm = detectCardForm();1002    if (!cardForm?.number) return;1003    if (!isVisible(cardForm.number)) return;1004    injectCardIcon(cardForm.number);1005  }10061007  // Initial detection sweep — same retry cadence as login fields so1008  // late-hydrating SPA checkout pages get caught.1009  setTimeout(scan, 0);1010  setTimeout(scan, 500);1011  setTimeout(scan, 1500);10121013  // Re-scan on DOM mutation (separate from the login MutationObserver1014  // because card forms typically appear on a single navigation event,1015  // not field-by-field — coarser observation is sufficient here).1016  let pending = false;1017  new MutationObserver(() => {1018    if (pending) return;1019    pending = true;1020    setTimeout(() => { pending = false; scan(); }, 200);1021  }).observe(document.body, { childList: true, subtree: true });10221023  // Field-focus path: on focus of a cc-number input, ensure icon is1024  // present and consider opening the selector when the user explicitly1025  // clicks into the card number field.1026  document.addEventListener("focusin", (e) => {1027    const target = e.target;1028    if (!(target instanceof HTMLInputElement)) return;1029    const cardForm = detectCardForm();1030    if (cardForm?.number === target) {1031      injectCardIcon(target);1032    }1033  }, true);1034}10351036chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1037  // Ignore anything not originating from our own background/service worker.1038  if (sender.id !== chrome.runtime.id) return;1039  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1040    const policy = detectPasswordPolicy();1041    sendResponse({ ok: true, data: policy });1042    return true;1043  }1044  if (msg?.type === "PING") {1045    sendResponse({ ok: true });1046    return true;1047  }1048  if (msg?.type === "SUMMON_AUTOFILL") {1049    const source = (msg as { type: string; source?: string }).source;1050    const isShortcut = source === "shortcut";1051    const isPasskeyUnlock = source === "passkey-unlock";10521053    const activeInput = getDeepActiveInput();1054    const fields = detectLoginFields();1055    const hasForm = isAnyCredentialForm(fields);10561057    if (hasForm) {1058      // Prefer the currently focused field if it's a login field, otherwise1059      // fall back to the first password field, then username/email.1060      const inForm = activeInput && fields.some(f => f.el === activeInput);1061      const target = inForm1062        ? activeInput1063        : (fields.find(f => f.type === "password")?.el1064            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1065      if (target) {1066        // Explicit user summon (shortcut or extension button) — bypass all1067        // suppression layers. The user is asking for the popup right now.1068        clearFillStateForExplicitSummon(target);1069        dismissLock = false;1070        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1071        lastDismissedField = null;1072        void handleFieldInteraction(target);1073      }1074    } else if (isPasskeyUnlock) {1075      // Vault is locked during a passkey GET request. Show the inline unlock1076      // prompt anchored to whatever element is focused on the page (typically1077      // the passkey/sign-in button the user just tapped).1078      const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1079        ? document.activeElement as unknown as HTMLInputElement1080        : null;1081      if (anchor) {1082        currentDismiss?.();1083        currentAnchorField = null;1084        passkeySummonActive = true;1085        currentDismiss = showAutofillSelector(anchor, [], () => {}, {1086          domain: getPageDomain(),1087          locked: true,1088          onDismiss: () => { passkeySummonActive = false; },1089        });1090      }1091    } else if (isShortcut) {1092      // Shortcut on a page with no login form — show clipboard-copy search mode.1093      showSearchPalette();1094    }10951096    // Record this domain for the recall system when triggered via shortcut.1097    if (isShortcut) {1098      const domain = getPageDomain();1099      if (domain) {1100        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1101      }1102    }11031104    sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1105    return true;1106  }1107  if (msg?.type === "PASSKEY_PRO_GATE") {1108    // Background rejected a passkey request for a free user. Show State 111109    // so they know what happened and can choose to upgrade.1110    showPasskeyProGate();1111    sendResponse({ ok: true });1112    return true;1113  }1114  if (msg?.type === "SHOW_PASSKEY_TOAST") {1115    // Block autofill selector for the lifetime of the toast and dismiss anything open.1116    passkeyToastActive = true;1117    if (currentDismiss) {1118      currentDismiss();1119      currentDismiss = null;1120      currentAnchorField = null;1121    }1122    return false; // inject.tsx owns the toast and calls sendResponse1123  }1124  if (msg?.type === "DISMISS_PASSKEY_TOAST") {1125    passkeyToastActive = false;1126    return false; // inject.tsx handles the actual dismissal1127  }1128  if (msg?.type === "VAULT_UNLOCKED") {1129    if (passkeySummonActive) {1130      // This unlock was for a pending passkey GET request. Just dismiss the1131      // inline popup — the passkey approval toast takes over from here.1132      passkeySummonActive = false;1133      if (currentDismiss) {1134        currentDismiss();1135        currentDismiss = null;1136        currentAnchorField = null;1137      }1138      sendResponse({ ok: true });1139      return true;1140    }1141    // Normal autofill path: close the locked-state prompt and re-open with1142    // fresh entry data at the same anchor field.1143    const savedField = currentAnchorField;1144    if (currentDismiss) {1145      currentDismiss();1146      currentDismiss = null;1147      currentAnchorField = null;1148    }1149    void handleFieldInteraction(savedField ?? undefined);1150    sendResponse({ ok: true });1151    return true;1152  }1153  return true;1154});11551156// inject.tsx posts this when the passkey toast closes (approve, deny, or timeout)1157// so we know it's safe to allow autofill again.1158window.addEventListener("message", (e: MessageEvent) => {1159  // Reject postMessages from cross-frame senders — only the same window's1160  // injected toast may flip this flag.1161  if (e.source !== window) return;1162  const d = e.data as { source?: string; type?: string } | undefined;1163  if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1164    passkeyToastActive = false;1165  }1166});11671168// ── Firefox passkey detection bridge (legacy observer path) ─────────────1169//1170// Pre-v2.12.0 the MAIN-world `passkeys-firefox.ts` was an observer — it1171// emitted `peach-passkey-firefox` postMessages so this content script could1172// surface State 12 (an inline "Save passkey to Peach" offer). v2.12.01173// replaced the observer with a full interception proxy (the page never1174// reaches a real navigator.credentials.create on Firefox anymore), and the1175// approval UI is opened by the background as part of the ceremony itself.1176// When the proxy is active the offer would be redundant noise, so the1177// listener gates on the flag. Once the proxy is removed (Firefox ships1178// webAuthenticationProxy) this whole block goes too.1179if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1180  let lastPasskeyOfferAt = 0;1181  const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11821183  window.addEventListener("message", (event: MessageEvent) => {1184    if (event.source !== window) return;1185    const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1186    if (!data || data.source !== "peach-passkey-firefox") return;1187    if (detectBrowser() !== "firefox") return;1188    if (data.type !== "create") return;11891190    // Cooldown: a single page interaction can fire multiple credentials.create1191    // calls. Show the offer at most once per 30 seconds per page session.1192    const now = Date.now();1193    if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1194    lastPasskeyOfferAt = now;11951196    const domain = location.hostname.replace(/^www\./, "");1197    chrome.runtime.sendMessage({1198      type: "GET_PASSKEY_OFFER_DECLINED",1199      payload: { domain },1200    }).then((res: { ok: boolean; data?: boolean } | undefined) => {1201      if (res?.data === true) return;1202      const rpId = data.rpId ?? domain;1203      showPasskeyRegistrationOffer({1204        rpId,1205        rpName: data.rpName,1206        userName: data.userName,1207        userDisplayName: data.userDisplayName,1208      });1209    }).catch(() => {});1210  });1211}12121213// Surface State 11 (passkey-available) only when it adds value:1214//   - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither1215//     browser will auto-route, so the banner explains the re-register need.1216//   - Firefox + same-browser entry: Firefox has no equivalent of1217//     webAuthenticationProxy, so without a banner the user has no signal that1218//     Peach is the source.1219// On Chrome with a same-browser entry: skip — webAuthenticationProxy handles1220// the page's own credentials.get transparently and the popup approval view1221// already surfaces it. A banner here would just be noise.1222//1223// Dedupe across navigation: each navigation re-injects this content script.1224// chrome.storage.session keyed by domain is the natural per-tab/per-session1225// memory; session storage clears when the user closes the browser.1226{1227  function checkPasskeyAvailability() {1228    const domain = location.hostname.replace(/^www\./, "");1229    if (!domain) return;1230    const sessionKey = `peach_state11_shown:${domain}`;1231    chrome.storage.session?.get(sessionKey).then((stored) => {1232      if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1233      chrome.runtime.sendMessage({1234        type: "GET_PASSKEY_FOR_DOMAIN",1235        payload: { domain },1236      }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1237        const data = res?.data;1238        if (!data) return;1239        const current = detectBrowser();1240        const isCrossBrowser =1241          data.browser && current !== "unknown" && data.browser !== current;1242        const valuableOnFirefox = current === "firefox";1243        if (!isCrossBrowser && !valuableOnFirefox) return;1244        chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1245        showPasskeyAvailable({1246          rpId: data.rpId,1247          userName: data.userName,1248          fromBrowser: data.browser,1249          currentBrowser: current,1250        });1251      }).catch(() => {});1252    }).catch(() => {});1253  }12541255  // Defer until DOM is interactive — content_scripts run at document_idle but1256  // some pages still mutate visibly afterwards. A short delay also avoids1257  // surfacing the State 11 toast while the user is in the middle of typing.1258  if (document.readyState === "loading") {1259    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1260  } else {1261    setTimeout(checkPasskeyAvailability, 800);1262  }1263}