detect.ts

9.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  if (wrappingLabel?.textContent) return wrappingLabel.textContent.toLowerCase();4445  let node: Element | null = field;46  for (let depth = 0; node && depth < 3; depth++) {47    const previous = node.previousElementSibling;48    const text = previous?.textContent?.trim().toLowerCase() ?? "";49    if (text && text.length <= 80 && !previous?.querySelector("input, select, textarea, button")) {50      return text;51    }52    node = node.parentElement;53  }54  return "";55}5657export function querySelectorAllDeep<T extends Element>(58  root: Document | ShadowRoot | Element,59  selector: string60): T[] {61  const results: T[] = [];62  const walk = (node: Document | ShadowRoot | Element) => {63    if (node instanceof Element) {64      results.push(...(node.querySelectorAll<T>(selector)));65      const shadowRoot = node.shadowRoot;66      if (shadowRoot) {67        shadowRoot.querySelectorAll<T>("*").forEach(walk);68      }69    }70  };71  root.querySelectorAll<T>("*").forEach(walk);72  return results;73}7475export function getDeepActiveInput(): HTMLInputElement | null {76  let current: Document | Element | null = document.activeElement;77  while (current) {78    if (current instanceof HTMLInputElement) return current;79    if (current instanceof Element && current.shadowRoot) {80      current = current.shadowRoot.activeElement;81    } else {82      break;83    }84  }85  return null;86}8788export function isTOTPField(input: HTMLInputElement): boolean {89  if (!isVisible(input)) return false;90  const autocomplete = input.autocomplete.toLowerCase();91  const fieldText = `${input.name} ${input.id} ${input.placeholder}`.toLowerCase();92  if (93    autocomplete === "one-time-code" ||94    /\b(otp|totp|2fa|mfa)\b/.test(fieldText) ||95    /\b(verification|authenticator|security)\s+code\b/.test(fieldText)96  ) {97    return true;98  }99100  const labelText = findLabelText(input);101  return (102    /\b(otp|totp|2fa|mfa)\b/.test(labelText) ||103    /\b(verification|authenticator|security)\s+code\b/.test(labelText)104  );105}106107export function isLoginForm(fields: DetectedField[]): boolean {108  const passwords = fields.filter((f) => f.type === "password");109  // Two or more password fields means signup/change-password, not login110  if (passwords.length >= 2) return false;111  const hasPassword = passwords.length > 0;112  const hasUsernameOrEmail = fields.some((f) => f.type === "username" || f.type === "email");113  if (hasPassword && hasUsernameOrEmail) return true;114  if (passwords.length === 1 && passwords[0].el.autocomplete === "current-password") {115    return true;116  }117  return false;118}119120export function isSignupForm(fields: DetectedField[]): boolean {121  const passwords = fields.filter((f) => f.type === "password");122  if (passwords.length >= 2) return true;123  if (passwords.some((f) => f.el.autocomplete === "new-password")) return true;124  if (125    passwords.some((f) => {126      const id = (f.el.id + f.el.name).toLowerCase();127      return /new|confirm/i.test(id);128    })129  ) {130    return true;131  }132  return false;133}134135export function detectLoginFields(root: Document | ShadowRoot = document): DetectedField[] {136  const inputs = Array.from(querySelectorAllDeep<HTMLInputElement>(root, "input"));137  const fields: DetectedField[] = [];138139  for (const el of inputs) {140    if (!isVisible(el)) continue;141    const type = el.type.toLowerCase();142    // Never treat buttons, checkboxes, hidden fields, etc. as autofill targets143    if (SKIP_INPUT_TYPES.has(type)) continue;144    // Catch <input> with no type attribute whose value text identifies it as a submit button145    if (looksLikeSubmitButton(el)) continue;146    const ac = el.autocomplete;147    const name = (el.name + el.id + el.placeholder).toLowerCase();148149    if (ac === "current-password" || ac === "new-password" || type === "password") {150      fields.push({ type: "password", el });151      continue;152    }153154    if (ac === "username" || ac === "email" || type === "email") {155      fields.push({ type: "username", el });156      continue;157    }158159    if (USERNAME_PATTERNS.test(name)) {160      fields.push({ type: "username", el });161      continue;162    }163164    const labelText = findLabelText(el);165    if (!fields.some((f) => f.el === el) && USERNAME_PATTERNS.test(labelText)) {166      fields.push({ type: "username", el });167    }168  }169170  // Fallback: if we have a password field but no username/email, look for171  // the first visible text input that appears before the password in DOM order.172  // This catches sites with unconventional field names (e.g. name="identifier").173  const hasUsername = fields.some((f) => f.type === "username" || f.type === "email");174  const pwField = fields.find((f) => f.type === "password");175  if (!hasUsername && pwField) {176    const allInputs = Array.from(inputs);177    const pwIndex = allInputs.indexOf(pwField.el);178    for (let i = 0; i < pwIndex; i++) {179      const candidate = allInputs[i];180      const candidateType = candidate.type.toLowerCase();181      if (182        (candidateType === "text" || candidateType === "email" || candidateType === "") &&183        isVisible(candidate) &&184        !SKIP_INPUT_TYPES.has(candidateType) &&185        !fields.some((f) => f.el === candidate)186      ) {187        fields.push({ type: "username", el: candidate });188        break; // only take the first one189      }190    }191  }192193  return fields;194}195196export function isVisible(el: HTMLElement): boolean {197  const s = getComputedStyle(el);198  const r = el.getBoundingClientRect();199  return (200    s.display !== "none" &&201    s.visibility !== "hidden" &&202    parseFloat(s.opacity) > 0 &&203    r.width > 0 &&204    r.height > 0205  );206}207208export function getPageDomain(): string {209  return extractDomain(location.hostname) ?? location.hostname;210}211212export interface CardFormFields {213  number: HTMLInputElement | null;214  expMonth: HTMLInputElement | null;215  expYear: HTMLInputElement | null;216  expiryCombo: HTMLInputElement | null;217  cvc: HTMLInputElement | null;218  name: HTMLInputElement | null;219}220221export function detectCardForm(root: Document | ShadowRoot = document): CardFormFields | null {222  const numberByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-number"]');223  const expByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp"]');224  const expMonthByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp-month"]');225  const expYearByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp-year"]');226  const cvcByAC = root.querySelector<HTMLInputElement>(227    'input[autocomplete="cc-csc"], input[autocomplete="cc-cvc"]'228  );229  const nameByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-name"]');230231  if (numberByAC) {232    return { number: numberByAC, expMonth: expMonthByAC, expYear: expYearByAC, expiryCombo: expByAC, cvc: cvcByAC, name: nameByAC };233  }234235  const allInputs = Array.from(root.querySelectorAll<HTMLInputElement>('input'));236  const numberField = allInputs.find(i =>237    /card.?num|cc.?num|cardnum|pan\b/i.test(i.name + i.id + i.placeholder)238  ) ?? null;239  const cvcField = allInputs.find(i =>240    /cvc|cvv|csc|security.?code/i.test(i.name + i.id + i.placeholder)241  ) ?? null;242  const expField = allInputs.find(i =>243    /exp|expiry|expiration/i.test(i.name + i.id + i.placeholder)244  ) ?? null;245246  if (!numberField) return null;247  return { number: numberField, expMonth: null, expYear: null, expiryCombo: expField, cvc: cvcField, name: null };248}249250const PAYMENT_PROCESSOR_IFRAMES = ['stripe.com', 'js.stripe.com', 'braintreegateway.com', 'paypal.com', 'adyen.com'];251252export function hasPaymentProcessorIframe(): boolean {253  const iframes = Array.from(document.querySelectorAll('iframe'));254  return iframes.some(f => PAYMENT_PROCESSOR_IFRAMES.some(host => f.src.includes(host)));255}