index.ts

22.0 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          await chrome.runtime.sendMessage({ type: "COPY", payload: { text: r.data.password, label: "Password" } });168          showToast("Password copied");169        } else {170          showToast("Could not copy password");171        }172        close();173        document.removeEventListener("keydown", onKeyDown, true);174      };175      list.appendChild(row);176    }177  }178179  searchInput.oninput = () => { query = searchInput.value; render(); };180181  fetchAutofillEntries(getPageDomain(), true).then(result => {182    if (result.locked) { showToast("Vault is locked — open Peach to unlock"); close(); return; }183    allEntries = result.entries;184    render();185    searchInput.focus();186  });187}188189function setNativeValue(el: HTMLInputElement, value: string): void {190  const nativeSetter = Object.getOwnPropertyDescriptor(191    HTMLInputElement.prototype, "value"192  )!.set!;193  nativeSetter.call(el, value);194  el.dispatchEvent(new Event("input", { bubbles: true }));195  el.dispatchEvent(new Event("change", { bubbles: true }));196}197198function findTOTPField(): HTMLInputElement | null {199  const inputs = document.querySelectorAll<HTMLInputElement>("input");200  for (const input of inputs) {201    if (!isVisible(input)) continue;202    const autocomplete = input.autocomplete.toLowerCase();203    const nameId = (input.name + input.id).toLowerCase();204    const nameIdPlaceholder = nameId + input.placeholder.toLowerCase();205    if (206      autocomplete === "one-time-code" ||207      /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(nameIdPlaceholder)208    ) {209      return input;210    }211    const labelEl = input.closest("label");212    if (labelEl && /\botp\b|\btotp\b|\b2fa\b|\bmfa\b|\bcode\b/.test(labelEl.textContent?.toLowerCase() ?? "")) {213      return input;214    }215  }216  return null;217}218219async function autofillTOTP(totpField: HTMLInputElement, totpSecret: string): Promise<void> {220  await new Promise((r) => setTimeout(r, 400));221  if (totpField.value === "" || totpField.value.trim() === "") {222    const { code } = generateTOTP(totpSecret);223    setNativeValue(totpField, code);224    showToast("TOTP autofilled");225  }226}227228229async function handleAutofill(230  field: HTMLInputElement,231  usernameEl: HTMLInputElement | null,232  passwordEl: HTMLInputElement,233  entry: VaultEntry234): Promise<void> {235  if (!entry.username && !entry.password) return;236  const pageDomain = getPageDomain();237  const form = passwordEl.closest("form") as HTMLFormElement | null;238  fillFields(usernameEl, passwordEl, entry.username ?? "", entry.password ?? "", form, pageDomain);239240  if (entry.canary) {241    chrome.runtime.sendMessage({242      type: "FIRE_CANARY_PING",243      payload: {244        webhookUrl: entry.canary.webhookUrl,245        entryTitle: entry.title,246        trigger: "autofilled",247      },248    }).catch(() => {});249    chrome.runtime.sendMessage({250      type: "UPDATE_ENTRY",251      payload: {252        id: entry.id,253        patch: {254          canary: {255            ...entry.canary,256            lastPinged: Date.now(),257            pingCount: (entry.canary.pingCount ?? 0) + 1,258          },259        },260      },261    }).catch(() => {});262  }263264  if (entry.totp) {265    const { code } = generateTOTP(entry.totp);266    const response = await chrome.runtime.sendMessage({267      type: "COPY",268      payload: { text: code, label: "TOTP" },269    });270    if ((response as { ok?: boolean }).ok) {271      showToast("TOTP copied · " + code);272    }273    const totpField = findTOTPField();274    if (totpField) {275      autofillTOTP(totpField, entry.totp);276    }277  }278}279280async function fetchAutofillEntries(281  domain: string,282  includeAll = false283): Promise<{ entries: SelectorEntry[]; locked: boolean }> {284  const response = await chrome.runtime.sendMessage({285    type: "AUTOFILL_QUERY",286    payload: { domain, includeAll },287  });288  const res = response as { ok: boolean; data?: SelectorEntry[]; error?: string };289  if (!res.ok && res.error === "VAULT_LOCKED") {290    return { entries: [], locked: true };291  }292  return { entries: res.data ?? [], locked: false };293}294295296function resolveAutofillFieldType(297  el: HTMLInputElement,298  predictedType?: FieldPrediction["type"] | null299): "password" | "username" | "email" | null {300  if (301    predictedType === "password" ||302    predictedType === "username" ||303    predictedType === "email"304  ) {305    return predictedType;306  }307308  const detected = detectLoginFields().find((field) => field.el === el)?.type;309  if (detected && AUTOFILL_FIELD_TYPES.has(detected)) {310    return detected;311  }312313  const htmlType = el.type.toLowerCase();314  if (htmlType === "password") return "password";315  if (htmlType === "email") return "email";316  return null;317}318319async function openAutofillSelector(320  anchorField: HTMLInputElement,321  usernameEl: HTMLInputElement | null,322  passwordEl: HTMLInputElement,323  domainEntries: SelectorEntry[],324  searchableEntries: SelectorEntry[],325  domain: string326): Promise<void> {327  currentDismiss?.();328  currentAnchorField = anchorField;329  currentDismiss = showAutofillSelector(330    anchorField,331    domainEntries,332    async (id: string) => {333      currentDismiss = null;334      currentAnchorField = null;335      const entryResponse = await chrome.runtime.sendMessage({336        type: "GET_ENTRY_FOR_FILL",337        payload: { id },338      });339      const entry = (entryResponse as { ok: boolean; data?: VaultEntry }).data;340      if (entry) {341        await handleAutofill(anchorField, usernameEl, passwordEl, entry);342        // Offer to set page domain as default for this entry when it differs.343        const pageDomain = location.hostname.replace(/^www\./, "");344        const entryDomain = (() => {345          try { return new URL(entry.url ?? "").hostname.replace(/^www\./, ""); } catch { return ""; }346        })();347        if (entryDomain && pageDomain && entryDomain !== pageDomain) {348          showDomainConfirmToast(pageDomain, entry.id);349        }350      }351    },352    {353      domain,354      searchableEntries,355      onDismiss: () => { lastDismissedField = anchorField; },356    }357  );358}359360async function openSignupSelector(361  usernameEl: HTMLInputElement,362  passwordEl: HTMLInputElement | null,363  domainEntries: SelectorEntry[],364  allEntries: SelectorEntry[],365  domain: string366): Promise<void> {367  currentDismiss?.();368  currentAnchorField = usernameEl;369  currentDismiss = showAutofillSelector(370    usernameEl,371    domainEntries,372    () => {}, // identity-click handled via onFillFields373    {374      domain,375      searchableEntries: allEntries,376      isSignup: true,377      onFillFields: (username, password) => {378        if (username) setNativeValue(usernameEl, username);379        if (password && passwordEl) setNativeValue(passwordEl, password);380      },381      onDismiss: () => { lastDismissedField = usernameEl; },382    }383  );384}385386387async function handleFieldInteraction(anchorField?: HTMLInputElement | null): Promise<void> {388  const field = anchorField ?? getDeepActiveInput();389  if (!field) return;390  if (!isVisible(field)) return;391392  // If a selector is already open for this exact field, don't flicker it.393  if (currentDismiss && currentAnchorField === field) return;394395  // If focus moved to a different field, the previous dismiss lock no longer applies.396  if (field !== lastDismissedField) lastDismissedField = null;397  // The user explicitly dismissed this field's selector — don't reopen it until398  // focus has genuinely moved away and come back.399  if (field === lastDismissedField) return;400401  // Prevent two concurrent calls for the same field (e.g. focusin + icon click402  // firing simultaneously — the second call would dismiss the first's selector).403  if (pendingInteractions.has(field)) return;404  pendingInteractions.add(field);405406  try {407    const fieldType = field.type.toLowerCase();408409    const mlPromise = contentMLDetector.predictBatch([field]).then((preds) => {410      return preds[0] ?? null;411    });412413    const mlPrediction = await new Promise<FieldPrediction | null>((resolve) => {414      const timeout = setTimeout(() => resolve(null), 150);415      mlPromise.then((pred) => {416        clearTimeout(timeout);417        resolve(pred);418      });419    });420421    if (fieldType !== "password" && mlPrediction && mlPrediction.type !== "username" && mlPrediction.type !== "email") {422      return;423    }424425    const autofillFieldType = resolveAutofillFieldType(field, mlPrediction?.type);426    if (autofillFieldType) {427      reattachListeners(field, autofillFieldType);428    }429430    let fields = detectLoginFields();431    const loginForm = isLoginForm(fields);432    const signupForm = isSignupForm(fields);433    if (!loginForm && !signupForm) {434      return;435    }436437    const domain = getPageDomain();438    const firstResult = await fetchAutofillEntries(domain);439440    // Vault is locked — show an inline unlock prompt.441    // Re-triggering after unlock is handled by the VAULT_UNLOCKED message so442    // there is no double-trigger race between onUnlocked and the broadcast.443    if (firstResult.locked) {444      currentDismiss?.();445      currentAnchorField = field;446      currentDismiss = showAutofillSelector(447        field,448        [],449        () => {},450        { domain, locked: true, onDismiss: () => { lastDismissedField = field; } }451      );452      return;453    }454455    const entries = firstResult.entries;456    const allEntries = entries.length === 0457      ? (await fetchAutofillEntries(domain, true)).entries458      : entries;459460    let usernameEl: HTMLInputElement | null = null;461    const userField = fields.find((f) => f.type === "username" || f.type === "email");462    if (userField) usernameEl = userField.el;463    const pwField = fields.find((f) => f.type === "password");464    if (!pwField) return;465    const passwordEl = pwField.el;466467    if (signupForm && usernameEl && field === usernameEl) {468      await openSignupSelector(usernameEl, passwordEl, entries, allEntries, domain);469      return;470    }471472    await openAutofillSelector(field, usernameEl, passwordEl, entries, allEntries, domain);473  } finally {474    pendingInteractions.delete(field);475  }476}477478async function onFocusIn(): Promise<void> {479  await handleFieldInteraction();480}481482function reattachListeners(483  el: HTMLInputElement,484  detectedType?: "password" | "username" | "email",485  contextFields?: ReturnType<typeof detectLoginFields>486): void {487  if (processedInputs.has(el)) return;488  if (!resolveAutofillFieldType(el, detectedType)) return;489  // Only inject icon when a real login/signup form is present on the page490  const fields = contextFields ?? detectLoginFields();491  if (!isLoginForm(fields) && !isSignupForm(fields)) return;492493  const cleanup = injectFieldIcon(el, () => {494    currentDismiss?.();495    currentDismiss = null;496    lastDismissedField = null; // icon click is always an explicit user open — clear the dismiss lock497    el.focus({ preventScroll: true });498    void handleFieldInteraction(el);499  });500  processedInputs.set(el, cleanup);501}502503const debouncedReattach = debounce(() => {504  const allFields = detectLoginFields();505  // Don't inject anything if there's no real login/signup form on this page506  if (!isLoginForm(allFields) && !isSignupForm(allFields)) return;507  const newFields = allFields.filter(508    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)509  );510  for (const f of newFields) {511    reattachListeners(f.el, f.type, allFields);512  }513  // 200ms debounce — below this, Peach and the host page's reactive layer514  // fight over the same layout properties every frame on React/Vue/Angular515  // login forms (v1.4.14 regression, Projects.md §4.7). Do not lower.516}, 200);517518function setupMutationObserver(): void {519  const observer = new MutationObserver(debouncedReattach);520  observer.observe(document.body, {521    childList: true,522    subtree: true,523    attributes: true,524    attributeFilter: ["type", "autocomplete", "name", "id", "placeholder", "hidden"],525  });526}527528function initialScan(aggressionLevel = 0, isFinalPass = false) {529  const allFields = detectLoginFields();530  const hasKnownForm = isLoginForm(allFields) || isSignupForm(allFields);531532  if (aggressionLevel === 0 && !hasKnownForm) return;533534  const newFields = allFields.filter(535    (f) => AUTOFILL_FIELD_TYPES.has(f.type) && !processedInputs.has(f.el)536  );537538  for (const f of newFields) {539    reattachListeners(f.el, f.type, allFields);540  }541542  // Level 2, final pass: inject icon on any visible password field even if543  // the form-context gate in reattachListeners would normally skip it.544  if (aggressionLevel >= 2 && isFinalPass && newFields.length === 0) {545    const pwInputs = document.querySelectorAll<HTMLInputElement>('input[type="password"]');546    for (const el of pwInputs) {547      if (isVisible(el) && !processedInputs.has(el)) {548        const cleanup = injectFieldIcon(el, () => {549          currentDismiss?.();550          currentDismiss = null;551          lastDismissedField = null;552          el.focus({ preventScroll: true });553          void handleFieldInteraction(el);554        });555        processedInputs.set(el, cleanup);556      }557    }558  }559}560561document.addEventListener("focusin", onFocusIn);562563setupMutationObserver();564setupSaveDetection();565566// Async init: check recall map before running the initial scans so we can567// apply the right aggression level for domains the user has needed before.568(async () => {569  let aggressionLevel = 0;570  try {571    const resp = await chrome.runtime.sendMessage({ type: "GET_SETTINGS" });572    const s = (resp as { ok: boolean; data?: { manualSummonDomains?: Record<string, { summonCount: number }> } }).data;573    const domain = getPageDomain();574    const record = domain ? s?.manualSummonDomains?.[domain] : undefined;575    aggressionLevel = !record ? 0 : record.summonCount >= 2 ? 2 : 1;576  } catch { /* SW may be starting up; proceed with normal scan */ }577578  setTimeout(() => initialScan(aggressionLevel, false), 0);579  setTimeout(() => initialScan(aggressionLevel, false), 500);580  setTimeout(() => initialScan(aggressionLevel, true), 1500);581})();582583chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {584  // Ignore anything not originating from our own background/service worker.585  if (sender.id !== chrome.runtime.id) return;586  if (msg?.type === "GET_SITE_PASSWORD_POLICY") {587    const policy = detectPasswordPolicy();588    sendResponse({ ok: true, data: policy });589    return true;590  }591  if (msg?.type === "PING") {592    sendResponse({ ok: true });593    return true;594  }595  if (msg?.type === "SUMMON_AUTOFILL") {596    const source = (msg as { type: string; source?: string }).source;597    const isShortcut = source === "shortcut";598599    const activeInput = getDeepActiveInput();600    const fields = detectLoginFields();601    const hasForm = isLoginForm(fields) || isSignupForm(fields);602603    if (hasForm) {604      // Prefer the currently focused field if it's a login field, otherwise605      // fall back to the first password field, then username/email.606      const inForm = activeInput && fields.some(f => f.el === activeInput);607      const target = inForm608        ? activeInput609        : (fields.find(f => f.type === "password")?.el610            ?? fields.find(f => f.type === "username" || f.type === "email")?.el);611      if (target) void handleFieldInteraction(target);612    } else if (isShortcut) {613      // Shortcut on a page with no login form — show clipboard-copy search mode.614      showSearchPalette();615    }616617    // Record this domain for the recall system when triggered via shortcut.618    if (isShortcut) {619      const domain = getPageDomain();620      if (domain) {621        chrome.runtime.sendMessage({ type: "RECORD_MANUAL_SUMMON", payload: { domain } }).catch(() => {});622      }623    }624625    sendResponse({ ok: hasForm || isShortcut });626    return true;627  }628  if (msg?.type === "VAULT_UNLOCKED") {629    // Close any open selector (e.g. the locked-state prompt) and re-open630    // with fresh entry data. Use the saved anchor field so we reopen exactly631    // where the user was — covers both inline unlock and popup unlock.632    const savedField = currentAnchorField;633    if (currentDismiss) {634      currentDismiss();635      currentDismiss = null;636      currentAnchorField = null;637    }638    void handleFieldInteraction(savedField ?? undefined);639    sendResponse({ ok: true });640    return true;641  }642  return true;643});