@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.
- package/CHANGELOG.md +83 -0
- package/README.md +141 -19
- package/README.zh-CN.md +141 -19
- package/THIRD_PARTY_NOTICES.md +20 -2
- package/bin/dsh-scrapling.mjs +13 -0
- package/client.js +11 -3
- package/cordis.patch.yml +1 -1
- package/host.js +40 -36
- package/package.json +26 -9
- package/py/adapters.py +763 -267
- package/py/bridge.py +27 -4
- package/py/crawl.py +640 -90
- package/py/extraction.py +400 -0
- package/py/guard.py +120 -27
- package/py/media.py +474 -0
- package/py/redact.py +118 -0
- package/py/redis_storage.py +129 -0
- package/py/runtime-requirements.txt +49 -0
- package/py/search.py +404 -0
- package/py/session_page.py +240 -0
- package/runtime-manifest.json +16 -0
package/py/media.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
"""下载落盘与截图字节。两者都不经过正文清洗:字节就是字节。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import contextlib
|
|
7
|
+
import hashlib
|
|
8
|
+
import os
|
|
9
|
+
import struct
|
|
10
|
+
import uuid
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import urlparse
|
|
14
|
+
|
|
15
|
+
DEFAULT_DOWNLOAD_MAX_BYTES = 10 * 1024 * 1024
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _error(code: str, message: str) -> Exception:
|
|
19
|
+
from adapters import AdapterError
|
|
20
|
+
|
|
21
|
+
return AdapterError(code, message)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _safe_name(raw: Any, url: str) -> str:
|
|
25
|
+
"""把调用方给的文件名收成目录内的纯文件名;任何路径成分都拒绝。"""
|
|
26
|
+
name = raw if isinstance(raw, str) and raw else Path(urlparse(url).path).name
|
|
27
|
+
if not name:
|
|
28
|
+
name = "download.bin"
|
|
29
|
+
if "\x00" in name or "/" in name or "\\" in name:
|
|
30
|
+
raise _error("DOWNLOAD_PATH", "filename must not contain path separators or NUL")
|
|
31
|
+
if name in (".", "..") or os.path.isabs(name):
|
|
32
|
+
raise _error("DOWNLOAD_PATH", "filename must be a plain file name")
|
|
33
|
+
return name
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _claim_path(directory: Path, name: str) -> Path:
|
|
37
|
+
"""占住一个当前不存在的目标名并创建空文件;占不住就按 -1、-2… 往后找。
|
|
38
|
+
|
|
39
|
+
「探测」与「占位」必须是同一原子操作:O_EXCL 的创建语义保证了两个并发下载不可能
|
|
40
|
+
各自都以为拿到了同一个名字——而先 ``exists()`` 再写的那两步之间,另一路可以整个
|
|
41
|
+
走完,后落盘的 ``os.replace`` 就把先到的那份覆盖掉了。占位本身产生一个空文件,
|
|
42
|
+
正常路径随后会被 ``os.replace`` 原子覆盖成正文。
|
|
43
|
+
"""
|
|
44
|
+
candidate = directory / name
|
|
45
|
+
stem = candidate.stem
|
|
46
|
+
suffix = candidate.suffix
|
|
47
|
+
index = 0
|
|
48
|
+
while True:
|
|
49
|
+
try:
|
|
50
|
+
handle = os.open(candidate, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
|
|
51
|
+
except FileExistsError:
|
|
52
|
+
index += 1
|
|
53
|
+
candidate = directory / f"{stem}-{index}{suffix}"
|
|
54
|
+
continue
|
|
55
|
+
os.close(handle)
|
|
56
|
+
return candidate
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _release_claim(target: Path) -> None:
|
|
60
|
+
"""撤掉一个尚未被正文覆盖的占位空文件;占位可能已被覆盖或已被撤,缺席不算错。"""
|
|
61
|
+
try:
|
|
62
|
+
if target.stat().st_size == 0:
|
|
63
|
+
target.unlink()
|
|
64
|
+
except OSError:
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _temp_path(directory: Path, name: str) -> Path:
|
|
69
|
+
"""一次落盘的临时文件名:点前缀 + uuid,让「写到一半」的文件不会撞上任何正名。"""
|
|
70
|
+
return directory / f".{name}.{uuid.uuid4().hex}.part"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _header_value(headers: Any, name: str) -> str:
|
|
74
|
+
"""按大小写不敏感读一个响应头;读不到给空串。dict 与 curl_cffi 的 Headers 都适用。"""
|
|
75
|
+
try:
|
|
76
|
+
items = list(headers.items())
|
|
77
|
+
except Exception: # noqa: BLE001 —— 形状不对就当没有这个头
|
|
78
|
+
return ""
|
|
79
|
+
for key, value in items:
|
|
80
|
+
if str(key).lower() == name.lower():
|
|
81
|
+
return str(value)
|
|
82
|
+
return ""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _commit_temp(directory: Path, name: str, temporary: Path) -> Path:
|
|
86
|
+
"""把已写完的临时文件落成正式名:占位 + 原子替换,不覆盖任何已存在的文件。"""
|
|
87
|
+
target = _claim_path(directory, name)
|
|
88
|
+
try:
|
|
89
|
+
os.replace(temporary, target)
|
|
90
|
+
except OSError:
|
|
91
|
+
_release_claim(target)
|
|
92
|
+
raise
|
|
93
|
+
return target
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _download_dir(args: dict[str, Any]) -> Path:
|
|
97
|
+
deployment = args.get("deployment")
|
|
98
|
+
configured = deployment.get("downloadDir") if isinstance(deployment, dict) else None
|
|
99
|
+
if isinstance(configured, str) and configured:
|
|
100
|
+
return Path(configured)
|
|
101
|
+
return Path.home() / ".dsh-scrapling" / "downloads"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _max_bytes(args: dict[str, Any]) -> int:
|
|
105
|
+
"""下载字节上限。
|
|
106
|
+
|
|
107
|
+
部署侧的 ``downloadMaxBytes`` 是**硬上限**:模型给的 ``maxBytes`` 只能在它下面
|
|
108
|
+
往下收,不能把它顶掉。早先只在 ``maxBytes`` 缺席时才读部署项,于是模型随手写一个
|
|
109
|
+
大数就绕过了运维定的那道闸。
|
|
110
|
+
"""
|
|
111
|
+
deployment = args.get("deployment")
|
|
112
|
+
configured = deployment.get("downloadMaxBytes") if isinstance(deployment, dict) else None
|
|
113
|
+
if configured is not None and (not isinstance(configured, int) or isinstance(configured, bool) or configured <= 0):
|
|
114
|
+
# 部署项写坏不悄悄回落默认值:那会让人以为「上限是默认的那一档」,而实际配置没生效。
|
|
115
|
+
raise _error("BAD_ARGS", "deployment.downloadMaxBytes must be a positive integer")
|
|
116
|
+
ceiling = configured if isinstance(configured, int) else DEFAULT_DOWNLOAD_MAX_BYTES
|
|
117
|
+
raw = args.get("maxBytes")
|
|
118
|
+
if raw is None:
|
|
119
|
+
return ceiling
|
|
120
|
+
if not isinstance(raw, int) or isinstance(raw, bool) or raw <= 0:
|
|
121
|
+
raise _error("BAD_ARGS", "maxBytes must be a positive integer")
|
|
122
|
+
return min(raw, ceiling)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
_DOWNLOAD_CHUNK_BYTES = 64 * 1024
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def download(args: dict[str, Any]) -> dict[str, Any]:
|
|
129
|
+
"""取一个 URL 的字节并写进下载目录;流式落盘,不覆盖、不越界。"""
|
|
130
|
+
import guard
|
|
131
|
+
|
|
132
|
+
if not guard.ALLOW_FILE_DOWNLOADS:
|
|
133
|
+
raise _error(
|
|
134
|
+
"DOWNLOAD_DISABLED",
|
|
135
|
+
f"file downloads are disabled; the deployment must set {guard.ALLOW_FILE_DOWNLOADS_ENV}",
|
|
136
|
+
)
|
|
137
|
+
from adapters import _string_map, _url
|
|
138
|
+
|
|
139
|
+
url = _url(args)
|
|
140
|
+
allowed, reason = guard.url_allowed(url)
|
|
141
|
+
if not allowed:
|
|
142
|
+
raise _error("URL_BLOCKED", f"{url}: {reason}")
|
|
143
|
+
name = _safe_name(args.get("filename"), url)
|
|
144
|
+
limit = _max_bytes(args)
|
|
145
|
+
directory = _download_dir(args)
|
|
146
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
147
|
+
|
|
148
|
+
headers = _string_map(args.get("headers"), "headers")
|
|
149
|
+
cookies = _string_map(args.get("cookies"), "cookies")
|
|
150
|
+
timeout = args.get("timeoutSeconds", 120.0)
|
|
151
|
+
if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or timeout <= 0:
|
|
152
|
+
raise _error("BAD_ARGS", "timeoutSeconds must be a positive number")
|
|
153
|
+
if args.get("useBrowser") is True:
|
|
154
|
+
if cookies is not None:
|
|
155
|
+
raise _error("BAD_ARGS", "cookies need a session; use useBrowser:false for a one-off download")
|
|
156
|
+
return _download_via_browser(url, name=name, directory=directory, limit=limit, timeout=timeout, headers=headers)
|
|
157
|
+
impersonate = args.get("impersonate")
|
|
158
|
+
return _download_via_stream(
|
|
159
|
+
url,
|
|
160
|
+
name=name,
|
|
161
|
+
directory=directory,
|
|
162
|
+
limit=limit,
|
|
163
|
+
timeout=timeout,
|
|
164
|
+
headers=headers,
|
|
165
|
+
cookies=cookies,
|
|
166
|
+
impersonate=impersonate if isinstance(impersonate, str) and impersonate else "chrome",
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _download_via_stream(
|
|
171
|
+
url: str,
|
|
172
|
+
*,
|
|
173
|
+
name: str,
|
|
174
|
+
directory: Path,
|
|
175
|
+
limit: int,
|
|
176
|
+
timeout: float,
|
|
177
|
+
headers: dict[str, str] | None,
|
|
178
|
+
cookies: dict[str, str] | None,
|
|
179
|
+
impersonate: str,
|
|
180
|
+
) -> dict[str, Any]:
|
|
181
|
+
"""流式下载:逐块落盘并计哈希,内存占用与块同阶,与响应体大小无关。
|
|
182
|
+
|
|
183
|
+
走 curl_cffi 而不是 Scrapling 的 Fetcher:后者的响应整体缓冲,大小上限只能在
|
|
184
|
+
「全部读进内存之后」判,一条快链路足以在超时窗口内把进程内存顶爆。下载不需要
|
|
185
|
+
Scrapling 的解析层;impersonate 的默认档沿用它的 ``chrome``,代理表与重定向
|
|
186
|
+
安全档与静态抓取共用同一份 guard 判定。
|
|
187
|
+
"""
|
|
188
|
+
import guard
|
|
189
|
+
from curl_cffi import requests as curl_requests
|
|
190
|
+
|
|
191
|
+
session_kwargs: dict[str, Any] = {"impersonate": impersonate}
|
|
192
|
+
proxies = guard.proxies_for(url)
|
|
193
|
+
if proxies is not None:
|
|
194
|
+
session_kwargs["proxies"] = proxies
|
|
195
|
+
request_kwargs: dict[str, Any] = {
|
|
196
|
+
"timeout": float(timeout),
|
|
197
|
+
# 直连 curl_cffi 就用它的参数名:Scrapling 的 follow_redirects 是它自己翻成
|
|
198
|
+
# allow_redirects 的那一层(engines/static.py),这里没有翻译层可借。
|
|
199
|
+
"allow_redirects": "safe",
|
|
200
|
+
"stream": True,
|
|
201
|
+
}
|
|
202
|
+
if headers is not None:
|
|
203
|
+
request_kwargs["headers"] = headers
|
|
204
|
+
if cookies is not None:
|
|
205
|
+
request_kwargs["cookies"] = cookies
|
|
206
|
+
try:
|
|
207
|
+
session = curl_requests.Session(**session_kwargs)
|
|
208
|
+
except Exception as error:
|
|
209
|
+
raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}: {error}") from error
|
|
210
|
+
try:
|
|
211
|
+
try:
|
|
212
|
+
response = session.request("GET", url, **request_kwargs)
|
|
213
|
+
except Exception as error:
|
|
214
|
+
raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}: {error}") from error
|
|
215
|
+
try:
|
|
216
|
+
status = int(getattr(response, "status_code", 0))
|
|
217
|
+
if not 200 <= status < 300:
|
|
218
|
+
raise _error("DOWNLOAD_FAILED", f"download answered HTTP {status}")
|
|
219
|
+
declared = _header_value(response.headers, "Content-Length")
|
|
220
|
+
# 头部预检在正文传输之前给出结论;谎报长度的服务端由流式循环里的复核兜住。
|
|
221
|
+
if declared.isdigit() and int(declared) > limit:
|
|
222
|
+
raise _error(
|
|
223
|
+
"DOWNLOAD_TOO_LARGE",
|
|
224
|
+
f"download is {int(declared)} bytes by Content-Length, over the {limit}-byte cap",
|
|
225
|
+
)
|
|
226
|
+
digest = hashlib.sha256()
|
|
227
|
+
total = 0
|
|
228
|
+
temporary = _temp_path(directory, name)
|
|
229
|
+
try:
|
|
230
|
+
with open(temporary, "wb") as sink:
|
|
231
|
+
for chunk in response.iter_content(chunk_size=_DOWNLOAD_CHUNK_BYTES):
|
|
232
|
+
sink.write(chunk)
|
|
233
|
+
digest.update(chunk)
|
|
234
|
+
total += len(chunk)
|
|
235
|
+
if total > limit:
|
|
236
|
+
raise _error(
|
|
237
|
+
"DOWNLOAD_TOO_LARGE",
|
|
238
|
+
f"download is over the {limit}-byte cap"
|
|
239
|
+
+ (f" (Content-Length declared {int(declared)})" if declared.isdigit() else ""),
|
|
240
|
+
)
|
|
241
|
+
target = _commit_temp(directory, name, temporary)
|
|
242
|
+
except BaseException:
|
|
243
|
+
temporary.unlink(missing_ok=True)
|
|
244
|
+
raise
|
|
245
|
+
return {
|
|
246
|
+
"path": str(target),
|
|
247
|
+
"bytes": total,
|
|
248
|
+
"sha256": digest.hexdigest(),
|
|
249
|
+
"contentType": _header_value(response.headers, "Content-Type"),
|
|
250
|
+
"status": status,
|
|
251
|
+
}
|
|
252
|
+
finally:
|
|
253
|
+
response.close()
|
|
254
|
+
finally:
|
|
255
|
+
session.close()
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _commit_bytes(directory: Path, name: str, body: bytes) -> Path:
|
|
259
|
+
"""把一段已在内存里的字节落成正式名(浏览器路径):临时文件 + 占位 + 原子替换。"""
|
|
260
|
+
temporary = _temp_path(directory, name)
|
|
261
|
+
try:
|
|
262
|
+
temporary.write_bytes(body)
|
|
263
|
+
return _commit_temp(directory, name, temporary)
|
|
264
|
+
except BaseException:
|
|
265
|
+
temporary.unlink(missing_ok=True)
|
|
266
|
+
raise
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _download_via_browser(
|
|
270
|
+
url: str,
|
|
271
|
+
*,
|
|
272
|
+
name: str,
|
|
273
|
+
directory: Path,
|
|
274
|
+
limit: int,
|
|
275
|
+
timeout: float,
|
|
276
|
+
headers: dict[str, str] | None,
|
|
277
|
+
) -> dict[str, Any]:
|
|
278
|
+
"""浏览器路径的下载:Scrapling 的响应整体缓冲,没有流式出口。
|
|
279
|
+
|
|
280
|
+
内存上界因此由 requestTimeoutSeconds 与链路吞吐共同决定;这一档是给「要 JS 才拿
|
|
281
|
+
得到文件」的少数场景用的,静态路径(默认)已经是流式。
|
|
282
|
+
"""
|
|
283
|
+
import guard
|
|
284
|
+
|
|
285
|
+
# 与 :func:`adapters.render` 同一条判据:浏览器路径必须显式挂上网络守卫与部署代理。
|
|
286
|
+
# 少了 ``page_setup``,重定向与页面子资源都不经过 guard.install 的 ``**/*`` 路由,
|
|
287
|
+
# 一条被下载链接重定向到内网的响应会绕过 url_allowed;少了 ``proxy``,配了代理的
|
|
288
|
+
# 机器上这条路径直连(Chromium 不读 HTTP_PROXY)。
|
|
289
|
+
from adapters import page_setup
|
|
290
|
+
from scrapling.fetchers import StealthyFetcher
|
|
291
|
+
|
|
292
|
+
browser_params: dict[str, Any] = {
|
|
293
|
+
"timeout": int(timeout * 1000),
|
|
294
|
+
"page_setup": page_setup,
|
|
295
|
+
}
|
|
296
|
+
proxy = guard.browser_proxy(url)
|
|
297
|
+
if proxy is not None:
|
|
298
|
+
browser_params["proxy"] = proxy
|
|
299
|
+
if headers is not None:
|
|
300
|
+
browser_params["extra_headers"] = headers
|
|
301
|
+
try:
|
|
302
|
+
response = StealthyFetcher.fetch(url, **browser_params)
|
|
303
|
+
except Exception as error: # noqa: BLE001 —— 把附件响应换一条路走完,而不是只剩一个类名
|
|
304
|
+
# 「Page.goto: Download is starting」:Chromium 不能把「触发下载的响应」当成一次
|
|
305
|
+
# 导航,fetch 这条路对附件/二进制响应天然走不通。换成等真实的 download 事件再把它
|
|
306
|
+
# 落盘。HTML 页走不到这里(fetch 成功就原样返回),所以既有成功路径不动。
|
|
307
|
+
return _download_via_browser_attachment(
|
|
308
|
+
url,
|
|
309
|
+
name=name,
|
|
310
|
+
directory=directory,
|
|
311
|
+
limit=limit,
|
|
312
|
+
timeout=timeout,
|
|
313
|
+
headers=headers,
|
|
314
|
+
cause=error,
|
|
315
|
+
)
|
|
316
|
+
status = int(getattr(response, "status", 0))
|
|
317
|
+
if not 200 <= status < 300:
|
|
318
|
+
raise _error("DOWNLOAD_FAILED", f"download answered HTTP {status}")
|
|
319
|
+
body = response.body
|
|
320
|
+
if not isinstance(body, (bytes, bytearray)):
|
|
321
|
+
raise _error("DOWNLOAD_FAILED", "download response had no byte body")
|
|
322
|
+
if len(body) > limit:
|
|
323
|
+
raise _error("DOWNLOAD_TOO_LARGE", f"download is {len(body)} bytes, over the {limit}-byte cap")
|
|
324
|
+
target = _commit_bytes(directory, name, bytes(body))
|
|
325
|
+
return {
|
|
326
|
+
"path": str(target),
|
|
327
|
+
"bytes": len(body),
|
|
328
|
+
"sha256": hashlib.sha256(bytes(body)).hexdigest(),
|
|
329
|
+
"contentType": _header_value(getattr(response, "headers", {}), "Content-Type"),
|
|
330
|
+
"status": status,
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _download_via_browser_attachment(
|
|
335
|
+
url: str,
|
|
336
|
+
*,
|
|
337
|
+
name: str,
|
|
338
|
+
directory: Path,
|
|
339
|
+
limit: int,
|
|
340
|
+
timeout: float,
|
|
341
|
+
headers: dict[str, str] | None,
|
|
342
|
+
cause: BaseException,
|
|
343
|
+
) -> dict[str, Any]:
|
|
344
|
+
"""浏览器路径的附件下载:等 ``download`` 事件,而不是等一次导航。
|
|
345
|
+
|
|
346
|
+
``StealthyFetcher.fetch`` 走的是 ``page.goto``,而触发下载的响应在 Chromium 里不算
|
|
347
|
+
导航,于是它只回一句 ``Page.goto: Download is starting``。这里直接开一个会话、挂上
|
|
348
|
+
与一次性路径同一套网络守卫,然后等 Playwright 的 ``expect_download`` 把附件交出来。
|
|
349
|
+
"""
|
|
350
|
+
import guard
|
|
351
|
+
from adapters import page_setup
|
|
352
|
+
from scrapling.fetchers import StealthySession
|
|
353
|
+
|
|
354
|
+
timeout_ms = int(timeout * 1000)
|
|
355
|
+
session_params: dict[str, Any] = {"timeout": timeout_ms}
|
|
356
|
+
proxy = guard.browser_proxy(url)
|
|
357
|
+
if proxy is not None:
|
|
358
|
+
session_params["proxy"] = proxy
|
|
359
|
+
session = StealthySession(**session_params)
|
|
360
|
+
page = None
|
|
361
|
+
try:
|
|
362
|
+
session.start()
|
|
363
|
+
page = session.context.new_page()
|
|
364
|
+
page.set_default_timeout(timeout_ms)
|
|
365
|
+
page_setup(page)
|
|
366
|
+
if headers is not None:
|
|
367
|
+
page.set_extra_http_headers(headers)
|
|
368
|
+
# 一触发下载这次导航就会失败,失败本身是预期的一部分(理由见上)。
|
|
369
|
+
with page.expect_download(timeout=timeout_ms) as pending, contextlib.suppress(Exception):
|
|
370
|
+
page.goto(url, wait_until="commit")
|
|
371
|
+
download = pending.value
|
|
372
|
+
source = download.path()
|
|
373
|
+
body = Path(source).read_bytes() if source is not None else b""
|
|
374
|
+
except Exception as error:
|
|
375
|
+
raise _error(
|
|
376
|
+
"DOWNLOAD_FAILED",
|
|
377
|
+
f"download failed: {type(cause).__name__}: {cause}; attachment fallback: {type(error).__name__}: {error}",
|
|
378
|
+
) from error
|
|
379
|
+
finally:
|
|
380
|
+
if page is not None:
|
|
381
|
+
with contextlib.suppress(Exception):
|
|
382
|
+
page.close()
|
|
383
|
+
with contextlib.suppress(Exception):
|
|
384
|
+
session.close()
|
|
385
|
+
if len(body) > limit:
|
|
386
|
+
raise _error("DOWNLOAD_TOO_LARGE", f"download is {len(body)} bytes, over the {limit}-byte cap")
|
|
387
|
+
target = _commit_bytes(directory, name, body)
|
|
388
|
+
return {
|
|
389
|
+
"path": str(target),
|
|
390
|
+
"bytes": len(body),
|
|
391
|
+
"sha256": hashlib.sha256(body).hexdigest(),
|
|
392
|
+
"contentType": None,
|
|
393
|
+
"status": 200,
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _image_size(data: bytes, image_type: str) -> tuple[int, int]:
|
|
398
|
+
"""从 PNG/JPEG 字节里读固有尺寸;读不出时给 (0, 0)。"""
|
|
399
|
+
if image_type == "png" and data[:8] == b"\x89PNG\r\n\x1a\n" and len(data) >= 24:
|
|
400
|
+
width, height = struct.unpack(">II", data[16:24])
|
|
401
|
+
return int(width), int(height)
|
|
402
|
+
if image_type == "jpeg":
|
|
403
|
+
index = 2
|
|
404
|
+
while index + 9 < len(data):
|
|
405
|
+
if data[index] != 0xFF:
|
|
406
|
+
index += 1
|
|
407
|
+
continue
|
|
408
|
+
marker = data[index + 1]
|
|
409
|
+
if marker in (0xC0, 0xC1, 0xC2, 0xC3):
|
|
410
|
+
height, width = struct.unpack(">HH", data[index + 5 : index + 9])
|
|
411
|
+
return int(width), int(height)
|
|
412
|
+
if marker in (0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
|
|
413
|
+
index += 2
|
|
414
|
+
continue
|
|
415
|
+
length = struct.unpack(">H", data[index + 2 : index + 4])[0]
|
|
416
|
+
index += 2 + length
|
|
417
|
+
return 0, 0
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def screenshot(
|
|
421
|
+
session: Any,
|
|
422
|
+
*,
|
|
423
|
+
image_type: str,
|
|
424
|
+
full_page: bool,
|
|
425
|
+
quality: Any,
|
|
426
|
+
selector: str | None,
|
|
427
|
+
timeout_ms: int,
|
|
428
|
+
) -> dict[str, Any]:
|
|
429
|
+
"""对会话当前页或页内单个元素截图,返回 base64 与固有尺寸。"""
|
|
430
|
+
from session_page import _finish_page, _ready_page
|
|
431
|
+
|
|
432
|
+
if image_type not in ("png", "jpeg"):
|
|
433
|
+
raise _error("BAD_ARGS", "imageType must be png or jpeg")
|
|
434
|
+
if quality is not None and (not isinstance(quality, int) or isinstance(quality, bool) or not 1 <= quality <= 100):
|
|
435
|
+
raise _error("BAD_ARGS", "quality must be an integer from 1 to 100")
|
|
436
|
+
if quality is not None and image_type != "jpeg":
|
|
437
|
+
raise _error("BAD_ARGS", "quality only applies to jpeg screenshots")
|
|
438
|
+
if full_page and selector is not None:
|
|
439
|
+
raise _error("BAD_ARGS", "fullPage and selector cannot be combined")
|
|
440
|
+
|
|
441
|
+
page_info = _ready_page(session)
|
|
442
|
+
page = page_info.page
|
|
443
|
+
try:
|
|
444
|
+
if page.is_closed():
|
|
445
|
+
raise _error("PAGE_BUSY", "the session's page has been closed")
|
|
446
|
+
if selector is not None:
|
|
447
|
+
locator = page.locator(selector)
|
|
448
|
+
matches = locator.count()
|
|
449
|
+
if matches != 1:
|
|
450
|
+
raise _error("BAD_ARGS", f"selector must match exactly one element, matched {matches}")
|
|
451
|
+
# timeout 与整页那支同源:参数面声明了 timeoutMs,两条路径都得真生效。
|
|
452
|
+
data = locator.screenshot(
|
|
453
|
+
type=image_type,
|
|
454
|
+
timeout=timeout_ms,
|
|
455
|
+
**({"quality": quality} if quality else {}),
|
|
456
|
+
)
|
|
457
|
+
else:
|
|
458
|
+
data = page.screenshot(
|
|
459
|
+
type=image_type,
|
|
460
|
+
full_page=full_page,
|
|
461
|
+
**({"quality": quality} if quality else {}),
|
|
462
|
+
timeout=timeout_ms,
|
|
463
|
+
)
|
|
464
|
+
encoded = bytes(data)
|
|
465
|
+
width, height = _image_size(encoded, image_type)
|
|
466
|
+
return {
|
|
467
|
+
"base64": base64.b64encode(encoded).decode("ascii"),
|
|
468
|
+
"mediaType": "image/png" if image_type == "png" else "image/jpeg",
|
|
469
|
+
"width": width,
|
|
470
|
+
"height": height,
|
|
471
|
+
"url": str(page.url),
|
|
472
|
+
}
|
|
473
|
+
finally:
|
|
474
|
+
_finish_page(session.page_pool, page_info)
|
package/py/redact.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""py/redact.py —— 把 URL 里像凭据的部分换成占位符。
|
|
2
|
+
|
|
3
|
+
guard 的日志与 adapters 的网络摘要在「给日志、给模型看」之前都要过这里。单独成模块
|
|
4
|
+
是因为 guard 不能 import adapters(adapters 顶层 import guard,反过来就是环)。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
|
10
|
+
|
|
11
|
+
# 查询串里这些名字的参数装的是凭据而不是筛选条件。XHR 摘要与守卫日志都是要离开本进程的
|
|
12
|
+
# 文本——摘要进会话上下文、进第三方 provider,日志进宿主日志面——而真实站点把 access
|
|
13
|
+
# token、会话 id、签名都放在查询串里。抓到一条就等于把凭据抄进载体,而读者既用不上它、
|
|
14
|
+
# 也拦不住它被复述出来。值的部分一律换成固定占位符:定位接口靠的是路径与参数名,不是那个
|
|
15
|
+
# token。
|
|
16
|
+
_SECRET_QUERY_KEYS = frozenset(
|
|
17
|
+
{
|
|
18
|
+
"access_token",
|
|
19
|
+
"api_key",
|
|
20
|
+
"apikey",
|
|
21
|
+
"auth",
|
|
22
|
+
"auth_token",
|
|
23
|
+
"authorization",
|
|
24
|
+
"code",
|
|
25
|
+
"credential",
|
|
26
|
+
"id_token",
|
|
27
|
+
"key",
|
|
28
|
+
"password",
|
|
29
|
+
"pwd",
|
|
30
|
+
"refresh_token",
|
|
31
|
+
"secret",
|
|
32
|
+
"session",
|
|
33
|
+
"sessionid",
|
|
34
|
+
"session_id",
|
|
35
|
+
"sig",
|
|
36
|
+
"signature",
|
|
37
|
+
"sign",
|
|
38
|
+
"token",
|
|
39
|
+
}
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _redacted_query(text: str) -> str:
|
|
44
|
+
"""把一段查询串里像凭据的参数值换成占位符;没有命中时原样返回。
|
|
45
|
+
|
|
46
|
+
与 :func:`redact_url_secrets` 同一套参数名判据,片段也复用它 —— OAuth2 隐式流程把
|
|
47
|
+
令牌放在 ``#access_token=`` 里,那同样是「离开本进程就等于抄出去」的凭据。
|
|
48
|
+
|
|
49
|
+
:param text: 查询串(或片段的查询部分)
|
|
50
|
+
:returns: 脱敏后的文本
|
|
51
|
+
"""
|
|
52
|
+
if not text:
|
|
53
|
+
return text
|
|
54
|
+
pairs: list[tuple[str, str]] = []
|
|
55
|
+
changed = False
|
|
56
|
+
for name, value in parse_qsl(text, keep_blank_values=True):
|
|
57
|
+
if name.strip().lower() in _SECRET_QUERY_KEYS:
|
|
58
|
+
pairs.append((name, "<redacted>"))
|
|
59
|
+
changed = True
|
|
60
|
+
else:
|
|
61
|
+
pairs.append((name, value))
|
|
62
|
+
if not changed:
|
|
63
|
+
return text
|
|
64
|
+
return urlencode(pairs)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _redacted_fragment(fragment: str) -> str:
|
|
68
|
+
"""把片段里像查询串的那一段脱敏;没有命中时原样返回。
|
|
69
|
+
|
|
70
|
+
片段有两种藏令牌的写法:OAuth2 隐式流程把整个片段当查询串(``#access_token=…``),
|
|
71
|
+
单页应用的路由则是先路径后查询(``#!/list?token=…``)。两种都要覆盖。
|
|
72
|
+
|
|
73
|
+
:param fragment: URL 的 fragment 段
|
|
74
|
+
:returns: 脱敏后的 fragment
|
|
75
|
+
"""
|
|
76
|
+
head, separator, query = fragment.partition("?")
|
|
77
|
+
if separator:
|
|
78
|
+
return f"{head}?{_redacted_query(query)}"
|
|
79
|
+
return _redacted_query(fragment)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def redact_url_secrets(raw: str) -> str:
|
|
83
|
+
"""把 URL 里像凭据的部分替换成占位符。
|
|
84
|
+
|
|
85
|
+
三处各藏一类凭据:查询串与片段的查询部分按**参数名**判(真实站点把 access token、
|
|
86
|
+
会话 id、签名放在那里),authority 里的 ``user:pass@`` 整段丢掉(代理与 Basic 认证
|
|
87
|
+
的接口都爱这么写)。值的部分一律换成固定占位符:定位接口靠的是路径与参数名,不是
|
|
88
|
+
那个 token。
|
|
89
|
+
|
|
90
|
+
只按参数名判断、不看值 —— 值本身无法可靠判定(短 token 与普通 id 长得一样)。
|
|
91
|
+
认不出来的参数原样保留:把 ``?page=2`` 也涂掉只会让摘要失去意义,而那不是凭据。
|
|
92
|
+
|
|
93
|
+
:param raw: 原始 URL
|
|
94
|
+
:returns: 已脱敏的 URL;解析不出或没有可脱敏的部分时原样返回
|
|
95
|
+
"""
|
|
96
|
+
try:
|
|
97
|
+
parsed = urlsplit(raw)
|
|
98
|
+
except ValueError:
|
|
99
|
+
return raw
|
|
100
|
+
# 没有 scheme 的 ``user:pass@host:8080`` 会被 urlsplit 读成 scheme='user'、
|
|
101
|
+
# path='pass@host:8080':netloc 为空,下面按 netloc 摘 userinfo 的那一步什么都不做,
|
|
102
|
+
# 整条代理口令于是原样漏进日志(PROXY_URL 不可用那条日志正是这么来的)。这种形态的
|
|
103
|
+
# authority 落在 path 的第一段上,按同一套规则摘掉;误读成 scheme 的那段一起丢弃。
|
|
104
|
+
authority, slash, rest = parsed.path.partition("/")
|
|
105
|
+
standalone_authority = not parsed.netloc and "@" in authority
|
|
106
|
+
if standalone_authority:
|
|
107
|
+
path = authority.rpartition("@")[2] + slash + rest
|
|
108
|
+
netloc = ""
|
|
109
|
+
else:
|
|
110
|
+
path = parsed.path
|
|
111
|
+
# rpartition 取最后一段:IPv6 字面量与端口都留在主机那一侧,只把用户信息摘掉。
|
|
112
|
+
netloc = parsed.netloc.rpartition("@")[2]
|
|
113
|
+
query = _redacted_query(parsed.query)
|
|
114
|
+
fragment = _redacted_fragment(parsed.fragment)
|
|
115
|
+
if path == parsed.path and netloc == parsed.netloc and query == parsed.query and fragment == parsed.fragment:
|
|
116
|
+
return raw
|
|
117
|
+
scheme = "" if standalone_authority else parsed.scheme
|
|
118
|
+
return urlunsplit((scheme, netloc, path, query, fragment))
|