papersearch 0.4.7 → 0.4.8
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/.env.example +3 -0
- package/README.en.md +36 -12
- package/README.md +36 -12
- package/assets/logo.svg +15 -0
- package/assets/overview.en.png +0 -0
- package/assets/overview.png +0 -0
- package/assets/progress-capsule.en.png +0 -0
- package/assets/progress-capsule.png +0 -0
- package/carsi/paper_search_carsi/assets/icon-32.png +0 -0
- package/carsi/paper_search_carsi/assets/icon-512.png +0 -0
- package/carsi/paper_search_carsi/assets/icon-64.png +0 -0
- package/carsi/paper_search_carsi/assets/icon.svg +13 -16
- package/carsi/paper_search_carsi/cli.py +27 -0
- package/carsi/paper_search_carsi/engine/batch.py +5 -1
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +29 -25
- package/carsi/paper_search_carsi/engine/bridge.py +5 -0
- package/carsi/paper_search_carsi/failure_export.py +239 -0
- package/carsi/paper_search_carsi/issues.py +8 -6
- package/carsi/paper_search_carsi/page_snapshot.py +64 -0
- package/carsi/paper_search_carsi/report_sanitizer.py +248 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/dist/cli.js +56 -5
- package/dist/cli.js.map +1 -1
- package/dist/config/ConfigService.d.ts +1 -1
- package/dist/config/ConfigService.d.ts.map +1 -1
- package/dist/config/ConfigService.js +1 -0
- package/dist/config/ConfigService.js.map +1 -1
- package/dist/management/failures/exportReport.d.ts +20 -0
- package/dist/management/failures/exportReport.d.ts.map +1 -0
- package/dist/management/failures/exportReport.js +73 -0
- package/dist/management/failures/exportReport.js.map +1 -0
- package/dist/management/failures/index.d.ts +20 -0
- package/dist/management/failures/index.d.ts.map +1 -1
- package/dist/management/failures/index.js +69 -43
- package/dist/management/failures/index.js.map +1 -1
- package/dist/management/updates/index.d.ts +37 -0
- package/dist/management/updates/index.d.ts.map +1 -0
- package/dist/management/updates/index.js +185 -0
- package/dist/management/updates/index.js.map +1 -0
- package/package.json +2 -1
- package/skills/paper-search/SKILL.md +3 -1
- package/skills/paper-search/references/browser-download.md +17 -4
- package/skills/paper-search/references/carsi-setup.md +1 -1
- package/skills/paper-search/references/cli-contract.md +2 -1
- package/skills/paper-search/references/management-layer.md +8 -0
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Offline failure packet export. Never opens a browser or modifies evidence."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import tempfile
|
|
10
|
+
import zipfile
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from .report_sanitizer import MAX_HTML_BYTES, Redactor, sanitize_html
|
|
15
|
+
|
|
16
|
+
MAX_REQUEST_BYTES = 8 * 1024 * 1024
|
|
17
|
+
MAX_JSON_BYTES = 4 * 1024 * 1024
|
|
18
|
+
MAX_IMAGE_BYTES = 2 * 1024 * 1024
|
|
19
|
+
MAX_PACKAGE_BYTES = 64 * 1024 * 1024
|
|
20
|
+
MAX_PAPERS = 100
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ExportError(ValueError):
|
|
24
|
+
"""Stable public error code; never includes original contents/paths."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _read(path: Path, limit: int) -> bytes:
|
|
28
|
+
if path.is_symlink() or not path.is_file():
|
|
29
|
+
raise ExportError('missing_or_unsafe_file')
|
|
30
|
+
with path.open('rb') as handle:
|
|
31
|
+
data = handle.read(limit + 1)
|
|
32
|
+
if len(data) > limit:
|
|
33
|
+
raise ExportError('file_size_limit')
|
|
34
|
+
return data
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _artifact(root: Path, raw: str, limit: int) -> bytes:
|
|
38
|
+
path = Path(raw)
|
|
39
|
+
if not path.is_absolute():
|
|
40
|
+
path = root / path
|
|
41
|
+
# No symlinks or traversal out of the diagnostic directory. We never glob
|
|
42
|
+
# a download directory (which can contain PDFs, cookies and profiles).
|
|
43
|
+
try:
|
|
44
|
+
relative = path.absolute().relative_to(root.absolute())
|
|
45
|
+
if '..' in relative.parts:
|
|
46
|
+
raise ValueError()
|
|
47
|
+
current = root
|
|
48
|
+
for part in relative.parts:
|
|
49
|
+
current = current / part
|
|
50
|
+
if current.is_symlink():
|
|
51
|
+
raise ValueError()
|
|
52
|
+
path.resolve().relative_to(root.resolve())
|
|
53
|
+
except ValueError:
|
|
54
|
+
raise ExportError('unsafe_artifact_path') from None
|
|
55
|
+
return _read(path, limit)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _load_record(row: dict) -> tuple[dict, Path | None, str | None]:
|
|
59
|
+
source = row.get('diagnostic') or row.get('record')
|
|
60
|
+
if not isinstance(source, str) or not source:
|
|
61
|
+
return row.get('detail') or {}, None, 'diagnostic_missing; ledger_only'
|
|
62
|
+
path = Path(source)
|
|
63
|
+
try:
|
|
64
|
+
data = json.loads(_read(path, MAX_JSON_BYTES))
|
|
65
|
+
if not isinstance(data, dict) or str(data.get('doi') or data.get('raw_doi') or '').lower() != row['doi'].lower():
|
|
66
|
+
raise ExportError('diagnostic_identity_mismatch')
|
|
67
|
+
if any(key in data and not isinstance(data[key], list) for key in ('events', 'snapshots', 'pages')):
|
|
68
|
+
raise ExportError('invalid_diagnostic_shape')
|
|
69
|
+
return data, path.parent, None
|
|
70
|
+
except (OSError, ValueError) as exc:
|
|
71
|
+
reason = str(exc) if isinstance(exc, ExportError) else 'diagnostic_unreadable'
|
|
72
|
+
return row.get('detail') or {}, None, reason + '; ledger_only'
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def export_report(request: dict, output: Path, config: dict | None = None) -> dict:
|
|
76
|
+
if request.get('schemaVersion') != 1 or not isinstance(request.get('papers'), list):
|
|
77
|
+
raise ExportError('invalid_export_request')
|
|
78
|
+
rows = request['papers']
|
|
79
|
+
if not rows:
|
|
80
|
+
raise ExportError('no_matching_failures')
|
|
81
|
+
if len(rows) > MAX_PAPERS:
|
|
82
|
+
raise ExportError('too_many_failures; select_a_run_or_doi; limit=100')
|
|
83
|
+
if any(not isinstance(row, dict) or not isinstance(row.get('doi'), str)
|
|
84
|
+
or ('detail' in row and not isinstance(row['detail'], dict)) for row in rows):
|
|
85
|
+
raise ExportError('invalid_export_request')
|
|
86
|
+
if output.suffix.lower() != '.zip':
|
|
87
|
+
raise ExportError('export_path_must_end_in_zip')
|
|
88
|
+
if output.exists() or output.is_symlink():
|
|
89
|
+
raise ExportError('export_target_exists')
|
|
90
|
+
redactor = Redactor(config)
|
|
91
|
+
loaded = []
|
|
92
|
+
total_input = 0
|
|
93
|
+
for row in rows:
|
|
94
|
+
data, root, problem = _load_record(row)
|
|
95
|
+
total_input += len(json.dumps(data, ensure_ascii=False).encode('utf-8'))
|
|
96
|
+
if total_input > MAX_PACKAGE_BYTES:
|
|
97
|
+
raise ExportError('source_size_limit; select_a_run_or_doi')
|
|
98
|
+
loaded.append((row, data, root, problem))
|
|
99
|
+
redactor.observe(row)
|
|
100
|
+
redactor.observe(data)
|
|
101
|
+
manifest = {
|
|
102
|
+
'schemaVersion': 1, 'createdAt': datetime.now(timezone.utc).isoformat(),
|
|
103
|
+
'version': redactor.text(str(request.get('version') or 'unknown')),
|
|
104
|
+
'exportSystem': platform.system(),
|
|
105
|
+
'reviewRequired': True, 'papers': [], 'files': [],
|
|
106
|
+
'limits': {'papers': MAX_PAPERS, 'htmlBytes': MAX_HTML_BYTES,
|
|
107
|
+
'imageBytes': MAX_IMAGE_BYTES, 'packageBytes': MAX_PACKAGE_BYTES},
|
|
108
|
+
}
|
|
109
|
+
output = output.expanduser().absolute()
|
|
110
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
fd, temp = tempfile.mkstemp(prefix='.papersearch-report-', suffix='.zip', dir=output.parent)
|
|
112
|
+
os.close(fd)
|
|
113
|
+
total = 0
|
|
114
|
+
try:
|
|
115
|
+
with zipfile.ZipFile(temp, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
|
|
116
|
+
def add(name: str, content: bytes) -> None:
|
|
117
|
+
nonlocal total
|
|
118
|
+
total += len(content)
|
|
119
|
+
if total > MAX_PACKAGE_BYTES:
|
|
120
|
+
raise ExportError('package_size_limit; select_a_run_or_doi')
|
|
121
|
+
archive.writestr(name, content)
|
|
122
|
+
manifest['files'].append({'path': name, 'bytes': len(content),
|
|
123
|
+
'sha256': hashlib.sha256(content).hexdigest()})
|
|
124
|
+
|
|
125
|
+
for i, (row, data, root, problem) in enumerate(loaded, 1):
|
|
126
|
+
folder = f'papers/{i:03d}' # no DOI/path/user content in archive paths
|
|
127
|
+
paper = redactor.clean({k: row.get(k) for k in
|
|
128
|
+
('doi', 'runId', 'publisher', 'failureClass', 'code', 'part', 'stoppedAt', 'evidence')})
|
|
129
|
+
paper.update(folder=folder, materials=[], omitted=[])
|
|
130
|
+
if not paper.get('stoppedAt'):
|
|
131
|
+
steps = [e for e in data.get('events', []) if isinstance(e, dict) and e.get('state')
|
|
132
|
+
and e['state'] not in {'snapshot', 'wait', 'publisher_session_saved'}]
|
|
133
|
+
paper['stoppedAt'] = redactor.text(str(steps[-1]['state'] if steps else data.get('state') or row.get('code') or 'unknown'))
|
|
134
|
+
paper['finalUrl'] = redactor.text(str(data.get('final_url') or data.get('article_url') or 'unknown'))
|
|
135
|
+
paper['captureSystem'] = redactor.clean(data.get('capture_system') or 'unknown (legacy record)')
|
|
136
|
+
paper['captureVersion'] = redactor.clean(data.get('capture_version') or 'unknown (legacy record)')
|
|
137
|
+
if problem:
|
|
138
|
+
paper['omitted'].append(problem)
|
|
139
|
+
clean = redactor.clean(data)
|
|
140
|
+
add(folder + '/diagnostic.json', _json(clean))
|
|
141
|
+
# Ledger provides the caller's attachment outcome even when the
|
|
142
|
+
# backend's original record pre-dates the supplementary step.
|
|
143
|
+
add(folder + '/outcome.json', _json(redactor.clean(row.get('outcome') or {})))
|
|
144
|
+
pages = [p for key in ('snapshots', 'pages') for p in (data.get(key) or []) if isinstance(p, dict)]
|
|
145
|
+
if len(pages) > 8:
|
|
146
|
+
paper['omitted'].append('page_count_limit')
|
|
147
|
+
for number, page in enumerate(pages[:8], 1):
|
|
148
|
+
for kind, limit, suffix in (('html', MAX_HTML_BYTES, '.html'), ('screenshot', MAX_IMAGE_BYTES, '.png')):
|
|
149
|
+
source = page.get(kind)
|
|
150
|
+
if not source or root is None:
|
|
151
|
+
if page.get(kind + '_omitted'):
|
|
152
|
+
paper['omitted'].append(f'page{number}/{kind}: capture_unavailable')
|
|
153
|
+
continue
|
|
154
|
+
if kind == 'screenshot':
|
|
155
|
+
if (page.get('screenshot_masked') is not True or page.get('screenshot_private') is True
|
|
156
|
+
or page.get('html_omitted') or redactor.private_page(
|
|
157
|
+
str(page.get('url') or ''), str(page.get('title') or ''), str(page.get('why') or '')
|
|
158
|
+
)):
|
|
159
|
+
paper['omitted'].append(f'page{number}/screenshot: login_school_or_unverified_origin')
|
|
160
|
+
continue
|
|
161
|
+
try:
|
|
162
|
+
content = _artifact(root, str(source), limit)
|
|
163
|
+
if kind == 'html':
|
|
164
|
+
content, truncated = sanitize_html(content.decode('utf-8'), redactor)
|
|
165
|
+
content = content.encode('utf-8')
|
|
166
|
+
if truncated or page.get('html_truncated'):
|
|
167
|
+
paper['omitted'].append(f'page{number}/html: truncated')
|
|
168
|
+
else:
|
|
169
|
+
if content.startswith(b'\x89PNG\r\n\x1a\n'):
|
|
170
|
+
suffix = '.png'
|
|
171
|
+
elif content.startswith(b'\xff\xd8\xff'):
|
|
172
|
+
suffix = '.jpg'
|
|
173
|
+
else:
|
|
174
|
+
raise ExportError('invalid_image')
|
|
175
|
+
name = f'{folder}/pages/{number:02d}{suffix}'
|
|
176
|
+
add(name, content)
|
|
177
|
+
paper['materials'].append({'path': name, 'kind': kind,
|
|
178
|
+
'url': redactor.text(str(page.get('url') or '')),
|
|
179
|
+
'why': redactor.text(str(page.get('why') or ''))})
|
|
180
|
+
except (OSError, ValueError, UnicodeError) as exc:
|
|
181
|
+
if isinstance(exc, ExportError) and str(exc).startswith('package_size_limit'):
|
|
182
|
+
raise
|
|
183
|
+
code = str(exc) if isinstance(exc, ExportError) else 'artifact_unreadable'
|
|
184
|
+
paper['omitted'].append(f'page{number}/{kind}: {code}')
|
|
185
|
+
if not any(p['kind'] == 'html' for p in paper['materials']):
|
|
186
|
+
paper['omitted'].append('html_unavailable; original_page_cannot_be_reconstructed')
|
|
187
|
+
if not any(p['kind'] == 'screenshot' for p in paper['materials']):
|
|
188
|
+
paper['omitted'].append('screenshots_unavailable_or_excluded')
|
|
189
|
+
manifest['papers'].append(paper)
|
|
190
|
+
add('summary.md', _summary(manifest).encode('utf-8'))
|
|
191
|
+
manifest_bytes = _json(manifest)
|
|
192
|
+
if total + len(manifest_bytes) > MAX_PACKAGE_BYTES:
|
|
193
|
+
raise ExportError('package_size_limit; select_a_run_or_doi')
|
|
194
|
+
archive.writestr('manifest.json', manifest_bytes)
|
|
195
|
+
# Exclusive final publication: a racing export cannot overwrite another
|
|
196
|
+
# report. Temporary file is on the same filesystem on Windows and Unix.
|
|
197
|
+
os.link(temp, output)
|
|
198
|
+
finally:
|
|
199
|
+
Path(temp).unlink(missing_ok=True)
|
|
200
|
+
return {'ok': True, 'schemaVersion': 1, 'path': str(output), 'papers': len(rows),
|
|
201
|
+
'files': len(manifest['files']) + 1, 'bytes': output.stat().st_size,
|
|
202
|
+
'reviewRequired': True,
|
|
203
|
+
'incompletePapers': sum(bool(p['omitted']) for p in manifest['papers'])}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _json(data) -> bytes:
|
|
207
|
+
return json.dumps(data, ensure_ascii=False, indent=2).encode('utf-8')
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _summary(manifest: dict) -> str:
|
|
211
|
+
# Keep site text from becoming active Markdown/HTML or injected issue UI.
|
|
212
|
+
def plain(value) -> str:
|
|
213
|
+
text = str(value or 'unknown').replace('\n', ' ').replace('\r', ' ').replace('<', '<').replace('>', '>').replace('`', "'")
|
|
214
|
+
return re.sub(r'([\\*_{}\[\]()#+!|])', r'\\\1', text)
|
|
215
|
+
|
|
216
|
+
lines = ['# PaperSearch 下载失败记录', '',
|
|
217
|
+
f"导出版本:{plain(manifest['version'])};导出系统:{plain(manifest['exportSystem'])}", '',
|
|
218
|
+
'## 公开前请核对', '',
|
|
219
|
+
'- [ ] 检查所有 HTML、诊断文本和截图中的姓名、邮箱、学号、学校标识及其他个人信息。',
|
|
220
|
+
'- [ ] 检查图片;字符串脱敏不能保证移除图片像素中的个人信息。',
|
|
221
|
+
'- [ ] 确认只分享这个导出包,不附原始 diagnostics、浏览器 profile、Cookie 或下载正文。',
|
|
222
|
+
'', 'HTML 为不可执行结构快照,href/action 记录为 data-href/data-action;只保留有限文本片段。',
|
|
223
|
+
'旧记录缺失的材料不会补造;导出不会重跑下载。', '']
|
|
224
|
+
for p in manifest['papers']:
|
|
225
|
+
lines.extend([f"## {plain(p['doi'])}", '',
|
|
226
|
+
f"- 出版社:{plain(p['publisher'])}",
|
|
227
|
+
f"- 失败部分:{plain(p.get('part') or 'main')};分类:{plain(p['failureClass'])};原因:{plain(p['code'])}",
|
|
228
|
+
f"- 停止步骤:{plain(p['stoppedAt'])}",
|
|
229
|
+
f"- 最后网址:`{plain(p['finalUrl'])}`",
|
|
230
|
+
f"- 采集版本 / 系统:{plain(p['captureVersion'])} / {plain(p['captureSystem'])}",
|
|
231
|
+
f"- 材料目录:{p['folder']}"])
|
|
232
|
+
if p.get('evidence'):
|
|
233
|
+
lines.append(f"- 依据:{plain(p['evidence'])}")
|
|
234
|
+
for material in p['materials']:
|
|
235
|
+
lines.append(f"- 检查文件:{material['path']}")
|
|
236
|
+
for omission in p['omitted']:
|
|
237
|
+
lines.append(f"- 材料缺项或限制:{plain(omission)}")
|
|
238
|
+
lines.append('')
|
|
239
|
+
return '\n'.join(lines)
|
|
@@ -150,6 +150,9 @@ def attach_page(folder: Path, page: Any, events: list[dict[str, Any]] | None = N
|
|
|
150
150
|
tabs = [p for p in list(page.context.pages) if not p.is_closed()]
|
|
151
151
|
except Exception:
|
|
152
152
|
tabs = [page]
|
|
153
|
+
from .page_snapshot import capture_structure, masked_screenshot
|
|
154
|
+
from .config import load_config
|
|
155
|
+
config = load_config()
|
|
153
156
|
for index, tab in enumerate(tabs[:6], 1):
|
|
154
157
|
row: dict[str, Any] = {"index": index, "working_tab": tab is page}
|
|
155
158
|
for key, getter in (("url", lambda t: t.url), ("title", lambda t: t.title())):
|
|
@@ -161,12 +164,11 @@ def attach_page(folder: Path, page: Any, events: list[dict[str, Any]] | None = N
|
|
|
161
164
|
row["text_excerpt"] = tab.evaluate("() => (document.body ? document.body.innerText : '').slice(0, 3000)")
|
|
162
165
|
except Exception:
|
|
163
166
|
row["text_excerpt"] = ""
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
pass
|
|
167
|
+
row.update(capture_structure(tab, folder / f"tab{index}.html", config))
|
|
168
|
+
row.update(masked_screenshot(tab, folder / f"tab{index}.png"))
|
|
169
|
+
for key in ("html", "screenshot"):
|
|
170
|
+
if key in row:
|
|
171
|
+
row[key] = Path(row[key]).name
|
|
170
172
|
info["tabs"].append(row)
|
|
171
173
|
if events is not None:
|
|
172
174
|
info["recent_events"] = events[-40:]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Bounded, inert page specimens shared by download diagnostics and issues."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .report_sanitizer import MAX_HTML_BYTES, Redactor, sanitize_html
|
|
8
|
+
|
|
9
|
+
# Walk live DOM without copying a script, a form value or an entire article.
|
|
10
|
+
# The RPC is bounded in time, number of nodes, depth, text and returned size.
|
|
11
|
+
_STRUCTURE = r"""(root, limit) => {
|
|
12
|
+
let size = 0, nodes = 0, textLeft = 6000, truncated = false;
|
|
13
|
+
const out = [], drop = new Set(['SCRIPT','STYLE','NOSCRIPT','IFRAME','OBJECT','EMBED','SVG','MATH','TEMPLATE','CANVAS']);
|
|
14
|
+
const attrs = new Set(['id','class','role','name','type','title','alt','aria-label','aria-labelledby','aria-describedby','aria-expanded','aria-controls','data-testid','data-test','href','action','disabled']);
|
|
15
|
+
const esc = s => s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
|
16
|
+
const push = s => { if (size + s.length <= limit) { out.push(s); size += s.length; } else truncated = true; };
|
|
17
|
+
const walk = (node, depth) => {
|
|
18
|
+
if (++nodes > 6000 || depth > 60 || size >= limit - 1024) { truncated = true; return; }
|
|
19
|
+
if (node.nodeType === 3) {
|
|
20
|
+
const s = node.textContent.trim().slice(0, Math.min(160, textLeft));
|
|
21
|
+
textLeft -= s.length; if (s) push(esc(s)); return;
|
|
22
|
+
}
|
|
23
|
+
if (node.nodeType !== 1 || drop.has(node.tagName) || (node.tagName === 'INPUT' && node.type === 'hidden')) return;
|
|
24
|
+
const tag = node.tagName.toLowerCase();
|
|
25
|
+
push('<' + tag + Array.from(node.attributes).filter(a => attrs.has(a.name)).map(a => ' ' + a.name + '="' + esc(a.value.slice(0,500)) + '"').join('') + '>');
|
|
26
|
+
if (['textarea','select'].includes(tag)) { push('</' + tag + '>'); return; }
|
|
27
|
+
for (const child of node.childNodes) { if (nodes >= 6000 || size >= limit - 1024) { truncated = true; break; } walk(child, depth + 1); }
|
|
28
|
+
if (!['input','img','br','hr','meta','link'].includes(tag)) push('</' + tag + '>');
|
|
29
|
+
};
|
|
30
|
+
walk(root, 0); return {html: out.join(''), truncated: truncated || textLeft <= 0,
|
|
31
|
+
private: !!root.querySelector('input[type=password],input[autocomplete=username],input[autocomplete=current-password]')};
|
|
32
|
+
}"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def capture_structure(page: Any, path: Path, config: dict | None = None) -> dict:
|
|
36
|
+
"""Optional evidence failure is recorded, never changes the download result."""
|
|
37
|
+
try:
|
|
38
|
+
from .browser import watchdog
|
|
39
|
+
if watchdog.fired:
|
|
40
|
+
return {'html_omitted': 'browser_stopped'}
|
|
41
|
+
raw = page.locator('html').evaluate(_STRUCTURE, MAX_HTML_BYTES // 2, timeout=3000)
|
|
42
|
+
if not isinstance(raw, dict) or not isinstance(raw.get('html'), str):
|
|
43
|
+
return {'html_omitted': 'capture_unavailable'}
|
|
44
|
+
content, truncated = sanitize_html(raw['html'], Redactor(config))
|
|
45
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
path.write_text(content, encoding='utf-8')
|
|
47
|
+
return {'html': str(path), 'html_truncated': bool(truncated or raw.get('truncated')),
|
|
48
|
+
'screenshot_private': bool(raw.get('private'))}
|
|
49
|
+
except Exception as exc:
|
|
50
|
+
return {'html_omitted': type(exc).__name__}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def masked_screenshot(page: Any, path: Path) -> dict:
|
|
54
|
+
try:
|
|
55
|
+
from .browser import watchdog
|
|
56
|
+
if watchdog.fired:
|
|
57
|
+
return {'screenshot_omitted': 'browser_stopped'}
|
|
58
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
encoding = {"type": "jpeg", "quality": 50} if path.suffix.lower() in {".jpg", ".jpeg"} else {"type": "png"}
|
|
60
|
+
page.screenshot(path=str(path), **encoding, full_page=False, timeout=3000,
|
|
61
|
+
mask=[page.locator('input, textarea, select, [contenteditable]')])
|
|
62
|
+
return {'screenshot': str(path), 'screenshot_masked': True}
|
|
63
|
+
except Exception as exc:
|
|
64
|
+
return {'screenshot_omitted': type(exc).__name__}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Sanitization for shareable copies, never for the original local diagnosis.
|
|
2
|
+
|
|
3
|
+
HTML is a structural specimen, not an executable/offline copy of a website.
|
|
4
|
+
Unknown query parameters are dropped; keeping publisher paths and selector
|
|
5
|
+
attributes is enough to investigate entries without retaining signed sessions.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import html
|
|
10
|
+
import re
|
|
11
|
+
from html.parser import HTMLParser
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from urllib.parse import parse_qsl, unquote, urlencode, urlsplit, urlunsplit
|
|
14
|
+
|
|
15
|
+
MAX_HTML_BYTES = 256 * 1024
|
|
16
|
+
MAX_TEXT_CHARS = 6000
|
|
17
|
+
_URL = re.compile(r'https?://[^\s<>"\x27]+', re.I)
|
|
18
|
+
_AUTH = re.compile(r'login|sign[ _-]?in|saml|oauth|shibboleth|\bsso\b|identity|authenticate|authorize|idp|登录|登入|认证', re.I)
|
|
19
|
+
_SECRET = re.compile(r'cookie|header|authorization|password|passwd|secret|token|ticket|session|saml|relaystate|credential|storage|api.?key|csrf|nonce|signature', re.I)
|
|
20
|
+
_ASSIGNMENT = re.compile(
|
|
21
|
+
r'(?i)\b(?:cookie|set-cookie|authorization|password|passwd|secret|[\w-]*token|ticket|'
|
|
22
|
+
r'[\w-]*session[\w-]*|samlrequest|samlresponse|relaystate|code|csrf|nonce|signature)'
|
|
23
|
+
r'\b[\s"\x27]*[:=]\s*(?:"[^"\n]*"|\x27[^\x27\n]*\x27|[^\s<>;,]+)')
|
|
24
|
+
_SAFE_QUERY = frozenset({'doi', 'article', 'articleid', 'id', 'pii', 'issue', 'volume', 'year', 'page', 'format', 'type'})
|
|
25
|
+
_OMIT = frozenset({'full_text', 'text_excerpt', 'pdf_path', 'file', 'record_path', 'diagnostic_path',
|
|
26
|
+
'traceback', 'browser', 'browser_start', 'screenshots', 'screenshot', 'html', 'path'})
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def decoded(value: str) -> str:
|
|
30
|
+
for _ in range(8):
|
|
31
|
+
new = html.unescape(unquote(value))
|
|
32
|
+
if new == value:
|
|
33
|
+
break
|
|
34
|
+
value = new
|
|
35
|
+
if html.unescape(unquote(value)) != value:
|
|
36
|
+
return '[ENCODED_VALUE_REMOVED]'
|
|
37
|
+
return value
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def host_of(url: str) -> str:
|
|
41
|
+
try:
|
|
42
|
+
return (urlsplit(url).hostname or '').lower()
|
|
43
|
+
except ValueError:
|
|
44
|
+
return ''
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Redactor:
|
|
48
|
+
def __init__(self, config: dict | None = None):
|
|
49
|
+
self.terms: set[str] = set()
|
|
50
|
+
self.school_hosts: set[str] = set()
|
|
51
|
+
cfg = config or {}
|
|
52
|
+
for key in ('carsi_idp_name', 'carsi_idp_name_en', 'idp_entity_id', 'institution_domain', 'idp_domain'):
|
|
53
|
+
value = str(cfg.get(key) or '').strip()
|
|
54
|
+
if len(value) > 2:
|
|
55
|
+
self.terms.add(value)
|
|
56
|
+
host = host_of(value) or (value if key.endswith('_domain') else '')
|
|
57
|
+
if host:
|
|
58
|
+
self.school_hosts.add(host)
|
|
59
|
+
# The configured IdP often lives below the institution's domain.
|
|
60
|
+
for host in list(self.school_hosts):
|
|
61
|
+
if host.split('.')[0] in {'idp', 'sso', 'login', 'auth'} and host.count('.') >= 2:
|
|
62
|
+
self.school_hosts.add(host.split('.', 1)[1])
|
|
63
|
+
self.home = str(Path.home())
|
|
64
|
+
self.usernames: set[str] = {Path.home().name}
|
|
65
|
+
self.secrets: set[str] = set()
|
|
66
|
+
for key, value in cfg.items():
|
|
67
|
+
if _SECRET.search(key) and isinstance(value, str) and len(value) >= 6:
|
|
68
|
+
self.secrets.add(value)
|
|
69
|
+
|
|
70
|
+
def observe(self, data, depth: int = 0) -> None:
|
|
71
|
+
"""Discover school URLs from explicitly labelled school/IdP evidence.
|
|
72
|
+
|
|
73
|
+
Generic federation login hosts are not automatically school domains.
|
|
74
|
+
A bare login URL still loses its query and its screenshot is excluded.
|
|
75
|
+
"""
|
|
76
|
+
if depth > 30:
|
|
77
|
+
return
|
|
78
|
+
if isinstance(data, dict):
|
|
79
|
+
state = str(data.get('state') or '').lower()
|
|
80
|
+
for key, value in data.items():
|
|
81
|
+
if _SECRET.search(str(key)) and isinstance(value, str) and len(value) >= 6:
|
|
82
|
+
self.secrets.add(value)
|
|
83
|
+
if isinstance(value, str) and (
|
|
84
|
+
key in {'idp_entity_id', 'idp_url', 'school_url', 'institution_domain'}
|
|
85
|
+
or ('school' in state and key in {'detail', 'url'})
|
|
86
|
+
):
|
|
87
|
+
for url in _URL.findall(decoded(value)):
|
|
88
|
+
host = host_of(url)
|
|
89
|
+
if host:
|
|
90
|
+
self.school_hosts.add(host)
|
|
91
|
+
self.observe(value, depth + 1)
|
|
92
|
+
elif isinstance(data, str):
|
|
93
|
+
value = decoded(data)
|
|
94
|
+
self.usernames.update(re.findall(r'(?i)(?:[A-Z]:[\\/](?:Users|Documents and Settings)[\\/]|/(?:Users|home)/)([^/\\\s"\x27]+)', value))
|
|
95
|
+
elif isinstance(data, list):
|
|
96
|
+
for row in data:
|
|
97
|
+
self.observe(row, depth + 1)
|
|
98
|
+
|
|
99
|
+
def school_url(self, url: str) -> bool:
|
|
100
|
+
host = host_of(url)
|
|
101
|
+
return any(host == h or host.endswith('.' + h) for h in self.school_hosts)
|
|
102
|
+
|
|
103
|
+
def private_page(self, url: str, title: str = '', why: str = '') -> bool:
|
|
104
|
+
return (not host_of(url) or self.school_url(url) or bool(_AUTH.search(url + ' ' + title))
|
|
105
|
+
or bool(re.search(r'school|学校|账号', why, re.I)))
|
|
106
|
+
|
|
107
|
+
def url(self, raw: str) -> str:
|
|
108
|
+
value = decoded(raw)
|
|
109
|
+
try:
|
|
110
|
+
parts = urlsplit(value)
|
|
111
|
+
if parts.scheme not in {'http', 'https', ''} or not parts.netloc and parts.scheme:
|
|
112
|
+
return '[URL_REMOVED]'
|
|
113
|
+
private = self.school_url(value)
|
|
114
|
+
host = 'school.invalid' if private else (parts.hostname or '')
|
|
115
|
+
if parts.port and not private:
|
|
116
|
+
host += ':' + str(parts.port)
|
|
117
|
+
auth = private or bool(_AUTH.search(parts.netloc + parts.path))
|
|
118
|
+
path = '/[AUTH_PATH]' if private else parts.path
|
|
119
|
+
path = re.sub(r'(?i)(/(?:token|ticket|session|code|saml|oauth|auth)/).*', r'\1[REDACTED]', path)
|
|
120
|
+
path = re.sub(r'(?i);[^/]*', '', path)
|
|
121
|
+
path = re.sub(r'(?<![\w-])[A-Za-z0-9_-]{48,}(?![\w-])', '[REDACTED]', path)
|
|
122
|
+
query = [] if auth else [(k, v) for k, v in parse_qsl(parts.query)
|
|
123
|
+
if k.lower() in _SAFE_QUERY and len(v) <= 160
|
|
124
|
+
and not _SECRET.search(k) and '://' not in v
|
|
125
|
+
and (v.isdigit() or (k.lower() == 'doi' and re.fullmatch(r'10\.\d{4,9}/[-._;()/:A-Za-z0-9]+', v))
|
|
126
|
+
or (k.lower() in {'format', 'type'} and v.lower() in {'pdf', 'html', 'xml', 'epdf', 'article'}))]
|
|
127
|
+
return self._terms(urlunsplit((parts.scheme, host, path, urlencode(query), '')))
|
|
128
|
+
except ValueError:
|
|
129
|
+
return '[URL_REMOVED]'
|
|
130
|
+
|
|
131
|
+
def _terms(self, text: str) -> str:
|
|
132
|
+
for secret in sorted(self.secrets, key=len, reverse=True):
|
|
133
|
+
text = text.replace(secret, '[SECRET_REMOVED]')
|
|
134
|
+
for name in self.usernames:
|
|
135
|
+
if len(name) >= 3:
|
|
136
|
+
text = re.sub(r'(?<![\w.-])' + re.escape(name) + r'(?![\w.-])', '[USER]', text, flags=re.I)
|
|
137
|
+
for term in sorted(self.terms | self.school_hosts, key=len, reverse=True):
|
|
138
|
+
text = re.sub(re.escape(term), '[INSTITUTION]', text, flags=re.I)
|
|
139
|
+
return text
|
|
140
|
+
|
|
141
|
+
def text(self, text: str) -> str:
|
|
142
|
+
text = decoded(text)
|
|
143
|
+
# Strip entire header lines, not merely the first word of a Cookie value.
|
|
144
|
+
text = re.sub(r'(?im)\b(?:cookie|set-cookie|authorization|proxy-authorization)\s*[:=][^\n]*', '[SECRET_REMOVED]', text)
|
|
145
|
+
text = _URL.sub(lambda m: self.url(m.group()), text)
|
|
146
|
+
text = _ASSIGNMENT.sub('[SECRET_REMOVED]', text)
|
|
147
|
+
text = text.replace(self.home, '~')
|
|
148
|
+
text = re.sub(r'(?i)(?:[A-Z]:[\\/](?:Users|Documents and Settings)[\\/]|/(?:Users|home)/)[^/\\\s"\x27]+', '~', text)
|
|
149
|
+
text = re.sub(r'(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b', '[EMAIL]', text)
|
|
150
|
+
text = re.sub(r'eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+', '[SECRET_REMOVED]', text)
|
|
151
|
+
return self._terms(text)
|
|
152
|
+
|
|
153
|
+
def clean(self, value, depth: int = 0):
|
|
154
|
+
if depth > 30:
|
|
155
|
+
return '[DEPTH_LIMIT]'
|
|
156
|
+
if isinstance(value, str):
|
|
157
|
+
return self.text(value)
|
|
158
|
+
if isinstance(value, dict):
|
|
159
|
+
return {self.text(str(k)): self.clean(v, depth + 1) for k, v in value.items()
|
|
160
|
+
if str(k).lower() not in _OMIT and not _SECRET.search(str(k))}
|
|
161
|
+
if isinstance(value, list):
|
|
162
|
+
return [self.clean(v, depth + 1) for v in value]
|
|
163
|
+
return value if value is None or isinstance(value, (bool, int, float)) else None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
TAGS = frozenset('html head body title main article section nav header footer aside div span p h1 h2 h3 h4 h5 h6 ul ol li dl dt dd a button form label input select option textarea table thead tbody tr th td details summary br hr strong em b i img'.split())
|
|
167
|
+
DROP = frozenset('script style noscript iframe object embed svg math template canvas'.split())
|
|
168
|
+
ATTRS = frozenset({'id', 'class', 'role', 'name', 'type', 'title', 'alt', 'aria-label', 'aria-labelledby',
|
|
169
|
+
'aria-describedby', 'aria-expanded', 'aria-controls', 'data-testid', 'data-test',
|
|
170
|
+
'href', 'action', 'data-href', 'data-action', 'disabled'})
|
|
171
|
+
VOID = frozenset('input img br hr meta link base area col source track wbr embed param'.split())
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class StructureParser(HTMLParser):
|
|
175
|
+
def __init__(self, redactor: Redactor):
|
|
176
|
+
super().__init__(convert_charrefs=True)
|
|
177
|
+
self.redactor = redactor
|
|
178
|
+
self.parts: list[str] = []
|
|
179
|
+
self.stack: list[tuple[str, bool]] = []
|
|
180
|
+
self.skip = 0
|
|
181
|
+
self.size = 0
|
|
182
|
+
self.text_left = MAX_TEXT_CHARS
|
|
183
|
+
self.truncated = False
|
|
184
|
+
|
|
185
|
+
def emit(self, value: str) -> None:
|
|
186
|
+
size = len(value.encode('utf-8'))
|
|
187
|
+
if self.size + size > MAX_HTML_BYTES - 1024:
|
|
188
|
+
self.truncated = True
|
|
189
|
+
return
|
|
190
|
+
self.parts.append(value)
|
|
191
|
+
self.size += size
|
|
192
|
+
|
|
193
|
+
def handle_starttag(self, tag, attrs):
|
|
194
|
+
hidden = tag in DROP or (tag == 'input' and (dict(attrs).get('type') or '').lower() == 'hidden')
|
|
195
|
+
value_field = tag in {'textarea', 'select'}
|
|
196
|
+
parent_skip = self.skip > 0
|
|
197
|
+
if tag not in VOID:
|
|
198
|
+
self.stack.append((tag, hidden or value_field))
|
|
199
|
+
if hidden or value_field:
|
|
200
|
+
self.skip += 1
|
|
201
|
+
if parent_skip or hidden or tag not in TAGS:
|
|
202
|
+
return
|
|
203
|
+
fields = []
|
|
204
|
+
for key, value in attrs:
|
|
205
|
+
if key not in ATTRS or value is None or _SECRET.search(key):
|
|
206
|
+
continue
|
|
207
|
+
if key in {'href', 'action', 'data-href', 'data-action'}:
|
|
208
|
+
key = 'data-' + key if not key.startswith('data-') else key
|
|
209
|
+
value = self.redactor.url(value)
|
|
210
|
+
else:
|
|
211
|
+
value = self.redactor.text(value[:500])
|
|
212
|
+
fields.append(f' {key}="{html.escape(value, quote=True)}"')
|
|
213
|
+
self.emit('<' + tag + ''.join(fields) + '>')
|
|
214
|
+
if value_field:
|
|
215
|
+
self.emit('</' + tag + '>')
|
|
216
|
+
|
|
217
|
+
def handle_startendtag(self, tag, attrs):
|
|
218
|
+
self.handle_starttag(tag, attrs)
|
|
219
|
+
if tag not in VOID:
|
|
220
|
+
self.handle_endtag(tag)
|
|
221
|
+
|
|
222
|
+
def handle_endtag(self, tag):
|
|
223
|
+
if tag in VOID:
|
|
224
|
+
return
|
|
225
|
+
# Malformed input must not prematurely escape a dropped subtree.
|
|
226
|
+
if not self.stack or self.stack[-1][0] != tag:
|
|
227
|
+
return
|
|
228
|
+
was_skip = self.skip
|
|
229
|
+
_, hidden = self.stack.pop()
|
|
230
|
+
if hidden:
|
|
231
|
+
self.skip -= 1
|
|
232
|
+
if not was_skip and tag in TAGS:
|
|
233
|
+
self.emit('</' + tag + '>')
|
|
234
|
+
|
|
235
|
+
def handle_data(self, data):
|
|
236
|
+
if self.skip or not data.strip() or self.text_left <= 0:
|
|
237
|
+
return
|
|
238
|
+
value = self.redactor.text(data.strip())[:min(160, self.text_left)]
|
|
239
|
+
self.text_left -= len(value)
|
|
240
|
+
self.emit(html.escape(value))
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def sanitize_html(source: str, redactor: Redactor) -> tuple[str, bool]:
|
|
244
|
+
parser = StructureParser(redactor)
|
|
245
|
+
parser.feed(source[:MAX_HTML_BYTES * 4])
|
|
246
|
+
parser.close()
|
|
247
|
+
prefix = '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; form-action \'none\'; base-uri \'none\'">\n'
|
|
248
|
+
return prefix + ''.join(parser.parts), parser.truncated or len(source) > MAX_HTML_BYTES * 4 or parser.text_left <= 0
|
|
@@ -17,7 +17,7 @@ export const CARSI_DOWNLOAD_TIMEOUT_MS = 1_200_000;
|
|
|
17
17
|
export const CARSI_CLEANUP_TIMEOUT_MS = 5_000;
|
|
18
18
|
const CARSI_BACKEND_SOURCE = "carsi";
|
|
19
19
|
// MCP clientInfo is informational only; keep in step with package.json on release.
|
|
20
|
-
const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.4.
|
|
20
|
+
const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.4.8";
|
|
21
21
|
const NO_BATCH_SUPPORT = {
|
|
22
22
|
downloadFields: false,
|
|
23
23
|
supplementsField: false,
|