tls-client-python 1.16.0.2__py3-none-win32.whl → 1.16.0.4__py3-none-win32.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.
tls_client/__init__.py CHANGED
@@ -39,6 +39,15 @@ from tls_client import ech, fingerprints
39
39
  from tls_client._multipart_boundary import blink_boundary, boundary, gecko_boundary
40
40
  from tls_client.context import RequestContext
41
41
  from tls_client.status_codes import codes
42
+ from tls_client.websocket import (
43
+ BINARY,
44
+ CLOSE,
45
+ PING,
46
+ PONG,
47
+ TEXT,
48
+ WebSocket,
49
+ WebSocketConnection,
50
+ )
42
51
 
43
52
  __all__ = [
44
53
  "Session",
@@ -76,5 +85,12 @@ __all__ = [
76
85
  "gecko_boundary",
77
86
  "status_codes",
78
87
  "structures",
88
+ "WebSocket",
89
+ "WebSocketConnection",
90
+ "TEXT",
91
+ "BINARY",
92
+ "CLOSE",
93
+ "PING",
94
+ "PONG",
79
95
  ]
80
- __version__ = "1.16.0.2"
96
+ __version__ = "1.16.0.4"
tls_client/_core.py CHANGED
@@ -152,10 +152,10 @@ class Request(TypedDict, total=False):
152
152
 
153
153
  Request body as raw bytes.
154
154
  """
155
- client_identifier: Optional[str]
156
- """TLS 指纹标识。
155
+ client_identifier: Optional[ClientIdentifiers]
156
+ """TLS 指纹标识。可为 :data:`ClientIdentifiers` 中的任一浏览器指纹。
157
157
 
158
- TLS fingerprint identifier.
158
+ TLS fingerprint identifier — one of :data:`ClientIdentifiers`.
159
159
  """
160
160
  timeout: Optional[int]
161
161
  """超时时间(秒)。
@@ -367,6 +367,99 @@ class Request(TypedDict, total=False):
367
367
 
368
368
  Each element is ``{'cert_pem': bytes, 'key_pem': bytes}``.
369
369
  """
370
+ # ── ABI 2 / 2.1 高级 TLS 控制 ── / Advanced TLS controls ──
371
+ disable_session_tickets: Optional[bool]
372
+ """是否禁用 TLS session tickets。
373
+
374
+ Whether to disable TLS session tickets.
375
+ """
376
+ tls_keylog_path: Optional[str]
377
+ """TLS keylog 文件路径,用于 Wireshark 解密调试。
378
+
379
+ TLS keylog file path for Wireshark decryption debugging.
380
+ """
381
+ root_ca_pem: Optional[bytes]
382
+ """自定义 CA 证书 PEM 内容,用于 TLS 校验。
383
+
384
+ Custom CA certificate PEM bytes for TLS verification.
385
+ """
386
+ h2_max_data_frame_size: Optional[int]
387
+ """HTTP/2 单帧 DATA 载荷上限(字节)。
388
+
389
+ HTTP/2 per-DATA-frame payload cap (bytes).
390
+ """
391
+ preface_ping_idle_ms: Optional[int]
392
+ """空闲 HTTP/2 连接发送 PING 的阈值(毫秒)。
393
+
394
+ Preface-ping idle threshold (ms) for idle HTTP/2 connections.
395
+ """
396
+ hpack_indexing_policy: Optional[str]
397
+ """HPACK 索引策略(如 ``"chrome"``)。
398
+
399
+ HPACK indexing policy (e.g. ``"chrome"``).
400
+ """
401
+ cookie_crumb: Optional[bool]
402
+ """是否将 Cookie 头按 cookie-pair 拆分发送。
403
+
404
+ Whether to split the Cookie header per cookie-pair.
405
+ """
406
+ # ── ABI 3 细粒度指纹控制 ── / Fine-grained fingerprint controls ──
407
+ extension_permute_mode: Optional[int]
408
+ """TLS 扩展乱序策略:``0``=off, ``1``=chrome, ``2``=all, ``3``=prefix。
409
+
410
+ Extension-order permutation policy: ``0``=off, ``1``=chrome, ``2``=all,
411
+ ``3``=prefix.
412
+ """
413
+ extension_permute_prefix: Optional[int]
414
+ """前缀长度(仅 ``extension_permute_mode=3`` 时生效):前 N 个扩展保持原位。
415
+
416
+ Prefix length (only when ``extension_permute_mode=3``): keep the first N
417
+ extensions in place.
418
+ """
419
+ h2_disable_priority_frames: Optional[bool]
420
+ """是否抑制 RFC 7540 PRIORITY 帧与 HEADERS 优先级标志。
421
+
422
+ Whether to suppress RFC 7540 PRIORITY frames / HEADERS priority flag.
423
+ """
424
+ header_order_by_dest: Optional[bool]
425
+ """是否按 Sec-Fetch-Dest 自动选择浏览器真实请求头顺序。
426
+
427
+ Whether to derive header order from Sec-Fetch-Dest instead of
428
+ ``header_order``.
429
+ """
430
+ header_order_dest: Optional[str]
431
+ """显式指定 Sec-Fetch-Dest 值(留空则由请求头推断)。
432
+
433
+ Explicit Sec-Fetch-Dest value (empty = infer from request headers).
434
+ """
435
+ tcp_dont_fragment: Optional[int]
436
+ """TCP DF 位:``-1``/``None`` 沿用预设,``0`` 清位,``1`` 置位。
437
+
438
+ TCP Don't-Fragment flag: ``-1``/``None`` keeps the profile default,
439
+ ``0`` clears, ``1`` sets.
440
+ """
441
+ tcp_tos: Optional[int]
442
+ """TCP 服务类型字段(TOS/DSCP)。``-1``/``None`` 沿用预设。
443
+
444
+ TCP Type-of-Service byte. ``-1``/``None`` keeps the profile default.
445
+ """
446
+ tcp_no_delay: Optional[int]
447
+ """TCP Nagle 算法:``-1``/``None`` 沿用预设,``0`` 开启,``1`` 关闭。
448
+
449
+ TCP_NODELAY: ``-1``/``None`` keeps the profile default, ``0`` enables
450
+ Nagle, ``1`` disables it.
451
+ """
452
+ tcp_window_clamp: Optional[int]
453
+ """TCP 接收窗口钳制值。``0``=不钳制。
454
+
455
+ TCP receive-window clamp. ``0`` = no clamp.
456
+ """
457
+ tcp_ip_id_mode: Optional[str]
458
+ """IP 分片 ID 生成模式(如 ``"random"``、``"zero"``、``"increment"``)。
459
+
460
+ IP fragmentation ID generation mode (e.g. ``"random"``, ``"zero"``,
461
+ ``"increment"``).
462
+ """
370
463
 
371
464
 
372
465
  # ---------------------------------------------------------------------------
@@ -1096,6 +1189,25 @@ typedef struct {
1096
1189
  char* _resp_strings;
1097
1190
  } ResponseResult;
1098
1191
 
1192
+ typedef struct {
1193
+ const char* url;
1194
+ const char* client_identifier;
1195
+ int force_http1;
1196
+ HttpHeader* headers;
1197
+ int headers_len;
1198
+ const char** header_order;
1199
+ int header_order_len;
1200
+ int read_buffer_size;
1201
+ int write_buffer_size;
1202
+ int handshake_timeout_milliseconds;
1203
+ } WebsocketOptions;
1204
+
1205
+ typedef struct {
1206
+ int message_type;
1207
+ const char* data;
1208
+ int data_len;
1209
+ } WebsocketMessage;
1210
+
1099
1211
  ResponseResult* ExecuteRequest(RequestOptions* opts);
1100
1212
  void FreeResponse(ResponseResult* res);
1101
1213
  void ClearClientPool(void);
@@ -1108,6 +1220,15 @@ char* ResolveECHConfig(char* host);
1108
1220
 
1109
1221
  typedef void (*async_callback_fn)(uintptr_t request_id, ResponseResult* response);
1110
1222
  int RequestAsync(RequestOptions* opts, uintptr_t request_id, async_callback_fn cb);
1223
+
1224
+ uintptr_t WebsocketNew(WebsocketOptions* opts, char** err_msg);
1225
+ uintptr_t WebsocketConnect(uintptr_t ws_id, char** err_msg);
1226
+ WebsocketMessage* WebsocketReadMessage(uintptr_t conn_id, char** err_msg);
1227
+ int WebsocketWriteMessage(uintptr_t conn_id, int message_type, const char* data, int data_len, char** err_msg);
1228
+ int WebsocketClose(uintptr_t conn_id, char** err_msg);
1229
+ void WebsocketFreeMessage(WebsocketMessage* msg);
1230
+ void WebsocketFreeHandle(uintptr_t handle_id);
1231
+ void FreeCString(char* s);
1111
1232
  """
1112
1233
 
1113
1234
  # ---------------------------------------------------------------------------
Binary file
@@ -12,6 +12,8 @@ from http.client import responses as reason_phrases
12
12
  from urllib.parse import urlencode, urljoin, urlsplit, urlunsplit
13
13
  from urllib.request import getproxies
14
14
 
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
15
17
  from tls_client import exceptions
16
18
  from tls_client import _multipart_boundary
17
19
  from tls_client.auth import HTTPBasicAuth
@@ -20,6 +22,7 @@ from tls_client.hooks import default_hooks, dispatch_hook, merge_hooks
20
22
  from tls_client.structures import CaseInsensitiveDict
21
23
  from tls_client._core import Session as NativeSession, SUPPORTED_CLIENT_IDENTIFIERS
22
24
  from tls_client._core import _load_client_certificates, _resolve_proxy_url
25
+ from tls_client._core import ClientIdentifiers, ProxyConfig
23
26
 
24
27
 
25
28
  REDIRECT_STATI = (301, 302, 303, 307, 308)
@@ -403,7 +406,172 @@ def _encoding_from_headers(headers):
403
406
 
404
407
 
405
408
  class Session(object):
406
- def __init__(self, **options):
409
+ def __init__(
410
+ self,
411
+ *,
412
+ # ── 指纹 / 协议 ── / Fingerprint / Protocol ──
413
+ client_identifier: ClientIdentifiers = "chrome_120",
414
+ force_http1: bool = False,
415
+ disable_http3: bool = False,
416
+ with_protocol_racing: bool = False,
417
+ random_tls_extension_order: bool = True,
418
+ # ── 超时 / 重定向 ── / Timeout / Redirect ──
419
+ timeout: int = 30,
420
+ timeout_milliseconds: int = 0,
421
+ follow_redirects: bool = False,
422
+ # ── TLS / 证书 ── / TLS / Cert ──
423
+ verify: bool = True,
424
+ server_name_overwrite: Optional[str] = None,
425
+ # ── 代理 ── / Proxy ──
426
+ proxy: Optional[ProxyConfig] = None,
427
+ proxies: Optional[ProxyConfig] = None,
428
+ local_address: Optional[str] = None,
429
+ # ── 请求头控制 ── / Header Control ──
430
+ request_host_override: Optional[str] = None,
431
+ pseudo_header_order: Optional[List[str]] = None,
432
+ h3_pseudo_header_order: Optional[List[str]] = None,
433
+ default_headers: Optional[Dict[str, str]] = None,
434
+ headers: Optional[Dict[str, str]] = None,
435
+ connect_headers: Optional[Dict[str, str]] = None,
436
+ # ── 证书固定 ── / Certificate Pinning ──
437
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]] = None,
438
+ with_default_bad_pin_handler: bool = False,
439
+ # ── Cookie ──
440
+ request_cookies: Optional[Dict[str, str]] = None,
441
+ cookies: Optional[Dict[str, str]] = None,
442
+ # ── 自定义 TLS ── / Custom TLS ──
443
+ custom_tls_client: Optional[Dict[str, Any]] = None,
444
+ client_certificates: Optional[List[Dict[str, bytes]]] = None,
445
+ # ── 连接池调优 ── / Connection Pool Tuning ──
446
+ max_idle_connections: int = 0,
447
+ max_idle_connections_per_host: int = 0,
448
+ max_connections_per_host: int = 0,
449
+ disable_keep_alives: bool = False,
450
+ disable_compression: bool = False,
451
+ idle_conn_timeout_seconds: int = 0,
452
+ max_response_header_bytes: int = 0,
453
+ write_buffer_size: int = 0,
454
+ read_buffer_size: int = 0,
455
+ # ── IP 协议栈控制 ── / IP Stack Control ──
456
+ disable_ipv4: bool = False,
457
+ disable_ipv6: bool = False,
458
+ # ── TCP/IP Fingerprint ──
459
+ tcp_ttl: int = 0,
460
+ tcp_window_size: int = 0,
461
+ tcp_window_scale: int = 0,
462
+ tcp_mss: int = 0,
463
+ # ── Cookie ──
464
+ allow_empty_cookies: bool = False,
465
+ without_cookie_jar: bool = False,
466
+ # ── requests 兼容属性 ── / requests-compatible ──
467
+ auth: Optional[Tuple[str, str]] = None,
468
+ params: Optional[Dict[str, str]] = None,
469
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
470
+ stream: bool = False,
471
+ # ── 调试 / 安全 ── / Debug / Safety ──
472
+ catch_panics: bool = True,
473
+ with_debug: bool = False,
474
+ disable_session_tickets: bool = False,
475
+ tls_keylog_path: Optional[str] = None,
476
+ root_ca_pem: Optional[bytes] = None,
477
+ h2_max_data_frame_size: int = 0,
478
+ preface_ping_idle_ms: int = 0,
479
+ hpack_indexing_policy: str = "",
480
+ cookie_crumb: bool = False,
481
+ # ── ABI 3 — 细粒度指纹控制 ── / fine-grained fingerprint control ──
482
+ extension_permute_mode: int = 0,
483
+ extension_permute_prefix: int = 0,
484
+ h2_disable_priority_frames: bool = False,
485
+ header_order_by_dest: bool = False,
486
+ header_order_dest: Optional[str] = None,
487
+ tcp_dont_fragment: int = -1,
488
+ tcp_tos: int = -1,
489
+ tcp_no_delay: int = -1,
490
+ tcp_window_clamp: int = 0,
491
+ tcp_ip_id_mode: str = "",
492
+ fingerprint: Optional[str] = None,
493
+ # ── requests-compat 专属 ── / requests-compat only ──
494
+ hooks: Optional[Dict[str, Any]] = None,
495
+ max_redirects: int = 30,
496
+ trust_env: bool = True,
497
+ **kwargs,
498
+ ) -> None:
499
+ # Fold the explicitly-typed parameters back into a single options dict
500
+ # so the remainder of this method (unchanged) sees them exactly as it
501
+ # did before the signature was typed. ``**kwargs`` still admits any
502
+ # extra native options passed programmatically.
503
+ options = dict(kwargs)
504
+ options.update({
505
+ "client_identifier": client_identifier,
506
+ "force_http1": force_http1,
507
+ "disable_http3": disable_http3,
508
+ "with_protocol_racing": with_protocol_racing,
509
+ "random_tls_extension_order": random_tls_extension_order,
510
+ "timeout": timeout,
511
+ "timeout_milliseconds": timeout_milliseconds,
512
+ "follow_redirects": follow_redirects,
513
+ "verify": verify,
514
+ "server_name_overwrite": server_name_overwrite,
515
+ "proxy": proxy,
516
+ "proxies": proxies,
517
+ "local_address": local_address,
518
+ "request_host_override": request_host_override,
519
+ "pseudo_header_order": pseudo_header_order,
520
+ "h3_pseudo_header_order": h3_pseudo_header_order,
521
+ "default_headers": default_headers,
522
+ "headers": headers,
523
+ "connect_headers": connect_headers,
524
+ "certificate_pinning_hosts": certificate_pinning_hosts,
525
+ "with_default_bad_pin_handler": with_default_bad_pin_handler,
526
+ "request_cookies": request_cookies,
527
+ "cookies": cookies,
528
+ "custom_tls_client": custom_tls_client,
529
+ "client_certificates": client_certificates,
530
+ "max_idle_connections": max_idle_connections,
531
+ "max_idle_connections_per_host": max_idle_connections_per_host,
532
+ "max_connections_per_host": max_connections_per_host,
533
+ "disable_keep_alives": disable_keep_alives,
534
+ "disable_compression": disable_compression,
535
+ "idle_conn_timeout_seconds": idle_conn_timeout_seconds,
536
+ "max_response_header_bytes": max_response_header_bytes,
537
+ "write_buffer_size": write_buffer_size,
538
+ "read_buffer_size": read_buffer_size,
539
+ "disable_ipv4": disable_ipv4,
540
+ "disable_ipv6": disable_ipv6,
541
+ "tcp_ttl": tcp_ttl,
542
+ "tcp_window_size": tcp_window_size,
543
+ "tcp_window_scale": tcp_window_scale,
544
+ "tcp_mss": tcp_mss,
545
+ "allow_empty_cookies": allow_empty_cookies,
546
+ "without_cookie_jar": without_cookie_jar,
547
+ "auth": auth,
548
+ "params": params,
549
+ "cert": cert,
550
+ "stream": stream,
551
+ "catch_panics": catch_panics,
552
+ "with_debug": with_debug,
553
+ "disable_session_tickets": disable_session_tickets,
554
+ "tls_keylog_path": tls_keylog_path,
555
+ "root_ca_pem": root_ca_pem,
556
+ "h2_max_data_frame_size": h2_max_data_frame_size,
557
+ "preface_ping_idle_ms": preface_ping_idle_ms,
558
+ "hpack_indexing_policy": hpack_indexing_policy,
559
+ "cookie_crumb": cookie_crumb,
560
+ "extension_permute_mode": extension_permute_mode,
561
+ "extension_permute_prefix": extension_permute_prefix,
562
+ "h2_disable_priority_frames": h2_disable_priority_frames,
563
+ "header_order_by_dest": header_order_by_dest,
564
+ "header_order_dest": header_order_dest,
565
+ "tcp_dont_fragment": tcp_dont_fragment,
566
+ "tcp_tos": tcp_tos,
567
+ "tcp_no_delay": tcp_no_delay,
568
+ "tcp_window_clamp": tcp_window_clamp,
569
+ "tcp_ip_id_mode": tcp_ip_id_mode,
570
+ "fingerprint": fingerprint,
571
+ "hooks": hooks,
572
+ "max_redirects": max_redirects,
573
+ "trust_env": trust_env,
574
+ })
407
575
  requested_identifier = options.get("client_identifier", "chrome_120")
408
576
  if requested_identifier not in SUPPORTED_CLIENT_IDENTIFIERS:
409
577
  raise ValueError("unsupported client_identifier %r" % requested_identifier)
@@ -660,15 +828,7 @@ def delete(url, **kwargs):
660
828
  return request("DELETE", url, **kwargs)
661
829
 
662
830
 
663
- # ``Session`` intentionally keeps a ``**options`` implementation so Requests
664
- # attributes can be normalised before constructing the native client. Expose
665
- # the complete native keyword signature to inspect(), IDEs and ``help()`` so
666
- # TLS controls are discoverable at the public top level as well.
667
- _session_signature = inspect.signature(NativeSession)
668
- _session_parameters = list(_session_signature.parameters.values())
669
- _session_parameters.extend([
670
- inspect.Parameter("hooks", inspect.Parameter.KEYWORD_ONLY, default=None),
671
- inspect.Parameter("max_redirects", inspect.Parameter.KEYWORD_ONLY, default=30),
672
- inspect.Parameter("trust_env", inspect.Parameter.KEYWORD_ONLY, default=True),
673
- ])
674
- Session.__signature__ = _session_signature.replace(parameters=_session_parameters)
831
+ # ``Session.__init__`` now declares the full native keyword signature directly
832
+ # (plus the requests-only ``hooks``/``max_redirects``/``trust_env`` extras), so
833
+ # both IDEs and ``inspect.signature()``/``help()`` see every TLS control without
834
+ # needing the ``__signature__`` shim that ``**options`` previously required.
@@ -0,0 +1,243 @@
1
+ """TLS-fingerprinted WebSocket client (native Go engine).
2
+
3
+ Builds on the same ``tls-client`` Go engine as :mod:`tls_client` so a
4
+ WebSocket handshake carries the identical TLS fingerprint, HTTP/2 → HTTP/1.1
5
+ upgrade headers and connection pool settings as regular HTTP requests.
6
+
7
+ WebSocket requires HTTP/1.1, so the underlying fingerprint client is always
8
+ created with ``force_http1``.
9
+
10
+ Example::
11
+
12
+ from tls_client import WebSocket
13
+
14
+ ws = WebSocket(url="wss://echo.websocket.events", client_identifier="chrome_131")
15
+ conn = ws.connect()
16
+ conn.send_text("hello")
17
+ message_type, data = conn.read_message()
18
+ conn.close()
19
+ ws.close()
20
+ """
21
+
22
+ from typing import Dict, List, Optional, Tuple
23
+
24
+ import tls_client._core as _core
25
+
26
+ # Message type codes — mirror the Go `github.com/bogdanfinn/websocket` package.
27
+ TEXT = 1
28
+ BINARY = 2
29
+ CLOSE = 8
30
+ PING = 9
31
+ PONG = 10
32
+
33
+
34
+ def _read_error(ffi, lib, err_ptr) -> str:
35
+ """Drain a ``char**`` out-param into a Python string, freeing the C buffer."""
36
+ if err_ptr[0] == ffi.NULL:
37
+ return "unknown error"
38
+ message = ffi.string(err_ptr[0]).decode("utf-8", errors="replace")
39
+ lib.FreeCString(err_ptr[0])
40
+ err_ptr[0] = ffi.NULL
41
+ return message
42
+
43
+
44
+ class WebSocketConnection:
45
+ """A live, TLS-fingerprinted WebSocket connection.
46
+
47
+ Returned by :meth:`WebSocket.connect`. Use :meth:`send_text` /
48
+ :meth:`send_binary` to write frames and :meth:`read_message` to read the
49
+ next frame (blocking).
50
+ """
51
+
52
+ def __init__(self, conn_id: int) -> None:
53
+ self._conn_id = conn_id
54
+ self._closed = False
55
+
56
+ @property
57
+ def closed(self) -> bool:
58
+ """``True`` once the connection has been closed."""
59
+ return self._closed
60
+
61
+ def read_message(self) -> Optional[Tuple[int, bytes]]:
62
+ """Block until the next message arrives.
63
+
64
+ Returns a ``(message_type, data)`` tuple. ``message_type`` is one of
65
+ :data:`TEXT` / :data:`BINARY` / :data:`PING` / :data:`PONG` / etc.;
66
+ ``data`` is the raw payload bytes. Returns ``None`` when the peer
67
+ closes the connection cleanly.
68
+
69
+ Raises :class:`RuntimeError` on a transport error.
70
+ """
71
+ if self._closed:
72
+ raise RuntimeError("websocket connection is closed")
73
+ ffi, lib = _core._get_ffi()
74
+ err = ffi.new("char **")
75
+ msg = lib.WebsocketReadMessage(self._conn_id, err)
76
+ if msg == ffi.NULL:
77
+ raise RuntimeError("websocket read failed: %s" % _read_error(ffi, lib, err))
78
+ try:
79
+ message_type = int(msg.message_type)
80
+ if msg.data != ffi.NULL and int(msg.data_len) > 0:
81
+ data = ffi.buffer(msg.data, int(msg.data_len))[:]
82
+ else:
83
+ data = b""
84
+ return message_type, data
85
+ finally:
86
+ lib.WebsocketFreeMessage(msg)
87
+
88
+ def send(self, data, message_type: int = TEXT) -> None:
89
+ """Send one frame. ``data`` may be ``str`` (UTF-8) or ``bytes``."""
90
+ if self._closed:
91
+ raise RuntimeError("websocket connection is closed")
92
+ if isinstance(data, str):
93
+ data = data.encode("utf-8")
94
+ ffi, lib = _core._get_ffi()
95
+ buf = ffi.from_buffer(data) if data else ffi.NULL
96
+ err = ffi.new("char **")
97
+ ret = lib.WebsocketWriteMessage(self._conn_id, message_type, buf, len(data), err)
98
+ if ret != 0:
99
+ raise RuntimeError("websocket send failed: %s" % _read_error(ffi, lib, err))
100
+
101
+ def send_text(self, data) -> None:
102
+ """Send a UTF-8 text frame."""
103
+ self.send(data, TEXT)
104
+
105
+ def send_binary(self, data: bytes) -> None:
106
+ """Send a binary frame."""
107
+ self.send(data, BINARY)
108
+
109
+ def close(self) -> None:
110
+ """Close the underlying connection (idempotent)."""
111
+ if self._closed:
112
+ return
113
+ ffi, lib = _core._get_ffi()
114
+ err = ffi.new("char **")
115
+ lib.WebsocketClose(self._conn_id, err)
116
+ lib.WebsocketFreeHandle(self._conn_id)
117
+ self._conn_id = 0
118
+ self._closed = True
119
+
120
+ def __enter__(self) -> "WebSocketConnection":
121
+ return self
122
+
123
+ def __exit__(self, *exc) -> bool:
124
+ self.close()
125
+ return False
126
+
127
+ def __del__(self) -> None:
128
+ try:
129
+ self.close()
130
+ except Exception:
131
+ pass
132
+
133
+
134
+ class WebSocket:
135
+ """A TLS-fingerprinted WebSocket client.
136
+
137
+ Parameters mirror the native Go ``NewWebsocket`` + ``WithTlsClient``
138
+ options. The fingerprint client is created from ``client_identifier``
139
+ (always with HTTP/1.1, as WebSocket requires).
140
+
141
+ Parameters
142
+ ----------
143
+ url:
144
+ WebSocket URL (``ws://`` or ``wss://``). Required.
145
+ client_identifier:
146
+ TLS fingerprint identifier — one of
147
+ :data:`tls_client.ClientIdentifiers`.
148
+ headers:
149
+ Extra handshake headers (e.g. ``User-Agent``, ``Origin``).
150
+ header_order:
151
+ Ordered list of header names controlling the wire order.
152
+ read_buffer_size / write_buffer_size:
153
+ Per-frame buffer sizes (0 = engine default).
154
+ handshake_timeout_milliseconds:
155
+ Handshake timeout (0 = engine default).
156
+ """
157
+
158
+ def __init__(
159
+ self,
160
+ *,
161
+ url: str,
162
+ client_identifier: str = "chrome_120",
163
+ headers: Optional[Dict[str, str]] = None,
164
+ header_order: Optional[List[str]] = None,
165
+ read_buffer_size: int = 0,
166
+ write_buffer_size: int = 0,
167
+ handshake_timeout_milliseconds: int = 0,
168
+ ) -> None:
169
+ if client_identifier not in _core.SUPPORTED_CLIENT_IDENTIFIERS:
170
+ raise ValueError("unsupported client_identifier %r" % client_identifier)
171
+
172
+ ffi, lib = _core._get_ffi()
173
+ keep_alive = []
174
+ opts = ffi.new("WebsocketOptions *")
175
+ keep_alive.append(opts)
176
+
177
+ c_url = _core._c_string(ffi, url)
178
+ keep_alive.append(c_url)
179
+ opts.url = c_url
180
+
181
+ c_ci = _core._c_string(ffi, client_identifier)
182
+ keep_alive.append(c_ci)
183
+ opts.client_identifier = c_ci
184
+
185
+ opts.force_http1 = 1
186
+
187
+ hdr_ptr, hdr_len = _core._build_headers(ffi, headers, keep_alive)
188
+ opts.headers = hdr_ptr
189
+ opts.headers_len = hdr_len
190
+
191
+ ho_ptr, ho_len = _core._build_string_array(ffi, header_order, keep_alive)
192
+ opts.header_order = ho_ptr
193
+ opts.header_order_len = ho_len
194
+
195
+ opts.read_buffer_size = read_buffer_size
196
+ opts.write_buffer_size = write_buffer_size
197
+ opts.handshake_timeout_milliseconds = handshake_timeout_milliseconds
198
+
199
+ err = ffi.new("char **")
200
+ ws_id = lib.WebsocketNew(opts, err)
201
+ if ws_id == 0:
202
+ raise RuntimeError("failed to create websocket: %s" % _read_error(ffi, lib, err))
203
+
204
+ self._ws_id = ws_id
205
+ self._closed = False
206
+
207
+ @property
208
+ def closed(self) -> bool:
209
+ """``True`` once this client has been released."""
210
+ return self._closed
211
+
212
+ def connect(self) -> WebSocketConnection:
213
+ """Open the WebSocket connection (blocking handshake)."""
214
+ if self._closed:
215
+ raise RuntimeError("websocket is closed")
216
+ ffi, lib = _core._get_ffi()
217
+ err = ffi.new("char **")
218
+ conn_id = lib.WebsocketConnect(self._ws_id, err)
219
+ if conn_id == 0:
220
+ raise RuntimeError("websocket connect failed: %s" % _read_error(ffi, lib, err))
221
+ return WebSocketConnection(conn_id)
222
+
223
+ def close(self) -> None:
224
+ """Release the client handle (idempotent)."""
225
+ if self._closed:
226
+ return
227
+ ffi, lib = _core._get_ffi()
228
+ lib.WebsocketFreeHandle(self._ws_id)
229
+ self._ws_id = 0
230
+ self._closed = True
231
+
232
+ def __enter__(self) -> "WebSocket":
233
+ return self
234
+
235
+ def __exit__(self, *exc) -> bool:
236
+ self.close()
237
+ return False
238
+
239
+ def __del__(self) -> None:
240
+ try:
241
+ self.close()
242
+ except Exception:
243
+ pass
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tls-client-python
3
- Version: 1.16.0.2
3
+ Version: 1.16.0.4
4
4
  Summary: High-performance Python binding for bogdanfinn/tls-client via CFFI – zero-copy, panic-proof, full TLS fingerprint control
5
5
  Author: komAAmok
6
6
  License-Expression: MIT
@@ -72,6 +72,7 @@ For a deep dive, see [this excellent article on TLS fingerprinting](https://http
72
72
  | 🔀 **Redirect Control** | Choose whether to follow redirects per request |
73
73
  | 📊 **Bandwidth Tracking** | Monitor upload/download bytes in real time |
74
74
  | 🔄 **sync/Async** | `Session` + `AsyncSession` |
75
+ | 🔌 **WebSocket** | TLS-fingerprinted WebSocket (HTTP/1.1 handshake) — `WebSocket` |
75
76
  | 🛡️ **Panic-proof** | All Go panics caught and surfaced as Python exceptions |
76
77
  | ⚙️ **Custom TLS** | Full 26-field custom TLS client configuration |
77
78
  | 🔬 **Chrome 99–153 Captures** | Byte-exact profiles for **every** Chrome major 99…153, recovered from live handshakes |
@@ -493,6 +494,42 @@ session = Session()
493
494
  apply(session, "chrome_150_linux") # identifier + headers + permute + TCP
494
495
  ```
495
496
 
497
+ ### WebSocket (TLS-fingerprinted)
498
+
499
+ WebSocket connections reuse the same TLS fingerprint, connection pool and
500
+ header ordering as regular requests. The handshake is forced to HTTP/1.1
501
+ (as the WebSocket upgrade requires it).
502
+
503
+ ```python
504
+ from tls_client import WebSocket, TEXT, BINARY
505
+
506
+ # The fingerprint client is created from client_identifier (HTTP/1.1 enforced).
507
+ ws = WebSocket(url="wss://echo.websocket.events", client_identifier="chrome_131")
508
+
509
+ conn = ws.connect() # blocking handshake
510
+ conn.send_text("hello") # UTF-8 text frame
511
+ conn.send_binary(b"\x00\x01\x02") # binary frame
512
+
513
+ message_type, data = conn.read_message() # (TEXT=1, b"...") — blocks
514
+
515
+ conn.close()
516
+ ws.close()
517
+ ```
518
+
519
+ `read_message()` returns a `(message_type, data)` tuple where `message_type` is
520
+ one of `TEXT`/`BINARY`/`CLOSE`/`PING`/`PONG`; it returns `None` on a clean
521
+ close. Handshake headers and their wire order are controllable:
522
+
523
+ ```python
524
+ ws = WebSocket(
525
+ url="wss://example.com/ws",
526
+ client_identifier="firefox_148",
527
+ headers={"User-Agent": "MyBot/1.0", "Origin": "https://example.com"},
528
+ header_order=["host", "upgrade", "connection", "user-agent"],
529
+ handshake_timeout_milliseconds=10000,
530
+ )
531
+ ```
532
+
496
533
  ### Build Tiers
497
534
 
498
535
  A single full-fidelity build ships in each wheel — QUIC/HTTP-3 enabled and
@@ -1,6 +1,6 @@
1
- tls_client/__init__.py,sha256=ZekQGOQTjzgc9ulEJV03u5__aeuGdclbfj157JhxPVI,1907
1
+ tls_client/__init__.py,sha256=dRYD_OcjEjGQO3zlAuWyZ3n_nRMwLVuOYMRAkTTv0Ng,2144
2
2
  tls_client/_client_hints.py,sha256=ERF_5N-ivpAO66rYKk9hlfefppp8DAwCnyeYOviGmJU,5374
3
- tls_client/_core.py,sha256=7J8wSyhtZJqWtrawuwxarSxR7VcsGK79-2jPmSTtY_o,194334
3
+ tls_client/_core.py,sha256=pVI4StrXR6HUdleht6uJ00hFnbvz8I9oFYVXylQMBqo,198839
4
4
  tls_client/_default_headers.py,sha256=pgPAnQ42ZVF2gQfhkmvir6IztQa5iXONPVa4ABtAdtQ,21621
5
5
  tls_client/_multipart_boundary.py,sha256=Bsc1UUE46aeVNZYf24ItwDxVM-bu6RTaCR3SPdISvJU,1929
6
6
  tls_client/adapters.py,sha256=f6HNcM6ET-MOOsacm1YzzODBBsvXEUuusps4Zv1apsM,198
@@ -12,17 +12,18 @@ tls_client/exceptions.py,sha256=UqrF5zjJ7ZXTHXuRWCdylQKX5PSnrNAzsoiDIa-RYq4,1484
12
12
  tls_client/hooks.py,sha256=VyFW1qpv-syy8N7s8VGO-LCJkkn1SM_mfDIrEFrsZ34,752
13
13
  tls_client/models.py,sha256=cauaeREtRzIl64AeLCNvwF4JQ5tC7rt89LheupNy6xU,172
14
14
  tls_client/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
- tls_client/requests_compat.py,sha256=t4f2_d_AQ4aQzPwYMPMnOdiVzzVja5FHQBHi1im_aI0,26737
15
+ tls_client/requests_compat.py,sha256=rZ579loLWVc8TvG0WKhMQic3o_X9eXOmEB1aNLVtlEc,34203
16
16
  tls_client/status_codes.py,sha256=eT2h4THZpR5nWK02DIxh0fw4000bWBX38UM8W0FsrhM,1301
17
17
  tls_client/structures.py,sha256=Lk4TDTJSzJ5GMyLGaGpxNUi56_ieTiHVZKnREHq803M,1639
18
- tls_client/bin/tls-client-windows-386.dll,sha256=Qhyg5SiW97ky5-oGOLfj3jsR15PsEf1GLq_mNge2gf4,12187136
18
+ tls_client/websocket.py,sha256=AIqNy0Xlwo45GYIzXB9e1j4ooOlvvDSNXWxW8vTtfoU,7882
19
+ tls_client/bin/tls-client-windows-386.dll,sha256=REuwpG2VT-9NC1aEDo2ygbjokK0qNem3VIgI-oOQLUE,12335104
19
20
  tls_client/fingerprints/__init__.py,sha256=tgG2rkUktnYtAw640tNRXHJVt1XKgRYC9q6H3wmdt6Q,1515
20
21
  tls_client/fingerprints/chrome.py,sha256=nhb2xH9SOml0Qm6YNigsctcYw7xZEu5xkjX-tcIigoA,5491
21
22
  tls_client/fingerprints/chrome_full.py,sha256=qsXi872HqdA6LcL29ooCbH4vU0Vr6VpzEDwWQu0a3YQ,448925
22
23
  tls_client/fingerprints/firefox.py,sha256=52c9pz90RTO0i40pjn8liC79fyCrzhVw0yEzQhTO2h4,3403
23
24
  tls_client/fingerprints/registry.py,sha256=myd9kGJY1Q1wFzXfxsRr3k5ixV7pQ8VZBntutqtCIBU,6954
24
- tls_client_python-1.16.0.2.dist-info/licenses/LICENSE,sha256=fauaTdZph_vldtU8HuBHwZNyXfb0-sZ94xWhJ0F_0VE,1662
25
- tls_client_python-1.16.0.2.dist-info/METADATA,sha256=lHiWPmGOXIcK-_CSA6B6tdSp6z248WmxHX8v53TfCSg,23232
26
- tls_client_python-1.16.0.2.dist-info/WHEEL,sha256=xksbYFdeOfRRyIBZRG9ZLgVTxOiHRgNaQRB0KP_rWuE,93
27
- tls_client_python-1.16.0.2.dist-info/top_level.txt,sha256=yLrfQtbTRfECzPN62knWdGNmbhcPRev1grCAMuEsEz0,11
28
- tls_client_python-1.16.0.2.dist-info/RECORD,,
25
+ tls_client_python-1.16.0.4.dist-info/licenses/LICENSE,sha256=fauaTdZph_vldtU8HuBHwZNyXfb0-sZ94xWhJ0F_0VE,1662
26
+ tls_client_python-1.16.0.4.dist-info/METADATA,sha256=VSPx8VvLJGUFYIEUbDlxQunIGFmouMHljlYg5VOeZl8,24556
27
+ tls_client_python-1.16.0.4.dist-info/WHEEL,sha256=xksbYFdeOfRRyIBZRG9ZLgVTxOiHRgNaQRB0KP_rWuE,93
28
+ tls_client_python-1.16.0.4.dist-info/top_level.txt,sha256=yLrfQtbTRfECzPN62knWdGNmbhcPRev1grCAMuEsEz0,11
29
+ tls_client_python-1.16.0.4.dist-info/RECORD,,