detect.ts

8.4 KB · raw

1import { extractDomain } from "../shared/domain";23export interface DetectedField {4  type: "username" | "password" | "email";5  el: HTMLInputElement;6}78// Conservative: "name" alone is too broad (matches "tag-name", "first-name", etc.).9// No \b anchors — modern sites use camelCase like "userId", "loginEmail" where10// the trigger token is contiguous with other word chars and would not match11// at a word boundary.12const USERNAME_PATTERNS = /(user(name|id|login|email)?|e?mail(box)?|login(email|username)?|account|identifier|signin|sign.?in|credential)/i;1314// Input types that are never text-entry fields and must never get autofill15// icons. submit/button/reset/image are interactive controls — putting the16// icon over them blocks the click. The rest are structurally incapable of17// holding a username/password.18const SKIP_INPUT_TYPES = new Set([19  "submit", "button", "reset", "image",20  "checkbox", "radio", "hidden", "file",21  "range", "color", "date", "time",22  "datetime-local", "month", "week",23]);2425// Some sites render submit buttons as <input> with no type attribute (defaults to "text")26// and a value like "Login" or "Submit". Catch those before injecting icons.27function looksLikeSubmitButton(input: HTMLInputElement): boolean {28  if (input.type === "password") return false;29  const val = (input.value || input.getAttribute("value") || "").toLowerCase().trim();30  if (!val) return false;31  return ["submit", "login", "sign in", "log in", "continue", "next", "go"].some(w => val === w || val.startsWith(w + " "));32}3334function findLabelText(field: HTMLInputElement): string {35  const ariaLabel = field.getAttribute("aria-label") ?? "";36  if (ariaLabel) return ariaLabel.toLowerCase();37  const id = field.id;38  if (id) {39    const label = document.querySelector<HTMLLabelElement>(`label[for="${id}"]`);40    if (label) return label.textContent?.toLowerCase() ?? "";41  }42  const wrappingLabel = field.closest("label");43  return wrappingLabel?.textContent?.toLowerCase() ?? "";44}4546export function querySelectorAllDeep<T extends Element>(47  root: Document | ShadowRoot | Element,48  selector: string49): T[] {50  const results: T[] = [];51  const walk = (node: Document | ShadowRoot | Element) => {52    if (node instanceof Element) {53      results.push(...(node.querySelectorAll<T>(selector)));54      const shadowRoot = node.shadowRoot;55      if (shadowRoot) {56        shadowRoot.querySelectorAll<T>("*").forEach(walk);57      }58    }59  };60  root.querySelectorAll<T>("*").forEach(walk);61  return results;62}6364export function getDeepActiveInput(): HTMLInputElement | null {65  let current: Document | Element | null = document.activeElement;66  while (current) {67    if (current instanceof HTMLInputElement) return current;68    if (current instanceof Element && current.shadowRoot) {69      current = current.shadowRoot.activeElement;70    } else {71      break;72    }73  }74  return null;75}7677export function isLoginForm(fields: DetectedField[]): boolean {78  const passwords = fields.filter((f) => f.type === "password");79  // Two or more password fields means signup/change-password, not login80  if (passwords.length >= 2) return false;81  const hasPassword = passwords.length > 0;82  const hasUsernameOrEmail = fields.some((f) => f.type === "username" || f.type === "email");83  if (hasPassword && hasUsernameOrEmail) return true;84  if (passwords.length === 1 && passwords[0].el.autocomplete === "current-password") {85    return true;86  }87  return false;88}8990export function isSignupForm(fields: DetectedField[]): boolean {91  const passwords = fields.filter((f) => f.type === "password");92  if (passwords.length >= 2) return true;93  if (passwords.some((f) => f.el.autocomplete === "new-password")) return true;94  if (95    passwords.some((f) => {96      const id = (f.el.id + f.el.name).toLowerCase();97      return /new|confirm/i.test(id);98    })99  ) {100    return true;101  }102  return false;103}104105export function detectLoginFields(root: Document | ShadowRoot = document): DetectedField[] {106  const inputs = Array.from(querySelectorAllDeep<HTMLInputElement>(root, "input"));107  const fields: DetectedField[] = [];108109  for (const el of inputs) {110    if (!isVisible(el)) continue;111    const type = el.type.toLowerCase();112    // Never treat buttons, checkboxes, hidden fields, etc. as autofill targets113    if (SKIP_INPUT_TYPES.has(type)) continue;114    // Catch <input> with no type attribute whose value text identifies it as a submit button115    if (looksLikeSubmitButton(el)) continue;116    const ac = el.autocomplete;117    const name = (el.name + el.id + el.placeholder).toLowerCase();118119    if (ac === "current-password" || ac === "new-password" || type === "password") {120      fields.push({ type: "password", el });121      continue;122    }123124    if (ac === "username" || ac === "email" || type === "email") {125      fields.push({ type: "username", el });126      continue;127    }128129    if (USERNAME_PATTERNS.test(name)) {130      fields.push({ type: "username", el });131      continue;132    }133134    const labelText = findLabelText(el);135    if (!fields.some((f) => f.el === el) && USERNAME_PATTERNS.test(labelText)) {136      fields.push({ type: "username", el });137    }138  }139140  // Fallback: if we have a password field but no username/email, look for141  // the first visible text input that appears before the password in DOM order.142  // This catches sites with unconventional field names (e.g. name="identifier").143  const hasUsername = fields.some((f) => f.type === "username" || f.type === "email");144  const pwField = fields.find((f) => f.type === "password");145  if (!hasUsername && pwField) {146    const allInputs = Array.from(inputs);147    const pwIndex = allInputs.indexOf(pwField.el);148    for (let i = 0; i < pwIndex; i++) {149      const candidate = allInputs[i];150      const candidateType = candidate.type.toLowerCase();151      if (152        (candidateType === "text" || candidateType === "email" || candidateType === "") &&153        isVisible(candidate) &&154        !SKIP_INPUT_TYPES.has(candidateType) &&155        !fields.some((f) => f.el === candidate)156      ) {157        fields.push({ type: "username", el: candidate });158        break; // only take the first one159      }160    }161  }162163  return fields;164}165166export function isVisible(el: HTMLElement): boolean {167  const s = getComputedStyle(el);168  const r = el.getBoundingClientRect();169  return (170    s.display !== "none" &&171    s.visibility !== "hidden" &&172    parseFloat(s.opacity) > 0 &&173    r.width > 0 &&174    r.height > 0175  );176}177178export function getPageDomain(): string {179  return extractDomain(location.hostname) ?? location.hostname;180}181182export interface CardFormFields {183  number: HTMLInputElement | null;184  expMonth: HTMLInputElement | null;185  expYear: HTMLInputElement | null;186  expiryCombo: HTMLInputElement | null;187  cvc: HTMLInputElement | null;188  name: HTMLInputElement | null;189}190191export function detectCardForm(root: Document | ShadowRoot = document): CardFormFields | null {192  const numberByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-number"]');193  const expByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp"]');194  const expMonthByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp-month"]');195  const expYearByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp-year"]');196  const cvcByAC = root.querySelector<HTMLInputElement>(197    'input[autocomplete="cc-csc"], input[autocomplete="cc-cvc"]'198  );199  const nameByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-name"]');200201  if (numberByAC) {202    return { number: numberByAC, expMonth: expMonthByAC, expYear: expYearByAC, expiryCombo: expByAC, cvc: cvcByAC, name: nameByAC };203  }204205  const allInputs = Array.from(root.querySelectorAll<HTMLInputElement>('input'));206  const numberField = allInputs.find(i =>207    /card.?num|cc.?num|cardnum|pan\b/i.test(i.name + i.id + i.placeholder)208  ) ?? null;209  const cvcField = allInputs.find(i =>210    /cvc|cvv|csc|security.?code/i.test(i.name + i.id + i.placeholder)211  ) ?? null;212  const expField = allInputs.find(i =>213    /exp|expiry|expiration/i.test(i.name + i.id + i.placeholder)214  ) ?? null;215216  if (!numberField) return null;217  return { number: numberField, expMonth: null, expYear: null, expiryCombo: expField, cvc: cvcField, name: null };218}219220const PAYMENT_PROCESSOR_IFRAMES = ['stripe.com', 'js.stripe.com', 'braintreegateway.com', 'paypal.com', 'adyen.com'];221222export function hasPaymentProcessorIframe(): boolean {223  const iframes = Array.from(document.querySelectorAll('iframe'));224  return iframes.some(f => PAYMENT_PROCESSOR_IFRAMES.some(host => f.src.includes(host)));225}