index.ts

45.8 KB · raw

1import {2  detectCardForm,3  detectLoginFields,4  getDeepActiveInput,5  getPageDomain,6  isAnyCredentialForm,7  isEmailFirstForm,8  isLoginForm,9  isSignupForm,10  isTOTPField,11  isVisible,12} from "./detect";13import {14  CardSelectorEntry,15  injectFieldIcon,16  SelectorEntry,17  showAutofillSelector,18  showCardSelector,19  showPasskeyAvailable,20  showPasskeyProGate,21  showPasskeyRegistrationOffer,22  showRememberSiteToast,23  showTOTPSelector,24} from "./inject";25import { detectBrowser } from "../shared/browser";26import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";27import { fillCardForm, fillFields, fillTOTPCode, setNativeValue } from "./fill";28import { setupSaveDetection } from "./save";29import { contentMLDetector } from "./content-ml-detector";30import { detectPasswordPolicy } from "./policy";31import type { FieldPrediction } from "../shared/ml";32import { generateTOTP } from "../crypto/totp";33import type { SavedIdentity, VaultEntry } from "../shared/types";3435// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value36// so we can tear down listeners if we ever need to re-process the same field.37// When the input is GC'd (SPA nav, React re-render), the map entry goes with38// it and we can re-inject without leaking the old handler.39const processedInputs = new WeakMap<HTMLInputElement, () => void>();40const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4142let currentDismiss: (() => void) | null = null;43// Field whose selector is currently open — used to avoid dismiss+reopen flicker44let currentAnchorField: HTMLInputElement | null = null;45// Prevents two concurrent handleFieldInteraction calls for the same field46const pendingInteractions = new WeakSet<HTMLInputElement>();47// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).48// Suppresses spurious reopens until focus moves to a different field. Layer 149// of the dismissal model — see Projects.md §4.12.50let lastDismissedField: HTMLInputElement | null = null;5152// ── Dismissal lock (Layer 2) ────────────────────────────────────────53// After any user-initiated dismiss, briefly block ALL reopens regardless of54// which field is focused. Catches the case where a page rapidly moves focus55// between fields after Escape — without this, focus moving to a SECOND field56// in <100ms would re-trigger the popup before the user finished dismissing.57const DISMISS_LOCK_MS = 800;58let dismissLock = false;59let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;60// Set when the inline popup was summoned specifically for a passkey-unlock61// flow. The VAULT_UNLOCKED handler checks this to skip re-triggering autofill62// (the passkey toast handles the next step instead).63let passkeySummonActive = false;64// Set while the passkey approval toast is visible. Prevents handleFieldInteraction65// from opening the autofill selector alongside it. Cleared by a window message66// posted by inject.tsx when the toast closes (and by DISMISS_PASSKEY_TOAST).67let passkeyToastActive = false;68function startDismissLock(): void {69  dismissLock = true;70  if (dismissLockTimer) clearTimeout(dismissLockTimer);71  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);72}73function canOpen(): boolean { return !dismissLock; }7475// ── Fill-success lock ───────────────────────────────────────────────76// After Peach autofills a form, the popup must NOT reappear on the filled77// fields, on the submit button (some sites refocus it briefly), or on any78// field in that form — even when host-page DOM mutations or the form's own79// validation flow refocus an input. Implemented as a WeakSet of forms plus80// a page-level timestamp:81//   - filledForms: every form Peach has filled this page session. Survives82//     until the form leaves the DOM (WeakSet GC).83//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders84//     window for fields that aren't inside a <form> element (some SPAs).85// SPA navigation resets pageFilledAt via the urlObserver below; filledForms86// self-empties as old form elements get GC'd.87const filledForms = new WeakSet<HTMLFormElement>();88let pageFilledAt: number | null = null;89const PAGE_FILL_GRACE_MS = 3000;9091function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {92  for (const f of fields) {93    if (!f) continue;94    const form = f.closest("form");95    if (form) filledForms.add(form);96  }97  pageFilledAt = Date.now();98}99100function wasAlreadyFilled(field: HTMLInputElement): boolean {101  const form = field.closest("form");102  if (form && filledForms.has(form)) return true;103  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;104  return false;105}106107function clearFillStateForExplicitSummon(field: HTMLInputElement): void {108  const form = field.closest("form");109  if (form) filledForms.delete(form);110  pageFilledAt = null;111}112113// Some sites briefly focus the submit button when the user clicks it (visual114// feedback, blur/focus dance for validation animations). Catch those at the115// focusin layer so we don't re-trigger handleFieldInteraction for an event116// target that was never going to be a credential field anyway.117function isSubmitButton(el: EventTarget | null): boolean {118  if (!(el instanceof HTMLElement)) return false;119  if (el instanceof HTMLButtonElement && el.type !== "button") return true;120  if (el instanceof HTMLInputElement && el.type === "submit") return true;121  if (el.getAttribute("type") === "submit") return true;122  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();123  if (!text || text.length > 24) return false;124  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);125}126127function debounce<T extends (...args: unknown[]) => void>(128  fn: T,129  ms: number130): (...args: Parameters<T>) => void {131  let timer: ReturnType<typeof setTimeout>;132  return (...args: Parameters<T>) => {133    clearTimeout(timer);134    timer = setTimeout(() => fn(...args), ms);135  };136}137138function showToast(message: string): void {139  const toast = document.createElement("div");140  toast.style.cssText = `141    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);142    background: #131109; color: #F0E8D8; padding: 8px 16px;143    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;144    font-size: 11px; z-index: 2147483647; opacity: 0;145    transition: opacity 200ms ease;146    border: 1px solid rgba(240,232,216,0.07);147    pointer-events: none;148  `;149  toast.textContent = message;150  document.body.appendChild(toast);151  requestAnimationFrame(() => { toast.style.opacity = "1"; });152  setTimeout(() => {153    toast.style.opacity = "0";154    setTimeout(() => toast.remove(), 200);155  }, 2000);156}157158function showSearchPalette(): void {159  const host = document.createElement("div");160  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";161  document.body.appendChild(host);162  const shadow = host.attachShadow({ mode: "closed" });163164  const style = document.createElement("style");165  style.textContent = `166    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;167      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;168      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}169    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);170      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}171    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}172    .s{padding:8px 12px}173    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);174      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;175      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}176    .l{max-height:220px;overflow-y:auto}177    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}178    .e:hover{background:rgba(240,232,216,.06)}179    .et{font-size:12px}180    .eu{font-size:10px;color:rgba(240,232,216,.45)}181    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}182  `;183184  let allEntries: SelectorEntry[] = [];185  let query = "";186187  const panel = document.createElement("div");188  panel.className = "p";189190  const hdr = document.createElement("div");191  hdr.className = "h";192  const hdrText = document.createElement("span");193  hdrText.textContent = "No form detected — search your vault";194  const closeBtn = document.createElement("button");195  closeBtn.className = "x";196  closeBtn.textContent = "✕";197  hdr.appendChild(hdrText);198  hdr.appendChild(closeBtn);199200  const searchWrap = document.createElement("div");201  searchWrap.className = "s";202  const searchInput = document.createElement("input");203  searchInput.placeholder = "search...";204  searchWrap.appendChild(searchInput);205206  const list = document.createElement("div");207  list.className = "l";208209  panel.appendChild(hdr);210  panel.appendChild(searchWrap);211  panel.appendChild(list);212  shadow.appendChild(style);213  shadow.appendChild(panel);214215  function close() { host.remove(); }216217  closeBtn.onclick = close;218219  function onKeyDown(e: KeyboardEvent) {220    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }221  }222  document.addEventListener("keydown", onKeyDown, true);223224  function render() {225    const q = query.toLowerCase();226    const filtered = q227      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))228      : allEntries;229    list.innerHTML = "";230    if (filtered.length === 0) {231      const em = document.createElement("div");232      em.className = "em";233      em.textContent = query ? "no matches" : "vault is empty";234      list.appendChild(em);235      return;236    }237    for (const entry of filtered.slice(0, 20)) {238      const row = document.createElement("div");239      row.className = "e";240      const title = document.createElement("div");241      title.className = "et";242      title.textContent = entry.title;243      row.appendChild(title);244      if (entry.username) {245        const user = document.createElement("div");246        user.className = "eu";247        user.textContent = entry.username;248        row.appendChild(user);249      }250      row.onclick = async () => {251        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });252        const r = resp as { ok: boolean; data?: { password?: string } };253        if (r.ok && r.data?.password) {254          let alreadyWritten = false;255          try {256            await navigator.clipboard.writeText(r.data.password);257            alreadyWritten = true;258          } catch (err) {259            console.warn("[Peach] clipboard write denied:", err);260          }261          const copyResp = await chrome.runtime.sendMessage({262            type: "COPY",263            payload: { text: r.data.password, label: "Password", alreadyWritten },264          }) as { ok?: boolean } | undefined;265          if (alreadyWritten || copyResp?.ok) {266            showToast("Password copied");267          } else {268            showToast("Could not copy password — clipboard blocked");269          }270        } else {271          showToast("Could not copy password");272        }273        close();274        document.removeEventListener("keydown", onKeyDown, true);275      };276      list.appendChild(row);277    }278  }279280  searchInput.oninput = () => { query = searchInput.value; render(); };281282  fetchAutofillEntries(getPageDomain(), true).then(result => {283    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }284    allEntries = result.entries;285    render();286    searchInput.focus();287  });288}289290function findTOTPField(root: Document | Element = document): HTMLInputElement | null {291  const inputs = root.querySelectorAll<HTMLInputElement>("input");292  for (const input of inputs) {293    if (isTOTPField(input)) return input;294  }295  return null;296}297298function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {299  const form = passwordEl.closest("form");300  return findTOTPField(form ?? document);301}302303304async function handleAutofill(305  _field: HTMLInputElement,306  usernameEl: HTMLInputElement | null,307  passwordEl: HTMLInputElement | null,308  entry: VaultEntry309): Promise<HTMLInputElement | null> {310  if (!entry.username && !entry.password) return null;311  const pageDomain = getPageDomain();312  const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;313  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);314  let filledTOTPField: HTMLInputElement | null = null;315316  if (entry.canary) {317    chrome.runtime.sendMessage({318      type: "FIRE_CANARY_PING",319      payload: {320        webhookUrl: entry.canary.webhookUrl,321        entryTitle: entry.title,322        trigger: "autofilled",323      },324    }).catch(() => {});325    chrome.runtime.sendMessage({326      type: "UPDATE_ENTRY",327      payload: {328        id: entry.id,329        patch: {330          canary: {331            ...entry.canary,332            lastPinged: Date.now(),333            pingCount: (entry.canary.pingCount ?? 0) + 1,334          },335        },336      },337    }).catch(() => {});338  }339340  if (entry.totp) {341    const { code } = generateTOTP(entry.totp);342    const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;343    if (fillTOTPCode(totpField, code)) {344      filledTOTPField = totpField;345    }346    let alreadyWritten = false;347    try {348      await navigator.clipboard.writeText(code);349      alreadyWritten = true;350    } catch (err) {351      console.warn("[Peach] clipboard write denied:", err);352    }353    const response = await chrome.runtime.sendMessage({354      type: "COPY",355      payload: { text: code, label: "TOTP", alreadyWritten },356    });357    if (filledTOTPField) {358      showToast("2FA code filled");359    } else if (alreadyWritten || (response as { ok?: boolean }).ok) {360      showToast("TOTP copied · " + code);361    } else {362      showToast("Could not copy TOTP — clipboard blocked");363    }364  }365366  return filledTOTPField;367}368369async function fetchAutofillEntries(370  domain: string,371  includeAll = false372): Promise<{ entries: SelectorEntry[]; locked: boolean }> {373  const response = await chrome.runtime.sendMessage({374    type: "AUTOFILL_QUERY",375    payload: { domain, includeAll },376  });377  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };378  if (!res.ok && res.error === "vault_locked") {379    return { entries: [], locked: true };380  }381  return { entries: res.data ?? [], locked: false };382}383384async function fetchTOTPEntries(385  domain: string386): Promise<{ entries: SelectorEntry[]; locked: boolean }> {387  const response = await chrome.runtime.sendMessage({388    type: "AUTOFILL_QUERY",389    payload: { domain, kind: "totp" },390  });391  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };392  if (!res.ok && res.error === "vault_locked") {393    return { entries: [], locked: true };394  }395  return { entries: res.data ?? [], locked: false };396}397398399function resolveAutofillFieldType(400  el: HTMLInputElement,401  predictedType?: FieldPrediction["type"] | null402): "password" | "username" | "email" | null {403  if (404    predictedType === "password" ||405    predictedType === "username" ||406    predictedType === "email"407  ) {408    return predictedType;409  }410411  const detected = detectLoginFields().find((field) => field.el === el)?.type;412  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {413    return detected;414  }415416  const htmlType = el.type.toLowerCase();417  if (htmlType === "password") return "password";418  if (htmlType === "email") return "email";419  return null;420}421422async function openAutofillSelector(423  anchorField: HTMLInputElement,424  usernameEl: HTMLInputElement | null,425  passwordEl: HTMLInputElement | null,426  domainEntries: SelectorEntry[],427  searchableEntries: SelectorEntry[],428  domain: string429): Promise<void> {430  // No saved entries for this site → signup/new-account mode.431  // Fetch vault identities for the identity-first surface and locate432  // the confirm-password field so "Copy & fill" can populate it too.433  const isSignup = domainEntries.length === 0;434  let savedIdentities: SavedIdentity[] | undefined;435  let confirmEl: HTMLInputElement | null = null;436  if (isSignup) {437    try {438      const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as439        { ok: boolean; data?: SavedIdentity[] } | null;440      if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;441    } catch { /* silent fallback */ }442443    const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;444    const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));445    confirmEl = allPwInputs.find(446      (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)447    ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);448  }449450  currentDismiss?.();451  currentAnchorField = anchorField;452  currentDismiss = showAutofillSelector(453    anchorField,454    domainEntries,455    async (id: string) => {456      currentDismiss = null;457      currentAnchorField = null;458      const entryResponse = await chrome.runtime.sendMessage({459        type: "GET_ENTRY_FOR_FILL",460        payload: { id },461      });462      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;463      if (entry) {464        const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry);465        recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);466        // Offer to remember the current site for this entry only if none of467        // its known domains (primary + additional) match — otherwise the468        // user already mapped it and the prompt would be noise.469        const pageDomain = location.hostname.replace(/^www\./, "");470        const entryDomains = new Set<string>();471        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {472          try {473            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));474          } catch { /* ignore unparseable */ }475        }476        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {477          showRememberSiteToast(pageDomain, entry.id);478        }479      }480    },481    {482      domain,483      searchableEntries,484      isSignup,485      savedIdentities,486      onFillFields: (username, password) => {487        const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;488        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());489        if (password && confirmEl) setNativeValue(confirmEl, password);490        recordFillSuccess(anchorField, usernameEl, passwordEl);491      },492      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },493    }494  );495}496497async function openTOTPSelector(anchorField: HTMLInputElement): Promise<void> {498  if (!canOpen()) return;499  if (currentDismiss && currentAnchorField === anchorField) return;500  if (anchorField !== lastDismissedField) lastDismissedField = null;501  if (anchorField === lastDismissedField) return;502  if (wasAlreadyFilled(anchorField)) return;503504  const domain = getPageDomain();505  const result = await fetchTOTPEntries(domain);506507  if (result.locked) {508    currentDismiss?.();509    currentAnchorField = anchorField;510    currentDismiss = showAutofillSelector(511      anchorField,512      [],513      () => {},514      {515        domain,516        locked: true,517        onUnlocked: () => void openTOTPSelector(anchorField),518        onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },519      }520    );521    return;522  }523524  if (result.entries.length === 0) {525    lastDismissedField = anchorField;526    startDismissLock();527    showToast("No 2FA entries for this site — add a code in Peach first");528    return;529  }530531  currentDismiss?.();532  currentAnchorField = anchorField;533  currentDismiss = showTOTPSelector(534    anchorField,535    result.entries,536    async (id: string) => {537      try {538        const entryResponse = await chrome.runtime.sendMessage({539          type: "GET_ENTRY_FOR_FILL",540          payload: { id },541        }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;542        const entry = entryResponse?.ok ? entryResponse.data : undefined;543        if (!entry?.totp) return;544        const { code } = generateTOTP(entry.totp);545        setNativeValue(anchorField, code);546        recordFillSuccess(anchorField);547        showToast("2FA code filled");548      } finally {549        currentDismiss = null;550        currentAnchorField = null;551      }552    },553    {554      domain,555      onDismiss: () => {556        lastDismissedField = anchorField;557        startDismissLock();558        currentDismiss = null;559        currentAnchorField = null;560      },561    }562  );563}564565566async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {567  const field = anchorField ?? getDeepActiveInput();568  if (!field) return;569  if (!isVisible(field)) return;570571  // Passkey toast is visible — don't open the credential selector alongside it.572  if (passkeyToastActive) return;573574  // Layer 2: post-dismiss global lock. Catches rapid focus moves between575  // fields immediately after Escape/click-outside.576  if (!canOpen()) return;577578  // If a selector is already open for this exact field, don't flicker it.579  if (currentDismiss && currentAnchorField === field) return;580581  // If focus moved to a different field, the previous per-field dismiss lock582  // no longer applies.583  if (field !== lastDismissedField) lastDismissedField = null;584  // Layer 1: the user explicitly dismissed this field's selector — don't585  // reopen it until focus has genuinely moved away and come back.586  if (field === lastDismissedField) return;587588  // Fill-success lock: Peach already filled this form (or fired a fill589  // anywhere on the page within the grace window). Sites often refocus an590  // input on submit click, on validation, or on a transition to a success591  // state — none of those should re-open the popup.592  if (wasAlreadyFilled(field)) return;593594  // Prevent two concurrent calls for the same field (e.g. focusin + icon click595  // firing simultaneously — the second call would dismiss the first's selector).596  if (pendingInteractions.has(field)) return;597  pendingInteractions.add(field);598599  try {600    if (isTOTPField(field)) {601      const formFields = detectLoginFields();602      if (!isLoginForm(formFields) && !isSignupForm(formFields)) {603        await openTOTPSelector(field);604        return;605      }606    }607608    const fieldType = field.type.toLowerCase();609610    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {611      return preds[0] ?? null;612    });613614    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {615      const timeout = setTimeout(() => resolve(null), 150);616      mlPromise.then((pred) => {617        clearTimeout(timeout);618        resolve(pred);619      });620    });621622    if (passkeyToastActive) return;623624    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {625      return;626    }627628    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);629    if (autofillFieldType) {630      reattachListeners(field, autofillFieldType);631    }632633    let fields = detectLoginFields();634    if (!isAnyCredentialForm(fields)) {635      return;636    }637638    const domain = getPageDomain();639    const firstResult = await fetchAutofillEntries(domain);640    if (passkeyToastActive) return;641642    // Vault is locked — show an inline unlock prompt.643    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so644    // there is no double-trigger race between onUnlocked and the broadcast.645    if (firstResult.locked) {646      currentDismiss?.();647      currentAnchorField = field;648      currentDismiss = showAutofillSelector(649        field,650        [],651        () => {},652        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }653      );654      return;655    }656657    const entries = firstResult.entries;658    // Always fetch the vault-wide list so the inline popup's search affordance659    // can reach entries that don't match this domain — the user may have a660    // valid login filed under a different URL (e.g. corp account on a vanity661    // domain) and still want to fill it here.662    const allEntries = (await fetchAutofillEntries(domain, true)).entries;663664    if (passkeyToastActive) return;665666    let usernameEl: HTMLInputElement | null = null;667    const userField = fields.find((f) => f.type === "username" || f.type === "email");668    if (userField) usernameEl = userField.el;669    const pwField = fields.find((f) => f.type === "password");670    // For email-first flows there is no password field on this step — that is expected.671    if (!pwField && !isEmailFirstForm(fields)) return;672    const passwordEl = pwField?.el ?? null;673674    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);675  } finally {676    pendingInteractions.delete(field);677  }678}679680async function onFocusIn(e: Event): Promise<void> {681  // Submit-button focus: catch the brief refocus some sites do when the682  // user clicks the login/submit button. Without this guard, that focus683  // event reaches handleFieldInteraction → getDeepActiveInput, and on684  // pages where the button is also a labelled <input> we briefly attempt685  // to open the popup over the very button the user just clicked.686  if (isSubmitButton(e.target)) return;687  await handleFieldInteraction();688}689690function reattachListeners(691  el: HTMLInputElement,692  detectedType?: "password" | "username" | "email",693  contextFields?: ReturnType<typeof detectLoginFields>694): void {695  if (processedInputs.has(el)) return;696  if (!resolveAutofillFieldType(el, detectedType)) return;697  // Only inject icon when a credential form is present on the page698  const fields = contextFields ?? detectLoginFields();699  if (!isAnyCredentialForm(fields)) return;700701  const cleanup = injectFieldIcon(el, () => {702    currentDismiss?.();703    currentDismiss = null;704    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock705    dismissLock = false; // ...and the global lock706    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }707    clearFillStateForExplicitSummon(el);708    el.focus({ preventScroll: true });709    void handleFieldInteraction(el);710  });711  processedInputs.set(el, cleanup);712}713714const debouncedReattach = debounce(() => {715  const allFields = detectLoginFields();716  if (!isAnyCredentialForm(allFields)) return;717  const newFields = allFields.filter(718    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)719  );720  for (const f of newFields) {721    reattachListeners(f.el, f.type, allFields);722  }723  // 200ms debounce — below this, Peach and the host page's reactive layer724  // fight over the same layout properties every frame on React/Vue/Angular725  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.726}, 200);727728function setupMutationObserver(): void {729  const observer = new MutationObserver(debouncedReattach);730  observer.observe(document.body, {731    childList: true,732    subtree: true,733    attributes: true,734    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],735  });736}737738function initialScan(aggressionLevel = 0, isFinalPass = false) {739  const allFields = detectLoginFields();740  const hasKnownForm = isAnyCredentialForm(allFields);741742  if (aggressionLevel === 0 && !hasKnownForm) return;743744  const newFields = allFields.filter(745    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)746  );747748  for (const f of newFields) {749    reattachListeners(f.el, f.type, allFields);750  }751752  // Level 2, final pass: inject icon on any visible password field even if753  // the form-context gate in reattachListeners would normally skip it.754  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {755    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');756    for (const el of pwInputs) {757      if (isVisible(el) && !processedInputs.has(el)) {758        const cleanup = injectFieldIcon(el, () => {759          currentDismiss?.();760          currentDismiss = null;761          lastDismissedField = null;762          dismissLock = false;763          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }764          clearFillStateForExplicitSummon(el);765          el.focus({ preventScroll: true });766          void handleFieldInteraction(el);767        });768        processedInputs.set(el, cleanup);769      }770    }771  }772}773774// ── TOTP-only fields ───────────────────────────────────────────────────────775// After a username/password submission, many sites swap the whole form for a776// lone "verification code" input. The credential selector intentionally gates777// on login/signup forms, so TOTP fields need a narrow path of their own.778const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();779780function hasLoginOrSignupForm(): boolean {781  const fields = detectLoginFields();782  return isAnyCredentialForm(fields);783}784785function injectTOTPFieldIcon(field: HTMLInputElement): void {786  if (processedTOTPInputs.has(field)) return;787  const cleanup = injectFieldIcon(field, () => {788    currentDismiss?.();789    currentDismiss = null;790    currentAnchorField = null;791    lastDismissedField = null;792    dismissLock = false;793    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }794    clearFillStateForExplicitSummon(field);795    field.focus({ preventScroll: true });796    void openTOTPSelector(field);797  });798  processedTOTPInputs.set(field, cleanup);799}800801function scanTOTPFields(): void {802  if (hasLoginOrSignupForm()) return;803  const inputs = document.querySelectorAll<HTMLInputElement>("input");804  for (const input of inputs) {805    if (!isTOTPField(input)) continue;806    injectTOTPFieldIcon(input);807  }808}809810function setupTOTPAutofill(): void {811  setTimeout(scanTOTPFields, 0);812  setTimeout(scanTOTPFields, 500);813  setTimeout(scanTOTPFields, 1500);814815  const debouncedScan = debounce(scanTOTPFields, 200);816  new MutationObserver(debouncedScan).observe(document.body, {817    childList: true,818    subtree: true,819    attributes: true,820    attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],821  });822823  document.addEventListener("focusin", (e) => {824    const target = e.target;825    if (!(target instanceof HTMLInputElement)) return;826    if (hasLoginOrSignupForm()) return;827    if (!isTOTPField(target)) return;828    injectTOTPFieldIcon(target);829  }, true);830}831832document.addEventListener("focusin", onFocusIn);833834setupMutationObserver();835setupTOTPAutofill();836setupSaveDetection();837setupCardAutofill();838839// SPA navigation reset: the content script does not reload across in-app840// route changes (history.pushState, hash navigation, framework routers).841// When the URL changes we clear the page-level fill timestamp so the next842// page works normally; filledForms (a WeakSet) self-empties as old form843// elements leave the DOM. subtree:false because route swaps reliably844// mutate document.body's direct children — subtree:true would fire on845// every internal DOM update and cost us a re-check per mutation.846let lastObservedUrl = location.href;847new MutationObserver(() => {848  if (location.href !== lastObservedUrl) {849    lastObservedUrl = location.href;850    pageFilledAt = null;851  }852}).observe(document.body, { childList: true, subtree: false });853854// Async init: check recall map before running the initial scans so we can855// apply the right aggression level for domains the user has needed before.856(async () => {857  let aggressionLevel = 0;858  try {859    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });860    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;861    const domain = getPageDomain();862    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;863    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;864  } catch { /* SW may be starting up; proceed with normal scan */ }865866  setTimeout(() => initialScan(aggressionLevel, false), 0);867  setTimeout(() => initialScan(aggressionLevel, false), 500);868  setTimeout(() => initialScan(aggressionLevel, true), 1500);869})();870871// ── Card autofill (State 7) ─────────────────────────────────────────872// Card forms get a parallel injection path. The login icon-injection gate873// in reattachListeners deliberately skips non-text fields, so we wire874// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping875// card detection contained makes the boundary easy to follow.876const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();877let currentCardDismiss: (() => void) | null = null;878let currentCardAnchor: HTMLInputElement | null = null;879let lastDismissedCardField: HTMLInputElement | null = null;880881async function fetchSavedCards(): Promise<CardSelectorEntry[]> {882  const resp = await chrome.runtime.sendMessage({883    type: "AUTOFILL_QUERY",884    payload: { domain: getPageDomain(), kind: "card" },885  }).catch(() => null);886  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;887  return r?.ok ? (r.data ?? []) : [];888}889890async function openCardSelector(anchor: HTMLInputElement): Promise<void> {891  if (!canOpen()) return;892  if (currentCardDismiss && currentCardAnchor === anchor) return;893  if (anchor === lastDismissedCardField) return;894  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;895  if (wasAlreadyFilled(anchor)) return;896897  const cards = await fetchSavedCards();898  if (cards.length === 0) return; // no saved cards → nothing to offer899900  const cardForm = detectCardForm();901  if (!cardForm?.number) return;902903  currentCardDismiss?.();904  currentCardAnchor = anchor;905  currentCardDismiss = showCardSelector(906    anchor,907    cards,908    {909      domain: getPageDomain(),910      onFill: (entry) => {911        if (!cardForm) return;912        fillCardForm(cardForm, {913          cardNumber: entry.cardNumber ?? "",914          expMonth: entry.expMonth ?? "",915          expYear: entry.expYear ?? "",916          cvc: entry.cvc ?? "",917          cardholderName: entry.cardholderName ?? "",918        });919        // All four card field types share the same form — recording the920        // number field's form is sufficient to suppress reopens on any of921        // them via wasAlreadyFilled().922        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);923        currentCardDismiss = null;924        currentCardAnchor = null;925      },926      onDismiss: () => {927        lastDismissedCardField = anchor;928        startDismissLock();929        currentCardDismiss = null;930        currentCardAnchor = null;931      },932    }933  );934}935936function injectCardIcon(field: HTMLInputElement): void {937  if (processedCardInputs.has(field)) return;938  const cleanup = injectFieldIcon(field, () => {939    currentCardDismiss?.();940    currentCardDismiss = null;941    lastDismissedCardField = null;942    dismissLock = false;943    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }944    clearFillStateForExplicitSummon(field);945    field.focus({ preventScroll: true });946    void openCardSelector(field);947  });948  processedCardInputs.set(field, cleanup);949}950951function setupCardAutofill(): void {952  function scan() {953    const cardForm = detectCardForm();954    if (!cardForm?.number) return;955    if (!isVisible(cardForm.number)) return;956    injectCardIcon(cardForm.number);957  }958959  // Initial detection sweep — same retry cadence as login fields so960  // late-hydrating SPA checkout pages get caught.961  setTimeout(scan, 0);962  setTimeout(scan, 500);963  setTimeout(scan, 1500);964965  // Re-scan on DOM mutation (separate from the login MutationObserver966  // because card forms typically appear on a single navigation event,967  // not field-by-field — coarser observation is sufficient here).968  let pending = false;969  new MutationObserver(() => {970    if (pending) return;971    pending = true;972    setTimeout(() => { pending = false; scan(); }, 200);973  }).observe(document.body, { childList: true, subtree: true });974975  // Field-focus path: on focus of a cc-number input, ensure icon is976  // present and consider opening the selector when the user explicitly977  // clicks into the card number field.978  document.addEventListener("focusin", (e) => {979    const target = e.target;980    if (!(target instanceof HTMLInputElement)) return;981    const cardForm = detectCardForm();982    if (cardForm?.number === target) {983      injectCardIcon(target);984    }985  }, true);986}987988chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {989  // Ignore anything not originating from our own background/service worker.990  if (sender.id !== chrome.runtime.id) return;991  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {992    const policy = detectPasswordPolicy();993    sendResponse({ ok: true, data: policy });994    return true;995  }996  if (msg?.type === "PING") {997    sendResponse({ ok: true });998    return true;999  }1000  if (msg?.type === "SUMMON_AUTOFILL") {1001    const source = (msg as { type: string; source?: string }).source;1002    const isShortcut = source === "shortcut";1003    const isPasskeyUnlock = source === "passkey-unlock";10041005    const activeInput = getDeepActiveInput();1006    const fields = detectLoginFields();1007    const hasForm = isAnyCredentialForm(fields);10081009    if (hasForm) {1010      // Prefer the currently focused field if it's a login field, otherwise1011      // fall back to the first password field, then username/email.1012      const inForm = activeInput && fields.some(f => f.el === activeInput);1013      const target = inForm1014        ? activeInput1015        : (fields.find(f => f.type === "password")?.el1016            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1017      if (target) {1018        // Explicit user summon (shortcut or extension button) — bypass all1019        // suppression layers. The user is asking for the popup right now.1020        clearFillStateForExplicitSummon(target);1021        dismissLock = false;1022        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1023        lastDismissedField = null;1024        void handleFieldInteraction(target);1025      }1026    } else if (isPasskeyUnlock) {1027      // Vault is locked during a passkey GET request. Show the inline unlock1028      // prompt anchored to whatever element is focused on the page (typically1029      // the passkey/sign-in button the user just tapped).1030      const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1031        ? document.activeElement as unknown as HTMLInputElement1032        : null;1033      if (anchor) {1034        currentDismiss?.();1035        currentAnchorField = null;1036        passkeySummonActive = true;1037        currentDismiss = showAutofillSelector(anchor, [], () => {}, {1038          domain: getPageDomain(),1039          locked: true,1040          onDismiss: () => { passkeySummonActive = false; },1041        });1042      }1043    } else if (isShortcut) {1044      // Shortcut on a page with no login form — show clipboard-copy search mode.1045      showSearchPalette();1046    }10471048    // Record this domain for the recall system when triggered via shortcut.1049    if (isShortcut) {1050      const domain = getPageDomain();1051      if (domain) {1052        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1053      }1054    }10551056    sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1057    return true;1058  }1059  if (msg?.type === "PASSKEY_PRO_GATE") {1060    // Background rejected a passkey request for a free user. Show State 111061    // so they know what happened and can choose to upgrade.1062    showPasskeyProGate();1063    sendResponse({ ok: true });1064    return true;1065  }1066  if (msg?.type === "SHOW_PASSKEY_TOAST") {1067    // Block autofill selector for the lifetime of the toast and dismiss anything open.1068    passkeyToastActive = true;1069    if (currentDismiss) {1070      currentDismiss();1071      currentDismiss = null;1072      currentAnchorField = null;1073    }1074    return false; // inject.tsx owns the toast and calls sendResponse1075  }1076  if (msg?.type === "DISMISS_PASSKEY_TOAST") {1077    passkeyToastActive = false;1078    return false; // inject.tsx handles the actual dismissal1079  }1080  if (msg?.type === "VAULT_UNLOCKED") {1081    if (passkeySummonActive) {1082      // This unlock was for a pending passkey GET request. Just dismiss the1083      // inline popup — the passkey approval toast takes over from here.1084      passkeySummonActive = false;1085      if (currentDismiss) {1086        currentDismiss();1087        currentDismiss = null;1088        currentAnchorField = null;1089      }1090      sendResponse({ ok: true });1091      return true;1092    }1093    // Normal autofill path: close the locked-state prompt and re-open with1094    // fresh entry data at the same anchor field.1095    const savedField = currentAnchorField;1096    if (currentDismiss) {1097      currentDismiss();1098      currentDismiss = null;1099      currentAnchorField = null;1100    }1101    void handleFieldInteraction(savedField ?? undefined);1102    sendResponse({ ok: true });1103    return true;1104  }1105  return true;1106});11071108// inject.tsx posts this when the passkey toast closes (approve, deny, or timeout)1109// so we know it's safe to allow autofill again.1110window.addEventListener("message", (e: MessageEvent) => {1111  // Reject postMessages from cross-frame senders — only the same window's1112  // injected toast may flip this flag.1113  if (e.source !== window) return;1114  const d = e.data as { source?: string; type?: string } | undefined;1115  if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1116    passkeyToastActive = false;1117  }1118});11191120// ── Firefox passkey detection bridge (legacy observer path) ─────────────1121//1122// Pre-v2.12.0 the MAIN-world `passkeys-firefox.ts` was an observer — it1123// emitted `peach-passkey-firefox` postMessages so this content script could1124// surface State 12 (an inline "Save passkey to Peach" offer). v2.12.01125// replaced the observer with a full interception proxy (the page never1126// reaches a real navigator.credentials.create on Firefox anymore), and the1127// approval UI is opened by the background as part of the ceremony itself.1128// When the proxy is active the offer would be redundant noise, so the1129// listener gates on the flag. Once the proxy is removed (Firefox ships1130// webAuthenticationProxy) this whole block goes too.1131if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1132  let lastPasskeyOfferAt = 0;1133  const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11341135  window.addEventListener("message", (event: MessageEvent) => {1136    if (event.source !== window) return;1137    const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1138    if (!data || data.source !== "peach-passkey-firefox") return;1139    if (detectBrowser() !== "firefox") return;1140    if (data.type !== "create") return;11411142    // Cooldown: a single page interaction can fire multiple credentials.create1143    // calls. Show the offer at most once per 30 seconds per page session.1144    const now = Date.now();1145    if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1146    lastPasskeyOfferAt = now;11471148    const domain = location.hostname.replace(/^www\./, "");1149    chrome.runtime.sendMessage({1150      type: "GET_PASSKEY_OFFER_DECLINED",1151      payload: { domain },1152    }).then((res: { ok: boolean; data?: boolean } | undefined) => {1153      if (res?.data === true) return;1154      const rpId = data.rpId ?? domain;1155      showPasskeyRegistrationOffer({1156        rpId,1157        rpName: data.rpName,1158        userName: data.userName,1159        userDisplayName: data.userDisplayName,1160      });1161    }).catch(() => {});1162  });1163}11641165// Surface State 11 (passkey-available) only when it adds value:1166//   - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither1167//     browser will auto-route, so the banner explains the re-register need.1168//   - Firefox + same-browser entry: Firefox has no equivalent of1169//     webAuthenticationProxy, so without a banner the user has no signal that1170//     Peach is the source.1171// On Chrome with a same-browser entry: skip — webAuthenticationProxy handles1172// the page's own credentials.get transparently and the popup approval view1173// already surfaces it. A banner here would just be noise.1174//1175// Dedupe across navigation: each navigation re-injects this content script.1176// chrome.storage.session keyed by domain is the natural per-tab/per-session1177// memory; session storage clears when the user closes the browser.1178{1179  function checkPasskeyAvailability() {1180    const domain = location.hostname.replace(/^www\./, "");1181    if (!domain) return;1182    const sessionKey = `peach_state11_shown:${domain}`;1183    chrome.storage.session?.get(sessionKey).then((stored) => {1184      if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1185      chrome.runtime.sendMessage({1186        type: "GET_PASSKEY_FOR_DOMAIN",1187        payload: { domain },1188      }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1189        const data = res?.data;1190        if (!data) return;1191        const current = detectBrowser();1192        const isCrossBrowser =1193          data.browser && current !== "unknown" && data.browser !== current;1194        const valuableOnFirefox = current === "firefox";1195        if (!isCrossBrowser && !valuableOnFirefox) return;1196        chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1197        showPasskeyAvailable({1198          rpId: data.rpId,1199          userName: data.userName,1200          fromBrowser: data.browser,1201          currentBrowser: current,1202        });1203      }).catch(() => {});1204    }).catch(() => {});1205  }12061207  // Defer until DOM is interactive — content_scripts run at document_idle but1208  // some pages still mutate visibly afterwards. A short delay also avoids1209  // surfacing the State 11 toast while the user is in the middle of typing.1210  if (document.readyState === "loading") {1211    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1212  } else {1213    setTimeout(checkPasskeyAvailability, 800);1214  }1215}