index.ts

33.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  showRememberSiteToast,18} from "./inject";19import { fillCardForm, fillFields } from "./fill";20import { setupSaveDetection } from "./save";21import { contentMLDetector } from "./content-ml-detector";22import { detectPasswordPolicy } from "./policy";23import type { FieldPrediction } from "../shared/ml";24import { generateTOTP } from "../crypto/totp";25import type { VaultEntry } from "../shared/types";2627// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value28// so we can tear down listeners if we ever need to re-process the same field.29// When the input is GC'd (SPA nav, React re-render), the map entry goes with30// it and we can re-inject without leaking the old handler.31const processedInputs = new WeakMap<HTMLInputElement, () => void>();32const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3334let currentDismiss: (() => void) | null = null;35// Field whose selector is currently open — used to avoid dismiss+reopen flicker36let currentAnchorField: HTMLInputElement | null = null;37// Prevents two concurrent handleFieldInteraction calls for the same field38const pendingInteractions = new WeakSet<HTMLInputElement>();39// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).40// Suppresses spurious reopens until focus moves to a different field. Layer 141// of the dismissal model — see Projects.md §4.12.42let lastDismissedField: HTMLInputElement | null = null;4344// ── Dismissal lock (Layer 2) ────────────────────────────────────────45// After any user-initiated dismiss, briefly block ALL reopens regardless of46// which field is focused. Catches the case where a page rapidly moves focus47// between fields after Escape — without this, focus moving to a SECOND field48// in <100ms would re-trigger the popup before the user finished dismissing.49const DISMISS_LOCK_MS = 800;50let dismissLock = false;51let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;52function startDismissLock(): void {53  dismissLock = true;54  if (dismissLockTimer) clearTimeout(dismissLockTimer);55  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);56}57function canOpen(): boolean { return !dismissLock; }5859// ── Fill-success lock ───────────────────────────────────────────────60// After Peach autofills a form, the popup must NOT reappear on the filled61// fields, on the submit button (some sites refocus it briefly), or on any62// field in that form — even when host-page DOM mutations or the form's own63// validation flow refocus an input. Implemented as a WeakSet of forms plus64// a page-level timestamp:65//   - filledForms: every form Peach has filled this page session. Survives66//     until the form leaves the DOM (WeakSet GC).67//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders68//     window for fields that aren't inside a <form> element (some SPAs).69// SPA navigation resets pageFilledAt via the urlObserver below; filledForms70// self-empties as old form elements get GC'd.71const filledForms = new WeakSet<HTMLFormElement>();72let pageFilledAt: number | null = null;73const PAGE_FILL_GRACE_MS = 3000;7475function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {76  for (const f of fields) {77    if (!f) continue;78    const form = f.closest("form");79    if (form) filledForms.add(form);80  }81  pageFilledAt = Date.now();82}8384function wasAlreadyFilled(field: HTMLInputElement): boolean {85  const form = field.closest("form");86  if (form && filledForms.has(form)) return true;87  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;88  return false;89}9091function clearFillStateForExplicitSummon(field: HTMLInputElement): void {92  const form = field.closest("form");93  if (form) filledForms.delete(form);94  pageFilledAt = null;95}9697// Some sites briefly focus the submit button when the user clicks it (visual98// feedback, blur/focus dance for validation animations). Catch those at the99// focusin layer so we don't re-trigger handleFieldInteraction for an event100// target that was never going to be a credential field anyway.101function isSubmitButton(el: EventTarget | null): boolean {102  if (!(el instanceof HTMLElement)) return false;103  if (el instanceof HTMLButtonElement && el.type !== "button") return true;104  if (el instanceof HTMLInputElement && el.type === "submit") return true;105  if (el.getAttribute("type") === "submit") return true;106  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();107  if (!text || text.length > 24) return false;108  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);109}110111function debounce<T extends (...args: unknown[]) => void>(112  fn: T,113  ms: number114): (...args: Parameters<T>) => void {115  let timer: ReturnType<typeof setTimeout>;116  return (...args: Parameters<T>) => {117    clearTimeout(timer);118    timer = setTimeout(() => fn(...args), ms);119  };120}121122function showToast(message: string): void {123  const toast = document.createElement("div");124  toast.style.cssText = `125    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);126    background: #131109; color: #F0E8D8; padding: 8px 16px;127    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;128    font-size: 11px; z-index: 2147483647; opacity: 0;129    transition: opacity 200ms ease;130    border: 1px solid rgba(240,232,216,0.07);131    pointer-events: none;132  `;133  toast.textContent = message;134  document.body.appendChild(toast);135  requestAnimationFrame(() => { toast.style.opacity = "1"; });136  setTimeout(() => {137    toast.style.opacity = "0";138    setTimeout(() => toast.remove(), 200);139  }, 2000);140}141142function showSearchPalette(): void {143  const host = document.createElement("div");144  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";145  document.body.appendChild(host);146  const shadow = host.attachShadow({ mode: "closed" });147148  const style = document.createElement("style");149  style.textContent = `150    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;151      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;152      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}153    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);154      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}155    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}156    .s{padding:8px 12px}157    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);158      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;159      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}160    .l{max-height:220px;overflow-y:auto}161    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}162    .e:hover{background:rgba(240,232,216,.06)}163    .et{font-size:12px}164    .eu{font-size:10px;color:rgba(240,232,216,.45)}165    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}166  `;167168  let allEntries: SelectorEntry[] = [];169  let query = "";170171  const panel = document.createElement("div");172  panel.className = "p";173174  const hdr = document.createElement("div");175  hdr.className = "h";176  const hdrText = document.createElement("span");177  hdrText.textContent = "No form detected — search your vault";178  const closeBtn = document.createElement("button");179  closeBtn.className = "x";180  closeBtn.textContent = "✕";181  hdr.appendChild(hdrText);182  hdr.appendChild(closeBtn);183184  const searchWrap = document.createElement("div");185  searchWrap.className = "s";186  const searchInput = document.createElement("input");187  searchInput.placeholder = "search...";188  searchWrap.appendChild(searchInput);189190  const list = document.createElement("div");191  list.className = "l";192193  panel.appendChild(hdr);194  panel.appendChild(searchWrap);195  panel.appendChild(list);196  shadow.appendChild(style);197  shadow.appendChild(panel);198199  function close() { host.remove(); }200201  closeBtn.onclick = close;202203  function onKeyDown(e: KeyboardEvent) {204    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }205  }206  document.addEventListener("keydown", onKeyDown, true);207208  function render() {209    const q = query.toLowerCase();210    const filtered = q211      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))212      : allEntries;213    list.innerHTML = "";214    if (filtered.length === 0) {215      const em = document.createElement("div");216      em.className = "em";217      em.textContent = query ? "no matches" : "vault is empty";218      list.appendChild(em);219      return;220    }221    for (const entry of filtered.slice(0, 20)) {222      const row = document.createElement("div");223      row.className = "e";224      const title = document.createElement("div");225      title.className = "et";226      title.textContent = entry.title;227      row.appendChild(title);228      if (entry.username) {229        const user = document.createElement("div");230        user.className = "eu";231        user.textContent = entry.username;232        row.appendChild(user);233      }234      row.onclick = async () => {235        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });236        const r = resp as { ok: boolean; data?: { password?: string } };237        if (r.ok && r.data?.password) {238          let alreadyWritten = false;239          try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}240          await chrome.runtime.sendMessage({241            type: "COPY",242            payload: { text: r.data.password, label: "Password", alreadyWritten },243          });244          showToast("Password copied");245        } else {246          showToast("Could not copy password");247        }248        close();249        document.removeEventListener("keydown", onKeyDown, true);250      };251      list.appendChild(row);252    }253  }254255  searchInput.oninput = () => { query = searchInput.value; render(); };256257  fetchAutofillEntries(getPageDomain(), true).then(result => {258    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }259    allEntries = result.entries;260    render();261    searchInput.focus();262  });263}264265function setNativeValue(el: HTMLInputElement, value: string): void {266  const nativeSetter = Object.getOwnPropertyDescriptor(267    HTMLInputElement.prototype, "value"268  )!.set!;269  nativeSetter.call(el, value);270  el.dispatchEvent(new Event("input", { bubbles: true }));271  el.dispatchEvent(new Event("change", { bubbles: true }));272}273274function findTOTPField(): HTMLInputElement | null {275  const inputs = document.querySelectorAll<HTMLInputElement>("input");276  for (const input of inputs) {277    if (!isVisible(input)) continue;278    const autocomplete = input.autocomplete.toLowerCase();279    const nameId = (input.name + input.id).toLowerCase();280    const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();281    if (282      autocomplete === "one-time-code" ||283      /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)284    ) {285      return input;286    }287    const labelEl = input.closest("label");288    if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {289      return input;290    }291  }292  return null;293}294295async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {296  await new Promise((r) => setTimeout(r, 400));297  if (totpField.value === "" || totpField.value.trim() === "") {298    const { code } = generateTOTP(totpSecret);299    setNativeValue(totpField, code);300    showToast("TOTP autofilled");301  }302}303304305async function handleAutofill(306  field: HTMLInputElement,307  usernameEl: HTMLInputElement | null,308  passwordEl: HTMLInputElement,309  entry: VaultEntry310): Promise<void> {311  if (!entry.username && !entry.password) return;312  const pageDomain = getPageDomain();313  const form = passwordEl.closest("form") as HTMLFormElement | null;314  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);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  if (entry.totp) {341    const { code } = generateTOTP(entry.totp);342    let alreadyWritten = false;343    try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}344    const response = await chrome.runtime.sendMessage({345      type: "COPY",346      payload: { text: code, label: "TOTP", alreadyWritten },347    });348    if (alreadyWritten || (response as { ok?: boolean }).ok) {349      showToast("TOTP copied · " + code);350    }351    const totpField = findTOTPField();352    if (totpField) {353      autofillTOTP(totpField, entry.totp);354    }355  }356}357358async function fetchAutofillEntries(359  domain: string,360  includeAll = false361): Promise<{ entries: SelectorEntry[]; locked: boolean }> {362  const response = await chrome.runtime.sendMessage({363    type: "AUTOFILL_QUERY",364    payload: { domain, includeAll },365  });366  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };367  if (!res.ok && res.error === "VAULT_LOCKED") {368    return { entries: [], locked: true };369  }370  return { entries: res.data ?? [], locked: false };371}372373374function resolveAutofillFieldType(375  el: HTMLInputElement,376  predictedType?: FieldPrediction["type"] | null377): "password" | "username" | "email" | null {378  if (379    predictedType === "password" ||380    predictedType === "username" ||381    predictedType === "email"382  ) {383    return predictedType;384  }385386  const detected = detectLoginFields().find((field) => field.el === el)?.type;387  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {388    return detected;389  }390391  const htmlType = el.type.toLowerCase();392  if (htmlType === "password") return "password";393  if (htmlType === "email") return "email";394  return null;395}396397async function openAutofillSelector(398  anchorField: HTMLInputElement,399  usernameEl: HTMLInputElement | null,400  passwordEl: HTMLInputElement,401  domainEntries: SelectorEntry[],402  searchableEntries: SelectorEntry[],403  domain: string404): Promise<void> {405  currentDismiss?.();406  currentAnchorField = anchorField;407  currentDismiss = showAutofillSelector(408    anchorField,409    domainEntries,410    async (id: string) => {411      currentDismiss = null;412      currentAnchorField = null;413      const entryResponse = await chrome.runtime.sendMessage({414        type: "GET_ENTRY_FOR_FILL",415        payload: { id },416      });417      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;418      if (entry) {419        await handleAutofill(anchorField, usernameEl, passwordEl, entry);420        recordFillSuccess(anchorField, usernameEl, passwordEl);421        // Offer to remember the current site for this entry only if none of422        // its known domains (primary + additional) match — otherwise the423        // user already mapped it and the prompt would be noise.424        const pageDomain = location.hostname.replace(/^www\./, "");425        const entryDomains = new Set<string>();426        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {427          try {428            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));429          } catch { /* ignore unparseable */ }430        }431        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {432          showRememberSiteToast(pageDomain, entry.id);433        }434      }435    },436    {437      domain,438      searchableEntries,439      // After State 5 (new entry) save: fill the detected fields with the440      // freshly-created credentials so the user can submit immediately.441      // On a login form the user created the entry to use here; on a signup442      // form the password was generated for this site. Same outcome either443      // way — the credentials land in the form and the popup exits.444      onFillFields: (username, password) => {445        const form = passwordEl.closest("form") as HTMLFormElement | null;446        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());447        recordFillSuccess(anchorField, usernameEl, passwordEl);448      },449      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },450    }451  );452}453454async function openSignupSelector(455  usernameEl: HTMLInputElement,456  passwordEl: HTMLInputElement | null,457  domainEntries: SelectorEntry[],458  allEntries: SelectorEntry[],459  domain: string460): Promise<void> {461  currentDismiss?.();462  currentAnchorField = usernameEl;463  currentDismiss = showAutofillSelector(464    usernameEl,465    domainEntries,466    () => {}, // identity-click handled via onFillFields467    {468      domain,469      searchableEntries: allEntries,470      isSignup: true,471      onFillFields: (username, password) => {472        if (username) setNativeValue(usernameEl, username);473        if (password && passwordEl) setNativeValue(passwordEl, password);474        recordFillSuccess(usernameEl, passwordEl);475      },476      onDismiss: () => { lastDismissedField = usernameEl; startDismissLock(); },477    }478  );479}480481482async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {483  const field = anchorField ?? getDeepActiveInput();484  if (!field) return;485  if (!isVisible(field)) return;486487  // Layer 2: post-dismiss global lock. Catches rapid focus moves between488  // fields immediately after Escape/click-outside.489  if (!canOpen()) return;490491  // If a selector is already open for this exact field, don't flicker it.492  if (currentDismiss && currentAnchorField === field) return;493494  // If focus moved to a different field, the previous per-field dismiss lock495  // no longer applies.496  if (field !== lastDismissedField) lastDismissedField = null;497  // Layer 1: the user explicitly dismissed this field's selector — don't498  // reopen it until focus has genuinely moved away and come back.499  if (field === lastDismissedField) return;500501  // Fill-success lock: Peach already filled this form (or fired a fill502  // anywhere on the page within the grace window). Sites often refocus an503  // input on submit click, on validation, or on a transition to a success504  // state — none of those should re-open the popup.505  if (wasAlreadyFilled(field)) return;506507  // Prevent two concurrent calls for the same field (e.g. focusin + icon click508  // firing simultaneously — the second call would dismiss the first's selector).509  if (pendingInteractions.has(field)) return;510  pendingInteractions.add(field);511512  try {513    const fieldType = field.type.toLowerCase();514515    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {516      return preds[0] ?? null;517    });518519    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {520      const timeout = setTimeout(() => resolve(null), 150);521      mlPromise.then((pred) => {522        clearTimeout(timeout);523        resolve(pred);524      });525    });526527    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {528      return;529    }530531    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);532    if (autofillFieldType) {533      reattachListeners(field, autofillFieldType);534    }535536    let fields = detectLoginFields();537    const loginForm = isLoginForm(fields);538    const signupForm = isSignupForm(fields);539    if (!loginForm && !signupForm) {540      return;541    }542543    const domain = getPageDomain();544    const firstResult = await fetchAutofillEntries(domain);545546    // Vault is locked — show an inline unlock prompt.547    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so548    // there is no double-trigger race between onUnlocked and the broadcast.549    if (firstResult.locked) {550      currentDismiss?.();551      currentAnchorField = field;552      currentDismiss = showAutofillSelector(553        field,554        [],555        () => {},556        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }557      );558      return;559    }560561    const entries = firstResult.entries;562    const allEntries = entries.length === 0563      ? (await fetchAutofillEntries(domain, true)).entries564      : entries;565566    let usernameEl: HTMLInputElement | null = null;567    const userField = fields.find((f) => f.type === "username" || f.type === "email");568    if (userField) usernameEl = userField.el;569    const pwField = fields.find((f) => f.type === "password");570    if (!pwField) return;571    const passwordEl = pwField.el;572573    if (signupForm && usernameEl && field === usernameEl) {574      await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);575      return;576    }577578    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);579  } finally {580    pendingInteractions.delete(field);581  }582}583584async function onFocusIn(e: Event): Promise<void> {585  // Submit-button focus: catch the brief refocus some sites do when the586  // user clicks the login/submit button. Without this guard, that focus587  // event reaches handleFieldInteraction → getDeepActiveInput, and on588  // pages where the button is also a labelled <input> we briefly attempt589  // to open the popup over the very button the user just clicked.590  if (isSubmitButton(e.target)) return;591  await handleFieldInteraction();592}593594function reattachListeners(595  el: HTMLInputElement,596  detectedType?: "password" | "username" | "email",597  contextFields?: ReturnType<typeof detectLoginFields>598): void {599  if (processedInputs.has(el)) return;600  if (!resolveAutofillFieldType(el, detectedType)) return;601  // Only inject icon when a real login/signup form is present on the page602  const fields = contextFields ?? detectLoginFields();603  if (!isLoginForm(fields) && !isSignupForm(fields)) return;604605  const cleanup = injectFieldIcon(el, () => {606    currentDismiss?.();607    currentDismiss = null;608    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock609    dismissLock = false; // ...and the global lock610    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }611    clearFillStateForExplicitSummon(el);612    el.focus({ preventScroll: true });613    void handleFieldInteraction(el);614  });615  processedInputs.set(el, cleanup);616}617618const debouncedReattach = debounce(() => {619  const allFields = detectLoginFields();620  // Don't inject anything if there's no real login/signup form on this page621  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;622  const newFields = allFields.filter(623    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)624  );625  for (const f of newFields) {626    reattachListeners(f.el, f.type, allFields);627  }628  // 200ms debounce — below this, Peach and the host page's reactive layer629  // fight over the same layout properties every frame on React/Vue/Angular630  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.631}, 200);632633function setupMutationObserver(): void {634  const observer = new MutationObserver(debouncedReattach);635  observer.observe(document.body, {636    childList: true,637    subtree: true,638    attributes: true,639    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],640  });641}642643function initialScan(aggressionLevel = 0, isFinalPass = false) {644  const allFields = detectLoginFields();645  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);646647  if (aggressionLevel === 0 && !hasKnownForm) return;648649  const newFields = allFields.filter(650    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)651  );652653  for (const f of newFields) {654    reattachListeners(f.el, f.type, allFields);655  }656657  // Level 2, final pass: inject icon on any visible password field even if658  // the form-context gate in reattachListeners would normally skip it.659  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {660    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');661    for (const el of pwInputs) {662      if (isVisible(el) && !processedInputs.has(el)) {663        const cleanup = injectFieldIcon(el, () => {664          currentDismiss?.();665          currentDismiss = null;666          lastDismissedField = null;667          dismissLock = false;668          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }669          clearFillStateForExplicitSummon(el);670          el.focus({ preventScroll: true });671          void handleFieldInteraction(el);672        });673        processedInputs.set(el, cleanup);674      }675    }676  }677}678679document.addEventListener("focusin", onFocusIn);680681setupMutationObserver();682setupSaveDetection();683setupCardAutofill();684685// SPA navigation reset: the content script does not reload across in-app686// route changes (history.pushState, hash navigation, framework routers).687// When the URL changes we clear the page-level fill timestamp so the next688// page works normally; filledForms (a WeakSet) self-empties as old form689// elements leave the DOM. subtree:false because route swaps reliably690// mutate document.body's direct children — subtree:true would fire on691// every internal DOM update and cost us a re-check per mutation.692let lastObservedUrl = location.href;693new MutationObserver(() => {694  if (location.href !== lastObservedUrl) {695    lastObservedUrl = location.href;696    pageFilledAt = null;697  }698}).observe(document.body, { childList: true, subtree: false });699700// Async init: check recall map before running the initial scans so we can701// apply the right aggression level for domains the user has needed before.702(async () => {703  let aggressionLevel = 0;704  try {705    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });706    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;707    const domain = getPageDomain();708    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;709    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;710  } catch { /* SW may be starting up; proceed with normal scan */ }711712  setTimeout(() => initialScan(aggressionLevel, false), 0);713  setTimeout(() => initialScan(aggressionLevel, false), 500);714  setTimeout(() => initialScan(aggressionLevel, true), 1500);715})();716717// ── Card autofill (State 7) ─────────────────────────────────────────718// Card forms get a parallel injection path. The login icon-injection gate719// in reattachListeners deliberately skips non-text fields, so we wire720// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping721// card detection contained makes the boundary easy to follow.722const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();723let currentCardDismiss: (() => void) | null = null;724let currentCardAnchor: HTMLInputElement | null = null;725let lastDismissedCardField: HTMLInputElement | null = null;726727async function fetchSavedCards(): Promise<CardSelectorEntry[]> {728  const resp = await chrome.runtime.sendMessage({729    type: "AUTOFILL_QUERY",730    payload: { domain: getPageDomain(), kind: "card" },731  }).catch(() => null);732  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;733  return r?.ok ? (r.data ?? []) : [];734}735736async function openCardSelector(anchor: HTMLInputElement): Promise<void> {737  if (!canOpen()) return;738  if (currentCardDismiss && currentCardAnchor === anchor) return;739  if (anchor === lastDismissedCardField) return;740  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;741  if (wasAlreadyFilled(anchor)) return;742743  const cards = await fetchSavedCards();744  if (cards.length === 0) return; // no saved cards → nothing to offer745746  const cardForm = detectCardForm();747  if (!cardForm?.number) return;748749  currentCardDismiss?.();750  currentCardAnchor = anchor;751  currentCardDismiss = showCardSelector(752    anchor,753    cards,754    {755      domain: getPageDomain(),756      onFill: (entry) => {757        if (!cardForm) return;758        fillCardForm(cardForm, {759          cardNumber: entry.cardNumber ?? "",760          expMonth: entry.expMonth ?? "",761          expYear: entry.expYear ?? "",762          cvc: entry.cvc ?? "",763          cardholderName: entry.cardholderName ?? "",764        });765        // All four card field types share the same form — recording the766        // number field's form is sufficient to suppress reopens on any of767        // them via wasAlreadyFilled().768        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);769        currentCardDismiss = null;770        currentCardAnchor = null;771      },772      onDismiss: () => {773        lastDismissedCardField = anchor;774        startDismissLock();775        currentCardDismiss = null;776        currentCardAnchor = null;777      },778    }779  );780}781782function injectCardIcon(field: HTMLInputElement): void {783  if (processedCardInputs.has(field)) return;784  const cleanup = injectFieldIcon(field, () => {785    currentCardDismiss?.();786    currentCardDismiss = null;787    lastDismissedCardField = null;788    dismissLock = false;789    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }790    clearFillStateForExplicitSummon(field);791    field.focus({ preventScroll: true });792    void openCardSelector(field);793  });794  processedCardInputs.set(field, cleanup);795}796797function setupCardAutofill(): void {798  function scan() {799    const cardForm = detectCardForm();800    if (!cardForm?.number) return;801    if (!isVisible(cardForm.number)) return;802    injectCardIcon(cardForm.number);803  }804805  // Initial detection sweep — same retry cadence as login fields so806  // late-hydrating SPA checkout pages get caught.807  setTimeout(scan, 0);808  setTimeout(scan, 500);809  setTimeout(scan, 1500);810811  // Re-scan on DOM mutation (separate from the login MutationObserver812  // because card forms typically appear on a single navigation event,813  // not field-by-field — coarser observation is sufficient here).814  let pending = false;815  new MutationObserver(() => {816    if (pending) return;817    pending = true;818    setTimeout(() => { pending = false; scan(); }, 200);819  }).observe(document.body, { childList: true, subtree: true });820821  // Field-focus path: on focus of a cc-number input, ensure icon is822  // present and consider opening the selector when the user explicitly823  // clicks into the card number field.824  document.addEventListener("focusin", (e) => {825    const target = e.target;826    if (!(target instanceof HTMLInputElement)) return;827    const cardForm = detectCardForm();828    if (cardForm?.number === target) {829      injectCardIcon(target);830    }831  }, true);832}833834chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {835  // Ignore anything not originating from our own background/service worker.836  if (sender.id !== chrome.runtime.id) return;837  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {838    const policy = detectPasswordPolicy();839    sendResponse({ ok: true, data: policy });840    return true;841  }842  if (msg?.type === "PING") {843    sendResponse({ ok: true });844    return true;845  }846  if (msg?.type === "SUMMON_AUTOFILL") {847    const source = (msg as { type: string; source?: string }).source;848    const isShortcut = source === "shortcut";849850    const activeInput = getDeepActiveInput();851    const fields = detectLoginFields();852    const hasForm = isLoginForm(fields) || isSignupForm(fields);853854    if (hasForm) {855      // Prefer the currently focused field if it's a login field, otherwise856      // fall back to the first password field, then username/email.857      const inForm = activeInput && fields.some(f => f.el === activeInput);858      const target = inForm859        ? activeInput860        : (fields.find(f => f.type === "password")?.el861            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);862      if (target) {863        // Explicit user summon (shortcut or extension button) — bypass all864        // suppression layers. The user is asking for the popup right now.865        clearFillStateForExplicitSummon(target);866        dismissLock = false;867        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }868        lastDismissedField = null;869        void handleFieldInteraction(target);870      }871    } else if (isShortcut) {872      // Shortcut on a page with no login form — show clipboard-copy search mode.873      showSearchPalette();874    }875876    // Record this domain for the recall system when triggered via shortcut.877    if (isShortcut) {878      const domain = getPageDomain();879      if (domain) {880        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});881      }882    }883884    sendResponse({ ok: hasForm || isShortcut });885    return true;886  }887  if (msg?.type === "VAULT_UNLOCKED") {888    // Close any open selector (e.g. the locked-state prompt) and re-open889    // with fresh entry data. Use the saved anchor field so we reopen exactly890    // where the user was — covers both inline unlock and popup unlock.891    const savedField = currentAnchorField;892    if (currentDismiss) {893      currentDismiss();894      currentDismiss = null;895      currentAnchorField = null;896    }897    void handleFieldInteraction(savedField ?? undefined);898    sendResponse({ ok: true });899    return true;900  }901  return true;902});