index.ts

29.1 KB · raw

1import {2  detectLoginFields,3  getDeepActiveInput,4  getPageDomain,5  isLoginForm,6  isSignupForm,7  isVisible,8} from "./detect";9import {10  injectFieldIcon,11  observeAnchorPosition,12  SelectorEntry,13  showAutofillSelector,14  showRememberSiteToast,15} from "./inject";16import { fillFields } from "./fill";17import { setupSaveDetection } from "./save";18import { contentMLDetector } from "./content-ml-detector";19import { detectPasswordPolicy } from "./policy";20import type { FieldPrediction } from "../shared/ml";21import { generateTOTP } from "../crypto/totp";22import type { VaultEntry } from "../shared/types";2324// WeakMap (not WeakSet) — we keep the per-input cleanup callback as the value25// so we can tear down listeners if we ever need to re-process the same field.26// When the input is GC'd (SPA nav, React re-render), the map entry goes with27// it and we can re-inject without leaking the old handler.28const processedInputs = new WeakMap<HTMLInputElement, () => void>();29const AUTOFILL_FIELD_TYPES = new Set(["password", "username", "email"]);3031let currentDismiss: (() => void) | null = null;32// Field whose selector is currently open — used to avoid dismiss+reopen flicker33let currentAnchorField: HTMLInputElement | null = null;34// Prevents two concurrent handleFieldInteraction calls for the same field35const pendingInteractions = new WeakSet<HTMLInputElement>();36// Tracks the last field the user explicitly dismissed (Escape / click-outside / Tab).37// Suppresses spurious reopens until focus moves to a different field. Layer 138// of the dismissal model — see Projects.md §4.12.39let lastDismissedField: HTMLInputElement | null = null;4041// ── Dismissal lock (Layer 2) ────────────────────────────────────────42// After any user-initiated dismiss, briefly block ALL reopens regardless of43// which field is focused. Catches the case where a page rapidly moves focus44// between fields after Escape — without this, focus moving to a SECOND field45// in <100ms would re-trigger the popup before the user finished dismissing.46const DISMISS_LOCK_MS = 800;47let dismissLock = false;48let dismissLockTimer: ReturnType<typeof setTimeout> | null = null;49function startDismissLock(): void {50  dismissLock = true;51  if (dismissLockTimer) clearTimeout(dismissLockTimer);52  dismissLockTimer = setTimeout(() => { dismissLock = false; }, DISMISS_LOCK_MS);53}54function canOpen(): boolean { return !dismissLock; }5556// ── Fill-success lock ───────────────────────────────────────────────57// After Peach autofills a form, the popup must NOT reappear on the filled58// fields, on the submit button (some sites refocus it briefly), or on any59// field in that form — even when host-page DOM mutations or the form's own60// validation flow refocus an input. Implemented as a WeakSet of forms plus61// a page-level timestamp:62//   - filledForms: every form Peach has filled this page session. Survives63//     until the form leaves the DOM (WeakSet GC).64//   - pageFilledAt: timestamp of last fill. Used as a 3s belt-and-suspenders65//     window for fields that aren't inside a <form> element (some SPAs).66// SPA navigation resets pageFilledAt via the urlObserver below; filledForms67// self-empties as old form elements get GC'd.68const filledForms = new WeakSet<HTMLFormElement>();69let pageFilledAt: number | null = null;70const PAGE_FILL_GRACE_MS = 3000;7172function recordFillSuccess(...fields: (HTMLInputElement | null | undefined)[]): void {73  for (const f of fields) {74    if (!f) continue;75    const form = f.closest("form");76    if (form) filledForms.add(form);77  }78  pageFilledAt = Date.now();79}8081function wasAlreadyFilled(field: HTMLInputElement): boolean {82  const form = field.closest("form");83  if (form && filledForms.has(form)) return true;84  if (pageFilledAt !== null && Date.now() - pageFilledAt < PAGE_FILL_GRACE_MS) return true;85  return false;86}8788function clearFillStateForExplicitSummon(field: HTMLInputElement): void {89  const form = field.closest("form");90  if (form) filledForms.delete(form);91  pageFilledAt = null;92}9394// Some sites briefly focus the submit button when the user clicks it (visual95// feedback, blur/focus dance for validation animations). Catch those at the96// focusin layer so we don't re-trigger handleFieldInteraction for an event97// target that was never going to be a credential field anyway.98function isSubmitButton(el: EventTarget | null): boolean {99  if (!(el instanceof HTMLElement)) return false;100  if (el instanceof HTMLButtonElement && el.type !== "button") return true;101  if (el instanceof HTMLInputElement && el.type === "submit") return true;102  if (el.getAttribute("type") === "submit") return true;103  const text = (el.textContent?.trim() ?? el.getAttribute("value") ?? "").toLowerCase();104  if (!text || text.length > 24) return false;105  return /^(submit|sign[ -]?in|log[ -]?in|continue|next|go)$/i.test(text);106}107108function debounce<T extends (...args: unknown[]) => void>(109  fn: T,110  ms: number111): (...args: Parameters<T>) => void {112  let timer: ReturnType<typeof setTimeout>;113  return (...args: Parameters<T>) => {114    clearTimeout(timer);115    timer = setTimeout(() => fn(...args), ms);116  };117}118119function showToast(message: string): void {120  const toast = document.createElement("div");121  toast.style.cssText = `122    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);123    background: #131109; color: #F0E8D8; padding: 8px 16px;124    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;125    font-size: 11px; z-index: 2147483647; opacity: 0;126    transition: opacity 200ms ease;127    border: 1px solid rgba(240,232,216,0.07);128    pointer-events: none;129  `;130  toast.textContent = message;131  document.body.appendChild(toast);132  requestAnimationFrame(() => { toast.style.opacity = "1"; });133  setTimeout(() => {134    toast.style.opacity = "0";135    setTimeout(() => toast.remove(), 200);136  }, 2000);137}138139function showSearchPalette(): void {140  const host = document.createElement("div");141  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";142  document.body.appendChild(host);143  const shadow = host.attachShadow({ mode: "closed" });144145  const style = document.createElement("style");146  style.textContent = `147    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;148      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;149      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}150    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);151      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}152    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}153    .s{padding:8px 12px}154    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);155      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;156      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}157    .l{max-height:220px;overflow-y:auto}158    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}159    .e:hover{background:rgba(240,232,216,.06)}160    .et{font-size:12px}161    .eu{font-size:10px;color:rgba(240,232,216,.45)}162    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}163  `;164165  let allEntries: SelectorEntry[] = [];166  let query = "";167168  const panel = document.createElement("div");169  panel.className = "p";170171  const hdr = document.createElement("div");172  hdr.className = "h";173  const hdrText = document.createElement("span");174  hdrText.textContent = "No form detected — search your vault";175  const closeBtn = document.createElement("button");176  closeBtn.className = "x";177  closeBtn.textContent = "✕";178  hdr.appendChild(hdrText);179  hdr.appendChild(closeBtn);180181  const searchWrap = document.createElement("div");182  searchWrap.className = "s";183  const searchInput = document.createElement("input");184  searchInput.placeholder = "search...";185  searchWrap.appendChild(searchInput);186187  const list = document.createElement("div");188  list.className = "l";189190  panel.appendChild(hdr);191  panel.appendChild(searchWrap);192  panel.appendChild(list);193  shadow.appendChild(style);194  shadow.appendChild(panel);195196  function close() { host.remove(); }197198  closeBtn.onclick = close;199200  function onKeyDown(e: KeyboardEvent) {201    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }202  }203  document.addEventListener("keydown", onKeyDown, true);204205  function render() {206    const q = query.toLowerCase();207    const filtered = q208      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))209      : allEntries;210    list.innerHTML = "";211    if (filtered.length === 0) {212      const em = document.createElement("div");213      em.className = "em";214      em.textContent = query ? "no matches" : "vault is empty";215      list.appendChild(em);216      return;217    }218    for (const entry of filtered.slice(0, 20)) {219      const row = document.createElement("div");220      row.className = "e";221      const title = document.createElement("div");222      title.className = "et";223      title.textContent = entry.title;224      row.appendChild(title);225      if (entry.username) {226        const user = document.createElement("div");227        user.className = "eu";228        user.textContent = entry.username;229        row.appendChild(user);230      }231      row.onclick = async () => {232        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });233        const r = resp as { ok: boolean; data?: { password?: string } };234        if (r.ok && r.data?.password) {235          let alreadyWritten = false;236          try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}237          await chrome.runtime.sendMessage({238            type: "COPY",239            payload: { text: r.data.password, label: "Password", alreadyWritten },240          });241          showToast("Password copied");242        } else {243          showToast("Could not copy password");244        }245        close();246        document.removeEventListener("keydown", onKeyDown, true);247      };248      list.appendChild(row);249    }250  }251252  searchInput.oninput = () => { query = searchInput.value; render(); };253254  fetchAutofillEntries(getPageDomain(), true).then(result => {255    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }256    allEntries = result.entries;257    render();258    searchInput.focus();259  });260}261262function setNativeValue(el: HTMLInputElement, value: string): void {263  const nativeSetter = Object.getOwnPropertyDescriptor(264    HTMLInputElement.prototype, "value"265  )!.set!;266  nativeSetter.call(el, value);267  el.dispatchEvent(new Event("input", { bubbles: true }));268  el.dispatchEvent(new Event("change", { bubbles: true }));269}270271function findTOTPField(): HTMLInputElement | null {272  const inputs = document.querySelectorAll<HTMLInputElement>("input");273  for (const input of inputs) {274    if (!isVisible(input)) continue;275    const autocomplete = input.autocomplete.toLowerCase();276    const nameId = (input.name + input.id).toLowerCase();277    const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();278    if (279      autocomplete === "one-time-code" ||280      /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)281    ) {282      return input;283    }284    const labelEl = input.closest("label");285    if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {286      return input;287    }288  }289  return null;290}291292async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {293  await new Promise((r) => setTimeout(r, 400));294  if (totpField.value === "" || totpField.value.trim() === "") {295    const { code } = generateTOTP(totpSecret);296    setNativeValue(totpField, code);297    showToast("TOTP autofilled");298  }299}300301302async function handleAutofill(303  field: HTMLInputElement,304  usernameEl: HTMLInputElement | null,305  passwordEl: HTMLInputElement,306  entry: VaultEntry307): Promise<void> {308  if (!entry.username && !entry.password) return;309  const pageDomain = getPageDomain();310  const form = passwordEl.closest("form") as HTMLFormElement | null;311  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);312313  if (entry.canary) {314    chrome.runtime.sendMessage({315      type: "FIRE_CANARY_PING",316      payload: {317        webhookUrl: entry.canary.webhookUrl,318        entryTitle: entry.title,319        trigger: "autofilled",320      },321    }).catch(() => {});322    chrome.runtime.sendMessage({323      type: "UPDATE_ENTRY",324      payload: {325        id: entry.id,326        patch: {327          canary: {328            ...entry.canary,329            lastPinged: Date.now(),330            pingCount: (entry.canary.pingCount ?? 0) + 1,331          },332        },333      },334    }).catch(() => {});335  }336337  if (entry.totp) {338    const { code } = generateTOTP(entry.totp);339    let alreadyWritten = false;340    try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}341    const response = await chrome.runtime.sendMessage({342      type: "COPY",343      payload: { text: code, label: "TOTP", alreadyWritten },344    });345    if (alreadyWritten || (response as { ok?: boolean }).ok) {346      showToast("TOTP copied · " + code);347    }348    const totpField = findTOTPField();349    if (totpField) {350      autofillTOTP(totpField, entry.totp);351    }352  }353}354355async function fetchAutofillEntries(356  domain: string,357  includeAll = false358): Promise<{ entries: SelectorEntry[]; locked: boolean }> {359  const response = await chrome.runtime.sendMessage({360    type: "AUTOFILL_QUERY",361    payload: { domain, includeAll },362  });363  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };364  if (!res.ok && res.error === "VAULT_LOCKED") {365    return { entries: [], locked: true };366  }367  return { entries: res.data ?? [], locked: false };368}369370371function resolveAutofillFieldType(372  el: HTMLInputElement,373  predictedType?: FieldPrediction["type"] | null374): "password" | "username" | "email" | null {375  if (376    predictedType === "password" ||377    predictedType === "username" ||378    predictedType === "email"379  ) {380    return predictedType;381  }382383  const detected = detectLoginFields().find((field) => field.el === el)?.type;384  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {385    return detected;386  }387388  const htmlType = el.type.toLowerCase();389  if (htmlType === "password") return "password";390  if (htmlType === "email") return "email";391  return null;392}393394async function openAutofillSelector(395  anchorField: HTMLInputElement,396  usernameEl: HTMLInputElement | null,397  passwordEl: HTMLInputElement,398  domainEntries: SelectorEntry[],399  searchableEntries: SelectorEntry[],400  domain: string401): Promise<void> {402  currentDismiss?.();403  currentAnchorField = anchorField;404  currentDismiss = showAutofillSelector(405    anchorField,406    domainEntries,407    async (id: string) => {408      currentDismiss = null;409      currentAnchorField = null;410      const entryResponse = await chrome.runtime.sendMessage({411        type: "GET_ENTRY_FOR_FILL",412        payload: { id },413      });414      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;415      if (entry) {416        await handleAutofill(anchorField, usernameEl, passwordEl, entry);417        recordFillSuccess(anchorField, usernameEl, passwordEl);418        // Offer to remember the current site for this entry only if none of419        // its known domains (primary + additional) match — otherwise the420        // user already mapped it and the prompt would be noise.421        const pageDomain = location.hostname.replace(/^www\./, "");422        const entryDomains = new Set<string>();423        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {424          try {425            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));426          } catch { /* ignore unparseable */ }427        }428        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {429          showRememberSiteToast(pageDomain, entry.id);430        }431      }432    },433    {434      domain,435      searchableEntries,436      // After State 5 (new entry) save: fill the detected fields with the437      // freshly-created credentials so the user can submit immediately.438      // On a login form the user created the entry to use here; on a signup439      // form the password was generated for this site. Same outcome either440      // way — the credentials land in the form and the popup exits.441      onFillFields: (username, password) => {442        const form = passwordEl.closest("form") as HTMLFormElement | null;443        fillFields(usernameEl, passwordEl, username, password, form, getPageDomain());444        recordFillSuccess(anchorField, usernameEl, passwordEl);445      },446      onDismiss: () => { lastDismissedField = anchorField; startDismissLock(); },447    }448  );449}450451async function openSignupSelector(452  usernameEl: HTMLInputElement,453  passwordEl: HTMLInputElement | null,454  domainEntries: SelectorEntry[],455  allEntries: SelectorEntry[],456  domain: string457): Promise<void> {458  currentDismiss?.();459  currentAnchorField = usernameEl;460  currentDismiss = showAutofillSelector(461    usernameEl,462    domainEntries,463    () => {}, // identity-click handled via onFillFields464    {465      domain,466      searchableEntries: allEntries,467      isSignup: true,468      onFillFields: (username, password) => {469        if (username) setNativeValue(usernameEl, username);470        if (password && passwordEl) setNativeValue(passwordEl, password);471        recordFillSuccess(usernameEl, passwordEl);472      },473      onDismiss: () => { lastDismissedField = usernameEl; startDismissLock(); },474    }475  );476}477478479async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {480  const field = anchorField ?? getDeepActiveInput();481  if (!field) return;482  if (!isVisible(field)) return;483484  // Layer 2: post-dismiss global lock. Catches rapid focus moves between485  // fields immediately after Escape/click-outside.486  if (!canOpen()) return;487488  // If a selector is already open for this exact field, don't flicker it.489  if (currentDismiss && currentAnchorField === field) return;490491  // If focus moved to a different field, the previous per-field dismiss lock492  // no longer applies.493  if (field !== lastDismissedField) lastDismissedField = null;494  // Layer 1: the user explicitly dismissed this field's selector — don't495  // reopen it until focus has genuinely moved away and come back.496  if (field === lastDismissedField) return;497498  // Fill-success lock: Peach already filled this form (or fired a fill499  // anywhere on the page within the grace window). Sites often refocus an500  // input on submit click, on validation, or on a transition to a success501  // state — none of those should re-open the popup.502  if (wasAlreadyFilled(field)) return;503504  // Prevent two concurrent calls for the same field (e.g. focusin + icon click505  // firing simultaneously — the second call would dismiss the first's selector).506  if (pendingInteractions.has(field)) return;507  pendingInteractions.add(field);508509  try {510    const fieldType = field.type.toLowerCase();511512    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {513      return preds[0] ?? null;514    });515516    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {517      const timeout = setTimeout(() => resolve(null), 150);518      mlPromise.then((pred) => {519        clearTimeout(timeout);520        resolve(pred);521      });522    });523524    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {525      return;526    }527528    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);529    if (autofillFieldType) {530      reattachListeners(field, autofillFieldType);531    }532533    let fields = detectLoginFields();534    const loginForm = isLoginForm(fields);535    const signupForm = isSignupForm(fields);536    if (!loginForm && !signupForm) {537      return;538    }539540    const domain = getPageDomain();541    const firstResult = await fetchAutofillEntries(domain);542543    // Vault is locked — show an inline unlock prompt.544    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so545    // there is no double-trigger race between onUnlocked and the broadcast.546    if (firstResult.locked) {547      currentDismiss?.();548      currentAnchorField = field;549      currentDismiss = showAutofillSelector(550        field,551        [],552        () => {},553        { domain, locked: true, onDismiss: () => { lastDismissedField = field; startDismissLock(); } }554      );555      return;556    }557558    const entries = firstResult.entries;559    const allEntries = entries.length === 0560      ? (await fetchAutofillEntries(domain, true)).entries561      : entries;562563    let usernameEl: HTMLInputElement | null = null;564    const userField = fields.find((f) => f.type === "username" || f.type === "email");565    if (userField) usernameEl = userField.el;566    const pwField = fields.find((f) => f.type === "password");567    if (!pwField) return;568    const passwordEl = pwField.el;569570    if (signupForm && usernameEl && field === usernameEl) {571      await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);572      return;573    }574575    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);576  } finally {577    pendingInteractions.delete(field);578  }579}580581async function onFocusIn(e: Event): Promise<void> {582  // Submit-button focus: catch the brief refocus some sites do when the583  // user clicks the login/submit button. Without this guard, that focus584  // event reaches handleFieldInteraction → getDeepActiveInput, and on585  // pages where the button is also a labelled <input> we briefly attempt586  // to open the popup over the very button the user just clicked.587  if (isSubmitButton(e.target)) return;588  await handleFieldInteraction();589}590591function reattachListeners(592  el: HTMLInputElement,593  detectedType?: "password" | "username" | "email",594  contextFields?: ReturnType<typeof detectLoginFields>595): void {596  if (processedInputs.has(el)) return;597  if (!resolveAutofillFieldType(el, detectedType)) return;598  // Only inject icon when a real login/signup form is present on the page599  const fields = contextFields ?? detectLoginFields();600  if (!isLoginForm(fields) && !isSignupForm(fields)) return;601602  const cleanup = injectFieldIcon(el, () => {603    currentDismiss?.();604    currentDismiss = null;605    lastDismissedField = null; // icon click is an explicit user open — clear per-field lock606    dismissLock = false; // ...and the global lock607    if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }608    clearFillStateForExplicitSummon(el);609    el.focus({ preventScroll: true });610    void handleFieldInteraction(el);611  });612  processedInputs.set(el, cleanup);613}614615const debouncedReattach = debounce(() => {616  const allFields = detectLoginFields();617  // Don't inject anything if there's no real login/signup form on this page618  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;619  const newFields = allFields.filter(620    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)621  );622  for (const f of newFields) {623    reattachListeners(f.el, f.type, allFields);624  }625  // 200ms debounce — below this, Peach and the host page's reactive layer626  // fight over the same layout properties every frame on React/Vue/Angular627  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.628}, 200);629630function setupMutationObserver(): void {631  const observer = new MutationObserver(debouncedReattach);632  observer.observe(document.body, {633    childList: true,634    subtree: true,635    attributes: true,636    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],637  });638}639640function initialScan(aggressionLevel = 0, isFinalPass = false) {641  const allFields = detectLoginFields();642  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);643644  if (aggressionLevel === 0 && !hasKnownForm) return;645646  const newFields = allFields.filter(647    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)648  );649650  for (const f of newFields) {651    reattachListeners(f.el, f.type, allFields);652  }653654  // Level 2, final pass: inject icon on any visible password field even if655  // the form-context gate in reattachListeners would normally skip it.656  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {657    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');658    for (const el of pwInputs) {659      if (isVisible(el) && !processedInputs.has(el)) {660        const cleanup = injectFieldIcon(el, () => {661          currentDismiss?.();662          currentDismiss = null;663          lastDismissedField = null;664          dismissLock = false;665          if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }666          clearFillStateForExplicitSummon(el);667          el.focus({ preventScroll: true });668          void handleFieldInteraction(el);669        });670        processedInputs.set(el, cleanup);671      }672    }673  }674}675676document.addEventListener("focusin", onFocusIn);677678setupMutationObserver();679setupSaveDetection();680681// SPA navigation reset: the content script does not reload across in-app682// route changes (history.pushState, hash navigation, framework routers).683// When the URL changes we clear the page-level fill timestamp so the next684// page works normally; filledForms (a WeakSet) self-empties as old form685// elements leave the DOM. subtree:false because route swaps reliably686// mutate document.body's direct children — subtree:true would fire on687// every internal DOM update and cost us a re-check per mutation.688let lastObservedUrl = location.href;689new MutationObserver(() => {690  if (location.href !== lastObservedUrl) {691    lastObservedUrl = location.href;692    pageFilledAt = null;693  }694}).observe(document.body, { childList: true, subtree: false });695696// Async init: check recall map before running the initial scans so we can697// apply the right aggression level for domains the user has needed before.698(async () => {699  let aggressionLevel = 0;700  try {701    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });702    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;703    const domain = getPageDomain();704    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;705    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;706  } catch { /* SW may be starting up; proceed with normal scan */ }707708  setTimeout(() => initialScan(aggressionLevel, false), 0);709  setTimeout(() => initialScan(aggressionLevel, false), 500);710  setTimeout(() => initialScan(aggressionLevel, true), 1500);711})();712713chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {714  // Ignore anything not originating from our own background/service worker.715  if (sender.id !== chrome.runtime.id) return;716  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {717    const policy = detectPasswordPolicy();718    sendResponse({ ok: true, data: policy });719    return true;720  }721  if (msg?.type === "PING") {722    sendResponse({ ok: true });723    return true;724  }725  if (msg?.type === "SUMMON_AUTOFILL") {726    const source = (msg as { type: string; source?: string }).source;727    const isShortcut = source === "shortcut";728729    const activeInput = getDeepActiveInput();730    const fields = detectLoginFields();731    const hasForm = isLoginForm(fields) || isSignupForm(fields);732733    if (hasForm) {734      // Prefer the currently focused field if it's a login field, otherwise735      // fall back to the first password field, then username/email.736      const inForm = activeInput && fields.some(f => f.el === activeInput);737      const target = inForm738        ? activeInput739        : (fields.find(f => f.type === "password")?.el740            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);741      if (target) {742        // Explicit user summon (shortcut or extension button) — bypass all743        // suppression layers. The user is asking for the popup right now.744        clearFillStateForExplicitSummon(target);745        dismissLock = false;746        if (dismissLockTimer) { clearTimeout(dismissLockTimer); dismissLockTimer = null; }747        lastDismissedField = null;748        void handleFieldInteraction(target);749      }750    } else if (isShortcut) {751      // Shortcut on a page with no login form — show clipboard-copy search mode.752      showSearchPalette();753    }754755    // Record this domain for the recall system when triggered via shortcut.756    if (isShortcut) {757      const domain = getPageDomain();758      if (domain) {759        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});760      }761    }762763    sendResponse({ ok: hasForm || isShortcut });764    return true;765  }766  if (msg?.type === "VAULT_UNLOCKED") {767    // Close any open selector (e.g. the locked-state prompt) and re-open768    // with fresh entry data. Use the saved anchor field so we reopen exactly769    // where the user was — covers both inline unlock and popup unlock.770    const savedField = currentAnchorField;771    if (currentDismiss) {772      currentDismiss();773      currentDismiss = null;774      currentAnchorField = null;775    }776    void handleFieldInteraction(savedField ?? undefined);777    sendResponse({ ok: true });778    return true;779  }780  return true;781});