index.ts

41.2 KB · raw

1import {2  detectCardForm,3  detectLoginFields,4  getDeepActiveInput,5  getPageDomain,6  isLoginForm,7  isSignupForm,8  isVisible,9} from "./detect";10import {11  CardSelectorEntry,12  injectFieldIcon,13  SelectorEntry,14  showAutofillSelector,15  showCardSelector,16  showPasskeyAvailable,17  showPasskeyProGate,18  showPasskeyRegistrationOffer,19  showRememberSiteToast,20} from "./inject";21import { detectBrowser } from "../shared/browser";22import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";23import { fillCardForm, fillFields, setNativeValue } from "./fill";24import { setupSaveDetection } from "./save";25import { contentMLDetector } from "./content-ml-detector";26import { detectPasswordPolicy } from "./policy";27import type { FieldPrediction } from "../shared/ml";28import { generateTOTP } from "../crypto/totp";29import type { SavedIdentity, VaultEntry } from "../shared/types";3031// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value32// so we can tear down listeners if we ever need to re-process the same field.33// When the input is GC'd (SPA nav, React re-render), the map entry goes with34// it and we can re-inject without leaking the old handler.35const processedInputs = new WeakMap<HTMLInputElement, () => void>();36const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3738let currentDismiss: (() => void) | null = null;39// Field whose selector is currently open — used to avoid dismiss+reopen flicker40let currentAnchorField: HTMLInputElement | null = null;41// Prevents two concurrent handleFieldInteraction calls for the same field42const pendingInteractions = new WeakSet<HTMLInputElement>();43// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).44// Suppresses spurious reopens until focus moves to a different field. Layer 145// of the dismissal model — see Projects.md §4.12.46let lastDismissedField: HTMLInputElement | null = null;4748// ── Dismissal lock (Layer 2) ────────────────────────────────────────49// After any user-initiated dismiss, briefly block ALL reopens regardless of50// which field is focused. Catches the case where a page rapidly moves focus51// between fields after Escape — without this, focus moving to a SECOND field52// in <100ms would re-trigger the popup before the user finished dismissing.53const DISMISS_LOCK_MS = 800;54let dismissLock = false;55let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;56// Set when the inline popup was summoned specifically for a passkey-unlock57// flow. The VAULT_UNLOCKED handler checks this to skip re-triggering autofill58// (the passkey toast handles the next step instead).59let passkeySummonActive = false;60// Set while the passkey approval toast is visible. Prevents handleFieldInteraction61// from opening the autofill selector alongside it. Cleared by a window message62// posted by inject.tsx when the toast closes (and by DISMISS_PASSKEY_TOAST).63let passkeyToastActive = false;64function startDismissLock(): void {65  dismissLock = true;66  if (dismissLockTimer) clearTimeout(dismissLockTimer);67  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);68}69function canOpen(): boolean { return !dismissLock; }7071// ── Fill-success lock ───────────────────────────────────────────────72// After Peach autofills a form, the popup must NOT reappear on the filled73// fields, on the submit button (some sites refocus it briefly), or on any74// field in that form — even when host-page DOM mutations or the form's own75// validation flow refocus an input. Implemented as a WeakSet of forms plus76// a page-level timestamp:77//   - filledForms: every form Peach has filled this page session. Survives78//     until the form leaves the DOM (WeakSet GC).79//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders80//     window for fields that aren't inside a <form> element (some SPAs).81// SPA navigation resets pageFilledAt via the urlObserver below; filledForms82// self-empties as old form elements get GC'd.83const filledForms = new WeakSet<HTMLFormElement>();84let pageFilledAt: number | null = null;85const PAGE_FILL_GRACE_MS = 3000;8687function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {88  for (const f of fields) {89    if (!f) continue;90    const form = f.closest("form");91    if (form) filledForms.add(form);92  }93  pageFilledAt = Date.now();94}9596function wasAlreadyFilled(field: HTMLInputElement): boolean {97  const form = field.closest("form");98  if (form && filledForms.has(form)) return true;99  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;100  return false;101}102103function clearFillStateForExplicitSummon(field: HTMLInputElement): void {104  const form = field.closest("form");105  if (form) filledForms.delete(form);106  pageFilledAt = null;107}108109// Some sites briefly focus the submit button when the user clicks it (visual110// feedback, blur/focus dance for validation animations). Catch those at the111// focusin layer so we don't re-trigger handleFieldInteraction for an event112// target that was never going to be a credential field anyway.113function isSubmitButton(el: EventTarget | null): boolean {114  if (!(el instanceof HTMLElement)) return false;115  if (el instanceof HTMLButtonElement && el.type !== "button") return true;116  if (el instanceof HTMLInputElement && el.type === "submit") return true;117  if (el.getAttribute("type") === "submit") return true;118  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();119  if (!text || text.length > 24) return false;120  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);121}122123function debounce<T extends (...args: unknown[]) => void>(124  fn: T,125  ms: number126): (...args: Parameters<T>) => void {127  let timer: ReturnType<typeof setTimeout>;128  return (...args: Parameters<T>) => {129    clearTimeout(timer);130    timer = setTimeout(() => fn(...args), ms);131  };132}133134function showToast(message: string): void {135  const toast = document.createElement("div");136  toast.style.cssText = `137    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);138    background: #131109; color: #F0E8D8; padding: 8px 16px;139    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;140    font-size: 11px; z-index: 2147483647; opacity: 0;141    transition: opacity 200ms ease;142    border: 1px solid rgba(240,232,216,0.07);143    pointer-events: none;144  `;145  toast.textContent = message;146  document.body.appendChild(toast);147  requestAnimationFrame(() => { toast.style.opacity = "1"; });148  setTimeout(() => {149    toast.style.opacity = "0";150    setTimeout(() => toast.remove(), 200);151  }, 2000);152}153154function showSearchPalette(): void {155  const host = document.createElement("div");156  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";157  document.body.appendChild(host);158  const shadow = host.attachShadow({ mode: "closed" });159160  const style = document.createElement("style");161  style.textContent = `162    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;163      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;164      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}165    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);166      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}167    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}168    .s{padding:8px 12px}169    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);170      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;171      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}172    .l{max-height:220px;overflow-y:auto}173    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}174    .e:hover{background:rgba(240,232,216,.06)}175    .et{font-size:12px}176    .eu{font-size:10px;color:rgba(240,232,216,.45)}177    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}178  `;179180  let allEntries: SelectorEntry[] = [];181  let query = "";182183  const panel = document.createElement("div");184  panel.className = "p";185186  const hdr = document.createElement("div");187  hdr.className = "h";188  const hdrText = document.createElement("span");189  hdrText.textContent = "No form detected — search your vault";190  const closeBtn = document.createElement("button");191  closeBtn.className = "x";192  closeBtn.textContent = "✕";193  hdr.appendChild(hdrText);194  hdr.appendChild(closeBtn);195196  const searchWrap = document.createElement("div");197  searchWrap.className = "s";198  const searchInput = document.createElement("input");199  searchInput.placeholder = "search...";200  searchWrap.appendChild(searchInput);201202  const list = document.createElement("div");203  list.className = "l";204205  panel.appendChild(hdr);206  panel.appendChild(searchWrap);207  panel.appendChild(list);208  shadow.appendChild(style);209  shadow.appendChild(panel);210211  function close() { host.remove(); }212213  closeBtn.onclick = close;214215  function onKeyDown(e: KeyboardEvent) {216    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }217  }218  document.addEventListener("keydown", onKeyDown, true);219220  function render() {221    const q = query.toLowerCase();222    const filtered = q223      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))224      : allEntries;225    list.innerHTML = "";226    if (filtered.length === 0) {227      const em = document.createElement("div");228      em.className = "em";229      em.textContent = query ? "no matches" : "vault is empty";230      list.appendChild(em);231      return;232    }233    for (const entry of filtered.slice(0, 20)) {234      const row = document.createElement("div");235      row.className = "e";236      const title = document.createElement("div");237      title.className = "et";238      title.textContent = entry.title;239      row.appendChild(title);240      if (entry.username) {241        const user = document.createElement("div");242        user.className = "eu";243        user.textContent = entry.username;244        row.appendChild(user);245      }246      row.onclick = async () => {247        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });248        const r = resp as { ok: boolean; data?: { password?: string } };249        if (r.ok && r.data?.password) {250          let alreadyWritten = false;251          try {252            await navigator.clipboard.writeText(r.data.password);253            alreadyWritten = true;254          } catch (err) {255            console.warn("[Peach] clipboard write denied:", err);256          }257          const copyResp = await chrome.runtime.sendMessage({258            type: "COPY",259            payload: { text: r.data.password, label: "Password", alreadyWritten },260          }) as { ok?: boolean } | undefined;261          if (alreadyWritten || copyResp?.ok) {262            showToast("Password copied");263          } else {264            showToast("Could not copy password — clipboard blocked");265          }266        } else {267          showToast("Could not copy password");268        }269        close();270        document.removeEventListener("keydown", onKeyDown, true);271      };272      list.appendChild(row);273    }274  }275276  searchInput.oninput = () => { query = searchInput.value; render(); };277278  fetchAutofillEntries(getPageDomain(), true).then(result => {279    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }280    allEntries = result.entries;281    render();282    searchInput.focus();283  });284}285286function findTOTPField(): HTMLInputElement | null {287  const inputs = document.querySelectorAll<HTMLInputElement>("input");288  for (const input of inputs) {289    if (!isVisible(input)) continue;290    const autocomplete = input.autocomplete.toLowerCase();291    const nameId = (input.name + input.id).toLowerCase();292    const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();293    if (294      autocomplete === "one-time-code" ||295      /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)296    ) {297      return input;298    }299    const labelEl = input.closest("label");300    if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {301      return input;302    }303  }304  return null;305}306307async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {308  await new Promise((r) => setTimeout(r, 400));309  if (totpField.value === "" || totpField.value.trim() === "") {310    const { code } = generateTOTP(totpSecret);311    setNativeValue(totpField, code);312    showToast("TOTP autofilled");313  }314}315316317async function handleAutofill(318  _field: HTMLInputElement,319  usernameEl: HTMLInputElement | null,320  passwordEl: HTMLInputElement,321  entry: VaultEntry322): Promise<void> {323  if (!entry.username && !entry.password) return;324  const pageDomain = getPageDomain();325  const form = passwordEl.closest("form") as HTMLFormElement | null;326  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);327328  if (entry.canary) {329    chrome.runtime.sendMessage({330      type: "FIRE_CANARY_PING",331      payload: {332        webhookUrl: entry.canary.webhookUrl,333        entryTitle: entry.title,334        trigger: "autofilled",335      },336    }).catch(() => {});337    chrome.runtime.sendMessage({338      type: "UPDATE_ENTRY",339      payload: {340        id: entry.id,341        patch: {342          canary: {343            ...entry.canary,344            lastPinged: Date.now(),345            pingCount: (entry.canary.pingCount ?? 0) + 1,346          },347        },348      },349    }).catch(() => {});350  }351352  if (entry.totp) {353    const { code } = generateTOTP(entry.totp);354    let alreadyWritten = false;355    try {356      await navigator.clipboard.writeText(code);357      alreadyWritten = true;358    } catch (err) {359      console.warn("[Peach] clipboard write denied:", err);360    }361    const response = await chrome.runtime.sendMessage({362      type: "COPY",363      payload: { text: code, label: "TOTP", alreadyWritten },364    });365    if (alreadyWritten || (response as { ok?: boolean }).ok) {366      showToast("TOTP copied · " + code);367    } else {368      showToast("Could not copy TOTP — clipboard blocked");369    }370    const totpField = findTOTPField();371    if (totpField) {372      autofillTOTP(totpField, entry.totp);373    }374  }375}376377async function fetchAutofillEntries(378  domain: string,379  includeAll = false380): Promise<{ entries: SelectorEntry[]; locked: boolean }> {381  const response = await chrome.runtime.sendMessage({382    type: "AUTOFILL_QUERY",383    payload: { domain, includeAll },384  });385  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };386  if (!res.ok && res.error === "VAULT_LOCKED") {387    return { entries: [], locked: true };388  }389  return { entries: res.data ?? [], locked: false };390}391392393function resolveAutofillFieldType(394  el: HTMLInputElement,395  predictedType?: FieldPrediction["type"] | null396): "password" | "username" | "email" | null {397  if (398    predictedType === "password" ||399    predictedType === "username" ||400    predictedType === "email"401  ) {402    return predictedType;403  }404405  const detected = detectLoginFields().find((field) => field.el === el)?.type;406  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {407    return detected;408  }409410  const htmlType = el.type.toLowerCase();411  if (htmlType === "password") return "password";412  if (htmlType === "email") return "email";413  return null;414}415416async function openAutofillSelector(417  anchorField: HTMLInputElement,418  usernameEl: HTMLInputElement | null,419  passwordEl: HTMLInputElement,420  domainEntries: SelectorEntry[],421  searchableEntries: SelectorEntry[],422  domain: string423): Promise<void> {424  // No saved entries for this site → signup/new-account mode.425  // Fetch vault identities for the identity-first surface and locate426  // the confirm-password field so "Copy & fill" can populate it too.427  const isSignup = domainEntries.length === 0;428  let savedIdentities: SavedIdentity[] | undefined;429  let confirmEl: HTMLInputElement | null = null;430  if (isSignup) {431    try {432      const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as433        { ok: boolean; data?: SavedIdentity[] } | null;434      if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;435    } catch { /* silent fallback */ }436437    const form = passwordEl.closest("form") ?? document.body;438    const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));439    confirmEl = allPwInputs.find(440      (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)441    ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);442  }443444  currentDismiss?.();445  currentAnchorField = anchorField;446  currentDismiss = showAutofillSelector(447    anchorField,448    domainEntries,449    async (id: string) => {450      currentDismiss = null;451      currentAnchorField = null;452      const entryResponse = await chrome.runtime.sendMessage({453        type: "GET_ENTRY_FOR_FILL",454        payload: { id },455      });456      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;457      if (entry) {458        await handleAutofill(anchorField, usernameEl, passwordEl, entry);459        recordFillSuccess(anchorField, usernameEl, passwordEl);460        // Offer to remember the current site for this entry only if none of461        // its known domains (primary + additional) match — otherwise the462        // user already mapped it and the prompt would be noise.463        const pageDomain = location.hostname.replace(/^www\./, "");464        const entryDomains = new Set<string>();465        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {466          try {467            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));468          } catch { /* ignore unparseable */ }469        }470        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {471          showRememberSiteToast(pageDomain, entry.id);472        }473      }474    },475    {476      domain,477      searchableEntries,478      isSignup,479      savedIdentities,480      onFillFields: (username, password) => {481        const form = passwordEl.closest("form") as HTMLFormElement | null;482        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());483        if (password && confirmEl) setNativeValue(confirmEl, password);484        recordFillSuccess(anchorField, usernameEl, passwordEl);485      },486      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },487    }488  );489}490491492async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {493  const field = anchorField ?? getDeepActiveInput();494  if (!field) return;495  if (!isVisible(field)) return;496497  // Passkey toast is visible — don't open the credential selector alongside it.498  if (passkeyToastActive) return;499500  // Layer 2: post-dismiss global lock. Catches rapid focus moves between501  // fields immediately after Escape/click-outside.502  if (!canOpen()) return;503504  // If a selector is already open for this exact field, don't flicker it.505  if (currentDismiss && currentAnchorField === field) return;506507  // If focus moved to a different field, the previous per-field dismiss lock508  // no longer applies.509  if (field !== lastDismissedField) lastDismissedField = null;510  // Layer 1: the user explicitly dismissed this field's selector — don't511  // reopen it until focus has genuinely moved away and come back.512  if (field === lastDismissedField) return;513514  // Fill-success lock: Peach already filled this form (or fired a fill515  // anywhere on the page within the grace window). Sites often refocus an516  // input on submit click, on validation, or on a transition to a success517  // state — none of those should re-open the popup.518  if (wasAlreadyFilled(field)) return;519520  // Prevent two concurrent calls for the same field (e.g. focusin + icon click521  // firing simultaneously — the second call would dismiss the first's selector).522  if (pendingInteractions.has(field)) return;523  pendingInteractions.add(field);524525  try {526    const fieldType = field.type.toLowerCase();527528    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {529      return preds[0] ?? null;530    });531532    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {533      const timeout = setTimeout(() => resolve(null), 150);534      mlPromise.then((pred) => {535        clearTimeout(timeout);536        resolve(pred);537      });538    });539540    if (passkeyToastActive) return;541542    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {543      return;544    }545546    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);547    if (autofillFieldType) {548      reattachListeners(field, autofillFieldType);549    }550551    let fields = detectLoginFields();552    const loginForm = isLoginForm(fields);553    const signupForm = isSignupForm(fields);554    if (!loginForm && !signupForm) {555      return;556    }557558    const domain = getPageDomain();559    const firstResult = await fetchAutofillEntries(domain);560    if (passkeyToastActive) return;561562    // Vault is locked — show an inline unlock prompt.563    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so564    // there is no double-trigger race between onUnlocked and the broadcast.565    if (firstResult.locked) {566      currentDismiss?.();567      currentAnchorField = field;568      currentDismiss = showAutofillSelector(569        field,570        [],571        () => {},572        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }573      );574      return;575    }576577    const entries = firstResult.entries;578    const allEntries = entries.length === 0579      ? (await fetchAutofillEntries(domain, true)).entries580      : entries;581582    if (passkeyToastActive) return;583584    let usernameEl: HTMLInputElement | null = null;585    const userField = fields.find((f) => f.type === "username" || f.type === "email");586    if (userField) usernameEl = userField.el;587    const pwField = fields.find((f) => f.type === "password");588    if (!pwField) return;589    const passwordEl = pwField.el;590591    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);592  } finally {593    pendingInteractions.delete(field);594  }595}596597async function onFocusIn(e: Event): Promise<void> {598  // Submit-button focus: catch the brief refocus some sites do when the599  // user clicks the login/submit button. Without this guard, that focus600  // event reaches handleFieldInteraction → getDeepActiveInput, and on601  // pages where the button is also a labelled <input> we briefly attempt602  // to open the popup over the very button the user just clicked.603  if (isSubmitButton(e.target)) return;604  await handleFieldInteraction();605}606607function reattachListeners(608  el: HTMLInputElement,609  detectedType?: "password" | "username" | "email",610  contextFields?: ReturnType<typeof detectLoginFields>611): void {612  if (processedInputs.has(el)) return;613  if (!resolveAutofillFieldType(el, detectedType)) return;614  // Only inject icon when a real login/signup form is present on the page615  const fields = contextFields ?? detectLoginFields();616  if (!isLoginForm(fields) && !isSignupForm(fields)) return;617618  const cleanup = injectFieldIcon(el, () => {619    currentDismiss?.();620    currentDismiss = null;621    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock622    dismissLock = false; // ...and the global lock623    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }624    clearFillStateForExplicitSummon(el);625    el.focus({ preventScroll: true });626    void handleFieldInteraction(el);627  });628  processedInputs.set(el, cleanup);629}630631const debouncedReattach = debounce(() => {632  const allFields = detectLoginFields();633  // Don't inject anything if there's no real login/signup form on this page634  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;635  const newFields = allFields.filter(636    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)637  );638  for (const f of newFields) {639    reattachListeners(f.el, f.type, allFields);640  }641  // 200ms debounce — below this, Peach and the host page's reactive layer642  // fight over the same layout properties every frame on React/Vue/Angular643  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.644}, 200);645646function setupMutationObserver(): void {647  const observer = new MutationObserver(debouncedReattach);648  observer.observe(document.body, {649    childList: true,650    subtree: true,651    attributes: true,652    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],653  });654}655656function initialScan(aggressionLevel = 0, isFinalPass = false) {657  const allFields = detectLoginFields();658  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);659660  if (aggressionLevel === 0 && !hasKnownForm) return;661662  const newFields = allFields.filter(663    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)664  );665666  for (const f of newFields) {667    reattachListeners(f.el, f.type, allFields);668  }669670  // Level 2, final pass: inject icon on any visible password field even if671  // the form-context gate in reattachListeners would normally skip it.672  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {673    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');674    for (const el of pwInputs) {675      if (isVisible(el) && !processedInputs.has(el)) {676        const cleanup = injectFieldIcon(el, () => {677          currentDismiss?.();678          currentDismiss = null;679          lastDismissedField = null;680          dismissLock = false;681          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }682          clearFillStateForExplicitSummon(el);683          el.focus({ preventScroll: true });684          void handleFieldInteraction(el);685        });686        processedInputs.set(el, cleanup);687      }688    }689  }690}691692document.addEventListener("focusin", onFocusIn);693694setupMutationObserver();695setupSaveDetection();696setupCardAutofill();697698// SPA navigation reset: the content script does not reload across in-app699// route changes (history.pushState, hash navigation, framework routers).700// When the URL changes we clear the page-level fill timestamp so the next701// page works normally; filledForms (a WeakSet) self-empties as old form702// elements leave the DOM. subtree:false because route swaps reliably703// mutate document.body's direct children — subtree:true would fire on704// every internal DOM update and cost us a re-check per mutation.705let lastObservedUrl = location.href;706new MutationObserver(() => {707  if (location.href !== lastObservedUrl) {708    lastObservedUrl = location.href;709    pageFilledAt = null;710  }711}).observe(document.body, { childList: true, subtree: false });712713// Async init: check recall map before running the initial scans so we can714// apply the right aggression level for domains the user has needed before.715(async () => {716  let aggressionLevel = 0;717  try {718    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });719    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;720    const domain = getPageDomain();721    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;722    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;723  } catch { /* SW may be starting up; proceed with normal scan */ }724725  setTimeout(() => initialScan(aggressionLevel, false), 0);726  setTimeout(() => initialScan(aggressionLevel, false), 500);727  setTimeout(() => initialScan(aggressionLevel, true), 1500);728})();729730// ── Card autofill (State 7) ─────────────────────────────────────────731// Card forms get a parallel injection path. The login icon-injection gate732// in reattachListeners deliberately skips non-text fields, so we wire733// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping734// card detection contained makes the boundary easy to follow.735const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();736let currentCardDismiss: (() => void) | null = null;737let currentCardAnchor: HTMLInputElement | null = null;738let lastDismissedCardField: HTMLInputElement | null = null;739740async function fetchSavedCards(): Promise<CardSelectorEntry[]> {741  const resp = await chrome.runtime.sendMessage({742    type: "AUTOFILL_QUERY",743    payload: { domain: getPageDomain(), kind: "card" },744  }).catch(() => null);745  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;746  return r?.ok ? (r.data ?? []) : [];747}748749async function openCardSelector(anchor: HTMLInputElement): Promise<void> {750  if (!canOpen()) return;751  if (currentCardDismiss && currentCardAnchor === anchor) return;752  if (anchor === lastDismissedCardField) return;753  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;754  if (wasAlreadyFilled(anchor)) return;755756  const cards = await fetchSavedCards();757  if (cards.length === 0) return; // no saved cards → nothing to offer758759  const cardForm = detectCardForm();760  if (!cardForm?.number) return;761762  currentCardDismiss?.();763  currentCardAnchor = anchor;764  currentCardDismiss = showCardSelector(765    anchor,766    cards,767    {768      domain: getPageDomain(),769      onFill: (entry) => {770        if (!cardForm) return;771        fillCardForm(cardForm, {772          cardNumber: entry.cardNumber ?? "",773          expMonth: entry.expMonth ?? "",774          expYear: entry.expYear ?? "",775          cvc: entry.cvc ?? "",776          cardholderName: entry.cardholderName ?? "",777        });778        // All four card field types share the same form — recording the779        // number field's form is sufficient to suppress reopens on any of780        // them via wasAlreadyFilled().781        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);782        currentCardDismiss = null;783        currentCardAnchor = null;784      },785      onDismiss: () => {786        lastDismissedCardField = anchor;787        startDismissLock();788        currentCardDismiss = null;789        currentCardAnchor = null;790      },791    }792  );793}794795function injectCardIcon(field: HTMLInputElement): void {796  if (processedCardInputs.has(field)) return;797  const cleanup = injectFieldIcon(field, () => {798    currentCardDismiss?.();799    currentCardDismiss = null;800    lastDismissedCardField = null;801    dismissLock = false;802    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }803    clearFillStateForExplicitSummon(field);804    field.focus({ preventScroll: true });805    void openCardSelector(field);806  });807  processedCardInputs.set(field, cleanup);808}809810function setupCardAutofill(): void {811  function scan() {812    const cardForm = detectCardForm();813    if (!cardForm?.number) return;814    if (!isVisible(cardForm.number)) return;815    injectCardIcon(cardForm.number);816  }817818  // Initial detection sweep — same retry cadence as login fields so819  // late-hydrating SPA checkout pages get caught.820  setTimeout(scan, 0);821  setTimeout(scan, 500);822  setTimeout(scan, 1500);823824  // Re-scan on DOM mutation (separate from the login MutationObserver825  // because card forms typically appear on a single navigation event,826  // not field-by-field — coarser observation is sufficient here).827  let pending = false;828  new MutationObserver(() => {829    if (pending) return;830    pending = true;831    setTimeout(() => { pending = false; scan(); }, 200);832  }).observe(document.body, { childList: true, subtree: true });833834  // Field-focus path: on focus of a cc-number input, ensure icon is835  // present and consider opening the selector when the user explicitly836  // clicks into the card number field.837  document.addEventListener("focusin", (e) => {838    const target = e.target;839    if (!(target instanceof HTMLInputElement)) return;840    const cardForm = detectCardForm();841    if (cardForm?.number === target) {842      injectCardIcon(target);843    }844  }, true);845}846847chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {848  // Ignore anything not originating from our own background/service worker.849  if (sender.id !== chrome.runtime.id) return;850  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {851    const policy = detectPasswordPolicy();852    sendResponse({ ok: true, data: policy });853    return true;854  }855  if (msg?.type === "PING") {856    sendResponse({ ok: true });857    return true;858  }859  if (msg?.type === "SUMMON_AUTOFILL") {860    const source = (msg as { type: string; source?: string }).source;861    const isShortcut = source === "shortcut";862    const isPasskeyUnlock = source === "passkey-unlock";863864    const activeInput = getDeepActiveInput();865    const fields = detectLoginFields();866    const hasForm = isLoginForm(fields) || isSignupForm(fields);867868    if (hasForm) {869      // Prefer the currently focused field if it's a login field, otherwise870      // fall back to the first password field, then username/email.871      const inForm = activeInput && fields.some(f => f.el === activeInput);872      const target = inForm873        ? activeInput874        : (fields.find(f => f.type === "password")?.el875            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);876      if (target) {877        // Explicit user summon (shortcut or extension button) — bypass all878        // suppression layers. The user is asking for the popup right now.879        clearFillStateForExplicitSummon(target);880        dismissLock = false;881        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }882        lastDismissedField = null;883        void handleFieldInteraction(target);884      }885    } else if (isPasskeyUnlock) {886      // Vault is locked during a passkey GET request. Show the inline unlock887      // prompt anchored to whatever element is focused on the page (typically888      // the passkey/sign-in button the user just tapped).889      const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)890        ? document.activeElement as unknown as HTMLInputElement891        : null;892      if (anchor) {893        currentDismiss?.();894        currentAnchorField = null;895        passkeySummonActive = true;896        currentDismiss = showAutofillSelector(anchor, [], () => {}, {897          domain: getPageDomain(),898          locked: true,899          onDismiss: () => { passkeySummonActive = false; },900        });901      }902    } else if (isShortcut) {903      // Shortcut on a page with no login form — show clipboard-copy search mode.904      showSearchPalette();905    }906907    // Record this domain for the recall system when triggered via shortcut.908    if (isShortcut) {909      const domain = getPageDomain();910      if (domain) {911        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});912      }913    }914915    sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });916    return true;917  }918  if (msg?.type === "PASSKEY_PRO_GATE") {919    // Background rejected a passkey request for a free user. Show State 11920    // so they know what happened and can choose to upgrade.921    showPasskeyProGate();922    sendResponse({ ok: true });923    return true;924  }925  if (msg?.type === "SHOW_PASSKEY_TOAST") {926    // Block autofill selector for the lifetime of the toast and dismiss anything open.927    passkeyToastActive = true;928    if (currentDismiss) {929      currentDismiss();930      currentDismiss = null;931      currentAnchorField = null;932    }933    return false; // inject.tsx owns the toast and calls sendResponse934  }935  if (msg?.type === "DISMISS_PASSKEY_TOAST") {936    passkeyToastActive = false;937    return false; // inject.tsx handles the actual dismissal938  }939  if (msg?.type === "VAULT_UNLOCKED") {940    if (passkeySummonActive) {941      // This unlock was for a pending passkey GET request. Just dismiss the942      // inline popup — the passkey approval toast takes over from here.943      passkeySummonActive = false;944      if (currentDismiss) {945        currentDismiss();946        currentDismiss = null;947        currentAnchorField = null;948      }949      sendResponse({ ok: true });950      return true;951    }952    // Normal autofill path: close the locked-state prompt and re-open with953    // fresh entry data at the same anchor field.954    const savedField = currentAnchorField;955    if (currentDismiss) {956      currentDismiss();957      currentDismiss = null;958      currentAnchorField = null;959    }960    void handleFieldInteraction(savedField ?? undefined);961    sendResponse({ ok: true });962    return true;963  }964  return true;965});966967// inject.tsx posts this when the passkey toast closes (approve, deny, or timeout)968// so we know it's safe to allow autofill again.969window.addEventListener("message", (e: MessageEvent) => {970  // Reject postMessages from cross-frame senders — only the same window's971  // injected toast may flip this flag.972  if (e.source !== window) return;973  const d = e.data as { source?: string; type?: string } | undefined;974  if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {975    passkeyToastActive = false;976  }977});978979// ── Firefox passkey detection bridge (legacy observer path) ─────────────980//981// Pre-v2.12.0 the MAIN-world `passkeys-firefox.ts` was an observer — it982// emitted `peach-passkey-firefox` postMessages so this content script could983// surface State 12 (an inline "Save passkey to Peach" offer). v2.12.0984// replaced the observer with a full interception proxy (the page never985// reaches a real navigator.credentials.create on Firefox anymore), and the986// approval UI is opened by the background as part of the ceremony itself.987// When the proxy is active the offer would be redundant noise, so the988// listener gates on the flag. Once the proxy is removed (Firefox ships989// webAuthenticationProxy) this whole block goes too.990if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {991  let lastPasskeyOfferAt = 0;992  const PASSKEY_OFFER_COOLDOWN_MS = 30_000;993994  window.addEventListener("message", (event: MessageEvent) => {995    if (event.source !== window) return;996    const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;997    if (!data || data.source !== "peach-passkey-firefox") return;998    if (detectBrowser() !== "firefox") return;999    if (data.type !== "create") return;10001001    // Cooldown: a single page interaction can fire multiple credentials.create1002    // calls. Show the offer at most once per 30 seconds per page session.1003    const now = Date.now();1004    if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1005    lastPasskeyOfferAt = now;10061007    const domain = location.hostname.replace(/^www\./, "");1008    chrome.runtime.sendMessage({1009      type: "GET_PASSKEY_OFFER_DECLINED",1010      payload: { domain },1011    }).then((res: { ok: boolean; data?: boolean } | undefined) => {1012      if (res?.data === true) return;1013      const rpId = data.rpId ?? domain;1014      showPasskeyRegistrationOffer({1015        rpId,1016        rpName: data.rpName,1017        userName: data.userName,1018        userDisplayName: data.userDisplayName,1019      });1020    }).catch(() => {});1021  });1022}10231024// Surface State 11 (passkey-available) only when it adds value:1025//   - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither1026//     browser will auto-route, so the banner explains the re-register need.1027//   - Firefox + same-browser entry: Firefox has no equivalent of1028//     webAuthenticationProxy, so without a banner the user has no signal that1029//     Peach is the source.1030// On Chrome with a same-browser entry: skip — webAuthenticationProxy handles1031// the page's own credentials.get transparently and the popup approval view1032// already surfaces it. A banner here would just be noise.1033//1034// Dedupe across navigation: each navigation re-injects this content script.1035// chrome.storage.session keyed by domain is the natural per-tab/per-session1036// memory; session storage clears when the user closes the browser.1037{1038  function checkPasskeyAvailability() {1039    const domain = location.hostname.replace(/^www\./, "");1040    if (!domain) return;1041    const sessionKey = `peach_state11_shown:${domain}`;1042    chrome.storage.session?.get(sessionKey).then((stored) => {1043      if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1044      chrome.runtime.sendMessage({1045        type: "GET_PASSKEY_FOR_DOMAIN",1046        payload: { domain },1047      }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1048        const data = res?.data;1049        if (!data) return;1050        const current = detectBrowser();1051        const isCrossBrowser =1052          data.browser && current !== "unknown" && data.browser !== current;1053        const valuableOnFirefox = current === "firefox";1054        if (!isCrossBrowser && !valuableOnFirefox) return;1055        chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1056        showPasskeyAvailable({1057          rpId: data.rpId,1058          userName: data.userName,1059          fromBrowser: data.browser,1060          currentBrowser: current,1061        });1062      }).catch(() => {});1063    }).catch(() => {});1064  }10651066  // Defer until DOM is interactive — content_scripts run at document_idle but1067  // some pages still mutate visibly afterwards. A short delay also avoids1068  // surfacing the State 11 toast while the user is in the middle of typing.1069  if (document.readyState === "loading") {1070    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1071  } else {1072    setTimeout(checkPasskeyAvailability, 800);1073  }1074}