Initial commit

This commit is contained in:
xxk
2026-06-25 14:58:52 +08:00
commit 46b922bdc5
3773 changed files with 471371 additions and 0 deletions
@@ -0,0 +1,39 @@
import click
from browserforge.download import Download, Remove
class DownloadException(Exception):
"""Raises when the download fails."""
@click.group()
def cli() -> None:
pass
@cli.command(name='update')
@click.option('--headers', is_flag=True, help='Only update header definitions')
@click.option('--fingerprints', is_flag=True, help='Only update fingerprint definitions')
def update(headers=False, fingerprints=False):
"""
Fetches header and fingerprint definitions
"""
# if no options passed, mark both as True
if not headers ^ fingerprints:
headers = fingerprints = True
Download(headers=headers, fingerprints=fingerprints)
@cli.command(name='remove')
def remove():
"""
Remove all downloaded files
"""
Remove()
click.secho('Removed all files!', fg='bright_yellow')
if __name__ == '__main__':
cli()
@@ -0,0 +1,296 @@
import random
import zipfile
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union
try:
import orjson as json
except ImportError:
import json
T = TypeVar('T')
Map = Union[list, tuple]
class BayesianNode:
"""
Implementation of a single node in a bayesian network allowing sampling from its conditional distribution
"""
def __init__(self, node_definition: Dict[str, Any]):
self.node_definition = node_definition
def get_probabilities_given_known_values(
self, parent_values: Dict[str, Any]
) -> Dict[Any, float]:
"""
Extracts unconditional probabilities of node values given the values of the parent nodes
"""
probabilities = self.node_definition['conditionalProbabilities']
for parent_name in self.parent_names:
parent_value = parent_values.get(parent_name)
if parent_value in probabilities.get('deeper', {}):
probabilities = probabilities['deeper'][parent_value]
else:
probabilities = probabilities.get('skip', {})
return probabilities
def sample_random_value_from_possibilities(
self, possible_values: List[str], probabilities: Dict[str, float]
) -> Any:
"""
Randomly samples from the given values using the given probabilities
"""
# Python natively supports weighted random sampling in random.choices,
# but this method is much faster
anchor = random.random()
cumulative_probability = 0.0
for possible_value in possible_values:
cumulative_probability += probabilities[possible_value]
if cumulative_probability > anchor:
return possible_value
# Default to first item
return possible_values[0]
def sample(self, parent_values: Dict[str, Any]) -> Any:
"""
Randomly samples from the conditional distribution of this node given values of parents
"""
probabilities = self.get_probabilities_given_known_values(parent_values)
return self.sample_random_value_from_possibilities(
list(probabilities.keys()), probabilities
)
def sample_according_to_restrictions(
self,
parent_values: Dict[str, Any],
value_possibilities: Iterable[str],
banned_values: List[str],
) -> Optional[str]:
"""
Randomly samples from the conditional distribution of this node given restrictions on the possible values and the values of the parents.
"""
probabilities = self.get_probabilities_given_known_values(parent_values)
valid_values = [
value
for value in value_possibilities
if value not in banned_values and value in probabilities
]
if valid_values:
return self.sample_random_value_from_possibilities(valid_values, probabilities)
else:
return None # Equivalent to `false` in TypeScript
@property
def name(self) -> str:
return self.node_definition['name']
@property
def parent_names(self) -> List[str]:
return self.node_definition.get('parentNames', [])
@property
def possible_values(self) -> List[str]:
return self.node_definition.get('possibleValues', [])
class BayesianNetwork:
"""
Implementation of a bayesian network capable of randomly sampling from its distribution
"""
def __init__(self, path: Path) -> None:
network_definition = extract_json(path)
self.nodes_in_sampling_order = [
BayesianNode(node_def) for node_def in network_definition['nodes']
]
self.nodes_by_name = {node.name: node for node in self.nodes_in_sampling_order}
def generate_sample(self, input_values: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""
Randomly samples from the distribution represented by the bayesian network.
"""
if input_values is None:
input_values = {}
sample = input_values.copy()
for node in self.nodes_in_sampling_order:
if node.name not in sample:
sample[node.name] = node.sample(sample)
return sample
def generate_consistent_sample_when_possible(
self, value_possibilities: Dict[str, Iterable[str]]
) -> Optional[Dict[str, Any]]:
"""
Randomly samples values from the distribution represented by the bayesian network,
making sure the sample is consistent with the provided restrictions on value possibilities.
Returns None if no such sample can be generated.
"""
return self.recursively_generate_consistent_sample_when_possible({}, value_possibilities, 0)
def recursively_generate_consistent_sample_when_possible(
self,
sample_so_far: Dict[str, Any],
value_possibilities: Dict[str, Iterable[str]],
depth: int,
) -> Optional[Dict[str, Any]]:
"""
Recursively generates a random sample consistent with the given restrictions on possible values.
"""
if depth == len(self.nodes_in_sampling_order):
return sample_so_far
node = self.nodes_in_sampling_order[depth]
banned_values: List[str] = []
sample_value = None
while True:
sample_value = node.sample_according_to_restrictions(
sample_so_far,
value_possibilities.get(node.name, node.possible_values),
banned_values,
)
if sample_value is None:
break
sample_so_far[node.name] = sample_value
next_sample = self.recursively_generate_consistent_sample_when_possible(
sample_so_far, value_possibilities, depth + 1
)
if next_sample is not None:
return next_sample
banned_values.append(sample_value)
del sample_so_far[node.name]
return None
def array_intersection(a: Sequence[T], b: Sequence[T]) -> List[T]:
"""
Performs a set "intersection" on the given (flat) arrays
"""
set_b = set(b)
return [x for x in a if x in set_b]
def array_zip(a: List[Tuple[T, ...]], b: List[Tuple[T, ...]]) -> List[Tuple[T, ...]]:
"""
Combines two arrays into a single array using the set union
Args:
a: First array to be combined.
b: Second array to be combined.
Returns:
Zipped (multi-dimensional) array.
"""
return [tuple(set(x).union(y)) for x, y in zip(a, b)]
def undeeper(obj: Dict[str, Any]) -> Dict[str, Any]:
"""
Removes the "deeper/skip" structures from the conditional probability table
"""
if not isinstance(obj, dict):
return obj
result: Dict[str, Any] = {}
for key, value in obj.items():
if key == 'skip':
continue
if key == 'deeper':
result.update(undeeper(value))
else:
result[key] = undeeper(value)
return result
def filter_by_last_level_keys(tree: Dict[str, Any], valid_keys: Map) -> List[Tuple[str, ...]]:
r"""
Performs DFS on the Tree and returns values of the nodes on the paths that end with the given keys
(stored by levels - first level is the root)
```
1
/ \
2 3
/ \ / \
4 5 6 7
```
filter_by_last_level_keys(tree, ['4', '7']) => [[1], [2,3]]
"""
out: List[Tuple[str, ...]] = []
def recurse(t: Dict[str, Any], vk: Union[Tuple[str, ...], List[str]], acc: List[str]) -> None:
for key in t.keys():
if not isinstance(t[key], dict) or t[key] is None:
if key in vk:
nonlocal out
out = (
[(x,) for x in acc]
if len(out) == 0
else array_zip(out, [(x,) for x in acc])
)
continue
else:
recurse(t[key], vk, acc + [key])
recurse(tree, valid_keys, [])
return out
def get_possible_values(
network: 'BayesianNetwork', possible_values: Dict[str, Union[Tuple[str, ...], List[str]]]
) -> Dict[str, Sequence[str]]:
"""
Given a `generative-bayesian-network` instance and a set of user constraints, returns an extended
set of constraints **induced** by the original constraints and network structure
"""
sets = []
# For every pre-specified node, compute the "closure" for values of the other nodes
for key, value in possible_values.items():
if not isinstance(value, (list, tuple)):
continue
if len(value) == 0:
raise ValueError(
"The current constraints are too restrictive. No possible values can be found for the given constraints."
)
node = network.nodes_by_name[key]
tree = undeeper(node.node_definition['conditionalProbabilities'])
zipped_values = filter_by_last_level_keys(tree, value)
sets.append({**dict(zip(node.parent_names, zipped_values)), key: value})
# Compute the intersection of all the possible values for each node
result: Dict[str, Sequence[str]] = {}
for set_dict in sets:
for key in set_dict.keys():
if key in result:
intersected_values = array_intersection(set_dict[key], result[key])
if not intersected_values:
raise ValueError(
"The current constraints are too restrictive. No possible values can be found for the given constraints."
)
result[key] = intersected_values
else:
result[key] = set_dict[key]
return result
def extract_json(path: Path) -> dict:
"""
Unzips a zip file if the path points to a zip file, otherwise directly loads a JSON file.
Parameters:
path: The path to the zip file or JSON file.
Returns:
A dictionary representing the JSON content.
"""
if path.suffix != '.zip':
# Directly load the JSON file
with open(path, 'rb') as file:
return json.loads(file.read())
# Unzip the file and load the JSON content
with zipfile.ZipFile(path, 'r') as zf:
# Find the first JSON file in zip
try:
filename = next(file for file in zf.namelist() if file.endswith('.json'))
except StopIteration:
return {} # Broken
with zf.open(filename) as f:
# Assuming only one JSON file is needed
return json.loads(f.read())
@@ -0,0 +1,147 @@
import shutil
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, Iterator
import click
"""
Downloads the required model definitions
"""
ROOT_DIR: Path = Path(__file__).parent
"""Constants for headers and fingerprints data"""
DATA_DIRS: Dict[str, Path] = {
"headers": ROOT_DIR / "headers/data",
"fingerprints": ROOT_DIR / "fingerprints/data",
}
DATA_FILES: Dict[str, Dict[str, str]] = {
"headers": {
"browser-helper-file.json": "browser-helper-file.json",
"header-network.zip": "header-network-definition.zip",
"headers-order.json": "headers-order.json",
"input-network.zip": "input-network-definition.zip",
},
"fingerprints": {
"fingerprint-network.zip": "fingerprint-network-definition.zip",
},
}
REMOTE_PATHS: Dict[str, str] = {
"headers": "https://github.com/apify/fingerprint-suite/raw/master/packages/header-generator/src/data_files",
"fingerprints": "https://github.com/apify/fingerprint-suite/raw/master/packages/fingerprint-generator/src/data_files",
}
class DownloadException(Exception):
"""Raises when the download fails."""
class DataDownloader:
"""
Download and extract data files for both headers and fingerprints.
"""
def __init__(self, **kwargs: bool) -> None:
self.options = _enabled_flags(kwargs)
def download_file(self, url: str, path: str) -> None:
"""
Download a file from the specified URL and save it to the given path.
"""
with urllib.request.urlopen(url) as resp: # nosec
if resp.status != 200:
raise DownloadException(f"Download failed with status code: {resp.status}")
with open(path, "wb") as f:
shutil.copyfileobj(resp, f)
def download(self) -> None:
"""
Download and extract data files for both headers and fingerprints.
"""
futures = {}
with ThreadPoolExecutor(10) as executor:
for data_type in self.options:
for local_name, remote_name in DATA_FILES[data_type].items():
url = f"{REMOTE_PATHS[data_type]}/{remote_name}"
path = str(DATA_DIRS[data_type] / local_name)
future = executor.submit(self.download_file, url, path)
futures[future] = local_name
for f in as_completed(futures):
try:
future.result()
click.secho(f"{futures[f]:<30}OK!", fg="green")
except Exception as e:
click.secho(f"Error downloading {local_name}: {e}", fg="red")
def _enabled_flags(flags: Dict[str, bool]) -> Iterator[str]:
"""
Returns a list of enabled flags based on a given dictionary
"""
for flag, enabled in flags.items():
if enabled:
yield flag
def _get_all_paths(**flags: bool) -> Iterator[Path]:
"""
Yields all the paths to the downloaded data files
"""
for data_type in _enabled_flags(flags):
data_path = DATA_DIRS[data_type]
for local_name, _ in DATA_FILES[data_type].items():
yield data_path / local_name
"""
Public download functions
"""
def Download(headers=False, fingerprints=False) -> None:
"""
Download the required data files
"""
# Announce that files are being downloaded
click.secho('Downloading model definition files...', fg='bright_yellow')
try:
DataDownloader(headers=headers, fingerprints=fingerprints).download()
except KeyboardInterrupt:
print("Download interrupted.")
Remove()
exit()
def DownloadIfNotExists(**flags: bool) -> None:
"""
Download the required data files if they don't exist
"""
if not IsDownloaded(**flags):
Download(**flags)
def IsDownloaded(**flags: bool) -> bool:
"""
Check if the required data files are already downloaded and not older than a month.
Returns True if all the requested data files are present and not older than a month, False otherwise.
"""
for path in _get_all_paths(**flags):
if not path.exists():
return False
# Check if the file is older than a month
file_creation_time = datetime.fromtimestamp(path.stat().st_ctime)
one_month_ago = datetime.now() - timedelta(weeks=5)
return file_creation_time >= one_month_ago
def Remove() -> None:
"""
Deletes all downloaded data files
"""
for path in _get_all_paths(headers=True, fingerprints=True):
path.unlink(missing_ok=True)
@@ -0,0 +1,24 @@
from browserforge.download import DownloadIfNotExists
DownloadIfNotExists(fingerprints=True, headers=True)
from browserforge.headers import Browser
from .generator import (
Fingerprint,
FingerprintGenerator,
NavigatorFingerprint,
Screen,
ScreenFingerprint,
VideoCard,
)
__all__ = [
"Browser",
"Fingerprint",
"FingerprintGenerator",
"NavigatorFingerprint",
"Screen",
"ScreenFingerprint",
"VideoCard",
]
@@ -0,0 +1,369 @@
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Dict, List, Optional
from browserforge.bayesian_network import BayesianNetwork, get_possible_values
from browserforge.headers import HeaderGenerator
from browserforge.headers.utils import get_user_agent
try:
import orjson as json
USE_ORJSON = True
except ImportError:
import json
USE_ORJSON = False
DATA_DIR: Path = Path(__file__).parent / 'data'
@dataclass
class ScreenFingerprint:
availHeight: int
availWidth: int
availTop: int
availLeft: int
colorDepth: int
height: int
pixelDepth: int
width: int
devicePixelRatio: float
pageXOffset: int
pageYOffset: int
innerHeight: int
outerHeight: int
outerWidth: int
innerWidth: int
screenX: int
clientWidth: int
clientHeight: int
hasHDR: bool
@dataclass
class NavigatorFingerprint:
userAgent: str
userAgentData: Dict[str, str]
doNotTrack: Optional[str]
appCodeName: str
appName: str
appVersion: str
oscpu: str
webdriver: str
language: str
languages: List[str]
platform: str
deviceMemory: Optional[int]
hardwareConcurrency: int
product: str
productSub: str
vendor: str
vendorSub: str
maxTouchPoints: int
extraProperties: Dict[str, str]
@dataclass
class VideoCard:
renderer: str
vendor: str
@dataclass
class Fingerprint:
"""Output data of the fingerprint generator"""
screen: ScreenFingerprint
navigator: NavigatorFingerprint
headers: Dict[str, str]
videoCodecs: Dict[str, str]
audioCodecs: Dict[str, str]
pluginsData: Dict[str, str]
battery: Optional[Dict[str, str]]
videoCard: Optional[VideoCard]
multimediaDevices: List[str]
fonts: List[str]
mockWebRTC: Optional[bool]
slim: Optional[bool]
def dumps(self) -> str:
"""
Dumps the dataclass as a JSON string.
"""
if USE_ORJSON:
return json.dumps(self).decode()
# Built-in `json` does not take dataclass objects
# Instead, convert to a dict first
return json.dumps(asdict(self))
@dataclass
class Screen:
"""Constrains the screen dimensions of the generated fingerprint"""
min_width: Optional[int] = None
max_width: Optional[int] = None
min_height: Optional[int] = None
max_height: Optional[int] = None
def __post_init__(self):
if (
None not in (self.min_width, self.max_width)
and self.min_width > self.max_width
or None not in (self.min_height, self.max_height)
and self.min_height > self.max_height
):
raise ValueError(
"Invalid screen constraints: min values cannot be greater than max values"
)
def is_set(self) -> bool:
"""
Returns true if any constraints were set
"""
return any(value is not None for value in self.__dict__.values())
class FingerprintGenerator:
"""Generates realistic browser fingerprints"""
fingerprint_generator_network = BayesianNetwork(DATA_DIR / "fingerprint-network.zip")
def __init__(
self,
screen: Optional[Screen] = None,
strict: bool = False,
mock_webrtc: bool = False,
slim: bool = False,
**header_kwargs,
):
"""
Initializes the FingerprintGenerator with the given options.
Parameters:
screen (Screen, optional): Screen constraints for the generated fingerprint.
strict (bool, optional): Whether to raise an exception if the constraints are too strict. Default is False.
mock_webrtc (bool, optional): Whether to mock WebRTC when injecting the fingerprint. Default is False.
slim (bool, optional): Disables performance-heavy evasions when injecting the fingerprint. Default is False.
**header_kwargs: Header generation options for HeaderGenerator
"""
self.header_generator: HeaderGenerator = HeaderGenerator(**header_kwargs)
# Set default options
self.screen: Optional[Screen] = screen
self.strict: bool = strict
self.mock_webrtc: bool = mock_webrtc
self.slim: bool = slim
def generate(
self,
*,
screen: Optional[Screen] = None,
strict: Optional[bool] = None,
mock_webrtc: Optional[bool] = None,
slim: Optional[bool] = None,
**header_kwargs,
) -> Fingerprint:
"""
Generates a fingerprint and a matching set of ordered headers using a combination of the default options
specified in the constructor and their possible overrides provided here.
Parameters:
screen (Screen, optional): Screen constraints for the generated fingerprint.
strict (bool, optional): Whether to raise an exception if the constraints are too strict.
mock_webrtc (bool, optional): Whether to mock WebRTC when injecting the fingerprint. Default is False.
slim (bool, optional): Disables performance-heavy evasions when injecting the fingerprint. Default is False.
**header_kwargs: Additional header generation options for HeaderGenerator.generate
"""
filtered_values: Dict[str, str] = {}
if header_kwargs is None:
header_kwargs = {}
# merge new options with old
screen = _first(screen, self.screen)
strict = _first(strict, self.strict)
partial_csp = self.partial_csp(
strict=strict, screen=screen, filtered_values=filtered_values
)
# Generate headers consistent with the inputs to get input-compatible user-agent
# and accept-language headers needed later
if partial_csp:
header_kwargs['user_agent'] = partial_csp['userAgent']
headers = self.header_generator.generate(**header_kwargs)
# Extract generated User-Agent
user_agent = get_user_agent(headers)
if user_agent is None:
raise ValueError("Failed to find User-Agent in generated response")
# Generate fingerprint consistent with the generated user agent
while True:
fingerprint: Optional[Dict] = (
self.fingerprint_generator_network.generate_consistent_sample_when_possible(
{**filtered_values, 'userAgent': (user_agent,)}
)
)
if fingerprint is not None:
break
# Raise
if strict:
raise ValueError(
'Cannot generate headers. User-Agent may be invalid, or screen constraints are too restrictive.'
)
# If no fingerprint was generated, relax the filtered values.
# This seems to be an issue with some Mac and Linux systems
filtered_values = {}
# Delete any missing attributes and unpack any object/array-like attributes
# that have been packed together to make the underlying network simpler
for attribute in list(fingerprint.keys()):
if fingerprint[attribute] == '*MISSING_VALUE*':
fingerprint[attribute] = None
if isinstance(fingerprint[attribute], str) and fingerprint[attribute].startswith(
'*STRINGIFIED*'
):
fingerprint[attribute] = json.loads(fingerprint[attribute][len('*STRINGIFIED*') :])
# Manually add the set of accepted languages required by the input
accept_language_header_value = headers.get('Accept-Language', '')
accepted_languages = [
locale.split(';', 1)[0] for locale in accept_language_header_value.split(',')
]
fingerprint['languages'] = accepted_languages
return self._transform_fingerprint(
fingerprint,
headers,
_first(mock_webrtc, self.mock_webrtc),
_first(slim, self.slim),
)
def partial_csp(
self, strict: Optional[bool], screen: Optional[Screen], filtered_values: Dict
) -> Optional[Dict]:
"""
Generates partial content security policy (CSP) based on the provided options and filtered values.
Parameters:
strict (Optional[bool): Whether to raise an exception if the constraints are too strict.
screen (Optional[Screen]): Screen for generating the partial CSP.
filtered_values (Dict): Filtered values used for generating the partial CSP.
Returns:
Dict: Partial CSP values.
"""
# if extensive constraints need to be used
if not (screen and screen.is_set()):
return None
filtered_values['screen'] = [
screen_string
for screen_string in self.fingerprint_generator_network.nodes_by_name[
'screen'
].possible_values
if self._is_screen_within_constraints(screen_string, screen)
]
try:
return get_possible_values(self.fingerprint_generator_network, filtered_values)
except Exception as e:
if strict:
raise e
del filtered_values['screen']
return None
@staticmethod
def _is_screen_within_constraints(screen_string: str, screen_options: Screen) -> bool:
"""
Checks if the given screen dimensions are within the specified constraints.
Parameters:
screen_string (str): Stringified screen dimensions.
screen_options (Screen): Screen constraint options.
Returns:
bool: True if the screen dimensions are within the constraints, False otherwise.
"""
try:
screen = json.loads(screen_string[len('*STRINGIFIED*') :])
return (
# Ensure that the screen width/height are greater than the minimum constraints
# Default missing values to -1 to ensure they are excluded
screen.get('width', -1) >= (screen_options.min_width or 0)
and screen.get('height', -1) >= (screen_options.min_height or 0)
# Ensure that the screen width/height are less than the maximum constraints
and screen.get('width', 0) <= (screen_options.max_width or 1e5)
and screen.get('height', 0) <= (screen_options.max_height or 1e5)
)
except (ValueError, TypeError):
return False
@staticmethod
def _transform_fingerprint(
fingerprint: Dict, headers: Dict, mock_webrtc: bool, slim: bool
) -> Fingerprint:
"""
Transforms fingerprint into a final dataclass instance.
Parameters:
fingerprint (Dict): Fingerprint to be transformed.
headers (Dict): Generated headers.
mock_webrtc (bool): Whether to mock WebRTC when injecting the fingerprint.
slim (bool): Disables performance-heavy evasions when injecting the fingerprint.
Returns:
Fingerprint: Transformed fingerprint as a Fingerprint dataclass instance.
"""
navigator_kwargs = {
k: fingerprint[k]
for k in (
'userAgent',
'userAgentData',
'doNotTrack',
'appCodeName',
'appName',
'appVersion',
'oscpu',
'webdriver',
'platform',
'deviceMemory',
'product',
'productSub',
'vendor',
'vendorSub',
'extraProperties',
'hardwareConcurrency',
'languages',
)
}
# Always take the first element for 'language'
navigator_kwargs['language'] = navigator_kwargs['languages'][0]
navigator_kwargs['maxTouchPoints'] = fingerprint.get('maxTouchPoints', 0)
return Fingerprint(
screen=ScreenFingerprint(**fingerprint['screen']),
navigator=NavigatorFingerprint(**navigator_kwargs),
headers=headers,
videoCodecs=fingerprint['videoCodecs'],
audioCodecs=fingerprint['audioCodecs'],
pluginsData=fingerprint['pluginsData'],
battery=fingerprint['battery'],
videoCard=(
VideoCard(**fingerprint['videoCard']) if fingerprint.get('videoCard') else None
),
multimediaDevices=fingerprint['multimediaDevices'],
fonts=fingerprint['fonts'],
mockWebRTC=mock_webrtc,
slim=slim,
)
def _first(*values):
"""
Simple function that returns the first non-None value passed
"""
return next((v for v in values if v is not None), None)
@@ -0,0 +1,10 @@
from browserforge.download import DownloadIfNotExists
DownloadIfNotExists(headers=True)
from .generator import Browser, HeaderGenerator
__all__ = [
"Browser",
"HeaderGenerator",
]
@@ -0,0 +1 @@
["chrome/147.0.0.0|2","edge/147.0.0.0|2","safari/26.4|2","chrome/147.0.0.0|1","safari/26.3|2","chrome/146.0.0.0|2","firefox/150.0|2","safari/26.2|2","safari/18.5|2","safari/26.0.1|2","firefox/135.0|2","chrome/148.0.0.0|2","chrome/142.0.0.0|2","safari/18.3|2","chrome/144.0.0.0|2","safari/18.2|2","safari/26.3.1|2","safari/18.7|2","edge/129.0.0.0|2","safari/18.7.4|2","safari/18.1|2","safari/18.6|2","safari/18.7.5|2","chrome/145.0.0.0|2","chrome/127.0.0.0|2","safari/16.6|2","chrome/141.0.0.0|2","edge/147.0.0.0|1","chrome/121.0.0.0|2","chrome/143.0.0.0|2","chrome/128.0.0.0|2","safari/17.2.1|2","safari/26.5|2","chrome/116.0.0.0|2","chrome/138.0.0.0|2","safari/26.1|2","safari/17.6|2","firefox/151.0|2","chrome/130.0.0.0|2","chrome/115.0.0.0|2","edge/146.0.0.0|2","chrome/149.0.0.0|2","chrome/140.0.0.0|2","safari/16.4|2","safari/18.1.1|2","edge/144.0.0.0|2","edge/128.0.0.0|2","chrome/109.0.0.0|2","chrome/139.0.0.0|2","edge/143.0.0.0|2","edge/146.0.0.0|1","safari/26.4|1","safari/17.4|2","chrome/143.0.0.0|1","chrome/131.0.0.0|2","safari/18.4|2","safari/18.0.1|2","chrome/134.0.0.0|2","safari/16.5.2|2","safari/26.4.2|2","chrome/120.0.0.0|2","chrome/137.0.0.0|2","safari/26.0|2","safari/16.6.1|2","firefox/147.0|2","edge/145.0.0.0|2","chrome/135.0.0.0|2","safari/18.5|1","safari/17.5|2","chrome/45.0.8909.1591|2","chrome/145.0.0.0|1","chrome/91.0.4450.0|2","safari/17.7|2","chrome/125.0.0.0|2","chrome/126.0.0.0|2","chrome/113.0.0.0|2","chrome/101.0.4951.54|2","chrome/108.0.0.0|2","edge/148.0.0.0|2","chrome/142.0.0.0|1","chrome/147.0.7727.56|2","safari/17.4.1|2","edge/123.0.0.0|2","chrome/136.0.0.0|2","safari/16.6.2|2","chrome/119.0.0.0|2","chrome/142.0.7444.138|2","safari/18.3.1|2","edge/138.0.0.0|2","chrome/146.0.0.0|1","firefox/136.0|2","chrome/114.0.0.0|2","safari/16.5|2","chrome/138.0.7204.235|2","chrome/59.0.9273.1293|2","chrome/144.0.7559.95|2","safari/17.3|2","edge/142.0.0.0|2","safari/18.7.3|2","chrome/138.0.7204.63|2","firefox/149.0|2","safari/17.8|2","safari/15.6.8|2","safari/17.3.1|2","chrome/147.0.7727.111|2","chrome/124.0.0.0|2","chrome/122.0.0.0|2","safari/15.6.7|2","chrome/107.0.0.0|2","firefox/146.0|2","edge/122.0.0.0|2","safari/16.2|2","chrome/103.0.0.0|2","chrome/90.0.4430.212|2","safari/17.1.2|2","chrome/132.0.0.0|2","safari/18.0|2","chrome/130.0.6723.73|2","chrome/133.0.0.0|2","firefox/142.0|2","safari/17.0|2","safari/17.1|2","chrome/96.0.4664.110|1","safari/18.7.7|2","chrome/147.0.7727.116|1","safari/18.7.2|2","safari/15.6.1|2","chrome/116.0.0.0|1","safari/17.2|2","safari/18.4.1|2","edge/135.0.3179.54|2","safari/26.4.1|2","chrome/106.0.0.0|2","safari/16.1|2","chrome/91.0.4472.124|2","chrome/132.0.6788.76|2","safari/16.3|2"]
@@ -0,0 +1,164 @@
{
"safari": [
"Referer",
"Origin",
"Content-Type",
"Accept",
"Upgrade-Insecure-Requests",
"User-Agent",
"Content-Length",
"Accept-Encoding",
"Accept-Language",
"Connection",
"Host",
"Cookie",
"Sec-Fetch-Dest",
"Sec-Fetch-Mode",
"Sec-Fetch-Site",
":method",
":scheme",
":authority",
":path",
"referer",
"origin",
"content-type",
"accept",
"user-agent",
"content-length",
"accept-encoding",
"accept-language",
"cookie",
"sec-fetch-dest",
"sec-fetch-mode",
"sec-fetch-site"
],
"chrome": [
"Host",
"Connection",
"Content-Length",
"Cache-Control",
"sec-ch-ua",
"sec-ch-ua-mobile",
"sec-ch-ua-platform",
"Origin",
"Content-Type",
"Upgrade-Insecure-Requests",
"User-Agent",
"Accept",
"Sec-Fetch-Site",
"Sec-Fetch-Mode",
"Sec-Fetch-User",
"Sec-Fetch-Dest",
"Referer",
"Accept-Encoding",
"Accept-Language",
"Cookie",
":method",
":authority",
":scheme",
":path",
"content-length",
"cache-control",
"sec-ch-ua",
"sec-ch-ua-mobile",
"sec-ch-ua-platform",
"origin",
"content-type",
"upgrade-insecure-requests",
"user-agent",
"accept",
"sec-fetch-site",
"sec-fetch-mode",
"sec-fetch-user",
"sec-fetch-dest",
"referer",
"accept-encoding",
"accept-language",
"cookie",
"priority"
],
"firefox": [
"Host",
"User-Agent",
"Accept",
"Accept-Language",
"Accept-Encoding",
"Content-Type",
"Content-Length",
"Origin",
"Connection",
"Referer",
"Cookie",
"Upgrade-Insecure-Requests",
"Sec-Fetch-Dest",
"Sec-Fetch-Mode",
"Sec-Fetch-Site",
"Sec-Fetch-User",
"Priority",
":method",
":path",
":authority",
":scheme",
"user-agent",
"accept",
"accept-language",
"accept-encoding",
"content-type",
"content-length",
"origin",
"referer",
"cookie",
"upgrade-insecure-requests",
"sec-fetch-dest",
"sec-fetch-mode",
"sec-fetch-site",
"sec-fetch-user",
"priority",
"te"
],
"edge": [
"Host",
"Connection",
"Content-Length",
"Cache-Control",
"sec-ch-ua",
"sec-ch-ua-mobile",
"sec-ch-ua-platform",
"Origin",
"Content-Type",
"Upgrade-Insecure-Requests",
"User-Agent",
"Accept",
"Sec-Fetch-Site",
"Sec-Fetch-Mode",
"Sec-Fetch-User",
"Sec-Fetch-Dest",
"Referer",
"Accept-Encoding",
"Accept-Language",
"Cookie",
":method",
":authority",
":scheme",
":path",
"content-length",
"cache-control",
"sec-ch-ua",
"sec-ch-ua-mobile",
"sec-ch-ua-platform",
"origin",
"content-type",
"upgrade-insecure-requests",
"user-agent",
"accept",
"sec-fetch-site",
"sec-fetch-mode",
"sec-fetch-user",
"sec-fetch-dest",
"referer",
"accept-encoding",
"accept-language",
"cookie",
"priority"
]
}
@@ -0,0 +1,551 @@
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple, Union
from browserforge.bayesian_network import BayesianNetwork, get_possible_values
from .utils import get_browser, get_user_agent, pascalize_headers, tuplify
try:
import orjson as json
except ImportError:
import json
try:
from typing import TypeAlias # novm
except ImportError:
from typing_extensions import TypeAlias # <3.10
"""Constants"""
SUPPORTED_BROWSERS = ('chrome', 'firefox', 'safari', 'edge')
SUPPORTED_OPERATING_SYSTEMS = ('windows', 'macos', 'linux', 'android', 'ios')
SUPPORTED_DEVICES = ('desktop', 'mobile')
SUPPORTED_HTTP_VERSIONS = ('1', '2')
MISSING_VALUE_DATASET_TOKEN = '*MISSING_VALUE*'
HTTP1_SEC_FETCH_ATTRIBUTES = {
'Sec-Fetch-Mode': 'same-site',
'Sec-Fetch-Dest': 'navigate',
'Sec-Fetch-Site': '?1',
'Sec-Fetch-User': 'document',
}
HTTP2_SEC_FETCH_ATTRIBUTES = {
'sec-fetch-mode': 'same-site',
'sec-fetch-dest': 'navigate',
'sec-fetch-site': '?1',
'sec-fetch-user': 'document',
}
DATA_DIR: Path = Path(__file__).parent / 'data'
ListOrString: TypeAlias = Union[Tuple[str, ...], List[str], str]
@dataclass
class Browser:
"""Represents a browser specification with name, min/max version, and HTTP version"""
name: str
min_version: Optional[int] = None
max_version: Optional[int] = None
http_version: Union[str, int] = '2'
def __post_init__(self):
# Convert http_version to
if isinstance(self.http_version, int):
self.http_version = str(self.http_version)
# Confirm min_version < max_version
if (
isinstance(self.min_version, int)
and isinstance(self.max_version, int)
and self.min_version > self.max_version
):
raise ValueError(
f'Browser min version constraint ({self.min_version}) cannot exceed max version ({self.max_version})'
)
@dataclass
class HttpBrowserObject:
"""Represents an HTTP browser object with name, version, complete string, and HTTP version"""
name: Optional[str]
version: Tuple[int, ...]
complete_string: str
http_version: str
@property
def is_http2(self):
return self.http_version == '2'
class HeaderGenerator:
"""Generates HTTP headers based on a set of constraints"""
relaxation_order: Tuple[str, ...] = ('locales', 'devices', 'operatingSystems', 'browsers')
# Initialize networks
input_generator_network = BayesianNetwork(DATA_DIR / "input-network.zip")
header_generator_network = BayesianNetwork(DATA_DIR / "header-network.zip")
def __init__(
self,
browser: Union[ListOrString, Iterable[Browser]] = SUPPORTED_BROWSERS,
os: ListOrString = SUPPORTED_OPERATING_SYSTEMS,
device: ListOrString = SUPPORTED_DEVICES,
locale: ListOrString = 'en-US',
http_version: Literal[1, 2] = 2,
strict: bool = False,
):
"""
Initializes the HeaderGenerator with the given options.
Parameters:
browser (Union[ListOrString, Iterable[Browser]], optional): Browser(s) or Browser object(s).
os (ListOrString, optional): Operating system(s) to generate headers for.
device (ListOrString, optional): Device(s) to generate the headers for.
locale (ListOrString, optional): List of at most 10 languages for the Accept-Language header. Default is 'en-US'.
http_version (Literal[1, 2], optional): Http version to be used to generate headers. Defaults to 2.
strict (bool, optional): Throws an error if it cannot generate headers based on the input. Defaults to False.
"""
http_ver: str = str(http_version)
self.options = {
'browsers': self._prepare_browsers_config(tuplify(browser), http_ver),
'os': tuplify(os),
'devices': tuplify(device),
'locales': tuplify(locale),
'http_version': http_ver,
'strict': strict,
}
# Loader orders
self.unique_browsers = self._load_unique_browsers()
self.headers_order = self._load_headers_order()
def generate(
self,
*,
browser: Optional[Iterable[Union[str, Browser]]] = None,
os: Optional[ListOrString] = None,
device: Optional[ListOrString] = None,
locale: Optional[ListOrString] = None,
http_version: Optional[Literal[1, 2]] = None,
user_agent: Optional[ListOrString] = None,
strict: Optional[bool] = None,
request_dependent_headers: Optional[Dict[str, str]] = None,
):
"""
Generates headers using the default options and their possible overrides.
Parameters:
browser (Optional[Iterable[Union[str, Browser]]], optional): Browser(s) to generate the headers for.
os (Optional[ListOrString], optional): Operating system(s) to generate the headers for.
device (Optional[ListOrString], optional): Device(s) to generate the headers for.
locale (Optional[ListOrString], optional): Language(s) to include in the Accept-Language header.
http_version (Optional[Literal[1, 2]], optional): HTTP version to be used to generate headers.
user_agent (Optional[ListOrString], optional): User-Agent(s) to use.
request_dependent_headers (Optional[Dict[str, str]], optional): Known values of request-dependent headers.
strict (Optional[bool], optional): If true, throws an error if it cannot generate headers based on the input.
"""
options = {
'browsers': tuplify(browser),
'os': tuplify(os),
'devices': tuplify(device),
'locales': tuplify(locale),
'http_version': str(http_version) if http_version else None,
'strict': strict,
'user_agent': tuplify(user_agent),
'request_dependent_headers': request_dependent_headers,
}
generated: Dict[str, str] = self._get_headers(
**{k: v for k, v in options.items() if v is not None}
)
if (options['http_version'] or self.options['http_version']) == '2':
return pascalize_headers(generated)
return generated
def _get_headers(
self,
request_dependent_headers: Optional[Dict[str, str]] = None,
user_agent: Optional[Iterable[str]] = None,
**options: Any,
) -> Dict[str, str]:
"""
Generates HTTP headers based on the given constraints.
Parameters:
request_dependent_headers (Dict[str, str], optional): Dictionary of request-dependent headers.
user_agent (Iterable[str], optional): User-Agent value(s).
**options (Any): Additional options for header generation.
Returns:
Dict[str, str]: Dictionary of generated HTTP headers.
"""
if request_dependent_headers is None:
request_dependent_headers = {}
# Process new options
if 'browsers' in options or (
# if a unique http_version was passed
'http_version' in options
and options['http_version'] != self.options['http_version']
):
self._update_http_version(options)
header_options = {**self.options, **options}
possible_attribute_values = self._get_possible_attribute_values(header_options)
if user_agent:
# evaluate iterable
if not isinstance(user_agent, (tuple, list)):
user_agent = tuple(user_agent)
http1_values, http2_values = (
get_possible_values(self.header_generator_network, {'User-Agent': user_agent}),
get_possible_values(self.header_generator_network, {'user-agent': user_agent}),
)
else:
http1_values, http2_values = {}, {}
constraints = self._prepare_constraints(
possible_attribute_values, http1_values, http2_values
)
input_sample = self.input_generator_network.generate_consistent_sample_when_possible(
constraints
)
if not input_sample:
if header_options['http_version'] == '1':
headers2 = self._get_headers(
request_dependent_headers, user_agent, **options, http_version='2'
)
return self.order_headers(pascalize_headers(headers2))
relaxation_index = next(
(i for i, key in enumerate(self.relaxation_order) if key in options), -1
)
if header_options['strict'] or relaxation_index == -1:
raise ValueError(
'No headers based on this input can be generated. Please relax or change some of the requirements you specified.'
)
relaxed_options = {**options}
del relaxed_options[self.relaxation_order[relaxation_index]]
return self._get_headers(request_dependent_headers, user_agent, **relaxed_options)
generated_sample = self.header_generator_network.generate_sample(input_sample)
generated_http_and_browser = self._prepare_http_browser_object(
generated_sample['*BROWSER_HTTP']
)
# Add Accept-Language header
accept_language_field_name = (
'accept-language' if generated_http_and_browser.is_http2 else 'Accept-Language'
)
generated_sample[accept_language_field_name] = self._get_accept_language_header(
header_options['locales']
)
# Add Sec headers
if self._should_add_sec_fetch(generated_http_and_browser):
if generated_http_and_browser.is_http2:
generated_sample.update(HTTP2_SEC_FETCH_ATTRIBUTES)
else:
generated_sample.update(HTTP1_SEC_FETCH_ATTRIBUTES)
# Ommit connection, close, and missing value headers
generated_sample = {
k: v
for k, v in generated_sample.items()
if not (
k.lower() == 'connection'
and v == 'close'
or k.startswith('*')
or v == MISSING_VALUE_DATASET_TOKEN
)
}
# Reorder headers
return self.order_headers({**generated_sample, **request_dependent_headers})
def _update_http_version(
self,
options: Dict[str, Any],
):
"""
Prepares options when a `browsers` or `http_version` kwarg is passed to .generate.
Parameters:
options (Dict[str, Any]): Other arguments.
"""
if 'http_version' in options:
http_version = options['http_version']
else:
http_version = self.options['http_version']
if 'browsers' in options:
options['browsers'] = self._prepare_browsers_config(options['browsers'], http_version)
else:
# Create a copy of the class browsers with an updated http_version
options['browsers'] = [
(
Browser(
name=brwsr.name,
min_version=brwsr.min_version,
max_version=brwsr.max_version,
http_version=http_version,
)
if isinstance(brwsr, Browser)
else Browser(name=brwsr, http_version=http_version)
)
for brwsr in self.options['browsers']
]
def _prepare_browsers_config(
self, browsers: Iterable[Union[str, Browser]], http_version: str
) -> List[Browser]:
"""
Prepares the browser configuration based on the given browsers and HTTP version.
Parameters:
browsers (Iterable[Union[str, Browser]]): Supported browsers or Browser objects.
http_version (str): HTTP version ('1' or '2').
Returns:
List[Browser]: List of Browser objects.
"""
return [
(
Browser(name=browser, http_version=http_version)
if isinstance(browser, str)
else browser
)
for browser in browsers
]
def _get_browser_http_options(self, browsers: Iterable[Browser]) -> List[str]:
"""
Retrieves the browser HTTP options based on the given browser specifications.
Parameters:
browsers (Iterable[Browser]): Iterable of Browser objects.
Returns:
List[str]: List of browser HTTP options.
"""
return [
browser_option.complete_string
for browser in browsers
for browser_option in self.unique_browsers
if browser.name == browser_option.name
and (not browser.min_version or browser.min_version <= browser_option.version[0])
and (not browser.max_version or browser.max_version >= browser_option.version[0])
and (not browser.http_version or browser.http_version == browser_option.http_version)
]
def order_headers(self, headers: Dict[str, str]) -> Dict[str, str]:
"""
Orders the headers based on the browser-specific header order.
Parameters:
headers (Dict[str, str]): Dictionary of headers.
Returns:
Dict[str, str]: Ordered dictionary of headers.
"""
# get the browser name
user_agent = get_user_agent(headers)
if user_agent is None:
raise ValueError("Failed to find User-Agent in generated response")
browser_name = get_browser(user_agent)
if browser_name is None:
raise ValueError("Failed to find browser in User-Agent")
header_order = self.headers_order.get(browser_name)
# Order headers according to the specific browser's header order
return (
{key: headers[key] for key in header_order if key in headers}
if header_order
else headers
)
def _get_possible_attribute_values(
self, header_options: Dict[str, Any]
) -> Dict[str, List[str]]:
"""
Retrieves the possible attribute values based on the given header options.
Parameters:
header_options (Dict[str, Any]): Dictionary of header options.
Returns:
Dict[str, List[str]]: Dictionary of possible attribute values.
"""
browsers = self._prepare_browsers_config(
header_options.get('browsers', ()),
header_options.get('http_version', '2'),
)
browser_http_options = self._get_browser_http_options(browsers)
possible_attribute_values = {
'*BROWSER_HTTP': browser_http_options,
'*OPERATING_SYSTEM': header_options.get('os', SUPPORTED_OPERATING_SYSTEMS),
}
if 'devices' in header_options:
possible_attribute_values['*DEVICE'] = header_options['devices']
return possible_attribute_values
def _should_add_sec_fetch(self, browser: HttpBrowserObject) -> bool:
"""
Determines whether Sec-Fetch headers should be added based on the user agent.
Parameters:
browser (HttpBrowserObject): Browser object.
Returns:
bool: True if Sec-Fetch headers should be added, False otherwise.
"""
if browser.name == 'chrome' and browser.version[0] >= 76:
return True
if browser.name == 'firefox' and browser.version[0] >= 90:
return True
if browser.name == 'edge' and browser.version[0] >= 79:
return True
return False
def _get_accept_language_header(self, locales: ListOrString) -> str:
"""
Generates the Accept-Language header based on the given locales.
Parameters:
locales (ListOrString): Locale(s).
Returns:
str: Accept-Language header string.
"""
return ', '.join(
f"{locale};q={1.0 - index * 0.1:.1f}" for index, locale in enumerate(locales)
)
def _load_headers_order(self) -> Dict[str, List[str]]:
"""
Loads the headers order from the headers-order.json file.
Returns:
Dict[str, List[str]]: Dictionary of headers order for each browser.
"""
headers_order_path = DATA_DIR / "headers-order.json"
return json.loads(headers_order_path.read_bytes())
def _load_unique_browsers(self) -> List[HttpBrowserObject]:
"""
Loads the unique browsers from the browser-helper-file.json file.
Returns:
List[HttpBrowserObject]: List of HttpBrowserObject instances.
"""
browser_helper_path = DATA_DIR / 'browser-helper-file.json'
unique_browser_strings = json.loads(browser_helper_path.read_bytes())
return [
self._prepare_http_browser_object(browser_str)
for browser_str in unique_browser_strings
if browser_str != MISSING_VALUE_DATASET_TOKEN
]
def _prepare_constraints(
self,
possible_attribute_values: Dict[str, List[str]],
http1_values: Dict[str, Any],
http2_values: Dict[str, Any],
) -> Dict[str, Iterable[str]]:
"""
Prepares the constraints for generating consistent samples.
Parameters:
possible_attribute_values (Dict[str, List[str]]): Dictionary of possible attribute values.
http1_values (Dict[str, Any]): Dictionary of HTTP/1 values.
http2_values (Dict[str, Any]): Dictionary of HTTP/2 values.
Returns:
Dict[str, Iterable[str]]: Dictionary of constraints for each attribute.
"""
return {
key: tuple(
filter(
lambda x: (
self.filter_browser_http(x, http1_values, http2_values)
if key == '*BROWSER_HTTP'
else self.filter_other_values(x, http1_values, http2_values, key)
),
values,
)
)
for key, values in possible_attribute_values.items()
}
@staticmethod
def filter_browser_http(
value: str, http1_values: Dict[str, Any], http2_values: Dict[str, Any]
) -> bool:
"""
Filters the browser HTTP value based on the HTTP/1 and HTTP/2 values.
Parameters:
value (str): Browser HTTP value.
http1_values (Dict[str, Any]): Dictionary of HTTP/1 values.
http2_values (Dict[str, Any]): Dictionary of HTTP/2 values.
Returns:
bool: True if the value should be included, False otherwise.
"""
browser_name, http_version = value.split('|')
return (
(not http1_values or browser_name in http1_values.get('*BROWSER', ()))
if http_version == '1'
else (not http2_values or browser_name in http2_values.get('*BROWSER', ()))
)
@staticmethod
def filter_other_values(
value: str, http1_values: Dict[str, Any], http2_values: Dict[str, Any], key: str
) -> bool:
"""
Filters the other attribute values based on the HTTP/1 and HTTP/2 values.
Parameters:
value (str): Attribute value.
http1_values (Dict[str, Any]): Dictionary of HTTP/1 values.
http2_values (Dict[str, Any]): Dictionary of HTTP/2 values.
key (str): Attribute key.
Returns:
bool: True if the value should be included, False otherwise.
"""
if http1_values or http2_values:
return value in http1_values.get(key, ()) or value in http2_values.get(key, ())
return True
def _prepare_http_browser_object(self, http_browser_string: str) -> HttpBrowserObject:
"""
Extracts structured information about a browser and HTTP version from a string.
Parameters:
http_browser_string (str): HTTP browser string.
Returns:
HttpBrowserObject: HttpBrowserObject instance.
"""
browser_string, http_version = http_browser_string.split('|')
if browser_string == MISSING_VALUE_DATASET_TOKEN:
return HttpBrowserObject(
name=None, version=(), complete_string=MISSING_VALUE_DATASET_TOKEN, http_version=''
)
browser_name, version_string = browser_string.split('/')
version_parts = version_string.split('.')
version = tuple(int(part) for part in version_parts)
return HttpBrowserObject(
name=browser_name,
version=version,
complete_string=http_browser_string,
http_version=http_version,
)
@@ -0,0 +1,46 @@
from typing import Any, Dict, Iterable, Optional
def get_user_agent(headers: Dict[str, str]) -> Optional[str]:
"""
Retrieves the User-Agent from the headers dictionary.
"""
return headers.get('User-Agent') or headers.get('user-agent')
def get_browser(user_agent: str) -> Optional[str]:
"""
Determines the browser name from the User-Agent string.
"""
if any(alias in user_agent for alias in ('Firefox', 'FxiOS')):
return 'firefox'
elif any(alias in user_agent for alias in ('Chrome', 'CriOS')):
return 'chrome'
elif 'Safari' in user_agent:
return 'safari'
elif any(alias in user_agent for alias in ('Edge', 'EdgA', 'Edg', 'EdgiOS')):
return 'edge'
return None
PASCALIZE_UPPER = {'dnt', 'rtt', 'ect'}
def pascalize(name: str) -> str:
# ignore
if name.startswith(':') or name.startswith('sec-ch-ua'):
return name
# uppercase
if name in PASCALIZE_UPPER:
return name.upper()
return name.title()
def pascalize_headers(headers: Dict[str, str]) -> Dict[str, str]:
return {pascalize(key): value for key, value in headers.items()}
def tuplify(obj: Any):
if (isinstance(obj, Iterable) and not isinstance(obj, str)) or obj is None:
return obj
return (obj,)
@@ -0,0 +1 @@
from . import utils
@@ -0,0 +1,10 @@
"""
utils.js.xz contains a compressed version of the utils.js file
from Apify's fingerprint-injector:
https://github.com/apify/fingerprint-suite/blob/master/packages/fingerprint-injector/src/utils.js
Its purpose is to inject a Fingerprint object into a browser page.
Copyright 2018 Apify Technologies s.r.o.
"""
@@ -0,0 +1,5 @@
from browserforge.injectors.utils import CheckIfInstalled
CheckIfInstalled('playwright')
from .injector import AsyncNewContext, NewContext
@@ -0,0 +1,101 @@
from typing import Dict, Optional
from browserforge.fingerprints import Fingerprint
from browserforge.injectors.utils import InjectFunction, _fingerprint, only_injectable_headers
from playwright.async_api import Browser as AsyncBrowser
from playwright.async_api import BrowserContext as AsyncBrowserContext
from playwright.sync_api import Browser, BrowserContext
async def AsyncNewContext(
browser: AsyncBrowser,
fingerprint: Optional[Fingerprint] = None,
fingerprint_options: Optional[Dict] = None,
**context_options,
) -> AsyncBrowserContext:
"""
Injects an async_api Playwright context with a Fingerprint.
Parameters:
browser (Browser): The browser to create the context in
fingerprint (Optional[Fingerprint]): The fingerprint to inject. If None, one will be generated
fingerprint_options (Optional[Dict]): Options for the Fingerprint generator if `fingerprint` is not passed
**context_options: Other options for the new context
"""
fingerprint = _fingerprint(fingerprint, fingerprint_options)
function = InjectFunction(fingerprint)
# Build new context
context = await browser.new_context(**_context_options(fingerprint, context_options))
# Set headers
await context.set_extra_http_headers(
only_injectable_headers(fingerprint.headers, browser.browser_type.name)
)
# Since there are no async lambdas, define a new async function for emulating dark scheme
async def on_page(page):
await page.emulate_media(color_scheme='dark')
# Dark mode
context.on("page", on_page)
# Inject function
await context.add_init_script(function)
return context
def NewContext(
browser: Browser,
fingerprint: Optional[Fingerprint] = None,
fingerprint_options: Optional[Dict] = None,
**context_options,
) -> BrowserContext:
"""
Injects a sync_api Playwright context with a Fingerprint.
Parameters:
browser (Browser): The browser to create the context in
fingerprint (Optional[Fingerprint]): The fingerprint to inject. If None, one will be generated
fingerprint_options (Optional[Dict]): Options for the Fingerprint generator if `fingerprint` is not passed
**context_options: Other options for the new context
"""
fingerprint = _fingerprint(fingerprint, fingerprint_options)
function = InjectFunction(fingerprint)
# Build new context
context = browser.new_context(**_context_options(fingerprint, context_options))
# Set headers
context.set_extra_http_headers(
only_injectable_headers(fingerprint.headers, browser.browser_type.name)
)
# Dark mode
context.on("page", lambda page: page.emulate_media(color_scheme='dark'))
# Inject function
context.add_init_script(function)
return context
def _context_options(
fingerprint: Fingerprint,
options: Dict,
):
"""
Builds options for new context
"""
return {
'user_agent': fingerprint.navigator.userAgent,
'color_scheme': 'dark',
'viewport': {
'width': fingerprint.screen.width,
'height': fingerprint.screen.height,
**options.pop('viewport', {}),
},
'extra_http_headers': {
'accept-language': fingerprint.headers['Accept-Language'],
**options.pop('extra_http_headers', {}),
},
'device_scale_factor': fingerprint.screen.devicePixelRatio,
**options,
}
@@ -0,0 +1,5 @@
from browserforge.injectors.utils import CheckIfInstalled
CheckIfInstalled('pyppeteer')
from .injector import NewPage
@@ -0,0 +1,63 @@
import re
from typing import Dict, Optional
from pyppeteer.browser import Browser
from pyppeteer.page import Page
from browserforge.fingerprints import Fingerprint
from browserforge.injectors.utils import InjectFunction, _fingerprint, only_injectable_headers
async def NewPage(
browser: Browser,
fingerprint: Optional[Fingerprint] = None,
fingerprint_options: Optional[Dict] = None,
) -> Page:
"""
Injects a Pyppeteer browser object with a Fingerprint.
Parameters:
browser (Browser): The browser to create the context in
fingerprint (Optional[Fingerprint]): The fingerprint to inject. If None, one will be generated
fingerprint_options (Optional[Dict]): Options for the Fingerprint generator if `fingerprint` is not passed
"""
fingerprint = _fingerprint(fingerprint, fingerprint_options)
function = InjectFunction(fingerprint)
# create a new page
page = await browser.newPage()
await page.setUserAgent(fingerprint.navigator.userAgent)
# Pyppeteer does not support firefox, so we can ignore checks
cdp_sess = await page.target.createCDPSession()
await cdp_sess.send(
'Page.setDeviceMetricsOverride',
{
'screenHeight': fingerprint.screen.height,
'screenWidth': fingerprint.screen.width,
'width': fingerprint.screen.width,
'height': fingerprint.screen.height,
'mobile': any(
name in fingerprint.navigator.userAgent for name in ('phone', 'android', 'mobile')
),
'screenOrientation': (
{'angle': 0, 'type': 'portraitPrimary'}
if fingerprint.screen.height > fingerprint.screen.width
else {'angle': 90, 'type': 'landscapePrimary'}
),
'deviceScaleFactor': fingerprint.screen.devicePixelRatio,
},
)
await page.setExtraHTTPHeaders(only_injectable_headers(fingerprint.headers, 'chrome'))
# Only set to dark mode if the Chrome version >= 76
version = re.search('.*?/(\d+)[\d\.]+?', await browser.version())
if version and int(version[1]) >= 76:
await page._client.send(
'Emulation.setEmulatedMedia',
{'features': [{'name': 'prefers-color-scheme', 'value': 'dark'}]},
)
# Inject function
await page.evaluateOnNewDocument(function)
return page
@@ -0,0 +1,10 @@
"""
The undetected_playwright injector is a 1:1 copy of the playwright injector,
using the "undetected_playwright" import name for typing purposes.
"""
from browserforge.injectors.utils import CheckIfInstalled
CheckIfInstalled('undetected_playwright')
from .injector import AsyncNewContext, NewContext
@@ -0,0 +1,100 @@
from typing import Dict, Optional
from browserforge.fingerprints import Fingerprint
from browserforge.injectors.utils import InjectFunction, _fingerprint, only_injectable_headers
from undetected_playwright.async_api import Browser as AsyncBrowser
from undetected_playwright.async_api import BrowserContext as AsyncBrowserContext
from undetected_playwright.sync_api import Browser, BrowserContext
async def AsyncNewContext(
browser: AsyncBrowser,
fingerprint: Optional[Fingerprint] = None,
fingerprint_options: Optional[Dict] = None,
**context_options,
) -> AsyncBrowserContext:
"""
Injects an async_api Undetected-Playwright context with a Fingerprint.
Parameters:
browser (Browser): The browser to create the context in
fingerprint (Optional[Fingerprint]): The fingerprint to inject. If None, one will be generated
fingerprint_options (Optional[Dict]): Options for the Fingerprint generator if `fingerprint` is not passed
**context_options: Other options for the new context
"""
fingerprint = _fingerprint(fingerprint, fingerprint_options)
function = InjectFunction(fingerprint)
# Build new context
context = await browser.new_context(**_context_options(fingerprint, context_options))
# Set headers
await context.set_extra_http_headers(
only_injectable_headers(fingerprint.headers, browser.browser_type.name)
)
# Since there are no async lambdas, define a new async function for emulating dark scheme
async def on_page(page):
await page.emulate_media(color_scheme='dark')
# Dark mode
context.on("page", on_page)
# Inject function
await context.add_init_script(function)
return context
def NewContext(
browser: Browser,
fingerprint: Optional[Fingerprint] = None,
fingerprint_options: Optional[Dict] = None,
**context_options,
) -> BrowserContext:
"""
Injects a sync_api Undetected-Playwright context with a Fingerprint.
Parameters:
browser (Browser): The browser to create the context in
fingerprint (Optional[Fingerprint]): The fingerprint to inject. If None, one will be generated
fingerprint_options (Optional[Dict]): Options for the Fingerprint generator if `fingerprint` is not passed
**context_options: Other options for the new context
"""
fingerprint = _fingerprint(fingerprint, fingerprint_options)
function = InjectFunction(fingerprint)
# Build new context
context = browser.new_context(**_context_options(fingerprint, context_options))
# Set headers
context.set_extra_http_headers(
only_injectable_headers(fingerprint.headers, browser.browser_type.name)
)
# Dark mode
context.on("page", lambda page: page.emulate_media(color_scheme='dark'))
# Inject function
context.add_init_script(function)
return context
def _context_options(
fingerprint: Fingerprint,
options: Dict,
):
"""
Builds options for new context
"""
return {
'user_agent': fingerprint.navigator.userAgent,
'color_scheme': 'dark',
'viewport': {
'width': fingerprint.screen.width,
'height': fingerprint.screen.height,
**options.pop('viewport', {}),
},
'extra_http_headers': {
'accept-language': fingerprint.headers['Accept-Language'],
**options.pop('extra_http_headers', {}),
},
**options,
}
@@ -0,0 +1,147 @@
import lzma
from pathlib import Path
from random import randrange
from typing import Dict, Optional, Set
from browserforge.fingerprints import Fingerprint, FingerprintGenerator
UTILS_JS: Path = Path(__file__).parent / 'data/utils.js.xz'
request_headers: Set[str] = {
'accept-encoding',
'accept',
'cache-control',
'pragma',
'sec-fetch-dest',
'sec-fetch-mode',
'sec-fetch-site',
'sec-fetch-user',
'upgrade-insecure-requests',
}
def only_injectable_headers(headers: Dict[str, str], browser_name: str) -> Dict[str, str]:
"""
Some HTTP headers depend on the request (for example Accept (with values application/json, image/png) etc.).
This function filters out those headers and leaves only the browser-wide ones.
"""
filtered_headers = {k: v for k, v in headers.items() if k.lower() not in request_headers}
# Chromium-based controlled browsers do not support `te` header.
# Remove the `te` header if the browser is not Firefox
if browser_name and 'firefox' not in browser_name.lower():
if 'te' in filtered_headers:
del filtered_headers['te']
if 'Te' in filtered_headers:
del filtered_headers['Te']
return filtered_headers
def InjectFunction(fingerprint: Fingerprint) -> str:
return f"""
(()=>{{
{utils_js()}
const fp = {fingerprint.dumps()};
const {{
battery,
navigator: {{
userAgentData,
webdriver,
...navigatorProps
}},
screen: allScreenProps,
videoCard,
audioCodecs,
videoCodecs,
mockWebRTC,
}} = fp;
slim = fp.slim;
const historyLength = {randrange(1, 6)};
const {{
outerHeight,
outerWidth,
devicePixelRatio,
innerWidth,
innerHeight,
screenX,
pageXOffset,
pageYOffset,
clientWidth,
clientHeight,
hasHDR,
...newScreen
}} = allScreenProps;
const windowScreenProps = {{
innerHeight,
outerHeight,
outerWidth,
innerWidth,
screenX,
pageXOffset,
pageYOffset,
devicePixelRatio,
}};
const documentScreenProps = {{
clientHeight,
clientWidth,
}};
runHeadlessFixes();
if (mockWebRTC) blockWebRTC();
if (slim) {{
window['slim'] = true;
}}
overrideIntlAPI(navigatorProps.language);
overrideStatic();
if (userAgentData) {{
overrideUserAgentData(userAgentData);
}}
if (window.navigator.webdriver) {{
navigatorProps.webdriver = false;
}}
overrideInstancePrototype(window.navigator, navigatorProps);
overrideInstancePrototype(window.screen, newScreen);
overrideWindowDimensionsProps(windowScreenProps);
overrideDocumentDimensionsProps(documentScreenProps);
overrideInstancePrototype(window.history, {{ length: historyLength }});
overrideWebGl(videoCard);
overrideCodecs(audioCodecs, videoCodecs);
overrideBattery(battery);
}})()
"""
def utils_js() -> str:
"""
Opens and uncompresses the utils.js file and returns it as a string
"""
with lzma.open(UTILS_JS, 'rt') as f:
return f.read()
def _fingerprint(
fingerprint: Optional[Fingerprint] = None, fingerprint_options: Optional[Dict] = None
) -> Fingerprint:
"""
Generates a fingerprint if one doesnt exist
"""
if fingerprint:
return fingerprint
generator = FingerprintGenerator()
return generator.generate(**(fingerprint_options or {}))
def CheckIfInstalled(module_name: str):
"""
Checks if a module is installed
"""
import importlib.util
return importlib.util.find_spec(module_name) is not None