index.ts

38.2 KB · raw

1import {2  detectCardForm,3  detectLoginFields,4  getDeepActiveInput,5  getPageDomain,6  isLoginForm,7  isSignupForm,8  isVisible,9} from "./detect";10import {11  CardSelectorEntry,12  injectFieldIcon,13  observeAnchorPosition,14  SelectorEntry,15  showAutofillSelector,16  showCardSelector,17  showPasskeyAvailable,18  showPasskeyProGate,19  showPasskeyRegistrationOffer,20  showRememberSiteToast,21} from "./inject";22import { detectBrowser } from "../shared/browser";23import { fillCardForm, fillFields } from "./fill";24import { setupSaveDetection } from "./save";25import { contentMLDetector } from "./content-ml-detector";26import { detectPasswordPolicy } from "./policy";27import type { FieldPrediction } from "../shared/ml";28import { generateTOTP } from "../crypto/totp";29import type { SavedIdentity, VaultEntry } from "../shared/types";3031// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value32// so we can tear down listeners if we ever need to re-process the same field.33// When the input is GC'd (SPA nav, React re-render), the map entry goes with34// it and we can re-inject without leaking the old handler.35const processedInputs = new WeakMap<HTMLInputElement, () => void>();36const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3738let currentDismiss: (() => void) | null = null;39// Field whose selector is currently open — used to avoid dismiss+reopen flicker40let currentAnchorField: HTMLInputElement | null = null;41// Prevents two concurrent handleFieldInteraction calls for the same field42const pendingInteractions = new WeakSet<HTMLInputElement>();43// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).44// Suppresses spurious reopens until focus moves to a different field. Layer 145// of the dismissal model — see Projects.md §4.12.46let lastDismissedField: HTMLInputElement | null = null;4748// ── Dismissal lock (Layer 2) ────────────────────────────────────────49// After any user-initiated dismiss, briefly block ALL reopens regardless of50// which field is focused. Catches the case where a page rapidly moves focus51// between fields after Escape — without this, focus moving to a SECOND field52// in <100ms would re-trigger the popup before the user finished dismissing.53const DISMISS_LOCK_MS = 800;54let dismissLock = false;55let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;56function startDismissLock(): void {57  dismissLock = true;58  if (dismissLockTimer) clearTimeout(dismissLockTimer);59  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);60}61function canOpen(): boolean { return !dismissLock; }6263// ── Fill-success lock ───────────────────────────────────────────────64// After Peach autofills a form, the popup must NOT reappear on the filled65// fields, on the submit button (some sites refocus it briefly), or on any66// field in that form — even when host-page DOM mutations or the form's own67// validation flow refocus an input. Implemented as a WeakSet of forms plus68// a page-level timestamp:69//   - filledForms: every form Peach has filled this page session. Survives70//     until the form leaves the DOM (WeakSet GC).71//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders72//     window for fields that aren't inside a <form> element (some SPAs).73// SPA navigation resets pageFilledAt via the urlObserver below; filledForms74// self-empties as old form elements get GC'd.75const filledForms = new WeakSet<HTMLFormElement>();76let pageFilledAt: number | null = null;77const PAGE_FILL_GRACE_MS = 3000;7879function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {80  for (const f of fields) {81    if (!f) continue;82    const form = f.closest("form");83    if (form) filledForms.add(form);84  }85  pageFilledAt = Date.now();86}8788function wasAlreadyFilled(field: HTMLInputElement): boolean {89  const form = field.closest("form");90  if (form && filledForms.has(form)) return true;91  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;92  return false;93}9495function clearFillStateForExplicitSummon(field: HTMLInputElement): void {96  const form = field.closest("form");97  if (form) filledForms.delete(form);98  pageFilledAt = null;99}100101// Some sites briefly focus the submit button when the user clicks it (visual102// feedback, blur/focus dance for validation animations). Catch those at the103// focusin layer so we don't re-trigger handleFieldInteraction for an event104// target that was never going to be a credential field anyway.105function isSubmitButton(el: EventTarget | null): boolean {106  if (!(el instanceof HTMLElement)) return false;107  if (el instanceof HTMLButtonElement && el.type !== "button") return true;108  if (el instanceof HTMLInputElement && el.type === "submit") return true;109  if (el.getAttribute("type") === "submit") return true;110  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();111  if (!text || text.length > 24) return false;112  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);113}114115function debounce<T extends (...args: unknown[]) => void>(116  fn: T,117  ms: number118): (...args: Parameters<T>) => void {119  let timer: ReturnType<typeof setTimeout>;120  return (...args: Parameters<T>) => {121    clearTimeout(timer);122    timer = setTimeout(() => fn(...args), ms);123  };124}125126function showToast(message: string): void {127  const toast = document.createElement("div");128  toast.style.cssText = `129    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);130    background: #131109; color: #F0E8D8; padding: 8px 16px;131    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;132    font-size: 11px; z-index: 2147483647; opacity: 0;133    transition: opacity 200ms ease;134    border: 1px solid rgba(240,232,216,0.07);135    pointer-events: none;136  `;137  toast.textContent = message;138  document.body.appendChild(toast);139  requestAnimationFrame(() => { toast.style.opacity = "1"; });140  setTimeout(() => {141    toast.style.opacity = "0";142    setTimeout(() => toast.remove(), 200);143  }, 2000);144}145146function showSearchPalette(): void {147  const host = document.createElement("div");148  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";149  document.body.appendChild(host);150  const shadow = host.attachShadow({ mode: "closed" });151152  const style = document.createElement("style");153  style.textContent = `154    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;155      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;156      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}157    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);158      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}159    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}160    .s{padding:8px 12px}161    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);162      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;163      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}164    .l{max-height:220px;overflow-y:auto}165    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}166    .e:hover{background:rgba(240,232,216,.06)}167    .et{font-size:12px}168    .eu{font-size:10px;color:rgba(240,232,216,.45)}169    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}170  `;171172  let allEntries: SelectorEntry[] = [];173  let query = "";174175  const panel = document.createElement("div");176  panel.className = "p";177178  const hdr = document.createElement("div");179  hdr.className = "h";180  const hdrText = document.createElement("span");181  hdrText.textContent = "No form detected — search your vault";182  const closeBtn = document.createElement("button");183  closeBtn.className = "x";184  closeBtn.textContent = "✕";185  hdr.appendChild(hdrText);186  hdr.appendChild(closeBtn);187188  const searchWrap = document.createElement("div");189  searchWrap.className = "s";190  const searchInput = document.createElement("input");191  searchInput.placeholder = "search...";192  searchWrap.appendChild(searchInput);193194  const list = document.createElement("div");195  list.className = "l";196197  panel.appendChild(hdr);198  panel.appendChild(searchWrap);199  panel.appendChild(list);200  shadow.appendChild(style);201  shadow.appendChild(panel);202203  function close() { host.remove(); }204205  closeBtn.onclick = close;206207  function onKeyDown(e: KeyboardEvent) {208    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }209  }210  document.addEventListener("keydown", onKeyDown, true);211212  function render() {213    const q = query.toLowerCase();214    const filtered = q215      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))216      : allEntries;217    list.innerHTML = "";218    if (filtered.length === 0) {219      const em = document.createElement("div");220      em.className = "em";221      em.textContent = query ? "no matches" : "vault is empty";222      list.appendChild(em);223      return;224    }225    for (const entry of filtered.slice(0, 20)) {226      const row = document.createElement("div");227      row.className = "e";228      const title = document.createElement("div");229      title.className = "et";230      title.textContent = entry.title;231      row.appendChild(title);232      if (entry.username) {233        const user = document.createElement("div");234        user.className = "eu";235        user.textContent = entry.username;236        row.appendChild(user);237      }238      row.onclick = async () => {239        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });240        const r = resp as { ok: boolean; data?: { password?: string } };241        if (r.ok && r.data?.password) {242          let alreadyWritten = false;243          try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}244          await chrome.runtime.sendMessage({245            type: "COPY",246            payload: { text: r.data.password, label: "Password", alreadyWritten },247          });248          showToast("Password copied");249        } else {250          showToast("Could not copy password");251        }252        close();253        document.removeEventListener("keydown", onKeyDown, true);254      };255      list.appendChild(row);256    }257  }258259  searchInput.oninput = () => { query = searchInput.value; render(); };260261  fetchAutofillEntries(getPageDomain(), true).then(result => {262    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }263    allEntries = result.entries;264    render();265    searchInput.focus();266  });267}268269function setNativeValue(el: HTMLInputElement, value: string): void {270  const nativeSetter = Object.getOwnPropertyDescriptor(271    HTMLInputElement.prototype, "value"272  )!.set!;273  nativeSetter.call(el, value);274  el.dispatchEvent(new Event("input", { bubbles: true }));275  el.dispatchEvent(new Event("change", { bubbles: true }));276}277278function findTOTPField(): HTMLInputElement | null {279  const inputs = document.querySelectorAll<HTMLInputElement>("input");280  for (const input of inputs) {281    if (!isVisible(input)) continue;282    const autocomplete = input.autocomplete.toLowerCase();283    const nameId = (input.name + input.id).toLowerCase();284    const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();285    if (286      autocomplete === "one-time-code" ||287      /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)288    ) {289      return input;290    }291    const labelEl = input.closest("label");292    if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {293      return input;294    }295  }296  return null;297}298299async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {300  await new Promise((r) => setTimeout(r, 400));301  if (totpField.value === "" || totpField.value.trim() === "") {302    const { code } = generateTOTP(totpSecret);303    setNativeValue(totpField, code);304    showToast("TOTP autofilled");305  }306}307308309async function handleAutofill(310  field: HTMLInputElement,311  usernameEl: HTMLInputElement | null,312  passwordEl: HTMLInputElement,313  entry: VaultEntry314): Promise<void> {315  if (!entry.username && !entry.password) return;316  const pageDomain = getPageDomain();317  const form = passwordEl.closest("form") as HTMLFormElement | null;318  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);319320  if (entry.canary) {321    chrome.runtime.sendMessage({322      type: "FIRE_CANARY_PING",323      payload: {324        webhookUrl: entry.canary.webhookUrl,325        entryTitle: entry.title,326        trigger: "autofilled",327      },328    }).catch(() => {});329    chrome.runtime.sendMessage({330      type: "UPDATE_ENTRY",331      payload: {332        id: entry.id,333        patch: {334          canary: {335            ...entry.canary,336            lastPinged: Date.now(),337            pingCount: (entry.canary.pingCount ?? 0) + 1,338          },339        },340      },341    }).catch(() => {});342  }343344  if (entry.totp) {345    const { code } = generateTOTP(entry.totp);346    let alreadyWritten = false;347    try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}348    const response = await chrome.runtime.sendMessage({349      type: "COPY",350      payload: { text: code, label: "TOTP", alreadyWritten },351    });352    if (alreadyWritten || (response as { ok?: boolean }).ok) {353      showToast("TOTP copied · " + code);354    }355    const totpField = findTOTPField();356    if (totpField) {357      autofillTOTP(totpField, entry.totp);358    }359  }360}361362async function fetchAutofillEntries(363  domain: string,364  includeAll = false365): Promise<{ entries: SelectorEntry[]; locked: boolean }> {366  const response = await chrome.runtime.sendMessage({367    type: "AUTOFILL_QUERY",368    payload: { domain, includeAll },369  });370  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };371  if (!res.ok && res.error === "VAULT_LOCKED") {372    return { entries: [], locked: true };373  }374  return { entries: res.data ?? [], locked: false };375}376377378function resolveAutofillFieldType(379  el: HTMLInputElement,380  predictedType?: FieldPrediction["type"] | null381): "password" | "username" | "email" | null {382  if (383    predictedType === "password" ||384    predictedType === "username" ||385    predictedType === "email"386  ) {387    return predictedType;388  }389390  const detected = detectLoginFields().find((field) => field.el === el)?.type;391  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {392    return detected;393  }394395  const htmlType = el.type.toLowerCase();396  if (htmlType === "password") return "password";397  if (htmlType === "email") return "email";398  return null;399}400401async function openAutofillSelector(402  anchorField: HTMLInputElement,403  usernameEl: HTMLInputElement | null,404  passwordEl: HTMLInputElement,405  domainEntries: SelectorEntry[],406  searchableEntries: SelectorEntry[],407  domain: string408): Promise<void> {409  currentDismiss?.();410  currentAnchorField = anchorField;411  currentDismiss = showAutofillSelector(412    anchorField,413    domainEntries,414    async (id: string) => {415      currentDismiss = null;416      currentAnchorField = null;417      const entryResponse = await chrome.runtime.sendMessage({418        type: "GET_ENTRY_FOR_FILL",419        payload: { id },420      });421      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;422      if (entry) {423        await handleAutofill(anchorField, usernameEl, passwordEl, entry);424        recordFillSuccess(anchorField, usernameEl, passwordEl);425        // Offer to remember the current site for this entry only if none of426        // its known domains (primary + additional) match — otherwise the427        // user already mapped it and the prompt would be noise.428        const pageDomain = location.hostname.replace(/^www\./, "");429        const entryDomains = new Set<string>();430        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {431          try {432            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));433          } catch { /* ignore unparseable */ }434        }435        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {436          showRememberSiteToast(pageDomain, entry.id);437        }438      }439    },440    {441      domain,442      searchableEntries,443      // After State 5 (new entry) save: fill the detected fields with the444      // freshly-created credentials so the user can submit immediately.445      // On a login form the user created the entry to use here; on a signup446      // form the password was generated for this site. Same outcome either447      // way — the credentials land in the form and the popup exits.448      onFillFields: (username, password) => {449        const form = passwordEl.closest("form") as HTMLFormElement | null;450        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());451        recordFillSuccess(anchorField, usernameEl, passwordEl);452      },453      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },454    }455  );456}457458async function openSignupSelector(459  usernameEl: HTMLInputElement,460  passwordEl: HTMLInputElement | null,461  domainEntries: SelectorEntry[],462  allEntries: SelectorEntry[],463  domain: string464): Promise<void> {465  // Fetch derived identity list (emails then usernames from vault).466  // Falls back to empty list silently so the popup still opens when the467  // vault is temporarily unreachable or returns no login entries.468  let savedIdentities: SavedIdentity[] = [];469  try {470    const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as471      { ok: boolean; data?: SavedIdentity[] } | null;472    if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;473  } catch { /* silent fallback */ }474475  // Find the confirm-password field (second password input, or one labelled476  // confirm/repeat/verify) so "Copy & fill" from the generator can fill it too.477  const form = passwordEl?.closest("form") ?? document.body;478  const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));479  const confirmEl = allPwInputs.find(480    (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)481  ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);482483  currentDismiss?.();484  currentAnchorField = usernameEl;485  currentDismiss = showAutofillSelector(486    usernameEl,487    domainEntries,488    () => {},489    {490      domain,491      searchableEntries: allEntries,492      isSignup: true,493      savedIdentities,494      onFillFields: (username, password) => {495        if (username) setNativeValue(usernameEl, username);496        if (password && passwordEl) {497          setNativeValue(passwordEl, password);498          if (confirmEl) setNativeValue(confirmEl, password);499        }500        recordFillSuccess(usernameEl, passwordEl);501      },502      onDismiss: () => { lastDismissedField = usernameEl; startDismissLock(); },503    }504  );505}506507508async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {509  const field = anchorField ?? getDeepActiveInput();510  if (!field) return;511  if (!isVisible(field)) return;512513  // Layer 2: post-dismiss global lock. Catches rapid focus moves between514  // fields immediately after Escape/click-outside.515  if (!canOpen()) return;516517  // If a selector is already open for this exact field, don't flicker it.518  if (currentDismiss && currentAnchorField === field) return;519520  // If focus moved to a different field, the previous per-field dismiss lock521  // no longer applies.522  if (field !== lastDismissedField) lastDismissedField = null;523  // Layer 1: the user explicitly dismissed this field's selector — don't524  // reopen it until focus has genuinely moved away and come back.525  if (field === lastDismissedField) return;526527  // Fill-success lock: Peach already filled this form (or fired a fill528  // anywhere on the page within the grace window). Sites often refocus an529  // input on submit click, on validation, or on a transition to a success530  // state — none of those should re-open the popup.531  if (wasAlreadyFilled(field)) return;532533  // Prevent two concurrent calls for the same field (e.g. focusin + icon click534  // firing simultaneously — the second call would dismiss the first's selector).535  if (pendingInteractions.has(field)) return;536  pendingInteractions.add(field);537538  try {539    const fieldType = field.type.toLowerCase();540541    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {542      return preds[0] ?? null;543    });544545    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {546      const timeout = setTimeout(() => resolve(null), 150);547      mlPromise.then((pred) => {548        clearTimeout(timeout);549        resolve(pred);550      });551    });552553    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {554      return;555    }556557    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);558    if (autofillFieldType) {559      reattachListeners(field, autofillFieldType);560    }561562    let fields = detectLoginFields();563    const loginForm = isLoginForm(fields);564    const signupForm = isSignupForm(fields);565    if (!loginForm && !signupForm) {566      return;567    }568569    const domain = getPageDomain();570    const firstResult = await fetchAutofillEntries(domain);571572    // Vault is locked — show an inline unlock prompt.573    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so574    // there is no double-trigger race between onUnlocked and the broadcast.575    if (firstResult.locked) {576      currentDismiss?.();577      currentAnchorField = field;578      currentDismiss = showAutofillSelector(579        field,580        [],581        () => {},582        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }583      );584      return;585    }586587    const entries = firstResult.entries;588    const allEntries = entries.length === 0589      ? (await fetchAutofillEntries(domain, true)).entries590      : entries;591592    let usernameEl: HTMLInputElement | null = null;593    const userField = fields.find((f) => f.type === "username" || f.type === "email");594    if (userField) usernameEl = userField.el;595    const pwField = fields.find((f) => f.type === "password");596    if (!pwField) return;597    const passwordEl = pwField.el;598599    if (signupForm && usernameEl && field === usernameEl) {600      await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);601      return;602    }603604    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);605  } finally {606    pendingInteractions.delete(field);607  }608}609610async function onFocusIn(e: Event): Promise<void> {611  // Submit-button focus: catch the brief refocus some sites do when the612  // user clicks the login/submit button. Without this guard, that focus613  // event reaches handleFieldInteraction → getDeepActiveInput, and on614  // pages where the button is also a labelled <input> we briefly attempt615  // to open the popup over the very button the user just clicked.616  if (isSubmitButton(e.target)) return;617  await handleFieldInteraction();618}619620function reattachListeners(621  el: HTMLInputElement,622  detectedType?: "password" | "username" | "email",623  contextFields?: ReturnType<typeof detectLoginFields>624): void {625  if (processedInputs.has(el)) return;626  if (!resolveAutofillFieldType(el, detectedType)) return;627  // Only inject icon when a real login/signup form is present on the page628  const fields = contextFields ?? detectLoginFields();629  if (!isLoginForm(fields) && !isSignupForm(fields)) return;630631  const cleanup = injectFieldIcon(el, () => {632    currentDismiss?.();633    currentDismiss = null;634    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock635    dismissLock = false; // ...and the global lock636    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }637    clearFillStateForExplicitSummon(el);638    el.focus({ preventScroll: true });639    void handleFieldInteraction(el);640  });641  processedInputs.set(el, cleanup);642}643644const debouncedReattach = debounce(() => {645  const allFields = detectLoginFields();646  // Don't inject anything if there's no real login/signup form on this page647  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;648  const newFields = allFields.filter(649    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)650  );651  for (const f of newFields) {652    reattachListeners(f.el, f.type, allFields);653  }654  // 200ms debounce — below this, Peach and the host page's reactive layer655  // fight over the same layout properties every frame on React/Vue/Angular656  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.657}, 200);658659function setupMutationObserver(): void {660  const observer = new MutationObserver(debouncedReattach);661  observer.observe(document.body, {662    childList: true,663    subtree: true,664    attributes: true,665    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],666  });667}668669function initialScan(aggressionLevel = 0, isFinalPass = false) {670  const allFields = detectLoginFields();671  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);672673  if (aggressionLevel === 0 && !hasKnownForm) return;674675  const newFields = allFields.filter(676    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)677  );678679  for (const f of newFields) {680    reattachListeners(f.el, f.type, allFields);681  }682683  // Level 2, final pass: inject icon on any visible password field even if684  // the form-context gate in reattachListeners would normally skip it.685  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {686    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');687    for (const el of pwInputs) {688      if (isVisible(el) && !processedInputs.has(el)) {689        const cleanup = injectFieldIcon(el, () => {690          currentDismiss?.();691          currentDismiss = null;692          lastDismissedField = null;693          dismissLock = false;694          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }695          clearFillStateForExplicitSummon(el);696          el.focus({ preventScroll: true });697          void handleFieldInteraction(el);698        });699        processedInputs.set(el, cleanup);700      }701    }702  }703}704705document.addEventListener("focusin", onFocusIn);706707setupMutationObserver();708setupSaveDetection();709setupCardAutofill();710711// SPA navigation reset: the content script does not reload across in-app712// route changes (history.pushState, hash navigation, framework routers).713// When the URL changes we clear the page-level fill timestamp so the next714// page works normally; filledForms (a WeakSet) self-empties as old form715// elements leave the DOM. subtree:false because route swaps reliably716// mutate document.body's direct children — subtree:true would fire on717// every internal DOM update and cost us a re-check per mutation.718let lastObservedUrl = location.href;719new MutationObserver(() => {720  if (location.href !== lastObservedUrl) {721    lastObservedUrl = location.href;722    pageFilledAt = null;723  }724}).observe(document.body, { childList: true, subtree: false });725726// Async init: check recall map before running the initial scans so we can727// apply the right aggression level for domains the user has needed before.728(async () => {729  let aggressionLevel = 0;730  try {731    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });732    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;733    const domain = getPageDomain();734    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;735    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;736  } catch { /* SW may be starting up; proceed with normal scan */ }737738  setTimeout(() => initialScan(aggressionLevel, false), 0);739  setTimeout(() => initialScan(aggressionLevel, false), 500);740  setTimeout(() => initialScan(aggressionLevel, true), 1500);741})();742743// ── Card autofill (State 7) ─────────────────────────────────────────744// Card forms get a parallel injection path. The login icon-injection gate745// in reattachListeners deliberately skips non-text fields, so we wire746// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping747// card detection contained makes the boundary easy to follow.748const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();749let currentCardDismiss: (() => void) | null = null;750let currentCardAnchor: HTMLInputElement | null = null;751let lastDismissedCardField: HTMLInputElement | null = null;752753async function fetchSavedCards(): Promise<CardSelectorEntry[]> {754  const resp = await chrome.runtime.sendMessage({755    type: "AUTOFILL_QUERY",756    payload: { domain: getPageDomain(), kind: "card" },757  }).catch(() => null);758  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;759  return r?.ok ? (r.data ?? []) : [];760}761762async function openCardSelector(anchor: HTMLInputElement): Promise<void> {763  if (!canOpen()) return;764  if (currentCardDismiss && currentCardAnchor === anchor) return;765  if (anchor === lastDismissedCardField) return;766  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;767  if (wasAlreadyFilled(anchor)) return;768769  const cards = await fetchSavedCards();770  if (cards.length === 0) return; // no saved cards → nothing to offer771772  const cardForm = detectCardForm();773  if (!cardForm?.number) return;774775  currentCardDismiss?.();776  currentCardAnchor = anchor;777  currentCardDismiss = showCardSelector(778    anchor,779    cards,780    {781      domain: getPageDomain(),782      onFill: (entry) => {783        if (!cardForm) return;784        fillCardForm(cardForm, {785          cardNumber: entry.cardNumber ?? "",786          expMonth: entry.expMonth ?? "",787          expYear: entry.expYear ?? "",788          cvc: entry.cvc ?? "",789          cardholderName: entry.cardholderName ?? "",790        });791        // All four card field types share the same form — recording the792        // number field's form is sufficient to suppress reopens on any of793        // them via wasAlreadyFilled().794        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);795        currentCardDismiss = null;796        currentCardAnchor = null;797      },798      onDismiss: () => {799        lastDismissedCardField = anchor;800        startDismissLock();801        currentCardDismiss = null;802        currentCardAnchor = null;803      },804    }805  );806}807808function injectCardIcon(field: HTMLInputElement): void {809  if (processedCardInputs.has(field)) return;810  const cleanup = injectFieldIcon(field, () => {811    currentCardDismiss?.();812    currentCardDismiss = null;813    lastDismissedCardField = null;814    dismissLock = false;815    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }816    clearFillStateForExplicitSummon(field);817    field.focus({ preventScroll: true });818    void openCardSelector(field);819  });820  processedCardInputs.set(field, cleanup);821}822823function setupCardAutofill(): void {824  function scan() {825    const cardForm = detectCardForm();826    if (!cardForm?.number) return;827    if (!isVisible(cardForm.number)) return;828    injectCardIcon(cardForm.number);829  }830831  // Initial detection sweep — same retry cadence as login fields so832  // late-hydrating SPA checkout pages get caught.833  setTimeout(scan, 0);834  setTimeout(scan, 500);835  setTimeout(scan, 1500);836837  // Re-scan on DOM mutation (separate from the login MutationObserver838  // because card forms typically appear on a single navigation event,839  // not field-by-field — coarser observation is sufficient here).840  let pending = false;841  new MutationObserver(() => {842    if (pending) return;843    pending = true;844    setTimeout(() => { pending = false; scan(); }, 200);845  }).observe(document.body, { childList: true, subtree: true });846847  // Field-focus path: on focus of a cc-number input, ensure icon is848  // present and consider opening the selector when the user explicitly849  // clicks into the card number field.850  document.addEventListener("focusin", (e) => {851    const target = e.target;852    if (!(target instanceof HTMLInputElement)) return;853    const cardForm = detectCardForm();854    if (cardForm?.number === target) {855      injectCardIcon(target);856    }857  }, true);858}859860chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {861  // Ignore anything not originating from our own background/service worker.862  if (sender.id !== chrome.runtime.id) return;863  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {864    const policy = detectPasswordPolicy();865    sendResponse({ ok: true, data: policy });866    return true;867  }868  if (msg?.type === "PING") {869    sendResponse({ ok: true });870    return true;871  }872  if (msg?.type === "SUMMON_AUTOFILL") {873    const source = (msg as { type: string; source?: string }).source;874    const isShortcut = source === "shortcut";875876    const activeInput = getDeepActiveInput();877    const fields = detectLoginFields();878    const hasForm = isLoginForm(fields) || isSignupForm(fields);879880    if (hasForm) {881      // Prefer the currently focused field if it's a login field, otherwise882      // fall back to the first password field, then username/email.883      const inForm = activeInput && fields.some(f => f.el === activeInput);884      const target = inForm885        ? activeInput886        : (fields.find(f => f.type === "password")?.el887            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);888      if (target) {889        // Explicit user summon (shortcut or extension button) — bypass all890        // suppression layers. The user is asking for the popup right now.891        clearFillStateForExplicitSummon(target);892        dismissLock = false;893        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }894        lastDismissedField = null;895        void handleFieldInteraction(target);896      }897    } else if (isShortcut) {898      // Shortcut on a page with no login form — show clipboard-copy search mode.899      showSearchPalette();900    }901902    // Record this domain for the recall system when triggered via shortcut.903    if (isShortcut) {904      const domain = getPageDomain();905      if (domain) {906        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});907      }908    }909910    sendResponse({ ok: hasForm || isShortcut });911    return true;912  }913  if (msg?.type === "PASSKEY_PRO_GATE") {914    // Background rejected a passkey request for a free user. Show State 11915    // so they know what happened and can choose to upgrade.916    showPasskeyProGate();917    sendResponse({ ok: true });918    return true;919  }920  if (msg?.type === "VAULT_UNLOCKED") {921    // Close any open selector (e.g. the locked-state prompt) and re-open922    // with fresh entry data. Use the saved anchor field so we reopen exactly923    // where the user was — covers both inline unlock and popup unlock.924    const savedField = currentAnchorField;925    if (currentDismiss) {926      currentDismiss();927      currentDismiss = null;928      currentAnchorField = null;929    }930    void handleFieldInteraction(savedField ?? undefined);931    sendResponse({ ok: true });932    return true;933  }934  return true;935});936937// ── Firefox passkey detection bridge ─────────────────────────────────────938//939// `src/content/passkeys-firefox.ts` runs in the page's MAIN world and940// monkey-patches navigator.credentials. It postMessages here when the page941// invokes create/get; we surface the inline registration offer (State 12)942// after a per-domain decline + dedupe check. Only relevant on Firefox; on943// Chrome the existing webAuthenticationProxy flow handles registration944// without needing this bridge.945{946  let lastPasskeyOfferAt = 0;947  const PASSKEY_OFFER_COOLDOWN_MS = 30_000;948949  window.addEventListener("message", (event: MessageEvent) => {950    if (event.source !== window) return;951    const data = event.data as { source?: string; type?: string; rpId?: string; rpName?: string; userName?: string; userDisplayName?: string } | undefined;952    if (!data || data.source !== "peach-passkey-firefox") return;953    if (detectBrowser() !== "firefox") return;954    if (data.type !== "create") return;955956    // Cooldown: a single page interaction can fire multiple credentials.create957    // calls. Show the offer at most once per 30 seconds per page session.958    const now = Date.now();959    if (now - lastPasskeyOfferAt < PASSKEY_OFFER_COOLDOWN_MS) return;960    lastPasskeyOfferAt = now;961962    const domain = location.hostname.replace(/^www\./, "");963    chrome.runtime.sendMessage({964      type: "GET_PASSKEY_OFFER_DECLINED",965      payload: { domain },966    }).then((res: { ok: boolean; data?: boolean } | undefined) => {967      if (res?.data === true) return;968      const rpId = data.rpId ?? domain;969      showPasskeyRegistrationOffer({970        rpId,971        rpName: data.rpName,972        userName: data.userName,973        userDisplayName: data.userDisplayName,974      });975    }).catch(() => {});976  });977}978979// Surface State 11 (passkey-available) once per page session when this domain980// has a stored passkey. The cross-browser banner inside the surface warns the981// user when their passkey was created on the other browser and isn't usable982// here without re-registration.983{984  let availabilityChecked = false;985986  function checkPasskeyAvailability() {987    if (availabilityChecked) return;988    availabilityChecked = true;989    const domain = location.hostname.replace(/^www\./, "");990    if (!domain) return;991    chrome.runtime.sendMessage({992      type: "GET_PASSKEY_FOR_DOMAIN",993      payload: { domain },994    }).then((res: { ok: boolean; data?: { rpId: string; userName: string; browser?: "chrome" | "firefox" } | null } | undefined) => {995      const data = res?.data;996      if (!data) return;997      showPasskeyAvailable({998        rpId: data.rpId,999        userName: data.userName,1000        fromBrowser: data.browser,1001        currentBrowser: detectBrowser(),1002      });1003    }).catch(() => {});1004  }10051006  // Defer until DOM is interactive — content_scripts run at document_idle but1007  // some pages still mutate visibly afterwards. A short delay also avoids1008  // surfacing the State 11 toast while the user is in the middle of typing.1009  if (document.readyState === "loading") {1010    document.addEventListener("DOMContentLoaded", () => setTimeout(checkPasskeyAvailability, 800));1011  } else {1012    setTimeout(checkPasskeyAvailability, 800);1013  }1014}