index.ts

34.6 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 { SavedIdentity, 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  // Fetch derived identity list (emails then usernames from vault).462  // Falls back to empty list silently so the popup still opens when the463  // vault is temporarily unreachable or returns no login entries.464  let savedIdentities: SavedIdentity[] = [];465  try {466    const idResp = await chrome.runtime.sendMessage({ type: "GET_IDENTITIES" }).catch(() => null) as467      { ok: boolean; data?: SavedIdentity[] } | null;468    if (idResp?.ok && Array.isArray(idResp.data)) savedIdentities = idResp.data;469  } catch { /* silent fallback */ }470471  // Find the confirm-password field (second password input, or one labelled472  // confirm/repeat/verify) so "Copy & fill" from the generator can fill it too.473  const form = passwordEl?.closest("form") ?? document.body;474  const allPwInputs = Array.from(form.querySelectorAll<HTMLInputElement>("input[type='password']"));475  const confirmEl = allPwInputs.find(476    (el) => el !== passwordEl && /confirm|repeat|verify/i.test(el.name + el.id + el.placeholder)477  ) ?? (allPwInputs.length >= 2 ? allPwInputs.find((el) => el !== passwordEl) ?? null : null);478479  currentDismiss?.();480  currentAnchorField = usernameEl;481  currentDismiss = showAutofillSelector(482    usernameEl,483    domainEntries,484    () => {},485    {486      domain,487      searchableEntries: allEntries,488      isSignup: true,489      savedIdentities,490      onFillFields: (username, password) => {491        if (username) setNativeValue(usernameEl, username);492        if (password && passwordEl) {493          setNativeValue(passwordEl, password);494          if (confirmEl) setNativeValue(confirmEl, password);495        }496        recordFillSuccess(usernameEl, passwordEl);497      },498      onDismiss: () => { lastDismissedField = usernameEl; startDismissLock(); },499    }500  );501}502503504async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {505  const field = anchorField ?? getDeepActiveInput();506  if (!field) return;507  if (!isVisible(field)) return;508509  // Layer 2: post-dismiss global lock. Catches rapid focus moves between510  // fields immediately after Escape/click-outside.511  if (!canOpen()) return;512513  // If a selector is already open for this exact field, don't flicker it.514  if (currentDismiss && currentAnchorField === field) return;515516  // If focus moved to a different field, the previous per-field dismiss lock517  // no longer applies.518  if (field !== lastDismissedField) lastDismissedField = null;519  // Layer 1: the user explicitly dismissed this field's selector — don't520  // reopen it until focus has genuinely moved away and come back.521  if (field === lastDismissedField) return;522523  // Fill-success lock: Peach already filled this form (or fired a fill524  // anywhere on the page within the grace window). Sites often refocus an525  // input on submit click, on validation, or on a transition to a success526  // state — none of those should re-open the popup.527  if (wasAlreadyFilled(field)) return;528529  // Prevent two concurrent calls for the same field (e.g. focusin + icon click530  // firing simultaneously — the second call would dismiss the first's selector).531  if (pendingInteractions.has(field)) return;532  pendingInteractions.add(field);533534  try {535    const fieldType = field.type.toLowerCase();536537    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {538      return preds[0] ?? null;539    });540541    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {542      const timeout = setTimeout(() => resolve(null), 150);543      mlPromise.then((pred) => {544        clearTimeout(timeout);545        resolve(pred);546      });547    });548549    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {550      return;551    }552553    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);554    if (autofillFieldType) {555      reattachListeners(field, autofillFieldType);556    }557558    let fields = detectLoginFields();559    const loginForm = isLoginForm(fields);560    const signupForm = isSignupForm(fields);561    if (!loginForm && !signupForm) {562      return;563    }564565    const domain = getPageDomain();566    const firstResult = await fetchAutofillEntries(domain);567568    // Vault is locked — show an inline unlock prompt.569    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so570    // there is no double-trigger race between onUnlocked and the broadcast.571    if (firstResult.locked) {572      currentDismiss?.();573      currentAnchorField = field;574      currentDismiss = showAutofillSelector(575        field,576        [],577        () => {},578        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }579      );580      return;581    }582583    const entries = firstResult.entries;584    const allEntries = entries.length === 0585      ? (await fetchAutofillEntries(domain, true)).entries586      : entries;587588    let usernameEl: HTMLInputElement | null = null;589    const userField = fields.find((f) => f.type === "username" || f.type === "email");590    if (userField) usernameEl = userField.el;591    const pwField = fields.find((f) => f.type === "password");592    if (!pwField) return;593    const passwordEl = pwField.el;594595    if (signupForm && usernameEl && field === usernameEl) {596      await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);597      return;598    }599600    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);601  } finally {602    pendingInteractions.delete(field);603  }604}605606async function onFocusIn(e: Event): Promise<void> {607  // Submit-button focus: catch the brief refocus some sites do when the608  // user clicks the login/submit button. Without this guard, that focus609  // event reaches handleFieldInteraction → getDeepActiveInput, and on610  // pages where the button is also a labelled <input> we briefly attempt611  // to open the popup over the very button the user just clicked.612  if (isSubmitButton(e.target)) return;613  await handleFieldInteraction();614}615616function reattachListeners(617  el: HTMLInputElement,618  detectedType?: "password" | "username" | "email",619  contextFields?: ReturnType<typeof detectLoginFields>620): void {621  if (processedInputs.has(el)) return;622  if (!resolveAutofillFieldType(el, detectedType)) return;623  // Only inject icon when a real login/signup form is present on the page624  const fields = contextFields ?? detectLoginFields();625  if (!isLoginForm(fields) && !isSignupForm(fields)) return;626627  const cleanup = injectFieldIcon(el, () => {628    currentDismiss?.();629    currentDismiss = null;630    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock631    dismissLock = false; // ...and the global lock632    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }633    clearFillStateForExplicitSummon(el);634    el.focus({ preventScroll: true });635    void handleFieldInteraction(el);636  });637  processedInputs.set(el, cleanup);638}639640const debouncedReattach = debounce(() => {641  const allFields = detectLoginFields();642  // Don't inject anything if there's no real login/signup form on this page643  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;644  const newFields = allFields.filter(645    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)646  );647  for (const f of newFields) {648    reattachListeners(f.el, f.type, allFields);649  }650  // 200ms debounce — below this, Peach and the host page's reactive layer651  // fight over the same layout properties every frame on React/Vue/Angular652  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.653}, 200);654655function setupMutationObserver(): void {656  const observer = new MutationObserver(debouncedReattach);657  observer.observe(document.body, {658    childList: true,659    subtree: true,660    attributes: true,661    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],662  });663}664665function initialScan(aggressionLevel = 0, isFinalPass = false) {666  const allFields = detectLoginFields();667  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);668669  if (aggressionLevel === 0 && !hasKnownForm) return;670671  const newFields = allFields.filter(672    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)673  );674675  for (const f of newFields) {676    reattachListeners(f.el, f.type, allFields);677  }678679  // Level 2, final pass: inject icon on any visible password field even if680  // the form-context gate in reattachListeners would normally skip it.681  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {682    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');683    for (const el of pwInputs) {684      if (isVisible(el) && !processedInputs.has(el)) {685        const cleanup = injectFieldIcon(el, () => {686          currentDismiss?.();687          currentDismiss = null;688          lastDismissedField = null;689          dismissLock = false;690          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }691          clearFillStateForExplicitSummon(el);692          el.focus({ preventScroll: true });693          void handleFieldInteraction(el);694        });695        processedInputs.set(el, cleanup);696      }697    }698  }699}700701document.addEventListener("focusin", onFocusIn);702703setupMutationObserver();704setupSaveDetection();705setupCardAutofill();706707// SPA navigation reset: the content script does not reload across in-app708// route changes (history.pushState, hash navigation, framework routers).709// When the URL changes we clear the page-level fill timestamp so the next710// page works normally; filledForms (a WeakSet) self-empties as old form711// elements leave the DOM. subtree:false because route swaps reliably712// mutate document.body's direct children — subtree:true would fire on713// every internal DOM update and cost us a re-check per mutation.714let lastObservedUrl = location.href;715new MutationObserver(() => {716  if (location.href !== lastObservedUrl) {717    lastObservedUrl = location.href;718    pageFilledAt = null;719  }720}).observe(document.body, { childList: true, subtree: false });721722// Async init: check recall map before running the initial scans so we can723// apply the right aggression level for domains the user has needed before.724(async () => {725  let aggressionLevel = 0;726  try {727    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });728    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;729    const domain = getPageDomain();730    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;731    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;732  } catch { /* SW may be starting up; proceed with normal scan */ }733734  setTimeout(() => initialScan(aggressionLevel, false), 0);735  setTimeout(() => initialScan(aggressionLevel, false), 500);736  setTimeout(() => initialScan(aggressionLevel, true), 1500);737})();738739// ── Card autofill (State 7) ─────────────────────────────────────────740// Card forms get a parallel injection path. The login icon-injection gate741// in reattachListeners deliberately skips non-text fields, so we wire742// cards independently rather than retrofit AUTOFILL_FIELD_TYPES — keeping743// card detection contained makes the boundary easy to follow.744const processedCardInputs = new WeakMap<HTMLInputElement, () => void>();745let currentCardDismiss: (() => void) | null = null;746let currentCardAnchor: HTMLInputElement | null = null;747let lastDismissedCardField: HTMLInputElement | null = null;748749async function fetchSavedCards(): Promise<CardSelectorEntry[]> {750  const resp = await chrome.runtime.sendMessage({751    type: "AUTOFILL_QUERY",752    payload: { domain: getPageDomain(), kind: "card" },753  }).catch(() => null);754  const r = resp as { ok: boolean; data?: CardSelectorEntry[] } | null;755  return r?.ok ? (r.data ?? []) : [];756}757758async function openCardSelector(anchor: HTMLInputElement): Promise<void> {759  if (!canOpen()) return;760  if (currentCardDismiss && currentCardAnchor === anchor) return;761  if (anchor === lastDismissedCardField) return;762  if (anchor !== lastDismissedCardField) lastDismissedCardField = null;763  if (wasAlreadyFilled(anchor)) return;764765  const cards = await fetchSavedCards();766  if (cards.length === 0) return; // no saved cards → nothing to offer767768  const cardForm = detectCardForm();769  if (!cardForm?.number) return;770771  currentCardDismiss?.();772  currentCardAnchor = anchor;773  currentCardDismiss = showCardSelector(774    anchor,775    cards,776    {777      domain: getPageDomain(),778      onFill: (entry) => {779        if (!cardForm) return;780        fillCardForm(cardForm, {781          cardNumber: entry.cardNumber ?? "",782          expMonth: entry.expMonth ?? "",783          expYear: entry.expYear ?? "",784          cvc: entry.cvc ?? "",785          cardholderName: entry.cardholderName ?? "",786        });787        // All four card field types share the same form — recording the788        // number field's form is sufficient to suppress reopens on any of789        // them via wasAlreadyFilled().790        recordFillSuccess(cardForm.number, cardForm.cvc, cardForm.expiryCombo, cardForm.name);791        currentCardDismiss = null;792        currentCardAnchor = null;793      },794      onDismiss: () => {795        lastDismissedCardField = anchor;796        startDismissLock();797        currentCardDismiss = null;798        currentCardAnchor = null;799      },800    }801  );802}803804function injectCardIcon(field: HTMLInputElement): void {805  if (processedCardInputs.has(field)) return;806  const cleanup = injectFieldIcon(field, () => {807    currentCardDismiss?.();808    currentCardDismiss = null;809    lastDismissedCardField = null;810    dismissLock = false;811    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }812    clearFillStateForExplicitSummon(field);813    field.focus({ preventScroll: true });814    void openCardSelector(field);815  });816  processedCardInputs.set(field, cleanup);817}818819function setupCardAutofill(): void {820  function scan() {821    const cardForm = detectCardForm();822    if (!cardForm?.number) return;823    if (!isVisible(cardForm.number)) return;824    injectCardIcon(cardForm.number);825  }826827  // Initial detection sweep — same retry cadence as login fields so828  // late-hydrating SPA checkout pages get caught.829  setTimeout(scan, 0);830  setTimeout(scan, 500);831  setTimeout(scan, 1500);832833  // Re-scan on DOM mutation (separate from the login MutationObserver834  // because card forms typically appear on a single navigation event,835  // not field-by-field — coarser observation is sufficient here).836  let pending = false;837  new MutationObserver(() => {838    if (pending) return;839    pending = true;840    setTimeout(() => { pending = false; scan(); }, 200);841  }).observe(document.body, { childList: true, subtree: true });842843  // Field-focus path: on focus of a cc-number input, ensure icon is844  // present and consider opening the selector when the user explicitly845  // clicks into the card number field.846  document.addEventListener("focusin", (e) => {847    const target = e.target;848    if (!(target instanceof HTMLInputElement)) return;849    const cardForm = detectCardForm();850    if (cardForm?.number === target) {851      injectCardIcon(target);852    }853  }, true);854}855856chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {857  // Ignore anything not originating from our own background/service worker.858  if (sender.id !== chrome.runtime.id) return;859  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {860    const policy = detectPasswordPolicy();861    sendResponse({ ok: true, data: policy });862    return true;863  }864  if (msg?.type === "PING") {865    sendResponse({ ok: true });866    return true;867  }868  if (msg?.type === "SUMMON_AUTOFILL") {869    const source = (msg as { type: string; source?: string }).source;870    const isShortcut = source === "shortcut";871872    const activeInput = getDeepActiveInput();873    const fields = detectLoginFields();874    const hasForm = isLoginForm(fields) || isSignupForm(fields);875876    if (hasForm) {877      // Prefer the currently focused field if it's a login field, otherwise878      // fall back to the first password field, then username/email.879      const inForm = activeInput && fields.some(f => f.el === activeInput);880      const target = inForm881        ? activeInput882        : (fields.find(f => f.type === "password")?.el883            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);884      if (target) {885        // Explicit user summon (shortcut or extension button) — bypass all886        // suppression layers. The user is asking for the popup right now.887        clearFillStateForExplicitSummon(target);888        dismissLock = false;889        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }890        lastDismissedField = null;891        void handleFieldInteraction(target);892      }893    } else if (isShortcut) {894      // Shortcut on a page with no login form — show clipboard-copy search mode.895      showSearchPalette();896    }897898    // Record this domain for the recall system when triggered via shortcut.899    if (isShortcut) {900      const domain = getPageDomain();901      if (domain) {902        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});903      }904    }905906    sendResponse({ ok: hasForm || isShortcut });907    return true;908  }909  if (msg?.type === "VAULT_UNLOCKED") {910    // Close any open selector (e.g. the locked-state prompt) and re-open911    // with fresh entry data. Use the saved anchor field so we reopen exactly912    // where the user was — covers both inline unlock and popup unlock.913    const savedField = currentAnchorField;914    if (currentDismiss) {915      currentDismiss();916      currentDismiss = null;917      currentAnchorField = null;918    }919    void handleFieldInteraction(savedField ?? undefined);920    sendResponse({ ok: true });921    return true;922  }923  return true;924});