detect.ts

12.3 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}106107// AUTH_SIGNALS_RE: submit buttons / form actions / headings that indicate auth intent.108// ANTI_AUTH_RE: signals that contradict auth (newsletter, registration with name fields, etc.).109const AUTH_SIGNALS_RE = /sign.?(?:in|up)|log.?in|continue|next\b|proceed|let.?me.?in|get started|verify|unlock|access/i;110const ANTI_AUTH_RE = /subscri|newsletter|register|join\b|contact|comment/i;111112// Email-first / identifier-first step: user enters email or username on this page;113// the password prompt comes on the next step. Requires at least one auth-intent114// signal (URL path, form action, or submit button text) to avoid false-positives115// on newsletter and search forms that also have a single email field.116export function isEmailFirstForm(fields: DetectedField[]): boolean {117  if (!fields.some(f => f.type === "username" || f.type === "email")) return false;118  if (fields.some(f => f.type === "password")) return false;119120  // Strong URL signal: /login, /signin, /auth, /sso, /account, etc.121  if (/\/(login|signin|sign-in|logon|auth|sso|connect|account(?:\/|$))\b/i.test(location.pathname)) return true;122123  // Check submit buttons for auth intent.124  const buttons = Array.from(document.querySelectorAll<HTMLElement>(125    'button[type="submit"], input[type="submit"], button:not([type="button"]):not([type="reset"])'126  ));127  const hasAuthButton = buttons.some(b => {128    const t = (b instanceof HTMLInputElement ? b.value : b.textContent) ?? "";129    return AUTH_SIGNALS_RE.test(t) && !ANTI_AUTH_RE.test(t);130  });131  if (!hasAuthButton) return false;132133  // Reject if the same form has name/phone/address fields — that's registration, not login.134  const identifierEl = fields.find(f => f.type === "username" || f.type === "email")!.el;135  const form = identifierEl.closest("form") ?? document.body;136  const hasRegistrationFields = Array.from(form.querySelectorAll<HTMLInputElement>("input")).some(el => {137    if (!["", "text", "tel", "number"].includes(el.type.toLowerCase())) return false;138    if (!isVisible(el)) return false;139    return /\b(first.?name|last.?name|fname|lname|given|family|phone|mobile|company|organization|address)\b/i140      .test(el.name + el.id + el.placeholder);141  });142  return !hasRegistrationFields;143}144145// Password-step: the email/username was entered on a previous page; this page146// shows only a single password field. Also catches sites that render username147// and password on separate screens without autocomplete hints.148export function isPasswordStepForm(fields: DetectedField[]): boolean {149  const passwords = fields.filter(f => f.type === "password");150  return passwords.length === 1 && !fields.some(f => f.type === "username" || f.type === "email");151}152153// Single entry point used by every gate in index.ts. Covers all four patterns:154// traditional login, signup, email-first step, and password-only step.155export function isAnyCredentialForm(fields: DetectedField[]): boolean {156  return isLoginForm(fields) || isSignupForm(fields) || isEmailFirstForm(fields) || isPasswordStepForm(fields);157}158159export function isLoginForm(fields: DetectedField[]): boolean {160  const passwords = fields.filter((f) => f.type === "password");161  // Two or more password fields means signup/change-password, not login162  if (passwords.length >= 2) return false;163  const hasPassword = passwords.length > 0;164  const hasUsernameOrEmail = fields.some((f) => f.type === "username" || f.type === "email");165  if (hasPassword && hasUsernameOrEmail) return true;166  if (passwords.length === 1 && passwords[0].el.autocomplete === "current-password") {167    return true;168  }169  return false;170}171172export function isSignupForm(fields: DetectedField[]): boolean {173  const passwords = fields.filter((f) => f.type === "password");174  if (passwords.length >= 2) return true;175  if (passwords.some((f) => f.el.autocomplete === "new-password")) return true;176  if (177    passwords.some((f) => {178      const id = (f.el.id + f.el.name).toLowerCase();179      return /new|confirm/i.test(id);180    })181  ) {182    return true;183  }184  return false;185}186187export function detectLoginFields(root: Document | ShadowRoot = document): DetectedField[] {188  const inputs = Array.from(querySelectorAllDeep<HTMLInputElement>(root, "input"));189  const fields: DetectedField[] = [];190191  for (const el of inputs) {192    if (!isVisible(el)) continue;193    const type = el.type.toLowerCase();194    // Never treat buttons, checkboxes, hidden fields, etc. as autofill targets195    if (SKIP_INPUT_TYPES.has(type)) continue;196    // Catch <input> with no type attribute whose value text identifies it as a submit button197    if (looksLikeSubmitButton(el)) continue;198    const ac = el.autocomplete;199    const name = (el.name + el.id + el.placeholder).toLowerCase();200201    if (ac === "current-password" || ac === "new-password" || type === "password") {202      fields.push({ type: "password", el });203      continue;204    }205206    if (ac === "username" || ac === "email" || type === "email") {207      fields.push({ type: "username", el });208      continue;209    }210211    if (USERNAME_PATTERNS.test(name)) {212      fields.push({ type: "username", el });213      continue;214    }215216    const labelText = findLabelText(el);217    if (!fields.some((f) => f.el === el) && USERNAME_PATTERNS.test(labelText)) {218      fields.push({ type: "username", el });219    }220  }221222  // Fallback: if we have a password field but no username/email, look for223  // the first visible text input that appears before the password in DOM order.224  // This catches sites with unconventional field names (e.g. name="identifier").225  const hasUsername = fields.some((f) => f.type === "username" || f.type === "email");226  const pwField = fields.find((f) => f.type === "password");227  if (!hasUsername && pwField) {228    const allInputs = Array.from(inputs);229    const pwIndex = allInputs.indexOf(pwField.el);230    for (let i = 0; i < pwIndex; i++) {231      const candidate = allInputs[i];232      const candidateType = candidate.type.toLowerCase();233      if (234        (candidateType === "text" || candidateType === "email" || candidateType === "") &&235        isVisible(candidate) &&236        !SKIP_INPUT_TYPES.has(candidateType) &&237        !fields.some((f) => f.el === candidate)238      ) {239        fields.push({ type: "username", el: candidate });240        break; // only take the first one241      }242    }243  }244245  return fields;246}247248export function isVisible(el: HTMLElement): boolean {249  const s = getComputedStyle(el);250  const r = el.getBoundingClientRect();251  return (252    s.display !== "none" &&253    s.visibility !== "hidden" &&254    parseFloat(s.opacity) > 0 &&255    r.width > 0 &&256    r.height > 0257  );258}259260export function getPageDomain(): string {261  return extractDomain(location.hostname) ?? location.hostname;262}263264export interface CardFormFields {265  number: HTMLInputElement | null;266  expMonth: HTMLInputElement | null;267  expYear: HTMLInputElement | null;268  expiryCombo: HTMLInputElement | null;269  cvc: HTMLInputElement | null;270  name: HTMLInputElement | null;271}272273export function detectCardForm(root: Document | ShadowRoot = document): CardFormFields | null {274  const numberByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-number"]');275  const expByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp"]');276  const expMonthByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp-month"]');277  const expYearByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp-year"]');278  const cvcByAC = root.querySelector<HTMLInputElement>(279    'input[autocomplete="cc-csc"], input[autocomplete="cc-cvc"]'280  );281  const nameByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-name"]');282283  if (numberByAC) {284    return { number: numberByAC, expMonth: expMonthByAC, expYear: expYearByAC, expiryCombo: expByAC, cvc: cvcByAC, name: nameByAC };285  }286287  const allInputs = Array.from(root.querySelectorAll<HTMLInputElement>('input'));288  const numberField = allInputs.find(i =>289    /card.?num|cc.?num|cardnum|pan\b/i.test(i.name + i.id + i.placeholder)290  ) ?? null;291  const cvcField = allInputs.find(i =>292    /cvc|cvv|csc|security.?code/i.test(i.name + i.id + i.placeholder)293  ) ?? null;294  const expField = allInputs.find(i =>295    /exp|expiry|expiration/i.test(i.name + i.id + i.placeholder)296  ) ?? null;297298  if (!numberField) return null;299  return { number: numberField, expMonth: null, expYear: null, expiryCombo: expField, cvc: cvcField, name: null };300}301302const PAYMENT_PROCESSOR_IFRAMES = ['stripe.com', 'js.stripe.com', 'braintreegateway.com', 'paypal.com', 'adyen.com'];303304export function hasPaymentProcessorIframe(): boolean {305  const iframes = Array.from(document.querySelectorAll('iframe'));306  return iframes.some(f => PAYMENT_PROCESSOR_IFRAMES.some(host => f.src.includes(host)));307}