index.ts

48.3 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  showRememberSiteToast,24  showTotpCopyToast,25  showTOTPSelector,26} from "./inject";27import { detectBrowser } from "../shared/browser";28import { fillAllowed, 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 { VaultEntry } from "../shared/types";35import { setPasskeyToastClosedListener } from "./passkey-toast/lifecycle";3637// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value38// so we can tear down listeners if we ever need to re-process the same field.39// When the input is GC'd (SPA nav, React re-render), the map entry goes with40// it and we can re-inject without leaking the old handler.41const processedInputs = new WeakMap<HTMLInputElement, () => void>();42const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4344let currentDismiss: (() => void) | null = null;45// Field whose selector is currently open — used to avoid dismiss+reopen flicker46let currentAnchorField: HTMLInputElement | null = null;47// Prevents two concurrent handleFieldInteraction calls for the same field48const pendingInteractions = new WeakSet<HTMLInputElement>();49// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).50// Suppresses spurious reopens until focus moves to a different field. Layer 151// of the dismissal model — see Projects.md §4.12.52let lastDismissedField: HTMLInputElement | null = null;5354// ── Dismissal lock (Layer 2) ────────────────────────────────────────55// After any user-initiated dismiss, briefly block ALL reopens regardless of56// which field is focused. Catches the case where a page rapidly moves focus57// between fields after Escape — without this, focus moving to a SECOND field58// in <100ms would re-trigger the popup before the user finished dismissing.59const DISMISS_LOCK_MS = 800;60let dismissLock = false;61let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;62// Set when the inline popup was summoned specifically for a passkey-unlock63// flow. The VAULT_UNLOCKED handler checks this to skip re-triggering autofill64// (the passkey toast handles the next step instead).65let passkeySummonActive = false;66// Set while the passkey approval toast is visible. Prevents handleFieldInteraction67// from opening the autofill selector alongside it. Cleared by the isolated-world68// toast lifecycle channel when the toast closes (and by DISMISS_PASSKEY_TOAST).69let passkeyToastActive = false;70let passkeyToastToken: string | null = null;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(capability?: string): 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, capability } });257        const r = resp as { ok: boolean; data?: { password?: string } };258        if (!r.ok) showToast("Could not access this entry. Open Peach to check it.");259        if (r.ok && r.data?.password) {260          let alreadyWritten = false;261          try {262            await navigator.clipboard.writeText(r.data.password);263            alreadyWritten = true;264          } catch (err) {265            console.warn("[Peach] clipboard write denied:", err);266          }267          const copyResp = await chrome.runtime.sendMessage({268            type: "COPY",269            payload: { text: r.data.password, label: "Password", alreadyWritten },270          }) as { ok?: boolean } | undefined;271          if (alreadyWritten || copyResp?.ok) {272            showToast("Password copied");273          } else {274            showToast("Could not copy password — clipboard blocked");275          }276        } else {277          showToast("Could not copy password");278        }279        close();280        document.removeEventListener("keydown", onKeyDown, true);281      };282      list.appendChild(row);283    }284  }285286  searchInput.oninput = () => { query = searchInput.value; render(); };287288  // The browser-issued command capability, not page UI state, authorizes the289  // vault-wide inventory.290  fetchAutofillEntries(getPageDomain(), true, capability).then(result => {291    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }292    allEntries = result.entries;293    render();294    searchInput.focus();295  });296}297298function findTOTPField(root: Document | Element = document): HTMLInputElement | null {299  const inputs = root.querySelectorAll<HTMLInputElement>("input");300  for (const input of inputs) {301    if (isTOTPField(input)) return input;302  }303  return null;304}305306function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {307  const form = passwordEl.closest("form");308  return findTOTPField(form ?? document);309}310311312async function handleAutofill(313  _field: HTMLInputElement,314  usernameEl: HTMLInputElement | null,315  passwordEl: HTMLInputElement | null,316  entry: VaultEntry,317  emailEl?: HTMLInputElement | null318): Promise<{ filledTOTPField: HTMLInputElement | null; gatePassed: boolean }> {319  if (!entry.username && !entry.password && !entry.email) return { filledTOTPField: null, gatePassed: false };320  const pageDomain = getPageDomain();321  const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;322  // Fill the email field with entry.email if set; fall back to entry.username when323  // it looks like an email address (sites that store email-as-username and have a324  // separate email field on signup forms).325  const emailValue = entry.email ?? (entry.username?.includes("@") ? entry.username : "");326  const gatePassed = fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain, emailEl, emailValue);327  let filledTOTPField: HTMLInputElement | null = null;328329  // The background sends a freshly-generated 6-digit code (totpCode), never the330  // base32 seed (SEV-3-C). Fill the code straight in.331  const totpCode = (entry as { totpCode?: string }).totpCode;332  if (totpCode && gatePassed) {333    const code = totpCode;334    const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;335    if (fillTOTPCode(totpField, code, form, pageDomain)) {336      filledTOTPField = totpField;337    }338    let alreadyWritten = false;339    try {340      await navigator.clipboard.writeText(code);341      alreadyWritten = true;342    } catch (err) {343      console.warn("[Peach] clipboard write denied:", err);344    }345    const response = await chrome.runtime.sendMessage({346      type: "COPY",347      payload: { text: code, label: "TOTP", alreadyWritten },348    });349    const res = response as { ok?: boolean; clearSeconds?: number };350    if (filledTOTPField) {351      showToast("2FA code filled");352    } else if (alreadyWritten || res.ok) {353      // Don't render the live code into the toast — the page can read it from the354      // DOM and consume the one-time code (audit LOW). The code is already on the355      // clipboard; the toast confirms the copy and shows how long until the356      // clipboard self-clears (Addendum 2). 30 mirrors DEFAULT_CLEAR_SECONDS.357      showTotpCopyToast(res.clearSeconds ?? 30);358    } else {359      showToast("Could not copy TOTP — clipboard blocked");360    }361  }362363  return { filledTOTPField, gatePassed };364}365366async function fetchAutofillEntries(367  domain: string,368  includeAll = false,369  capability?: string370): Promise<{ entries: SelectorEntry[]; locked: boolean }> {371  const response = await chrome.runtime.sendMessage({372    type: "AUTOFILL_QUERY",373    payload: { domain, includeAll, capability },374  });375  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };376  if (!res.ok && res.error === "vault_locked") {377    return { entries: [], locked: true };378  }379  return { entries: res.data ?? [], locked: false };380}381382async function fetchTOTPEntries(383  domain: string,384  capability?: string,385): Promise<{ entries: SelectorEntry[]; locked: boolean }> {386  const response = await chrome.runtime.sendMessage({387    type: "AUTOFILL_QUERY",388    payload: { domain, kind: "totp", capability },389  });390  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };391  if (!res.ok && res.error === "vault_locked") {392    return { entries: [], locked: true };393  }394  return { entries: res.data ?? [], locked: false };395}396397398function resolveAutofillFieldType(399  el: HTMLInputElement,400  predictedType?: FieldPrediction["type"] | null401): "password" | "username" | "email" | null {402  if (403    predictedType === "password" ||404    predictedType === "username" ||405    predictedType === "email"406  ) {407    return predictedType;408  }409410  const detected = detectLoginFields().find((field) => field.el === el)?.type;411  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {412    return detected;413  }414415  const htmlType = el.type.toLowerCase();416  if (htmlType === "password") return "password";417  if (htmlType === "email") return "email";418  return null;419}420421async function openAutofillSelector(422  anchorField: HTMLInputElement,423  usernameEl: HTMLInputElement | null,424  passwordEl: HTMLInputElement | null,425  domainEntries: SelectorEntry[],426  loadSearchableEntries: () => Promise<SelectorEntry[]>,427  domain: string,428  identityKind: "email" | "username",429  emailEl?: HTMLInputElement | null,430  capability?: string,431): Promise<void> {432  // No saved entries for this site → signup/new-account mode.433  // Locate the confirm-password field so "Copy & fill" can populate it too.434  const isSignup = domainEntries.length === 0;435  let confirmEl: HTMLInputElement | null = null;436  if (isSignup) {437    const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;438    const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));439    confirmEl = allPwInputs.find(440      (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)441    ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);442  }443444  currentDismiss?.();445  currentAnchorField = anchorField;446  currentDismiss = showAutofillSelector(447    anchorField,448    domainEntries,449    async (id: string) => {450      currentDismiss = null;451      currentAnchorField = null;452      const entryResponse = await chrome.runtime.sendMessage({453        type: "GET_ENTRY_FOR_FILL",454        payload: { id, capability },455      });456       if (!(entryResponse as { ok: boolean }).ok) showToast("Could not access this entry. Open Peach to check it.");457       const entry = (entryResponse as { ok: boolean }).ok ? (entryResponse as { data?: VaultEntry }).data : undefined;458       if (entry) {459         const { filledTOTPField, gatePassed } = await handleAutofill(anchorField, usernameEl, passwordEl, entry, emailEl);460         if (gatePassed) recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);461        // Offer to remember the current site for this entry only if none of462        // its known domains (primary + additional) match — otherwise the463        // user already mapped it and the prompt would be noise.464        const pageDomain = location.hostname.replace(/^www\./, "");465        const entryDomains = new Set<string>();466        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {467          try {468            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));469          } catch { /* ignore unparseable */ }470        }471        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {472          showRememberSiteToast(location.origin, entry.id);473        }474      }475    },476    {477      domain,478      capability,479      loadSearchableEntries,480      isSignup,481      identityKind,482      hasEmailField: !!emailEl,483      onFillFields: (username, password, email) => {484        const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;485        if (!fillFields(usernameEl, passwordEl, username, password, form, getPageDomain(), emailEl, email)) return;486        if (password && confirmEl) setNativeValue(confirmEl, password);487        recordFillSuccess(anchorField, usernameEl, passwordEl);488      },489      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },490    }491  );492}493494async function openTOTPSelector(495  anchorField: HTMLInputElement,496  otpDigitBoxes?: HTMLInputElement[],497  capability?: string,498): Promise<void> {499  if (!canOpen()) return;500  if (currentDismiss && currentAnchorField === anchorField) return;501  if (anchorField !== lastDismissedField) lastDismissedField = null;502  if (anchorField === lastDismissedField) return;503  if (wasAlreadyFilled(anchorField)) return;504505  const domain = getPageDomain();506  const result = await fetchTOTPEntries(domain, capability);507508  if (result.locked) {509    currentDismiss?.();510    currentAnchorField = anchorField;511    currentDismiss = showAutofillSelector(512      anchorField,513      [],514      () => {},515      {516        domain,517        locked: true,518        onUnlocked: () => void openTOTPSelector(anchorField),519        onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },520      }521    );522    return;523  }524525  if (result.entries.length === 0) {526    lastDismissedField = anchorField;527    startDismissLock();528    showToast("No 2FA entries for this site — add a code in Peach first");529    return;530  }531532  currentDismiss?.();533  currentAnchorField = anchorField;534  currentDismiss = showTOTPSelector(535    anchorField,536    result.entries,537    async (id: string) => {538      try {539        const entryResponse = await chrome.runtime.sendMessage({540          type: "GET_ENTRY_FOR_FILL",541          payload: { id, capability },542        }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;543        if (!entryResponse?.ok) showToast("Could not access this entry. Open Peach to check it.");544        const entry = entryResponse?.ok ? entryResponse.data : undefined;545        const code = (entry as { totpCode?: string } | undefined)?.totpCode;546        if (!code) return;547        if (!fillAllowed(anchorField.closest("form"), getPageDomain())) return;548        if (otpDigitBoxes && otpDigitBoxes.length > 1) {549          fillOTPDigitBoxes(otpDigitBoxes, code);550        } else {551          setNativeValue(anchorField, code);552        }553        recordFillSuccess(anchorField);554        showToast("2FA code filled");555      } finally {556        currentDismiss = null;557        currentAnchorField = null;558      }559    },560    {561      domain,562      onDismiss: () => {563        lastDismissedField = anchorField;564        startDismissLock();565        currentDismiss = null;566        currentAnchorField = null;567      },568    }569  );570}571572573export /* @testable */ async function handleFieldInteraction(574  anchorField?: HTMLInputElement | null,575  explicitSummon = false,576  capability?: string577): Promise<void> {578  const field = anchorField ?? getDeepActiveInput();579  if (!field) return;580  if (!isVisible(field)) return;581582  // Passkey toast is visible — don't open the credential selector alongside it.583  if (passkeyToastActive) return;584585  // Layer 2: post-dismiss global lock. Catches rapid focus moves between586  // fields immediately after Escape/click-outside.587  if (!canOpen()) return;588589  // If a selector is already open for this exact field, don't flicker it.590  if (currentDismiss && currentAnchorField === field) return;591592  // If focus moved to a different field, the previous per-field dismiss lock593  // no longer applies.594  if (field !== lastDismissedField) lastDismissedField = null;595  // Layer 1: the user explicitly dismissed this field's selector — don't596  // reopen it until focus has genuinely moved away and come back.597  if (field === lastDismissedField) return;598599  // Fill-success lock: Peach already filled this form (or fired a fill600  // anywhere on the page within the grace window). Sites often refocus an601  // input on submit click, on validation, or on a transition to a success602  // state — none of those should re-open the popup.603  if (wasAlreadyFilled(field)) return;604605  // Prevent two concurrent calls for the same field (e.g. focusin + icon click606  // firing simultaneously — the second call would dismiss the first's selector).607  if (pendingInteractions.has(field)) return;608  pendingInteractions.add(field);609610  try {611    // Multi-digit OTP entry: a group of digit boxes opens one selector anchored612    // on the first box and fills every box at once — never one icon per box.613    // findOTPDigitBoxGroup covers maxlength=1 boxes; findOtpSignalingGroup614    // covers boxes that carry OTP signaling (autocomplete=one-time-code,615    // name/id/label matches otp/totp/2fa) but lack maxlength="1".616    const otpGroup = findOTPDigitBoxGroup(field) ?? findOtpSignalingGroup(field);617    if (otpGroup) {618      await openTOTPSelector(otpGroup[0]!, otpGroup, capability);619      return;620    }621622    if (isTOTPField(field)) {623      const formFields = detectLoginFields();624      if (!isLoginForm(formFields) && !isSignupForm(formFields)) {625        await openTOTPSelector(field, undefined, capability);626        return;627      }628    }629630    const fieldType = field.type.toLowerCase();631632    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {633      return preds[0] ?? null;634    });635636    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {637      const timeout = setTimeout(() => resolve(null), 150);638      mlPromise.then((pred) => {639        clearTimeout(timeout);640        resolve(pred);641      });642    });643644    if (passkeyToastActive) return;645646    if (!explicitSummon && fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {647      return;648    }649650    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);651    if (autofillFieldType) {652      reattachListeners(field, autofillFieldType);653    }654655    const fields = detectLoginFields();656    const targets = resolveAutofillInteractionTargets(field, fields, explicitSummon);657    if (!targets.shouldOpen) {658      return;659    }660661    const domain = getPageDomain();662    const commandAuthorized = explicitSummon && capability !== undefined;663    const firstResult = await fetchAutofillEntries(664      domain,665      commandAuthorized,666      commandAuthorized ? capability : undefined,667    );668    if (passkeyToastActive) return;669670    // Vault is locked — show an inline unlock prompt.671    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so672    // there is no double-trigger race between onUnlocked and the broadcast.673    if (firstResult.locked) {674      currentDismiss?.();675      currentAnchorField = field;676      currentDismiss = showAutofillSelector(677        field,678        [],679        () => {},680        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }681      );682      return;683    }684685    const entries = firstResult.entries;686    // MV-2: the vault-wide list is NOT fetched here. It is loaded lazily,687    // only when the user activates the search affordance inside the inline688    // popup (an explicit gesture), via the thunk below. Passive form focus689    // never ships the full account inventory into the page's content-script690    // world — and never hands out the entry ids that made MV-1 a full-vault691    // primitive.692    const loadSearchableEntries = async (): Promise<SelectorEntry[]> =>693      commandAuthorized694        ? entries695        : (await fetchAutofillEntries(domain)).entries;696697    if (passkeyToastActive) return;698699    const pwField = fields.find((f) => f.type === "password");700    // For email-first flows there is no password field on this step — that is expected.701    if (!explicitSummon && !pwField && !isEmailFirstForm(fields)) return;702    const usernameEl = targets.usernameEl;703    const passwordEl = targets.passwordEl;704    const emailEl = targets.emailEl;705706    await openAutofillSelector(707      field,708      usernameEl,709      passwordEl,710      entries,711      loadSearchableEntries,712      domain,713      autofillFieldType === "email" ? "email" : "username",714      emailEl,715      commandAuthorized ? capability : undefined,716    );717  } finally {718    pendingInteractions.delete(field);719  }720}721722async function onFocusIn(e: Event): Promise<void> {723  // Submit-button focus: catch the brief refocus some sites do when the724  // user clicks the login/submit button. Without this guard, that focus725  // event reaches handleFieldInteraction → getDeepActiveInput, and on726  // pages where the button is also a labelled <input> we briefly attempt727  // to open the popup over the very button the user just clicked.728  if (isSubmitButton(e.target)) return;729730  const field = e.target instanceof HTMLInputElement ? e.target : null;731  if (field) {732    const fields = detectLoginFields();733    if (isAnyCredentialForm(fields)) {734      const detected = fields.find((candidate) => candidate.el === field)?.type;735      reattachListeners(field, detected, fields);736    }737  }738739  await handleFieldInteraction();740}741742function reattachListeners(743  el: HTMLInputElement,744  detectedType?: "password" | "username" | "email",745  contextFields?: ReturnType<typeof detectLoginFields>746): void {747  if (processedInputs.has(el)) return;748  if (!resolveAutofillFieldType(el, detectedType)) return;749  // Only inject icon when a credential form is present on the page750  const fields = contextFields ?? detectLoginFields();751  if (!isAnyCredentialForm(fields)) return;752753  const cleanup = injectFieldIcon(el, () => {754    currentDismiss?.();755    currentDismiss = null;756    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock757    dismissLock = false; // ...and the global lock758    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }759    clearFillStateForExplicitSummon(el);760    el.focus({ preventScroll: true });761    void handleFieldInteraction(el, true);762  });763  processedInputs.set(el, cleanup);764}765766const debouncedReattach = debounce(() => {767  const allFields = detectLoginFields();768  if (!isAnyCredentialForm(allFields)) return;769  const newFields = allFields.filter(770    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)771  );772  for (const f of newFields) {773    reattachListeners(f.el, f.type, allFields);774  }775  // 200ms debounce — below this, Peach and the host page's reactive layer776  // fight over the same layout properties every frame on React/Vue/Angular777  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.778}, 200);779780function setupMutationObserver(): void {781  const observer = new MutationObserver(debouncedReattach);782  observer.observe(document.body, {783    childList: true,784    subtree: true,785    attributes: true,786    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],787  });788}789790export /* @testable */ function initialScan(aggressionLevel = 0, isFinalPass = false) {791  const allFields = detectLoginFields();792  const hasKnownForm = isAnyCredentialForm(allFields);793794  if (aggressionLevel === 0 && !hasKnownForm) return;795796  const newFields = allFields.filter(797    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)798  );799800  for (const f of newFields) {801    reattachListeners(f.el, f.type, allFields);802  }803804  // Level 2, final pass: inject icon on any visible password field even if805  // the form-context gate in reattachListeners would normally skip it.806  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {807    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');808    for (const el of pwInputs) {809      if (isVisible(el) && !processedInputs.has(el)) {810        const cleanup = injectFieldIcon(el, () => {811          currentDismiss?.();812          currentDismiss = null;813          lastDismissedField = null;814          dismissLock = false;815          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }816          clearFillStateForExplicitSummon(el);817          el.focus({ preventScroll: true });818          void handleFieldInteraction(el, true);819        });820        processedInputs.set(el, cleanup);821      }822    }823  }824}825826// @testable seam — gives unit tests read/write access to module-private state827// without exposing it in the production API surface.828export const _testSeam = {829  getLastDismissedField(): HTMLInputElement | null { return lastDismissedField; },830  setLastDismissedField(f: HTMLInputElement | null): void { lastDismissedField = f; },831  isDismissLocked(): boolean { return dismissLock; },832  DISMISS_LOCK_MS,833} as const;834835// ── TOTP-only fields ───────────────────────────────────────────────────────836// After a username/password submission, many sites swap the whole form for a837// lone "verification code" input. The credential selector intentionally gates838// on login/signup forms, so TOTP fields need a narrow path of their own.839const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();840841function hasLoginOrSignupForm(): boolean {842  const fields = detectLoginFields();843  return isAnyCredentialForm(fields);844}845846function injectTOTPFieldIcon(847  field: HTMLInputElement,848  otpDigitBoxes?: HTMLInputElement[]849): void {850  if (processedTOTPInputs.has(field)) return;851  const cleanup = injectFieldIcon(field, () => {852    currentDismiss?.();853    currentDismiss = null;854    currentAnchorField = null;855    lastDismissedField = null;856    dismissLock = false;857    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }858    clearFillStateForExplicitSummon(field);859    field.focus({ preventScroll: true });860    void openTOTPSelector(field, otpDigitBoxes);861  });862  processedTOTPInputs.set(field, cleanup);863}864865// A split-OTP group (4+ OTP-signaling boxes lacking maxlength="1") shows one866// icon on the first box, not one per box. Returns the anchor to inject on867// (group[0]) and its full group, or just the field itself when it's a lone868// TOTP input.869function resolveTOTPIconTarget(870  field: HTMLInputElement871): { anchor: HTMLInputElement; group?: HTMLInputElement[] } {872  const group = findOtpSignalingGroup(field);873  if (group) return { anchor: group[0]!, group };874  return { anchor: field };875}876877export /* @testable */ function scanTOTPFields(): void {878  if (hasLoginOrSignupForm()) return;879  const inputs = document.querySelectorAll<HTMLInputElement>("input");880  for (const input of inputs) {881    if (!isTOTPField(input)) continue;882    const { anchor, group } = resolveTOTPIconTarget(input);883    injectTOTPFieldIcon(anchor, group);884  }885}886887function setupTOTPAutofill(): void {888  setTimeout(scanTOTPFields, 0);889  setTimeout(scanTOTPFields, 500);890  setTimeout(scanTOTPFields, 1500);891892  const debouncedScan = debounce(scanTOTPFields, 200);893  new MutationObserver(debouncedScan).observe(document.body, {894    childList: true,895    subtree: true,896    attributes: true,897    attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],898  });899900  document.addEventListener("focusin", (e) => {901    const target = e.target;902    if (!(target instanceof HTMLInputElement)) return;903    if (hasLoginOrSignupForm()) return;904    if (!isTOTPField(target)) return;905    const { anchor, group } = resolveTOTPIconTarget(target);906    injectTOTPFieldIcon(anchor, group);907  }, true);908}909910document.addEventListener("focusin", onFocusIn);911912setupMutationObserver();913setupTOTPAutofill();914setupSaveDetection();915setupCardAutofill();916917// SPA navigation reset: the content script does not reload across in-app918// route changes (history.pushState, hash navigation, framework routers).919// When the URL changes we clear the page-level fill timestamp so the next920// page works normally; filledForms (a WeakSet) self-empties as old form921// elements leave the DOM. subtree:false because route swaps reliably922// mutate document.body's direct children — subtree:true would fire on923// every internal DOM update and cost us a re-check per mutation.924let lastObservedUrl = globalThis.location.href;925new MutationObserver(() => {926  const currentUrl = globalThis.location?.href;927  if (!currentUrl || currentUrl === lastObservedUrl) return;928  lastObservedUrl = currentUrl;929  pageFilledAt = null;930}).observe(document.body, { childList: true, subtree: false });931932// Async init: check recall map before running the initial scans so we can933// apply the right aggression level for domains the user has needed before.934(async () => {935  let aggressionLevel = 0;936  try {937    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });938    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;939    const domain = getPageDomain();940    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;941    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;942  } catch { /* SW may be starting up; proceed with normal scan */ }943944  setTimeout(() => initialScan(aggressionLevel, false), 0);945  setTimeout(() => initialScan(aggressionLevel, false), 500);946  setTimeout(() => initialScan(aggressionLevel, true), 1500);947})();948949// ── Card autofill (State 7) ─────────────────────────────────────────950// Card forms get a parallel injection path. The login icon-injection gate951// in reattachListeners deliberately skips non-text fields, so we wire952// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping953// card detection contained makes the boundary easy to follow.954const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();955let currentCardDismiss: (() => void) | null = null;956let currentCardAnchor: HTMLInputElement | null = null;957let lastDismissedCardField: HTMLInputElement | null = null;958959async function fetchSavedCards(capability?: string): Promise<CardSelectorEntry[]> {960  const resp = await chrome.runtime.sendMessage({961    type: "AUTOFILL_QUERY",962    payload: { domain: getPageDomain(), kind: "card", capability },963  }).catch(() => null);964  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;965  return r?.ok ? (r.data ?? []) : [];966}967968async function openCardSelector(anchor: HTMLInputElement, capability?: string): Promise<void> {969  if (!canOpen()) return;970  if (currentCardDismiss && currentCardAnchor === anchor) return;971  if (anchor === lastDismissedCardField) return;972  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;973  if (wasAlreadyFilled(anchor)) return;974975  const cards = await fetchSavedCards(capability);976  if (cards.length === 0) return; // no saved cards → nothing to offer977978  const cardForm = detectCardForm();979  if (!cardForm?.number) return;980981  currentCardDismiss?.();982  currentCardAnchor = anchor;983  currentCardDismiss = showCardSelector(984    anchor,985    cards,986    {987      domain: getPageDomain(),988      capability,989      onFill: (entry) => {990        if (!cardForm) return;991        fillCardForm(cardForm, {992          cardNumber: entry.cardNumber ?? "",993          expMonth: entry.expMonth ?? "",994          expYear: entry.expYear ?? "",995          cvc: entry.cvc ?? "",996          cardholderName: entry.cardholderName ?? "",997        });998        // All four card field types share the same form — recording the999        // number field's form is sufficient to suppress reopens on any of1000        // them via wasAlreadyFilled().1001        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);1002        currentCardDismiss = null;1003        currentCardAnchor = null;1004      },1005      onDismiss: () => {1006        lastDismissedCardField = anchor;1007        startDismissLock();1008        currentCardDismiss = null;1009        currentCardAnchor = null;1010      },1011    }1012  );1013}10141015function injectCardIcon(field: HTMLInputElement): void {1016  if (processedCardInputs.has(field)) return;1017  const cleanup = injectFieldIcon(field, () => {1018    currentCardDismiss?.();1019    currentCardDismiss = null;1020    lastDismissedCardField = null;1021    dismissLock = false;1022    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1023    clearFillStateForExplicitSummon(field);1024    field.focus({ preventScroll: true });1025    void openCardSelector(field);1026  });1027  processedCardInputs.set(field, cleanup);1028}10291030function setupCardAutofill(): void {1031  function scan() {1032    const cardForm = detectCardForm();1033    if (!cardForm?.number) return;1034    if (!isVisible(cardForm.number)) return;1035    injectCardIcon(cardForm.number);1036  }10371038  // Initial detection sweep — same retry cadence as login fields so1039  // late-hydrating SPA checkout pages get caught.1040  setTimeout(scan, 0);1041  setTimeout(scan, 500);1042  setTimeout(scan, 1500);10431044  // Re-scan on DOM mutation (separate from the login MutationObserver1045  // because card forms typically appear on a single navigation event,1046  // not field-by-field — coarser observation is sufficient here).1047  let pending = false;1048  new MutationObserver(() => {1049    if (pending) return;1050    pending = true;1051    setTimeout(() => { pending = false; scan(); }, 200);1052  }).observe(document.body, { childList: true, subtree: true });10531054  // Field-focus path: on focus of a cc-number input, ensure icon is1055  // present and consider opening the selector when the user explicitly1056  // clicks into the card number field.1057  document.addEventListener("focusin", (e) => {1058    const target = e.target;1059    if (!(target instanceof HTMLInputElement)) return;1060    const cardForm = detectCardForm();1061    if (cardForm?.number === target) {1062      injectCardIcon(target);1063    }1064  }, true);1065}10661067chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1068  // Ignore anything not originating from our own background/service worker.1069  if (sender.id !== chrome.runtime.id) return;1070  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1071    const policy = detectPasswordPolicy();1072    sendResponse({ ok: true, data: policy });1073    return true;1074  }1075  if (msg?.type === "PING") {1076    sendResponse({ ok: true });1077    return true;1078  }1079  if (msg?.type === "SUMMON_AUTOFILL") {1080    const source = (msg as { type: string; source?: string; capability?: string }).source;1081    const capability = (msg as { capability?: string }).capability;1082    const isShortcut = source === "shortcut";1083    const isPasskeyUnlock = source === "passkey-unlock";10841085    const activeInput = getDeepActiveInput();1086    const fields = detectLoginFields();1087    const hasForm = isAnyCredentialForm(fields);1088    const cardForm = detectCardForm();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, true, capability);1106      }1107    } else if (isShortcut && cardForm?.number) {1108      clearFillStateForExplicitSummon(cardForm.number);1109      dismissLock = false;1110      if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1111      lastDismissedCardField = null;1112      void openCardSelector(cardForm.number, capability);1113    } else if (isPasskeyUnlock) {1114      // Vault is locked during a passkey GET request. Show the inline unlock1115      // prompt anchored to whatever element is focused on the page (typically1116      // the passkey/sign-in button the user just tapped).1117      const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1118        ? document.activeElement as unknown as HTMLInputElement1119        : null;1120      if (anchor) {1121        currentDismiss?.();1122        currentAnchorField = null;1123        passkeySummonActive = true;1124        currentDismiss = showAutofillSelector(anchor, [], () => {}, {1125          domain: getPageDomain(),1126          locked: true,1127          onDismiss: () => { passkeySummonActive = false; },1128        });1129      }1130    } else if (isShortcut) {1131      // Shortcut on a page with no login form — show clipboard-copy search mode.1132      showSearchPalette(capability);1133    }11341135    // Record this domain for the recall system when triggered via shortcut.1136    if (isShortcut) {1137      const domain = getPageDomain();1138      if (domain) {1139        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1140      }1141    }11421143    sendResponse({ ok: hasForm || Boolean(cardForm?.number) || isShortcut || isPasskeyUnlock });1144    return true;1145  }1146  if (msg?.type === "PASSKEY_PRO_GATE") {1147    // Background rejected a passkey request for a free user. Show State 111148    // so they know what happened and can choose to upgrade.1149    showPasskeyProGate();1150    sendResponse({ ok: true });1151    return true;1152  }1153  if (msg?.type === "SHOW_PASSKEY_TOAST") {1154    // Block autofill selector for the lifetime of the toast and dismiss anything open.1155    passkeyToastActive = true;1156    passkeyToastToken = typeof (msg.payload as { toastToken?: unknown } | undefined)?.toastToken === "string"1157      ? (msg.payload as { toastToken: string }).toastToken1158      : null;1159    if (currentDismiss) {1160      currentDismiss();1161      currentDismiss = null;1162      currentAnchorField = null;1163    }1164    return false; // inject.tsx owns the toast and calls sendResponse1165  }1166  if (msg?.type === "DISMISS_PASSKEY_TOAST") {1167    passkeyToastActive = false;1168    passkeyToastToken = null;1169    return false; // inject.tsx handles the actual dismissal1170  }1171  if (msg?.type === "VAULT_UNLOCKED") {1172    if (passkeySummonActive) {1173      // This unlock was for a pending passkey GET request. Just dismiss the1174      // inline popup — the passkey approval toast takes over from here.1175      passkeySummonActive = false;1176      if (currentDismiss) {1177        currentDismiss();1178        currentDismiss = null;1179        currentAnchorField = null;1180      }1181      sendResponse({ ok: true });1182      return true;1183    }1184    // Normal autofill path: close the locked-state prompt and re-open with1185    // fresh entry data at the same anchor field.1186    const savedField = currentAnchorField;1187    if (currentDismiss) {1188      currentDismiss();1189      currentDismiss = null;1190      currentAnchorField = null;1191    }1192    void handleFieldInteraction(savedField ?? undefined);1193    sendResponse({ ok: true });1194    return true;1195  }1196  return true;1197});11981199setPasskeyToastClosedListener((toastToken) => {1200  if (toastToken === passkeyToastToken) {1201    passkeyToastActive = false;1202    passkeyToastToken = null;1203  }1204});12051206// Surface State 11 (passkey-available) only when it adds value:1207//   - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither1208//     browser will auto-route, so the banner explains the re-register need.1209//   - Firefox + same-browser entry: Firefox has no equivalent of1210//     webAuthenticationProxy, so without a banner the user has no signal that1211//     Peach is the source.1212// On Chrome with a same-browser entry: skip — webAuthenticationProxy handles1213// the page's own credentials.get transparently and the popup approval view1214// already surfaces it. A banner here would just be noise.1215//1216// Dedupe across navigation: the "already shown" flag lives in trusted1217// background session storage behind MARK_PASSKEY_BANNER_SHOWN — content1218// scripts must not touch chrome.storage.session directly (PB-26-203), since1219// that API has to stay inaccessible to hostile-page-adjacent contexts.1220{1221  function checkPasskeyAvailability() {1222    const domain = location.hostname.replace(/^www\./, "");1223    if (!domain) return;1224    chrome.runtime.sendMessage({1225      type: "GET_PASSKEY_FOR_DOMAIN",1226      payload: { domain },1227    }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox"; bannerShown?: boolean } | null } | undefined) => {1228      const data = res?.data;1229      if (!data || data.bannerShown) return;1230      const current = detectBrowser();1231      const isCrossBrowser =1232        data.browser && current !== "unknown" && data.browser !== current;1233      const valuableOnFirefox = current === "firefox";1234      if (!isCrossBrowser && !valuableOnFirefox) return;1235      chrome.runtime.sendMessage({1236        type: "MARK_PASSKEY_BANNER_SHOWN",1237        payload: { domain },1238      }).catch(() => {});1239      showPasskeyAvailable({1240        rpId: data.rpId,1241        userName: data.userName,1242        fromBrowser: data.browser,1243        currentBrowser: current,1244      });1245    }).catch(() => {});1246  }12471248  // Defer until DOM is interactive — content_scripts run at document_idle but1249  // some pages still mutate visibly afterwards. A short delay also avoids1250  // surfacing the State 11 toast while the user is in the middle of typing.1251  if (document.readyState === "loading") {1252    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1253  } else {1254    setTimeout(checkPasskeyAvailability, 800);1255  }1256}