from __future__ import annotations import json import os import random import re import subprocess from pathlib import Path from typing import Any, Dict try: from browserforge.fingerprints import FingerprintGenerator, Screen except Exception: # pragma: no cover FingerprintGenerator = None Screen = None WINDOWS_MACHINE_PROFILES = [ { "locale": "en-US", "languages": ["en-US", "en"], "acceptLanguage": "en-US,en;q=0.9", "timezone": "America/New_York", "geoCountry": "US", "screen_pool": [ {"width": 1920, "height": 1080}, {"width": 1536, "height": 864}, {"width": 1600, "height": 900}, ], }, { "locale": "en-GB", "languages": ["en-GB", "en"], "acceptLanguage": "en-GB,en;q=0.9", "timezone": "Europe/London", "geoCountry": "GB", "screen_pool": [ {"width": 1920, "height": 1080}, {"width": 1366, "height": 768}, {"width": 1536, "height": 864}, ], }, { "locale": "de-DE", "languages": ["de-DE", "de", "en-US"], "acceptLanguage": "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7", "timezone": "Europe/Berlin", "geoCountry": "DE", "screen_pool": [ {"width": 1920, "height": 1080}, {"width": 1536, "height": 864}, {"width": 1440, "height": 900}, ], }, { "locale": "fr-FR", "languages": ["fr-FR", "fr", "en-US"], "acceptLanguage": "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7", "timezone": "Europe/Paris", "geoCountry": "FR", "screen_pool": [ {"width": 1920, "height": 1080}, {"width": 1536, "height": 864}, {"width": 1366, "height": 768}, ], }, { "locale": "zh-CN", "languages": ["zh-CN", "zh", "en-US"], "acceptLanguage": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7", "timezone": "Asia/Shanghai", "geoCountry": "CN", "screen_pool": [ {"width": 1920, "height": 1080}, {"width": 1600, "height": 900}, {"width": 1536, "height": 864}, ], }, ] def generate_fingerprint( browser_family: str = "chromium", *, browser_version: str | None = None, full_version: str | None = None, locale: str | None = None, timezone: str | None = None, geo_country: str | None = None, geo_mode: str | None = None, screen_width: int | None = None, screen_height: int | None = None, runtime_path: str | None = None, ) -> Dict[str, Any]: runtime_version = ( (full_version or "").strip() or _detect_runtime_version(browser_family, runtime_path) or _fallback_runtime_version(browser_family, browser_version) ) generated = _generate_with_browserforge( browser_family, screen_width=screen_width, screen_height=screen_height, locale=locale, timezone=timezone, geo_country=geo_country, runtime_version=runtime_version, ) if generated: return generated return _fallback_fingerprint( browser_family, screen_width=screen_width, screen_height=screen_height, locale=locale, timezone=timezone, geo_country=geo_country, runtime_version=runtime_version, ) def _generate_with_browserforge( browser_family: str, *, screen_width: int | None = None, screen_height: int | None = None, locale: str | None = None, timezone: str | None = None, geo_country: str | None = None, runtime_version: str | None = None, ) -> Dict[str, Any] | None: if FingerprintGenerator is None or Screen is None: return None browser_name = "firefox" if browser_family == "firefox" else "chrome" machine_profile = _select_machine_profile( locale=locale, timezone=timezone, geo_country=geo_country, ) selected_screen = _select_screen(machine_profile["screen_pool"], screen_width, screen_height) generator = FingerprintGenerator( screen=Screen( min_width=selected_screen["width"], max_width=selected_screen["width"], min_height=selected_screen["height"], max_height=selected_screen["height"], ), os="windows", device="desktop", locale=tuple(machine_profile["languages"]), strict=False, ) fingerprint = None for builder in ( lambda: generator.generate( browser=browser_name, os="windows", device="desktop", locale=tuple(machine_profile["languages"]), ), lambda: generator.generate( browser=browser_name, os="windows", locale=tuple(machine_profile["languages"]), ), lambda: generator.generate( browser=browser_name, locale=tuple(machine_profile["languages"]), ), lambda: generator.generate(), ): try: fingerprint = builder() if fingerprint is not None: break except TypeError: continue except Exception: return None if fingerprint is None: return None data = _to_dict(fingerprint) normalized = _normalize_generated_fingerprint( data, browser_family, machine_profile, selected_screen=selected_screen, runtime_version=runtime_version, ) screen = normalized["screen"] payload = { "source": "browserforge", "machineProfile": { "locale": machine_profile["locale"], "languages": machine_profile["languages"], "acceptLanguage": machine_profile["acceptLanguage"], "timezone": machine_profile["timezone"], "geoCountry": machine_profile["geoCountry"], }, "raw": normalized["raw"], } return { "browserFamily": browser_family, "browserVersion": _extract_browser_version(browser_family, runtime_version), "userAgent": normalized["user_agent"], "locale": machine_profile["locale"], "timezone": machine_profile["timezone"], "geoCountry": machine_profile["geoCountry"], "screenWidth": screen["width"], "screenHeight": screen["height"], "webRtcPolicy": _first_non_empty(data.get("webRtcPolicy"), "proxy_only"), "canvasPolicy": _first_non_empty(data.get("canvasPolicy"), "noise"), "webglPolicy": _first_non_empty(data.get("webglPolicy"), "mask"), "audioPolicy": _first_non_empty(data.get("audioPolicy"), "noise"), "fontPolicy": _first_non_empty(data.get("fontPolicy"), "system_default"), "encryptedPayload": json.dumps(payload, ensure_ascii=False), } def _fallback_fingerprint( browser_family: str, *, screen_width: int | None = None, screen_height: int | None = None, locale: str | None = None, timezone: str | None = None, geo_country: str | None = None, runtime_version: str | None = None, ) -> Dict[str, Any]: machine_profile = _select_machine_profile( locale=locale, timezone=timezone, geo_country=geo_country, ) screen = _select_screen(machine_profile["screen_pool"], screen_width, screen_height) if browser_family == "firefox": major = _detect_major_version(runtime_version) or random.choice([128, 129, 130, 131]) user_agent = ( f"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:{major}.0) " f"Gecko/20100101 Firefox/{major}.0" ) sec_ch_ua = None ua_meta = { "browser": "Firefox", "majorVersion": str(major), "fullVersion": f"{major}.0", "platform": "Windows", "platformVersion": "10.0.0", "architecture": "x86", "bitness": "64", "mobile": False, } else: full_version = _build_chromium_version(runtime_version) major = int(full_version.split(".", 1)[0]) user_agent = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " f"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{full_version} Safari/537.36" ) sec_ch_ua = ( f"\"Google Chrome\";v=\"{major}\", " f"\"Chromium\";v=\"{major}\", " "\"Not.A/Brand\";v=\"8\"" ) ua_meta = { "brands": [ {"brand": "Google Chrome", "version": str(major)}, {"brand": "Chromium", "version": str(major)}, {"brand": "Not.A/Brand", "version": "8"}, ], "fullVersionList": [ {"brand": "Google Chrome", "version": full_version}, {"brand": "Chromium", "version": full_version}, {"brand": "Not.A/Brand", "version": "8.0.0.0"}, ], "uaFullVersion": full_version, "platform": "Windows", "platformVersion": "19.0.0", "architecture": "x86", "bitness": "64", "mobile": False, "model": "", } payload = { "source": "fallback", "platform": "windows", "engine": browser_family, "locale": machine_profile["locale"], "languages": machine_profile["languages"], "acceptLanguage": machine_profile["acceptLanguage"], "timezone": machine_profile["timezone"], "geoCountry": machine_profile["geoCountry"], "screenWidth": screen["width"], "screenHeight": screen["height"], "webRtcPolicy": "proxy_only", "canvasPolicy": "noise", "webglPolicy": "mask", "audioPolicy": "noise", "fontPolicy": "system_default", "navigator": { "userAgent": user_agent, "language": machine_profile["locale"], "languages": machine_profile["languages"], "platform": "Win32", "hardwareConcurrency": random.choice([8, 12, 16]), "deviceMemory": random.choice([8, 16]), "vendor": "Google Inc." if browser_family == "chromium" else "", "userAgentData": ua_meta if browser_family == "chromium" else None, }, "headers": { "User-Agent": user_agent, "Accept-Language": machine_profile["acceptLanguage"], "sec-ch-ua": sec_ch_ua, "sec-ch-ua-mobile": "?0" if browser_family == "chromium" else None, "sec-ch-ua-platform": "\"Windows\"" if browser_family == "chromium" else None, }, "screen": { "width": screen["width"], "height": screen["height"], "availWidth": screen["width"], "availHeight": max(screen["height"] - random.choice([32, 40, 48]), 720), "colorDepth": 24, "pixelDepth": 24, }, } return { "browserFamily": browser_family, "browserVersion": _extract_browser_version(browser_family, runtime_version), "userAgent": user_agent, "locale": payload["locale"], "timezone": payload["timezone"], "geoCountry": payload["geoCountry"], "screenWidth": payload["screenWidth"], "screenHeight": payload["screenHeight"], "webRtcPolicy": payload["webRtcPolicy"], "canvasPolicy": payload["canvasPolicy"], "webglPolicy": payload["webglPolicy"], "audioPolicy": payload["audioPolicy"], "fontPolicy": payload["fontPolicy"], "encryptedPayload": json.dumps(payload, ensure_ascii=False), } def _select_machine_profile( *, locale: str | None = None, timezone: str | None = None, geo_country: str | None = None, ) -> Dict[str, Any]: normalized_locale = (locale or "").strip().lower() normalized_timezone = (timezone or "").strip() normalized_country = (geo_country or "").strip().upper() matches = [] for profile in WINDOWS_MACHINE_PROFILES: score = 0 if normalized_country and profile["geoCountry"] == normalized_country: score += 3 if normalized_timezone and profile["timezone"] == normalized_timezone: score += 2 if normalized_locale and profile["locale"].lower() == normalized_locale: score += 2 elif normalized_locale and normalized_locale in { language.lower() for language in profile["languages"] }: score += 1 matches.append((score, profile)) best_score = max((score for score, _ in matches), default=0) if best_score <= 0: return random.choice(WINDOWS_MACHINE_PROFILES) candidates = [profile for score, profile in matches if score == best_score] return random.choice(candidates) def _normalize_generated_fingerprint( data: Dict[str, Any], browser_family: str, machine_profile: Dict[str, Any], *, selected_screen: Dict[str, int] | None = None, runtime_version: str | None = None, ) -> Dict[str, Any]: raw = json.loads(json.dumps(data)) navigator = raw.setdefault("navigator", {}) headers = raw.setdefault("headers", {}) screen = raw.setdefault("screen", {}) selected_screen = selected_screen or random.choice(machine_profile["screen_pool"]) user_agent = _first_non_empty( raw.get("userAgent"), raw.get("user_agent"), navigator.get("userAgent"), "", ) if user_agent: user_agent = _normalize_user_agent_version(user_agent, browser_family, runtime_version) navigator["userAgent"] = user_agent headers["User-Agent"] = user_agent navigator["language"] = machine_profile["locale"] navigator["languages"] = machine_profile["languages"] raw["locale"] = machine_profile["locale"] raw["language"] = machine_profile["locale"] raw["timezone"] = machine_profile["timezone"] raw["timezoneId"] = machine_profile["timezone"] raw["geoCountry"] = machine_profile["geoCountry"] raw["country"] = machine_profile["geoCountry"] headers["Accept-Language"] = machine_profile["acceptLanguage"] screen["width"] = selected_screen["width"] screen["height"] = selected_screen["height"] screen["availWidth"] = selected_screen["width"] screen["availHeight"] = max(selected_screen["height"] - random.choice([32, 40, 48]), 720) screen["colorDepth"] = screen.get("colorDepth") or 24 screen["pixelDepth"] = screen.get("pixelDepth") or 24 raw["screenWidth"] = selected_screen["width"] raw["screenHeight"] = selected_screen["height"] if browser_family == "chromium": ua_data = navigator.get("userAgentData") or {} full_version = _extract_full_chrome_version(user_agent) major_version = full_version.split(".", 1)[0] if full_version else "137" ua_data["brands"] = [ {"brand": "Google Chrome", "version": major_version}, {"brand": "Chromium", "version": major_version}, {"brand": "Not.A/Brand", "version": "8"}, ] ua_data["fullVersionList"] = [ {"brand": "Google Chrome", "version": full_version}, {"brand": "Chromium", "version": full_version}, {"brand": "Not.A/Brand", "version": "8.0.0.0"}, ] ua_data["uaFullVersion"] = full_version ua_data["platform"] = "Windows" ua_data["platformVersion"] = "19.0.0" ua_data["architecture"] = "x86" ua_data["bitness"] = "64" ua_data["mobile"] = False ua_data["model"] = "" navigator["userAgentData"] = ua_data navigator["vendor"] = "Google Inc." headers["sec-ch-ua"] = ( f"\"Google Chrome\";v=\"{major_version}\", " f"\"Chromium\";v=\"{major_version}\", " "\"Not.A/Brand\";v=\"8\"" ) headers["sec-ch-ua-mobile"] = "?0" headers["sec-ch-ua-platform"] = "\"Windows\"" else: navigator.pop("userAgentData", None) navigator["vendor"] = "" headers.pop("sec-ch-ua", None) headers.pop("sec-ch-ua-mobile", None) headers.pop("sec-ch-ua-platform", None) return { "raw": raw, "screen": {"width": selected_screen["width"], "height": selected_screen["height"]}, "user_agent": user_agent, } def _to_dict(value: Any) -> Dict[str, Any]: if isinstance(value, dict): return value if hasattr(value, "model_dump"): try: return value.model_dump() except Exception: pass if hasattr(value, "dict"): try: return value.dict() except Exception: pass if hasattr(value, "__dict__"): try: result: Dict[str, Any] = {} for key, item in vars(value).items(): if key.startswith("_"): continue if isinstance(item, dict): result[key] = item elif hasattr(item, "__dict__"): result[key] = _to_dict(item) else: result[key] = item return result except Exception: return {} return {} def _extract_screen(data: Dict[str, Any]) -> Dict[str, int]: screen = data.get("screen") or {} width = _first_non_empty( screen.get("width"), data.get("screenWidth"), data.get("screen_width"), 1920, ) height = _first_non_empty( screen.get("height"), data.get("screenHeight"), data.get("screen_height"), 1080, ) return {"width": int(width), "height": int(height)} def _extract_full_chrome_version(user_agent: str) -> str: marker = "Chrome/" if marker not in user_agent: return "137.0.0.0" version = user_agent.split(marker, 1)[1].split(" ", 1)[0].strip() return version or "137.0.0.0" def _detect_runtime_version(browser_family: str, runtime_path: str | None) -> str | None: normalized_path = _normalize_runtime_path(runtime_path) if not normalized_path: return None try: result = subprocess.run( [normalized_path, "--version"], capture_output=True, text=True, timeout=3, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), ) except Exception: return None output = " ".join( part.strip() for part in (result.stdout, result.stderr) if isinstance(part, str) and part.strip() ) match = re.search(r"(\d+\.\d+\.\d+\.\d+)", output) if match: return match.group(1) major_match = re.search(r"(\d+)(?:\.\d+)?", output) if major_match and browser_family == "firefox": return f"{major_match.group(1)}.0" return None def _normalize_runtime_path(runtime_path: str | None) -> str | None: if runtime_path and Path(runtime_path).exists(): return runtime_path env_path = os.environ.get("CHROMIUM_RUNTIME_PATH") if env_path and Path(env_path).exists(): return env_path return None def _detect_major_version(version: str | None) -> int | None: if not version: return None try: return int(str(version).split(".", 1)[0]) except (TypeError, ValueError): return None def _build_chromium_version(runtime_version: str | None) -> str: if runtime_version and re.fullmatch(r"\d+\.\d+\.\d+\.\d+", runtime_version): return runtime_version major = random.choice([136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147]) build = random.randint(7100, 7999) patch = random.randint(40, 199) return f"{major}.0.{build}.{patch}" def _fallback_runtime_version(browser_family: str, browser_version: str | None) -> str | None: normalized = (browser_version or "").strip() if not normalized: return None if browser_family == "firefox": return f"{normalized}.0" if re.fullmatch(r"\d+", normalized) else normalized if re.fullmatch(r"\d+\.\d+\.\d+\.\d+", normalized): return normalized if re.fullmatch(r"\d+", normalized): return f"{normalized}.0.0.0" return normalized def _extract_browser_version(browser_family: str, runtime_version: str | None) -> str | None: if not runtime_version: return None if browser_family == "firefox": return str(_detect_major_version(runtime_version) or runtime_version) return runtime_version.split(".", 1)[0] def _select_screen(screen_pool: list[dict], screen_width: int | None, screen_height: int | None) -> dict: if screen_width and screen_height: return {"width": int(screen_width), "height": int(screen_height)} return random.choice(screen_pool) def _normalize_user_agent_version( user_agent: str, browser_family: str, runtime_version: str | None, ) -> str: if browser_family != "chromium" or not runtime_version: return user_agent return re.sub(r"Chrome/\d+\.\d+\.\d+\.\d+", f"Chrome/{runtime_version}", user_agent, count=1) def _first_non_empty(*values: Any) -> Any: for value in values: if value is None: continue if isinstance(value, str) and value == "": continue return value return None