@jayyuen66/dsh-scrapling 0.1.5 → 0.1.7
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/CHANGELOG.md +81 -7
- package/LICENSE +1 -1
- package/README.md +20 -19
- package/README.zh-CN.md +18 -17
- package/THIRD_PARTY_NOTICES.md +32 -11
- package/bin/dsh-scrapling.mjs +68 -71
- package/client.js +9 -9
- package/cordis.patch.yml +7 -3
- package/docs/DETAIL.md +6 -6
- package/docs/DETAIL.zh.md +6 -6
- package/host.js +19 -33
- package/package.json +53 -47
- package/py/adapters.py +30 -8
- package/py/bridge.py +137 -30
- package/py/crawl.py +69 -27
- package/py/extraction.py +70 -24
- package/py/guard.py +55 -24
- package/py/media.py +30 -9
- package/py/redact.py +20 -2
- package/py/redis_storage.py +92 -31
- package/py/search.py +9 -2
- package/py/session_page.py +57 -24
package/py/crawl.py
CHANGED
|
@@ -151,7 +151,9 @@ def _allowed_domains(url: str) -> set[str]:
|
|
|
151
151
|
# 主机名与 host:port 都放进去:Scrapling 的域过滤可能按 hostname 比,也可能按
|
|
152
152
|
# netloc 比。少放一个的表现是「只爬到第一页就停」,不报错,很难一眼看出原因。
|
|
153
153
|
parsed = urlparse(url)
|
|
154
|
-
|
|
154
|
+
# 统一小写:_within_allowed_domains 拿 netloc.lower() 来比,集合里保留原大小写
|
|
155
|
+
# 会让 `http://Example.com:8080/` 的每一页都判成站外(只抓到 0 页且不报错)。
|
|
156
|
+
return {value.lower() for value in (parsed.hostname, parsed.netloc) if value}
|
|
155
157
|
|
|
156
158
|
|
|
157
159
|
def _within_allowed_domains(url: str, allowed: set[str]) -> bool:
|
|
@@ -282,17 +284,6 @@ def _session_config(manager: Any, url: str) -> None:
|
|
|
282
284
|
manager.add("default", FetcherSession(**session_kwargs))
|
|
283
285
|
|
|
284
286
|
|
|
285
|
-
def _policy_attrs(policy: dict[str, Any]) -> dict[str, Any]:
|
|
286
|
-
"""Spider 类属性上的待站策略(三种模板共用同一份)。"""
|
|
287
|
-
return {
|
|
288
|
-
"robots_txt_obey": policy["obey_robots"],
|
|
289
|
-
"download_delay": policy["delay_seconds"],
|
|
290
|
-
"concurrent_requests": policy["concurrency"],
|
|
291
|
-
"crawl_strategy": policy["strategy"],
|
|
292
|
-
"autothrottle_enabled": policy["autothrottle"],
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
|
|
296
287
|
def _make_spider(
|
|
297
288
|
url: str,
|
|
298
289
|
limit: int,
|
|
@@ -751,7 +742,7 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
751
742
|
# shopify 模式真正抓的主机可以来自 sitemapUrl:_make_shopify_spider 用它的 netloc 拼
|
|
752
743
|
# collections/products 两个 URL。而站内判定用的是 allowed_domains —— 两处取不同来源时
|
|
753
744
|
# spider 发出的每个请求都会被判成站外,一页都收不到。所以主机以真正要打的那一个为准。
|
|
754
|
-
domain_source =
|
|
745
|
+
domain_source = _domain_source_of(mode, url, sitemap_url, feed_url)
|
|
755
746
|
domains = _allowed_domains(domain_source)
|
|
756
747
|
|
|
757
748
|
# Host 闸门判的是这条 URL,但协议层不该假设调用方一定判过:这道复核与浏览器路径上
|
|
@@ -847,7 +838,7 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
847
838
|
"exclude_patterns": exclude_patterns,
|
|
848
839
|
},
|
|
849
840
|
)
|
|
850
|
-
except
|
|
841
|
+
except Exception as error:
|
|
851
842
|
with _CRAWL_LOCK:
|
|
852
843
|
_CRAWLS.pop(crawl_id, None)
|
|
853
844
|
if isinstance(error, AdapterError):
|
|
@@ -875,12 +866,8 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
875
866
|
# crawlStarted 必须在 start() **之前**发。反过来有两处会出错:一是快蜘蛛可能在这一帧落地
|
|
876
867
|
# 之前就先推了 progress,宿主侧「第一条是 crawlStarted」的读法于是变成随缘;二是万一这一帧
|
|
877
868
|
# 发不出去(stdout 断了、序列化炸了),异常抛给调用方时蜘蛛已经在跑 —— 调用方拿不到
|
|
878
|
-
# crawlId
|
|
879
|
-
|
|
880
|
-
"crawlStarted",
|
|
881
|
-
crawlId=crawl_id,
|
|
882
|
-
text=f"crawling {url} in {mode} mode (max {max_pages} items)",
|
|
883
|
-
)
|
|
869
|
+
# crawlId,就叫不停它,那个名额要一直占到进程退出。撤占位与重抛在 _announce_crawl_started 里。
|
|
870
|
+
_announce_crawl_started(crawl_id, f"crawling {url} in {mode} mode (max {max_pages} items)")
|
|
884
871
|
try:
|
|
885
872
|
thread.start()
|
|
886
873
|
except RuntimeError:
|
|
@@ -891,6 +878,25 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
891
878
|
return {"crawlId": crawl_id}
|
|
892
879
|
|
|
893
880
|
|
|
881
|
+
def _announce_crawl_started(crawl_id: str, message: str) -> None:
|
|
882
|
+
"""发 crawlStarted 帧;发不出去就撤掉占位再抛。
|
|
883
|
+
|
|
884
|
+
调用方此时已经登记了 spider 与 thread,但还没 start()。这一帧发不出去(stdout
|
|
885
|
+
断了、序列化炸了)时异常要抛给调用方,登记也必须撤掉:调用方拿不到 crawlId
|
|
886
|
+
就叫不停这条爬虫,留着的登记会被 _is_running 当成「正在跑」,名额一直占到
|
|
887
|
+
进程退出。
|
|
888
|
+
|
|
889
|
+
:param crawl_id: 爬虫登记键
|
|
890
|
+
:param message: 帧正文
|
|
891
|
+
"""
|
|
892
|
+
try:
|
|
893
|
+
_emit_event("crawlStarted", crawlId=crawl_id, text=message)
|
|
894
|
+
except BaseException:
|
|
895
|
+
with _CRAWL_LOCK:
|
|
896
|
+
_CRAWLS.pop(crawl_id, None)
|
|
897
|
+
raise
|
|
898
|
+
|
|
899
|
+
|
|
894
900
|
def _is_running(entry: dict[str, Any]) -> bool:
|
|
895
901
|
"""这个登记条目算不算「正在跑」。
|
|
896
902
|
|
|
@@ -940,6 +946,24 @@ def _get_crawl(crawl_id: Any) -> dict[str, Any]:
|
|
|
940
946
|
return entry
|
|
941
947
|
|
|
942
948
|
|
|
949
|
+
def _domain_source_of(
|
|
950
|
+
mode: str,
|
|
951
|
+
url: str,
|
|
952
|
+
sitemap_url: str | None,
|
|
953
|
+
feed_url: str | None,
|
|
954
|
+
) -> str:
|
|
955
|
+
"""真正被 spider 请求的那个地址:站内判定以它的主机为准。
|
|
956
|
+
|
|
957
|
+
sitemap / shopify 抓的是 sitemapUrl,feed 抓的是 feedUrl;起点 url 只决定默认值。
|
|
958
|
+
两处取不同来源时,spider 发出的每个请求都会被引擎判成站外。
|
|
959
|
+
"""
|
|
960
|
+
if mode in ("shopify", "sitemap"):
|
|
961
|
+
return sitemap_url or url
|
|
962
|
+
if mode == "feed":
|
|
963
|
+
return feed_url or url
|
|
964
|
+
return url
|
|
965
|
+
|
|
966
|
+
|
|
943
967
|
def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
944
968
|
"""查一个爬虫的状态与已收结果。
|
|
945
969
|
|
|
@@ -963,10 +987,12 @@ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
963
987
|
# 进锁里取一段:一边序列化一边追加,结果要么漏一页要么撞上 RuntimeError。
|
|
964
988
|
with _CRAWL_LOCK:
|
|
965
989
|
feed_rows = state.get("mode") in ("feed", "shopify")
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
990
|
+
# 锁内只取稳定快照:序列化计量与截断是纯 CPU 工作,放进全局锁会把所有
|
|
991
|
+
# worker 的 crawl.run / stop / close_all_crawls 串行化到回包速度上。
|
|
992
|
+
source = list(state["rows"] if feed_rows else state["pages"])
|
|
969
993
|
running = _is_running(entry)
|
|
994
|
+
total = len(source)
|
|
995
|
+
taken, more = _take_pages(source, since)
|
|
970
996
|
pages = [] if feed_rows else taken
|
|
971
997
|
rows = taken if feed_rows else []
|
|
972
998
|
return {
|
|
@@ -1006,7 +1032,19 @@ def _shrink_page(page: dict[str, Any], budget: int) -> dict[str, Any]:
|
|
|
1006
1032
|
:returns: 压过的新页(不就地改原对象,state 里留全量)
|
|
1007
1033
|
"""
|
|
1008
1034
|
if "markdown" not in page:
|
|
1009
|
-
|
|
1035
|
+
# feed/shopify 的行没有 markdown:退化成「反复把最长的字符串字段减半」。
|
|
1036
|
+
# 不处理这一类,超大的行仍会顶过 Host 的 8 MiB 切帧线。
|
|
1037
|
+
shrunk = dict(page)
|
|
1038
|
+
while len(json.dumps(shrunk, ensure_ascii=False).encode("utf-8")) > budget:
|
|
1039
|
+
key = max(
|
|
1040
|
+
(name for name, value in shrunk.items() if isinstance(value, str) and value),
|
|
1041
|
+
key=lambda name: len(shrunk[name]),
|
|
1042
|
+
default=None,
|
|
1043
|
+
)
|
|
1044
|
+
if key is None:
|
|
1045
|
+
break
|
|
1046
|
+
shrunk[key] = shrunk[key][: len(shrunk[key]) // 2]
|
|
1047
|
+
return {**shrunk, "truncated": True}
|
|
1010
1048
|
overhead = len(json.dumps({**page, "markdown": ""}, ensure_ascii=False).encode("utf-8"))
|
|
1011
1049
|
room = max(0, budget - overhead)
|
|
1012
1050
|
markdown = str(page.get("markdown", ""))
|
|
@@ -1062,10 +1100,14 @@ def _request_stop(entry: dict[str, Any]) -> bool:
|
|
|
1062
1100
|
state["deadline"] = time.monotonic()
|
|
1063
1101
|
with _CRAWL_LOCK:
|
|
1064
1102
|
spider = entry.get("spider")
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1103
|
+
worker = entry.get("thread")
|
|
1104
|
+
# 线程对象已登记但还没 start()(ident 为 None)也算「还没跑起来」:这段窗口里
|
|
1105
|
+
# 只调 pause 对未启动的引擎无效,worker 起手仍会照常抓取。
|
|
1106
|
+
if spider is None or worker is None or worker.ident is None:
|
|
1068
1107
|
entry["stop_requested"] = True
|
|
1108
|
+
running = False
|
|
1109
|
+
else:
|
|
1110
|
+
running = _is_running(entry)
|
|
1069
1111
|
if spider is not None and running:
|
|
1070
1112
|
with suppress(RuntimeError):
|
|
1071
1113
|
spider.pause()
|
package/py/extraction.py
CHANGED
|
@@ -17,6 +17,41 @@ def _json_len(value: Any) -> int:
|
|
|
17
17
|
return len(json.dumps(value, ensure_ascii=False))
|
|
18
18
|
|
|
19
19
|
|
|
20
|
+
def _fit_text(text: str, available: int) -> str:
|
|
21
|
+
"""把文本收到 JSON 序列化后不超过 available 个字符;预算不足时给空串。
|
|
22
|
+
|
|
23
|
+
按字符裁再量一次是不够的:JSON 会转义引号/反斜杠/控制字符,裁到 N 个字符的串
|
|
24
|
+
序列化后可能远超 N。这里直接按序列化长度二分,保证返回值的 json 长度落在预算内。
|
|
25
|
+
"""
|
|
26
|
+
if available < _json_len(""):
|
|
27
|
+
return ""
|
|
28
|
+
if _json_len(text) <= available:
|
|
29
|
+
return text
|
|
30
|
+
low, high = 0, len(text)
|
|
31
|
+
while low < high:
|
|
32
|
+
middle = (low + high + 1) // 2
|
|
33
|
+
if _json_len(text[:middle]) <= available:
|
|
34
|
+
low = middle
|
|
35
|
+
else:
|
|
36
|
+
high = middle - 1
|
|
37
|
+
return text[:low]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _json_value_within(value: Any, room: int) -> tuple[Any, int, bool]:
|
|
41
|
+
"""把值收进 room 的 JSON 预算;返回 (值, 实际长度, 是否被裁)。
|
|
42
|
+
|
|
43
|
+
字符串按序列化长度收缩;其它形态(列表、对象)没有便宜的收缩方式,超预算时
|
|
44
|
+
降级为 null —— 留着整段会让调用方拿到的载荷远超 maxContentChars。
|
|
45
|
+
"""
|
|
46
|
+
size = _json_len(value)
|
|
47
|
+
if size <= room:
|
|
48
|
+
return value, size, False
|
|
49
|
+
if isinstance(value, str) and room >= _json_len(""):
|
|
50
|
+
fitted = _fit_text(value, room)
|
|
51
|
+
return fitted, _json_len(fitted), True
|
|
52
|
+
return None, _json_len(None), True
|
|
53
|
+
|
|
54
|
+
|
|
20
55
|
def _resolve_url(page: Any, value: str) -> str:
|
|
21
56
|
"""把相对地址拼成绝对地址;空值或拼不出来时保留原值。"""
|
|
22
57
|
if not value:
|
|
@@ -27,15 +62,15 @@ def _resolve_url(page: Any, value: str) -> str:
|
|
|
27
62
|
return value
|
|
28
63
|
|
|
29
64
|
|
|
30
|
-
def _query_type(
|
|
31
|
-
"""把旧的 ``useXpath`` 布尔值归一到 queryType。"""
|
|
65
|
+
def _query_type(query_type: str | None, use_xpath: bool) -> str:
|
|
66
|
+
"""把旧的 ``useXpath`` 布尔值归一到 queryType:显式 queryType 优先,其次 useXpath,最后 css。"""
|
|
32
67
|
return query_type or ("xpath" if use_xpath else "css")
|
|
33
68
|
|
|
34
69
|
|
|
35
70
|
def query_nodes(
|
|
36
71
|
page: Any,
|
|
37
72
|
selector: str,
|
|
38
|
-
query_type: str =
|
|
73
|
+
query_type: str | None = None,
|
|
39
74
|
*,
|
|
40
75
|
use_xpath: bool = False,
|
|
41
76
|
partial: bool = False,
|
|
@@ -51,7 +86,7 @@ def query_nodes(
|
|
|
51
86
|
"""
|
|
52
87
|
if not isinstance(selector, str) or not selector:
|
|
53
88
|
raise ValueError("selector is required")
|
|
54
|
-
kind = _query_type(
|
|
89
|
+
kind = _query_type(query_type, use_xpath)
|
|
55
90
|
if kind == "css":
|
|
56
91
|
return list(page.css(selector)), ""
|
|
57
92
|
if kind == "xpath":
|
|
@@ -199,23 +234,21 @@ def collect_fields(
|
|
|
199
234
|
rows: list[dict[str, Any]] = []
|
|
200
235
|
spent = 0
|
|
201
236
|
truncated = False
|
|
202
|
-
|
|
237
|
+
node_iter = iter(nodes)
|
|
238
|
+
for node in node_iter:
|
|
203
239
|
row: dict[str, Any] = {}
|
|
204
240
|
for name, spec in fields.items():
|
|
205
241
|
value = field_value(node, spec, page=page, resolve_urls=resolve_urls)
|
|
206
242
|
room = max(0, max_content_chars - spent)
|
|
207
|
-
size =
|
|
208
|
-
|
|
209
|
-
if isinstance(value, str):
|
|
210
|
-
# JSON 字符串带两个引号;留出它们再把正文裁到剩余预算。
|
|
211
|
-
value = value[: max(0, room - 2)]
|
|
212
|
-
size = _json_len(value)
|
|
213
|
-
truncated = True
|
|
243
|
+
value, size, dropped = _json_value_within(value, room)
|
|
244
|
+
truncated = truncated or dropped
|
|
214
245
|
spent += size
|
|
215
246
|
row[str(name)] = value
|
|
216
247
|
rows.append(row)
|
|
217
248
|
if spent >= max_content_chars:
|
|
218
|
-
|
|
249
|
+
# 只有确实还有下一条时才算截断:最后一条刚好用尽预算不是截断。
|
|
250
|
+
if next(node_iter, None) is not None:
|
|
251
|
+
truncated = True
|
|
219
252
|
break
|
|
220
253
|
return rows, truncated
|
|
221
254
|
|
|
@@ -234,11 +267,13 @@ def locate(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
234
267
|
if url is not None and not isinstance(url, str):
|
|
235
268
|
raise ValueError("url must be a string or null")
|
|
236
269
|
query_type = args.get("queryType")
|
|
237
|
-
if query_type is not None
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
270
|
+
if query_type is not None:
|
|
271
|
+
if not isinstance(query_type, str):
|
|
272
|
+
raise ValueError("queryType must be a string")
|
|
273
|
+
if query_type not in ("css", "xpath", "text", "regex", "similar"):
|
|
274
|
+
raise ValueError(f"unknown queryType: {query_type}")
|
|
275
|
+
# 缺省留 None 交给 query_nodes 归一:显式 queryType 优先,其次 useXpath,最后 css。
|
|
276
|
+
# 这里先落成 "css" 会让调用方传的 useXpath 永远失效("//p" 被当 CSS 选择器,命中 0)。
|
|
242
277
|
limit = _positive_int(args.get("limit"), "limit", 200)
|
|
243
278
|
budget = _positive_int(args.get("maxContentChars"), "maxContentChars", 200_000)
|
|
244
279
|
include_ancestors = bool(args.get("includeAncestors", True))
|
|
@@ -259,16 +294,13 @@ def locate(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
259
294
|
matches: list[dict[str, Any]] = []
|
|
260
295
|
spent = 0
|
|
261
296
|
truncated = False
|
|
262
|
-
|
|
297
|
+
node_iter = iter(nodes)
|
|
298
|
+
for node in node_iter:
|
|
263
299
|
if len(matches) >= limit:
|
|
264
300
|
truncated = True
|
|
265
301
|
break
|
|
266
302
|
text = str(node.get_all_text(strip=True))
|
|
267
303
|
room = max(0, budget - spent)
|
|
268
|
-
if len(text) > room:
|
|
269
|
-
text = text[:room]
|
|
270
|
-
truncated = True
|
|
271
|
-
spent += len(text)
|
|
272
304
|
item: dict[str, Any] = {
|
|
273
305
|
"tag": str(getattr(node, "tag", "") or ""),
|
|
274
306
|
"text": text,
|
|
@@ -289,9 +321,23 @@ def locate(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
289
321
|
else []
|
|
290
322
|
),
|
|
291
323
|
}
|
|
324
|
+
size = _json_len(item)
|
|
325
|
+
if size > room:
|
|
326
|
+
# 预算按整条载荷算:attributes、四个选择器与 ancestors 都占字符,只量 text
|
|
327
|
+
# 会让真实返回体远超 maxContentChars。先把正文收到剩余预算,再复核一次。
|
|
328
|
+
fixed = _json_len({**item, "text": ""})
|
|
329
|
+
item["text"] = _fit_text(text, max(0, room - fixed))
|
|
330
|
+
size = _json_len(item)
|
|
331
|
+
truncated = True
|
|
332
|
+
if size > room:
|
|
333
|
+
# 连不含正文的固定结构都放不下:这一条不再进结果,预算到此为止。
|
|
334
|
+
break
|
|
335
|
+
spent += size
|
|
292
336
|
matches.append(item)
|
|
293
337
|
if spent >= budget:
|
|
294
|
-
|
|
338
|
+
# 只有确实还有下一条时才算截断:最后一条刚好用尽预算不是截断。
|
|
339
|
+
if next(node_iter, None) is not None:
|
|
340
|
+
truncated = True
|
|
295
341
|
break
|
|
296
342
|
return {
|
|
297
343
|
"count": len(nodes),
|
package/py/guard.py
CHANGED
|
@@ -150,6 +150,14 @@ def configure(
|
|
|
150
150
|
ALLOWED_HOSTS = allowed_hosts
|
|
151
151
|
if nat64_prefixes is not None:
|
|
152
152
|
EXTRA_NAT64_PREFIXES = nat64_prefixes
|
|
153
|
+
for raw in nat64_prefixes:
|
|
154
|
+
try:
|
|
155
|
+
network = ipaddress.ip_network(raw, strict=True)
|
|
156
|
+
except ValueError:
|
|
157
|
+
_log(f"ignoring an invalid extra NAT64 prefix {raw!r}")
|
|
158
|
+
continue
|
|
159
|
+
if not isinstance(network, ipaddress.IPv6Network) or network.prefixlen not in _NAT64_EMBEDDED_OFFSET:
|
|
160
|
+
_log(f"ignoring an unsupported extra NAT64 prefix {raw!r} (need /40, /48, /56, /64 or /96)")
|
|
153
161
|
if allow_write_methods is not None:
|
|
154
162
|
ALLOW_WRITE_METHODS = allow_write_methods
|
|
155
163
|
if allow_browser_actions is not None:
|
|
@@ -228,7 +236,7 @@ def configure_from_env() -> None:
|
|
|
228
236
|
PROXY_URL = ""
|
|
229
237
|
if _PAC_NOTICE:
|
|
230
238
|
_log(
|
|
231
|
-
f"system proxy is a PAC script ({_PAC_NOTICE}); it is not evaluated here — "
|
|
239
|
+
f"system proxy is a PAC script ({redact_url_secrets(_PAC_NOTICE)}); it is not evaluated here — "
|
|
232
240
|
f"set {PROXY_ENV} (the settings card's proxy) to the proxy address you want"
|
|
233
241
|
)
|
|
234
242
|
if _SYSTEM_PROXIES and not (PROXY_URL or _ENV_PROXIES):
|
|
@@ -422,6 +430,11 @@ def _host_matches(host: str, entry: str) -> bool:
|
|
|
422
430
|
:param entry: 清单里的一项(可能带前导 ``.`` 或 ``*``)
|
|
423
431
|
:returns: 是否命中
|
|
424
432
|
"""
|
|
433
|
+
if entry.strip() == "*":
|
|
434
|
+
# 整条星号是「全部绕过」。不放这里认它,它会被 lstrip 成空串再落到
|
|
435
|
+
# not item 那条假分支上 —— default_proxy 单独特判过它,两条路于是对同一份
|
|
436
|
+
# 配置给出相反答案(会话直连、静态抓取仍走代理)。
|
|
437
|
+
return True
|
|
425
438
|
item = entry.strip().lower().lstrip("*")
|
|
426
439
|
if not item:
|
|
427
440
|
return False
|
|
@@ -736,47 +749,59 @@ def effective_ip(
|
|
|
736
749
|
# 检测合成解析器用的控制域名:与用户的目标无关,答案只反映解析器本身的行为。
|
|
737
750
|
CONTROL_HOSTS: tuple[str, ...] = ("example.com", "www.iana.org", "www.wikipedia.org")
|
|
738
751
|
|
|
739
|
-
#
|
|
740
|
-
|
|
752
|
+
# 检测结果:认出的那个合成池;只算一次并缓存。None = 没有认出(或控制答案不构成单一池)。
|
|
753
|
+
_SYNTHETIC_POOL: ipaddress.IPv4Network | None = None
|
|
741
754
|
|
|
742
755
|
|
|
743
|
-
def detect_synthetic_resolver() ->
|
|
744
|
-
"""
|
|
756
|
+
def detect_synthetic_resolver() -> ipaddress.IPv4Network | None:
|
|
757
|
+
"""判断当前解析器是不是在合成地址,并给出要放宽到的那**一个**池。
|
|
745
758
|
|
|
746
759
|
依据是 fake-ip 的指纹:**所有**主机名都被指到同一个非公网小池里。实测在一台开着 TUN +
|
|
747
760
|
fake-ip 的机器上,example.com / github.com / wikipedia.org / echarts.apache.org /
|
|
748
761
|
www.apple.com 全部落在 198.18.0.0/15 内且互不相同,而 IP 字面量原样不动。
|
|
749
762
|
|
|
750
|
-
|
|
751
|
-
|
|
763
|
+
每个控制域名都要有答案,且全部答案落在**同一个**已知池里;跨池分流或有一枚落在池外都
|
|
764
|
+
判否。100.64.0.0/10 同时是 Tailscale 等真实内网常用的 CGNAT 段,拿另一个池的检测结果
|
|
765
|
+
把这一整段放宽,会让指向真实 ``100.64.x.x`` 的域名通过闸门。判否只让守卫维持最严,
|
|
766
|
+
不会误放行。
|
|
752
767
|
|
|
753
|
-
:returns:
|
|
768
|
+
:returns: 认出的合成池;判否时 None
|
|
754
769
|
"""
|
|
755
|
-
global
|
|
756
|
-
if
|
|
757
|
-
return
|
|
770
|
+
global _SYNTHETIC_POOL # noqa: PLW0603 —— 缓存一次即可
|
|
771
|
+
if _SYNTHETIC_POOL is not None:
|
|
772
|
+
return _SYNTHETIC_POOL
|
|
758
773
|
resolved: list[str] = []
|
|
759
774
|
for host in CONTROL_HOSTS:
|
|
760
775
|
try:
|
|
761
776
|
infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
|
|
762
777
|
except OSError:
|
|
763
|
-
|
|
764
|
-
|
|
778
|
+
return None
|
|
779
|
+
addresses = [str(info[4][0]) for info in infos]
|
|
780
|
+
# 每个域名都要有答案:只校验总数时,一个域名回三条、另外两个解析失败也能凑够 3,
|
|
781
|
+
# 那三条同源答案不构成「所有主机名都被指到同一个池」的指纹。
|
|
782
|
+
if not addresses:
|
|
783
|
+
return None
|
|
765
784
|
# getaddrinfo 的答案元素是 str | int(sockaddr 的形状),而这里只要地址串。
|
|
766
|
-
resolved.extend(
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
return
|
|
785
|
+
resolved.extend(addresses)
|
|
786
|
+
# 全指向同一处(解析器坏了)不当成 fake-ip。
|
|
787
|
+
if len(set(resolved)) < 2:
|
|
788
|
+
return None
|
|
770
789
|
parsed = []
|
|
771
790
|
for item in resolved:
|
|
772
791
|
try:
|
|
773
792
|
parsed.append(ipaddress.ip_address(item))
|
|
774
793
|
except ValueError:
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
794
|
+
return None
|
|
795
|
+
if not all(not item.is_global for item in parsed):
|
|
796
|
+
return None
|
|
797
|
+
if not all(isinstance(item, ipaddress.IPv4Address) for item in parsed):
|
|
798
|
+
return None
|
|
799
|
+
# 全部答案必须落在同一个池;命中不止一个池说明解析器跨池分流,判否。
|
|
800
|
+
for pool in SYNTHETIC_POOLS:
|
|
801
|
+
if isinstance(pool, ipaddress.IPv4Network) and all(item in pool for item in parsed):
|
|
802
|
+
_SYNTHETIC_POOL = pool
|
|
803
|
+
return _SYNTHETIC_POOL
|
|
804
|
+
return None
|
|
780
805
|
|
|
781
806
|
|
|
782
807
|
def _acceptable_resolved(item: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
|
|
@@ -796,7 +821,8 @@ def _acceptable_resolved(item: ipaddress.IPv4Address | ipaddress.IPv6Address) ->
|
|
|
796
821
|
return True
|
|
797
822
|
if not isinstance(item, ipaddress.IPv4Address):
|
|
798
823
|
return False
|
|
799
|
-
|
|
824
|
+
synthetic_pool = detect_synthetic_resolver()
|
|
825
|
+
if synthetic_pool is not None and item in synthetic_pool:
|
|
800
826
|
return True
|
|
801
827
|
return bool(SYNTHETIC_NETWORKS) and any(item in network for network in SYNTHETIC_NETWORKS)
|
|
802
828
|
|
|
@@ -901,7 +927,12 @@ def url_allowed(url: str, *, websocket: bool = False) -> tuple[bool, str]:
|
|
|
901
927
|
:param websocket: 按 WebSocket 握手的口径判(认 ws/wss);发出请求的那几条路径都不传
|
|
902
928
|
:returns: (是否允许, 原因);允许时原因为空串
|
|
903
929
|
"""
|
|
904
|
-
|
|
930
|
+
try:
|
|
931
|
+
parsed = urlparse(url)
|
|
932
|
+
except ValueError:
|
|
933
|
+
# 畸形 URL(如 http://[::1 缺少右括号)在 urlparse 里就抛 ValueError。
|
|
934
|
+
# 契约是「返回 (False, reason)」,让异常漏出去会把一个坏输入变成调用方的崩溃。
|
|
935
|
+
return False, "URL is malformed"
|
|
905
936
|
# ws/wss 与 http/https 走同一套地址判定。WebSocket 握手是独立路由,page.route 拦不到,
|
|
906
937
|
# 这里不认它就等于把公网 WebSocket 一起杀了 —— 不少站点的实时数据就靠它。
|
|
907
938
|
# 而真正**发出请求**的那几条路径(fetch/crawl/download/session)不认 ws:它们不会用
|
package/py/media.py
CHANGED
|
@@ -229,15 +229,16 @@ def _download_via_stream(
|
|
|
229
229
|
try:
|
|
230
230
|
with open(temporary, "wb") as sink:
|
|
231
231
|
for chunk in response.iter_content(chunk_size=_DOWNLOAD_CHUNK_BYTES):
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
total += len(chunk)
|
|
235
|
-
if total > limit:
|
|
232
|
+
# 先判后写:写盘再判会让落盘字节超过上限最多一个块(64 KiB)。
|
|
233
|
+
if total + len(chunk) > limit:
|
|
236
234
|
raise _error(
|
|
237
235
|
"DOWNLOAD_TOO_LARGE",
|
|
238
236
|
f"download is over the {limit}-byte cap"
|
|
239
237
|
+ (f" (Content-Length declared {int(declared)})" if declared.isdigit() else ""),
|
|
240
238
|
)
|
|
239
|
+
sink.write(chunk)
|
|
240
|
+
digest.update(chunk)
|
|
241
|
+
total += len(chunk)
|
|
241
242
|
target = _commit_temp(directory, name, temporary)
|
|
242
243
|
except BaseException:
|
|
243
244
|
temporary.unlink(missing_ok=True)
|
|
@@ -300,10 +301,13 @@ def _download_via_browser(
|
|
|
300
301
|
browser_params["extra_headers"] = headers
|
|
301
302
|
try:
|
|
302
303
|
response = StealthyFetcher.fetch(url, **browser_params)
|
|
303
|
-
except Exception as error:
|
|
304
|
+
except Exception as error:
|
|
304
305
|
# 「Page.goto: Download is starting」:Chromium 不能把「触发下载的响应」当成一次
|
|
305
306
|
# 导航,fetch 这条路对附件/二进制响应天然走不通。换成等真实的 download 事件再把它
|
|
306
|
-
#
|
|
307
|
+
# 落盘。其它异常(超时、网络错误、路由拒绝)仍按失败上报:这里再导航一次会重复请求,
|
|
308
|
+
# 还会把真实原因盖成附件路径的异常类名。
|
|
309
|
+
if "download is starting" not in str(error).lower():
|
|
310
|
+
raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}: {error}") from error
|
|
307
311
|
return _download_via_browser_attachment(
|
|
308
312
|
url,
|
|
309
313
|
name=name,
|
|
@@ -331,6 +335,21 @@ def _download_via_browser(
|
|
|
331
335
|
}
|
|
332
336
|
|
|
333
337
|
|
|
338
|
+
def _body_from_download(source: Any, limit: int) -> bytes:
|
|
339
|
+
"""读浏览器交出的下载临时文件;先量大小再读,超限时不把整份内容读进内存。
|
|
340
|
+
|
|
341
|
+
Download.path() 给的是本地临时文件,所以体积在打开之前就知道。先 read_bytes
|
|
342
|
+
再判上限意味着一个几 GB 的附件会先被整份读进内存、然后才被拒绝。
|
|
343
|
+
"""
|
|
344
|
+
if source is None:
|
|
345
|
+
raise _error("DOWNLOAD_FAILED", "download produced no local file")
|
|
346
|
+
path = Path(source)
|
|
347
|
+
size = path.stat().st_size
|
|
348
|
+
if size > limit:
|
|
349
|
+
raise _error("DOWNLOAD_TOO_LARGE", f"download is {size} bytes, over the {limit}-byte cap")
|
|
350
|
+
return path.read_bytes()
|
|
351
|
+
|
|
352
|
+
|
|
334
353
|
def _download_via_browser_attachment(
|
|
335
354
|
url: str,
|
|
336
355
|
*,
|
|
@@ -348,7 +367,7 @@ def _download_via_browser_attachment(
|
|
|
348
367
|
与一次性路径同一套网络守卫,然后等 Playwright 的 ``expect_download`` 把附件交出来。
|
|
349
368
|
"""
|
|
350
369
|
import guard
|
|
351
|
-
from adapters import page_setup
|
|
370
|
+
from adapters import AdapterError, page_setup
|
|
352
371
|
from scrapling.fetchers import StealthySession
|
|
353
372
|
|
|
354
373
|
timeout_ms = int(timeout * 1000)
|
|
@@ -369,8 +388,10 @@ def _download_via_browser_attachment(
|
|
|
369
388
|
with page.expect_download(timeout=timeout_ms) as pending, contextlib.suppress(Exception):
|
|
370
389
|
page.goto(url, wait_until="commit")
|
|
371
390
|
download = pending.value
|
|
372
|
-
|
|
373
|
-
|
|
391
|
+
body = _body_from_download(download.path(), limit)
|
|
392
|
+
except AdapterError:
|
|
393
|
+
# 超限是 caller 可读的结论(DOWNLOAD_TOO_LARGE),别再包成 DOWNLOAD_FAILED。
|
|
394
|
+
raise
|
|
374
395
|
except Exception as error:
|
|
375
396
|
raise _error(
|
|
376
397
|
"DOWNLOAD_FAILED",
|
package/py/redact.py
CHANGED
|
@@ -6,8 +6,16 @@ guard 的日志与 adapters 的网络摘要在「给日志、给模型看」之
|
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
+
import re
|
|
9
10
|
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
|
10
11
|
|
|
12
|
+
# 畸形 URL(urlsplit 抛 ValueError)上仍要按参数名兜底:解析失败不能等于「整串放行」。
|
|
13
|
+
_QUERY_SECRET_FALLBACK = re.compile(
|
|
14
|
+
r"(?i)([?&;](?:token|key|secret|password|pwd|sig|signature|auth|session)[^=&#]*=)[^&#]*"
|
|
15
|
+
)
|
|
16
|
+
# 这些 scheme 的 ``@`` 属于地址本身(mailto/tel 之类),不是 user:pass@host 的 authority。
|
|
17
|
+
_NON_AUTHORITY_SCHEMES = frozenset({"mailto", "tel", "data", "javascript", "urn", "about", "blob"})
|
|
18
|
+
|
|
11
19
|
# 查询串里这些名字的参数装的是凭据而不是筛选条件。XHR 摘要与守卫日志都是要离开本进程的
|
|
12
20
|
# 文本——摘要进会话上下文、进第三方 provider,日志进宿主日志面——而真实站点把 access
|
|
13
21
|
# token、会话 id、签名都放在查询串里。抓到一条就等于把凭据抄进载体,而读者既用不上它、
|
|
@@ -18,6 +26,14 @@ _SECRET_QUERY_KEYS = frozenset(
|
|
|
18
26
|
"access_token",
|
|
19
27
|
"api_key",
|
|
20
28
|
"apikey",
|
|
29
|
+
"client_secret",
|
|
30
|
+
"x-api-key",
|
|
31
|
+
"x-amz-credential",
|
|
32
|
+
"x-amz-signature",
|
|
33
|
+
"x-amz-security-token",
|
|
34
|
+
"x-goog-signature",
|
|
35
|
+
"private_key",
|
|
36
|
+
"jwt",
|
|
21
37
|
"auth",
|
|
22
38
|
"auth_token",
|
|
23
39
|
"authorization",
|
|
@@ -96,13 +112,15 @@ def redact_url_secrets(raw: str) -> str:
|
|
|
96
112
|
try:
|
|
97
113
|
parsed = urlsplit(raw)
|
|
98
114
|
except ValueError:
|
|
99
|
-
return raw
|
|
115
|
+
return _QUERY_SECRET_FALLBACK.sub(r"\1<redacted>", raw)
|
|
100
116
|
# 没有 scheme 的 ``user:pass@host:8080`` 会被 urlsplit 读成 scheme='user'、
|
|
101
117
|
# path='pass@host:8080':netloc 为空,下面按 netloc 摘 userinfo 的那一步什么都不做,
|
|
102
118
|
# 整条代理口令于是原样漏进日志(PROXY_URL 不可用那条日志正是这么来的)。这种形态的
|
|
103
119
|
# authority 落在 path 的第一段上,按同一套规则摘掉;误读成 scheme 的那段一起丢弃。
|
|
104
120
|
authority, slash, rest = parsed.path.partition("/")
|
|
105
|
-
standalone_authority =
|
|
121
|
+
standalone_authority = (
|
|
122
|
+
not parsed.netloc and "@" in authority and parsed.scheme.lower() not in _NON_AUTHORITY_SCHEMES
|
|
123
|
+
)
|
|
106
124
|
if standalone_authority:
|
|
107
125
|
path = authority.rpartition("@")[2] + slash + rest
|
|
108
126
|
netloc = ""
|