index.ts

22.6 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;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 remember the current site for this entry only if none of350        // its known domains (primary + additional) match — otherwise the351        // user already mapped it and the prompt would be noise.352        const pageDomain = location.hostname.replace(/^www\./, "");353        const entryDomains = new Set<string>();354        for (const u of [entry.url, ...(entry.additionalUrls ?? [])]) {355          try {356            if (u) entryDomains.add(new URL(u).hostname.replace(/^www\./, ""));357          } catch { /* ignore unparseable */ }358        }359        if (pageDomain && entryDomains.size > 0 && !entryDomains.has(pageDomain)) {360          showRememberSiteToast(pageDomain, entry.id);361        }362      }363    },364    {365      domain,366      searchableEntries,367      onDismiss: () => { lastDismissedField = anchorField; },368    }369  );370}371372async function openSignupSelector(373  usernameEl: HTMLInputElement,374  passwordEl: HTMLInputElement | null,375  domainEntries: SelectorEntry[],376  allEntries: SelectorEntry[],377  domain: string378): Promise<void> {379  currentDismiss?.();380  currentAnchorField = usernameEl;381  currentDismiss = showAutofillSelector(382    usernameEl,383    domainEntries,384    () => {}, // identity-click handled via onFillFields385    {386      domain,387      searchableEntries: allEntries,388      isSignup: true,389      onFillFields: (username, password) => {390        if (username) setNativeValue(usernameEl, username);391        if (password && passwordEl) setNativeValue(passwordEl, password);392      },393      onDismiss: () => { lastDismissedField = usernameEl; },394    }395  );396}397398399async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {400  const field = anchorField ?? getDeepActiveInput();401  if (!field) return;402  if (!isVisible(field)) return;403404  // If a selector is already open for this exact field, don't flicker it.405  if (currentDismiss && currentAnchorField === field) return;406407  // If focus moved to a different field, the previous dismiss lock no longer applies.408  if (field !== lastDismissedField) lastDismissedField = null;409  // The user explicitly dismissed this field's selector — don't reopen it until410  // focus has genuinely moved away and come back.411  if (field === lastDismissedField) return;412413  // Prevent two concurrent calls for the same field (e.g. focusin + icon click414  // firing simultaneously — the second call would dismiss the first's selector).415  if (pendingInteractions.has(field)) return;416  pendingInteractions.add(field);417418  try {419    const fieldType = field.type.toLowerCase();420421    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {422      return preds[0] ?? null;423    });424425    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {426      const timeout = setTimeout(() => resolve(null), 150);427      mlPromise.then((pred) => {428        clearTimeout(timeout);429        resolve(pred);430      });431    });432433    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {434      return;435    }436437    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);438    if (autofillFieldType) {439      reattachListeners(field, autofillFieldType);440    }441442    let fields = detectLoginFields();443    const loginForm = isLoginForm(fields);444    const signupForm = isSignupForm(fields);445    if (!loginForm && !signupForm) {446      return;447    }448449    const domain = getPageDomain();450    const firstResult = await fetchAutofillEntries(domain);451452    // Vault is locked — show an inline unlock prompt.453    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so454    // there is no double-trigger race between onUnlocked and the broadcast.455    if (firstResult.locked) {456      currentDismiss?.();457      currentAnchorField = field;458      currentDismiss = showAutofillSelector(459        field,460        [],461        () => {},462        { domain, locked: true, onDismiss: () => { lastDismissedField = field; } }463      );464      return;465    }466467    const entries = firstResult.entries;468    const allEntries = entries.length === 0469      ? (await fetchAutofillEntries(domain, true)).entries470      : entries;471472    let usernameEl: HTMLInputElement | null = null;473    const userField = fields.find((f) => f.type === "username" || f.type === "email");474    if (userField) usernameEl = userField.el;475    const pwField = fields.find((f) => f.type === "password");476    if (!pwField) return;477    const passwordEl = pwField.el;478479    if (signupForm && usernameEl && field === usernameEl) {480      await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);481      return;482    }483484    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);485  } finally {486    pendingInteractions.delete(field);487  }488}489490async function onFocusIn(): Promise<void> {491  await handleFieldInteraction();492}493494function reattachListeners(495  el: HTMLInputElement,496  detectedType?: "password" | "username" | "email",497  contextFields?: ReturnType<typeof detectLoginFields>498): void {499  if (processedInputs.has(el)) return;500  if (!resolveAutofillFieldType(el, detectedType)) return;501  // Only inject icon when a real login/signup form is present on the page502  const fields = contextFields ?? detectLoginFields();503  if (!isLoginForm(fields) && !isSignupForm(fields)) return;504505  const cleanup = injectFieldIcon(el, () => {506    currentDismiss?.();507    currentDismiss = null;508    lastDismissedField = null; // icon click is always an explicit user open — clear the dismiss lock509    el.focus({ preventScroll: true });510    void handleFieldInteraction(el);511  });512  processedInputs.set(el, cleanup);513}514515const debouncedReattach = debounce(() => {516  const allFields = detectLoginFields();517  // Don't inject anything if there's no real login/signup form on this page518  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;519  const newFields = allFields.filter(520    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)521  );522  for (const f of newFields) {523    reattachListeners(f.el, f.type, allFields);524  }525  // 200ms debounce — below this, Peach and the host page's reactive layer526  // fight over the same layout properties every frame on React/Vue/Angular527  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.528}, 200);529530function setupMutationObserver(): void {531  const observer = new MutationObserver(debouncedReattach);532  observer.observe(document.body, {533    childList: true,534    subtree: true,535    attributes: true,536    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],537  });538}539540function initialScan(aggressionLevel = 0, isFinalPass = false) {541  const allFields = detectLoginFields();542  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);543544  if (aggressionLevel === 0 && !hasKnownForm) return;545546  const newFields = allFields.filter(547    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)548  );549550  for (const f of newFields) {551    reattachListeners(f.el, f.type, allFields);552  }553554  // Level 2, final pass: inject icon on any visible password field even if555  // the form-context gate in reattachListeners would normally skip it.556  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {557    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');558    for (const el of pwInputs) {559      if (isVisible(el) && !processedInputs.has(el)) {560        const cleanup = injectFieldIcon(el, () => {561          currentDismiss?.();562          currentDismiss = null;563          lastDismissedField = null;564          el.focus({ preventScroll: true });565          void handleFieldInteraction(el);566        });567        processedInputs.set(el, cleanup);568      }569    }570  }571}572573document.addEventListener("focusin", onFocusIn);574575setupMutationObserver();576setupSaveDetection();577578// Async init: check recall map before running the initial scans so we can579// apply the right aggression level for domains the user has needed before.580(async () => {581  let aggressionLevel = 0;582  try {583    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });584    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;585    const domain = getPageDomain();586    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;587    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;588  } catch { /* SW may be starting up; proceed with normal scan */ }589590  setTimeout(() => initialScan(aggressionLevel, false), 0);591  setTimeout(() => initialScan(aggressionLevel, false), 500);592  setTimeout(() => initialScan(aggressionLevel, true), 1500);593})();594595chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {596  // Ignore anything not originating from our own background/service worker.597  if (sender.id !== chrome.runtime.id) return;598  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {599    const policy = detectPasswordPolicy();600    sendResponse({ ok: true, data: policy });601    return true;602  }603  if (msg?.type === "PING") {604    sendResponse({ ok: true });605    return true;606  }607  if (msg?.type === "SUMMON_AUTOFILL") {608    const source = (msg as { type: string; source?: string }).source;609    const isShortcut = source === "shortcut";610611    const activeInput = getDeepActiveInput();612    const fields = detectLoginFields();613    const hasForm = isLoginForm(fields) || isSignupForm(fields);614615    if (hasForm) {616      // Prefer the currently focused field if it's a login field, otherwise617      // fall back to the first password field, then username/email.618      const inForm = activeInput && fields.some(f => f.el === activeInput);619      const target = inForm620        ? activeInput621        : (fields.find(f => f.type === "password")?.el622            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);623      if (target) void handleFieldInteraction(target);624    } else if (isShortcut) {625      // Shortcut on a page with no login form — show clipboard-copy search mode.626      showSearchPalette();627    }628629    // Record this domain for the recall system when triggered via shortcut.630    if (isShortcut) {631      const domain = getPageDomain();632      if (domain) {633        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});634      }635    }636637    sendResponse({ ok: hasForm || isShortcut });638    return true;639  }640  if (msg?.type === "VAULT_UNLOCKED") {641    // Close any open selector (e.g. the locked-state prompt) and re-open642    // with fresh entry data. Use the saved anchor field so we reopen exactly643    // where the user was — covers both inline unlock and popup unlock.644    const savedField = currentAnchorField;645    if (currentDismiss) {646      currentDismiss();647      currentDismiss = null;648      currentAnchorField = null;649    }650    void handleFieldInteraction(savedField ?? undefined);651    sendResponse({ ok: true });652    return true;653  }654  return true;655});