@jayyuen66/dsh-scrapling 0.0.1-rc → 0.0.1-rc.2
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.
- package/README.md +128 -11
- package/README.zh-CN.md +93 -7
- package/client.js +846 -1
- package/host.js +13 -10
- package/package.json +1 -1
- package/py/adapters.py +132 -9
- package/py/crawl.py +30 -7
- package/py/guard.py +510 -7
package/py/guard.py
CHANGED
|
@@ -22,7 +22,8 @@ import ipaddress
|
|
|
22
22
|
import re
|
|
23
23
|
import socket
|
|
24
24
|
from collections.abc import Iterable
|
|
25
|
-
from
|
|
25
|
+
from typing import Any
|
|
26
|
+
from urllib.parse import unquote, urlparse
|
|
26
27
|
|
|
27
28
|
# 放行的额外主机名。默认空 —— 只有字面量公网 IP 与解析到公网的域名能过。
|
|
28
29
|
ALLOWED_HOSTS: frozenset[str] = frozenset()
|
|
@@ -46,6 +47,61 @@ ALLOWED_HOSTS_ENV = "DSH_SCRAPLING_ALLOWED_HOSTS"
|
|
|
46
47
|
# 判定表——不声明时,藏在运营商自建前缀里的私网 IPv4 会被当成公网放行。
|
|
47
48
|
NAT64_PREFIXES_ENV = "DSH_SCRAPLING_NAT64_PREFIXES"
|
|
48
49
|
|
|
50
|
+
# 放行「代理软件合成的 DNS 答案」的环境变量。默认不设 ⇒ 自动判定,判定不出来时最严。
|
|
51
|
+
#
|
|
52
|
+
# fake-IP 模式的代理不返回真实地址:每个域名都落进 198.18.0.0/15(RFC 2544 基准测试段),
|
|
53
|
+
# 另一批客户端落在 100.64.0.0/10(CGNAT)。Python 的 ipaddress 把两段都算 is_private,
|
|
54
|
+
# 于是守卫会把**每一个** URL 判否——开了代理反而全都抓不了。自动识别认出这一类解析器后
|
|
55
|
+
# 才放宽;列在环境变量里的是识别失灵时的手动兜底。放宽只对**解析结果**生效:URL 里写死
|
|
56
|
+
# 的 IP 字面量照旧严格判定。
|
|
57
|
+
SYNTHETIC_RANGES_ENV = "DSH_SCRAPLING_SYNTHETIC_RANGES"
|
|
58
|
+
|
|
59
|
+
# 抓取走的代理地址与它的绕过清单,逗号分隔的清单项形如 NO_PROXY。判定顺序是
|
|
60
|
+
# 「设置卡 proxyUrl → 环境里的代理变量 → 操作系统代理设置 → 直连」,详见
|
|
61
|
+
# :func:`proxy_for`。
|
|
62
|
+
PROXY_ENV = "DSH_SCRAPLING_PROXY"
|
|
63
|
+
PROXY_BYPASS_ENV = "DSH_SCRAPLING_PROXY_BYPASS"
|
|
64
|
+
|
|
65
|
+
# 手动追加的合成段(CIDR)。默认空 —— 自动检测是主路径。
|
|
66
|
+
SYNTHETIC_NETWORKS: tuple[ipaddress.IPv4Network, ...] = ()
|
|
67
|
+
|
|
68
|
+
# 抓取走的代理(部署设置)。留空表示依次跟随环境里的代理变量与操作系统的代理设置。
|
|
69
|
+
PROXY_URL = ""
|
|
70
|
+
|
|
71
|
+
# 不走代理的主机名(逗号分隔,对应 NO_PROXY)。命中时该请求直连。
|
|
72
|
+
PROXY_BYPASS = ""
|
|
73
|
+
|
|
74
|
+
# 环境里的代理变量与绕过清单,启动时快照一次。进程生命周期内环境不会变,而每次请求
|
|
75
|
+
# 都重新扫一遍 os.environ 在浏览器抓取(每个子资源都过一次守卫)下并不便宜。
|
|
76
|
+
_ENV_PROXIES: dict[str, str] = {}
|
|
77
|
+
_ENV_BYPASS: tuple[str, ...] = ()
|
|
78
|
+
|
|
79
|
+
# 操作系统「系统代理」设置里读出来的全局代理,同样只在启动时取一次。macOS 的代理软件
|
|
80
|
+
# (Clash Verge / Surge / Shadowrocket 等)默认就走这一档:它们把代理写进系统网络设置,
|
|
81
|
+
# 浏览器全部自动跟随,而 curl_cffi 只读环境变量、对它一无所知 —— 不补这一档,「开了
|
|
82
|
+
# 代理」的用户就会发现本插件的静态抓取在必须代理的网络上一个 URL 都抓不到。
|
|
83
|
+
_SYSTEM_PROXIES: dict[str, str] = {}
|
|
84
|
+
|
|
85
|
+
# 系统代理是 PAC(自动配置脚本)时记下这一条。PAC 要下载脚本并求值,各平台格式互不相同,
|
|
86
|
+
# 本包不猜;遇到它就在 stderr 点一句,让用户知道该手填 proxyUrl,而不是看到一个
|
|
87
|
+
# 「明明开了系统代理却不走」的静默行为。
|
|
88
|
+
_PAC_NOTICE = ""
|
|
89
|
+
|
|
90
|
+
# 设置与环境的绕过清单合并后的结果,同样只在启动时算一次。
|
|
91
|
+
_BYPASS_ENTRIES: tuple[str, ...] = ()
|
|
92
|
+
|
|
93
|
+
# Playwright 认识的代理协议。与 Scrapling 的 construct_proxy_dict 取同一份清单。
|
|
94
|
+
# socks5h 是 libcurl 的写法(由代理去解析域名,不在本地泄漏 DNS);Chromium 的 SOCKS5
|
|
95
|
+
# 本来就把解析放在代理侧,所以浏览器那份折成 socks5,curl 那份保留 socks5h。
|
|
96
|
+
_PROXY_SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
|
|
97
|
+
_BROWSER_PROXY_SCHEMES = ("http", "https", "socks4", "socks5")
|
|
98
|
+
|
|
99
|
+
# Chromium 的 WebRTC 会绕过 HTTP/SOCKS 代理直接发 UDP,于是页面里一句 STUN 就能问出
|
|
100
|
+
# 访客的真实出口 IP —— 对「我要走代理」的部署方来说,那等于代理白配。这条 flag 让
|
|
101
|
+
# 非代理 UDP 一律不走;Playwright 不暴露对应开关(patchright 那边有 block_webrtc),
|
|
102
|
+
# 只能从启动参数进去。
|
|
103
|
+
WEBRTC_NO_LEAK_FLAG = "--force-webrtc-ip-handling-policy=disable_non_proxied_udp"
|
|
104
|
+
|
|
49
105
|
# 额外的 NAT64 前缀(CIDR 字符串)。IPv6 地址命中其中之一时,会抽出内嵌 IPv4 复判;
|
|
50
106
|
# 运营商自建前缀必须在这里声明,否则藏在 IPv6 里的私网 IPv4 会被当成公网放行。
|
|
51
107
|
EXTRA_NAT64_PREFIXES: tuple[str, ...] = ()
|
|
@@ -73,9 +129,10 @@ def configure(allowed_hosts=None, allowed_ports=None, nat64_prefixes=None) -> No
|
|
|
73
129
|
|
|
74
130
|
|
|
75
131
|
def configure_from_env() -> None:
|
|
76
|
-
"""
|
|
132
|
+
"""从环境变量读放行主机名、额外 NAT64 前缀、合成段与代理设置,供启动时调用。
|
|
77
133
|
|
|
78
|
-
|
|
134
|
+
变量都是逗号分隔;未设置或为空则保持最严。环境里的代理变量与 NO_PROXY 在这里快照成
|
|
135
|
+
模块级状态(:func:`proxy_for` 每个请求都要读一次,不适合每次现扫环境)。
|
|
79
136
|
"""
|
|
80
137
|
import os
|
|
81
138
|
|
|
@@ -89,6 +146,373 @@ def configure_from_env() -> None:
|
|
|
89
146
|
if prefixes:
|
|
90
147
|
configure(nat64_prefixes=prefixes)
|
|
91
148
|
|
|
149
|
+
global SYNTHETIC_NETWORKS, PROXY_URL, PROXY_BYPASS, _BYPASS_ENTRIES # noqa: PLW0603 —— 启动时定一次
|
|
150
|
+
global _ENV_PROXIES, _ENV_BYPASS, _SYSTEM_PROXIES, _PAC_NOTICE # noqa: PLW0603 —— 同上
|
|
151
|
+
networks = []
|
|
152
|
+
for item in os.environ.get(SYNTHETIC_RANGES_ENV, "").split(","):
|
|
153
|
+
text = item.strip()
|
|
154
|
+
if text:
|
|
155
|
+
try:
|
|
156
|
+
networks.append(ipaddress.ip_network(text))
|
|
157
|
+
except ValueError:
|
|
158
|
+
continue
|
|
159
|
+
SYNTHETIC_NETWORKS = tuple(networks)
|
|
160
|
+
PROXY_URL = os.environ.get(PROXY_ENV, "").strip()
|
|
161
|
+
PROXY_BYPASS = os.environ.get(PROXY_BYPASS_ENV, "").strip()
|
|
162
|
+
_ENV_PROXIES, _ENV_BYPASS = _snapshot_env_proxies()
|
|
163
|
+
_SYSTEM_PROXIES, _PAC_NOTICE = _read_system_proxies()
|
|
164
|
+
_BYPASS_ENTRIES = (
|
|
165
|
+
*(item.strip() for item in PROXY_BYPASS.split(",") if item.strip()),
|
|
166
|
+
*_ENV_BYPASS,
|
|
167
|
+
)
|
|
168
|
+
if PROXY_URL and split_proxy(PROXY_URL) is None:
|
|
169
|
+
# 不抛:抛出去 sidecar 直接起不来,用户看到的只是「插件加载失败」,看不出是自己
|
|
170
|
+
# 填错了一个地址。记一行指向明确的日志,让侧栏里的能力摘要照实报成未配置。
|
|
171
|
+
_log(f"ignoring an unusable {PROXY_ENV}: {PROXY_URL!r} (scheme must be one of {_PROXY_SCHEMES})")
|
|
172
|
+
PROXY_URL = ""
|
|
173
|
+
if _PAC_NOTICE:
|
|
174
|
+
_log(
|
|
175
|
+
f"system proxy is a PAC script ({_PAC_NOTICE}); it is not evaluated here — "
|
|
176
|
+
f"set {PROXY_ENV} (the settings card's proxy) to the proxy address you want"
|
|
177
|
+
)
|
|
178
|
+
if _SYSTEM_PROXIES and not (PROXY_URL or _ENV_PROXIES):
|
|
179
|
+
# 只在「本来要直连、却发现系统里开着代理」时记一行:这时候用户看到的现象是
|
|
180
|
+
# 「浏览器能上,本插件抓不到」,这行日志就是他们要找的那条线索。
|
|
181
|
+
_log(f"following the system proxy for fetches: {sorted(_SYSTEM_PROXIES.values())}")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _snapshot_env_proxies() -> tuple[dict[str, str], tuple[str, ...]]:
|
|
185
|
+
"""从环境变量里读出代理表与绕过清单。
|
|
186
|
+
|
|
187
|
+
这是 curl_cffi(静态抓取)**唯一**认的来源:它的 trust_env 只看环境变量,macOS /
|
|
188
|
+
Windows 的「系统代理」开关对它完全不可见。操作系统的代理由 :func:`_read_system_proxies`
|
|
189
|
+
单独读,两边合起来才是「这台机器当前要怎么出去」。
|
|
190
|
+
|
|
191
|
+
:returns: (代理表, 绕过清单项)
|
|
192
|
+
"""
|
|
193
|
+
import os
|
|
194
|
+
|
|
195
|
+
table: dict[str, str] = {}
|
|
196
|
+
for name in ("http", "https", "all"):
|
|
197
|
+
value = (os.environ.get(f"{name}_proxy") or os.environ.get(f"{name.upper()}_PROXY") or "").strip()
|
|
198
|
+
if value:
|
|
199
|
+
table[name] = value
|
|
200
|
+
raw_bypass = os.environ.get("no_proxy") or os.environ.get("NO_PROXY") or ""
|
|
201
|
+
return table, tuple(item.strip() for item in raw_bypass.split(",") if item.strip())
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def parse_scutil_proxy(blob: str) -> dict[str, str]:
|
|
205
|
+
"""解析 ``scutil --proxy`` 的输出,取**全局**那几项。
|
|
206
|
+
|
|
207
|
+
只取全局(``__SCOPED__`` 之外的顶层键)是有意的:按接口分别配代理的形态少见得多,
|
|
208
|
+
而把带缩进的子字典一起扫进来会把某个网卡的局部设置误当成全局出口。
|
|
209
|
+
|
|
210
|
+
macOS 的 SOCKS 项说的是 SOCKS5,所以统一写成 ``socks5://``。只有 HTTP 一项时也给 https
|
|
211
|
+
补上同一份:CFNetwork 与浏览器都是这个行为,用户把「系统代理」只勾了 HTTP 时预期就是
|
|
212
|
+
https 也走它。
|
|
213
|
+
|
|
214
|
+
:param blob: ``scutil --proxy`` 的标准输出
|
|
215
|
+
:returns: 形如 ``{"http": url, "https": url, "all": url}`` 的代理表
|
|
216
|
+
"""
|
|
217
|
+
import re
|
|
218
|
+
|
|
219
|
+
fields: dict[str, str] = {}
|
|
220
|
+
scoped_indent: int | None = None
|
|
221
|
+
for line in blob.splitlines():
|
|
222
|
+
match = re.match(r"\A\s*([A-Za-z_]\w*)\s*:\s*(.*?)\s*\Z", line)
|
|
223
|
+
if match is None:
|
|
224
|
+
continue
|
|
225
|
+
indent = len(line) - len(line.lstrip())
|
|
226
|
+
if scoped_indent is None:
|
|
227
|
+
if match.group(1) == "__SCOPED__":
|
|
228
|
+
# 它的子树按接口分别配代理,比全局那几项缩进更深;记下这个深度,后面一律跳过。
|
|
229
|
+
scoped_indent = indent
|
|
230
|
+
else:
|
|
231
|
+
fields[match.group(1)] = match.group(2)
|
|
232
|
+
elif indent < scoped_indent:
|
|
233
|
+
# 理论上不会有(__SCOPED__ 之后只有它的子树),留这条以免未来多一层时错位。
|
|
234
|
+
fields[match.group(1)] = match.group(2)
|
|
235
|
+
|
|
236
|
+
def endpoint(name: str, port_name: str) -> str:
|
|
237
|
+
host = fields.get(name, "").strip()
|
|
238
|
+
port = fields.get(port_name, "").strip()
|
|
239
|
+
return f"{host}:{port}" if host and port else ""
|
|
240
|
+
|
|
241
|
+
table: dict[str, str] = {}
|
|
242
|
+
for key, prefix, scheme in (("http", "HTTP", "http"), ("https", "HTTPS", "https")):
|
|
243
|
+
if fields.get(f"{prefix}Enable", "0") == "1":
|
|
244
|
+
target = endpoint(f"{prefix}Proxy", f"{prefix}Port")
|
|
245
|
+
if target:
|
|
246
|
+
table[key] = f"{scheme}://{target}"
|
|
247
|
+
if table and "https" not in table:
|
|
248
|
+
table["https"] = table["http"]
|
|
249
|
+
if fields.get("SOCKSEnable", "0") == "1":
|
|
250
|
+
target = endpoint("SOCKSProxy", "SOCKSPort")
|
|
251
|
+
if target:
|
|
252
|
+
table["all"] = f"socks5://{target}"
|
|
253
|
+
return table
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def parse_windows_proxy(entries: dict[str, str]) -> dict[str, str]:
|
|
257
|
+
"""解析 Windows Internet Settings 那三枚注册表值。
|
|
258
|
+
|
|
259
|
+
``ProxyServer`` 有两种写法:单个 ``host:port``(对所有协议生效),或者分协议的
|
|
260
|
+
``http=h:1;https=h:2;socks=h:3``。两种都认。
|
|
261
|
+
|
|
262
|
+
``AutoConfigURL``(PAC)不在这里处理:求值 PAC 要下载脚本、跑 JavaScript,各平台格式
|
|
263
|
+
还不一样。见到它只报一声,让用户手填 proxyUrl。
|
|
264
|
+
|
|
265
|
+
:param entries: 键是 ``ProxyEnable`` / ``ProxyServer`` / ``AutoConfigURL`` 的小写形式
|
|
266
|
+
:returns: 代理表
|
|
267
|
+
"""
|
|
268
|
+
if entries.get("proxyenable", "0") != "1":
|
|
269
|
+
return {}
|
|
270
|
+
raw = entries.get("proxyserver", "").strip()
|
|
271
|
+
if not raw:
|
|
272
|
+
return {}
|
|
273
|
+
if "=" in raw:
|
|
274
|
+
parts = dict(
|
|
275
|
+
item.split("=", 1) for item in raw.split(";") if "=" in item
|
|
276
|
+
)
|
|
277
|
+
else:
|
|
278
|
+
parts = {"http": raw, "https": raw}
|
|
279
|
+
table: dict[str, str] = {}
|
|
280
|
+
for key, scheme in (("http", "http"), ("https", "https"), ("socks", "socks5")):
|
|
281
|
+
target = parts.get(key, "").strip()
|
|
282
|
+
if target and ":" in target:
|
|
283
|
+
table[key if key != "socks" else "all"] = f"{scheme}://{target}"
|
|
284
|
+
return table
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _run_readonly(argv: list[str]) -> str:
|
|
288
|
+
"""跑一条只读的系统查询命令,拿它的标准输出。
|
|
289
|
+
|
|
290
|
+
刻意不抛:读不到系统代理只意味着「按直连处理」,而让 sidecar 为此起不来是不可接受的。
|
|
291
|
+
绝对路径而不是靠 PATH —— dsh 拉起 sidecar 时给的是一份裁剪过的环境变量,PATH 里未必
|
|
292
|
+
还在。
|
|
293
|
+
|
|
294
|
+
:param argv: 命令与参数
|
|
295
|
+
:returns: 标准输出;任何失败都返回空串
|
|
296
|
+
"""
|
|
297
|
+
import subprocess
|
|
298
|
+
|
|
299
|
+
try:
|
|
300
|
+
done = subprocess.run( # noqa: S603 —— 参数是本文件里的常量,没有外部输入
|
|
301
|
+
argv,
|
|
302
|
+
capture_output=True,
|
|
303
|
+
text=True,
|
|
304
|
+
timeout=3,
|
|
305
|
+
check=False,
|
|
306
|
+
)
|
|
307
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
308
|
+
return ""
|
|
309
|
+
return done.stdout
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _macos_system_proxies() -> dict[str, str]:
|
|
313
|
+
"""读 macOS 的全局系统代理。"""
|
|
314
|
+
return parse_scutil_proxy(_run_readonly(["/usr/sbin/scutil", "--proxy"]))
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _windows_system_proxies() -> tuple[dict[str, str], str]:
|
|
318
|
+
"""读 Windows 的用户级 Internet Settings。返回 (代理表, PAC 地址)。"""
|
|
319
|
+
import os
|
|
320
|
+
import re
|
|
321
|
+
|
|
322
|
+
root = os.environ.get("SystemRoot", "C:\\Windows")
|
|
323
|
+
blob = _run_readonly(
|
|
324
|
+
[
|
|
325
|
+
f"{root}\\System32\\reg.exe",
|
|
326
|
+
"query",
|
|
327
|
+
r"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings",
|
|
328
|
+
]
|
|
329
|
+
)
|
|
330
|
+
entries: dict[str, str] = {}
|
|
331
|
+
for line in blob.splitlines():
|
|
332
|
+
match = re.match(r"\s{4}(\w+)\s+REG_\w+\s+(.+?)\s*\Z", line)
|
|
333
|
+
if match is not None:
|
|
334
|
+
entries[match.group(1).lower()] = match.group(2)
|
|
335
|
+
return parse_windows_proxy(entries), entries.get("autoconfigurl", "").strip()
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _read_system_proxies() -> tuple[dict[str, str], str]:
|
|
339
|
+
"""读操作系统设置里的全局代理。返回 (代理表, PAC 地址)。
|
|
340
|
+
|
|
341
|
+
只覆盖 macOS 与 Windows:这两边「系统代理」是代理软件的默认形态,也是 curl_cffi 唯一
|
|
342
|
+
完全看不见的那种代理。Linux 上的代理几乎都用 TUN 或环境变量表达,那两条已经在别处
|
|
343
|
+
覆盖;gsettings 的输出格式与前两者毫无共同之处,为它单开一套解析不值得。
|
|
344
|
+
|
|
345
|
+
:returns: 代理表与 PAC 地址(PAC 不为空时本包不求值它)
|
|
346
|
+
"""
|
|
347
|
+
import sys
|
|
348
|
+
|
|
349
|
+
if sys.platform == "darwin":
|
|
350
|
+
return _macos_system_proxies(), ""
|
|
351
|
+
if sys.platform == "win32":
|
|
352
|
+
return _windows_system_proxies()
|
|
353
|
+
return {}, ""
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _host_matches(host: str, entry: str) -> bool:
|
|
357
|
+
"""NO_PROXY 口径的主机名匹配:整名命中,也覆盖该名下的全部子域。
|
|
358
|
+
|
|
359
|
+
``example.com`` 命中 ``example.com`` 与 ``a.b.example.com``,但不命中
|
|
360
|
+
``notexample.com`` —— 后缀相同而已,那不是同一台主机。用 ``.example.com`` /
|
|
361
|
+
``*.example.com`` 写也等价。单独一个 ``*`` 表示全部绕过(即整台机器直连)。
|
|
362
|
+
|
|
363
|
+
:param host: 待判定的小写主机名
|
|
364
|
+
:param entry: 清单里的一项(可能带前导 ``.`` 或 ``*``)
|
|
365
|
+
:returns: 是否命中
|
|
366
|
+
"""
|
|
367
|
+
item = entry.strip().lower().lstrip("*")
|
|
368
|
+
if not item:
|
|
369
|
+
return False
|
|
370
|
+
name = host.lower()
|
|
371
|
+
item = item.lstrip(".")
|
|
372
|
+
return name == item or name.endswith(f".{item}")
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _is_bypassed(host: str) -> bool:
|
|
376
|
+
"""主机名是否命中绕过清单(设置与环境的并集)。
|
|
377
|
+
|
|
378
|
+
:param host: 待判定的主机名
|
|
379
|
+
:returns: 命中即直连
|
|
380
|
+
"""
|
|
381
|
+
return any(_host_matches(host, entry) for entry in _BYPASS_ENTRIES)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _proxy_scheme_key(url: str) -> str:
|
|
385
|
+
"""URL 该去环境表的哪一栏取代理。
|
|
386
|
+
|
|
387
|
+
:param url: 待判定的完整 URL
|
|
388
|
+
:returns: ``"https"`` 或 ``"http"``
|
|
389
|
+
"""
|
|
390
|
+
return "https" if urlparse(url).scheme in ("https", "wss") else "http"
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def proxy_for(url: str) -> str:
|
|
394
|
+
"""这次请求该走哪个代理;空串 = 直连。
|
|
395
|
+
|
|
396
|
+
顺序是**设置卡 proxyUrl → 环境里的代理变量 → 操作系统的代理设置 → 直连**,绕过清单
|
|
397
|
+
横切在最前(命中即直连,无论代理来自哪边)。设置里填了 proxyUrl 时后面两档整份被忽略:
|
|
398
|
+
显式设置就该压过隐式来源,否则「我明明填了 7890 却还在走 1080」这类问题无从查起。
|
|
399
|
+
|
|
400
|
+
三档各有各的存在理由,少一档就有一类用户抓不到东西:设置卡是显式意图;环境变量覆盖
|
|
401
|
+
CI、ssh 会话、docker exec 这类只在 shell 里 export 过的地方;系统代理是 macOS 与
|
|
402
|
+
Windows 上代理软件的默认形态(Clash Verge、Surge 等把「系统代理」一勾浏览器立刻就上,
|
|
403
|
+
而 curl_cffi 对它一无所知)。
|
|
404
|
+
|
|
405
|
+
:param url: 待判定的完整 URL
|
|
406
|
+
:returns: 代理地址;直连时为空串
|
|
407
|
+
"""
|
|
408
|
+
if _is_bypassed(urlparse(url).hostname or ""):
|
|
409
|
+
return ""
|
|
410
|
+
if PROXY_URL:
|
|
411
|
+
return PROXY_URL
|
|
412
|
+
key = _proxy_scheme_key(url)
|
|
413
|
+
return (
|
|
414
|
+
_ENV_PROXIES.get(key)
|
|
415
|
+
or _ENV_PROXIES.get("all")
|
|
416
|
+
or _SYSTEM_PROXIES.get(key)
|
|
417
|
+
or _SYSTEM_PROXIES.get("all", "")
|
|
418
|
+
)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def proxies_for(url: str) -> dict[str, str] | None:
|
|
422
|
+
"""curl_cffi 形态的代理表。
|
|
423
|
+
|
|
424
|
+
返回 None 表示「本包不表态」,由 curl_cffi 照它自己的 trust_env 去读环境 —— 那是
|
|
425
|
+
设置、绕过清单与系统代理**都**为空时的路径,行为与本包不介入时逐字节一致。
|
|
426
|
+
返回 ``{"all": ""}`` 才是「明确直连」:curl 会把空串当成 ``CURLOPT_PROXY=""``,即彻底
|
|
427
|
+
关掉代理,包括环境里的那份。
|
|
428
|
+
|
|
429
|
+
:param url: 待判定的完整 URL
|
|
430
|
+
:returns: 代理表,或 None 表示交给底层自己判断
|
|
431
|
+
"""
|
|
432
|
+
if not (PROXY_URL or PROXY_BYPASS or _BYPASS_ENTRIES or _SYSTEM_PROXIES):
|
|
433
|
+
return None
|
|
434
|
+
return {"all": proxy_for(url)}
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def default_proxy() -> str:
|
|
438
|
+
"""不依赖具体主机的那个代理,供会话开场这类「还不知道 URL」的场合用。
|
|
439
|
+
|
|
440
|
+
与 :func:`proxy_for` 的差别只有一处:不看绕过清单 —— 会话开在哪个主机上尚未可知,
|
|
441
|
+
而浏览器会话的代理在 context 创建时就定死了(中途换 context 等于丢掉 cookie)。
|
|
442
|
+
绕过清单里单独一个 ``*`` 是「整台机器直连」,那个要照认。
|
|
443
|
+
|
|
444
|
+
:returns: 代理地址;没有配置代理时为空串
|
|
445
|
+
"""
|
|
446
|
+
if any(entry.strip() == "*" for entry in _BYPASS_ENTRIES):
|
|
447
|
+
return ""
|
|
448
|
+
table = PROXY_URL or next(iter(_ENV_PROXIES.values()), "") or next(
|
|
449
|
+
iter(_SYSTEM_PROXIES.values()), ""
|
|
450
|
+
)
|
|
451
|
+
return table
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def split_proxy(raw: str) -> dict[str, str] | None:
|
|
455
|
+
"""把代理地址拆成 Playwright 认的 ``{server, username, password}``。
|
|
456
|
+
|
|
457
|
+
自己拆而不是交给 Scrapling 的 ``construct_proxy_dict``:那份丢掉 IPv6 字面量的方括号
|
|
458
|
+
(``socks5://[::1]:1080`` 会变成 ``socks5://::1``),而代理软件确实会用回环监听。
|
|
459
|
+
路径、查询串与片段一并丢掉 —— 代理地址里出现它们没有任何意义。
|
|
460
|
+
|
|
461
|
+
:param raw: 代理地址
|
|
462
|
+
:returns: 代理字典;地址不可用时为 None
|
|
463
|
+
"""
|
|
464
|
+
parsed = urlparse(raw)
|
|
465
|
+
scheme = (parsed.scheme or "").lower()
|
|
466
|
+
if scheme not in _BROWSER_PROXY_SCHEMES or not parsed.hostname:
|
|
467
|
+
return None
|
|
468
|
+
# urlparse 已经把 IPv6 字面量的方括号摘掉了(hostname 是 `::1`),Playwright 要的
|
|
469
|
+
# server 里得再装回去 —— 否则 `[::1]` 会被解析成端口。
|
|
470
|
+
host = parsed.hostname if ":" not in parsed.hostname else f"[{parsed.hostname}]"
|
|
471
|
+
server = f"{scheme}://{host}"
|
|
472
|
+
if parsed.port:
|
|
473
|
+
server = f"{server}:{parsed.port}"
|
|
474
|
+
return {
|
|
475
|
+
"server": server,
|
|
476
|
+
# 凭据要 percent-decode:urlparse 不解,而 Playwright 是把这对值原样塞进
|
|
477
|
+
# Proxy-Authorization 的 Basic 段(不做解码),libcurl 则会解码。不在这里解开,
|
|
478
|
+
# 含 `@` 或 `:` 的密码就会在两条路径上给出两个不同的密码。
|
|
479
|
+
"username": unquote(parsed.username or ""),
|
|
480
|
+
"password": unquote(parsed.password or ""),
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def browser_proxy(url: str) -> dict[str, str] | None:
|
|
485
|
+
"""浏览器引擎形态的代理。
|
|
486
|
+
|
|
487
|
+
:param url: 待判定的完整 URL
|
|
488
|
+
:returns: 代理字典;直连时为 None
|
|
489
|
+
"""
|
|
490
|
+
return split_proxy(proxy_for(url))
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def proxy_settings() -> dict[str, Any]:
|
|
494
|
+
"""当前代理配置的可展示摘要,供能力上报如实说明。
|
|
495
|
+
|
|
496
|
+
**绝不含凭据**:只回显 ``scheme://host:port``,连用户名都不带 —— 这份摘要会进日志、
|
|
497
|
+
进能力协商帧,而密码只应该待在环境变量与设置文件里。
|
|
498
|
+
|
|
499
|
+
``source`` 如实标出代理是从哪一档来的。用户报「抓不到东西」时,这一栏就是第一眼的
|
|
500
|
+
答案:``system`` 表示跟着操作系统的代理设置走(浏览器能上、本插件静态抓取也能上,
|
|
501
|
+
两侧一致),``none`` 表示这台机器压根没配代理。
|
|
502
|
+
|
|
503
|
+
:returns: ``{configured, source, server}``
|
|
504
|
+
"""
|
|
505
|
+
if PROXY_URL:
|
|
506
|
+
source, raw = "settings", PROXY_URL
|
|
507
|
+
elif _ENV_PROXIES:
|
|
508
|
+
source, raw = "environment", next(iter(_ENV_PROXIES.values()))
|
|
509
|
+
elif _SYSTEM_PROXIES:
|
|
510
|
+
source, raw = "system", next(iter(_SYSTEM_PROXIES.values()))
|
|
511
|
+
else:
|
|
512
|
+
source, raw = "none", ""
|
|
513
|
+
parsed = split_proxy(raw)
|
|
514
|
+
return {"configured": bool(parsed), "source": source, "server": parsed["server"] if parsed else ""}
|
|
515
|
+
|
|
92
516
|
|
|
93
517
|
def _nat64_tables() -> tuple[tuple[ipaddress.IPv6Network, int, int], ...]:
|
|
94
518
|
"""把 NAT64 前缀表预解析成 (网络, 前缀长度, 偏移)。"""
|
|
@@ -129,10 +553,84 @@ def effective_ip(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> ipad
|
|
|
129
553
|
return address
|
|
130
554
|
|
|
131
555
|
|
|
132
|
-
|
|
556
|
+
# 检测合成解析器用的控制域名:与用户的目标无关,答案只反映解析器本身的行为。
|
|
557
|
+
CONTROL_HOSTS: tuple[str, ...] = ("example.com", "www.iana.org", "www.wikipedia.org")
|
|
558
|
+
|
|
559
|
+
# 检测结果;只算一次并缓存。
|
|
560
|
+
_SYNTHETIC_RESOLVER: bool | None = None
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def detect_synthetic_resolver() -> bool:
|
|
564
|
+
"""判断当前解析器是不是在合成地址。
|
|
565
|
+
|
|
566
|
+
依据是 fake-ip 的指纹:**所有**主机名都被指到同一个非公网小池里。实测在一台开着 TUN +
|
|
567
|
+
fake-ip 的机器上,example.com / github.com / wikipedia.org / echarts.apache.org /
|
|
568
|
+
www.apple.com 全部落在 198.18.0.0/15 内且互不相同,而 IP 字面量原样不动。
|
|
569
|
+
|
|
570
|
+
这么判而不是枚举段:落点由代理自己定,用户不该被迫先知道自己代理用了哪一段。控制域名
|
|
571
|
+
解析失败时判否——判否只让守卫维持最严,不会误放行。
|
|
572
|
+
|
|
573
|
+
:returns: 解析器是否在合成地址
|
|
574
|
+
"""
|
|
575
|
+
global _SYNTHETIC_RESOLVER # noqa: PLW0603 —— 缓存一次即可
|
|
576
|
+
if _SYNTHETIC_RESOLVER is not None:
|
|
577
|
+
return _SYNTHETIC_RESOLVER
|
|
578
|
+
resolved: list[str] = []
|
|
579
|
+
for host in CONTROL_HOSTS:
|
|
580
|
+
try:
|
|
581
|
+
infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
|
|
582
|
+
except OSError:
|
|
583
|
+
_SYNTHETIC_RESOLVER = False
|
|
584
|
+
return _SYNTHETIC_RESOLVER
|
|
585
|
+
resolved.extend(info[4][0] for info in infos)
|
|
586
|
+
if len(resolved) < len(CONTROL_HOSTS):
|
|
587
|
+
_SYNTHETIC_RESOLVER = False
|
|
588
|
+
return _SYNTHETIC_RESOLVER
|
|
589
|
+
parsed = []
|
|
590
|
+
for item in resolved:
|
|
591
|
+
try:
|
|
592
|
+
parsed.append(ipaddress.ip_address(item))
|
|
593
|
+
except ValueError:
|
|
594
|
+
_SYNTHETIC_RESOLVER = False
|
|
595
|
+
return _SYNTHETIC_RESOLVER
|
|
596
|
+
# 全非公网且彼此不同 = 一个合成池。全指向同一处更像是解析器坏了,不当成 fake-ip。
|
|
597
|
+
_SYNTHETIC_RESOLVER = all(not item.is_global for item in parsed) and len(set(parsed)) > 1
|
|
598
|
+
return _SYNTHETIC_RESOLVER
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def _acceptable_resolved(item: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
|
|
602
|
+
"""判定一个**解析得到**的地址能否放行。
|
|
603
|
+
|
|
604
|
+
与字面量口径的唯一差别在这里:认出合成解析器、或用户手动列了合成段时,那几段算通过。
|
|
605
|
+
字面量走 :func:`is_public_address` 里另一条分支,拿不到这份放宽。
|
|
606
|
+
|
|
607
|
+
:param item: 已做过内嵌 IPv4 复判的地址
|
|
608
|
+
:returns: 是否放行
|
|
609
|
+
"""
|
|
610
|
+
if item.is_global:
|
|
611
|
+
return True
|
|
612
|
+
if not isinstance(item, ipaddress.IPv4Address):
|
|
613
|
+
return False
|
|
614
|
+
if detect_synthetic_resolver():
|
|
615
|
+
return True
|
|
616
|
+
return bool(SYNTHETIC_NETWORKS) and any(item in network for network in SYNTHETIC_NETWORKS)
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def is_public_address(host: str, *, proxied: bool = False) -> bool:
|
|
133
620
|
"""判定一个主机名/字面量是否指向公网地址。
|
|
134
621
|
|
|
135
|
-
|
|
622
|
+
没有代理时,解析失败一律按不可抓处理 —— 拿不到答案时选择拒,而不是选择放行。
|
|
623
|
+
|
|
624
|
+
``proxied`` 为真时**只有一条**判据放宽:本机解析失败改成放行。理由是那一刻请求根本
|
|
625
|
+
不从本机网络命名空间出去,域名由代理去解析,本机解析器答不上来什么也说明不了 ——
|
|
626
|
+
而在 DNS 被按地区过滤的网络里,恰恰是这些站点才需要代理才能访问。字面量与本地能解析
|
|
627
|
+
出来的私网答案**照旧拒**(上面两条分支都不看 ``proxied``),单标签主机名也照旧拒:
|
|
628
|
+
`intranet`、`router` 这类名字经代理去解析也没有公网含义,放开它等于把「猜一个内网名
|
|
629
|
+
试试」重新变成一条可用路径。
|
|
630
|
+
|
|
631
|
+
:param host: 主机名或 IP 字面量
|
|
632
|
+
:param proxied: 这次请求是否经代理发出
|
|
633
|
+
:returns: 是否放行
|
|
136
634
|
"""
|
|
137
635
|
if host in ALLOWED_HOSTS:
|
|
138
636
|
return True
|
|
@@ -150,17 +648,22 @@ def is_public_address(host: str) -> bool:
|
|
|
150
648
|
# getaddrinfo 去赌平台解析器的口径,直接判否。
|
|
151
649
|
if _IP_LITERAL_SHAPE.search(host) and not host.startswith("["):
|
|
152
650
|
return False
|
|
651
|
+
if "." not in host:
|
|
652
|
+
return False
|
|
153
653
|
|
|
154
654
|
try:
|
|
155
655
|
infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
|
|
156
656
|
except OSError:
|
|
657
|
+
if proxied:
|
|
658
|
+
_log(f"local DNS has no answer for {host}; allowing it through the proxy")
|
|
659
|
+
return True
|
|
157
660
|
return False
|
|
158
661
|
# 整张答案表都要是公网:混入一条私网即整体拒绝,避免 DNS 轮询绕过。
|
|
159
662
|
addresses: Iterable[ipaddress.IPv4Address | ipaddress.IPv6Address] = (
|
|
160
663
|
ipaddress.ip_address(info[4][0]) for info in infos
|
|
161
664
|
)
|
|
162
665
|
resolved = [effective_ip(item) for item in addresses]
|
|
163
|
-
return bool(resolved) and all(item
|
|
666
|
+
return bool(resolved) and all(_acceptable_resolved(item) for item in resolved)
|
|
164
667
|
|
|
165
668
|
|
|
166
669
|
def url_allowed(url: str) -> tuple[bool, str]:
|
|
@@ -183,7 +686,7 @@ def url_allowed(url: str) -> tuple[bool, str]:
|
|
|
183
686
|
return False, "URL has an invalid port"
|
|
184
687
|
if ALLOWED_PORTS and port is not None and port not in ALLOWED_PORTS:
|
|
185
688
|
return False, f"port {port} is not in the allow list"
|
|
186
|
-
if not is_public_address(host):
|
|
689
|
+
if not is_public_address(host, proxied=bool(proxy_for(url))):
|
|
187
690
|
return False, f"host does not resolve to a public address: {host}"
|
|
188
691
|
return True, ""
|
|
189
692
|
|