index.ts

22.4 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  showDomainConfirmToast,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;3940function debounce<T extends (...args: unknown[]) => void>(41  fn: T,42  ms: number43): (...args: Parameters<T>) => void {44  let timer: ReturnType<typeof setTimeout>;45  return (...args: Parameters<T>) => {46    clearTimeout(timer);47    timer = setTimeout(() => fn(...args), ms);48  };49}5051function showToast(message: string): void {52  const toast = document.createElement("div");53  toast.style.cssText = `54    position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);55    background: #131109; color: #F0E8D8; padding: 8px 16px;56    border-radius: 8px; font-family: 'IBM Plex Mono', monospace;57    font-size: 11px; z-index: 2147483647; opacity: 0;58    transition: opacity 200ms ease;59    border: 1px solid rgba(240,232,216,0.07);60    pointer-events: none;61  `;62  toast.textContent = message;63  document.body.appendChild(toast);64  requestAnimationFrame(() => { toast.style.opacity = "1"; });65  setTimeout(() => {66    toast.style.opacity = "0";67    setTimeout(() => toast.remove(), 200);68  }, 2000);69}7071function showSearchPalette(): void {72  const host = document.createElement("div");73  host.style.cssText = "position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:2147483647;width:340px;";74  document.body.appendChild(host);75  const shadow = host.attachShadow({ mode: "closed" });7677  const style = document.createElement("style");78  style.textContent = `79    .p{background:#131109;border:1px solid rgba(240,232,216,.12);border-radius:12px;80      font-family:'IBM Plex Mono',monospace;font-size:12px;color:#F0E8D8;81      box-shadow:0 8px 24px rgba(0,0,0,.5);overflow:hidden}82    .h{padding:10px 12px 8px;border-bottom:1px solid rgba(240,232,216,.08);83      font-size:11px;color:rgba(240,232,216,.5);display:flex;justify-content:space-between;align-items:center}84    .x{background:none;border:none;color:rgba(240,232,216,.4);cursor:pointer;font-size:14px;padding:0;line-height:1}85    .s{padding:8px 12px}86    .s input{width:100%;box-sizing:border-box;background:rgba(240,232,216,.06);87      border:1px solid rgba(240,232,216,.12);border-radius:6px;color:#F0E8D8;88      padding:6px 8px;font-family:inherit;font-size:12px;outline:none}89    .l{max-height:220px;overflow-y:auto}90    .e{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column;gap:2px}91    .e:hover{background:rgba(240,232,216,.06)}92    .et{font-size:12px}93    .eu{font-size:10px;color:rgba(240,232,216,.45)}94    .em{padding:12px;color:rgba(240,232,216,.4);text-align:center}95  `;9697  let allEntries: SelectorEntry[] = [];98  let query = "";99100  const panel = document.createElement("div");101  panel.className = "p";102103  const hdr = document.createElement("div");104  hdr.className = "h";105  const hdrText = document.createElement("span");106  hdrText.textContent = "No form detected — search your vault";107  const closeBtn = document.createElement("button");108  closeBtn.className = "x";109  closeBtn.textContent = "✕";110  hdr.appendChild(hdrText);111  hdr.appendChild(closeBtn);112113  const searchWrap = document.createElement("div");114  searchWrap.className = "s";115  const searchInput = document.createElement("input");116  searchInput.placeholder = "search...";117  searchWrap.appendChild(searchInput);118119  const list = document.createElement("div");120  list.className = "l";121122  panel.appendChild(hdr);123  panel.appendChild(searchWrap);124  panel.appendChild(list);125  shadow.appendChild(style);126  shadow.appendChild(panel);127128  function close() { host.remove(); }129130  closeBtn.onclick = close;131132  function onKeyDown(e: KeyboardEvent) {133    if (e.key === "Escape") { close(); document.removeEventListener("keydown", onKeyDown, true); }134  }135  document.addEventListener("keydown", onKeyDown, true);136137  function render() {138    const q = query.toLowerCase();139    const filtered = q140      ? allEntries.filter(e => e.title.toLowerCase().includes(q) || (e.username ?? "").toLowerCase().includes(q))141      : allEntries;142    list.innerHTML = "";143    if (filtered.length === 0) {144      const em = document.createElement("div");145      em.className = "em";146      em.textContent = query ? "no matches" : "vault is empty";147      list.appendChild(em);148      return;149    }150    for (const entry of filtered.slice(0, 20)) {151      const row = document.createElement("div");152      row.className = "e";153      const title = document.createElement("div");154      title.className = "et";155      title.textContent = entry.title;156      row.appendChild(title);157      if (entry.username) {158        const user = document.createElement("div");159        user.className = "eu";160        user.textContent = entry.username;161        row.appendChild(user);162      }163      row.onclick = async () => {164        const resp = await chrome.runtime.sendMessage({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } });165        const r = resp as { ok: boolean; data?: { password?: string } };166        if (r.ok && r.data?.password) {167          let alreadyWritten = false;168          try { await navigator.clipboard.writeText(r.data.password); alreadyWritten = true; } catch {}169          await chrome.runtime.sendMessage({170            type: "COPY",171            payload: { text: r.data.password, label: "Password", alreadyWritten },172          });173          showToast("Password copied");174        } else {175          showToast("Could not copy password");176        }177        close();178        document.removeEventListener("keydown", onKeyDown, true);179      };180      list.appendChild(row);181    }182  }183184  searchInput.oninput = () => { query = searchInput.value; render(); };185186  fetchAutofillEntries(getPageDomain(), true).then(result => {187    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }188    allEntries = result.entries;189    render();190    searchInput.focus();191  });192}193194function setNativeValue(el: HTMLInputElement, value: string): void {195  const nativeSetter = Object.getOwnPropertyDescriptor(196    HTMLInputElement.prototype, "value"197  )!.set!;198  nativeSetter.call(el, value);199  el.dispatchEvent(new Event("input", { bubbles: true }));200  el.dispatchEvent(new Event("change", { bubbles: true }));201}202203function findTOTPField(): HTMLInputElement | null {204  const inputs = document.querySelectorAll<HTMLInputElement>("input");205  for (const input of inputs) {206    if (!isVisible(input)) continue;207    const autocomplete = input.autocomplete.toLowerCase();208    const nameId = (input.name + input.id).toLowerCase();209    const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();210    if (211      autocomplete === "one-time-code" ||212      /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)213    ) {214      return input;215    }216    const labelEl = input.closest("label");217    if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {218      return input;219    }220  }221  return null;222}223224async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {225  await new Promise((r) => setTimeout(r, 400));226  if (totpField.value === "" || totpField.value.trim() === "") {227    const { code } = generateTOTP(totpSecret);228    setNativeValue(totpField, code);229    showToast("TOTP autofilled");230  }231}232233234async function handleAutofill(235  field: HTMLInputElement,236  usernameEl: HTMLInputElement | null,237  passwordEl: HTMLInputElement,238  entry: VaultEntry239): Promise<void> {240  if (!entry.username && !entry.password) return;241  const pageDomain = getPageDomain();242  const form = passwordEl.closest("form") as HTMLFormElement | null;243  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);244245  if (entry.canary) {246    chrome.runtime.sendMessage({247      type: "FIRE_CANARY_PING",248      payload: {249        webhookUrl: entry.canary.webhookUrl,250        entryTitle: entry.title,251        trigger: "autofilled",252      },253    }).catch(() => {});254    chrome.runtime.sendMessage({255      type: "UPDATE_ENTRY",256      payload: {257        id: entry.id,258        patch: {259          canary: {260            ...entry.canary,261            lastPinged: Date.now(),262            pingCount: (entry.canary.pingCount ?? 0) + 1,263          },264        },265      },266    }).catch(() => {});267  }268269  if (entry.totp) {270    const { code } = generateTOTP(entry.totp);271    let alreadyWritten = false;272    try { await navigator.clipboard.writeText(code); alreadyWritten = true; } catch {}273    const response = await chrome.runtime.sendMessage({274      type: "COPY",275      payload: { text: code, label: "TOTP", alreadyWritten },276    });277    if (alreadyWritten || (response as { ok?: boolean }).ok) {278      showToast("TOTP copied · " + code);279    }280    const totpField = findTOTPField();281    if (totpField) {282      autofillTOTP(totpField, entry.totp);283    }284  }285}286287async function fetchAutofillEntries(288  domain: string,289  includeAll = false290): Promise<{ entries: SelectorEntry[]; locked: boolean }> {291  const response = await chrome.runtime.sendMessage({292    type: "AUTOFILL_QUERY",293    payload: { domain, includeAll },294  });295  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };296  if (!res.ok && res.error === "VAULT_LOCKED") {297    return { entries: [], locked: true };298  }299  return { entries: res.data ?? [], locked: false };300}301302303function resolveAutofillFieldType(304  el: HTMLInputElement,305  predictedType?: FieldPrediction["type"] | null306): "password" | "username" | "email" | null {307  if (308    predictedType === "password" ||309    predictedType === "username" ||310    predictedType === "email"311  ) {312    return predictedType;313  }314315  const detected = detectLoginFields().find((field) => field.el === el)?.type;316  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {317    return detected;318  }319320  const htmlType = el.type.toLowerCase();321  if (htmlType === "password") return "password";322  if (htmlType === "email") return "email";323  return null;324}325326async function openAutofillSelector(327  anchorField: HTMLInputElement,328  usernameEl: HTMLInputElement | null,329  passwordEl: HTMLInputElement,330  domainEntries: SelectorEntry[],331  searchableEntries: SelectorEntry[],332  domain: string333): Promise<void> {334  currentDismiss?.();335  currentAnchorField = anchorField;336  currentDismiss = showAutofillSelector(337    anchorField,338    domainEntries,339    async (id: string) => {340      currentDismiss = null;341      currentAnchorField = null;342      const entryResponse = await chrome.runtime.sendMessage({343        type: "GET_ENTRY_FOR_FILL",344        payload: { id },345      });346      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;347      if (entry) {348        await handleAutofill(anchorField, usernameEl, passwordEl, entry);349        // Offer to set page domain as default for this entry when it differs.350        const pageDomain = location.hostname.replace(/^www\./, "");351        const entryDomain = (() => {352          try { return new URL(entry.url ?? "").hostname.replace(/^www\./, ""); } catch { return ""; }353        })();354        if (entryDomain && pageDomain && entryDomain !== pageDomain) {355          showDomainConfirmToast(pageDomain, entry.id);356        }357      }358    },359    {360      domain,361      searchableEntries,362      onDismiss: () => { lastDismissedField = anchorField; },363    }364  );365}366367async function openSignupSelector(368  usernameEl: HTMLInputElement,369  passwordEl: HTMLInputElement | null,370  domainEntries: SelectorEntry[],371  allEntries: SelectorEntry[],372  domain: string373): Promise<void> {374  currentDismiss?.();375  currentAnchorField = usernameEl;376  currentDismiss = showAutofillSelector(377    usernameEl,378    domainEntries,379    () => {}, // identity-click handled via onFillFields380    {381      domain,382      searchableEntries: allEntries,383      isSignup: true,384      onFillFields: (username, password) => {385        if (username) setNativeValue(usernameEl, username);386        if (password && passwordEl) setNativeValue(passwordEl, password);387      },388      onDismiss: () => { lastDismissedField = usernameEl; },389    }390  );391}392393394async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {395  const field = anchorField ?? getDeepActiveInput();396  if (!field) return;397  if (!isVisible(field)) return;398399  // If a selector is already open for this exact field, don't flicker it.400  if (currentDismiss && currentAnchorField === field) return;401402  // If focus moved to a different field, the previous dismiss lock no longer applies.403  if (field !== lastDismissedField) lastDismissedField = null;404  // The user explicitly dismissed this field's selector — don't reopen it until405  // focus has genuinely moved away and come back.406  if (field === lastDismissedField) return;407408  // Prevent two concurrent calls for the same field (e.g. focusin + icon click409  // firing simultaneously — the second call would dismiss the first's selector).410  if (pendingInteractions.has(field)) return;411  pendingInteractions.add(field);412413  try {414    const fieldType = field.type.toLowerCase();415416    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {417      return preds[0] ?? null;418    });419420    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {421      const timeout = setTimeout(() => resolve(null), 150);422      mlPromise.then((pred) => {423        clearTimeout(timeout);424        resolve(pred);425      });426    });427428    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {429      return;430    }431432    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);433    if (autofillFieldType) {434      reattachListeners(field, autofillFieldType);435    }436437    let fields = detectLoginFields();438    const loginForm = isLoginForm(fields);439    const signupForm = isSignupForm(fields);440    if (!loginForm && !signupForm) {441      return;442    }443444    const domain = getPageDomain();445    const firstResult = await fetchAutofillEntries(domain);446447    // Vault is locked — show an inline unlock prompt.448    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so449    // there is no double-trigger race between onUnlocked and the broadcast.450    if (firstResult.locked) {451      currentDismiss?.();452      currentAnchorField = field;453      currentDismiss = showAutofillSelector(454        field,455        [],456        () => {},457        { domain, locked: true, onDismiss: () => { lastDismissedField = field; } }458      );459      return;460    }461462    const entries = firstResult.entries;463    const allEntries = entries.length === 0464      ? (await fetchAutofillEntries(domain, true)).entries465      : entries;466467    let usernameEl: HTMLInputElement | null = null;468    const userField = fields.find((f) => f.type === "username" || f.type === "email");469    if (userField) usernameEl = userField.el;470    const pwField = fields.find((f) => f.type === "password");471    if (!pwField) return;472    const passwordEl = pwField.el;473474    if (signupForm && usernameEl && field === usernameEl) {475      await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);476      return;477    }478479    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);480  } finally {481    pendingInteractions.delete(field);482  }483}484485async function onFocusIn(): Promise<void> {486  await handleFieldInteraction();487}488489function reattachListeners(490  el: HTMLInputElement,491  detectedType?: "password" | "username" | "email",492  contextFields?: ReturnType<typeof detectLoginFields>493): void {494  if (processedInputs.has(el)) return;495  if (!resolveAutofillFieldType(el, detectedType)) return;496  // Only inject icon when a real login/signup form is present on the page497  const fields = contextFields ?? detectLoginFields();498  if (!isLoginForm(fields) && !isSignupForm(fields)) return;499500  const cleanup = injectFieldIcon(el, () => {501    currentDismiss?.();502    currentDismiss = null;503    lastDismissedField = null; // icon click is always an explicit user open — clear the dismiss lock504    el.focus({ preventScroll: true });505    void handleFieldInteraction(el);506  });507  processedInputs.set(el, cleanup);508}509510const debouncedReattach = debounce(() => {511  const allFields = detectLoginFields();512  // Don't inject anything if there's no real login/signup form on this page513  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;514  const newFields = allFields.filter(515    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)516  );517  for (const f of newFields) {518    reattachListeners(f.el, f.type, allFields);519  }520  // 200ms debounce — below this, Peach and the host page's reactive layer521  // fight over the same layout properties every frame on React/Vue/Angular522  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.523}, 200);524525function setupMutationObserver(): void {526  const observer = new MutationObserver(debouncedReattach);527  observer.observe(document.body, {528    childList: true,529    subtree: true,530    attributes: true,531    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],532  });533}534535function initialScan(aggressionLevel = 0, isFinalPass = false) {536  const allFields = detectLoginFields();537  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);538539  if (aggressionLevel === 0 && !hasKnownForm) return;540541  const newFields = allFields.filter(542    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)543  );544545  for (const f of newFields) {546    reattachListeners(f.el, f.type, allFields);547  }548549  // Level 2, final pass: inject icon on any visible password field even if550  // the form-context gate in reattachListeners would normally skip it.551  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {552    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');553    for (const el of pwInputs) {554      if (isVisible(el) && !processedInputs.has(el)) {555        const cleanup = injectFieldIcon(el, () => {556          currentDismiss?.();557          currentDismiss = null;558          lastDismissedField = null;559          el.focus({ preventScroll: true });560          void handleFieldInteraction(el);561        });562        processedInputs.set(el, cleanup);563      }564    }565  }566}567568document.addEventListener("focusin", onFocusIn);569570setupMutationObserver();571setupSaveDetection();572573// Async init: check recall map before running the initial scans so we can574// apply the right aggression level for domains the user has needed before.575(async () => {576  let aggressionLevel = 0;577  try {578    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });579    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;580    const domain = getPageDomain();581    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;582    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;583  } catch { /* SW may be starting up; proceed with normal scan */ }584585  setTimeout(() => initialScan(aggressionLevel, false), 0);586  setTimeout(() => initialScan(aggressionLevel, false), 500);587  setTimeout(() => initialScan(aggressionLevel, true), 1500);588})();589590chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {591  // Ignore anything not originating from our own background/service worker.592  if (sender.id !== chrome.runtime.id) return;593  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {594    const policy = detectPasswordPolicy();595    sendResponse({ ok: true, data: policy });596    return true;597  }598  if (msg?.type === "PING") {599    sendResponse({ ok: true });600    return true;601  }602  if (msg?.type === "SUMMON_AUTOFILL") {603    const source = (msg as { type: string; source?: string }).source;604    const isShortcut = source === "shortcut";605606    const activeInput = getDeepActiveInput();607    const fields = detectLoginFields();608    const hasForm = isLoginForm(fields) || isSignupForm(fields);609610    if (hasForm) {611      // Prefer the currently focused field if it's a login field, otherwise612      // fall back to the first password field, then username/email.613      const inForm = activeInput && fields.some(f => f.el === activeInput);614      const target = inForm615        ? activeInput616        : (fields.find(f => f.type === "password")?.el617            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);618      if (target) void handleFieldInteraction(target);619    } else if (isShortcut) {620      // Shortcut on a page with no login form — show clipboard-copy search mode.621      showSearchPalette();622    }623624    // Record this domain for the recall system when triggered via shortcut.625    if (isShortcut) {626      const domain = getPageDomain();627      if (domain) {628        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});629      }630    }631632    sendResponse({ ok: hasForm || isShortcut });633    return true;634  }635  if (msg?.type === "VAULT_UNLOCKED") {636    // Close any open selector (e.g. the locked-state prompt) and re-open637    // with fresh entry data. Use the saved anchor field so we reopen exactly638    // where the user was — covers both inline unlock and popup unlock.639    const savedField = currentAnchorField;640    if (currentDismiss) {641      currentDismiss();642      currentDismiss = null;643      currentAnchorField = null;644    }645    void handleFieldInteraction(savedField ?? undefined);646    sendResponse({ ok: true });647    return true;648  }649  return true;650});