index.ts

39.5 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  observeAnchorPosition,14  SelectorEntry,15  showAutofillSelector,16  showCardSelector,17  showPasskeyAvailable,18  showPasskeyProGate,19  showPasskeyRegistrationOffer,20  showRememberSiteToast,21} from "./inject";22import { detectBrowser } from "../shared/browser";23import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";24import { fillCardForm, fillFields } from "./fill";25import { setupSaveDetection } from "./save";26import { contentMLDetector } from "./content-ml-detector";27import { detectPasswordPolicy } from "./policy";28import type { FieldPrediction } from "../shared/ml";29import { generateTOTP } from "../crypto/totp";30import type { SavedIdentity, VaultEntry } from "../shared/types";3132// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value33// so we can tear down listeners if we ever need to re-process the same field.34// When the input is GC'd (SPA nav, React re-render), the map entry goes with35// it and we can re-inject without leaking the old handler.36const processedInputs = new WeakMap<HTMLInputElement, () => void>();37const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3839let currentDismiss: (() => void) | null = null;40// Field whose selector is currently open — used to avoid dismiss+reopen flicker41let currentAnchorField: HTMLInputElement | null = null;42// Prevents two concurrent handleFieldInteraction calls for the same field43const pendingInteractions = new WeakSet<HTMLInputElement>();44// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).45// Suppresses spurious reopens until focus moves to a different field. Layer 146// of the dismissal model — see Projects.md §4.12.47let lastDismissedField: HTMLInputElement | null = null;4849// ── Dismissal lock (Layer 2) ────────────────────────────────────────50// After any user-initiated dismiss, briefly block ALL reopens regardless of51// which field is focused. Catches the case where a page rapidly moves focus52// between fields after Escape — without this, focus moving to a SECOND field53// in <100ms would re-trigger the popup before the user finished dismissing.54const DISMISS_LOCK_MS = 800;55let dismissLock = false;56let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;57function startDismissLock(): void {58  dismissLock = true;59  if (dismissLockTimer) clearTimeout(dismissLockTimer);60  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);61}62function canOpen(): boolean { return !dismissLock; }6364// ── Fill-success lock ───────────────────────────────────────────────65// After Peach autofills a form, the popup must NOT reappear on the filled66// fields, on the submit button (some sites refocus it briefly), or on any67// field in that form — even when host-page DOM mutations or the form's own68// validation flow refocus an input. Implemented as a WeakSet of forms plus69// a page-level timestamp:70//   - filledForms: every form Peach has filled this page session. Survives71//     until the form leaves the DOM (WeakSet GC).72//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders73//     window for fields that aren't inside a <form> element (some SPAs).74// SPA navigation resets pageFilledAt via the urlObserver below; filledForms75// self-empties as old form elements get GC'd.76const filledForms = new WeakSet<HTMLFormElement>();77let pageFilledAt: number | null = null;78const PAGE_FILL_GRACE_MS = 3000;7980function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {81  for (const f of fields) {82    if (!f) continue;83    const form = f.closest("form");84    if (form) filledForms.add(form);85  }86  pageFilledAt = Date.now();87}8889function wasAlreadyFilled(field: HTMLInputElement): boolean {90  const form = field.closest("form");91  if (form && filledForms.has(form)) return true;92  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;93  return false;94}9596function clearFillStateForExplicitSummon(field: HTMLInputElement): void {97  const form = field.closest("form");98  if (form) filledForms.delete(form);99  pageFilledAt = null;100}101102// Some sites briefly focus the submit button when the user clicks it (visual103// feedback, blur/focus dance for validation animations). Catch those at the104// focusin layer so we don't re-trigger handleFieldInteraction for an event105// target that was never going to be a credential field anyway.106function isSubmitButton(el: EventTarget | null): boolean {107  if (!(el instanceof HTMLElement)) return false;108  if (el instanceof HTMLButtonElement && el.type !== "button") return true;109  if (el instanceof HTMLInputElement && el.type === "submit") return true;110  if (el.getAttribute("type") === "submit") return true;111  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();112  if (!text || text.length > 24) return false;113  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);114}115116function debounce<T extends (...args: unknown[]) => void>(117  fn: T,118  ms: number119): (...args: Parameters<T>) => void {120  let timer: ReturnType<typeof setTimeout>;121  return (...args: Parameters<T>) => {122    clearTimeout(timer);123    timer = setTimeout(() => fn(...args), ms);124  };125}126127function showToast(message: string): void {128  const toast = document.createElement("div");129  toast.style.cssText = `130    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);131    background: #131109; color: #F0E8D8; padding: 8px 16px;132    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;133    font-size: 11px; z-index: 2147483647; opacity: 0;134    transition: opacity 200ms ease;135    border: 1px solid rgba(240,232,216,0.07);136    pointer-events: none;137  `;138  toast.textContent = message;139  document.body.appendChild(toast);140  requestAnimationFrame(() => { toast.style.opacity = "1"; });141  setTimeout(() => {142    toast.style.opacity = "0";143    setTimeout(() => toast.remove(), 200);144  }, 2000);145}146147function showSearchPalette(): void {148  const host = document.createElement("div");149  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";150  document.body.appendChild(host);151  const shadow = host.attachShadow({ mode: "closed" });152153  const style = document.createElement("style");154  style.textContent = `155    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;156      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;157      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}158    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);159      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}160    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}161    .s{padding:8px 12px}162    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);163      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;164      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}165    .l{max-height:220px;overflow-y:auto}166    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}167    .e:hover{background:rgba(240,232,216,.06)}168    .et{font-size:12px}169    .eu{font-size:10px;color:rgba(240,232,216,.45)}170    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}171  `;172173  let allEntries: SelectorEntry[] = [];174  let query = "";175176  const panel = document.createElement("div");177  panel.className = "p";178179  const hdr = document.createElement("div");180  hdr.className = "h";181  const hdrText = document.createElement("span");182  hdrText.textContent = "No form detected — search your vault";183  const closeBtn = document.createElement("button");184  closeBtn.className = "x";185  closeBtn.textContent = "✕";186  hdr.appendChild(hdrText);187  hdr.appendChild(closeBtn);188189  const searchWrap = document.createElement("div");190  searchWrap.className = "s";191  const searchInput = document.createElement("input");192  searchInput.placeholder = "search...";193  searchWrap.appendChild(searchInput);194195  const list = document.createElement("div");196  list.className = "l";197198  panel.appendChild(hdr);199  panel.appendChild(searchWrap);200  panel.appendChild(list);201  shadow.appendChild(style);202  shadow.appendChild(panel);203204  function close() { host.remove(); }205206  closeBtn.onclick = close;207208  function onKeyDown(e: KeyboardEvent) {209    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }210  }211  document.addEventListener("keydown", onKeyDown, true);212213  function render() {214    const q = query.toLowerCase();215    const filtered = q216      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))217      : allEntries;218    list.innerHTML = "";219    if (filtered.length === 0) {220      const em = document.createElement("div");221      em.className = "em";222      em.textContent = query ? "no matches" : "vault is empty";223      list.appendChild(em);224      return;225    }226    for (const entry of filtered.slice(0, 20)) {227      const row = document.createElement("div");228      row.className = "e";229      const title = document.createElement("div");230      title.className = "et";231      title.textContent = entry.title;232      row.appendChild(title);233      if (entry.username) {234        const user = document.createElement("div");235        user.className = "eu";236        user.textContent = entry.username;237        row.appendChild(user);238      }239      row.onclick = async () => {240        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });241        const r = resp as { ok: boolean; data?: { password?: string } };242        if (r.ok && r.data?.password) {243          let alreadyWritten = false;244          try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}245          await chrome.runtime.sendMessage({246            type: "COPY",247            payload: { text: r.data.password, label: "Password", alreadyWritten },248          });249          showToast("Password copied");250        } else {251          showToast("Could not copy password");252        }253        close();254        document.removeEventListener("keydown", onKeyDown, true);255      };256      list.appendChild(row);257    }258  }259260  searchInput.oninput = () => { query = searchInput.value; render(); };261262  fetchAutofillEntries(getPageDomain(), true).then(result => {263    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }264    allEntries = result.entries;265    render();266    searchInput.focus();267  });268}269270function setNativeValue(el: HTMLInputElement, value: string): void {271  const nativeSetter = Object.getOwnPropertyDescriptor(272    HTMLInputElement.prototype, "value"273  )!.set!;274  nativeSetter.call(el, value);275  el.dispatchEvent(new Event("input", { bubbles: true }));276  el.dispatchEvent(new Event("change", { bubbles: true }));277}278279function findTOTPField(): HTMLInputElement | null {280  const inputs = document.querySelectorAll<HTMLInputElement>("input");281  for (const input of inputs) {282    if (!isVisible(input)) continue;283    const autocomplete = input.autocomplete.toLowerCase();284    const nameId = (input.name + input.id).toLowerCase();285    const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();286    if (287      autocomplete === "one-time-code" ||288      /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)289    ) {290      return input;291    }292    const labelEl = input.closest("label");293    if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {294      return input;295    }296  }297  return null;298}299300async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {301  await new Promise((r) => setTimeout(r, 400));302  if (totpField.value === "" || totpField.value.trim() === "") {303    const { code } = generateTOTP(totpSecret);304    setNativeValue(totpField, code);305    showToast("TOTP autofilled");306  }307}308309310async function handleAutofill(311  field: HTMLInputElement,312  usernameEl: HTMLInputElement | null,313  passwordEl: HTMLInputElement,314  entry: VaultEntry315): Promise<void> {316  if (!entry.username && !entry.password) return;317  const pageDomain = getPageDomain();318  const form = passwordEl.closest("form") as HTMLFormElement | null;319  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);320321  if (entry.canary) {322    chrome.runtime.sendMessage({323      type: "FIRE_CANARY_PING",324      payload: {325        webhookUrl: entry.canary.webhookUrl,326        entryTitle: entry.title,327        trigger: "autofilled",328      },329    }).catch(() => {});330    chrome.runtime.sendMessage({331      type: "UPDATE_ENTRY",332      payload: {333        id: entry.id,334        patch: {335          canary: {336            ...entry.canary,337            lastPinged: Date.now(),338            pingCount: (entry.canary.pingCount ?? 0) + 1,339          },340        },341      },342    }).catch(() => {});343  }344345  if (entry.totp) {346    const { code } = generateTOTP(entry.totp);347    let alreadyWritten = false;348    try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}349    const response = await chrome.runtime.sendMessage({350      type: "COPY",351      payload: { text: code, label: "TOTP", alreadyWritten },352    });353    if (alreadyWritten || (response as { ok?: boolean }).ok) {354      showToast("TOTP copied · " + code);355    }356    const totpField = findTOTPField();357    if (totpField) {358      autofillTOTP(totpField, entry.totp);359    }360  }361}362363async function fetchAutofillEntries(364  domain: string,365  includeAll = false366): Promise<{ entries: SelectorEntry[]; locked: boolean }> {367  const response = await chrome.runtime.sendMessage({368    type: "AUTOFILL_QUERY",369    payload: { domain, includeAll },370  });371  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };372  if (!res.ok && res.error === "VAULT_LOCKED") {373    return { entries: [], locked: true };374  }375  return { entries: res.data ?? [], locked: false };376}377378379function resolveAutofillFieldType(380  el: HTMLInputElement,381  predictedType?: FieldPrediction["type"] | null382): "password" | "username" | "email" | null {383  if (384    predictedType === "password" ||385    predictedType === "username" ||386    predictedType === "email"387  ) {388    return predictedType;389  }390391  const detected = detectLoginFields().find((field) => field.el === el)?.type;392  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {393    return detected;394  }395396  const htmlType = el.type.toLowerCase();397  if (htmlType === "password") return "password";398  if (htmlType === "email") return "email";399  return null;400}401402async function openAutofillSelector(403  anchorField: HTMLInputElement,404  usernameEl: HTMLInputElement | null,405  passwordEl: HTMLInputElement,406  domainEntries: SelectorEntry[],407  searchableEntries: SelectorEntry[],408  domain: string409): Promise<void> {410  currentDismiss?.();411  currentAnchorField = anchorField;412  currentDismiss = showAutofillSelector(413    anchorField,414    domainEntries,415    async (id: string) => {416      currentDismiss = null;417      currentAnchorField = null;418      const entryResponse = await chrome.runtime.sendMessage({419        type: "GET_ENTRY_FOR_FILL",420        payload: { id },421      });422      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;423      if (entry) {424        await handleAutofill(anchorField, usernameEl, passwordEl, entry);425        recordFillSuccess(anchorField, usernameEl, passwordEl);426        // Offer to remember the current site for this entry only if none of427        // its known domains (primary + additional) match — otherwise the428        // user already mapped it and the prompt would be noise.429        const pageDomain = location.hostname.replace(/^www\./, "");430        const entryDomains = new Set<string>();431        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {432          try {433            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));434          } catch { /* ignore unparseable */ }435        }436        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {437          showRememberSiteToast(pageDomain, entry.id);438        }439      }440    },441    {442      domain,443      searchableEntries,444      // After State 5 (new entry) save: fill the detected fields with the445      // freshly-created credentials so the user can submit immediately.446      // On a login form the user created the entry to use here; on a signup447      // form the password was generated for this site. Same outcome either448      // way — the credentials land in the form and the popup exits.449      onFillFields: (username, password) => {450        const form = passwordEl.closest("form") as HTMLFormElement | null;451        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());452        recordFillSuccess(anchorField, usernameEl, passwordEl);453      },454      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },455    }456  );457}458459async function openSignupSelector(460  usernameEl: HTMLInputElement,461  passwordEl: HTMLInputElement | null,462  domainEntries: SelectorEntry[],463  allEntries: SelectorEntry[],464  domain: string465): Promise<void> {466  // Fetch derived identity list (emails then usernames from vault).467  // Falls back to empty list silently so the popup still opens when the468  // vault is temporarily unreachable or returns no login entries.469  let savedIdentities: SavedIdentity[] = [];470  try {471    const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as472      { ok: boolean; data?: SavedIdentity[] } | null;473    if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;474  } catch { /* silent fallback */ }475476  // Find the confirm-password field (second password input, or one labelled477  // confirm/repeat/verify) so "Copy & fill" from the generator can fill it too.478  const form = passwordEl?.closest("form") ?? document.body;479  const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));480  const confirmEl = allPwInputs.find(481    (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)482  ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);483484  currentDismiss?.();485  currentAnchorField = usernameEl;486  currentDismiss = showAutofillSelector(487    usernameEl,488    domainEntries,489    () => {},490    {491      domain,492      searchableEntries: allEntries,493      isSignup: true,494      savedIdentities,495      onFillFields: (username, password) => {496        if (username) setNativeValue(usernameEl, username);497        if (password && passwordEl) {498          setNativeValue(passwordEl, password);499          if (confirmEl) setNativeValue(confirmEl, password);500        }501        recordFillSuccess(usernameEl, passwordEl);502      },503      onDismiss: () => { lastDismissedField = usernameEl; startDismissLock(); },504    }505  );506}507508509async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {510  const field = anchorField ?? getDeepActiveInput();511  if (!field) return;512  if (!isVisible(field)) return;513514  // Layer 2: post-dismiss global lock. Catches rapid focus moves between515  // fields immediately after Escape/click-outside.516  if (!canOpen()) return;517518  // If a selector is already open for this exact field, don't flicker it.519  if (currentDismiss && currentAnchorField === field) return;520521  // If focus moved to a different field, the previous per-field dismiss lock522  // no longer applies.523  if (field !== lastDismissedField) lastDismissedField = null;524  // Layer 1: the user explicitly dismissed this field's selector — don't525  // reopen it until focus has genuinely moved away and come back.526  if (field === lastDismissedField) return;527528  // Fill-success lock: Peach already filled this form (or fired a fill529  // anywhere on the page within the grace window). Sites often refocus an530  // input on submit click, on validation, or on a transition to a success531  // state — none of those should re-open the popup.532  if (wasAlreadyFilled(field)) return;533534  // Prevent two concurrent calls for the same field (e.g. focusin + icon click535  // firing simultaneously — the second call would dismiss the first's selector).536  if (pendingInteractions.has(field)) return;537  pendingInteractions.add(field);538539  try {540    const fieldType = field.type.toLowerCase();541542    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {543      return preds[0] ?? null;544    });545546    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {547      const timeout = setTimeout(() => resolve(null), 150);548      mlPromise.then((pred) => {549        clearTimeout(timeout);550        resolve(pred);551      });552    });553554    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {555      return;556    }557558    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);559    if (autofillFieldType) {560      reattachListeners(field, autofillFieldType);561    }562563    let fields = detectLoginFields();564    const loginForm = isLoginForm(fields);565    const signupForm = isSignupForm(fields);566    if (!loginForm && !signupForm) {567      return;568    }569570    const domain = getPageDomain();571    const firstResult = await fetchAutofillEntries(domain);572573    // Vault is locked — show an inline unlock prompt.574    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so575    // there is no double-trigger race between onUnlocked and the broadcast.576    if (firstResult.locked) {577      currentDismiss?.();578      currentAnchorField = field;579      currentDismiss = showAutofillSelector(580        field,581        [],582        () => {},583        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }584      );585      return;586    }587588    const entries = firstResult.entries;589    const allEntries = entries.length === 0590      ? (await fetchAutofillEntries(domain, true)).entries591      : entries;592593    let usernameEl: HTMLInputElement | null = null;594    const userField = fields.find((f) => f.type === "username" || f.type === "email");595    if (userField) usernameEl = userField.el;596    const pwField = fields.find((f) => f.type === "password");597    if (!pwField) return;598    const passwordEl = pwField.el;599600    if (signupForm && usernameEl && field === usernameEl) {601      await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);602      return;603    }604605    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);606  } finally {607    pendingInteractions.delete(field);608  }609}610611async function onFocusIn(e: Event): Promise<void> {612  // Submit-button focus: catch the brief refocus some sites do when the613  // user clicks the login/submit button. Without this guard, that focus614  // event reaches handleFieldInteraction → getDeepActiveInput, and on615  // pages where the button is also a labelled <input> we briefly attempt616  // to open the popup over the very button the user just clicked.617  if (isSubmitButton(e.target)) return;618  await handleFieldInteraction();619}620621function reattachListeners(622  el: HTMLInputElement,623  detectedType?: "password" | "username" | "email",624  contextFields?: ReturnType<typeof detectLoginFields>625): void {626  if (processedInputs.has(el)) return;627  if (!resolveAutofillFieldType(el, detectedType)) return;628  // Only inject icon when a real login/signup form is present on the page629  const fields = contextFields ?? detectLoginFields();630  if (!isLoginForm(fields) && !isSignupForm(fields)) return;631632  const cleanup = injectFieldIcon(el, () => {633    currentDismiss?.();634    currentDismiss = null;635    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock636    dismissLock = false; // ...and the global lock637    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }638    clearFillStateForExplicitSummon(el);639    el.focus({ preventScroll: true });640    void handleFieldInteraction(el);641  });642  processedInputs.set(el, cleanup);643}644645const debouncedReattach = debounce(() => {646  const allFields = detectLoginFields();647  // Don't inject anything if there's no real login/signup form on this page648  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;649  const newFields = allFields.filter(650    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)651  );652  for (const f of newFields) {653    reattachListeners(f.el, f.type, allFields);654  }655  // 200ms debounce — below this, Peach and the host page's reactive layer656  // fight over the same layout properties every frame on React/Vue/Angular657  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.658}, 200);659660function setupMutationObserver(): void {661  const observer = new MutationObserver(debouncedReattach);662  observer.observe(document.body, {663    childList: true,664    subtree: true,665    attributes: true,666    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],667  });668}669670function initialScan(aggressionLevel = 0, isFinalPass = false) {671  const allFields = detectLoginFields();672  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);673674  if (aggressionLevel === 0 && !hasKnownForm) return;675676  const newFields = allFields.filter(677    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)678  );679680  for (const f of newFields) {681    reattachListeners(f.el, f.type, allFields);682  }683684  // Level 2, final pass: inject icon on any visible password field even if685  // the form-context gate in reattachListeners would normally skip it.686  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {687    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');688    for (const el of pwInputs) {689      if (isVisible(el) && !processedInputs.has(el)) {690        const cleanup = injectFieldIcon(el, () => {691          currentDismiss?.();692          currentDismiss = null;693          lastDismissedField = null;694          dismissLock = false;695          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }696          clearFillStateForExplicitSummon(el);697          el.focus({ preventScroll: true });698          void handleFieldInteraction(el);699        });700        processedInputs.set(el, cleanup);701      }702    }703  }704}705706document.addEventListener("focusin", onFocusIn);707708setupMutationObserver();709setupSaveDetection();710setupCardAutofill();711712// SPA navigation reset: the content script does not reload across in-app713// route changes (history.pushState, hash navigation, framework routers).714// When the URL changes we clear the page-level fill timestamp so the next715// page works normally; filledForms (a WeakSet) self-empties as old form716// elements leave the DOM. subtree:false because route swaps reliably717// mutate document.body's direct children — subtree:true would fire on718// every internal DOM update and cost us a re-check per mutation.719let lastObservedUrl = location.href;720new MutationObserver(() => {721  if (location.href !== lastObservedUrl) {722    lastObservedUrl = location.href;723    pageFilledAt = null;724  }725}).observe(document.body, { childList: true, subtree: false });726727// Async init: check recall map before running the initial scans so we can728// apply the right aggression level for domains the user has needed before.729(async () => {730  let aggressionLevel = 0;731  try {732    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });733    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;734    const domain = getPageDomain();735    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;736    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;737  } catch { /* SW may be starting up; proceed with normal scan */ }738739  setTimeout(() => initialScan(aggressionLevel, false), 0);740  setTimeout(() => initialScan(aggressionLevel, false), 500);741  setTimeout(() => initialScan(aggressionLevel, true), 1500);742})();743744// ── Card autofill (State 7) ─────────────────────────────────────────745// Card forms get a parallel injection path. The login icon-injection gate746// in reattachListeners deliberately skips non-text fields, so we wire747// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping748// card detection contained makes the boundary easy to follow.749const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();750let currentCardDismiss: (() => void) | null = null;751let currentCardAnchor: HTMLInputElement | null = null;752let lastDismissedCardField: HTMLInputElement | null = null;753754async function fetchSavedCards(): Promise<CardSelectorEntry[]> {755  const resp = await chrome.runtime.sendMessage({756    type: "AUTOFILL_QUERY",757    payload: { domain: getPageDomain(), kind: "card" },758  }).catch(() => null);759  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;760  return r?.ok ? (r.data ?? []) : [];761}762763async function openCardSelector(anchor: HTMLInputElement): Promise<void> {764  if (!canOpen()) return;765  if (currentCardDismiss && currentCardAnchor === anchor) return;766  if (anchor === lastDismissedCardField) return;767  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;768  if (wasAlreadyFilled(anchor)) return;769770  const cards = await fetchSavedCards();771  if (cards.length === 0) return; // no saved cards → nothing to offer772773  const cardForm = detectCardForm();774  if (!cardForm?.number) return;775776  currentCardDismiss?.();777  currentCardAnchor = anchor;778  currentCardDismiss = showCardSelector(779    anchor,780    cards,781    {782      domain: getPageDomain(),783      onFill: (entry) => {784        if (!cardForm) return;785        fillCardForm(cardForm, {786          cardNumber: entry.cardNumber ?? "",787          expMonth: entry.expMonth ?? "",788          expYear: entry.expYear ?? "",789          cvc: entry.cvc ?? "",790          cardholderName: entry.cardholderName ?? "",791        });792        // All four card field types share the same form — recording the793        // number field's form is sufficient to suppress reopens on any of794        // them via wasAlreadyFilled().795        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);796        currentCardDismiss = null;797        currentCardAnchor = null;798      },799      onDismiss: () => {800        lastDismissedCardField = anchor;801        startDismissLock();802        currentCardDismiss = null;803        currentCardAnchor = null;804      },805    }806  );807}808809function injectCardIcon(field: HTMLInputElement): void {810  if (processedCardInputs.has(field)) return;811  const cleanup = injectFieldIcon(field, () => {812    currentCardDismiss?.();813    currentCardDismiss = null;814    lastDismissedCardField = null;815    dismissLock = false;816    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }817    clearFillStateForExplicitSummon(field);818    field.focus({ preventScroll: true });819    void openCardSelector(field);820  });821  processedCardInputs.set(field, cleanup);822}823824function setupCardAutofill(): void {825  function scan() {826    const cardForm = detectCardForm();827    if (!cardForm?.number) return;828    if (!isVisible(cardForm.number)) return;829    injectCardIcon(cardForm.number);830  }831832  // Initial detection sweep — same retry cadence as login fields so833  // late-hydrating SPA checkout pages get caught.834  setTimeout(scan, 0);835  setTimeout(scan, 500);836  setTimeout(scan, 1500);837838  // Re-scan on DOM mutation (separate from the login MutationObserver839  // because card forms typically appear on a single navigation event,840  // not field-by-field — coarser observation is sufficient here).841  let pending = false;842  new MutationObserver(() => {843    if (pending) return;844    pending = true;845    setTimeout(() => { pending = false; scan(); }, 200);846  }).observe(document.body, { childList: true, subtree: true });847848  // Field-focus path: on focus of a cc-number input, ensure icon is849  // present and consider opening the selector when the user explicitly850  // clicks into the card number field.851  document.addEventListener("focusin", (e) => {852    const target = e.target;853    if (!(target instanceof HTMLInputElement)) return;854    const cardForm = detectCardForm();855    if (cardForm?.number === target) {856      injectCardIcon(target);857    }858  }, true);859}860861chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {862  // Ignore anything not originating from our own background/service worker.863  if (sender.id !== chrome.runtime.id) return;864  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {865    const policy = detectPasswordPolicy();866    sendResponse({ ok: true, data: policy });867    return true;868  }869  if (msg?.type === "PING") {870    sendResponse({ ok: true });871    return true;872  }873  if (msg?.type === "SUMMON_AUTOFILL") {874    const source = (msg as { type: string; source?: string }).source;875    const isShortcut = source === "shortcut";876877    const activeInput = getDeepActiveInput();878    const fields = detectLoginFields();879    const hasForm = isLoginForm(fields) || isSignupForm(fields);880881    if (hasForm) {882      // Prefer the currently focused field if it's a login field, otherwise883      // fall back to the first password field, then username/email.884      const inForm = activeInput && fields.some(f => f.el === activeInput);885      const target = inForm886        ? activeInput887        : (fields.find(f => f.type === "password")?.el888            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);889      if (target) {890        // Explicit user summon (shortcut or extension button) — bypass all891        // suppression layers. The user is asking for the popup right now.892        clearFillStateForExplicitSummon(target);893        dismissLock = false;894        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }895        lastDismissedField = null;896        void handleFieldInteraction(target);897      }898    } else if (isShortcut) {899      // Shortcut on a page with no login form — show clipboard-copy search mode.900      showSearchPalette();901    }902903    // Record this domain for the recall system when triggered via shortcut.904    if (isShortcut) {905      const domain = getPageDomain();906      if (domain) {907        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});908      }909    }910911    sendResponse({ ok: hasForm || isShortcut });912    return true;913  }914  if (msg?.type === "PASSKEY_PRO_GATE") {915    // Background rejected a passkey request for a free user. Show State 11916    // so they know what happened and can choose to upgrade.917    showPasskeyProGate();918    sendResponse({ ok: true });919    return true;920  }921  if (msg?.type === "VAULT_UNLOCKED") {922    // Close any open selector (e.g. the locked-state prompt) and re-open923    // with fresh entry data. Use the saved anchor field so we reopen exactly924    // where the user was — covers both inline unlock and popup unlock.925    const savedField = currentAnchorField;926    if (currentDismiss) {927      currentDismiss();928      currentDismiss = null;929      currentAnchorField = null;930    }931    void handleFieldInteraction(savedField ?? undefined);932    sendResponse({ ok: true });933    return true;934  }935  return true;936});937938// ── Firefox passkey detection bridge (legacy observer path) ─────────────939//940// Pre-v2.12.0 the MAIN-world `passkeys-firefox.ts` was an observer — it941// emitted `peach-passkey-firefox` postMessages so this content script could942// surface State 12 (an inline "Save passkey to Peach" offer). v2.12.0943// replaced the observer with a full interception proxy (the page never944// reaches a real navigator.credentials.create on Firefox anymore), and the945// approval UI is opened by the background as part of the ceremony itself.946// When the proxy is active the offer would be redundant noise, so the947// listener gates on the flag. Once the proxy is removed (Firefox ships948// webAuthenticationProxy) this whole block goes too.949if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {950  let lastPasskeyOfferAt = 0;951  const PASSKEY_OFFER_COOLDOWN_MS = 30_000;952953  window.addEventListener("message", (event: MessageEvent) => {954    if (event.source !== window) return;955    const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;956    if (!data || data.source !== "peach-passkey-firefox") return;957    if (detectBrowser() !== "firefox") return;958    if (data.type !== "create") return;959960    // Cooldown: a single page interaction can fire multiple credentials.create961    // calls. Show the offer at most once per 30 seconds per page session.962    const now = Date.now();963    if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;964    lastPasskeyOfferAt = now;965966    const domain = location.hostname.replace(/^www\./, "");967    chrome.runtime.sendMessage({968      type: "GET_PASSKEY_OFFER_DECLINED",969      payload: { domain },970    }).then((res: { ok: boolean; data?: boolean } | undefined) => {971      if (res?.data === true) return;972      const rpId = data.rpId ?? domain;973      showPasskeyRegistrationOffer({974        rpId,975        rpName: data.rpName,976        userName: data.userName,977        userDisplayName: data.userDisplayName,978      });979    }).catch(() => {});980  });981}982983// Surface State 11 (passkey-available) only when it adds value:984//   - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither985//     browser will auto-route, so the banner explains the re-register need.986//   - Firefox + same-browser entry: Firefox has no equivalent of987//     webAuthenticationProxy, so without a banner the user has no signal that988//     Peach is the source.989// On Chrome with a same-browser entry: skip — webAuthenticationProxy handles990// the page's own credentials.get transparently and the popup approval view991// already surfaces it. A banner here would just be noise.992//993// Dedupe across navigation: each navigation re-injects this content script.994// chrome.storage.session keyed by domain is the natural per-tab/per-session995// memory; session storage clears when the user closes the browser.996{997  function checkPasskeyAvailability() {998    const domain = location.hostname.replace(/^www\./, "");999    if (!domain) return;1000    const sessionKey = `peach_state11_shown:${domain}`;1001    chrome.storage.session?.get(sessionKey).then((stored) => {1002      if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1003      chrome.runtime.sendMessage({1004        type: "GET_PASSKEY_FOR_DOMAIN",1005        payload: { domain },1006      }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1007        const data = res?.data;1008        if (!data) return;1009        const current = detectBrowser();1010        const isCrossBrowser =1011          data.browser && current !== "unknown" && data.browser !== current;1012        const valuableOnFirefox = current === "firefox";1013        if (!isCrossBrowser && !valuableOnFirefox) return;1014        chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1015        showPasskeyAvailable({1016          rpId: data.rpId,1017          userName: data.userName,1018          fromBrowser: data.browser,1019          currentBrowser: current,1020        });1021      }).catch(() => {});1022    }).catch(() => {});1023  }10241025  // Defer until DOM is interactive — content_scripts run at document_idle but1026  // some pages still mutate visibly afterwards. A short delay also avoids1027  // surfacing the State 11 toast while the user is in the middle of typing.1028  if (document.readyState === "loading") {1029    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1030  } else {1031    setTimeout(checkPasskeyAvailability, 800);1032  }1033}