tlsmask 1.16.0__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tlsmask/__init__.py +38 -0
- tlsmask/__main__.py +31 -0
- tlsmask/_library.py +212 -0
- tlsmask/_payload.py +352 -0
- tlsmask/_pins.py +135 -0
- tlsmask/_version.py +4 -0
- tlsmask/asyncio.py +103 -0
- tlsmask/bin/tls-client-windows-64-1.16.0.dll +0 -0
- tlsmask/cookies.py +231 -0
- tlsmask/exceptions.py +21 -0
- tlsmask/profiles.py +97 -0
- tlsmask/py.typed +0 -0
- tlsmask/response.py +118 -0
- tlsmask/sessions.py +446 -0
- tlsmask/structures.py +48 -0
- tlsmask-1.16.0.dist-info/METADATA +266 -0
- tlsmask-1.16.0.dist-info/RECORD +20 -0
- tlsmask-1.16.0.dist-info/WHEEL +4 -0
- tlsmask-1.16.0.dist-info/licenses/LICENSE +21 -0
- tlsmask-1.16.0.dist-info/licenses/LICENSE-tls-client +27 -0
tlsmask/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""tlsmask: talk to websites the way a real browser does, down to the TLS handshake.
|
|
2
|
+
|
|
3
|
+
A drop-in replacement for the `tls-client` package that runs bogdanfinn's
|
|
4
|
+
current tls-client library, bundled and pinned by SHA-256:
|
|
5
|
+
|
|
6
|
+
import tlsmask
|
|
7
|
+
|
|
8
|
+
with tlsmask.Session("chrome_150") as session:
|
|
9
|
+
print(session.get("https://tls.peet.ws/api/all").json()["tls"]["ja4"])
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from ._pins import DEFAULT_PROFILE, PROFILES
|
|
13
|
+
from ._pins import LIBRARY_VERSION as __library_version__
|
|
14
|
+
from ._version import __version__
|
|
15
|
+
from .asyncio import AsyncSession
|
|
16
|
+
from .cookies import CookieJar
|
|
17
|
+
from .exceptions import HTTPError, TLSClientException, TLSClientExeption
|
|
18
|
+
from .profiles import ClientIdentifier, ClientIdentifiers
|
|
19
|
+
from .response import Response
|
|
20
|
+
from .sessions import Session
|
|
21
|
+
from .structures import CaseInsensitiveDict
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"DEFAULT_PROFILE",
|
|
25
|
+
"PROFILES",
|
|
26
|
+
"AsyncSession",
|
|
27
|
+
"CaseInsensitiveDict",
|
|
28
|
+
"ClientIdentifier",
|
|
29
|
+
"ClientIdentifiers",
|
|
30
|
+
"CookieJar",
|
|
31
|
+
"HTTPError",
|
|
32
|
+
"Response",
|
|
33
|
+
"Session",
|
|
34
|
+
"TLSClientException",
|
|
35
|
+
"TLSClientExeption",
|
|
36
|
+
"__library_version__",
|
|
37
|
+
"__version__",
|
|
38
|
+
]
|
tlsmask/__main__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""`python -m tlsmask`: which tls-client this is, and whether its file checks out.
|
|
2
|
+
|
|
3
|
+
Paste the output into bug reports.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from . import _library, _pins
|
|
11
|
+
from ._version import __version__
|
|
12
|
+
from .exceptions import TLSClientException
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main() -> int:
|
|
16
|
+
ok, detail = _library.verify()
|
|
17
|
+
if ok:
|
|
18
|
+
try: # a file can hash fine and still not load (another platform, too old a system)
|
|
19
|
+
_library.call("destroySession", {"sessionId": "tlsmask-self-check"})
|
|
20
|
+
except TLSClientException as exc:
|
|
21
|
+
ok, detail = False, f"{detail}, but it could not be loaded: {exc}"
|
|
22
|
+
target = _library.current_target() or "no bundled build"
|
|
23
|
+
print(f"tlsmask {__version__}")
|
|
24
|
+
print(f"tls-client {_pins.LIBRARY_VERSION} (github.com/bogdanfinn/tls-client)")
|
|
25
|
+
print(f"platform {_library.platform_label()} -> {target}")
|
|
26
|
+
print(f"library {'OK' if ok else 'PROBLEM'}: {detail}")
|
|
27
|
+
return 0 if ok else 1
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
if __name__ == "__main__":
|
|
31
|
+
sys.exit(main())
|
tlsmask/_library.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Finding, checking and calling bogdanfinn's tls-client library.
|
|
2
|
+
|
|
3
|
+
The library's C API takes a JSON string and returns one. Each answer carries an
|
|
4
|
+
`id` and stays allocated inside Go until `freeMemory(id)` is called, so every
|
|
5
|
+
answer is freed here, right after ctypes has copied it into Python bytes.
|
|
6
|
+
|
|
7
|
+
Only the file shipped inside the wheel is loaded, and only if its SHA-256 is
|
|
8
|
+
the one pinned in `_pins.py`. `TLSMASK_LIBRARY_PATH` names another file (for a
|
|
9
|
+
platform without a wheel, or your own build), which is used as-is.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import ctypes
|
|
15
|
+
import glob
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import platform
|
|
20
|
+
import struct
|
|
21
|
+
import sys
|
|
22
|
+
import threading
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from . import _pins
|
|
27
|
+
from .exceptions import TLSClientException
|
|
28
|
+
|
|
29
|
+
BIN_DIR = Path(__file__).resolve().parent / "bin"
|
|
30
|
+
ENV_VAR = "TLSMASK_LIBRARY_PATH"
|
|
31
|
+
|
|
32
|
+
# The C functions tlsmask calls; tests/test_contract.py checks the pinned
|
|
33
|
+
# version still exports each one.
|
|
34
|
+
BOUND = ("request", "destroySession", "freeMemory")
|
|
35
|
+
|
|
36
|
+
_ARCH = {
|
|
37
|
+
"x86_64": "amd64",
|
|
38
|
+
"amd64": "amd64",
|
|
39
|
+
"arm64": "arm64",
|
|
40
|
+
"aarch64": "arm64",
|
|
41
|
+
"armv7l": "armv7",
|
|
42
|
+
"armv8l": "armv7",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _is_musl() -> bool:
|
|
47
|
+
# a glibc distro can have musl installed next to it; only a system without
|
|
48
|
+
# glibc is really musl-based (Alpine)
|
|
49
|
+
if platform.libc_ver()[0] == "glibc":
|
|
50
|
+
return False
|
|
51
|
+
return bool(glob.glob("/lib/ld-musl-*.so.1"))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def current_target(
|
|
55
|
+
system: str | None = None,
|
|
56
|
+
machine: str | None = None,
|
|
57
|
+
bits: int | None = None,
|
|
58
|
+
musl: bool | None = None,
|
|
59
|
+
) -> str | None:
|
|
60
|
+
"""This interpreter's key in `_pins.BINARIES`, or None if upstream ships no build for it."""
|
|
61
|
+
system = system or sys.platform
|
|
62
|
+
machine = (platform.machine() if machine is None else machine).lower()
|
|
63
|
+
bits = bits or struct.calcsize("P") * 8
|
|
64
|
+
if system in ("win32", "cygwin"):
|
|
65
|
+
if machine in ("arm64", "aarch64"):
|
|
66
|
+
return None # bogdanfinn publishes no Windows ARM build
|
|
67
|
+
return "windows-amd64" if bits == 64 else "windows-386"
|
|
68
|
+
arch = _ARCH.get(machine)
|
|
69
|
+
if system == "darwin":
|
|
70
|
+
return f"darwin-{arch}" if arch in ("amd64", "arm64") else None
|
|
71
|
+
if system.startswith("linux"):
|
|
72
|
+
if arch == "amd64":
|
|
73
|
+
return "musl-amd64" if (_is_musl() if musl is None else musl) else "linux-amd64"
|
|
74
|
+
if arch == "arm64":
|
|
75
|
+
return "linux-arm64" if bits == 64 else "linux-armv7"
|
|
76
|
+
if arch == "armv7":
|
|
77
|
+
return "linux-armv7"
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def platform_label() -> str:
|
|
82
|
+
return f"{sys.platform}/{platform.machine() or '?'} ({struct.calcsize('P') * 8}-bit Python)"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def sha256_of(path: Path) -> str:
|
|
86
|
+
digest = hashlib.sha256()
|
|
87
|
+
with path.open("rb") as handle:
|
|
88
|
+
for block in iter(lambda: handle.read(1 << 20), b""):
|
|
89
|
+
digest.update(block)
|
|
90
|
+
return digest.hexdigest()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _bundled() -> tuple[str, Path] | None:
|
|
94
|
+
"""(target, file) for the library inside this install, if there is one."""
|
|
95
|
+
target = current_target()
|
|
96
|
+
if target in _pins.BINARIES:
|
|
97
|
+
path = BIN_DIR / _pins.BINARIES[target][0]
|
|
98
|
+
if path.is_file():
|
|
99
|
+
return target, path
|
|
100
|
+
# pip picked the wheel for this machine, so the one file it installed is
|
|
101
|
+
# the right one, even where current_target() guesses wrong.
|
|
102
|
+
for name, (asset, _digest, _tag) in _pins.BINARIES.items():
|
|
103
|
+
path = BIN_DIR / asset
|
|
104
|
+
if path.is_file():
|
|
105
|
+
return name, path
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def locate() -> tuple[Path, str | None]:
|
|
110
|
+
"""(library file, the SHA-256 it must have); None means a file the caller chose."""
|
|
111
|
+
override = os.environ.get(ENV_VAR)
|
|
112
|
+
if override:
|
|
113
|
+
path = Path(override)
|
|
114
|
+
if not path.is_file():
|
|
115
|
+
raise TLSClientException(f"{ENV_VAR}={override} is not a file")
|
|
116
|
+
return path, None
|
|
117
|
+
found = _bundled()
|
|
118
|
+
if found is None and current_target() == "musl-amd64":
|
|
119
|
+
raise TLSClientException(
|
|
120
|
+
"tls-client's Alpine (musl) build can't be loaded into Python, so tlsmask has no "
|
|
121
|
+
"wheel for Alpine. Use a glibc-based image (python:3.12-slim, for example), or set "
|
|
122
|
+
f"{ENV_VAR} to a tls-client {_pins.LIBRARY_VERSION} library that loads on your system."
|
|
123
|
+
)
|
|
124
|
+
if found is None and current_target() in _pins.BINARIES:
|
|
125
|
+
raise TLSClientException(
|
|
126
|
+
"this tlsmask install has no tls-client library, which happens when pip builds "
|
|
127
|
+
"tlsmask from source instead of installing its wheel. Reinstall with "
|
|
128
|
+
"`pip install --force-reinstall --only-binary=tlsmask tlsmask`, or set "
|
|
129
|
+
f"{ENV_VAR} to a build of bogdanfinn/tls-client {_pins.LIBRARY_VERSION}."
|
|
130
|
+
)
|
|
131
|
+
if found is None:
|
|
132
|
+
raise TLSClientException(
|
|
133
|
+
f"tlsmask ships no tls-client library for {platform_label()}. Set {ENV_VAR} "
|
|
134
|
+
f"to a build of bogdanfinn/tls-client {_pins.LIBRARY_VERSION} to use your own."
|
|
135
|
+
)
|
|
136
|
+
target, path = found
|
|
137
|
+
return path, _pins.BINARIES[target][1]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def verify() -> tuple[bool, str]:
|
|
141
|
+
"""Whether the library is here and is the pinned file, with a line saying why."""
|
|
142
|
+
try:
|
|
143
|
+
path, expected = locate()
|
|
144
|
+
except TLSClientException as exc:
|
|
145
|
+
return False, str(exc)
|
|
146
|
+
if expected is None:
|
|
147
|
+
return True, f"{path} (from {ENV_VAR}, not hash-checked)"
|
|
148
|
+
actual = sha256_of(path)
|
|
149
|
+
if actual != expected:
|
|
150
|
+
return False, (
|
|
151
|
+
f"{path} hashes to {actual}, but tls-client {_pins.LIBRARY_VERSION} "
|
|
152
|
+
f"is pinned to {expected}"
|
|
153
|
+
)
|
|
154
|
+
return True, f"{path} (sha256 {actual}, as pinned)"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
_lib: Any = None
|
|
158
|
+
_lock = threading.Lock()
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _load() -> Any:
|
|
162
|
+
global _lib
|
|
163
|
+
if _lib is not None:
|
|
164
|
+
return _lib
|
|
165
|
+
with _lock:
|
|
166
|
+
if _lib is not None:
|
|
167
|
+
return _lib
|
|
168
|
+
path, expected = locate()
|
|
169
|
+
# Checked on every load, not only when the wheel was built: a truncated
|
|
170
|
+
# or swapped file must fail here, not somewhere inside a native call.
|
|
171
|
+
if expected is not None and sha256_of(path) != expected:
|
|
172
|
+
raise TLSClientException(
|
|
173
|
+
f"{path.name} is not the file pinned for tls-client {_pins.LIBRARY_VERSION} "
|
|
174
|
+
"(SHA-256 mismatch); reinstall tlsmask"
|
|
175
|
+
)
|
|
176
|
+
try:
|
|
177
|
+
lib = ctypes.CDLL(str(path))
|
|
178
|
+
except OSError as exc: # a file that is not a library for this machine
|
|
179
|
+
raise TLSClientException(f"could not load {path}: {exc}") from None
|
|
180
|
+
for name in ("request", "destroySession"):
|
|
181
|
+
function = getattr(lib, name)
|
|
182
|
+
function.argtypes = [ctypes.c_char_p]
|
|
183
|
+
function.restype = ctypes.c_void_p # a C string we copy, then free by its id
|
|
184
|
+
lib.freeMemory.argtypes = [ctypes.c_char_p]
|
|
185
|
+
lib.freeMemory.restype = None # it returns nothing
|
|
186
|
+
_lib = lib
|
|
187
|
+
return lib
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def call(function: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
191
|
+
"""One call into the library: JSON in, JSON out, the answer freed.
|
|
192
|
+
|
|
193
|
+
ctypes releases the GIL for the native call, so calls made from different
|
|
194
|
+
threads run in parallel.
|
|
195
|
+
"""
|
|
196
|
+
if function not in ("request", "destroySession"):
|
|
197
|
+
# only these two have their return type declared in _load()
|
|
198
|
+
raise ValueError(f"tlsmask does not call tls-client's {function!r}")
|
|
199
|
+
lib = _load()
|
|
200
|
+
pointer = getattr(lib, function)(json.dumps(payload).encode("utf-8"))
|
|
201
|
+
if not pointer:
|
|
202
|
+
raise TLSClientException(f"tls-client's {function} returned nothing")
|
|
203
|
+
raw = ctypes.string_at(pointer)
|
|
204
|
+
try:
|
|
205
|
+
answer = json.loads(raw)
|
|
206
|
+
except ValueError:
|
|
207
|
+
# Upstream's last-resort error path: a bare string it never
|
|
208
|
+
# registered, so there is no id to free.
|
|
209
|
+
raise TLSClientException(raw.decode("utf-8", "replace")) from None
|
|
210
|
+
if isinstance(answer, dict) and answer.get("id"):
|
|
211
|
+
lib.freeMemory(str(answer["id"]).encode("utf-8"))
|
|
212
|
+
return answer
|
tlsmask/_payload.py
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
"""Pure translation from tlsmask's settings to the JSON tls-client reads.
|
|
2
|
+
|
|
3
|
+
Nothing here does I/O, so every option is tested without the library. Field
|
|
4
|
+
names are upstream's (cffi_src/types.go); tests/test_contract.py checks each
|
|
5
|
+
one against the snapshot of the pinned version.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import difflib
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import unicodedata
|
|
15
|
+
from collections.abc import Iterable, Mapping
|
|
16
|
+
from typing import Any
|
|
17
|
+
from urllib.parse import quote, urlencode, urlsplit, urlunsplit
|
|
18
|
+
|
|
19
|
+
from ._pins import LIBRARY_VERSION, PROFILES
|
|
20
|
+
from .exceptions import TLSClientException
|
|
21
|
+
|
|
22
|
+
# Session attribute -> customTlsClient field; sent only with client_identifier=None.
|
|
23
|
+
CUSTOM_FIELDS: dict[str, str] = {
|
|
24
|
+
"ja3_string": "ja3String",
|
|
25
|
+
"h2_settings": "h2Settings",
|
|
26
|
+
"h2_settings_order": "h2SettingsOrder",
|
|
27
|
+
"supported_signature_algorithms": "supportedSignatureAlgorithms",
|
|
28
|
+
"supported_delegated_credentials_algorithms": "supportedDelegatedCredentialsAlgorithms",
|
|
29
|
+
"supported_versions": "supportedVersions",
|
|
30
|
+
"key_share_curves": "keyShareCurves",
|
|
31
|
+
"cert_compression_algos": "certCompressionAlgos",
|
|
32
|
+
"pseudo_header_order": "pseudoHeaderOrder",
|
|
33
|
+
"connection_flow": "connectionFlow",
|
|
34
|
+
"priority_frames": "priorityFrames",
|
|
35
|
+
"header_priority": "headerPriority",
|
|
36
|
+
"alpn_protocols": "alpnProtocols",
|
|
37
|
+
"alps_protocols": "alpsProtocols",
|
|
38
|
+
"record_size_limit": "recordSizeLimit",
|
|
39
|
+
"ech_candidate_payloads": "ECHCandidatePayloads",
|
|
40
|
+
"ech_candidate_cipher_suites": "ECHCandidateCipherSuites",
|
|
41
|
+
"h3_settings": "h3Settings",
|
|
42
|
+
"h3_settings_order": "h3SettingsOrder",
|
|
43
|
+
"h3_pseudo_header_order": "h3PseudoHeaderOrder",
|
|
44
|
+
"h3_priority_param": "h3PriorityParam",
|
|
45
|
+
"h3_send_grease_frames": "h3SendGreaseFrames",
|
|
46
|
+
"stream_id": "streamId",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
# Session attribute -> top-level field that shapes the Go client.
|
|
50
|
+
CLIENT_FIELDS: dict[str, str] = {
|
|
51
|
+
"random_tls_extension_order": "withRandomTLSExtensionOrder",
|
|
52
|
+
"force_http1": "forceHttp1",
|
|
53
|
+
"catch_panics": "catchPanics",
|
|
54
|
+
"debug": "withDebug",
|
|
55
|
+
"certificate_pinning": "certificatePinningHosts",
|
|
56
|
+
"disable_http3": "disableHttp3",
|
|
57
|
+
"with_protocol_racing": "withProtocolRacing",
|
|
58
|
+
"disable_ipv4": "disableIPV4",
|
|
59
|
+
"disable_ipv6": "disableIPV6",
|
|
60
|
+
"local_address": "localAddress",
|
|
61
|
+
"server_name_overwrite": "serverNameOverwrite",
|
|
62
|
+
"transport_options": "transportOptions",
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
# Every Session attribute client_options() reads.
|
|
66
|
+
SETTINGS: tuple[str, ...] = (
|
|
67
|
+
"client_identifier",
|
|
68
|
+
"cert_compression_algo",
|
|
69
|
+
*CUSTOM_FIELDS,
|
|
70
|
+
*CLIENT_FIELDS,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
# The proxy schemes tls-client can dial.
|
|
74
|
+
_PROXY_SCHEMES = frozenset({"http", "https", "socks5", "socks5h"})
|
|
75
|
+
# What requests' requote_uri leaves alone.
|
|
76
|
+
_SAFE = "!#$%&'()*+,/:;=?@[]~"
|
|
77
|
+
# The ALPS extension's code points (old and new).
|
|
78
|
+
_ALPS = frozenset({"17513", "17613"})
|
|
79
|
+
# JA3 extensions tls-client 1.16 cannot build without a matching setting; left
|
|
80
|
+
# out, the handshake fails later with messages like "tls: internal error".
|
|
81
|
+
_JA3_NEEDS = {
|
|
82
|
+
"13": (
|
|
83
|
+
"signature_algorithms",
|
|
84
|
+
"supported_signature_algorithms",
|
|
85
|
+
"supportedSignatureAlgorithms",
|
|
86
|
+
),
|
|
87
|
+
"27": ("compress_certificate", "cert_compression_algos", "certCompressionAlgos"),
|
|
88
|
+
"43": ("supported_versions", "supported_versions", "supportedVersions"),
|
|
89
|
+
"51": ("key_share", "key_share_curves", "keyShareCurves"),
|
|
90
|
+
}
|
|
91
|
+
# Dots other scripts use in host names (NFKC leaves U+3002 as it is).
|
|
92
|
+
_IDEOGRAPHIC_DOTS = {0x3002: ".", 0xFF0E: ".", 0xFF61: "."}
|
|
93
|
+
# Characters a URL cannot carry as they are (besides controls and non-ASCII).
|
|
94
|
+
_UNSAFE = frozenset(' "<>\\^`{|}')
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def check_profile(name: str) -> None:
|
|
98
|
+
"""Refuse a profile the pinned library does not ship: it would silently send its default."""
|
|
99
|
+
if name in PROFILES:
|
|
100
|
+
return
|
|
101
|
+
close = difflib.get_close_matches(str(name), sorted(PROFILES), n=3, cutoff=0.6)
|
|
102
|
+
hint = f" (did you mean {', '.join(close)}?)" if close else ""
|
|
103
|
+
raise ValueError(
|
|
104
|
+
f"tls-client {LIBRARY_VERSION} has no profile {name!r}{hint}; "
|
|
105
|
+
"it would silently send its default browser instead"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def custom_fields_set(settings: Mapping[str, Any]) -> bool:
|
|
110
|
+
return any(settings.get(attr) is not None for attr in (*CUSTOM_FIELDS, "cert_compression_algo"))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def client_options(
|
|
114
|
+
settings: Mapping[str, Any], *, timeout_ms: int, insecure_skip_verify: bool
|
|
115
|
+
) -> dict[str, Any]:
|
|
116
|
+
"""The fields that shape the Go client.
|
|
117
|
+
|
|
118
|
+
Upstream builds a session's client on its first request and afterwards only
|
|
119
|
+
changes its proxy, so tlsmask names each Go client after these fields
|
|
120
|
+
(client_key): a different setting gets a client of its own.
|
|
121
|
+
"""
|
|
122
|
+
# tls-client refuses these combinations only when it builds the client
|
|
123
|
+
if settings.get("disable_ipv4") and settings.get("disable_ipv6"):
|
|
124
|
+
raise ValueError("disable_ipv4 and disable_ipv6 together leave no way to connect")
|
|
125
|
+
if settings.get("with_protocol_racing") and (
|
|
126
|
+
settings.get("disable_http3") or settings.get("force_http1")
|
|
127
|
+
):
|
|
128
|
+
raise ValueError(
|
|
129
|
+
"with_protocol_racing races HTTP/3 against HTTP/2, so it cannot be combined "
|
|
130
|
+
"with disable_http3 or force_http1"
|
|
131
|
+
)
|
|
132
|
+
options: dict[str, Any] = {
|
|
133
|
+
"timeoutMilliseconds": int(timeout_ms),
|
|
134
|
+
"insecureSkipVerify": bool(insecure_skip_verify),
|
|
135
|
+
"withoutCookieJar": True,
|
|
136
|
+
}
|
|
137
|
+
for attr, field in CLIENT_FIELDS.items():
|
|
138
|
+
value = settings.get(attr)
|
|
139
|
+
if value is not None:
|
|
140
|
+
options[field] = value
|
|
141
|
+
identifier = settings.get("client_identifier")
|
|
142
|
+
if identifier is None:
|
|
143
|
+
options["customTlsClient"] = _custom_client(settings)
|
|
144
|
+
else:
|
|
145
|
+
check_profile(identifier)
|
|
146
|
+
options["tlsClientIdentifier"] = identifier
|
|
147
|
+
return options
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _custom_client(settings: Mapping[str, Any]) -> dict[str, Any]:
|
|
151
|
+
if not settings.get("ja3_string"):
|
|
152
|
+
raise ValueError(
|
|
153
|
+
"client_identifier=None builds a custom TLS client, which needs ja3_string"
|
|
154
|
+
)
|
|
155
|
+
custom = {
|
|
156
|
+
field: settings[attr]
|
|
157
|
+
for attr, field in CUSTOM_FIELDS.items()
|
|
158
|
+
if settings.get(attr) is not None
|
|
159
|
+
}
|
|
160
|
+
legacy = settings.get("cert_compression_algo")
|
|
161
|
+
if legacy and "certCompressionAlgos" not in custom:
|
|
162
|
+
# The old wrapper sent certCompressionAlgo (one string); v1.16 reads a list.
|
|
163
|
+
custom["certCompressionAlgos"] = [legacy]
|
|
164
|
+
# tls-client 1.16 builds the ALPN (and ALPS) extensions from these lists. Left
|
|
165
|
+
# empty, it sends an empty ALPN extension and servers stall, and the old
|
|
166
|
+
# tls-client package had no such settings, so default to what browsers offer.
|
|
167
|
+
extensions = _ja3_extensions(custom["ja3String"])
|
|
168
|
+
custom.setdefault("alpnProtocols", ["h2", "http/1.1"])
|
|
169
|
+
if "alpsProtocols" not in custom and extensions & _ALPS:
|
|
170
|
+
custom["alpsProtocols"] = ["h2"]
|
|
171
|
+
for extension, (name, attr, field) in _JA3_NEEDS.items():
|
|
172
|
+
if extension in extensions and not custom.get(field):
|
|
173
|
+
raise ValueError(
|
|
174
|
+
f"the JA3 string lists extension {extension} ({name}), "
|
|
175
|
+
f"so tls-client also needs {attr}"
|
|
176
|
+
)
|
|
177
|
+
return custom
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _ja3_extensions(ja3: str) -> set[str]:
|
|
181
|
+
fields = ja3.split(",")
|
|
182
|
+
return set(fields[2].split("-")) if len(fields) > 2 else set()
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def client_key(options: Mapping[str, Any]) -> str:
|
|
186
|
+
blob = json.dumps(options, sort_keys=True, separators=(",", ":"), default=str)
|
|
187
|
+
return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def pick_proxy(proxy: str | Mapping[str, str] | None, url: str) -> str:
|
|
191
|
+
"""The proxy for `url`: a string as-is; from a dict, the entry for the URL's
|
|
192
|
+
scheme, then "all", then any entry. A non-empty dict never means "no proxy"
|
|
193
|
+
(the old wrapper read only "http" and sent the rest direct)."""
|
|
194
|
+
return _checked_proxy(_choose_proxy(proxy, url))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _choose_proxy(proxy: str | Mapping[str, str] | None, url: str) -> str:
|
|
198
|
+
if not proxy:
|
|
199
|
+
return ""
|
|
200
|
+
if isinstance(proxy, str):
|
|
201
|
+
return proxy
|
|
202
|
+
scheme = urlsplit(url).scheme.lower()
|
|
203
|
+
for key in (scheme, "all"):
|
|
204
|
+
if proxy.get(key):
|
|
205
|
+
return str(proxy[key])
|
|
206
|
+
for value in proxy.values():
|
|
207
|
+
if value:
|
|
208
|
+
return str(value)
|
|
209
|
+
return ""
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _checked_proxy(proxy: str) -> str:
|
|
213
|
+
"""`host:port` means an http:// proxy, as in requests. A proxy tls-client
|
|
214
|
+
cannot use is refused here: tls-client itself would keep a broken client."""
|
|
215
|
+
if not proxy:
|
|
216
|
+
return ""
|
|
217
|
+
if "://" not in proxy:
|
|
218
|
+
proxy = f"http://{proxy}"
|
|
219
|
+
parts = urlsplit(proxy)
|
|
220
|
+
if parts.scheme.lower() not in _PROXY_SCHEMES or not parts.hostname:
|
|
221
|
+
raise TLSClientException(
|
|
222
|
+
f"tls-client cannot use a {parts.scheme}:// proxy at {parts.hostname or '?'}; "
|
|
223
|
+
"it takes http://, https://, socks5:// or socks5h:// with a host and port"
|
|
224
|
+
)
|
|
225
|
+
return proxy
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def with_params(url: str, *param_sets: Any) -> str:
|
|
229
|
+
"""`url` with each set's parameters appended to its query, keeping the existing ones."""
|
|
230
|
+
chunks: list[str] = []
|
|
231
|
+
for params in param_sets:
|
|
232
|
+
if not params:
|
|
233
|
+
continue
|
|
234
|
+
if isinstance(params, (str, bytes)):
|
|
235
|
+
text = params.decode() if isinstance(params, bytes) else params
|
|
236
|
+
chunks.append(text.lstrip("?"))
|
|
237
|
+
continue
|
|
238
|
+
pairs = params.items() if isinstance(params, Mapping) else params
|
|
239
|
+
chunks.append(urlencode([(k, v) for k, v in pairs if v is not None], doseq=True))
|
|
240
|
+
chunks = [chunk for chunk in chunks if chunk]
|
|
241
|
+
if not chunks:
|
|
242
|
+
return url
|
|
243
|
+
parts = urlsplit(url)
|
|
244
|
+
query = "&".join(([parts.query] if parts.query else []) + chunks)
|
|
245
|
+
return urlunsplit(parts._replace(query=query))
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _ascii_host(host: str) -> str:
|
|
249
|
+
"""A host name as browsers send it: each non-ASCII label lower-cased and in
|
|
250
|
+
punycode. (Python's "idna" codec follows IDNA 2003, which turns ß into ss,
|
|
251
|
+
and that is a different domain.)"""
|
|
252
|
+
# compatibility forms (full-width letters, ideographic dots) become plain ones,
|
|
253
|
+
# as a browser's URL parser does; lower() rather than casefold() keeps ß
|
|
254
|
+
host = unicodedata.normalize("NFKC", host).translate(_IDEOGRAPHIC_DOTS)
|
|
255
|
+
labels = []
|
|
256
|
+
for label in host.split("."):
|
|
257
|
+
if not label.isascii():
|
|
258
|
+
label = "xn--" + unicodedata.normalize("NFC", label.lower()).encode("punycode").decode()
|
|
259
|
+
labels.append(label)
|
|
260
|
+
return ".".join(labels)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def requote(url: str) -> str:
|
|
264
|
+
"""`url` as a browser sends it: a non-ASCII host in punycode, and spaces and
|
|
265
|
+
other characters a URL cannot carry percent-encoded. Existing %XX escapes are
|
|
266
|
+
kept, and a URL that needs nothing is returned untouched."""
|
|
267
|
+
if url.isascii() and not any(c in _UNSAFE or ord(c) < 33 or ord(c) == 127 for c in url):
|
|
268
|
+
return url
|
|
269
|
+
parts = urlsplit(url)
|
|
270
|
+
netloc = parts.netloc
|
|
271
|
+
if not netloc.isascii():
|
|
272
|
+
userinfo, at, hostport = netloc.rpartition("@")
|
|
273
|
+
host, colon, port = hostport.partition(":")
|
|
274
|
+
netloc = f"{userinfo}{at}{_ascii_host(host)}{colon}{port}"
|
|
275
|
+
return urlunsplit(
|
|
276
|
+
(
|
|
277
|
+
parts.scheme,
|
|
278
|
+
netloc,
|
|
279
|
+
quote(parts.path, safe=_SAFE),
|
|
280
|
+
quote(parts.query, safe=_SAFE),
|
|
281
|
+
quote(parts.fragment, safe=_SAFE),
|
|
282
|
+
)
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def encode_body(data: Any, json_value: Any) -> tuple[str | bytes | None, str | None]:
|
|
287
|
+
"""(body, the Content-Type to add for this request only)."""
|
|
288
|
+
if data is None and json_value is not None:
|
|
289
|
+
if isinstance(json_value, (bytes, bytearray)):
|
|
290
|
+
return bytes(json_value), "application/json"
|
|
291
|
+
if isinstance(json_value, str):
|
|
292
|
+
return json_value, "application/json"
|
|
293
|
+
return json.dumps(json_value, separators=(",", ":")), "application/json"
|
|
294
|
+
if data is None:
|
|
295
|
+
return None, None
|
|
296
|
+
if isinstance(data, (bytes, bytearray)):
|
|
297
|
+
return bytes(data), None
|
|
298
|
+
if isinstance(data, str):
|
|
299
|
+
return data, None
|
|
300
|
+
if isinstance(data, Mapping):
|
|
301
|
+
data = list(data.items())
|
|
302
|
+
if isinstance(data, (list, tuple)):
|
|
303
|
+
return urlencode(data, doseq=True), "application/x-www-form-urlencoded"
|
|
304
|
+
raise TypeError(
|
|
305
|
+
f"data must be str, bytes, a dict or a list of pairs, not {type(data).__name__}"
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def header_order(headers: Iterable[str], order: Iterable[str] | None = None) -> list[str]:
|
|
310
|
+
"""Lower-cased: the names in `order`, then every other header in the order
|
|
311
|
+
it was set. Upstream sorts any header missing from this list alphabetically.
|
|
312
|
+
Host leads, as browsers send it over HTTP/1.1, unless `order` places it."""
|
|
313
|
+
order = list(order or ())
|
|
314
|
+
result: list[str] = [] if any(name.lower() == "host" for name in order) else ["host"]
|
|
315
|
+
for name in [*order, *headers]:
|
|
316
|
+
low = name.lower()
|
|
317
|
+
if low not in result:
|
|
318
|
+
result.append(low)
|
|
319
|
+
return result
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def request_payload(
|
|
323
|
+
*,
|
|
324
|
+
session_id: str,
|
|
325
|
+
client: Mapping[str, Any],
|
|
326
|
+
method: str,
|
|
327
|
+
url: str,
|
|
328
|
+
headers: Mapping[str, str],
|
|
329
|
+
header_order: Iterable[str],
|
|
330
|
+
body: str | bytes | None,
|
|
331
|
+
proxy: str,
|
|
332
|
+
is_rotating_proxy: bool = False,
|
|
333
|
+
) -> dict[str, Any]:
|
|
334
|
+
payload = dict(client)
|
|
335
|
+
payload.update(
|
|
336
|
+
sessionId=session_id,
|
|
337
|
+
requestMethod=method.upper(),
|
|
338
|
+
requestUrl=url,
|
|
339
|
+
headers=dict(headers),
|
|
340
|
+
headerOrder=list(header_order),
|
|
341
|
+
proxyUrl=proxy,
|
|
342
|
+
isRotatingProxy=bool(is_rotating_proxy),
|
|
343
|
+
followRedirects=False, # tlsmask follows redirects itself, so each hop's cookies are kept
|
|
344
|
+
isByteResponse=True, # bodies come back as base64, so binary survives
|
|
345
|
+
requestCookies=[], # cookies travel in the Cookie header
|
|
346
|
+
)
|
|
347
|
+
if isinstance(body, bytes):
|
|
348
|
+
payload["isByteRequest"] = True
|
|
349
|
+
payload["requestBody"] = base64.b64encode(body).decode("ascii")
|
|
350
|
+
elif body:
|
|
351
|
+
payload["requestBody"] = body
|
|
352
|
+
return payload
|