1import { extractDomain } from "../shared/domain";23export interface DetectedField {4 type: "username" | "password" | "email";5 el: HTMLInputElement;6}789101112const USERNAME_PATTERNS = /(user(name|id|login|email)?|e?mail(box)?|login(email|username)?|account|identifier|signin|sign.?in|credential)/i;13141516const 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;171819202122const 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]);28293031function 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 44 45 46 try {47 const label = document.querySelector<HTMLLabelElement>(`label[for="${CSS.escape(id)}"]`);48 if (label) return label.textContent?.toLowerCase() ?? "";49 } catch {50 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 73 74 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}96979899100101102103104function isSingleDigitBox(el: HTMLInputElement): boolean {105 return el.getAttribute("maxlength") === "1";106}107108export function isTOTPField(input: HTMLInputElement): boolean {109 if (!isVisible(input)) return false;110 111 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}129130131132const 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;134135136137138139export 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 144 if (/\/(login|signin|sign-in|logon|auth|sso|connect|account(?:\/|$))\b/i.test(location.pathname)) return true;145146 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 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}167168169170171export 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}175176177178export 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 185 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 218 if (SKIP_INPUT_TYPES.has(type)) continue;219 220 if (isSingleDigitBox(el)) continue;221 222 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 237 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 255 256 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; 276 }277 }278 }279280 return fields;281}282283284285286287288export 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}306307308309310311312313export 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}