detect.ts

16.5 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// Personal name fields (display name, first/last name) — not credential fields.15// Applied to prevent the fallback from picking up name inputs on signup forms.16const NAME_FIELD_PATTERNS = /\b(first[\s_-]?name|last[\s_-]?name|full[\s_-]?name|display[\s_-]?name|real[\s_-]?name|given[\s_-]?name|family[\s_-]?name|middle[\s_-]?name)\b|^(name|fname|lname|fullname|displayname|realname)$/i;1718// Input types that are never text-entry fields and must never get autofill19// icons. submit/button/reset/image are interactive controls — putting the20// icon over them blocks the click. The rest are structurally incapable of21// holding a username/password.22const SKIP_INPUT_TYPES = new Set([23  "submit", "button", "reset", "image",24  "checkbox", "radio", "hidden", "file",25  "range", "color", "date", "time",26  "datetime-local", "month", "week",27]);2829// Some sites render submit buttons as <input> with no type attribute (defaults to "text")30// and a value like "Login" or "Submit". Catch those before injecting icons.31function looksLikeSubmitButton(input: HTMLInputElement): boolean {32  if (input.type === "password") return false;33  const val = (input.value || input.getAttribute("value") || "").toLowerCase().trim();34  if (!val) return false;35  return ["submit", "login", "sign in", "log in", "continue", "next", "go"].some(w => val === w || val.startsWith(w + " "));36}3738function findLabelText(field: HTMLInputElement): string {39  const ariaLabel = field.getAttribute("aria-label") ?? "";40  if (ariaLabel) return ariaLabel.toLowerCase();41  const id = field.id;42  if (id) {43    // PCH-01-025: ids can contain CSS-special chars (quotes, brackets, leading44    // digits). Escape, and defensively swallow a malformed-selector throw so a45    // single weird id can't abort field detection for the whole page.46    try {47      const label = document.querySelector<HTMLLabelElement>(`label[for="${CSS.escape(id)}"]`);48      if (label) return label.textContent?.toLowerCase() ?? "";49    } catch {50      /* malformed id — skip label-by-id lookup, continue field detection */51    }52  }53  const wrappingLabel = field.closest("label");54  if (wrappingLabel?.textContent) return wrappingLabel.textContent.toLowerCase();5556  let node: Element | null = field;57  for (let depth = 0; node && depth < 3; depth++) {58    const previous = node.previousElementSibling;59    const text = previous?.textContent?.trim().toLowerCase() ?? "";60    if (text && text.length <= 80 && !previous?.querySelector("input, select, textarea, button")) {61      return text;62    }63    node = node.parentElement;64  }65  return "";66}6768export function querySelectorAllDeep<T extends Element>(69  root: Document | ShadowRoot | Element,70  selector: string71): T[] {72  // One query per root, then recurse into each open shadow root. Re-querying73  // every visited element returned a nested field once per ancestor and missed74  // shadow roots' direct children.75  const results = Array.from(root.querySelectorAll<T>(selector));76  for (const host of root.querySelectorAll("*")) {77    const shadowRoot = host.shadowRoot;78    if (!shadowRoot) continue;79    for (const match of querySelectorAllDeep<T>(shadowRoot, selector)) results.push(match);80  }81  return results;82}8384export function getDeepActiveInput(): HTMLInputElement | null {85  let current: Document | Element | null = document.activeElement;86  while (current) {87    if (current instanceof HTMLInputElement) return current;88    if (current instanceof Element && current.shadowRoot) {89      current = current.shadowRoot.activeElement;90    } else {91      break;92    }93  }94  return null;95}9697// True for a single-character OTP digit box. Reads the maxlength ATTRIBUTE, not98// the .maxLength property: for type="number"/"tel" inputs (the usual way to get99// a numeric keypad for 2FA codes) the maxlength attribute is IGNORED — browsers100// report .maxLength as a large default (524288) even when the author wrote101// maxlength="1". Reading the attribute reliably captures the real intent, so a102// numeric 2FA box group is recognised as split-OTP instead of each box being103// injected with its own autofill icon.104function isSingleDigitBox(el: HTMLInputElement): boolean {105  return el.getAttribute("maxlength") === "1";106}107108export function isTOTPField(input: HTMLInputElement): boolean {109  if (!isVisible(input)) return false;110  // Single-character inputs are individual OTP digit boxes — treat the form's111  // full-code input (if any) as the TOTP field, not each individual digit box.112  if (isSingleDigitBox(input)) return false;113  const autocomplete = input.autocomplete.toLowerCase();114  const fieldText = `${input.name} ${input.id} ${input.placeholder}`.toLowerCase();115  if (116    autocomplete === "one-time-code" ||117    /\b(otp|totp|2fa|mfa)\b/.test(fieldText) ||118    /\b(verification|authenticator|security)\s+code\b/.test(fieldText)119  ) {120    return true;121  }122123  const labelText = findLabelText(input);124  return (125    /\b(otp|totp|2fa|mfa)\b/.test(labelText) ||126    /\b(verification|authenticator|security)\s+code\b/.test(labelText)127  );128}129130// AUTH_SIGNALS_RE: submit buttons / form actions / headings that indicate auth intent.131// ANTI_AUTH_RE: signals that contradict auth (newsletter, registration with name fields, etc.).132const AUTH_SIGNALS_RE = /sign.?(?:in|up)|log.?in|continue|next\b|proceed|let.?me.?in|get started|verify|unlock|access/i;133const ANTI_AUTH_RE = /subscri|newsletter|register|join\b|contact|comment/i;134135// Email-first / identifier-first step: user enters email or username on this page;136// the password prompt comes on the next step. Requires at least one auth-intent137// signal (URL path, form action, or submit button text) to avoid false-positives138// on newsletter and search forms that also have a single email field.139export function isEmailFirstForm(fields: DetectedField[]): boolean {140  if (!fields.some(f => f.type === "username" || f.type === "email")) return false;141  if (fields.some(f => f.type === "password")) return false;142143  // Strong URL signal: /login, /signin, /auth, /sso, /account, etc.144  if (/\/(login|signin|sign-in|logon|auth|sso|connect|account(?:\/|$))\b/i.test(location.pathname)) return true;145146  // Check submit buttons for auth intent.147  const buttons = Array.from(document.querySelectorAll<HTMLElement>(148    'button[type="submit"], input[type="submit"], button:not([type="button"]):not([type="reset"])'149  ));150  const hasAuthButton = buttons.some(b => {151    const t = (b instanceof HTMLInputElement ? b.value : b.textContent) ?? "";152    return AUTH_SIGNALS_RE.test(t) && !ANTI_AUTH_RE.test(t);153  });154  if (!hasAuthButton) return false;155156  // Reject if the same form has name/phone/address fields — that's registration, not login.157  const identifierEl = fields.find(f => f.type === "username" || f.type === "email")!.el;158  const form = identifierEl.closest("form") ?? document.body;159  const hasRegistrationFields = Array.from(form.querySelectorAll<HTMLInputElement>("input")).some(el => {160    if (!["", "text", "tel", "number"].includes(el.type.toLowerCase())) return false;161    if (!isVisible(el)) return false;162    return /\b(first.?name|last.?name|fname|lname|given|family|phone|mobile|company|organization|address)\b/i163      .test(el.name + el.id + el.placeholder);164  });165  return !hasRegistrationFields;166}167168// Password-step: the email/username was entered on a previous page; this page169// shows only a single password field. Also catches sites that render username170// and password on separate screens without autocomplete hints.171export function isPasswordStepForm(fields: DetectedField[]): boolean {172  const passwords = fields.filter(f => f.type === "password");173  return passwords.length === 1 && !fields.some(f => f.type === "username" || f.type === "email");174}175176// Single entry point used by every gate in index.ts. Covers all four patterns:177// traditional login, signup, email-first step, and password-only step.178export function isAnyCredentialForm(fields: DetectedField[]): boolean {179  return isLoginForm(fields) || isSignupForm(fields) || isEmailFirstForm(fields) || isPasswordStepForm(fields);180}181182export function isLoginForm(fields: DetectedField[]): boolean {183  const passwords = fields.filter((f) => f.type === "password");184  // Two or more password fields means signup/change-password, not login185  if (passwords.length >= 2) return false;186  const hasPassword = passwords.length > 0;187  const hasUsernameOrEmail = fields.some((f) => f.type === "username" || f.type === "email");188  if (hasPassword && hasUsernameOrEmail) return true;189  if (passwords.length === 1 && passwords[0].el.autocomplete === "current-password") {190    return true;191  }192  return false;193}194195export function isSignupForm(fields: DetectedField[]): boolean {196  const passwords = fields.filter((f) => f.type === "password");197  if (passwords.length >= 2) return true;198  if (passwords.some((f) => f.el.autocomplete === "new-password")) return true;199  if (200    passwords.some((f) => {201      const id = (f.el.id + f.el.name).toLowerCase();202      return /new|confirm/i.test(id);203    })204  ) {205    return true;206  }207  return false;208}209210export function detectLoginFields(root: Document | ShadowRoot = document): DetectedField[] {211  const inputs = Array.from(querySelectorAllDeep<HTMLInputElement>(root, "input"));212  const fields: DetectedField[] = [];213214  for (const el of inputs) {215    if (!isVisible(el)) continue;216    const type = el.type.toLowerCase();217    // Never treat buttons, checkboxes, hidden fields, etc. as autofill targets218    if (SKIP_INPUT_TYPES.has(type)) continue;219    // Single-character inputs are individual OTP digit boxes — never credential fields220    if (isSingleDigitBox(el)) continue;221    // Catch <input> with no type attribute whose value text identifies it as a submit button222    if (looksLikeSubmitButton(el)) continue;223    const ac = el.autocomplete;224    const name = (el.name + el.id + el.placeholder).toLowerCase();225226    if (ac === "current-password" || ac === "new-password" || type === "password") {227      fields.push({ type: "password", el });228      continue;229    }230231    if (ac === "username") {232      fields.push({ type: "username", el });233      continue;234    }235236    // Explicit email autocomplete or type — classified as "email" so interaction.ts237    // can track it separately from the username field on signup forms.238    if (ac === "email" || type === "email") {239      fields.push({ type: "email", el });240      continue;241    }242243    if (USERNAME_PATTERNS.test(name)) {244      fields.push({ type: "username", el });245      continue;246    }247248    const labelText = findLabelText(el);249    if (!fields.some((f) => f.el === el) && USERNAME_PATTERNS.test(labelText)) {250      fields.push({ type: "username", el });251    }252  }253254  // Fallback: if we have a password field but no username/email, look for255  // the first visible text input that appears before the password in DOM order.256  // This catches sites with unconventional field names (e.g. name="identifier").257  const hasUsername = fields.some((f) => f.type === "username" || f.type === "email");258  const pwField = fields.find((f) => f.type === "password");259  if (!hasUsername && pwField) {260    const allInputs = Array.from(inputs);261    const pwIndex = allInputs.indexOf(pwField.el);262    for (let i = 0; i < pwIndex; i++) {263      const candidate = allInputs[i];264      const candidateType = candidate.type.toLowerCase();265      const candidateHint = (candidate.name + " " + candidate.id + " " + candidate.placeholder).toLowerCase();266      const candidateLabel = findLabelText(candidate);267      if (268        (candidateType === "text" || candidateType === "email" || candidateType === "") &&269        isVisible(candidate) &&270        !SKIP_INPUT_TYPES.has(candidateType) &&271        !fields.some((f) => f.el === candidate) &&272        !NAME_FIELD_PATTERNS.test(candidateHint + " " + candidateLabel)273      ) {274        fields.push({ type: "username", el: candidate });275        break; // only take the first one276      }277    }278  }279280  return fields;281}282283// Returns the ordered list of single-character inputs that form a multi-digit284// OTP entry group, or null if `el` is not part of one. Anchors the search on285// the nearest <form>; falls back to document.body for formless SPA pages.286// Groups of fewer than 4 or more than 10 boxes are ignored — those ranges287// are outside every practical OTP code length.288export function findOTPDigitBoxGroup(el: HTMLInputElement): HTMLInputElement[] | null {289  if (!isSingleDigitBox(el)) return null;290  const t = el.type.toLowerCase();291  if (!["text", "number", "tel", ""].includes(t)) return null;292  if (!isVisible(el)) return null;293294  const searchRoot: Element = el.closest("form") ?? document.body;295  const digitBoxes = Array.from(searchRoot.querySelectorAll<HTMLInputElement>("input")).filter(input => {296    if (!isSingleDigitBox(input)) return false;297    if (!isVisible(input)) return false;298    const it = input.type.toLowerCase();299    return ["text", "number", "tel", ""].includes(it);300  });301302  if (digitBoxes.length < 4 || digitBoxes.length > 10) return null;303  if (!digitBoxes.includes(el)) return null;304  return digitBoxes;305}306307// Returns the ordered OTP-signaling inputs sharing `field`'s form when there are308// 4–10 of them — the split-digit-box pattern used by sites whose individual309// boxes lack maxlength="1" (so isSingleDigitBox / findOTPDigitBoxGroup miss them310// and each box would otherwise get its own injected icon). isTOTPField already311// rejects maxlength=1 boxes, so this never overlaps with findOTPDigitBoxGroup;312// a lone one-time-code field has only one peer and returns null.313export function findOtpSignalingGroup(field: HTMLInputElement): HTMLInputElement[] | null {314  if (!isVisible(field)) return null;315  if (!isTOTPField(field)) return null;316  const root: Element = field.form ?? document.body;317  const peers = Array.from(root.querySelectorAll<HTMLInputElement>("input")).filter(isTOTPField);318  if (peers.length < 4 || peers.length > 10) return null;319  return peers.includes(field) ? peers : null;320}321322export function isVisible(el: HTMLElement): boolean {323  const s = getComputedStyle(el);324  const r = el.getBoundingClientRect();325  return (326    s.display !== "none" &&327    s.visibility !== "hidden" &&328    parseFloat(s.opacity) > 0 &&329    r.width > 0 &&330    r.height > 0331  );332}333334export function getPageDomain(): string {335  return extractDomain(location.hostname) ?? location.hostname;336}337338export interface CardFormFields {339  number: HTMLInputElement | null;340  expMonth: HTMLInputElement | null;341  expYear: HTMLInputElement | null;342  expiryCombo: HTMLInputElement | null;343  cvc: HTMLInputElement | null;344  name: HTMLInputElement | null;345}346347export function detectCardForm(root: Document | ShadowRoot = document): CardFormFields | null {348  const numberByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-number"]');349  const expByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp"]');350  const expMonthByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp-month"]');351  const expYearByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-exp-year"]');352  const cvcByAC = root.querySelector<HTMLInputElement>(353    'input[autocomplete="cc-csc"], input[autocomplete="cc-cvc"]'354  );355  const nameByAC = root.querySelector<HTMLInputElement>('input[autocomplete="cc-name"]');356357  if (numberByAC) {358    return { number: numberByAC, expMonth: expMonthByAC, expYear: expYearByAC, expiryCombo: expByAC, cvc: cvcByAC, name: nameByAC };359  }360361  const allInputs = Array.from(root.querySelectorAll<HTMLInputElement>('input'));362  const numberField = allInputs.find(i =>363    /card.?num|cc.?num|cardnum|pan\b/i.test(i.name + i.id + i.placeholder)364  ) ?? null;365  const cvcField = allInputs.find(i =>366    /cvc|cvv|csc|security.?code/i.test(i.name + i.id + i.placeholder)367  ) ?? null;368  const expField = allInputs.find(i =>369    /exp|expiry|expiration/i.test(i.name + i.id + i.placeholder)370  ) ?? null;371372  if (!numberField) return null;373  return { number: numberField, expMonth: null, expYear: null, expiryCombo: expField, cvc: cvcField, name: null };374}375376const PAYMENT_PROCESSOR_IFRAMES = ['stripe.com', 'js.stripe.com', 'braintreegateway.com', 'paypal.com', 'adyen.com'];377378export function hasPaymentProcessorIframe(): boolean {379  const iframes = Array.from(document.querySelectorAll('iframe'));380  return iframes.some(f => PAYMENT_PROCESSOR_IFRAMES.some(host => f.src.includes(host)));381}