626 lines
22 KiB
Python
626 lines
22 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import threading
|
|
import time
|
|
import urllib.request
|
|
from typing import Any, Dict, Optional
|
|
|
|
import websockets
|
|
|
|
|
|
class ChromiumFingerprintSession:
|
|
def __init__(
|
|
self,
|
|
port: int,
|
|
fingerprint: Optional[dict],
|
|
start_url: str,
|
|
timeout_seconds: float = 8.0,
|
|
) -> None:
|
|
self.port = port
|
|
self.start_url = start_url
|
|
self.timeout_seconds = timeout_seconds
|
|
self._thread: Optional[threading.Thread] = None
|
|
self._stop_event = threading.Event()
|
|
self._status_lock = threading.Lock()
|
|
self._prepare_error: Optional[str] = None
|
|
self._payload = self._prepare_payload(fingerprint)
|
|
self._status: Dict[str, Any] = self._initial_status()
|
|
|
|
def start(self) -> Dict[str, Any]:
|
|
if not self._payload:
|
|
self._update_status(
|
|
attempted=bool(self._status["attempted"]),
|
|
applied=False,
|
|
reason=self._status.get("reason") or "no_fingerprint",
|
|
)
|
|
return self.status()
|
|
self._thread = threading.Thread(
|
|
target=self._run_loop,
|
|
name=f"chromium-fingerprint-{self.port}",
|
|
daemon=True,
|
|
)
|
|
self._thread.start()
|
|
deadline = time.time() + self.timeout_seconds
|
|
while time.time() < deadline:
|
|
snapshot = self.status()
|
|
if snapshot.get("applied") or snapshot.get("reason") not in {"starting", "waiting_for_target"}:
|
|
return snapshot
|
|
time.sleep(0.1)
|
|
return self.status()
|
|
|
|
def stop(self) -> None:
|
|
self._stop_event.set()
|
|
if self._thread and self._thread.is_alive():
|
|
self._thread.join(timeout=3)
|
|
|
|
def status(self) -> Dict[str, Any]:
|
|
with self._status_lock:
|
|
return dict(self._status)
|
|
|
|
def _initial_status(self) -> Dict[str, Any]:
|
|
if self._prepare_error:
|
|
return {
|
|
"attempted": True,
|
|
"applied": False,
|
|
"reason": "invalid_fingerprint_payload",
|
|
"error": self._prepare_error,
|
|
}
|
|
if not self._payload:
|
|
return {
|
|
"attempted": False,
|
|
"applied": False,
|
|
"reason": "no_fingerprint",
|
|
}
|
|
return {
|
|
"attempted": True,
|
|
"applied": False,
|
|
"reason": "starting",
|
|
"attached_targets": 0,
|
|
}
|
|
|
|
def _prepare_payload(self, fingerprint: Optional[dict]) -> Optional[Dict[str, Any]]:
|
|
if not fingerprint:
|
|
return None
|
|
try:
|
|
return _build_injection_payload(fingerprint)
|
|
except Exception as exc:
|
|
self._prepare_error = str(exc)
|
|
return None
|
|
|
|
def _run_loop(self) -> None:
|
|
try:
|
|
asyncio.run(self._run_async())
|
|
except Exception as exc:
|
|
self._update_status(applied=False, reason="cdp_session_failed", error=str(exc))
|
|
|
|
async def _run_async(self) -> None:
|
|
if not self._payload:
|
|
return
|
|
self._update_status(reason="waiting_for_target")
|
|
version_info = await _wait_for_version(self.port, self.timeout_seconds)
|
|
websocket_url = version_info.get("webSocketDebuggerUrl")
|
|
if not websocket_url:
|
|
raise RuntimeError("missing browser websocket debugger url")
|
|
|
|
async with websockets.connect(websocket_url, max_size=None) as ws:
|
|
session = _BrowserSession(
|
|
websocket=ws,
|
|
port=self.port,
|
|
payload=self._payload,
|
|
start_url=self.start_url,
|
|
stop_event=self._stop_event,
|
|
status_callback=self._update_status,
|
|
)
|
|
await session.run()
|
|
|
|
def _update_status(self, **changes: Any) -> None:
|
|
with self._status_lock:
|
|
self._status.update(changes)
|
|
|
|
|
|
class _BrowserSession:
|
|
def __init__(
|
|
self,
|
|
websocket: websockets.WebSocketClientProtocol,
|
|
port: int,
|
|
payload: Dict[str, Any],
|
|
start_url: str,
|
|
stop_event: threading.Event,
|
|
status_callback,
|
|
) -> None:
|
|
self._websocket = websocket
|
|
self._port = port
|
|
self._payload = payload
|
|
self._start_url = start_url
|
|
self._stop_event = stop_event
|
|
self._status_callback = status_callback
|
|
self._next_id = 0
|
|
self._pending: dict[int, asyncio.Future] = {}
|
|
self._session_scripts: set[str] = set()
|
|
self._target_tasks: set[asyncio.Task] = set()
|
|
self._initial_navigated = False
|
|
self._attached_targets = 0
|
|
|
|
async def run(self) -> None:
|
|
receiver = asyncio.create_task(self._recv_loop())
|
|
try:
|
|
await self._call(
|
|
"Target.setAutoAttach",
|
|
{
|
|
"autoAttach": True,
|
|
"waitForDebuggerOnStart": False,
|
|
"flatten": True,
|
|
},
|
|
)
|
|
await self._call("Target.setDiscoverTargets", {"discover": True})
|
|
await self._attach_existing_targets()
|
|
deadline = time.time() + 1.5
|
|
while time.time() < deadline and not self._initial_navigated:
|
|
await asyncio.sleep(0.05)
|
|
self._status_callback(
|
|
applied=self._initial_navigated,
|
|
reason="ok" if self._initial_navigated else "session_running",
|
|
attached_targets=self._attached_targets,
|
|
)
|
|
while not self._stop_event.is_set():
|
|
await asyncio.sleep(0.2)
|
|
finally:
|
|
receiver.cancel()
|
|
for task in list(self._target_tasks):
|
|
task.cancel()
|
|
try:
|
|
await receiver
|
|
except asyncio.CancelledError:
|
|
pass
|
|
|
|
async def _attach_existing_targets(self) -> None:
|
|
targets = _fetch_json(f"http://127.0.0.1:{self._port}/json/list")
|
|
if not isinstance(targets, list):
|
|
return
|
|
for target in targets:
|
|
target_id = target.get("id")
|
|
if target.get("type") != "page" or not target_id:
|
|
continue
|
|
try:
|
|
result = await self._call(
|
|
"Target.attachToTarget",
|
|
{"targetId": target_id, "flatten": True},
|
|
)
|
|
session_id = result.get("sessionId")
|
|
if session_id:
|
|
await self._apply_to_target(
|
|
session_id,
|
|
{
|
|
"targetId": target_id,
|
|
"type": target.get("type"),
|
|
"url": target.get("url"),
|
|
"title": target.get("title"),
|
|
},
|
|
)
|
|
except Exception:
|
|
continue
|
|
|
|
async def _recv_loop(self) -> None:
|
|
while True:
|
|
message = json.loads(await self._websocket.recv())
|
|
if "id" in message:
|
|
future = self._pending.pop(message["id"], None)
|
|
if future and not future.done():
|
|
if "error" in message:
|
|
future.set_exception(RuntimeError(str(message["error"])))
|
|
else:
|
|
future.set_result(message.get("result", {}))
|
|
continue
|
|
method = message.get("method")
|
|
params = message.get("params", {})
|
|
if method == "Target.attachedToTarget":
|
|
session_id = params.get("sessionId")
|
|
target_info = params.get("targetInfo") or {}
|
|
if session_id and target_info.get("type") == "page":
|
|
task = asyncio.create_task(self._apply_to_target(session_id, target_info))
|
|
self._target_tasks.add(task)
|
|
task.add_done_callback(self._target_tasks.discard)
|
|
|
|
async def _apply_to_target(self, session_id: str, target_info: Dict[str, Any]) -> None:
|
|
if session_id in self._session_scripts:
|
|
return
|
|
self._session_scripts.add(session_id)
|
|
self._attached_targets += 1
|
|
headers = {
|
|
key: value
|
|
for key, value in self._payload["headers"].items()
|
|
if isinstance(value, str) and value
|
|
}
|
|
await self._call("Page.enable", session_id=session_id)
|
|
await self._call("Network.enable", session_id=session_id)
|
|
await self._call(
|
|
"Network.setUserAgentOverride",
|
|
{
|
|
"userAgent": self._payload["user_agent"],
|
|
"acceptLanguage": self._payload["accept_language"],
|
|
"platform": self._payload["platform"],
|
|
"userAgentMetadata": self._payload["user_agent_metadata"],
|
|
},
|
|
session_id=session_id,
|
|
)
|
|
if headers:
|
|
await self._call(
|
|
"Network.setExtraHTTPHeaders",
|
|
{"headers": headers},
|
|
session_id=session_id,
|
|
)
|
|
for cookie in self._payload.get("cookies", []):
|
|
try:
|
|
cookie_payload = dict(cookie)
|
|
if "url" not in cookie_payload and "domain" not in cookie_payload and self._start_url:
|
|
cookie_payload["url"] = self._start_url
|
|
await self._call(
|
|
"Network.setCookie",
|
|
cookie_payload,
|
|
session_id=session_id,
|
|
)
|
|
except Exception:
|
|
continue
|
|
if self._payload.get("timezone"):
|
|
await self._call(
|
|
"Emulation.setTimezoneOverride",
|
|
{"timezoneId": self._payload["timezone"]},
|
|
session_id=session_id,
|
|
)
|
|
if self._payload.get("locale"):
|
|
await self._call(
|
|
"Emulation.setLocaleOverride",
|
|
{"locale": self._payload["locale"]},
|
|
session_id=session_id,
|
|
)
|
|
await self._call(
|
|
"Page.addScriptToEvaluateOnNewDocument",
|
|
{"source": _build_init_script(self._payload)},
|
|
session_id=session_id,
|
|
)
|
|
if not self._initial_navigated and target_info.get("url") in {"", "about:blank"}:
|
|
await self._call(
|
|
"Page.navigate",
|
|
{"url": self._start_url},
|
|
session_id=session_id,
|
|
)
|
|
self._initial_navigated = True
|
|
self._status_callback(
|
|
applied=self._initial_navigated,
|
|
reason="ok" if self._initial_navigated else "session_running",
|
|
attached_targets=self._attached_targets,
|
|
last_target_id=target_info.get("targetId"),
|
|
)
|
|
|
|
async def _call(
|
|
self,
|
|
method: str,
|
|
params: Optional[Dict[str, Any]] = None,
|
|
*,
|
|
session_id: Optional[str] = None,
|
|
) -> Dict[str, Any]:
|
|
self._next_id += 1
|
|
message_id = self._next_id
|
|
payload = {
|
|
"id": message_id,
|
|
"method": method,
|
|
"params": params or {},
|
|
}
|
|
if session_id:
|
|
payload["sessionId"] = session_id
|
|
future = asyncio.get_running_loop().create_future()
|
|
self._pending[message_id] = future
|
|
await self._websocket.send(json.dumps(payload))
|
|
return await future
|
|
|
|
|
|
def start_fingerprint_session(
|
|
port: int,
|
|
fingerprint: Optional[dict],
|
|
start_url: str,
|
|
timeout_seconds: float = 8.0,
|
|
) -> ChromiumFingerprintSession:
|
|
session = ChromiumFingerprintSession(
|
|
port=port,
|
|
fingerprint=fingerprint,
|
|
start_url=start_url,
|
|
timeout_seconds=timeout_seconds,
|
|
)
|
|
session.start()
|
|
return session
|
|
|
|
|
|
async def _wait_for_version(port: int, timeout_seconds: float) -> Dict[str, Any]:
|
|
deadline = time.time() + timeout_seconds
|
|
last_error = ""
|
|
while time.time() < deadline:
|
|
try:
|
|
payload = _fetch_json(f"http://127.0.0.1:{port}/json/version")
|
|
if isinstance(payload, dict) and payload.get("webSocketDebuggerUrl"):
|
|
return payload
|
|
except Exception as exc:
|
|
last_error = str(exc)
|
|
await asyncio.sleep(0.2)
|
|
raise RuntimeError(last_error or "timed out waiting for chromium devtools version")
|
|
|
|
|
|
def _fetch_json(url: str) -> Any:
|
|
request = urllib.request.Request(url, headers={"Connection": "close"})
|
|
with urllib.request.urlopen(request, timeout=2.0) as response:
|
|
return json.loads(response.read().decode("utf-8"))
|
|
|
|
|
|
def _build_injection_payload(fingerprint: dict) -> Optional[Dict[str, Any]]:
|
|
raw_payload = fingerprint.get("payload") or fingerprint.get("encryptedPayload")
|
|
if not raw_payload:
|
|
return None
|
|
parsed = json.loads(raw_payload) if isinstance(raw_payload, str) else raw_payload
|
|
raw = parsed.get("raw") if isinstance(parsed, dict) and isinstance(parsed.get("raw"), dict) else parsed
|
|
if not isinstance(raw, dict):
|
|
return None
|
|
|
|
navigator = raw.get("navigator") or {}
|
|
headers = raw.get("headers") or {}
|
|
screen = raw.get("screen") or {}
|
|
user_agent = _first_non_empty(
|
|
fingerprint.get("userAgent"),
|
|
navigator.get("userAgent"),
|
|
headers.get("User-Agent"),
|
|
)
|
|
if not user_agent:
|
|
raise ValueError("missing user agent")
|
|
|
|
locale = _first_non_empty(
|
|
fingerprint.get("locale"),
|
|
raw.get("locale"),
|
|
navigator.get("language"),
|
|
) or "en-US"
|
|
languages = navigator.get("languages")
|
|
if not isinstance(languages, list) or not languages:
|
|
languages = [locale]
|
|
timezone = _first_non_empty(
|
|
fingerprint.get("timezone"),
|
|
raw.get("timezone"),
|
|
raw.get("timezoneId"),
|
|
)
|
|
vendor = navigator.get("vendor")
|
|
hardware_concurrency = _safe_int(navigator.get("hardwareConcurrency"))
|
|
device_memory = _safe_number(navigator.get("deviceMemory"))
|
|
ua_data = navigator.get("userAgentData") or {}
|
|
metadata = {
|
|
"brands": _normalize_brand_list(ua_data.get("brands")),
|
|
"fullVersionList": _normalize_brand_list(ua_data.get("fullVersionList")),
|
|
"fullVersion": _first_non_empty(
|
|
ua_data.get("uaFullVersion"),
|
|
_extract_full_chrome_version(user_agent),
|
|
),
|
|
"platform": ua_data.get("platform") or "Windows",
|
|
"platformVersion": ua_data.get("platformVersion") or "10.0.0",
|
|
"architecture": ua_data.get("architecture") or "x86",
|
|
"bitness": ua_data.get("bitness") or "64",
|
|
"model": ua_data.get("model") or "",
|
|
"mobile": bool(ua_data.get("mobile", False)),
|
|
"wow64": bool(ua_data.get("wow64", False)),
|
|
}
|
|
if not metadata["brands"]:
|
|
major = metadata["fullVersion"].split(".", 1)[0]
|
|
metadata["brands"] = [
|
|
{"brand": "Google Chrome", "version": major},
|
|
{"brand": "Chromium", "version": major},
|
|
{"brand": "Not.A/Brand", "version": "8"},
|
|
]
|
|
if not metadata["fullVersionList"]:
|
|
full_version = metadata["fullVersion"]
|
|
metadata["fullVersionList"] = [
|
|
{"brand": "Google Chrome", "version": full_version},
|
|
{"brand": "Chromium", "version": full_version},
|
|
{"brand": "Not.A/Brand", "version": "8.0.0.0"},
|
|
]
|
|
|
|
normalized_headers = {
|
|
"Accept-Language": _first_non_empty(headers.get("Accept-Language"), locale),
|
|
"sec-ch-ua": headers.get("sec-ch-ua"),
|
|
"sec-ch-ua-mobile": headers.get("sec-ch-ua-mobile"),
|
|
"sec-ch-ua-platform": headers.get("sec-ch-ua-platform"),
|
|
}
|
|
cookies = _normalize_cookies(fingerprint.get("cookieConfig"), raw.get("cookieConfig"))
|
|
|
|
return {
|
|
"user_agent": user_agent,
|
|
"accept_language": normalized_headers["Accept-Language"],
|
|
"platform": metadata["platform"],
|
|
"locale": locale,
|
|
"languages": languages,
|
|
"timezone": timezone,
|
|
"vendor": vendor if isinstance(vendor, str) else "Google Inc.",
|
|
"hardware_concurrency": hardware_concurrency,
|
|
"device_memory": device_memory,
|
|
"screen": {
|
|
"width": _safe_int(screen.get("width")) or _safe_int(fingerprint.get("screenWidth")) or 1920,
|
|
"height": _safe_int(screen.get("height")) or _safe_int(fingerprint.get("screenHeight")) or 1080,
|
|
"availWidth": _safe_int(screen.get("availWidth")) or _safe_int(screen.get("width")) or 1920,
|
|
"availHeight": _safe_int(screen.get("availHeight")) or _safe_int(screen.get("height")) or 1080,
|
|
"colorDepth": _safe_int(screen.get("colorDepth")) or 24,
|
|
"pixelDepth": _safe_int(screen.get("pixelDepth")) or 24,
|
|
},
|
|
"user_agent_metadata": metadata,
|
|
"headers": normalized_headers,
|
|
"cookies": cookies,
|
|
}
|
|
|
|
|
|
def _build_init_script(payload: Dict[str, Any]) -> str:
|
|
script_payload = {
|
|
"userAgent": payload["user_agent"],
|
|
"language": payload["locale"],
|
|
"languages": payload["languages"],
|
|
"platform": "Win32",
|
|
"vendor": payload["vendor"],
|
|
"hardwareConcurrency": payload["hardware_concurrency"],
|
|
"deviceMemory": payload["device_memory"],
|
|
"screen": payload["screen"],
|
|
"userAgentData": payload["user_agent_metadata"],
|
|
}
|
|
return f"""
|
|
(() => {{
|
|
const fp = {json.dumps(script_payload, ensure_ascii=True)};
|
|
const defineValue = (target, key, value) => {{
|
|
Object.defineProperty(target, key, {{
|
|
configurable: true,
|
|
enumerable: true,
|
|
get: () => value,
|
|
}});
|
|
}};
|
|
const patchObject = (target, values) => {{
|
|
for (const [key, value] of Object.entries(values)) {{
|
|
if (value === undefined || value === null) {{
|
|
continue;
|
|
}}
|
|
defineValue(target, key, value);
|
|
}}
|
|
}};
|
|
patchObject(Navigator.prototype, {{
|
|
userAgent: fp.userAgent,
|
|
appVersion: fp.userAgent.replace(/^Mozilla\\//, ''),
|
|
language: fp.language,
|
|
languages: fp.languages,
|
|
platform: fp.platform,
|
|
vendor: fp.vendor,
|
|
hardwareConcurrency: fp.hardwareConcurrency,
|
|
deviceMemory: fp.deviceMemory,
|
|
}});
|
|
const uaData = {{
|
|
brands: fp.userAgentData.brands,
|
|
mobile: fp.userAgentData.mobile,
|
|
platform: fp.userAgentData.platform,
|
|
getHighEntropyValues: async (hints) => {{
|
|
const values = {{
|
|
architecture: fp.userAgentData.architecture,
|
|
bitness: fp.userAgentData.bitness,
|
|
brands: fp.userAgentData.brands,
|
|
fullVersionList: fp.userAgentData.fullVersionList,
|
|
mobile: fp.userAgentData.mobile,
|
|
model: fp.userAgentData.model,
|
|
platform: fp.userAgentData.platform,
|
|
platformVersion: fp.userAgentData.platformVersion,
|
|
uaFullVersion: fp.userAgentData.fullVersion,
|
|
wow64: fp.userAgentData.wow64,
|
|
}};
|
|
if (!Array.isArray(hints)) {{
|
|
return values;
|
|
}}
|
|
return hints.reduce((result, hint) => {{
|
|
if (hint in values) {{
|
|
result[hint] = values[hint];
|
|
}}
|
|
return result;
|
|
}}, {{
|
|
brands: values.brands,
|
|
mobile: values.mobile,
|
|
platform: values.platform,
|
|
}});
|
|
}},
|
|
toJSON: () => {{
|
|
return {{
|
|
brands: fp.userAgentData.brands,
|
|
mobile: fp.userAgentData.mobile,
|
|
platform: fp.userAgentData.platform,
|
|
}};
|
|
}},
|
|
}};
|
|
defineValue(Navigator.prototype, 'userAgentData', uaData);
|
|
patchObject(Screen.prototype, fp.screen);
|
|
}})();
|
|
""".strip()
|
|
|
|
|
|
def _normalize_brand_list(value: Any) -> list[dict]:
|
|
if not isinstance(value, list):
|
|
return []
|
|
items: list[dict] = []
|
|
for item in value:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
brand = item.get("brand")
|
|
version = item.get("version")
|
|
if isinstance(brand, str) and isinstance(version, str):
|
|
items.append({"brand": brand, "version": version})
|
|
return items
|
|
|
|
|
|
def _safe_int(value: Any) -> Optional[int]:
|
|
try:
|
|
if value is None or value == "":
|
|
return None
|
|
return int(value)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def _safe_number(value: Any) -> Optional[float | int]:
|
|
try:
|
|
if value is None or value == "":
|
|
return None
|
|
number = float(value)
|
|
return int(number) if number.is_integer() else number
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
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 _normalize_cookies(*values: Any) -> list[dict]:
|
|
raw_value = _first_non_empty(*values)
|
|
if not raw_value:
|
|
return []
|
|
try:
|
|
parsed = json.loads(raw_value) if isinstance(raw_value, str) else raw_value
|
|
except Exception:
|
|
return []
|
|
if not isinstance(parsed, list):
|
|
return []
|
|
cookies: list[dict] = []
|
|
for item in parsed:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
name = item.get("name")
|
|
value = item.get("value")
|
|
if not isinstance(name, str) or not isinstance(value, str):
|
|
continue
|
|
cookie: dict[str, Any] = {"name": name, "value": value}
|
|
if isinstance(item.get("url"), str) and item.get("url"):
|
|
cookie["url"] = item["url"]
|
|
if isinstance(item.get("domain"), str) and item.get("domain"):
|
|
cookie["domain"] = item["domain"]
|
|
if isinstance(item.get("path"), str) and item.get("path"):
|
|
cookie["path"] = item["path"]
|
|
if isinstance(item.get("httpOnly"), bool):
|
|
cookie["httpOnly"] = item["httpOnly"]
|
|
if isinstance(item.get("secure"), bool):
|
|
cookie["secure"] = item["secure"]
|
|
if isinstance(item.get("sameSite"), str) and item["sameSite"] in {"Strict", "Lax", "None"}:
|
|
cookie["sameSite"] = item["sameSite"]
|
|
expires = item.get("expires")
|
|
if isinstance(expires, (int, float)):
|
|
cookie["expires"] = expires
|
|
cookies.append(cookie)
|
|
return cookies
|
|
|
|
|
|
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
|