index.ts

45.5 KB · raw

1import {2  detectCardForm,3  detectLoginFields,4  getDeepActiveInput,5  getPageDomain,6  isLoginForm,7  isSignupForm,8  isTOTPField,9  isVisible,10} from "./detect";11import {12  CardSelectorEntry,13  injectFieldIcon,14  SelectorEntry,15  showAutofillSelector,16  showCardSelector,17  showPasskeyAvailable,18  showPasskeyProGate,19  showPasskeyRegistrationOffer,20  showRememberSiteToast,21  showTOTPSelector,22} from "./inject";23import { detectBrowser } from "../shared/browser";24import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";25import { fillCardForm, fillFields, fillTOTPCode, setNativeValue } from "./fill";26import { setupSaveDetection } from "./save";27import { contentMLDetector } from "./content-ml-detector";28import { detectPasswordPolicy } from "./policy";29import type { FieldPrediction } from "../shared/ml";30import { generateTOTP } from "../crypto/totp";31import type { SavedIdentity, VaultEntry } from "../shared/types";3233// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value34// so we can tear down listeners if we ever need to re-process the same field.35// When the input is GC'd (SPA nav, React re-render), the map entry goes with36// it and we can re-inject without leaking the old handler.37const processedInputs = new WeakMap<HTMLInputElement, () => void>();38const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3940let currentDismiss: (() => void) | null = null;41// Field whose selector is currently open — used to avoid dismiss+reopen flicker42let currentAnchorField: HTMLInputElement | null = null;43// Prevents two concurrent handleFieldInteraction calls for the same field44const pendingInteractions = new WeakSet<HTMLInputElement>();45// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).46// Suppresses spurious reopens until focus moves to a different field. Layer 147// of the dismissal model — see Projects.md §4.12.48let lastDismissedField: HTMLInputElement | null = null;4950// ── Dismissal lock (Layer 2) ────────────────────────────────────────51// After any user-initiated dismiss, briefly block ALL reopens regardless of52// which field is focused. Catches the case where a page rapidly moves focus53// between fields after Escape — without this, focus moving to a SECOND field54// in <100ms would re-trigger the popup before the user finished dismissing.55const DISMISS_LOCK_MS = 800;56let dismissLock = false;57let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;58// Set when the inline popup was summoned specifically for a passkey-unlock59// flow. The VAULT_UNLOCKED handler checks this to skip re-triggering autofill60// (the passkey toast handles the next step instead).61let passkeySummonActive = false;62// Set while the passkey approval toast is visible. Prevents handleFieldInteraction63// from opening the autofill selector alongside it. Cleared by a window message64// posted by inject.tsx when the toast closes (and by DISMISS_PASSKEY_TOAST).65let passkeyToastActive = false;66function startDismissLock(): void {67  dismissLock = true;68  if (dismissLockTimer) clearTimeout(dismissLockTimer);69  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);70}71function canOpen(): boolean { return !dismissLock; }7273// ── Fill-success lock ───────────────────────────────────────────────74// After Peach autofills a form, the popup must NOT reappear on the filled75// fields, on the submit button (some sites refocus it briefly), or on any76// field in that form — even when host-page DOM mutations or the form's own77// validation flow refocus an input. Implemented as a WeakSet of forms plus78// a page-level timestamp:79//   - filledForms: every form Peach has filled this page session. Survives80//     until the form leaves the DOM (WeakSet GC).81//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders82//     window for fields that aren't inside a <form> element (some SPAs).83// SPA navigation resets pageFilledAt via the urlObserver below; filledForms84// self-empties as old form elements get GC'd.85const filledForms = new WeakSet<HTMLFormElement>();86let pageFilledAt: number | null = null;87const PAGE_FILL_GRACE_MS = 3000;8889function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {90  for (const f of fields) {91    if (!f) continue;92    const form = f.closest("form");93    if (form) filledForms.add(form);94  }95  pageFilledAt = Date.now();96}9798function wasAlreadyFilled(field: HTMLInputElement): boolean {99  const form = field.closest("form");100  if (form && filledForms.has(form)) return true;101  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;102  return false;103}104105function clearFillStateForExplicitSummon(field: HTMLInputElement): void {106  const form = field.closest("form");107  if (form) filledForms.delete(form);108  pageFilledAt = null;109}110111// Some sites briefly focus the submit button when the user clicks it (visual112// feedback, blur/focus dance for validation animations). Catch those at the113// focusin layer so we don't re-trigger handleFieldInteraction for an event114// target that was never going to be a credential field anyway.115function isSubmitButton(el: EventTarget | null): boolean {116  if (!(el instanceof HTMLElement)) return false;117  if (el instanceof HTMLButtonElement && el.type !== "button") return true;118  if (el instanceof HTMLInputElement && el.type === "submit") return true;119  if (el.getAttribute("type") === "submit") return true;120  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();121  if (!text || text.length > 24) return false;122  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);123}124125function debounce<T extends (...args: unknown[]) => void>(126  fn: T,127  ms: number128): (...args: Parameters<T>) => void {129  let timer: ReturnType<typeof setTimeout>;130  return (...args: Parameters<T>) => {131    clearTimeout(timer);132    timer = setTimeout(() => fn(...args), ms);133  };134}135136function showToast(message: string): void {137  const toast = document.createElement("div");138  toast.style.cssText = `139    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);140    background: #131109; color: #F0E8D8; padding: 8px 16px;141    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;142    font-size: 11px; z-index: 2147483647; opacity: 0;143    transition: opacity 200ms ease;144    border: 1px solid rgba(240,232,216,0.07);145    pointer-events: none;146  `;147  toast.textContent = message;148  document.body.appendChild(toast);149  requestAnimationFrame(() => { toast.style.opacity = "1"; });150  setTimeout(() => {151    toast.style.opacity = "0";152    setTimeout(() => toast.remove(), 200);153  }, 2000);154}155156function showSearchPalette(): void {157  const host = document.createElement("div");158  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";159  document.body.appendChild(host);160  const shadow = host.attachShadow({ mode: "closed" });161162  const style = document.createElement("style");163  style.textContent = `164    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;165      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;166      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}167    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);168      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}169    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}170    .s{padding:8px 12px}171    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);172      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;173      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}174    .l{max-height:220px;overflow-y:auto}175    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}176    .e:hover{background:rgba(240,232,216,.06)}177    .et{font-size:12px}178    .eu{font-size:10px;color:rgba(240,232,216,.45)}179    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}180  `;181182  let allEntries: SelectorEntry[] = [];183  let query = "";184185  const panel = document.createElement("div");186  panel.className = "p";187188  const hdr = document.createElement("div");189  hdr.className = "h";190  const hdrText = document.createElement("span");191  hdrText.textContent = "No form detected — search your vault";192  const closeBtn = document.createElement("button");193  closeBtn.className = "x";194  closeBtn.textContent = "✕";195  hdr.appendChild(hdrText);196  hdr.appendChild(closeBtn);197198  const searchWrap = document.createElement("div");199  searchWrap.className = "s";200  const searchInput = document.createElement("input");201  searchInput.placeholder = "search...";202  searchWrap.appendChild(searchInput);203204  const list = document.createElement("div");205  list.className = "l";206207  panel.appendChild(hdr);208  panel.appendChild(searchWrap);209  panel.appendChild(list);210  shadow.appendChild(style);211  shadow.appendChild(panel);212213  function close() { host.remove(); }214215  closeBtn.onclick = close;216217  function onKeyDown(e: KeyboardEvent) {218    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }219  }220  document.addEventListener("keydown", onKeyDown, true);221222  function render() {223    const q = query.toLowerCase();224    const filtered = q225      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))226      : allEntries;227    list.innerHTML = "";228    if (filtered.length === 0) {229      const em = document.createElement("div");230      em.className = "em";231      em.textContent = query ? "no matches" : "vault is empty";232      list.appendChild(em);233      return;234    }235    for (const entry of filtered.slice(0, 20)) {236      const row = document.createElement("div");237      row.className = "e";238      const title = document.createElement("div");239      title.className = "et";240      title.textContent = entry.title;241      row.appendChild(title);242      if (entry.username) {243        const user = document.createElement("div");244        user.className = "eu";245        user.textContent = entry.username;246        row.appendChild(user);247      }248      row.onclick = async () => {249        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });250        const r = resp as { ok: boolean; data?: { password?: string } };251        if (r.ok && r.data?.password) {252          let alreadyWritten = false;253          try {254            await navigator.clipboard.writeText(r.data.password);255            alreadyWritten = true;256          } catch (err) {257            console.warn("[Peach] clipboard write denied:", err);258          }259          const copyResp = await chrome.runtime.sendMessage({260            type: "COPY",261            payload: { text: r.data.password, label: "Password", alreadyWritten },262          }) as { ok?: boolean } | undefined;263          if (alreadyWritten || copyResp?.ok) {264            showToast("Password copied");265          } else {266            showToast("Could not copy password — clipboard blocked");267          }268        } else {269          showToast("Could not copy password");270        }271        close();272        document.removeEventListener("keydown", onKeyDown, true);273      };274      list.appendChild(row);275    }276  }277278  searchInput.oninput = () => { query = searchInput.value; render(); };279280  fetchAutofillEntries(getPageDomain(), true).then(result => {281    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }282    allEntries = result.entries;283    render();284    searchInput.focus();285  });286}287288function findTOTPField(root: Document | Element = document): HTMLInputElement | null {289  const inputs = root.querySelectorAll<HTMLInputElement>("input");290  for (const input of inputs) {291    if (isTOTPField(input)) return input;292  }293  return null;294}295296function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {297  const form = passwordEl.closest("form");298  return findTOTPField(form ?? document);299}300301302async function handleAutofill(303  _field: HTMLInputElement,304  usernameEl: HTMLInputElement | null,305  passwordEl: HTMLInputElement,306  entry: VaultEntry307): Promise<HTMLInputElement | null> {308  if (!entry.username && !entry.password) return null;309  const pageDomain = getPageDomain();310  const form = passwordEl.closest("form") as HTMLFormElement | null;311  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);312  let filledTOTPField: HTMLInputElement | null = null;313314  if (entry.canary) {315    chrome.runtime.sendMessage({316      type: "FIRE_CANARY_PING",317      payload: {318        webhookUrl: entry.canary.webhookUrl,319        entryTitle: entry.title,320        trigger: "autofilled",321      },322    }).catch(() => {});323    chrome.runtime.sendMessage({324      type: "UPDATE_ENTRY",325      payload: {326        id: entry.id,327        patch: {328          canary: {329            ...entry.canary,330            lastPinged: Date.now(),331            pingCount: (entry.canary.pingCount ?? 0) + 1,332          },333        },334      },335    }).catch(() => {});336  }337338  if (entry.totp) {339    const { code } = generateTOTP(entry.totp);340    const totpField = findSameLoginTOTPField(passwordEl);341    if (fillTOTPCode(totpField, code)) {342      filledTOTPField = totpField;343    }344    let alreadyWritten = false;345    try {346      await navigator.clipboard.writeText(code);347      alreadyWritten = true;348    } catch (err) {349      console.warn("[Peach] clipboard write denied:", err);350    }351    const response = await chrome.runtime.sendMessage({352      type: "COPY",353      payload: { text: code, label: "TOTP", alreadyWritten },354    });355    if (filledTOTPField) {356      showToast("2FA code filled");357    } else if (alreadyWritten || (response as { ok?: boolean }).ok) {358      showToast("TOTP copied · " + code);359    } else {360      showToast("Could not copy TOTP — clipboard blocked");361    }362  }363364  return filledTOTPField;365}366367async function fetchAutofillEntries(368  domain: string,369  includeAll = false370): Promise<{ entries: SelectorEntry[]; locked: boolean }> {371  const response = await chrome.runtime.sendMessage({372    type: "AUTOFILL_QUERY",373    payload: { domain, includeAll },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: string384): Promise<{ entries: SelectorEntry[]; locked: boolean }> {385  const response = await chrome.runtime.sendMessage({386    type: "AUTOFILL_QUERY",387    payload: { domain, kind: "totp" },388  });389  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };390  if (!res.ok && res.error === "vault_locked") {391    return { entries: [], locked: true };392  }393  return { entries: res.data ?? [], locked: false };394}395396397function resolveAutofillFieldType(398  el: HTMLInputElement,399  predictedType?: FieldPrediction["type"] | null400): "password" | "username" | "email" | null {401  if (402    predictedType === "password" ||403    predictedType === "username" ||404    predictedType === "email"405  ) {406    return predictedType;407  }408409  const detected = detectLoginFields().find((field) => field.el === el)?.type;410  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {411    return detected;412  }413414  const htmlType = el.type.toLowerCase();415  if (htmlType === "password") return "password";416  if (htmlType === "email") return "email";417  return null;418}419420async function openAutofillSelector(421  anchorField: HTMLInputElement,422  usernameEl: HTMLInputElement | null,423  passwordEl: HTMLInputElement,424  domainEntries: SelectorEntry[],425  searchableEntries: SelectorEntry[],426  domain: string427): Promise<void> {428  // No saved entries for this site → signup/new-account mode.429  // Fetch vault identities for the identity-first surface and locate430  // the confirm-password field so "Copy & fill" can populate it too.431  const isSignup = domainEntries.length === 0;432  let savedIdentities: SavedIdentity[] | undefined;433  let confirmEl: HTMLInputElement | null = null;434  if (isSignup) {435    try {436      const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as437        { ok: boolean; data?: SavedIdentity[] } | null;438      if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;439    } catch { /* silent fallback */ }440441    const form = passwordEl.closest("form") ?? document.body;442    const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));443    confirmEl = allPwInputs.find(444      (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)445    ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);446  }447448  currentDismiss?.();449  currentAnchorField = anchorField;450  currentDismiss = showAutofillSelector(451    anchorField,452    domainEntries,453    async (id: string) => {454      currentDismiss = null;455      currentAnchorField = null;456      const entryResponse = await chrome.runtime.sendMessage({457        type: "GET_ENTRY_FOR_FILL",458        payload: { id },459      });460      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;461      if (entry) {462        const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry);463        recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);464        // Offer to remember the current site for this entry only if none of465        // its known domains (primary + additional) match — otherwise the466        // user already mapped it and the prompt would be noise.467        const pageDomain = location.hostname.replace(/^www\./, "");468        const entryDomains = new Set<string>();469        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {470          try {471            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));472          } catch { /* ignore unparseable */ }473        }474        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {475          showRememberSiteToast(pageDomain, entry.id);476        }477      }478    },479    {480      domain,481      searchableEntries,482      isSignup,483      savedIdentities,484      onFillFields: (username, password) => {485        const form = passwordEl.closest("form") as HTMLFormElement | null;486        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());487        if (password && confirmEl) setNativeValue(confirmEl, password);488        recordFillSuccess(anchorField, usernameEl, passwordEl);489      },490      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },491    }492  );493}494495async function openTOTPSelector(anchorField: HTMLInputElement): Promise<void> {496  if (!canOpen()) return;497  if (currentDismiss && currentAnchorField === anchorField) return;498  if (anchorField !== lastDismissedField) lastDismissedField = null;499  if (anchorField === lastDismissedField) return;500  if (wasAlreadyFilled(anchorField)) return;501502  const domain = getPageDomain();503  const result = await fetchTOTPEntries(domain);504505  if (result.locked) {506    currentDismiss?.();507    currentAnchorField = anchorField;508    currentDismiss = showAutofillSelector(509      anchorField,510      [],511      () => {},512      {513        domain,514        locked: true,515        onUnlocked: () => void openTOTPSelector(anchorField),516        onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },517      }518    );519    return;520  }521522  if (result.entries.length === 0) {523    lastDismissedField = anchorField;524    startDismissLock();525    showToast("No 2FA entries for this site — add a code in Peach first");526    return;527  }528529  currentDismiss?.();530  currentAnchorField = anchorField;531  currentDismiss = showTOTPSelector(532    anchorField,533    result.entries,534    async (id: string) => {535      try {536        const entryResponse = await chrome.runtime.sendMessage({537          type: "GET_ENTRY_FOR_FILL",538          payload: { id },539        }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;540        const entry = entryResponse?.ok ? entryResponse.data : undefined;541        if (!entry?.totp) return;542        const { code } = generateTOTP(entry.totp);543        setNativeValue(anchorField, code);544        recordFillSuccess(anchorField);545        showToast("2FA code filled");546      } finally {547        currentDismiss = null;548        currentAnchorField = null;549      }550    },551    {552      domain,553      onDismiss: () => {554        lastDismissedField = anchorField;555        startDismissLock();556        currentDismiss = null;557        currentAnchorField = null;558      },559    }560  );561}562563564async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {565  const field = anchorField ?? getDeepActiveInput();566  if (!field) return;567  if (!isVisible(field)) return;568569  // Passkey toast is visible — don't open the credential selector alongside it.570  if (passkeyToastActive) return;571572  // Layer 2: post-dismiss global lock. Catches rapid focus moves between573  // fields immediately after Escape/click-outside.574  if (!canOpen()) return;575576  // If a selector is already open for this exact field, don't flicker it.577  if (currentDismiss && currentAnchorField === field) return;578579  // If focus moved to a different field, the previous per-field dismiss lock580  // no longer applies.581  if (field !== lastDismissedField) lastDismissedField = null;582  // Layer 1: the user explicitly dismissed this field's selector — don't583  // reopen it until focus has genuinely moved away and come back.584  if (field === lastDismissedField) return;585586  // Fill-success lock: Peach already filled this form (or fired a fill587  // anywhere on the page within the grace window). Sites often refocus an588  // input on submit click, on validation, or on a transition to a success589  // state — none of those should re-open the popup.590  if (wasAlreadyFilled(field)) return;591592  // Prevent two concurrent calls for the same field (e.g. focusin + icon click593  // firing simultaneously — the second call would dismiss the first's selector).594  if (pendingInteractions.has(field)) return;595  pendingInteractions.add(field);596597  try {598    if (isTOTPField(field)) {599      const formFields = detectLoginFields();600      if (!isLoginForm(formFields) && !isSignupForm(formFields)) {601        await openTOTPSelector(field);602        return;603      }604    }605606    const fieldType = field.type.toLowerCase();607608    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {609      return preds[0] ?? null;610    });611612    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {613      const timeout = setTimeout(() => resolve(null), 150);614      mlPromise.then((pred) => {615        clearTimeout(timeout);616        resolve(pred);617      });618    });619620    if (passkeyToastActive) return;621622    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {623      return;624    }625626    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);627    if (autofillFieldType) {628      reattachListeners(field, autofillFieldType);629    }630631    let fields = detectLoginFields();632    const loginForm = isLoginForm(fields);633    const signupForm = isSignupForm(fields);634    if (!loginForm && !signupForm) {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    const allEntries = entries.length === 0659      ? (await fetchAutofillEntries(domain, true)).entries660      : entries;661662    if (passkeyToastActive) return;663664    let usernameEl: HTMLInputElement | null = null;665    const userField = fields.find((f) => f.type === "username" || f.type === "email");666    if (userField) usernameEl = userField.el;667    const pwField = fields.find((f) => f.type === "password");668    if (!pwField) return;669    const passwordEl = pwField.el;670671    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);672  } finally {673    pendingInteractions.delete(field);674  }675}676677async function onFocusIn(e: Event): Promise<void> {678  // Submit-button focus: catch the brief refocus some sites do when the679  // user clicks the login/submit button. Without this guard, that focus680  // event reaches handleFieldInteraction → getDeepActiveInput, and on681  // pages where the button is also a labelled <input> we briefly attempt682  // to open the popup over the very button the user just clicked.683  if (isSubmitButton(e.target)) return;684  await handleFieldInteraction();685}686687function reattachListeners(688  el: HTMLInputElement,689  detectedType?: "password" | "username" | "email",690  contextFields?: ReturnType<typeof detectLoginFields>691): void {692  if (processedInputs.has(el)) return;693  if (!resolveAutofillFieldType(el, detectedType)) return;694  // Only inject icon when a real login/signup form is present on the page695  const fields = contextFields ?? detectLoginFields();696  if (!isLoginForm(fields) && !isSignupForm(fields)) return;697698  const cleanup = injectFieldIcon(el, () => {699    currentDismiss?.();700    currentDismiss = null;701    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock702    dismissLock = false; // ...and the global lock703    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }704    clearFillStateForExplicitSummon(el);705    el.focus({ preventScroll: true });706    void handleFieldInteraction(el);707  });708  processedInputs.set(el, cleanup);709}710711const debouncedReattach = debounce(() => {712  const allFields = detectLoginFields();713  // Don't inject anything if there's no real login/signup form on this page714  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;715  const newFields = allFields.filter(716    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)717  );718  for (const f of newFields) {719    reattachListeners(f.el, f.type, allFields);720  }721  // 200ms debounce — below this, Peach and the host page's reactive layer722  // fight over the same layout properties every frame on React/Vue/Angular723  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.724}, 200);725726function setupMutationObserver(): void {727  const observer = new MutationObserver(debouncedReattach);728  observer.observe(document.body, {729    childList: true,730    subtree: true,731    attributes: true,732    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],733  });734}735736function initialScan(aggressionLevel = 0, isFinalPass = false) {737  const allFields = detectLoginFields();738  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);739740  if (aggressionLevel === 0 && !hasKnownForm) return;741742  const newFields = allFields.filter(743    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)744  );745746  for (const f of newFields) {747    reattachListeners(f.el, f.type, allFields);748  }749750  // Level 2, final pass: inject icon on any visible password field even if751  // the form-context gate in reattachListeners would normally skip it.752  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {753    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');754    for (const el of pwInputs) {755      if (isVisible(el) && !processedInputs.has(el)) {756        const cleanup = injectFieldIcon(el, () => {757          currentDismiss?.();758          currentDismiss = null;759          lastDismissedField = null;760          dismissLock = false;761          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }762          clearFillStateForExplicitSummon(el);763          el.focus({ preventScroll: true });764          void handleFieldInteraction(el);765        });766        processedInputs.set(el, cleanup);767      }768    }769  }770}771772// ── TOTP-only fields ───────────────────────────────────────────────────────773// After a username/password submission, many sites swap the whole form for a774// lone "verification code" input. The credential selector intentionally gates775// on login/signup forms, so TOTP fields need a narrow path of their own.776const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();777778function hasLoginOrSignupForm(): boolean {779  const fields = detectLoginFields();780  return isLoginForm(fields) || isSignupForm(fields);781}782783function injectTOTPFieldIcon(field: HTMLInputElement): void {784  if (processedTOTPInputs.has(field)) return;785  const cleanup = injectFieldIcon(field, () => {786    currentDismiss?.();787    currentDismiss = null;788    currentAnchorField = null;789    lastDismissedField = null;790    dismissLock = false;791    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }792    clearFillStateForExplicitSummon(field);793    field.focus({ preventScroll: true });794    void openTOTPSelector(field);795  });796  processedTOTPInputs.set(field, cleanup);797}798799function scanTOTPFields(): void {800  if (hasLoginOrSignupForm()) return;801  const inputs = document.querySelectorAll<HTMLInputElement>("input");802  for (const input of inputs) {803    if (!isTOTPField(input)) continue;804    injectTOTPFieldIcon(input);805  }806}807808function setupTOTPAutofill(): void {809  setTimeout(scanTOTPFields, 0);810  setTimeout(scanTOTPFields, 500);811  setTimeout(scanTOTPFields, 1500);812813  const debouncedScan = debounce(scanTOTPFields, 200);814  new MutationObserver(debouncedScan).observe(document.body, {815    childList: true,816    subtree: true,817    attributes: true,818    attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],819  });820821  document.addEventListener("focusin", (e) => {822    const target = e.target;823    if (!(target instanceof HTMLInputElement)) return;824    if (hasLoginOrSignupForm()) return;825    if (!isTOTPField(target)) return;826    injectTOTPFieldIcon(target);827  }, true);828}829830document.addEventListener("focusin", onFocusIn);831832setupMutationObserver();833setupTOTPAutofill();834setupSaveDetection();835setupCardAutofill();836837// SPA navigation reset: the content script does not reload across in-app838// route changes (history.pushState, hash navigation, framework routers).839// When the URL changes we clear the page-level fill timestamp so the next840// page works normally; filledForms (a WeakSet) self-empties as old form841// elements leave the DOM. subtree:false because route swaps reliably842// mutate document.body's direct children — subtree:true would fire on843// every internal DOM update and cost us a re-check per mutation.844let lastObservedUrl = location.href;845new MutationObserver(() => {846  if (location.href !== lastObservedUrl) {847    lastObservedUrl = location.href;848    pageFilledAt = null;849  }850}).observe(document.body, { childList: true, subtree: false });851852// Async init: check recall map before running the initial scans so we can853// apply the right aggression level for domains the user has needed before.854(async () => {855  let aggressionLevel = 0;856  try {857    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });858    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;859    const domain = getPageDomain();860    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;861    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;862  } catch { /* SW may be starting up; proceed with normal scan */ }863864  setTimeout(() => initialScan(aggressionLevel, false), 0);865  setTimeout(() => initialScan(aggressionLevel, false), 500);866  setTimeout(() => initialScan(aggressionLevel, true), 1500);867})();868869// ── Card autofill (State 7) ─────────────────────────────────────────870// Card forms get a parallel injection path. The login icon-injection gate871// in reattachListeners deliberately skips non-text fields, so we wire872// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping873// card detection contained makes the boundary easy to follow.874const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();875let currentCardDismiss: (() => void) | null = null;876let currentCardAnchor: HTMLInputElement | null = null;877let lastDismissedCardField: HTMLInputElement | null = null;878879async function fetchSavedCards(): Promise<CardSelectorEntry[]> {880  const resp = await chrome.runtime.sendMessage({881    type: "AUTOFILL_QUERY",882    payload: { domain: getPageDomain(), kind: "card" },883  }).catch(() => null);884  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;885  return r?.ok ? (r.data ?? []) : [];886}887888async function openCardSelector(anchor: HTMLInputElement): Promise<void> {889  if (!canOpen()) return;890  if (currentCardDismiss && currentCardAnchor === anchor) return;891  if (anchor === lastDismissedCardField) return;892  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;893  if (wasAlreadyFilled(anchor)) return;894895  const cards = await fetchSavedCards();896  if (cards.length === 0) return; // no saved cards → nothing to offer897898  const cardForm = detectCardForm();899  if (!cardForm?.number) return;900901  currentCardDismiss?.();902  currentCardAnchor = anchor;903  currentCardDismiss = showCardSelector(904    anchor,905    cards,906    {907      domain: getPageDomain(),908      onFill: (entry) => {909        if (!cardForm) return;910        fillCardForm(cardForm, {911          cardNumber: entry.cardNumber ?? "",912          expMonth: entry.expMonth ?? "",913          expYear: entry.expYear ?? "",914          cvc: entry.cvc ?? "",915          cardholderName: entry.cardholderName ?? "",916        });917        // All four card field types share the same form — recording the918        // number field's form is sufficient to suppress reopens on any of919        // them via wasAlreadyFilled().920        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);921        currentCardDismiss = null;922        currentCardAnchor = null;923      },924      onDismiss: () => {925        lastDismissedCardField = anchor;926        startDismissLock();927        currentCardDismiss = null;928        currentCardAnchor = null;929      },930    }931  );932}933934function injectCardIcon(field: HTMLInputElement): void {935  if (processedCardInputs.has(field)) return;936  const cleanup = injectFieldIcon(field, () => {937    currentCardDismiss?.();938    currentCardDismiss = null;939    lastDismissedCardField = null;940    dismissLock = false;941    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }942    clearFillStateForExplicitSummon(field);943    field.focus({ preventScroll: true });944    void openCardSelector(field);945  });946  processedCardInputs.set(field, cleanup);947}948949function setupCardAutofill(): void {950  function scan() {951    const cardForm = detectCardForm();952    if (!cardForm?.number) return;953    if (!isVisible(cardForm.number)) return;954    injectCardIcon(cardForm.number);955  }956957  // Initial detection sweep — same retry cadence as login fields so958  // late-hydrating SPA checkout pages get caught.959  setTimeout(scan, 0);960  setTimeout(scan, 500);961  setTimeout(scan, 1500);962963  // Re-scan on DOM mutation (separate from the login MutationObserver964  // because card forms typically appear on a single navigation event,965  // not field-by-field — coarser observation is sufficient here).966  let pending = false;967  new MutationObserver(() => {968    if (pending) return;969    pending = true;970    setTimeout(() => { pending = false; scan(); }, 200);971  }).observe(document.body, { childList: true, subtree: true });972973  // Field-focus path: on focus of a cc-number input, ensure icon is974  // present and consider opening the selector when the user explicitly975  // clicks into the card number field.976  document.addEventListener("focusin", (e) => {977    const target = e.target;978    if (!(target instanceof HTMLInputElement)) return;979    const cardForm = detectCardForm();980    if (cardForm?.number === target) {981      injectCardIcon(target);982    }983  }, true);984}985986chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {987  // Ignore anything not originating from our own background/service worker.988  if (sender.id !== chrome.runtime.id) return;989  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {990    const policy = detectPasswordPolicy();991    sendResponse({ ok: true, data: policy });992    return true;993  }994  if (msg?.type === "PING") {995    sendResponse({ ok: true });996    return true;997  }998  if (msg?.type === "SUMMON_AUTOFILL") {999    const source = (msg as { type: string; source?: string }).source;1000    const isShortcut = source === "shortcut";1001    const isPasskeyUnlock = source === "passkey-unlock";10021003    const activeInput = getDeepActiveInput();1004    const fields = detectLoginFields();1005    const hasForm = isLoginForm(fields) || isSignupForm(fields);10061007    if (hasForm) {1008      // Prefer the currently focused field if it's a login field, otherwise1009      // fall back to the first password field, then username/email.1010      const inForm = activeInput && fields.some(f => f.el === activeInput);1011      const target = inForm1012        ? activeInput1013        : (fields.find(f => f.type === "password")?.el1014            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1015      if (target) {1016        // Explicit user summon (shortcut or extension button) — bypass all1017        // suppression layers. The user is asking for the popup right now.1018        clearFillStateForExplicitSummon(target);1019        dismissLock = false;1020        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1021        lastDismissedField = null;1022        void handleFieldInteraction(target);1023      }1024    } else if (isPasskeyUnlock) {1025      // Vault is locked during a passkey GET request. Show the inline unlock1026      // prompt anchored to whatever element is focused on the page (typically1027      // the passkey/sign-in button the user just tapped).1028      const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1029        ? document.activeElement as unknown as HTMLInputElement1030        : null;1031      if (anchor) {1032        currentDismiss?.();1033        currentAnchorField = null;1034        passkeySummonActive = true;1035        currentDismiss = showAutofillSelector(anchor, [], () => {}, {1036          domain: getPageDomain(),1037          locked: true,1038          onDismiss: () => { passkeySummonActive = false; },1039        });1040      }1041    } else if (isShortcut) {1042      // Shortcut on a page with no login form — show clipboard-copy search mode.1043      showSearchPalette();1044    }10451046    // Record this domain for the recall system when triggered via shortcut.1047    if (isShortcut) {1048      const domain = getPageDomain();1049      if (domain) {1050        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1051      }1052    }10531054    sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1055    return true;1056  }1057  if (msg?.type === "PASSKEY_PRO_GATE") {1058    // Background rejected a passkey request for a free user. Show State 111059    // so they know what happened and can choose to upgrade.1060    showPasskeyProGate();1061    sendResponse({ ok: true });1062    return true;1063  }1064  if (msg?.type === "SHOW_PASSKEY_TOAST") {1065    // Block autofill selector for the lifetime of the toast and dismiss anything open.1066    passkeyToastActive = true;1067    if (currentDismiss) {1068      currentDismiss();1069      currentDismiss = null;1070      currentAnchorField = null;1071    }1072    return false; // inject.tsx owns the toast and calls sendResponse1073  }1074  if (msg?.type === "DISMISS_PASSKEY_TOAST") {1075    passkeyToastActive = false;1076    return false; // inject.tsx handles the actual dismissal1077  }1078  if (msg?.type === "VAULT_UNLOCKED") {1079    if (passkeySummonActive) {1080      // This unlock was for a pending passkey GET request. Just dismiss the1081      // inline popup — the passkey approval toast takes over from here.1082      passkeySummonActive = false;1083      if (currentDismiss) {1084        currentDismiss();1085        currentDismiss = null;1086        currentAnchorField = null;1087      }1088      sendResponse({ ok: true });1089      return true;1090    }1091    // Normal autofill path: close the locked-state prompt and re-open with1092    // fresh entry data at the same anchor field.1093    const savedField = currentAnchorField;1094    if (currentDismiss) {1095      currentDismiss();1096      currentDismiss = null;1097      currentAnchorField = null;1098    }1099    void handleFieldInteraction(savedField ?? undefined);1100    sendResponse({ ok: true });1101    return true;1102  }1103  return true;1104});11051106// inject.tsx posts this when the passkey toast closes (approve, deny, or timeout)1107// so we know it's safe to allow autofill again.1108window.addEventListener("message", (e: MessageEvent) => {1109  // Reject postMessages from cross-frame senders — only the same window's1110  // injected toast may flip this flag.1111  if (e.source !== window) return;1112  const d = e.data as { source?: string; type?: string } | undefined;1113  if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1114    passkeyToastActive = false;1115  }1116});11171118// ── Firefox passkey detection bridge (legacy observer path) ─────────────1119//1120// Pre-v2.12.0 the MAIN-world `passkeys-firefox.ts` was an observer — it1121// emitted `peach-passkey-firefox` postMessages so this content script could1122// surface State 12 (an inline "Save passkey to Peach" offer). v2.12.01123// replaced the observer with a full interception proxy (the page never1124// reaches a real navigator.credentials.create on Firefox anymore), and the1125// approval UI is opened by the background as part of the ceremony itself.1126// When the proxy is active the offer would be redundant noise, so the1127// listener gates on the flag. Once the proxy is removed (Firefox ships1128// webAuthenticationProxy) this whole block goes too.1129if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1130  let lastPasskeyOfferAt = 0;1131  const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11321133  window.addEventListener("message", (event: MessageEvent) => {1134    if (event.source !== window) return;1135    const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1136    if (!data || data.source !== "peach-passkey-firefox") return;1137    if (detectBrowser() !== "firefox") return;1138    if (data.type !== "create") return;11391140    // Cooldown: a single page interaction can fire multiple credentials.create1141    // calls. Show the offer at most once per 30 seconds per page session.1142    const now = Date.now();1143    if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1144    lastPasskeyOfferAt = now;11451146    const domain = location.hostname.replace(/^www\./, "");1147    chrome.runtime.sendMessage({1148      type: "GET_PASSKEY_OFFER_DECLINED",1149      payload: { domain },1150    }).then((res: { ok: boolean; data?: boolean } | undefined) => {1151      if (res?.data === true) return;1152      const rpId = data.rpId ?? domain;1153      showPasskeyRegistrationOffer({1154        rpId,1155        rpName: data.rpName,1156        userName: data.userName,1157        userDisplayName: data.userDisplayName,1158      });1159    }).catch(() => {});1160  });1161}11621163// Surface State 11 (passkey-available) only when it adds value:1164//   - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither1165//     browser will auto-route, so the banner explains the re-register need.1166//   - Firefox + same-browser entry: Firefox has no equivalent of1167//     webAuthenticationProxy, so without a banner the user has no signal that1168//     Peach is the source.1169// On Chrome with a same-browser entry: skip — webAuthenticationProxy handles1170// the page's own credentials.get transparently and the popup approval view1171// already surfaces it. A banner here would just be noise.1172//1173// Dedupe across navigation: each navigation re-injects this content script.1174// chrome.storage.session keyed by domain is the natural per-tab/per-session1175// memory; session storage clears when the user closes the browser.1176{1177  function checkPasskeyAvailability() {1178    const domain = location.hostname.replace(/^www\./, "");1179    if (!domain) return;1180    const sessionKey = `peach_state11_shown:${domain}`;1181    chrome.storage.session?.get(sessionKey).then((stored) => {1182      if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1183      chrome.runtime.sendMessage({1184        type: "GET_PASSKEY_FOR_DOMAIN",1185        payload: { domain },1186      }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1187        const data = res?.data;1188        if (!data) return;1189        const current = detectBrowser();1190        const isCrossBrowser =1191          data.browser && current !== "unknown" && data.browser !== current;1192        const valuableOnFirefox = current === "firefox";1193        if (!isCrossBrowser && !valuableOnFirefox) return;1194        chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1195        showPasskeyAvailable({1196          rpId: data.rpId,1197          userName: data.userName,1198          fromBrowser: data.browser,1199          currentBrowser: current,1200        });1201      }).catch(() => {});1202    }).catch(() => {});1203  }12041205  // Defer until DOM is interactive — content_scripts run at document_idle but1206  // some pages still mutate visibly afterwards. A short delay also avoids1207  // surfacing the State 11 toast while the user is in the middle of typing.1208  if (document.readyState === "loading") {1209    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1210  } else {1211    setTimeout(checkPasskeyAvailability, 800);1212  }1213}