index.ts

23.9 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.38let lastDismissedField: HTMLInputElement | null = null;3940// Fields that were just autofilled — suppress popup reopens on them briefly.41// Some sites refocus an input on form submit (validation flows, animation42// blur/focus, framework handlers), which would otherwise re-trigger the43// selector right as the user clicks the login button. Cleared by explicit44// user-summon (icon click, keyboard shortcut) or after AUTOFILL_SUPPRESS_MS.45const recentlyAutofilledFields = new WeakSet<HTMLInputElement>();46const AUTOFILL_SUPPRESS_MS = 5000;47function markAutofilled(...fields: (HTMLInputElement | null | undefined)[]): void {48  for (const f of fields) {49    if (!f) continue;50    recentlyAutofilledFields.add(f);51    setTimeout(() => recentlyAutofilledFields.delete(f), AUTOFILL_SUPPRESS_MS);52  }53}5455function debounce<T extends (...args: unknown[]) => void>(56  fn: T,57  ms: number58): (...args: Parameters<T>) => void {59  let timer: ReturnType<typeof setTimeout>;60  return (...args: Parameters<T>) => {61    clearTimeout(timer);62    timer = setTimeout(() => fn(...args), ms);63  };64}6566function showToast(message: string): void {67  const toast = document.createElement("div");68  toast.style.cssText = `69    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);70    background: #131109; color: #F0E8D8; padding: 8px 16px;71    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;72    font-size: 11px; z-index: 2147483647; opacity: 0;73    transition: opacity 200ms ease;74    border: 1px solid rgba(240,232,216,0.07);75    pointer-events: none;76  `;77  toast.textContent = message;78  document.body.appendChild(toast);79  requestAnimationFrame(() => { toast.style.opacity = "1"; });80  setTimeout(() => {81    toast.style.opacity = "0";82    setTimeout(() => toast.remove(), 200);83  }, 2000);84}8586function showSearchPalette(): void {87  const host = document.createElement("div");88  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";89  document.body.appendChild(host);90  const shadow = host.attachShadow({ mode: "closed" });9192  const style = document.createElement("style");93  style.textContent = `94    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;95      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;96      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}97    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);98      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}99    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}100    .s{padding:8px 12px}101    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);102      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;103      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}104    .l{max-height:220px;overflow-y:auto}105    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}106    .e:hover{background:rgba(240,232,216,.06)}107    .et{font-size:12px}108    .eu{font-size:10px;color:rgba(240,232,216,.45)}109    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}110  `;111112  let allEntries: SelectorEntry[] = [];113  let query = "";114115  const panel = document.createElement("div");116  panel.className = "p";117118  const hdr = document.createElement("div");119  hdr.className = "h";120  const hdrText = document.createElement("span");121  hdrText.textContent = "No form detected — search your vault";122  const closeBtn = document.createElement("button");123  closeBtn.className = "x";124  closeBtn.textContent = "✕";125  hdr.appendChild(hdrText);126  hdr.appendChild(closeBtn);127128  const searchWrap = document.createElement("div");129  searchWrap.className = "s";130  const searchInput = document.createElement("input");131  searchInput.placeholder = "search...";132  searchWrap.appendChild(searchInput);133134  const list = document.createElement("div");135  list.className = "l";136137  panel.appendChild(hdr);138  panel.appendChild(searchWrap);139  panel.appendChild(list);140  shadow.appendChild(style);141  shadow.appendChild(panel);142143  function close() { host.remove(); }144145  closeBtn.onclick = close;146147  function onKeyDown(e: KeyboardEvent) {148    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }149  }150  document.addEventListener("keydown", onKeyDown, true);151152  function render() {153    const q = query.toLowerCase();154    const filtered = q155      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))156      : allEntries;157    list.innerHTML = "";158    if (filtered.length === 0) {159      const em = document.createElement("div");160      em.className = "em";161      em.textContent = query ? "no matches" : "vault is empty";162      list.appendChild(em);163      return;164    }165    for (const entry of filtered.slice(0, 20)) {166      const row = document.createElement("div");167      row.className = "e";168      const title = document.createElement("div");169      title.className = "et";170      title.textContent = entry.title;171      row.appendChild(title);172      if (entry.username) {173        const user = document.createElement("div");174        user.className = "eu";175        user.textContent = entry.username;176        row.appendChild(user);177      }178      row.onclick = async () => {179        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });180        const r = resp as { ok: boolean; data?: { password?: string } };181        if (r.ok && r.data?.password) {182          let alreadyWritten = false;183          try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}184          await chrome.runtime.sendMessage({185            type: "COPY",186            payload: { text: r.data.password, label: "Password", alreadyWritten },187          });188          showToast("Password copied");189        } else {190          showToast("Could not copy password");191        }192        close();193        document.removeEventListener("keydown", onKeyDown, true);194      };195      list.appendChild(row);196    }197  }198199  searchInput.oninput = () => { query = searchInput.value; render(); };200201  fetchAutofillEntries(getPageDomain(), true).then(result => {202    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }203    allEntries = result.entries;204    render();205    searchInput.focus();206  });207}208209function setNativeValue(el: HTMLInputElement, value: string): void {210  const nativeSetter = Object.getOwnPropertyDescriptor(211    HTMLInputElement.prototype, "value"212  )!.set!;213  nativeSetter.call(el, value);214  el.dispatchEvent(new Event("input", { bubbles: true }));215  el.dispatchEvent(new Event("change", { bubbles: true }));216}217218function findTOTPField(): HTMLInputElement | null {219  const inputs = document.querySelectorAll<HTMLInputElement>("input");220  for (const input of inputs) {221    if (!isVisible(input)) continue;222    const autocomplete = input.autocomplete.toLowerCase();223    const nameId = (input.name + input.id).toLowerCase();224    const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();225    if (226      autocomplete === "one-time-code" ||227      /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)228    ) {229      return input;230    }231    const labelEl = input.closest("label");232    if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {233      return input;234    }235  }236  return null;237}238239async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {240  await new Promise((r) => setTimeout(r, 400));241  if (totpField.value === "" || totpField.value.trim() === "") {242    const { code } = generateTOTP(totpSecret);243    setNativeValue(totpField, code);244    showToast("TOTP autofilled");245  }246}247248249async function handleAutofill(250  field: HTMLInputElement,251  usernameEl: HTMLInputElement | null,252  passwordEl: HTMLInputElement,253  entry: VaultEntry254): Promise<void> {255  if (!entry.username && !entry.password) return;256  const pageDomain = getPageDomain();257  const form = passwordEl.closest("form") as HTMLFormElement | null;258  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);259260  if (entry.canary) {261    chrome.runtime.sendMessage({262      type: "FIRE_CANARY_PING",263      payload: {264        webhookUrl: entry.canary.webhookUrl,265        entryTitle: entry.title,266        trigger: "autofilled",267      },268    }).catch(() => {});269    chrome.runtime.sendMessage({270      type: "UPDATE_ENTRY",271      payload: {272        id: entry.id,273        patch: {274          canary: {275            ...entry.canary,276            lastPinged: Date.now(),277            pingCount: (entry.canary.pingCount ?? 0) + 1,278          },279        },280      },281    }).catch(() => {});282  }283284  if (entry.totp) {285    const { code } = generateTOTP(entry.totp);286    let alreadyWritten = false;287    try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}288    const response = await chrome.runtime.sendMessage({289      type: "COPY",290      payload: { text: code, label: "TOTP", alreadyWritten },291    });292    if (alreadyWritten || (response as { ok?: boolean }).ok) {293      showToast("TOTP copied · " + code);294    }295    const totpField = findTOTPField();296    if (totpField) {297      autofillTOTP(totpField, entry.totp);298    }299  }300}301302async function fetchAutofillEntries(303  domain: string,304  includeAll = false305): Promise<{ entries: SelectorEntry[]; locked: boolean }> {306  const response = await chrome.runtime.sendMessage({307    type: "AUTOFILL_QUERY",308    payload: { domain, includeAll },309  });310  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };311  if (!res.ok && res.error === "VAULT_LOCKED") {312    return { entries: [], locked: true };313  }314  return { entries: res.data ?? [], locked: false };315}316317318function resolveAutofillFieldType(319  el: HTMLInputElement,320  predictedType?: FieldPrediction["type"] | null321): "password" | "username" | "email" | null {322  if (323    predictedType === "password" ||324    predictedType === "username" ||325    predictedType === "email"326  ) {327    return predictedType;328  }329330  const detected = detectLoginFields().find((field) => field.el === el)?.type;331  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {332    return detected;333  }334335  const htmlType = el.type.toLowerCase();336  if (htmlType === "password") return "password";337  if (htmlType === "email") return "email";338  return null;339}340341async function openAutofillSelector(342  anchorField: HTMLInputElement,343  usernameEl: HTMLInputElement | null,344  passwordEl: HTMLInputElement,345  domainEntries: SelectorEntry[],346  searchableEntries: SelectorEntry[],347  domain: string348): Promise<void> {349  currentDismiss?.();350  currentAnchorField = anchorField;351  currentDismiss = showAutofillSelector(352    anchorField,353    domainEntries,354    async (id: string) => {355      currentDismiss = null;356      currentAnchorField = null;357      const entryResponse = await chrome.runtime.sendMessage({358        type: "GET_ENTRY_FOR_FILL",359        payload: { id },360      });361      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;362      if (entry) {363        await handleAutofill(anchorField, usernameEl, passwordEl, entry);364        markAutofilled(anchorField, usernameEl, passwordEl);365        // Offer to remember the current site for this entry only if none of366        // its known domains (primary + additional) match — otherwise the367        // user already mapped it and the prompt would be noise.368        const pageDomain = location.hostname.replace(/^www\./, "");369        const entryDomains = new Set<string>();370        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {371          try {372            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));373          } catch { /* ignore unparseable */ }374        }375        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {376          showRememberSiteToast(pageDomain, entry.id);377        }378      }379    },380    {381      domain,382      searchableEntries,383      onDismiss: () => { lastDismissedField = anchorField; },384    }385  );386}387388async function openSignupSelector(389  usernameEl: HTMLInputElement,390  passwordEl: HTMLInputElement | null,391  domainEntries: SelectorEntry[],392  allEntries: SelectorEntry[],393  domain: string394): Promise<void> {395  currentDismiss?.();396  currentAnchorField = usernameEl;397  currentDismiss = showAutofillSelector(398    usernameEl,399    domainEntries,400    () => {}, // identity-click handled via onFillFields401    {402      domain,403      searchableEntries: allEntries,404      isSignup: true,405      onFillFields: (username, password) => {406        if (username) setNativeValue(usernameEl, username);407        if (password && passwordEl) setNativeValue(passwordEl, password);408      },409      onDismiss: () => { lastDismissedField = usernameEl; },410    }411  );412}413414415async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {416  const field = anchorField ?? getDeepActiveInput();417  if (!field) return;418  if (!isVisible(field)) return;419420  // If a selector is already open for this exact field, don't flicker it.421  if (currentDismiss && currentAnchorField === field) return;422423  // If focus moved to a different field, the previous dismiss lock no longer applies.424  if (field !== lastDismissedField) lastDismissedField = null;425  // The user explicitly dismissed this field's selector — don't reopen it until426  // focus has genuinely moved away and come back.427  if (field === lastDismissedField) return;428429  // Field was just autofilled — sites often refocus an input on submit click,430  // which would otherwise re-trigger the selector right when the user is431  // trying to log in. Bail unless the user explicitly summoned us.432  if (recentlyAutofilledFields.has(field)) return;433434  // Prevent two concurrent calls for the same field (e.g. focusin + icon click435  // firing simultaneously — the second call would dismiss the first's selector).436  if (pendingInteractions.has(field)) return;437  pendingInteractions.add(field);438439  try {440    const fieldType = field.type.toLowerCase();441442    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {443      return preds[0] ?? null;444    });445446    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {447      const timeout = setTimeout(() => resolve(null), 150);448      mlPromise.then((pred) => {449        clearTimeout(timeout);450        resolve(pred);451      });452    });453454    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {455      return;456    }457458    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);459    if (autofillFieldType) {460      reattachListeners(field, autofillFieldType);461    }462463    let fields = detectLoginFields();464    const loginForm = isLoginForm(fields);465    const signupForm = isSignupForm(fields);466    if (!loginForm && !signupForm) {467      return;468    }469470    const domain = getPageDomain();471    const firstResult = await fetchAutofillEntries(domain);472473    // Vault is locked — show an inline unlock prompt.474    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so475    // there is no double-trigger race between onUnlocked and the broadcast.476    if (firstResult.locked) {477      currentDismiss?.();478      currentAnchorField = field;479      currentDismiss = showAutofillSelector(480        field,481        [],482        () => {},483        { domain, locked: true, onDismiss: () => { lastDismissedField = field; } }484      );485      return;486    }487488    const entries = firstResult.entries;489    const allEntries = entries.length === 0490      ? (await fetchAutofillEntries(domain, true)).entries491      : entries;492493    let usernameEl: HTMLInputElement | null = null;494    const userField = fields.find((f) => f.type === "username" || f.type === "email");495    if (userField) usernameEl = userField.el;496    const pwField = fields.find((f) => f.type === "password");497    if (!pwField) return;498    const passwordEl = pwField.el;499500    if (signupForm && usernameEl && field === usernameEl) {501      await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);502      return;503    }504505    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);506  } finally {507    pendingInteractions.delete(field);508  }509}510511async function onFocusIn(): Promise<void> {512  await handleFieldInteraction();513}514515function reattachListeners(516  el: HTMLInputElement,517  detectedType?: "password" | "username" | "email",518  contextFields?: ReturnType<typeof detectLoginFields>519): void {520  if (processedInputs.has(el)) return;521  if (!resolveAutofillFieldType(el, detectedType)) return;522  // Only inject icon when a real login/signup form is present on the page523  const fields = contextFields ?? detectLoginFields();524  if (!isLoginForm(fields) && !isSignupForm(fields)) return;525526  const cleanup = injectFieldIcon(el, () => {527    currentDismiss?.();528    currentDismiss = null;529    lastDismissedField = null; // icon click is always an explicit user open — clear the dismiss lock530    recentlyAutofilledFields.delete(el); // explicit summon also clears autofill suppression531    el.focus({ preventScroll: true });532    void handleFieldInteraction(el);533  });534  processedInputs.set(el, cleanup);535}536537const debouncedReattach = debounce(() => {538  const allFields = detectLoginFields();539  // Don't inject anything if there's no real login/signup form on this page540  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;541  const newFields = allFields.filter(542    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)543  );544  for (const f of newFields) {545    reattachListeners(f.el, f.type, allFields);546  }547  // 200ms debounce — below this, Peach and the host page's reactive layer548  // fight over the same layout properties every frame on React/Vue/Angular549  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.550}, 200);551552function setupMutationObserver(): void {553  const observer = new MutationObserver(debouncedReattach);554  observer.observe(document.body, {555    childList: true,556    subtree: true,557    attributes: true,558    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],559  });560}561562function initialScan(aggressionLevel = 0, isFinalPass = false) {563  const allFields = detectLoginFields();564  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);565566  if (aggressionLevel === 0 && !hasKnownForm) return;567568  const newFields = allFields.filter(569    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)570  );571572  for (const f of newFields) {573    reattachListeners(f.el, f.type, allFields);574  }575576  // Level 2, final pass: inject icon on any visible password field even if577  // the form-context gate in reattachListeners would normally skip it.578  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {579    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');580    for (const el of pwInputs) {581      if (isVisible(el) && !processedInputs.has(el)) {582        const cleanup = injectFieldIcon(el, () => {583          currentDismiss?.();584          currentDismiss = null;585          lastDismissedField = null;586          recentlyAutofilledFields.delete(el);587          el.focus({ preventScroll: true });588          void handleFieldInteraction(el);589        });590        processedInputs.set(el, cleanup);591      }592    }593  }594}595596document.addEventListener("focusin", onFocusIn);597598setupMutationObserver();599setupSaveDetection();600601// Async init: check recall map before running the initial scans so we can602// apply the right aggression level for domains the user has needed before.603(async () => {604  let aggressionLevel = 0;605  try {606    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });607    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;608    const domain = getPageDomain();609    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;610    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;611  } catch { /* SW may be starting up; proceed with normal scan */ }612613  setTimeout(() => initialScan(aggressionLevel, false), 0);614  setTimeout(() => initialScan(aggressionLevel, false), 500);615  setTimeout(() => initialScan(aggressionLevel, true), 1500);616})();617618chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {619  // Ignore anything not originating from our own background/service worker.620  if (sender.id !== chrome.runtime.id) return;621  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {622    const policy = detectPasswordPolicy();623    sendResponse({ ok: true, data: policy });624    return true;625  }626  if (msg?.type === "PING") {627    sendResponse({ ok: true });628    return true;629  }630  if (msg?.type === "SUMMON_AUTOFILL") {631    const source = (msg as { type: string; source?: string }).source;632    const isShortcut = source === "shortcut";633634    const activeInput = getDeepActiveInput();635    const fields = detectLoginFields();636    const hasForm = isLoginForm(fields) || isSignupForm(fields);637638    if (hasForm) {639      // Prefer the currently focused field if it's a login field, otherwise640      // fall back to the first password field, then username/email.641      const inForm = activeInput && fields.some(f => f.el === activeInput);642      const target = inForm643        ? activeInput644        : (fields.find(f => f.type === "password")?.el645            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);646      if (target) {647        recentlyAutofilledFields.delete(target); // explicit summon clears suppression648        void handleFieldInteraction(target);649      }650    } else if (isShortcut) {651      // Shortcut on a page with no login form — show clipboard-copy search mode.652      showSearchPalette();653    }654655    // Record this domain for the recall system when triggered via shortcut.656    if (isShortcut) {657      const domain = getPageDomain();658      if (domain) {659        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});660      }661    }662663    sendResponse({ ok: hasForm || isShortcut });664    return true;665  }666  if (msg?.type === "VAULT_UNLOCKED") {667    // Close any open selector (e.g. the locked-state prompt) and re-open668    // with fresh entry data. Use the saved anchor field so we reopen exactly669    // where the user was — covers both inline unlock and popup unlock.670    const savedField = currentAnchorField;671    if (currentDismiss) {672      currentDismiss();673      currentDismiss = null;674      currentAnchorField = null;675    }676    void handleFieldInteraction(savedField ?? undefined);677    sendResponse({ ok: true });678    return true;679  }680  return true;681});