index.ts

46.6 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 type { SavedIdentity, VaultEntry } from "../shared/types";3435// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value36// so we can tear down listeners if we ever need to re-process the same field.37// When the input is GC'd (SPA nav, React re-render), the map entry goes with38// it and we can re-inject without leaking the old handler.39const processedInputs = new WeakMap<HTMLInputElement, () => void>();40const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);4142let currentDismiss: (() => void) | null = null;43// Field whose selector is currently open — used to avoid dismiss+reopen flicker44let currentAnchorField: HTMLInputElement | null = null;45// Prevents two concurrent handleFieldInteraction calls for the same field46const pendingInteractions = new WeakSet<HTMLInputElement>();47// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).48// Suppresses spurious reopens until focus moves to a different field. Layer 149// of the dismissal model — see Projects.md §4.12.50let lastDismissedField: HTMLInputElement | null = null;5152// ── Dismissal lock (Layer 2) ────────────────────────────────────────53// After any user-initiated dismiss, briefly block ALL reopens regardless of54// which field is focused. Catches the case where a page rapidly moves focus55// between fields after Escape — without this, focus moving to a SECOND field56// in <100ms would re-trigger the popup before the user finished dismissing.57const DISMISS_LOCK_MS = 800;58let dismissLock = false;59let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;60// Set when the inline popup was summoned specifically for a passkey-unlock61// flow. The VAULT_UNLOCKED handler checks this to skip re-triggering autofill62// (the passkey toast handles the next step instead).63let passkeySummonActive = false;64// Set while the passkey approval toast is visible. Prevents handleFieldInteraction65// from opening the autofill selector alongside it. Cleared by a window message66// posted by inject.tsx when the toast closes (and by DISMISS_PASSKEY_TOAST).67let passkeyToastActive = false;68function startDismissLock(): void {69  dismissLock = true;70  if (dismissLockTimer) clearTimeout(dismissLockTimer);71  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);72}73function canOpen(): boolean { return !dismissLock; }7475// ── Fill-success lock ───────────────────────────────────────────────76// After Peach autofills a form, the popup must NOT reappear on the filled77// fields, on the submit button (some sites refocus it briefly), or on any78// field in that form — even when host-page DOM mutations or the form's own79// validation flow refocus an input. Implemented as a WeakSet of forms plus80// a page-level timestamp:81//   - filledForms: every form Peach has filled this page session. Survives82//     until the form leaves the DOM (WeakSet GC).83//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders84//     window for fields that aren't inside a <form> element (some SPAs).85// SPA navigation resets pageFilledAt via the urlObserver below; filledForms86// self-empties as old form elements get GC'd.87const filledForms = new WeakSet<HTMLFormElement>();88let pageFilledAt: number | null = null;89const PAGE_FILL_GRACE_MS = 3000;9091function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {92  for (const f of fields) {93    if (!f) continue;94    const form = f.closest("form");95    if (form) filledForms.add(form);96  }97  pageFilledAt = Date.now();98}99100function wasAlreadyFilled(field: HTMLInputElement): boolean {101  const form = field.closest("form");102  if (form && filledForms.has(form)) return true;103  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;104  return false;105}106107function clearFillStateForExplicitSummon(field: HTMLInputElement): void {108  const form = field.closest("form");109  if (form) filledForms.delete(form);110  pageFilledAt = null;111}112113// Some sites briefly focus the submit button when the user clicks it (visual114// feedback, blur/focus dance for validation animations). Catch those at the115// focusin layer so we don't re-trigger handleFieldInteraction for an event116// target that was never going to be a credential field anyway.117function isSubmitButton(el: EventTarget | null): boolean {118  if (!(el instanceof HTMLElement)) return false;119  if (el instanceof HTMLButtonElement && el.type !== "button") return true;120  if (el instanceof HTMLInputElement && el.type === "submit") return true;121  if (el.getAttribute("type") === "submit") return true;122  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();123  if (!text || text.length > 24) return false;124  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);125}126127function debounce<T extends (...args: unknown[]) => void>(128  fn: T,129  ms: number130): (...args: Parameters<T>) => void {131  let timer: ReturnType<typeof setTimeout>;132  return (...args: Parameters<T>) => {133    clearTimeout(timer);134    timer = setTimeout(() => fn(...args), ms);135  };136}137138function showToast(message: string): void {139  const toast = document.createElement("div");140  toast.style.cssText = `141    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);142    background: #131109; color: #F0E8D8; padding: 8px 16px;143    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;144    font-size: 11px; z-index: 2147483647; opacity: 0;145    transition: opacity 200ms ease;146    border: 1px solid rgba(240,232,216,0.07);147    pointer-events: none;148  `;149  toast.textContent = message;150  document.body.appendChild(toast);151  requestAnimationFrame(() => { toast.style.opacity = "1"; });152  setTimeout(() => {153    toast.style.opacity = "0";154    setTimeout(() => toast.remove(), 200);155  }, 2000);156}157158function showSearchPalette(): void {159  const host = document.createElement("div");160  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";161  document.body.appendChild(host);162  const shadow = host.attachShadow({ mode: "closed" });163164  const style = document.createElement("style");165  style.textContent = `166    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;167      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;168      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}169    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);170      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}171    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}172    .s{padding:8px 12px}173    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);174      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;175      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}176    .l{max-height:220px;overflow-y:auto}177    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}178    .e:hover{background:rgba(240,232,216,.06)}179    .et{font-size:12px}180    .eu{font-size:10px;color:rgba(240,232,216,.45)}181    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}182  `;183184  let allEntries: SelectorEntry[] = [];185  let query = "";186187  const panel = document.createElement("div");188  panel.className = "p";189190  const hdr = document.createElement("div");191  hdr.className = "h";192  const hdrText = document.createElement("span");193  hdrText.textContent = "No form detected — search your vault";194  const closeBtn = document.createElement("button");195  closeBtn.className = "x";196  closeBtn.textContent = "✕";197  hdr.appendChild(hdrText);198  hdr.appendChild(closeBtn);199200  const searchWrap = document.createElement("div");201  searchWrap.className = "s";202  const searchInput = document.createElement("input");203  searchInput.placeholder = "search...";204  searchWrap.appendChild(searchInput);205206  const list = document.createElement("div");207  list.className = "l";208209  panel.appendChild(hdr);210  panel.appendChild(searchWrap);211  panel.appendChild(list);212  shadow.appendChild(style);213  shadow.appendChild(panel);214215  function close() { host.remove(); }216217  closeBtn.onclick = close;218219  function onKeyDown(e: KeyboardEvent) {220    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }221  }222  document.addEventListener("keydown", onKeyDown, true);223224  function render() {225    const q = query.toLowerCase();226    const filtered = q227      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))228      : allEntries;229    list.innerHTML = "";230    if (filtered.length === 0) {231      const em = document.createElement("div");232      em.className = "em";233      em.textContent = query ? "no matches" : "vault is empty";234      list.appendChild(em);235      return;236    }237    for (const entry of filtered.slice(0, 20)) {238      const row = document.createElement("div");239      row.className = "e";240      const title = document.createElement("div");241      title.className = "et";242      title.textContent = entry.title;243      row.appendChild(title);244      if (entry.username) {245        const user = document.createElement("div");246        user.className = "eu";247        user.textContent = entry.username;248        row.appendChild(user);249      }250      row.onclick = async () => {251        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });252        const r = resp as { ok: boolean; data?: { password?: string } };253        if (r.ok && r.data?.password) {254          let alreadyWritten = false;255          try {256            await navigator.clipboard.writeText(r.data.password);257            alreadyWritten = true;258          } catch (err) {259            console.warn("[Peach] clipboard write denied:", err);260          }261          const copyResp = await chrome.runtime.sendMessage({262            type: "COPY",263            payload: { text: r.data.password, label: "Password", alreadyWritten },264          }) as { ok?: boolean } | undefined;265          if (alreadyWritten || copyResp?.ok) {266            showToast("Password copied");267          } else {268            showToast("Could not copy password — clipboard blocked");269          }270        } else {271          showToast("Could not copy password");272        }273        close();274        document.removeEventListener("keydown", onKeyDown, true);275      };276      list.appendChild(row);277    }278  }279280  searchInput.oninput = () => { query = searchInput.value; render(); };281282  fetchAutofillEntries(getPageDomain(), true).then(result => {283    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }284    allEntries = result.entries;285    render();286    searchInput.focus();287  });288}289290function findTOTPField(root: Document | Element = document): HTMLInputElement | null {291  const inputs = root.querySelectorAll<HTMLInputElement>("input");292  for (const input of inputs) {293    if (isTOTPField(input)) return input;294  }295  return null;296}297298function findSameLoginTOTPField(passwordEl: HTMLInputElement): HTMLInputElement | null {299  const form = passwordEl.closest("form");300  return findTOTPField(form ?? document);301}302303304async function handleAutofill(305  _field: HTMLInputElement,306  usernameEl: HTMLInputElement | null,307  passwordEl: HTMLInputElement | null,308  entry: VaultEntry309): Promise<HTMLInputElement | null> {310  if (!entry.username && !entry.password) return null;311  const pageDomain = getPageDomain();312  const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;313  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);314  let filledTOTPField: HTMLInputElement | null = null;315316  if (entry.canary) {317    chrome.runtime.sendMessage({318      type: "FIRE_CANARY_PING",319      payload: {320        webhookUrl: entry.canary.webhookUrl,321        entryTitle: entry.title,322        trigger: "autofilled",323      },324    }).catch(() => {});325    chrome.runtime.sendMessage({326      type: "UPDATE_ENTRY",327      payload: {328        id: entry.id,329        patch: {330          canary: {331            ...entry.canary,332            lastPinged: Date.now(),333            pingCount: (entry.canary.pingCount ?? 0) + 1,334          },335        },336      },337    }).catch(() => {});338  }339340  // The background sends a freshly-generated 6-digit code (totpCode), never the341  // base32 seed (SEV-3-C). Fill the code straight in.342  const totpCode = (entry as { totpCode?: string }).totpCode;343  if (totpCode) {344    const code = totpCode;345    const totpField = passwordEl ? findSameLoginTOTPField(passwordEl) : null;346    if (fillTOTPCode(totpField, code)) {347      filledTOTPField = totpField;348    }349    let alreadyWritten = false;350    try {351      await navigator.clipboard.writeText(code);352      alreadyWritten = true;353    } catch (err) {354      console.warn("[Peach] clipboard write denied:", err);355    }356    const response = await chrome.runtime.sendMessage({357      type: "COPY",358      payload: { text: code, label: "TOTP", alreadyWritten },359    });360    if (filledTOTPField) {361      showToast("2FA code filled");362    } else if (alreadyWritten || (response as { ok?: boolean }).ok) {363      // Don't render the live code into the light-DOM toast — the page can read364      // it from the DOM and consume the one-time code (audit LOW). The code is365      // already on the clipboard; just confirm.366      showToast("2FA code copied");367    } else {368      showToast("Could not copy TOTP — clipboard blocked");369    }370  }371372  return filledTOTPField;373}374375async function fetchAutofillEntries(376  domain: string,377  includeAll = false378): Promise<{ entries: SelectorEntry[]; locked: boolean }> {379  const response = await chrome.runtime.sendMessage({380    type: "AUTOFILL_QUERY",381    payload: { domain, includeAll },382  });383  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };384  if (!res.ok && res.error === "vault_locked") {385    return { entries: [], locked: true };386  }387  return { entries: res.data ?? [], locked: false };388}389390async function fetchTOTPEntries(391  domain: string392): Promise<{ entries: SelectorEntry[]; locked: boolean }> {393  const response = await chrome.runtime.sendMessage({394    type: "AUTOFILL_QUERY",395    payload: { domain, kind: "totp" },396  });397  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };398  if (!res.ok && res.error === "vault_locked") {399    return { entries: [], locked: true };400  }401  return { entries: res.data ?? [], locked: false };402}403404405function resolveAutofillFieldType(406  el: HTMLInputElement,407  predictedType?: FieldPrediction["type"] | null408): "password" | "username" | "email" | null {409  if (410    predictedType === "password" ||411    predictedType === "username" ||412    predictedType === "email"413  ) {414    return predictedType;415  }416417  const detected = detectLoginFields().find((field) => field.el === el)?.type;418  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {419    return detected;420  }421422  const htmlType = el.type.toLowerCase();423  if (htmlType === "password") return "password";424  if (htmlType === "email") return "email";425  return null;426}427428async function openAutofillSelector(429  anchorField: HTMLInputElement,430  usernameEl: HTMLInputElement | null,431  passwordEl: HTMLInputElement | null,432  domainEntries: SelectorEntry[],433  searchableEntries: SelectorEntry[],434  domain: string435): Promise<void> {436  // No saved entries for this site → signup/new-account mode.437  // Fetch vault identities for the identity-first surface and locate438  // the confirm-password field so "Copy & fill" can populate it too.439  const isSignup = domainEntries.length === 0;440  let savedIdentities: SavedIdentity[] | undefined;441  let confirmEl: HTMLInputElement | null = null;442  if (isSignup) {443    try {444      const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as445        { ok: boolean; data?: SavedIdentity[] } | null;446      if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;447    } catch { /* silent fallback */ }448449    const form = (passwordEl ?? usernameEl)?.closest("form") ?? document.body;450    const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));451    confirmEl = allPwInputs.find(452      (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)453    ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);454  }455456  currentDismiss?.();457  currentAnchorField = anchorField;458  currentDismiss = showAutofillSelector(459    anchorField,460    domainEntries,461    async (id: string) => {462      currentDismiss = null;463      currentAnchorField = null;464      const entryResponse = await chrome.runtime.sendMessage({465        type: "GET_ENTRY_FOR_FILL",466        payload: { id },467      });468      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;469      if (entry) {470        const filledTOTPField = await handleAutofill(anchorField, usernameEl, passwordEl, entry);471        recordFillSuccess(anchorField, usernameEl, passwordEl, filledTOTPField);472        // Offer to remember the current site for this entry only if none of473        // its known domains (primary + additional) match — otherwise the474        // user already mapped it and the prompt would be noise.475        const pageDomain = location.hostname.replace(/^www\./, "");476        const entryDomains = new Set<string>();477        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {478          try {479            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));480          } catch { /* ignore unparseable */ }481        }482        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {483          showRememberSiteToast(pageDomain, entry.id);484        }485      }486    },487    {488      domain,489      searchableEntries,490      isSignup,491      savedIdentities,492      onFillFields: (username, password) => {493        const form = (passwordEl ?? usernameEl)?.closest("form") as HTMLFormElement | null ?? null;494        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());495        if (password && confirmEl) setNativeValue(confirmEl, password);496        recordFillSuccess(anchorField, usernameEl, passwordEl);497      },498      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },499    }500  );501}502503async function openTOTPSelector(anchorField: HTMLInputElement, otpDigitBoxes?: HTMLInputElement[]): Promise<void> {504  if (!canOpen()) return;505  if (currentDismiss && currentAnchorField === anchorField) return;506  if (anchorField !== lastDismissedField) lastDismissedField = null;507  if (anchorField === lastDismissedField) return;508  if (wasAlreadyFilled(anchorField)) return;509510  const domain = getPageDomain();511  const result = await fetchTOTPEntries(domain);512513  if (result.locked) {514    currentDismiss?.();515    currentAnchorField = anchorField;516    currentDismiss = showAutofillSelector(517      anchorField,518      [],519      () => {},520      {521        domain,522        locked: true,523        onUnlocked: () => void openTOTPSelector(anchorField),524        onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },525      }526    );527    return;528  }529530  if (result.entries.length === 0) {531    lastDismissedField = anchorField;532    startDismissLock();533    showToast("No 2FA entries for this site — add a code in Peach first");534    return;535  }536537  currentDismiss?.();538  currentAnchorField = anchorField;539  currentDismiss = showTOTPSelector(540    anchorField,541    result.entries,542    async (id: string) => {543      try {544        const entryResponse = await chrome.runtime.sendMessage({545          type: "GET_ENTRY_FOR_FILL",546          payload: { id },547        }).catch(() => null) as { ok: boolean; data?: VaultEntry } | null;548        const entry = entryResponse?.ok ? entryResponse.data : undefined;549        const code = (entry as { totpCode?: string } | undefined)?.totpCode;550        if (!code) return;551        if (otpDigitBoxes && otpDigitBoxes.length > 1) {552          fillOTPDigitBoxes(otpDigitBoxes, code);553        } else {554          setNativeValue(anchorField, code);555        }556        recordFillSuccess(anchorField);557        showToast("2FA code filled");558      } finally {559        currentDismiss = null;560        currentAnchorField = null;561      }562    },563    {564      domain,565      onDismiss: () => {566        lastDismissedField = anchorField;567        startDismissLock();568        currentDismiss = null;569        currentAnchorField = null;570      },571    }572  );573}574575576async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {577  const field = anchorField ?? getDeepActiveInput();578  if (!field) return;579  if (!isVisible(field)) return;580581  // Passkey toast is visible — don't open the credential selector alongside it.582  if (passkeyToastActive) return;583584  // Layer 2: post-dismiss global lock. Catches rapid focus moves between585  // fields immediately after Escape/click-outside.586  if (!canOpen()) return;587588  // If a selector is already open for this exact field, don't flicker it.589  if (currentDismiss && currentAnchorField === field) return;590591  // If focus moved to a different field, the previous per-field dismiss lock592  // no longer applies.593  if (field !== lastDismissedField) lastDismissedField = null;594  // Layer 1: the user explicitly dismissed this field's selector — don't595  // reopen it until focus has genuinely moved away and come back.596  if (field === lastDismissedField) return;597598  // Fill-success lock: Peach already filled this form (or fired a fill599  // anywhere on the page within the grace window). Sites often refocus an600  // input on submit click, on validation, or on a transition to a success601  // state — none of those should re-open the popup.602  if (wasAlreadyFilled(field)) return;603604  // Prevent two concurrent calls for the same field (e.g. focusin + icon click605  // firing simultaneously — the second call would dismiss the first's selector).606  if (pendingInteractions.has(field)) return;607  pendingInteractions.add(field);608609  try {610    // Multi-digit OTP entry: individual maxLength=1 boxes get no icon (too small)611    // but the TOTP selector opens on focus and fills every box at once.612    const otpGroup = findOTPDigitBoxGroup(field);613    if (otpGroup) {614      await openTOTPSelector(otpGroup[0]!, otpGroup);615      return;616    }617618    if (isTOTPField(field)) {619      const formFields = detectLoginFields();620      if (!isLoginForm(formFields) && !isSignupForm(formFields)) {621        await openTOTPSelector(field);622        return;623      }624    }625626    const fieldType = field.type.toLowerCase();627628    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {629      return preds[0] ?? null;630    });631632    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {633      const timeout = setTimeout(() => resolve(null), 150);634      mlPromise.then((pred) => {635        clearTimeout(timeout);636        resolve(pred);637      });638    });639640    if (passkeyToastActive) return;641642    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {643      return;644    }645646    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);647    if (autofillFieldType) {648      reattachListeners(field, autofillFieldType);649    }650651    let fields = detectLoginFields();652    if (!isAnyCredentialForm(fields)) {653      return;654    }655656    const domain = getPageDomain();657    const firstResult = await fetchAutofillEntries(domain);658    if (passkeyToastActive) return;659660    // Vault is locked — show an inline unlock prompt.661    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so662    // there is no double-trigger race between onUnlocked and the broadcast.663    if (firstResult.locked) {664      currentDismiss?.();665      currentAnchorField = field;666      currentDismiss = showAutofillSelector(667        field,668        [],669        () => {},670        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }671      );672      return;673    }674675    const entries = firstResult.entries;676    // Always fetch the vault-wide list so the inline popup's search affordance677    // can reach entries that don't match this domain — the user may have a678    // valid login filed under a different URL (e.g. corp account on a vanity679    // domain) and still want to fill it here.680    const allEntries = (await fetchAutofillEntries(domain, true)).entries;681682    if (passkeyToastActive) return;683684    let usernameEl: HTMLInputElement | null = null;685    const userField = fields.find((f) => f.type === "username" || f.type === "email");686    if (userField) usernameEl = userField.el;687    const pwField = fields.find((f) => f.type === "password");688    // For email-first flows there is no password field on this step — that is expected.689    if (!pwField && !isEmailFirstForm(fields)) return;690    const passwordEl = pwField?.el ?? null;691692    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);693  } finally {694    pendingInteractions.delete(field);695  }696}697698async function onFocusIn(e: Event): Promise<void> {699  // Submit-button focus: catch the brief refocus some sites do when the700  // user clicks the login/submit button. Without this guard, that focus701  // event reaches handleFieldInteraction → getDeepActiveInput, and on702  // pages where the button is also a labelled <input> we briefly attempt703  // to open the popup over the very button the user just clicked.704  if (isSubmitButton(e.target)) return;705  await handleFieldInteraction();706}707708function reattachListeners(709  el: HTMLInputElement,710  detectedType?: "password" | "username" | "email",711  contextFields?: ReturnType<typeof detectLoginFields>712): void {713  if (processedInputs.has(el)) return;714  if (!resolveAutofillFieldType(el, detectedType)) return;715  // Only inject icon when a credential form is present on the page716  const fields = contextFields ?? detectLoginFields();717  if (!isAnyCredentialForm(fields)) return;718719  const cleanup = injectFieldIcon(el, () => {720    currentDismiss?.();721    currentDismiss = null;722    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock723    dismissLock = false; // ...and the global lock724    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }725    clearFillStateForExplicitSummon(el);726    el.focus({ preventScroll: true });727    void handleFieldInteraction(el);728  });729  processedInputs.set(el, cleanup);730}731732const debouncedReattach = debounce(() => {733  const allFields = detectLoginFields();734  if (!isAnyCredentialForm(allFields)) return;735  const newFields = allFields.filter(736    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)737  );738  for (const f of newFields) {739    reattachListeners(f.el, f.type, allFields);740  }741  // 200ms debounce — below this, Peach and the host page's reactive layer742  // fight over the same layout properties every frame on React/Vue/Angular743  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.744}, 200);745746function setupMutationObserver(): void {747  const observer = new MutationObserver(debouncedReattach);748  observer.observe(document.body, {749    childList: true,750    subtree: true,751    attributes: true,752    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],753  });754}755756function initialScan(aggressionLevel = 0, isFinalPass = false) {757  const allFields = detectLoginFields();758  const hasKnownForm = isAnyCredentialForm(allFields);759760  if (aggressionLevel === 0 && !hasKnownForm) return;761762  const newFields = allFields.filter(763    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)764  );765766  for (const f of newFields) {767    reattachListeners(f.el, f.type, allFields);768  }769770  // Level 2, final pass: inject icon on any visible password field even if771  // the form-context gate in reattachListeners would normally skip it.772  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {773    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');774    for (const el of pwInputs) {775      if (isVisible(el) && !processedInputs.has(el)) {776        const cleanup = injectFieldIcon(el, () => {777          currentDismiss?.();778          currentDismiss = null;779          lastDismissedField = null;780          dismissLock = false;781          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }782          clearFillStateForExplicitSummon(el);783          el.focus({ preventScroll: true });784          void handleFieldInteraction(el);785        });786        processedInputs.set(el, cleanup);787      }788    }789  }790}791792// ── TOTP-only fields ───────────────────────────────────────────────────────793// After a username/password submission, many sites swap the whole form for a794// lone "verification code" input. The credential selector intentionally gates795// on login/signup forms, so TOTP fields need a narrow path of their own.796const processedTOTPInputs = new WeakMap<HTMLInputElement, () => void>();797798function hasLoginOrSignupForm(): boolean {799  const fields = detectLoginFields();800  return isAnyCredentialForm(fields);801}802803function injectTOTPFieldIcon(field: HTMLInputElement): void {804  if (processedTOTPInputs.has(field)) return;805  const cleanup = injectFieldIcon(field, () => {806    currentDismiss?.();807    currentDismiss = null;808    currentAnchorField = null;809    lastDismissedField = null;810    dismissLock = false;811    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }812    clearFillStateForExplicitSummon(field);813    field.focus({ preventScroll: true });814    void openTOTPSelector(field);815  });816  processedTOTPInputs.set(field, cleanup);817}818819function scanTOTPFields(): void {820  if (hasLoginOrSignupForm()) return;821  const inputs = document.querySelectorAll<HTMLInputElement>("input");822  for (const input of inputs) {823    if (!isTOTPField(input)) continue;824    injectTOTPFieldIcon(input);825  }826}827828function setupTOTPAutofill(): void {829  setTimeout(scanTOTPFields, 0);830  setTimeout(scanTOTPFields, 500);831  setTimeout(scanTOTPFields, 1500);832833  const debouncedScan = debounce(scanTOTPFields, 200);834  new MutationObserver(debouncedScan).observe(document.body, {835    childList: true,836    subtree: true,837    attributes: true,838    attributeFilter: ["autocomplete", "name", "id", "placeholder", "hidden"],839  });840841  document.addEventListener("focusin", (e) => {842    const target = e.target;843    if (!(target instanceof HTMLInputElement)) return;844    if (hasLoginOrSignupForm()) return;845    if (!isTOTPField(target)) return;846    injectTOTPFieldIcon(target);847  }, true);848}849850document.addEventListener("focusin", onFocusIn);851852setupMutationObserver();853setupTOTPAutofill();854setupSaveDetection();855setupCardAutofill();856857// SPA navigation reset: the content script does not reload across in-app858// route changes (history.pushState, hash navigation, framework routers).859// When the URL changes we clear the page-level fill timestamp so the next860// page works normally; filledForms (a WeakSet) self-empties as old form861// elements leave the DOM. subtree:false because route swaps reliably862// mutate document.body's direct children — subtree:true would fire on863// every internal DOM update and cost us a re-check per mutation.864let lastObservedUrl = location.href;865new MutationObserver(() => {866  if (location.href !== lastObservedUrl) {867    lastObservedUrl = location.href;868    pageFilledAt = null;869  }870}).observe(document.body, { childList: true, subtree: false });871872// Async init: check recall map before running the initial scans so we can873// apply the right aggression level for domains the user has needed before.874(async () => {875  let aggressionLevel = 0;876  try {877    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });878    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;879    const domain = getPageDomain();880    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;881    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;882  } catch { /* SW may be starting up; proceed with normal scan */ }883884  setTimeout(() => initialScan(aggressionLevel, false), 0);885  setTimeout(() => initialScan(aggressionLevel, false), 500);886  setTimeout(() => initialScan(aggressionLevel, true), 1500);887})();888889// ── Card autofill (State 7) ─────────────────────────────────────────890// Card forms get a parallel injection path. The login icon-injection gate891// in reattachListeners deliberately skips non-text fields, so we wire892// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping893// card detection contained makes the boundary easy to follow.894const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();895let currentCardDismiss: (() => void) | null = null;896let currentCardAnchor: HTMLInputElement | null = null;897let lastDismissedCardField: HTMLInputElement | null = null;898899async function fetchSavedCards(): Promise<CardSelectorEntry[]> {900  const resp = await chrome.runtime.sendMessage({901    type: "AUTOFILL_QUERY",902    payload: { domain: getPageDomain(), kind: "card" },903  }).catch(() => null);904  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;905  return r?.ok ? (r.data ?? []) : [];906}907908async function openCardSelector(anchor: HTMLInputElement): Promise<void> {909  if (!canOpen()) return;910  if (currentCardDismiss && currentCardAnchor === anchor) return;911  if (anchor === lastDismissedCardField) return;912  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;913  if (wasAlreadyFilled(anchor)) return;914915  const cards = await fetchSavedCards();916  if (cards.length === 0) return; // no saved cards → nothing to offer917918  const cardForm = detectCardForm();919  if (!cardForm?.number) return;920921  currentCardDismiss?.();922  currentCardAnchor = anchor;923  currentCardDismiss = showCardSelector(924    anchor,925    cards,926    {927      domain: getPageDomain(),928      onFill: (entry) => {929        if (!cardForm) return;930        fillCardForm(cardForm, {931          cardNumber: entry.cardNumber ?? "",932          expMonth: entry.expMonth ?? "",933          expYear: entry.expYear ?? "",934          cvc: entry.cvc ?? "",935          cardholderName: entry.cardholderName ?? "",936        });937        // All four card field types share the same form — recording the938        // number field's form is sufficient to suppress reopens on any of939        // them via wasAlreadyFilled().940        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);941        currentCardDismiss = null;942        currentCardAnchor = null;943      },944      onDismiss: () => {945        lastDismissedCardField = anchor;946        startDismissLock();947        currentCardDismiss = null;948        currentCardAnchor = null;949      },950    }951  );952}953954function injectCardIcon(field: HTMLInputElement): void {955  if (processedCardInputs.has(field)) return;956  const cleanup = injectFieldIcon(field, () => {957    currentCardDismiss?.();958    currentCardDismiss = null;959    lastDismissedCardField = null;960    dismissLock = false;961    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }962    clearFillStateForExplicitSummon(field);963    field.focus({ preventScroll: true });964    void openCardSelector(field);965  });966  processedCardInputs.set(field, cleanup);967}968969function setupCardAutofill(): void {970  function scan() {971    const cardForm = detectCardForm();972    if (!cardForm?.number) return;973    if (!isVisible(cardForm.number)) return;974    injectCardIcon(cardForm.number);975  }976977  // Initial detection sweep — same retry cadence as login fields so978  // late-hydrating SPA checkout pages get caught.979  setTimeout(scan, 0);980  setTimeout(scan, 500);981  setTimeout(scan, 1500);982983  // Re-scan on DOM mutation (separate from the login MutationObserver984  // because card forms typically appear on a single navigation event,985  // not field-by-field — coarser observation is sufficient here).986  let pending = false;987  new MutationObserver(() => {988    if (pending) return;989    pending = true;990    setTimeout(() => { pending = false; scan(); }, 200);991  }).observe(document.body, { childList: true, subtree: true });992993  // Field-focus path: on focus of a cc-number input, ensure icon is994  // present and consider opening the selector when the user explicitly995  // clicks into the card number field.996  document.addEventListener("focusin", (e) => {997    const target = e.target;998    if (!(target instanceof HTMLInputElement)) return;999    const cardForm = detectCardForm();1000    if (cardForm?.number === target) {1001      injectCardIcon(target);1002    }1003  }, true);1004}10051006chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {1007  // Ignore anything not originating from our own background/service worker.1008  if (sender.id !== chrome.runtime.id) return;1009  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {1010    const policy = detectPasswordPolicy();1011    sendResponse({ ok: true, data: policy });1012    return true;1013  }1014  if (msg?.type === "PING") {1015    sendResponse({ ok: true });1016    return true;1017  }1018  if (msg?.type === "SUMMON_AUTOFILL") {1019    const source = (msg as { type: string; source?: string }).source;1020    const isShortcut = source === "shortcut";1021    const isPasskeyUnlock = source === "passkey-unlock";10221023    const activeInput = getDeepActiveInput();1024    const fields = detectLoginFields();1025    const hasForm = isAnyCredentialForm(fields);10261027    if (hasForm) {1028      // Prefer the currently focused field if it's a login field, otherwise1029      // fall back to the first password field, then username/email.1030      const inForm = activeInput && fields.some(f => f.el === activeInput);1031      const target = inForm1032        ? activeInput1033        : (fields.find(f => f.type === "password")?.el1034            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);1035      if (target) {1036        // Explicit user summon (shortcut or extension button) — bypass all1037        // suppression layers. The user is asking for the popup right now.1038        clearFillStateForExplicitSummon(target);1039        dismissLock = false;1040        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }1041        lastDismissedField = null;1042        void handleFieldInteraction(target);1043      }1044    } else if (isPasskeyUnlock) {1045      // Vault is locked during a passkey GET request. Show the inline unlock1046      // prompt anchored to whatever element is focused on the page (typically1047      // the passkey/sign-in button the user just tapped).1048      const anchor = (document.activeElement instanceof HTMLElement && document.activeElement !== document.body)1049        ? document.activeElement as unknown as HTMLInputElement1050        : null;1051      if (anchor) {1052        currentDismiss?.();1053        currentAnchorField = null;1054        passkeySummonActive = true;1055        currentDismiss = showAutofillSelector(anchor, [], () => {}, {1056          domain: getPageDomain(),1057          locked: true,1058          onDismiss: () => { passkeySummonActive = false; },1059        });1060      }1061    } else if (isShortcut) {1062      // Shortcut on a page with no login form — show clipboard-copy search mode.1063      showSearchPalette();1064    }10651066    // Record this domain for the recall system when triggered via shortcut.1067    if (isShortcut) {1068      const domain = getPageDomain();1069      if (domain) {1070        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});1071      }1072    }10731074    sendResponse({ ok: hasForm || isShortcut || isPasskeyUnlock });1075    return true;1076  }1077  if (msg?.type === "PASSKEY_PRO_GATE") {1078    // Background rejected a passkey request for a free user. Show State 111079    // so they know what happened and can choose to upgrade.1080    showPasskeyProGate();1081    sendResponse({ ok: true });1082    return true;1083  }1084  if (msg?.type === "SHOW_PASSKEY_TOAST") {1085    // Block autofill selector for the lifetime of the toast and dismiss anything open.1086    passkeyToastActive = true;1087    if (currentDismiss) {1088      currentDismiss();1089      currentDismiss = null;1090      currentAnchorField = null;1091    }1092    return false; // inject.tsx owns the toast and calls sendResponse1093  }1094  if (msg?.type === "DISMISS_PASSKEY_TOAST") {1095    passkeyToastActive = false;1096    return false; // inject.tsx handles the actual dismissal1097  }1098  if (msg?.type === "VAULT_UNLOCKED") {1099    if (passkeySummonActive) {1100      // This unlock was for a pending passkey GET request. Just dismiss the1101      // inline popup — the passkey approval toast takes over from here.1102      passkeySummonActive = false;1103      if (currentDismiss) {1104        currentDismiss();1105        currentDismiss = null;1106        currentAnchorField = null;1107      }1108      sendResponse({ ok: true });1109      return true;1110    }1111    // Normal autofill path: close the locked-state prompt and re-open with1112    // fresh entry data at the same anchor field.1113    const savedField = currentAnchorField;1114    if (currentDismiss) {1115      currentDismiss();1116      currentDismiss = null;1117      currentAnchorField = null;1118    }1119    void handleFieldInteraction(savedField ?? undefined);1120    sendResponse({ ok: true });1121    return true;1122  }1123  return true;1124});11251126// inject.tsx posts this when the passkey toast closes (approve, deny, or timeout)1127// so we know it's safe to allow autofill again.1128window.addEventListener("message", (e: MessageEvent) => {1129  // Reject postMessages from cross-frame senders — only the same window's1130  // injected toast may flip this flag.1131  if (e.source !== window) return;1132  const d = e.data as { source?: string; type?: string } | undefined;1133  if (d?.source === "peach-passkey-toast" && d?.type === "toast-closed") {1134    passkeyToastActive = false;1135  }1136});11371138// ── Firefox passkey detection bridge (legacy observer path) ─────────────1139//1140// Pre-v2.12.0 the MAIN-world `passkeys-firefox.ts` was an observer — it1141// emitted `peach-passkey-firefox` postMessages so this content script could1142// surface State 12 (an inline "Save passkey to Peach" offer). v2.12.01143// replaced the observer with a full interception proxy (the page never1144// reaches a real navigator.credentials.create on Firefox anymore), and the1145// approval UI is opened by the background as part of the ceremony itself.1146// When the proxy is active the offer would be redundant noise, so the1147// listener gates on the flag. Once the proxy is removed (Firefox ships1148// webAuthenticationProxy) this whole block goes too.1149if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY) {1150  let lastPasskeyOfferAt = 0;1151  const PASSKEY_OFFER_COOLDOWN_MS = 30_000;11521153  window.addEventListener("message", (event: MessageEvent) => {1154    if (event.source !== window) return;1155    const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;1156    if (!data || data.source !== "peach-passkey-firefox") return;1157    if (detectBrowser() !== "firefox") return;1158    if (data.type !== "create") return;11591160    // Cooldown: a single page interaction can fire multiple credentials.create1161    // calls. Show the offer at most once per 30 seconds per page session.1162    const now = Date.now();1163    if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;1164    lastPasskeyOfferAt = now;11651166    const domain = location.hostname.replace(/^www\./, "");1167    chrome.runtime.sendMessage({1168      type: "GET_PASSKEY_OFFER_DECLINED",1169      payload: { domain },1170    }).then((res: { ok: boolean; data?: boolean } | undefined) => {1171      if (res?.data === true) return;1172      const rpId = data.rpId ?? domain;1173      showPasskeyRegistrationOffer({1174        rpId,1175        rpName: data.rpName,1176        userName: data.userName,1177        userDisplayName: data.userDisplayName,1178      });1179    }).catch(() => {});1180  });1181}11821183// Surface State 11 (passkey-available) only when it adds value:1184//   - Cross-browser entry: Chrome passkey on Firefox or vice versa — neither1185//     browser will auto-route, so the banner explains the re-register need.1186//   - Firefox + same-browser entry: Firefox has no equivalent of1187//     webAuthenticationProxy, so without a banner the user has no signal that1188//     Peach is the source.1189// On Chrome with a same-browser entry: skip — webAuthenticationProxy handles1190// the page's own credentials.get transparently and the popup approval view1191// already surfaces it. A banner here would just be noise.1192//1193// Dedupe across navigation: each navigation re-injects this content script.1194// chrome.storage.session keyed by domain is the natural per-tab/per-session1195// memory; session storage clears when the user closes the browser.1196{1197  function checkPasskeyAvailability() {1198    const domain = location.hostname.replace(/^www\./, "");1199    if (!domain) return;1200    const sessionKey = `peach_state11_shown:${domain}`;1201    chrome.storage.session?.get(sessionKey).then((stored) => {1202      if (stored && (stored as Record<string, unknown>)[sessionKey]) return;1203      chrome.runtime.sendMessage({1204        type: "GET_PASSKEY_FOR_DOMAIN",1205        payload: { domain },1206      }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {1207        const data = res?.data;1208        if (!data) return;1209        const current = detectBrowser();1210        const isCrossBrowser =1211          data.browser && current !== "unknown" && data.browser !== current;1212        const valuableOnFirefox = current === "firefox";1213        if (!isCrossBrowser && !valuableOnFirefox) return;1214        chrome.storage.session?.set({ [sessionKey]: Date.now() }).catch(() => {});1215        showPasskeyAvailable({1216          rpId: data.rpId,1217          userName: data.userName,1218          fromBrowser: data.browser,1219          currentBrowser: current,1220        });1221      }).catch(() => {});1222    }).catch(() => {});1223  }12241225  // Defer until DOM is interactive — content_scripts run at document_idle but1226  // some pages still mutate visibly afterwards. A short delay also avoids1227  // surfacing the State 11 toast while the user is in the middle of typing.1228  if (document.readyState === "loading") {1229    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1230  } else {1231    setTimeout(checkPasskeyAvailability, 800);1232  }1233}