index.ts

46.3 KB · raw

1import {2  detectCardForm,3  detectLoginFields,4  findOTPDigitBoxGroup,5  getDeepActiveInput,6  getPageDomain,7  isAnyCredentialForm,8  isEmailFirstForm,9  isLoginForm,10  isSignupForm,11  isTOTPField,12  isVisible,13} from "./detect";14import {15  CardSelectorEntry,16  injectFieldIcon,17  SelectorEntry,18  showAutofillSelector,19  showCardSelector,20  showPasskeyAvailable,21  showPasskeyProGate,22  showPasskeyRegistrationOffer,23  showRememberSiteToast,24  showTOTPSelector,25} from "./inject";26import { detectBrowser } from "../shared/browser";27import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";28import { fillCardForm, fillFields, fillOTPDigitBoxes, fillTOTPCode, setNativeValue } from "./fill";29import { setupSaveDetection } from "./save";30import { contentMLDetector } from "./content-ml-detector";31import { detectPasswordPolicy } from "./policy";32import type { FieldPrediction } from "../shared/ml";33import { generateTOTP } from "../crypto/totp";34import type { SavedIdentity, VaultEntry } from "../shared/types";3536// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value37// so we can tear down listeners if we ever need to re-process the same field.38// When the input is GC'd (SPA nav, React re-render), the map entry goes with39// it and we can re-inject without leaking the old handler.40const processedInputs = new WeakMap<HTMLInputElement, () => void>();41const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4243let currentDismiss: (() => void) | null = null;44// Field whose selector is currently open — used to avoid dismiss+reopen flicker45let currentAnchorField: HTMLInputElement | null = null;46// Prevents two concurrent handleFieldInteraction calls for the same field47const pendingInteractions = new WeakSet<HTMLInputElement>();48// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).49// Suppresses spurious reopens until focus moves to a different field. Layer 150// of the dismissal model — see Projects.md §4.12.51let lastDismissedField: HTMLInputElement | null = null;5253// ── Dismissal lock (Layer 2) ────────────────────────────────────────54// After any user-initiated dismiss, briefly block ALL reopens regardless of55// which field is focused. Catches the case where a page rapidly moves focus56// between fields after Escape — without this, focus moving to a SECOND field57// in <100ms would re-trigger the popup before the user finished dismissing.58const DISMISS_LOCK_MS = 800;59let dismissLock = false;60let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;61// Set when the inline popup was summoned specifically for a passkey-unlock62// flow. The VAULT_UNLOCKED handler checks this to skip re-triggering autofill63// (the passkey toast handles the next step instead).64let passkeySummonActive = false;65// Set while the passkey approval toast is visible. Prevents handleFieldInteraction66// from opening the autofill selector alongside it. Cleared by a window message67// posted by inject.tsx when the toast closes (and by DISMISS_PASSKEY_TOAST).68let passkeyToastActive = false;69function startDismissLock(): void {70  dismissLock = true;71  if (dismissLockTimer) clearTimeout(dismissLockTimer);72  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);73}74function canOpen(): boolean { return !dismissLock; }7576// ── Fill-success lock ───────────────────────────────────────────────77// After Peach autofills a form, the popup must NOT reappear on the filled78// fields, on the submit button (some sites refocus it briefly), or on any79// field in that form — even when host-page DOM mutations or the form's own80// validation flow refocus an input. Implemented as a WeakSet of forms plus81// a page-level timestamp:82//   - filledForms: every form Peach has filled this page session. Survives83//     until the form leaves the DOM (WeakSet GC).84//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders85//     window for fields that aren't inside a <form> element (some SPAs).86// SPA navigation resets pageFilledAt via the urlObserver below; filledForms87// self-empties as old form elements get GC'd.88const filledForms = new WeakSet<HTMLFormElement>();89let pageFilledAt: number | null = null;90const PAGE_FILL_GRACE_MS = 3000;9192function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {93  for (const f of fields) {94    if (!f) continue;95    const form = f.closest("form");96    if (form) filledForms.add(form);97  }98  pageFilledAt = Date.now();99}100101function wasAlreadyFilled(field: HTMLInputElement): boolean {102  const form = field.closest("form");103  if (form && filledForms.has(form)) return true;104  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;105  return false;106}107108function clearFillStateForExplicitSummon(field: HTMLInputElement): void {109  const form = field.closest("form");110  if (form) filledForms.delete(form);111  pageFilledAt = null;112}113114// Some sites briefly focus the submit button when the user clicks it (visual115// feedback, blur/focus dance for validation animations). Catch those at the116// focusin layer so we don't re-trigger handleFieldInteraction for an event117// target that was never going to be a credential field anyway.118function isSubmitButton(el: EventTarget | null): boolean {119  if (!(el instanceof HTMLElement)) return false;120  if (el instanceof HTMLButtonElement && el.type !== "button") return true;121  if (el instanceof HTMLInputElement && el.type === "submit") return true;122  if (el.getAttribute("type") === "submit") return true;123  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();124  if (!text || text.length > 24) return false;125  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);126}127128function debounce<T extends (...args: unknown[]) => void>(129  fn: T,130  ms: number131): (...args: Parameters<T>) => void {132  let timer: ReturnType<typeof setTimeout>;133  return (...args: Parameters<T>) => {134    clearTimeout(timer);135    timer = setTimeout(() => fn(...args), ms);136  };137}138139function showToast(message: string): void {140  const toast = document.createElement("div");141  toast.style.cssText = `142    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);143    background: #131109; color: #F0E8D8; padding: 8px 16px;144    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;145    font-size: 11px; z-index: 2147483647; opacity: 0;146    transition: opacity 200ms ease;147    border: 1px solid rgba(240,232,216,0.07);148    pointer-events: none;149  `;150  toast.textContent = message;151  document.body.appendChild(toast);152  requestAnimationFrame(() => { toast.style.opacity = "1"; });153  setTimeout(() => {154    toast.style.opacity = "0";155    setTimeout(() => toast.remove(), 200);156  }, 2000);157}158159function showSearchPalette(): void {160  const host = document.createElement("div");161  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";162  document.body.appendChild(host);163  const shadow = host.attachShadow({ mode: "closed" });164165  const style = document.createElement("style");166  style.textContent = `167    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;168      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;169      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}170    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);171      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}172    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}173    .s{padding:8px 12px}174    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);175      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;176      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}177    .l{max-height:220px;overflow-y:auto}178    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}179    .e:hover{background:rgba(240,232,216,.06)}180    .et{font-size:12px}181    .eu{font-size:10px;color:rgba(240,232,216,.45)}182    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}183  `;184185  let allEntries: SelectorEntry[] = [];186  let query = "";187188  const panel = document.createElement("div");189  panel.className = "p";190191  const hdr = document.createElement("div");192  hdr.className = "h";193  const hdrText = document.createElement("span");194  hdrText.textContent = "No form detected — search your vault";195  const closeBtn = document.createElement("button");196  closeBtn.className = "x";197  closeBtn.textContent = "✕";198  hdr.appendChild(hdrText);199  hdr.appendChild(closeBtn);200201  const searchWrap = document.createElement("div");202  searchWrap.className = "s";203  const searchInput = document.createElement("input");204  searchInput.placeholder = "search...";205  searchWrap.appendChild(searchInput);206207  const list = document.createElement("div");208  list.className = "l";209210  panel.appendChild(hdr);211  panel.appendChild(searchWrap);212  panel.appendChild(list);213  shadow.appendChild(style);214  shadow.appendChild(panel);215216  function close() { host.remove(); }217218  closeBtn.onclick = close;219220  function onKeyDown(e: KeyboardEvent) {221    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }222  }223  document.addEventListener("keydown", onKeyDown, true);224225  function render() {226    const q = query.toLowerCase();227    const filtered = q228      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))229      : allEntries;230    list.innerHTML = "";231    if (filtered.length === 0) {232      const em = document.createElement("div");233      em.className = "em";234      em.textContent = query ? "no matches" : "vault is empty";235      list.appendChild(em);236      return;237    }238    for (const entry of filtered.slice(0, 20)) {239      const row = document.createElement("div");240      row.className = "e";241      const title = document.createElement("div");242      title.className = "et";243      title.textContent = entry.title;244      row.appendChild(title);245      if (entry.username) {246        const user = document.createElement("div");247        user.className = "eu";248        user.textContent = entry.username;249        row.appendChild(user);250      }251      row.onclick = async () => {252        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });253        const r = resp as { ok: boolean; data?: { password?: string } };254        if (r.ok && r.data?.password) {255          let alreadyWritten = false;256          try {257            await navigator.clipboard.writeText(r.data.password);258            alreadyWritten = true;259          } catch (err) {260            console.warn("[Peach] clipboard write denied:", err);261          }262          const copyResp = await chrome.runtime.sendMessage({263            type: "COPY",264            payload: { text: r.data.password, label: "Password", alreadyWritten },265          }) as { ok?: boolean } | undefined;266          if (alreadyWritten || copyResp?.ok) {267            showToast("Password copied");268          } else {269            showToast("Could not copy password — clipboard blocked");270          }271        } else {272          showToast("Could not copy password");273        }274        close();275        document.removeEventListener("keydown", onKeyDown, true);276      };277      list.appendChild(row);278    }279  }280281  searchInput.oninput = () => { query = searchInput.value; render(); };282283  fetchAutofillEntries(getPageDomain(), true).then(result => {284    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }285    allEntries = result.entries;286    render();287    searchInput.focus();288  });289}290291function findTOTPField(root: Document | Element = document): HTMLInputElement | null {292  const inputs = root.querySelectorAll<HTMLInputElement>("input");293  for (const input of inputs) {294    if (isTOTPField(input)) return input;295  }296  return null;297}298299function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {300  const form = passwordEl.closest("form");301  return findTOTPField(form ?? document);302}303304305async function handleAutofill(306  _field: HTMLInputElement,307  usernameEl: HTMLInputElement | null,308  passwordEl: HTMLInputElement | null,309  entry: VaultEntry310): Promise<HTMLInputElement | null> {311  if (!entry.username && !entry.password) return null;312  const pageDomain = getPageDomain();313  const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;314  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);315  let filledTOTPField: HTMLInputElement | null = null;316317  if (entry.canary) {318    chrome.runtime.sendMessage({319      type: "FIRE_CANARY_PING",320      payload: {321        webhookUrl: entry.canary.webhookUrl,322        entryTitle: entry.title,323        trigger: "autofilled",324      },325    }).catch(() => {});326    chrome.runtime.sendMessage({327      type: "UPDATE_ENTRY",328      payload: {329        id: entry.id,330        patch: {331          canary: {332            ...entry.canary,333            lastPinged: Date.now(),334            pingCount: (entry.canary.pingCount ?? 0) + 1,335          },336        },337      },338    }).catch(() => {});339  }340341  if (entry.totp) {342    const { code } = generateTOTP(entry.totp);343    const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;344    if (fillTOTPCode(totpField, code)) {345      filledTOTPField = totpField;346    }347    let alreadyWritten = false;348    try {349      await navigator.clipboard.writeText(code);350      alreadyWritten = true;351    } catch (err) {352      console.warn("[Peach] clipboard write denied:", err);353    }354    const response = await chrome.runtime.sendMessage({355      type: "COPY",356      payload: { text: code, label: "TOTP", alreadyWritten },357    });358    if (filledTOTPField) {359      showToast("2FA code filled");360    } else if (alreadyWritten || (response as { ok?: boolean }).ok) {361      showToast("TOTP copied · " + code);362    } else {363      showToast("Could not copy TOTP — clipboard blocked");364    }365  }366367  return filledTOTPField;368}369370async function fetchAutofillEntries(371  domain: string,372  includeAll = false373): Promise<{ entries: SelectorEntry[]; locked: boolean }> {374  const response = await chrome.runtime.sendMessage({375    type: "AUTOFILL_QUERY",376    payload: { domain, includeAll },377  });378  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };379  if (!res.ok && res.error === "vault_locked") {380    return { entries: [], locked: true };381  }382  return { entries: res.data ?? [], locked: false };383}384385async function fetchTOTPEntries(386  domain: string387): Promise<{ entries: SelectorEntry[]; locked: boolean }> {388  const response = await chrome.runtime.sendMessage({389    type: "AUTOFILL_QUERY",390    payload: { domain, kind: "totp" },391  });392  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };393  if (!res.ok && res.error === "vault_locked") {394    return { entries: [], locked: true };395  }396  return { entries: res.data ?? [], locked: false };397}398399400function resolveAutofillFieldType(401  el: HTMLInputElement,402  predictedType?: FieldPrediction["type"] | null403): "password" | "username" | "email" | null {404  if (405    predictedType === "password" ||406    predictedType === "username" ||407    predictedType === "email"408  ) {409    return predictedType;410  }411412  const detected = detectLoginFields().find((field) => field.el === el)?.type;413  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {414    return detected;415  }416417  const htmlType = el.type.toLowerCase();418  if (htmlType === "password") return "password";419  if (htmlType === "email") return "email";420  return null;421}422423async function openAutofillSelector(424  anchorField: HTMLInputElement,425  usernameEl: HTMLInputElement | null,426  passwordEl: HTMLInputElement | null,427  domainEntries: SelectorEntry[],428  searchableEntries: SelectorEntry[],429  domain: string430): Promise<void> {431  // No saved entries for this site → signup/new-account mode.432  // Fetch vault identities for the identity-first surface and locate433  // the confirm-password field so "Copy & fill" can populate it too.434  const isSignup = domainEntries.length === 0;435  let savedIdentities: SavedIdentity[] | undefined;436  let confirmEl: HTMLInputElement | null = null;437  if (isSignup) {438    try {439      const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as440        { ok: boolean; data?: SavedIdentity[] } | null;441      if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;442    } catch { /* silent fallback */ }443444    const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;445    const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));446    confirmEl = allPwInputs.find(447      (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)448    ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);449  }450451  currentDismiss?.();452  currentAnchorField = anchorField;453  currentDismiss = showAutofillSelector(454    anchorField,455    domainEntries,456    async (id: string) => {457      currentDismiss = null;458      currentAnchorField = null;459      const entryResponse = await chrome.runtime.sendMessage({460        type: "GET_ENTRY_FOR_FILL",461        payload: { id },462      });463      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;464      if (entry) {465        const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry);466        recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);467        // Offer to remember the current site for this entry only if none of468        // its known domains (primary + additional) match — otherwise the469        // user already mapped it and the prompt would be noise.470        const pageDomain = location.hostname.replace(/^www\./, "");471        const entryDomains = new Set<string>();472        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {473          try {474            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));475          } catch { /* ignore unparseable */ }476        }477        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {478          showRememberSiteToast(pageDomain, entry.id);479        }480      }481    },482    {483      domain,484      searchableEntries,485      isSignup,486      savedIdentities,487      onFillFields: (username, password) => {488        const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;489        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());490        if (password && confirmEl) setNativeValue(confirmEl, password);491        recordFillSuccess(anchorField, usernameEl, passwordEl);492      },493      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },494    }495  );496}497498async function openTOTPSelector(anchorField: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[]): Promise<void> {499  if (!canOpen()) return;500  if (currentDismiss && currentAnchorField === anchorField) return;501  if (anchorField !== lastDismissedField) lastDismissedField = null;502  if (anchorField === lastDismissedField) return;503  if (wasAlreadyFilled(anchorField)) return;504505  const domain = getPageDomain();506  const result = await fetchTOTPEntries(domain);507508  if (result.locked) {509    currentDismiss?.();510    currentAnchorField = anchorField;511    currentDismiss = showAutofillSelector(512      anchorField,513      [],514      () => {},515      {516        domain,517        locked: true,518        onUnlocked: () => void openTOTPSelector(anchorField),519        onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },520      }521    );522    return;523  }524525  if (result.entries.length === 0) {526    lastDismissedField = anchorField;527    startDismissLock();528    showToast("No 2FA entries for this site — add a code in Peach first");529    return;530  }531532  currentDismiss?.();533  currentAnchorField = anchorField;534  currentDismiss = showTOTPSelector(535    anchorField,536    result.entries,537    async (id: string) => {538      try {539        const entryResponse = await chrome.runtime.sendMessage({540          type: "GET_ENTRY_FOR_FILL",541          payload: { id },542        }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;543        const entry = entryResponse?.ok ? entryResponse.data : undefined;544        if (!entry?.totp) return;545        const { code } = generateTOTP(entry.totp);546        if (otpDigitBoxes && otpDigitBoxes.length > 1) {547          fillOTPDigitBoxes(otpDigitBoxes, code);548        } else {549          setNativeValue(anchorField, code);550        }551        recordFillSuccess(anchorField);552        showToast("2FA code filled");553      } finally {554        currentDismiss = null;555        currentAnchorField = null;556      }557    },558    {559      domain,560      onDismiss: () => {561        lastDismissedField = anchorField;562        startDismissLock();563        currentDismiss = null;564        currentAnchorField = null;565      },566    }567  );568}569570571async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {572  const field = anchorField ?? getDeepActiveInput();573  if (!field) return;574  if (!isVisible(field)) return;575576  // Passkey toast is visible — don't open the credential selector alongside it.577  if (passkeyToastActive) return;578579  // Layer 2: post-dismiss global lock. Catches rapid focus moves between580  // fields immediately after Escape/click-outside.581  if (!canOpen()) return;582583  // If a selector is already open for this exact field, don't flicker it.584  if (currentDismiss && currentAnchorField === field) return;585586  // If focus moved to a different field, the previous per-field dismiss lock587  // no longer applies.588  if (field !== lastDismissedField) lastDismissedField = null;589  // Layer 1: the user explicitly dismissed this field's selector — don't590  // reopen it until focus has genuinely moved away and come back.591  if (field === lastDismissedField) return;592593  // Fill-success lock: Peach already filled this form (or fired a fill594  // anywhere on the page within the grace window). Sites often refocus an595  // input on submit click, on validation, or on a transition to a success596  // state — none of those should re-open the popup.597  if (wasAlreadyFilled(field)) return;598599  // Prevent two concurrent calls for the same field (e.g. focusin + icon click600  // firing simultaneously — the second call would dismiss the first's selector).601  if (pendingInteractions.has(field)) return;602  pendingInteractions.add(field);603604  try {605    // Multi-digit OTP entry: individual maxLength=1 boxes get no icon (too small)606    // but the TOTP selector opens on focus and fills every box at once.607    const otpGroup = findOTPDigitBoxGroup(field);608    if (otpGroup) {609      await openTOTPSelector(otpGroup[0]!, otpGroup);610      return;611    }612613    if (isTOTPField(field)) {614      const formFields = detectLoginFields();615      if (!isLoginForm(formFields) && !isSignupForm(formFields)) {616        await openTOTPSelector(field);617        return;618      }619    }620621    const fieldType = field.type.toLowerCase();622623    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {624      return preds[0] ?? null;625    });626627    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {628      const timeout = setTimeout(() => resolve(null), 150);629      mlPromise.then((pred) => {630        clearTimeout(timeout);631        resolve(pred);632      });633    });634635    if (passkeyToastActive) return;636637    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {638      return;639    }640641    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);642    if (autofillFieldType) {643      reattachListeners(field, autofillFieldType);644    }645646    let fields = detectLoginFields();647    if (!isAnyCredentialForm(fields)) {648      return;649    }650651    const domain = getPageDomain();652    const firstResult = await fetchAutofillEntries(domain);653    if (passkeyToastActive) return;654655    // Vault is locked — show an inline unlock prompt.656    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so657    // there is no double-trigger race between onUnlocked and the broadcast.658    if (firstResult.locked) {659      currentDismiss?.();660      currentAnchorField = field;661      currentDismiss = showAutofillSelector(662        field,663        [],664        () => {},665        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }666      );667      return;668    }669670    const entries = firstResult.entries;671    // Always fetch the vault-wide list so the inline popup's search affordance672    // can reach entries that don't match this domain — the user may have a673    // valid login filed under a different URL (e.g. corp account on a vanity674    // domain) and still want to fill it here.675    const allEntries = (await fetchAutofillEntries(domain, true)).entries;676677    if (passkeyToastActive) return;678679    let usernameEl: HTMLInputElement | null = null;680    const userField = fields.find((f) => f.type === "username" || f.type === "email");681    if (userField) usernameEl = userField.el;682    const pwField = fields.find((f) => f.type === "password");683    // For email-first flows there is no password field on this step — that is expected.684    if (!pwField && !isEmailFirstForm(fields)) return;685    const passwordEl = pwField?.el ?? null;686687    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);688  } finally {689    pendingInteractions.delete(field);690  }691}692693async function onFocusIn(e: Event): Promise<void> {694  // Submit-button focus: catch the brief refocus some sites do when the695  // user clicks the login/submit button. Without this guard, that focus696  // event reaches handleFieldInteraction → getDeepActiveInput, and on697  // pages where the button is also a labelled <input> we briefly attempt698  // to open the popup over the very button the user just clicked.699  if (isSubmitButton(e.target)) return;700  await handleFieldInteraction();701}702703function reattachListeners(704  el: HTMLInputElement,705  detectedType?: "password" | "username" | "email",706  contextFields?: ReturnType<typeof detectLoginFields>707): void {708  if (processedInputs.has(el)) return;709  if (!resolveAutofillFieldType(el, detectedType)) return;710  // Only inject icon when a credential form is present on the page711  const fields = contextFields ?? detectLoginFields();712  if (!isAnyCredentialForm(fields)) return;713714  const cleanup = injectFieldIcon(el, () => {715    currentDismiss?.();716    currentDismiss = null;717    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock718    dismissLock = false; // ...and the global lock719    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }720    clearFillStateForExplicitSummon(el);721    el.focus({ preventScroll: true });722    void handleFieldInteraction(el);723  });724  processedInputs.set(el, cleanup);725}726727const debouncedReattach = debounce(() => {728  const allFields = detectLoginFields();729  if (!isAnyCredentialForm(allFields)) return;730  const newFields = allFields.filter(731    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)732  );733  for (const f of newFields) {734    reattachListeners(f.el, f.type, allFields);735  }736  // 200ms debounce — below this, Peach and the host page's reactive layer737  // fight over the same layout properties every frame on React/Vue/Angular738  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.739}, 200);740741function setupMutationObserver(): void {742  const observer = new MutationObserver(debouncedReattach);743  observer.observe(document.body, {744    childList: true,745    subtree: true,746    attributes: true,747    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],748  });749}750751function initialScan(aggressionLevel = 0, isFinalPass = false) {752  const allFields = detectLoginFields();753  const hasKnownForm = isAnyCredentialForm(allFields);754755  if (aggressionLevel === 0 && !hasKnownForm) return;756757  const newFields = allFields.filter(758    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)759  );760761  for (const f of newFields) {762    reattachListeners(f.el, f.type, allFields);763  }764765  // Level 2, final pass: inject icon on any visible password field even if766  // the form-context gate in reattachListeners would normally skip it.767  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {768    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');769    for (const el of pwInputs) {770      if (isVisible(el) && !processedInputs.has(el)) {771        const cleanup = injectFieldIcon(el, () => {772          currentDismiss?.();773          currentDismiss = null;774          lastDismissedField = null;775          dismissLock = false;776          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }777          clearFillStateForExplicitSummon(el);778          el.focus({ preventScroll: true });779          void handleFieldInteraction(el);780        });781        processedInputs.set(el, cleanup);782      }783    }784  }785}786787// ── TOTP-only fields ───────────────────────────────────────────────────────788// After a username/password submission, many sites swap the whole form for a789// lone "verification code" input. The credential selector intentionally gates790// on login/signup forms, so TOTP fields need a narrow path of their own.791const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();792793function hasLoginOrSignupForm(): boolean {794  const fields = detectLoginFields();795  return isAnyCredentialForm(fields);796}797798function injectTOTPFieldIcon(field: HTMLInputElement): void {799  if (processedTOTPInputs.has(field)) return;800  const cleanup = injectFieldIcon(field, () => {801    currentDismiss?.();802    currentDismiss = null;803    currentAnchorField = null;804    lastDismissedField = null;805    dismissLock = false;806    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }807    clearFillStateForExplicitSummon(field);808    field.focus({ preventScroll: true });809    void openTOTPSelector(field);810  });811  processedTOTPInputs.set(field, cleanup);812}813814function scanTOTPFields(): void {815  if (hasLoginOrSignupForm()) return;816  const inputs = document.querySelectorAll<HTMLInputElement>("input");817  for (const input of inputs) {818    if (!isTOTPField(input)) continue;819    injectTOTPFieldIcon(input);820  }821}822823function setupTOTPAutofill(): void {824  setTimeout(scanTOTPFields, 0);825  setTimeout(scanTOTPFields, 500);826  setTimeout(scanTOTPFields, 1500);827828  const debouncedScan = debounce(scanTOTPFields, 200);829  new MutationObserver(debouncedScan).observe(document.body, {830    childList: true,831    subtree: true,832    attributes: true,833    attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],834  });835836  document.addEventListener("focusin", (e) => {837    const target = e.target;838    if (!(target instanceof HTMLInputElement)) return;839    if (hasLoginOrSignupForm()) return;840    if (!isTOTPField(target)) return;841    injectTOTPFieldIcon(target);842  }, true);843}844845document.addEventListener("focusin", onFocusIn);846847setupMutationObserver();848setupTOTPAutofill();849setupSaveDetection();850setupCardAutofill();851852// SPA navigation reset: the content script does not reload across in-app853// route changes (history.pushState, hash navigation, framework routers).854// When the URL changes we clear the page-level fill timestamp so the next855// page works normally; filledForms (a WeakSet) self-empties as old form856// elements leave the DOM. subtree:false because route swaps reliably857// mutate document.body's direct children — subtree:true would fire on858// every internal DOM update and cost us a re-check per mutation.859let lastObservedUrl = location.href;860new MutationObserver(() => {861  if (location.href !== lastObservedUrl) {862    lastObservedUrl = location.href;863    pageFilledAt = null;864  }865}).observe(document.body, { childList: true, subtree: false });866867// Async init: check recall map before running the initial scans so we can868// apply the right aggression level for domains the user has needed before.869(async () => {870  let aggressionLevel = 0;871  try {872    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });873    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;874    const domain = getPageDomain();875    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;876    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;877  } catch { /* SW may be starting up; proceed with normal scan */ }878879  setTimeout(() => initialScan(aggressionLevel, false), 0);880  setTimeout(() => initialScan(aggressionLevel, false), 500);881  setTimeout(() => initialScan(aggressionLevel, true), 1500);882})();883884// ── Card autofill (State 7) ─────────────────────────────────────────885// Card forms get a parallel injection path. The login icon-injection gate886// in reattachListeners deliberately skips non-text fields, so we wire887// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping888// card detection contained makes the boundary easy to follow.889const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();890let currentCardDismiss: (() => void) | null = null;891let currentCardAnchor: HTMLInputElement | null = null;892let lastDismissedCardField: HTMLInputElement | null = null;893894async function fetchSavedCards(): Promise<CardSelectorEntry[]> {895  const resp = await chrome.runtime.sendMessage({896    type: "AUTOFILL_QUERY",897    payload: { domain: getPageDomain(), kind: "card" },898  }).catch(() => null);899  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;900  return r?.ok ? (r.data ?? []) : [];901}902903async function openCardSelector(anchor: HTMLInputElement): Promise<void> {904  if (!canOpen()) return;905  if (currentCardDismiss && currentCardAnchor === anchor) return;906  if (anchor === lastDismissedCardField) return;907  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;908  if (wasAlreadyFilled(anchor)) return;909910  const cards = await fetchSavedCards();911  if (cards.length === 0) return; // no saved cards → nothing to offer912913  const cardForm = detectCardForm();914  if (!cardForm?.number) return;915916  currentCardDismiss?.();917  currentCardAnchor = anchor;918  currentCardDismiss = showCardSelector(919    anchor,920    cards,921    {922      domain: getPageDomain(),923      onFill: (entry) => {924        if (!cardForm) return;925        fillCardForm(cardForm, {926          cardNumber: entry.cardNumber ?? "",927          expMonth: entry.expMonth ?? "",928          expYear: entry.expYear ?? "",929          cvc: entry.cvc ?? "",930          cardholderName: entry.cardholderName ?? "",931        });932        // All four card field types share the same form — recording the933        // number field's form is sufficient to suppress reopens on any of934        // them via wasAlreadyFilled().935        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);936        currentCardDismiss = null;937        currentCardAnchor = null;938      },939      onDismiss: () => {940        lastDismissedCardField = anchor;941        startDismissLock();942        currentCardDismiss = null;943        currentCardAnchor = null;944      },945    }946  );947}948949function injectCardIcon(field: HTMLInputElement): void {950  if (processedCardInputs.has(field)) return;951  const cleanup = injectFieldIcon(field, () => {952    currentCardDismiss?.();953    currentCardDismiss = null;954    lastDismissedCardField = null;955    dismissLock = false;956    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }957    clearFillStateForExplicitSummon(field);958    field.focus({ preventScroll: true });959    void openCardSelector(field);960  });961  processedCardInputs.set(field, cleanup);962}963964function setupCardAutofill(): void {965  function scan() {966    const cardForm = detectCardForm();967    if (!cardForm?.number) return;968    if (!isVisible(cardForm.number)) return;969    injectCardIcon(cardForm.number);970  }971972  // Initial detection sweep — same retry cadence as login fields so973  // late-hydrating SPA checkout pages get caught.974  setTimeout(scan, 0);975  setTimeout(scan, 500);976  setTimeout(scan, 1500);977978  // Re-scan on DOM mutation (separate from the login MutationObserver979  // because card forms typically appear on a single navigation event,980  // not field-by-field — coarser observation is sufficient here).981  let pending = false;982  new MutationObserver(() => {983    if (pending) return;984    pending = true;985    setTimeout(() => { pending = false; scan(); }, 200);986  }).observe(document.body, { childList: true, subtree: true });987988  // Field-focus path: on focus of a cc-number input, ensure icon is989  // present and consider opening the selector when the user explicitly990  // clicks into the card number field.991  document.addEventListener("focusin", (e) => {992    const target = e.target;993    if (!(target instanceof HTMLInputElement)) return;994    const cardForm = detectCardForm();995    if (cardForm?.number === target) {996      injectCardIcon(target);997    }998  }, true);999}10001001chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1002  // Ignore anything not originating from our own background/service worker.1003  if (sender.id !== chrome.runtime.id) return;1004  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1005    const policy = detectPasswordPolicy();1006    sendResponse({ ok: true, data: policy });1007    return true;1008  }1009  if (msg?.type === "PING") {1010    sendResponse({ ok: true });1011    return true;1012  }1013  if (msg?.type === "SUMMON_AUTOFILL") {1014    const source = (msg as { type: string; source?: string }).source;1015    const isShortcut = source === "shortcut";1016    const isPasskeyUnlock = source === "passkey-unlock";10171018    const activeInput = getDeepActiveInput();1019    const fields = detectLoginFields();1020    const hasForm = isAnyCredentialForm(fields);10211022    if (hasForm) {1023      // Prefer the currently focused field if it's a login field, otherwise1024      // fall back to the first password field, then username/email.1025      const inForm = activeInput && fields.some(f => f.el === activeInput);1026      const target = inForm1027        ? activeInput1028        : (fields.find(f => f.type === "password")?.el1029            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1030      if (target) {1031        // Explicit user summon (shortcut or extension button) — bypass all1032        // suppression layers. The user is asking for the popup right now.1033        clearFillStateForExplicitSummon(target);1034        dismissLock = false;1035        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1036        lastDismissedField = null;1037        void handleFieldInteraction(target);1038      }1039    } else if (isPasskeyUnlock) {1040      // Vault is locked during a passkey GET request. Show the inline unlock1041      // prompt anchored to whatever element is focused on the page (typically1042      // the passkey/sign-in button the user just tapped).1043      const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1044        ? document.activeElement as unknown as HTMLInputElement1045        : null;1046      if (anchor) {1047        currentDismiss?.();1048        currentAnchorField = null;1049        passkeySummonActive = true;1050        currentDismiss = showAutofillSelector(anchor, [], () => {}, {1051          domain: getPageDomain(),1052          locked: true,1053          onDismiss: () => { passkeySummonActive = false; },1054        });1055      }1056    } else if (isShortcut) {1057      // Shortcut on a page with no login form — show clipboard-copy search mode.1058      showSearchPalette();1059    }10601061    // Record this domain for the recall system when triggered via shortcut.1062    if (isShortcut) {1063      const domain = getPageDomain();1064      if (domain) {1065        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1066      }1067    }10681069    sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1070    return true;1071  }1072  if (msg?.type === "PASSKEY_PRO_GATE") {1073    // Background rejected a passkey request for a free user. Show State 111074    // so they know what happened and can choose to upgrade.1075    showPasskeyProGate();1076    sendResponse({ ok: true });1077    return true;1078  }1079  if (msg?.type === "SHOW_PASSKEY_TOAST") {1080    // Block autofill selector for the lifetime of the toast and dismiss anything open.1081    passkeyToastActive = true;1082    if (currentDismiss) {1083      currentDismiss();1084      currentDismiss = null;1085      currentAnchorField = null;1086    }1087    return false; // inject.tsx owns the toast and calls sendResponse1088  }1089  if (msg?.type === "DISMISS_PASSKEY_TOAST") {1090    passkeyToastActive = false;1091    return false; // inject.tsx handles the actual dismissal1092  }1093  if (msg?.type === "VAULT_UNLOCKED") {1094    if (passkeySummonActive) {1095      // This unlock was for a pending passkey GET request. Just dismiss the1096      // inline popup — the passkey approval toast takes over from here.1097      passkeySummonActive = false;1098      if (currentDismiss) {1099        currentDismiss();1100        currentDismiss = null;1101        currentAnchorField = null;1102      }1103      sendResponse({ ok: true });1104      return true;1105    }1106    // Normal autofill path: close the locked-state prompt and re-open with1107    // fresh entry data at the same anchor field.1108    const savedField = currentAnchorField;1109    if (currentDismiss) {1110      currentDismiss();1111      currentDismiss = null;1112      currentAnchorField = null;1113    }1114    void handleFieldInteraction(savedField ?? undefined);1115    sendResponse({ ok: true });1116    return true;1117  }1118  return true;1119});11201121// inject.tsx posts this when the passkey toast closes (approve, deny, or timeout)1122// so we know it's safe to allow autofill again.1123window.addEventListener("message", (e: MessageEvent) => {1124  // Reject postMessages from cross-frame senders — only the same window's1125  // injected toast may flip this flag.1126  if (e.source !== window) return;1127  const d = e.data as { source?: string; type?: string } | undefined;1128  if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1129    passkeyToastActive = false;1130  }1131});11321133// ── Firefox passkey detection bridge (legacy observer path) ─────────────1134//1135// Pre-v2.12.0 the MAIN-world `passkeys-firefox.ts` was an observer — it1136// emitted `peach-passkey-firefox` postMessages so this content script could1137// surface State 12 (an inline "Save passkey to Peach" offer). v2.12.01138// replaced the observer with a full interception proxy (the page never1139// reaches a real navigator.credentials.create on Firefox anymore), and the1140// approval UI is opened by the background as part of the ceremony itself.1141// When the proxy is active the offer would be redundant noise, so the1142// listener gates on the flag. Once the proxy is removed (Firefox ships1143// webAuthenticationProxy) this whole block goes too.1144if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1145  let lastPasskeyOfferAt = 0;1146  const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11471148  window.addEventListener("message", (event: MessageEvent) => {1149    if (event.source !== window) return;1150    const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1151    if (!data || data.source !== "peach-passkey-firefox") return;1152    if (detectBrowser() !== "firefox") return;1153    if (data.type !== "create") return;11541155    // Cooldown: a single page interaction can fire multiple credentials.create1156    // calls. Show the offer at most once per 30 seconds per page session.1157    const now = Date.now();1158    if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1159    lastPasskeyOfferAt = now;11601161    const domain = location.hostname.replace(/^www\./, "");1162    chrome.runtime.sendMessage({1163      type: "GET_PASSKEY_OFFER_DECLINED",1164      payload: { domain },1165    }).then((res: { ok: boolean; data?: boolean } | undefined) => {1166      if (res?.data === true) return;1167      const rpId = data.rpId ?? domain;1168      showPasskeyRegistrationOffer({1169        rpId,1170        rpName: data.rpName,1171        userName: data.userName,1172        userDisplayName: data.userDisplayName,1173      });1174    }).catch(() => {});1175  });1176}11771178// Surface State 11 (passkey-available) only when it adds value:1179//   - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither1180//     browser will auto-route, so the banner explains the re-register need.1181//   - Firefox + same-browser entry: Firefox has no equivalent of1182//     webAuthenticationProxy, so without a banner the user has no signal that1183//     Peach is the source.1184// On Chrome with a same-browser entry: skip — webAuthenticationProxy handles1185// the page's own credentials.get transparently and the popup approval view1186// already surfaces it. A banner here would just be noise.1187//1188// Dedupe across navigation: each navigation re-injects this content script.1189// chrome.storage.session keyed by domain is the natural per-tab/per-session1190// memory; session storage clears when the user closes the browser.1191{1192  function checkPasskeyAvailability() {1193    const domain = location.hostname.replace(/^www\./, "");1194    if (!domain) return;1195    const sessionKey = `peach_state11_shown:${domain}`;1196    chrome.storage.session?.get(sessionKey).then((stored) => {1197      if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1198      chrome.runtime.sendMessage({1199        type: "GET_PASSKEY_FOR_DOMAIN",1200        payload: { domain },1201      }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1202        const data = res?.data;1203        if (!data) return;1204        const current = detectBrowser();1205        const isCrossBrowser =1206          data.browser && current !== "unknown" && data.browser !== current;1207        const valuableOnFirefox = current === "firefox";1208        if (!isCrossBrowser && !valuableOnFirefox) return;1209        chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1210        showPasskeyAvailable({1211          rpId: data.rpId,1212          userName: data.userName,1213          fromBrowser: data.browser,1214          currentBrowser: current,1215        });1216      }).catch(() => {});1217    }).catch(() => {});1218  }12191220  // Defer until DOM is interactive — content_scripts run at document_idle but1221  // some pages still mutate visibly afterwards. A short delay also avoids1222  // surfacing the State 11 toast while the user is in the middle of typing.1223  if (document.readyState === "loading") {1224    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1225  } else {1226    setTimeout(checkPasskeyAvailability, 800);1227  }1228}