@jayyuen66/dsh-scrapling 0.1.2 → 0.1.4

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.
@@ -0,0 +1,400 @@
1
+ """选择器查询与字段抽取的纯函数。
2
+
3
+ 只做 HTML 到 Python 值的转换;不读环境、不发请求、不处理 protocol 帧。
4
+ `adapters.select` 负责参数错误码,`locate`/`links` 在后续任务复用这里的查询与序列化。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import Any, Iterable, cast
11
+
12
+ _URL_ATTRIBUTES = frozenset({"href", "src", "action"})
13
+
14
+
15
+ def _json_len(value: Any) -> int:
16
+ """按 JSON 序列化后的字符数计预算;与模型看到的形状一致。"""
17
+ return len(json.dumps(value, ensure_ascii=False))
18
+
19
+
20
+ def _resolve_url(page: Any, value: str) -> str:
21
+ """把相对地址拼成绝对地址;空值或拼不出来时保留原值。"""
22
+ if not value:
23
+ return value
24
+ try:
25
+ return str(page.urljoin(value))
26
+ except Exception: # noqa: BLE001 —— 不是合法 URL 时保留原值比抛错更有用
27
+ return value
28
+
29
+
30
+ def _query_type(selector: str, query_type: str | None, use_xpath: bool) -> str:
31
+ """把旧的 ``useXpath`` 布尔值归一到 queryType。"""
32
+ return query_type or ("xpath" if use_xpath else "css")
33
+
34
+
35
+ def query_nodes(
36
+ page: Any,
37
+ selector: str,
38
+ query_type: str = "css",
39
+ *,
40
+ use_xpath: bool = False,
41
+ partial: bool = False,
42
+ case_sensitive: bool = False,
43
+ clean_match: bool = True,
44
+ similarity_threshold: float = 0.2,
45
+ ignore_attributes: Iterable[str] = ("href", "src"),
46
+ match_text: bool = False,
47
+ ) -> tuple[list[Any], str]:
48
+ """按 queryType 返回节点列表与一条可读说明。
49
+
50
+ ``similar`` 无种子时返回空列表与说明,绝不回退成整页。
51
+ """
52
+ if not isinstance(selector, str) or not selector:
53
+ raise ValueError("selector is required")
54
+ kind = _query_type(selector, query_type, use_xpath)
55
+ if kind == "css":
56
+ return list(page.css(selector)), ""
57
+ if kind == "xpath":
58
+ return list(page.xpath(selector)), ""
59
+ if kind == "text":
60
+ found = page.find_by_text(
61
+ selector,
62
+ first_match=False,
63
+ partial=partial,
64
+ case_sensitive=case_sensitive,
65
+ clean_match=clean_match,
66
+ )
67
+ return list(found or []), ""
68
+ if kind == "regex":
69
+ found = page.find_by_regex(
70
+ selector,
71
+ first_match=False,
72
+ case_sensitive=case_sensitive,
73
+ clean_match=clean_match,
74
+ )
75
+ return list(found or []), ""
76
+ if kind == "similar":
77
+ seeds = list(page.xpath(selector) if use_xpath else page.css(selector))
78
+ if not seeds:
79
+ return [], "similar seed matched nothing"
80
+ found = seeds[0].find_similar(
81
+ similarity_threshold=similarity_threshold,
82
+ ignore_attributes=list(ignore_attributes),
83
+ match_text=match_text,
84
+ )
85
+ return list(found or []), ""
86
+ raise ValueError(f"unknown queryType: {kind}")
87
+
88
+
89
+ def serialize_match(
90
+ node: Any,
91
+ *,
92
+ page: Any,
93
+ attribute: str | None = None,
94
+ include_attributes: bool = False,
95
+ include_html: bool = False,
96
+ resolve_urls: bool = False,
97
+ ) -> dict[str, Any]:
98
+ """把一条元素/文本节点归一成匹配载荷。"""
99
+ item: dict[str, Any] = {"tag": str(getattr(node, "tag", "") or "")}
100
+ if attribute:
101
+ value = node.attrib.get(attribute, "")
102
+ item["value"] = _resolve_url(page, str(value)) if resolve_urls and attribute in _URL_ATTRIBUTES else str(value)
103
+ else:
104
+ item["text"] = str(node.get_all_text(strip=True))
105
+ if include_html:
106
+ item["html"] = str(node.html_content)
107
+ if include_attributes:
108
+ item["attributes"] = {str(key): str(value) for key, value in node.attrib.items()}
109
+ return item
110
+
111
+
112
+ def _field_spec(spec: Any) -> tuple[str, str, str | None, bool]:
113
+ """把字段描述归一成 (selector, mode, attribute, all)。"""
114
+ selector: str
115
+ mode: str
116
+ attribute: str | None
117
+ many: bool
118
+ if isinstance(spec, str):
119
+ selector, mode, attribute, many = spec, "text", None, False
120
+ elif isinstance(spec, dict):
121
+ raw_selector = spec.get("selector")
122
+ attribute = spec.get("attribute")
123
+ raw_mode = spec.get("mode")
124
+ mode = (
125
+ str(raw_mode)
126
+ if raw_mode is not None
127
+ else ("attribute" if isinstance(attribute, str) and attribute else "text")
128
+ )
129
+ many = bool(spec.get("all", False))
130
+ if not isinstance(raw_selector, str) or not raw_selector:
131
+ raise ValueError("field selector is required")
132
+ selector = raw_selector
133
+ if mode not in ("text", "html", "attribute"):
134
+ raise ValueError(f"unknown field mode: {mode}")
135
+ if mode == "attribute" and (not isinstance(attribute, str) or not attribute):
136
+ raise ValueError("attribute mode requires an attribute name")
137
+ else:
138
+ raise ValueError("field spec must be a string or an object")
139
+ return selector, mode, attribute if isinstance(attribute, str) else None, many
140
+
141
+
142
+ def _select_field_nodes(node: Any, selector: str) -> list[Any]:
143
+ """字段选择器相对记录节点执行;以 .// 或 / 开头时走 XPath。"""
144
+ if selector.startswith(".//") or selector.startswith("/"):
145
+ return list(node.xpath(selector))
146
+ return list(node.css(selector))
147
+
148
+
149
+ def field_value(
150
+ node: Any,
151
+ spec: Any,
152
+ *,
153
+ page: Any,
154
+ resolve_urls: bool = False,
155
+ ) -> Any:
156
+ """取一个字段的值;缺失给 None,all=true 时给列表。"""
157
+ selector, mode, attribute, many = _field_spec(spec)
158
+ found = _select_field_nodes(node, selector)
159
+ if many:
160
+ values = [_field_scalar(item, mode, attribute, page, resolve_urls) for item in found]
161
+ return [value for value in values if value is not None]
162
+ for item in found:
163
+ value = _field_scalar(item, mode, attribute, page, resolve_urls)
164
+ if value is not None:
165
+ return value
166
+ return None
167
+
168
+
169
+ def _field_scalar(
170
+ item: Any,
171
+ mode: str,
172
+ attribute: str | None,
173
+ page: Any,
174
+ resolve_urls: bool,
175
+ ) -> Any:
176
+ """从一个命中节点取 text/html/attribute 值。"""
177
+ if mode == "html":
178
+ return str(item.html_content)
179
+ if mode == "attribute":
180
+ value = item.attrib.get(attribute or "")
181
+ if value is None:
182
+ return None
183
+ text = str(value)
184
+ return _resolve_url(page, text) if resolve_urls and (attribute or "") in _URL_ATTRIBUTES else text
185
+ return str(item.get_all_text(strip=True))
186
+
187
+
188
+ def collect_fields(
189
+ nodes: Iterable[Any],
190
+ fields: dict[str, Any],
191
+ *,
192
+ page: Any,
193
+ max_content_chars: int,
194
+ resolve_urls: bool = False,
195
+ ) -> tuple[list[dict[str, Any]], bool]:
196
+ """把记录节点按字段表收成行;返回 (rows, truncated)。"""
197
+ if not isinstance(fields, dict) or not fields:
198
+ raise ValueError("fields must be a non-empty object")
199
+ rows: list[dict[str, Any]] = []
200
+ spent = 0
201
+ truncated = False
202
+ for node in nodes:
203
+ row: dict[str, Any] = {}
204
+ for name, spec in fields.items():
205
+ value = field_value(node, spec, page=page, resolve_urls=resolve_urls)
206
+ room = max(0, max_content_chars - spent)
207
+ size = _json_len(value)
208
+ if size > room:
209
+ if isinstance(value, str):
210
+ # JSON 字符串带两个引号;留出它们再把正文裁到剩余预算。
211
+ value = value[: max(0, room - 2)]
212
+ size = _json_len(value)
213
+ truncated = True
214
+ spent += size
215
+ row[str(name)] = value
216
+ rows.append(row)
217
+ if spent >= max_content_chars:
218
+ truncated = True
219
+ break
220
+ return rows, truncated
221
+
222
+
223
+ def locate(args: dict[str, Any]) -> dict[str, Any]:
224
+ """定位元素并返回生成选择器;不发网络请求,不写 adaptive 指纹。"""
225
+ from scrapling.parser import Selector
226
+
227
+ html = args.get("html")
228
+ if not isinstance(html, str):
229
+ raise ValueError("html must be a string")
230
+ selector = args.get("selector")
231
+ if not isinstance(selector, str) or not selector:
232
+ raise ValueError("selector is required")
233
+ url = args.get("url")
234
+ if url is not None and not isinstance(url, str):
235
+ raise ValueError("url must be a string or null")
236
+ query_type = args.get("queryType")
237
+ if query_type is not None and not isinstance(query_type, str):
238
+ raise ValueError("queryType must be a string")
239
+ query_type = query_type or "css"
240
+ if query_type not in ("css", "xpath", "text", "regex", "similar"):
241
+ raise ValueError(f"unknown queryType: {query_type}")
242
+ limit = _positive_int(args.get("limit"), "limit", 200)
243
+ budget = _positive_int(args.get("maxContentChars"), "maxContentChars", 200_000)
244
+ include_ancestors = bool(args.get("includeAncestors", True))
245
+ generate_selectors = bool(args.get("generateSelectors", True))
246
+ page = Selector(html, url=url or "")
247
+ nodes, notice = query_nodes(
248
+ page,
249
+ selector,
250
+ query_type,
251
+ use_xpath=bool(args.get("useXpath", False)),
252
+ partial=bool(args.get("partial", False)),
253
+ case_sensitive=bool(args.get("caseSensitive", False)),
254
+ clean_match=bool(args.get("cleanMatch", True)),
255
+ similarity_threshold=float(args.get("similarityThreshold", 0.2)),
256
+ ignore_attributes=args.get("ignoreAttributes") or ("href", "src"),
257
+ match_text=bool(args.get("matchText", False)),
258
+ )
259
+ matches: list[dict[str, Any]] = []
260
+ spent = 0
261
+ truncated = False
262
+ for node in nodes:
263
+ if len(matches) >= limit:
264
+ truncated = True
265
+ break
266
+ text = str(node.get_all_text(strip=True))
267
+ room = max(0, budget - spent)
268
+ if len(text) > room:
269
+ text = text[:room]
270
+ truncated = True
271
+ spent += len(text)
272
+ item: dict[str, Any] = {
273
+ "tag": str(getattr(node, "tag", "") or ""),
274
+ "text": text,
275
+ "attributes": {str(key): str(value) for key, value in node.attrib.items()},
276
+ "cssSelector": str(node.generate_css_selector) if generate_selectors else "",
277
+ "xpathSelector": str(node.generate_xpath_selector) if generate_selectors else "",
278
+ "fullCssSelector": str(node.generate_full_css_selector) if generate_selectors else "",
279
+ "fullXpathSelector": str(node.generate_full_xpath_selector) if generate_selectors else "",
280
+ "ancestors": (
281
+ [
282
+ {
283
+ "tag": str(getattr(ancestor, "tag", "") or ""),
284
+ "attributes": {str(key): str(value) for key, value in ancestor.attrib.items()},
285
+ }
286
+ for ancestor in node.iterancestors()
287
+ ]
288
+ if include_ancestors
289
+ else []
290
+ ),
291
+ }
292
+ matches.append(item)
293
+ if spent >= budget:
294
+ truncated = True
295
+ break
296
+ return {
297
+ "count": len(nodes),
298
+ "truncated": truncated or len(nodes) > len(matches),
299
+ "matches": matches,
300
+ "notice": notice,
301
+ }
302
+
303
+
304
+ def _next_reason(text: str, url: str) -> str:
305
+ """给分页候选一个可读的原因;没有命中给空串。"""
306
+ lowered = text.lower()
307
+ if "load more" in lowered:
308
+ return "text:load more"
309
+ if "next" in lowered:
310
+ return "text:next"
311
+ if "more" in lowered:
312
+ return "text:more"
313
+ lowered_url = url.lower()
314
+ if "page=" in lowered_url:
315
+ return "url:page"
316
+ if "/page/" in lowered_url:
317
+ return "url:page-path"
318
+ if "offset=" in lowered_url:
319
+ return "url:offset"
320
+ return ""
321
+
322
+
323
+ def links(args: dict[str, Any]) -> dict[str, Any]:
324
+ """对已有 HTML 跑 LinkExtractor,并给出分页候选。"""
325
+ from scrapling.parser import Selector
326
+ from scrapling.spiders import LinkExtractor
327
+
328
+ html = args.get("html")
329
+ if not isinstance(html, str):
330
+ raise ValueError("html must be a string")
331
+ base_url = args.get("baseUrl")
332
+ if base_url is not None and not isinstance(base_url, str):
333
+ raise ValueError("baseUrl must be a string or null")
334
+ page = Selector(html, url=base_url or "")
335
+ limit = _positive_int(args.get("limit"), "limit", 200)
336
+ find_next = bool(args.get("findNext", True))
337
+ options: dict[str, Any] = {}
338
+ for source, target in (
339
+ ("allow", "allow"),
340
+ ("deny", "deny"),
341
+ ("allowDomains", "allow_domains"),
342
+ ("denyDomains", "deny_domains"),
343
+ ("restrictCss", "restrict_css"),
344
+ ("restrictXpath", "restrict_xpath"),
345
+ ("tags", "tags"),
346
+ ("attrs", "attrs"),
347
+ ("denyExtensions", "deny_extensions"),
348
+ ):
349
+ value = args.get(source)
350
+ if value is not None:
351
+ options[target] = value
352
+ for source, target in (
353
+ ("canonicalize", "canonicalize"),
354
+ ("strip", "strip"),
355
+ ("keepFragment", "keep_fragment"),
356
+ ):
357
+ value = args.get(source)
358
+ if isinstance(value, bool):
359
+ options[target] = value
360
+ try:
361
+ extractor = LinkExtractor(**options)
362
+ except Exception as error:
363
+ raise ValueError(f"invalid link rule: {error}") from error
364
+ # 上游把注解写成 Response,实际只读 .url 与 .css;Selector 已在 V11 实测可用。
365
+ urls = list(extractor.extract(cast(Any, page)))
366
+ truncated = len(urls) > limit
367
+ kept = urls[:limit]
368
+ candidates: list[dict[str, str]] = []
369
+ seen: set[str] = set()
370
+ if find_next:
371
+ for element in page.css("a, area"):
372
+ href = element.attrib.get("href")
373
+ if not href:
374
+ continue
375
+ text = str(element.get_all_text(strip=True))
376
+ reason = _next_reason(text, href)
377
+ if not reason:
378
+ continue
379
+ url = str(page.urljoin(href))
380
+ if url in seen:
381
+ continue
382
+ seen.add(url)
383
+ candidates.append({"url": url, "text": text, "reason": reason})
384
+ if len(candidates) >= 20:
385
+ break
386
+ return {
387
+ "count": len(urls),
388
+ "truncated": truncated,
389
+ "links": [{"url": url} for url in kept],
390
+ "nextCandidates": candidates,
391
+ }
392
+
393
+
394
+ def _positive_int(value: Any, field: str, default: int) -> int:
395
+ """取一个正整数;非法值抛 ValueError,由 adapters 转成 BAD_ARGS。"""
396
+ if value is None:
397
+ return default
398
+ if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
399
+ raise ValueError(f"{field} must be a positive integer")
400
+ return value
package/py/guard.py CHANGED
@@ -20,10 +20,14 @@ from __future__ import annotations
20
20
 
21
21
  import ipaddress
22
22
  import socket
23
+ import threading
24
+ import time
23
25
  from collections.abc import Iterable
24
26
  from typing import Any
25
27
  from urllib.parse import unquote, urlparse
26
28
 
29
+ from redact import redact_url_secrets
30
+
27
31
  # 放行的额外主机名。默认空 —— 只有字面量公网 IP 与解析到公网的域名能过。
28
32
  ALLOWED_HOSTS: frozenset[str] = frozenset()
29
33
 
@@ -66,6 +70,13 @@ ALLOW_WRITE_METHODS_ENV = "DSH_SCRAPLING_ALLOW_WRITE_METHODS"
66
70
  # 当前是否允许写方法;由 :func:`configure_from_env` 按上面那枚变量填。
67
71
  ALLOW_WRITE_METHODS: bool = False
68
72
 
73
+ # 结构化浏览器动作与文件下载是两组独立的高风险能力:动作会改页面对端状态,下载会把
74
+ # 远端字节写进本机目录。两者都默认关,由部署方分别表态。
75
+ ALLOW_BROWSER_ACTIONS_ENV = "DSH_SCRAPLING_ALLOW_BROWSER_ACTIONS"
76
+ ALLOW_BROWSER_ACTIONS: bool = False
77
+ ALLOW_FILE_DOWNLOADS_ENV = "DSH_SCRAPLING_ALLOW_FILE_DOWNLOADS"
78
+ ALLOW_FILE_DOWNLOADS: bool = False
79
+
69
80
  # 手动追加的合成段(CIDR)。默认空 —— 自动检测是主路径。
70
81
  SYNTHETIC_NETWORKS: tuple[ipaddress.IPv4Network, ...] = ()
71
82
 
@@ -118,7 +129,13 @@ EXTRA_NAT64_PREFIXES: tuple[str, ...] = ()
118
129
  _NAT64_EMBEDDED_OFFSET: dict[int, int] = {96: 12, 64: 9, 56: 7, 48: 6, 40: 5, 32: 4}
119
130
 
120
131
 
121
- def configure(allowed_hosts=None, nat64_prefixes=None, allow_write_methods=None) -> None:
132
+ def configure(
133
+ allowed_hosts: frozenset[str] | None = None,
134
+ nat64_prefixes: tuple[str, ...] | None = None,
135
+ allow_write_methods: bool | None = None,
136
+ allow_browser_actions: bool | None = None,
137
+ allow_file_downloads: bool | None = None,
138
+ ) -> None:
122
139
  """按部署配置收紧或放宽放行集合。
123
140
 
124
141
  只应由宿主侧在启动时调用一次,参数来自用户显式设置,而不是模型入参。
@@ -128,12 +145,17 @@ def configure(allowed_hosts=None, nat64_prefixes=None, allow_write_methods=None)
128
145
  :param allow_write_methods: 是否开放写方法;None 表示沿用当前值
129
146
  """
130
147
  global ALLOWED_HOSTS, EXTRA_NAT64_PREFIXES, ALLOW_WRITE_METHODS # noqa: PLW0603 —— 模块级策略常量,需整体替换
148
+ global ALLOW_BROWSER_ACTIONS, ALLOW_FILE_DOWNLOADS # noqa: PLW0603
131
149
  if allowed_hosts is not None:
132
150
  ALLOWED_HOSTS = allowed_hosts
133
151
  if nat64_prefixes is not None:
134
152
  EXTRA_NAT64_PREFIXES = nat64_prefixes
135
153
  if allow_write_methods is not None:
136
154
  ALLOW_WRITE_METHODS = allow_write_methods
155
+ if allow_browser_actions is not None:
156
+ ALLOW_BROWSER_ACTIONS = allow_browser_actions
157
+ if allow_file_downloads is not None:
158
+ ALLOW_FILE_DOWNLOADS = allow_file_downloads
137
159
 
138
160
 
139
161
  def configure_from_env() -> None:
@@ -155,6 +177,7 @@ def configure_from_env() -> None:
155
177
  configure(nat64_prefixes=prefixes)
156
178
 
157
179
  global SYNTHETIC_NETWORKS, PROXY_URL, PROXY_BYPASS, ALLOW_WRITE_METHODS, _BYPASS_ENTRIES # noqa: PLW0603 —— 启动时定一次
180
+ global ALLOW_BROWSER_ACTIONS, ALLOW_FILE_DOWNLOADS # noqa: PLW0603
158
181
  global _ENV_PROXIES, _ENV_BYPASS, _SYSTEM_PROXIES, _PAC_NOTICE # 同上
159
182
  networks: list[ipaddress.IPv4Network] = []
160
183
  for item in os.environ.get(SYNTHETIC_RANGES_ENV, "").split(","):
@@ -176,6 +199,18 @@ def configure_from_env() -> None:
176
199
  # 写方法开关只认那几种明确写法:拼错的值("ture")必须落在「关」那一侧,而不是被
177
200
  # `bool("非空")` 读成开 —— 一个安全开关的默认失败方向是收紧。
178
201
  ALLOW_WRITE_METHODS = os.environ.get(ALLOW_WRITE_METHODS_ENV, "").strip().lower() in ("1", "true", "yes", "on")
202
+ ALLOW_BROWSER_ACTIONS = os.environ.get(ALLOW_BROWSER_ACTIONS_ENV, "").strip().lower() in (
203
+ "1",
204
+ "true",
205
+ "yes",
206
+ "on",
207
+ )
208
+ ALLOW_FILE_DOWNLOADS = os.environ.get(ALLOW_FILE_DOWNLOADS_ENV, "").strip().lower() in (
209
+ "1",
210
+ "true",
211
+ "yes",
212
+ "on",
213
+ )
179
214
  _ENV_PROXIES, _ENV_BYPASS = _snapshot_env_proxies()
180
215
  _SYSTEM_PROXIES, _PAC_NOTICE = _read_system_proxies()
181
216
  _BYPASS_ENTRIES = (
@@ -185,7 +220,11 @@ def configure_from_env() -> None:
185
220
  if PROXY_URL and split_proxy(PROXY_URL) is None:
186
221
  # 不抛:抛出去 sidecar 直接起不来,用户看到的只是「插件加载失败」,看不出是自己
187
222
  # 填错了一个地址。记一行指向明确的日志,让侧栏里的能力摘要照实报成未配置。
188
- _log(f"ignoring an unusable {PROXY_ENV}: {PROXY_URL!r} (scheme must be one of {_PROXY_SCHEMES})")
223
+ # 日志面过 redact:代理地址常带 user:pass@,不能原样进宿主日志。
224
+ _log(
225
+ f"ignoring an unusable {PROXY_ENV}: {redact_url_secrets(PROXY_URL)!r}"
226
+ f" (scheme must be one of {_PROXY_SCHEMES})"
227
+ )
189
228
  PROXY_URL = ""
190
229
  if _PAC_NOTICE:
191
230
  _log(
@@ -311,10 +350,12 @@ def _run_readonly(argv: list[str]) -> str:
311
350
  :param argv: 命令与参数
312
351
  :returns: 标准输出;任何失败都返回空串
313
352
  """
314
- import subprocess
353
+ # 只读系统命令,参数全是本文件常量。
354
+ import subprocess # nosec B404
315
355
 
316
356
  try:
317
- done = subprocess.run( # noqa: S603 —— 参数是本文件里的常量,没有外部输入
357
+ # 参数是本文件里的常量,没有外部输入。
358
+ done = subprocess.run( # noqa: S603 # nosec B603
318
359
  argv,
319
360
  capture_output=True,
320
361
  text=True,
@@ -760,6 +801,51 @@ def _acceptable_resolved(item: ipaddress.IPv4Address | ipaddress.IPv6Address) ->
760
801
  return bool(SYNTHETIC_NETWORKS) and any(item in network for network in SYNTHETIC_NETWORKS)
761
802
 
762
803
 
804
+ # 逐主机解析结果的小缓存。浏览器路径的每个子资源都要过一次守卫,而解析是同步的:
805
+ # 解析器变慢或故障时,每个子资源都要等满一次解析超时,整页加载被逐个资源放大。
806
+ # 正向答案按常见 DNS TTL 的量级缓存;负向(解析失败)只缓存一小拍,让恢复先于缓存过期。
807
+ # 缓存放大的是「校验通过到真正建连」之间的 TOCTOU 窗口,量级与 DNS 自身的记录缓存同阶。
808
+ _DNS_CACHE: dict[str, tuple[float, list[str] | None]] = {}
809
+ _DNS_CACHE_LOCK = threading.Lock()
810
+ _DNS_CACHE_LIMIT = 1024
811
+ _DNS_TTL_OK_SECONDS = 60.0
812
+ _DNS_TTL_FAIL_SECONDS = 10.0
813
+
814
+
815
+ def _resolve_cached(host: str) -> list[str] | None:
816
+ """解析一个主机名,命中未过期的缓存就不出网。解析失败记 ``None``。
817
+
818
+ :param host: 主机名
819
+ :returns: 地址串列表;解析失败时为 None
820
+ """
821
+ now = time.monotonic()
822
+ with _DNS_CACHE_LOCK:
823
+ hit = _DNS_CACHE.get(host)
824
+ if hit is not None and hit[0] > now:
825
+ return hit[1]
826
+ try:
827
+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
828
+ except OSError:
829
+ answer = None
830
+ ttl = _DNS_TTL_FAIL_SECONDS
831
+ else:
832
+ answer = [str(info[4][0]) for info in infos]
833
+ ttl = _DNS_TTL_OK_SECONDS
834
+ with _DNS_CACHE_LOCK:
835
+ # 简单封顶:超限就先淘汰最早写入的条目。键数受「近期抓取的站点数」约束,
836
+ # 到得了上限说明键在净增长,FIFO 足够。
837
+ while len(_DNS_CACHE) >= _DNS_CACHE_LIMIT:
838
+ _DNS_CACHE.pop(next(iter(_DNS_CACHE)), None)
839
+ _DNS_CACHE[host] = (now + ttl, answer)
840
+ return answer
841
+
842
+
843
+ def _dns_cache_clear() -> None:
844
+ """清空解析缓存;测试换假解析器时用,生产路径不需要。"""
845
+ with _DNS_CACHE_LOCK:
846
+ _DNS_CACHE.clear()
847
+
848
+
763
849
  def is_public_address(host: str, *, proxied: bool = False) -> bool:
764
850
  """判定一个主机名/字面量是否指向公网地址。
765
851
 
@@ -796,32 +882,37 @@ def is_public_address(host: str, *, proxied: bool = False) -> bool:
796
882
  if "." not in host:
797
883
  return False
798
884
 
799
- try:
800
- infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
801
- except OSError:
885
+ answer = _resolve_cached(host)
886
+ if answer is None:
802
887
  if proxied:
803
888
  _log(f"local DNS has no answer for {host}; allowing it through the proxy")
804
889
  return True
805
890
  return False
806
891
  # 整张答案表都要是公网:混入一条私网即整体拒绝,避免 DNS 轮询绕过。
807
- addresses: Iterable[ipaddress.IPv4Address | ipaddress.IPv6Address] = (
808
- ipaddress.ip_address(info[4][0]) for info in infos
809
- )
892
+ addresses: Iterable[ipaddress.IPv4Address | ipaddress.IPv6Address] = (ipaddress.ip_address(item) for item in answer)
810
893
  resolved = [effective_ip(item) for item in addresses]
811
894
  return bool(resolved) and all(_acceptable_resolved(item) for item in resolved)
812
895
 
813
896
 
814
- def url_allowed(url: str) -> tuple[bool, str]:
897
+ def url_allowed(url: str, *, websocket: bool = False) -> tuple[bool, str]:
815
898
  """判定一个 URL 是否允许发出。
816
899
 
817
900
  :param url: 待判定的完整 URL
901
+ :param websocket: 按 WebSocket 握手的口径判(认 ws/wss);发出请求的那几条路径都不传
818
902
  :returns: (是否允许, 原因);允许时原因为空串
819
903
  """
820
904
  parsed = urlparse(url)
821
905
  # ws/wss 与 http/https 走同一套地址判定。WebSocket 握手是独立路由,page.route 拦不到,
822
906
  # 这里不认它就等于把公网 WebSocket 一起杀了 —— 不少站点的实时数据就靠它。
823
- if parsed.scheme not in ("http", "https", "ws", "wss"):
907
+ # 而真正**发出请求**的那几条路径(fetch/crawl/download/session)不认 ws:它们不会用
908
+ # ws 取字节,认了就是给「scheme 判拒」留一条按调用方变化的缝。
909
+ schemes = ("http", "https", "ws", "wss") if websocket else ("http", "https")
910
+ if parsed.scheme not in schemes:
824
911
  return False, f"unsupported URL scheme: {parsed.scheme!r}"
912
+ # 内嵌凭据一律判拒,Host 侧 url-policy 的同一条规则在这里也要成立:两道闸门一边严一边
913
+ # 松时,弱的那道就是那条能走的路。放行名单只豁免「地址必须公网」,不豁免这一条。
914
+ if parsed.username or parsed.password:
915
+ return False, "URL embeds credentials"
825
916
  host = parsed.hostname or ""
826
917
  if not host:
827
918
  return False, "URL has no host"
@@ -839,10 +930,10 @@ def install(page: Any) -> None:
839
930
  """把守卫注册到 Playwright 的 page 上。
840
931
 
841
932
  用法是交给 Scrapling 的 ``page_setup=install``。选择器用 ``**/*`` 以覆盖主导航、
842
- 子资源与 XHR;Scrapling 自己在 ``_get_page`` 里会先 ``page.unroute_all()`` 再注册它
843
- 自带的 handler,而 ``page_setup`` 在那之后才跑(见
844
- ``engines/_browsers/_controllers.py``:``_page_generator`` 在前,``page_setup`` 在后,
845
- ``goto`` 最后),所以我们的 handler 不会被冲掉,且每次重试都会重新注册。
933
+ 子资源与 XHR;Scrapling 自己在 ``engines/_browsers/_base.py`` 的 ``_get_page`` 里会先
934
+ ``page.unroute_all()`` 再注册它自带的 handler,而 ``page_setup`` 在那之后才跑(同仓
935
+ ``_stealth.py`` 在 ``_page_generator`` 给出的页上调用它,仍在 ``goto`` 之前),所以我们的
936
+ handler 不会被冲掉,且每次重试都会重新注册。
846
937
 
847
938
  放行时走 ``fallback()`` 而不是 ``continue_()``:Playwright 里多个匹配的 handler 逆序
848
939
  执行,而 ``continue_()`` 会**立刻**把请求放到网络上,跳过后面所有 handler。守卫排第一
@@ -873,36 +964,38 @@ def install(page: Any) -> None:
873
964
  else:
874
965
  route.continue_()
875
966
  else:
876
- _log(f"blocked {request.url}: {reason}")
967
+ _log(f"blocked {redact_url_secrets(request.url)}: {reason}")
877
968
  route.abort()
878
969
 
879
970
  def ws_handler(websocket: Any) -> None:
880
971
  url = getattr(websocket, "url", "")
881
- allowed, reason = url_allowed(url if isinstance(url, str) else "")
972
+ allowed, reason = url_allowed(url if isinstance(url, str) else "", websocket=True)
882
973
  if allowed:
883
974
  # 显式连一次而不是什么都不做:不连时 Playwright 自己放行,那条默认路径
884
975
  # 不经任何判定,显式连接才与 HTTP 侧摆在同一套逻辑里。
885
976
  websocket.connect_to_server()
886
977
  else:
887
- _log(f"blocked websocket {url}: {reason}")
978
+ _log(f"blocked websocket {redact_url_secrets(url)}: {reason}")
888
979
  websocket.close()
889
980
 
890
981
  page.route("**/*", handler)
891
982
 
892
- route_ws = getattr(page, "route_web_socket", None)
893
- if callable(route_ws):
894
- route_ws("**/*", ws_handler)
983
+ if websocket_guard_supported(page):
984
+ page.route_web_socket("**/*", ws_handler)
895
985
  else:
896
986
  _log("this Playwright build has no route_web_socket; WebSocket connections are not covered by the URL guard")
897
987
 
898
988
 
899
- def websocket_guard_supported(page: Any) -> bool:
900
- """page 上挂得上 WebSocket 守卫与否;供能力报告如实说明覆盖面。
989
+ def websocket_guard_supported(candidate: Any) -> bool:
990
+ """这一版 Playwright 拦不拦得住 WebSocket 握手;Page 类与 page 实例都收。
991
+
992
+ 能力报告在握手那一刻就要回答这一问题(那时还没有 page),而 :func:`install` 手上是
993
+ 真页面对象,所以两侧共用这一条判据,而不是各写一份 ``getattr``。
901
994
 
902
- :param page: Playwright 的 Page 对象
903
- :returns 是否支持拦截 WebSocket 握手
995
+ :param candidate: Playwright / patchright 的 Page 类或其实例
996
+ :returns: 是否支持拦截 WebSocket 握手
904
997
  """
905
- return callable(getattr(page, "route_web_socket", None))
998
+ return callable(getattr(candidate, "route_web_socket", None))
906
999
 
907
1000
 
908
1001
  def _log(message: str) -> None: