@vessel-agent/web-tools 0.0.0-stage → 2.3.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +329 -2
- package/package.json +182 -4
- package/src/backends.ts +61 -0
- package/src/budget.ts +80 -0
- package/src/cache.ts +94 -0
- package/src/config.ts +412 -0
- package/src/deepseek-client.ts +406 -0
- package/src/deepseek-fetch.ts +168 -0
- package/src/extract.ts +373 -0
- package/src/fetch/local.ts +36 -0
- package/src/fetch/provider.ts +56 -0
- package/src/http.ts +415 -0
- package/src/index.ts +649 -0
- package/src/limits.ts +388 -0
- package/src/provider-http.ts +102 -0
- package/src/render.ts +248 -0
- package/src/robots.ts +187 -0
- package/src/search/custom.ts +595 -0
- package/src/search/deepseek.ts +111 -0
- package/src/search/index.ts +725 -0
- package/src/search/provider.ts +200 -0
- package/src/search/serper.ts +157 -0
- package/src/search/tavily.ts +146 -0
- package/src/secrets.ts +87 -0
- package/src/ssrf.ts +287 -0
- package/src/types.ts +137 -0
package/src/http.ts
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 一级抓取:纯 HTTP + 受控重定向。
|
|
3
|
+
*
|
|
4
|
+
* 关键点(都是安全边界,改动前先想清楚):
|
|
5
|
+
* - `redirect: 'manual'`:绝不让 fetch 自己跟跳,否则 SSRF 校验只在第一跳生效;
|
|
6
|
+
* - 每一跳都重新 `checkUrl` + 重新解析 DNS 并校验 IP;
|
|
7
|
+
* - 整体一个 deadline(`timeout_ms`),不是「每跳一个」——否则 6 跳能拖 60s;
|
|
8
|
+
* - 先看 `content-length` 再流式读,边读边计数,超限立刻 cancel。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { lookup } from 'node:dns/promises';
|
|
12
|
+
import { truncateText } from './budget';
|
|
13
|
+
import { isAllowedContentType, type WebFetchConfig } from './config';
|
|
14
|
+
import { extractDocument } from './extract';
|
|
15
|
+
import {
|
|
16
|
+
allowAllRules,
|
|
17
|
+
disallowAllRules,
|
|
18
|
+
parseRobotsTxt,
|
|
19
|
+
RobotsCache,
|
|
20
|
+
type RobotsRules,
|
|
21
|
+
} from './robots';
|
|
22
|
+
import { assertAddressAllowed, type CheckedUrl, checkUrl, type UrlPolicy } from './ssrf';
|
|
23
|
+
import { WebFetchError, type WebFetchResult } from './types';
|
|
24
|
+
|
|
25
|
+
export interface WebFetchDeps {
|
|
26
|
+
/** 注入点:探针用替身,生产用全局 fetch */
|
|
27
|
+
fetch?: typeof fetch;
|
|
28
|
+
/** 注入点:DNS 解析(返回全部 A/AAAA) */
|
|
29
|
+
resolveHost?: (host: string) => Promise<string[]>;
|
|
30
|
+
/** 注入点:时钟 */
|
|
31
|
+
now?: () => number;
|
|
32
|
+
/** 注入点:robots 缓存(探针用来断言同源只拉一次) */
|
|
33
|
+
robotsCache?: RobotsCache;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface FetchPageOptions {
|
|
37
|
+
config: WebFetchConfig;
|
|
38
|
+
deps?: WebFetchDeps;
|
|
39
|
+
signal?: AbortSignal;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
|
|
43
|
+
|
|
44
|
+
async function defaultResolveHost(host: string): Promise<string[]> {
|
|
45
|
+
const records = await lookup(host, { all: true, verbatim: true });
|
|
46
|
+
return records.map((record) => record.address);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function policyOf(config: WebFetchConfig): UrlPolicy {
|
|
50
|
+
return {
|
|
51
|
+
allowPrivateNetworks: config.allowPrivateNetworks,
|
|
52
|
+
domainAllowlist: config.domainAllowlist,
|
|
53
|
+
domainDenylist: config.domainDenylist,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function requestHeaders(config: WebFetchConfig): Record<string, string> {
|
|
58
|
+
return {
|
|
59
|
+
'user-agent': config.userAgent,
|
|
60
|
+
accept:
|
|
61
|
+
'text/html,application/xhtml+xml,application/xml;q=0.9,application/json;q=0.8,text/plain;q=0.7,*/*;q=0.1',
|
|
62
|
+
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
|
63
|
+
'cache-control': 'no-cache',
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** DNS 解析 + 逐 IP 校验(rebinding 防护的「解析后校验」这一半,残留窗口见 ssrf.ts 注释)。 */
|
|
68
|
+
async function assertHostPublic(
|
|
69
|
+
checked: CheckedUrl,
|
|
70
|
+
resolveHost: (host: string) => Promise<string[]>,
|
|
71
|
+
config: WebFetchConfig,
|
|
72
|
+
): Promise<void> {
|
|
73
|
+
if (checked.isIpLiteral) return;
|
|
74
|
+
let addresses: string[];
|
|
75
|
+
try {
|
|
76
|
+
addresses = await resolveHost(checked.host);
|
|
77
|
+
} catch {
|
|
78
|
+
throw new WebFetchError('dns_failed', `DNS 解析失败:${checked.host}`, {
|
|
79
|
+
url: checked.url.href,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (addresses.length === 0) {
|
|
83
|
+
throw new WebFetchError('dns_failed', `DNS 未返回任何地址:${checked.host}`, {
|
|
84
|
+
url: checked.url.href,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
for (const address of addresses) {
|
|
88
|
+
try {
|
|
89
|
+
assertAddressAllowed(address, checked.host, config.allowPrivateNetworks);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error instanceof WebFetchError) {
|
|
92
|
+
throw new WebFetchError(error.code, error.message, { url: checked.url.href });
|
|
93
|
+
}
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 取 robots.txt 也走同一套逐跳校验:`redirect: 'manual'` + 最多 3 跳 + 每跳 checkUrl,
|
|
101
|
+
* 免得 robots.txt 的 302 把请求带去 169.254.169.254。
|
|
102
|
+
*/
|
|
103
|
+
async function loadRobots(
|
|
104
|
+
origin: string,
|
|
105
|
+
config: WebFetchConfig,
|
|
106
|
+
doFetch: typeof fetch,
|
|
107
|
+
signal: AbortSignal,
|
|
108
|
+
): Promise<RobotsRules> {
|
|
109
|
+
const policy = policyOf(config);
|
|
110
|
+
let target = new URL('/robots.txt', origin);
|
|
111
|
+
for (let hop = 0; hop < 3; hop += 1) {
|
|
112
|
+
let checked: CheckedUrl;
|
|
113
|
+
try {
|
|
114
|
+
checked = checkUrl(target.href, policy);
|
|
115
|
+
} catch {
|
|
116
|
+
return disallowAllRules();
|
|
117
|
+
}
|
|
118
|
+
let response: Response;
|
|
119
|
+
try {
|
|
120
|
+
response = await doFetch(checked.url.href, {
|
|
121
|
+
method: 'GET',
|
|
122
|
+
redirect: 'manual',
|
|
123
|
+
headers: { 'user-agent': config.userAgent, accept: 'text/plain,*/*' },
|
|
124
|
+
signal,
|
|
125
|
+
});
|
|
126
|
+
} catch {
|
|
127
|
+
// 网络层拿不到 robots.txt:保守视为全部禁止
|
|
128
|
+
return disallowAllRules();
|
|
129
|
+
}
|
|
130
|
+
const location = response.headers.get('location');
|
|
131
|
+
if (REDIRECT_STATUS.has(response.status) && location) {
|
|
132
|
+
try {
|
|
133
|
+
target = new URL(location, checked.url);
|
|
134
|
+
} catch {
|
|
135
|
+
return disallowAllRules();
|
|
136
|
+
}
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (response.status >= 500) return disallowAllRules();
|
|
140
|
+
if (response.status < 200 || response.status >= 300) return allowAllRules();
|
|
141
|
+
let raw: string;
|
|
142
|
+
try {
|
|
143
|
+
raw = await response.text();
|
|
144
|
+
} catch {
|
|
145
|
+
return disallowAllRules();
|
|
146
|
+
}
|
|
147
|
+
return parseRobotsTxt(raw.slice(0, 512 * 1024), config.userAgent);
|
|
148
|
+
}
|
|
149
|
+
return disallowAllRules();
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function assertRobotsAllowed(
|
|
153
|
+
checked: CheckedUrl,
|
|
154
|
+
config: WebFetchConfig,
|
|
155
|
+
cache: RobotsCache,
|
|
156
|
+
doFetch: typeof fetch,
|
|
157
|
+
signal: AbortSignal,
|
|
158
|
+
): Promise<void> {
|
|
159
|
+
const rules = await cache.get(checked.url.origin, () =>
|
|
160
|
+
loadRobots(checked.url.origin, config, doFetch, signal),
|
|
161
|
+
);
|
|
162
|
+
const path = `${checked.url.pathname}${checked.url.search}`;
|
|
163
|
+
if (!rules.isAllowed(path)) {
|
|
164
|
+
throw new WebFetchError('blocked_by_robots', `robots.txt 不允许抓取 ${path}`, {
|
|
165
|
+
url: checked.url.href,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function readBodyLimited(
|
|
171
|
+
response: Response,
|
|
172
|
+
maxBytes: number,
|
|
173
|
+
url: string,
|
|
174
|
+
): Promise<Uint8Array> {
|
|
175
|
+
const body = response.body;
|
|
176
|
+
if (!body) return new Uint8Array(0);
|
|
177
|
+
|
|
178
|
+
const reader = body.getReader();
|
|
179
|
+
const chunks: Uint8Array[] = [];
|
|
180
|
+
let total = 0;
|
|
181
|
+
for (;;) {
|
|
182
|
+
const step = await reader.read();
|
|
183
|
+
if (step.done) break;
|
|
184
|
+
const value = step.value;
|
|
185
|
+
if (!value) continue;
|
|
186
|
+
total += value.byteLength;
|
|
187
|
+
if (total > maxBytes) {
|
|
188
|
+
await reader.cancel().catch(() => undefined); // benign: 超限取消流,失败不掩盖原始错误。
|
|
189
|
+
throw new WebFetchError('too_large', `响应体超过 ${maxBytes} 字节上限`, { url });
|
|
190
|
+
}
|
|
191
|
+
chunks.push(value);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const joined = new Uint8Array(total);
|
|
195
|
+
let offset = 0;
|
|
196
|
+
for (const chunk of chunks) {
|
|
197
|
+
joined.set(chunk, offset);
|
|
198
|
+
offset += chunk.byteLength;
|
|
199
|
+
}
|
|
200
|
+
return joined;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function filterSameOriginLinks(links: string[], base: URL, limit: number): string[] {
|
|
204
|
+
if (limit <= 0) return [];
|
|
205
|
+
const seen = new Set<string>();
|
|
206
|
+
const out: string[] = [];
|
|
207
|
+
for (const link of links) {
|
|
208
|
+
if (out.length >= limit) break;
|
|
209
|
+
let parsed: URL;
|
|
210
|
+
try {
|
|
211
|
+
parsed = new URL(link);
|
|
212
|
+
} catch {
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') continue;
|
|
216
|
+
if (parsed.origin !== base.origin) continue;
|
|
217
|
+
parsed.hash = '';
|
|
218
|
+
const href = parsed.href;
|
|
219
|
+
if (seen.has(href)) continue;
|
|
220
|
+
seen.add(href);
|
|
221
|
+
out.push(href);
|
|
222
|
+
}
|
|
223
|
+
return out;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
interface RedirectOutcome {
|
|
227
|
+
response: Response;
|
|
228
|
+
checked: CheckedUrl;
|
|
229
|
+
redirects: string[];
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** 把「失败就抛」的调用收成一个表达式,避免 `let x!: T` 这类靠 CFA 的写法。 */
|
|
233
|
+
async function attempt<T>(run: () => Promise<T>, onError: (error: unknown) => never): Promise<T> {
|
|
234
|
+
try {
|
|
235
|
+
return await run();
|
|
236
|
+
} catch (error) {
|
|
237
|
+
return onError(error);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export async function fetchPage(
|
|
242
|
+
rawUrl: string,
|
|
243
|
+
options: FetchPageOptions,
|
|
244
|
+
): Promise<WebFetchResult> {
|
|
245
|
+
const config = options.config;
|
|
246
|
+
const deps = options.deps ?? {};
|
|
247
|
+
const doFetch = deps.fetch ?? fetch;
|
|
248
|
+
const resolveHost = deps.resolveHost ?? defaultResolveHost;
|
|
249
|
+
const now = deps.now ?? (() => Date.now());
|
|
250
|
+
const robots = deps.robotsCache ?? new RobotsCache(config.robotsTtlMs);
|
|
251
|
+
const policy = policyOf(config);
|
|
252
|
+
|
|
253
|
+
const requested = rawUrl.trim();
|
|
254
|
+
// 第一跳在开 timer 之前先做静态校验:连 URL 都不合法就不用建 controller 了
|
|
255
|
+
checkUrl(requested, policy);
|
|
256
|
+
|
|
257
|
+
const controller = new AbortController();
|
|
258
|
+
let timedOut = false;
|
|
259
|
+
const timer = setTimeout(() => {
|
|
260
|
+
timedOut = true;
|
|
261
|
+
controller.abort();
|
|
262
|
+
}, config.timeoutMs);
|
|
263
|
+
const onOuterAbort = () => controller.abort();
|
|
264
|
+
options.signal?.addEventListener('abort', onOuterAbort, { once: true });
|
|
265
|
+
|
|
266
|
+
/** 网络层错误 → 统一错误码。放这里是为了能读到 timedOut / 调用方取消。 */
|
|
267
|
+
const toWebFetchError = (error: unknown, url: string): never => {
|
|
268
|
+
if (error instanceof WebFetchError) throw error;
|
|
269
|
+
if (options.signal?.aborted && !timedOut) {
|
|
270
|
+
throw new WebFetchError('connect_failed', '抓取被调用方取消', { url });
|
|
271
|
+
}
|
|
272
|
+
if (timedOut || (error as { name?: string } | null)?.name === 'AbortError') {
|
|
273
|
+
throw new WebFetchError('timeout', `抓取超时(>${config.timeoutMs}ms)`, { url });
|
|
274
|
+
}
|
|
275
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
276
|
+
if (/certificate|tls|ssl|self-signed/i.test(message)) {
|
|
277
|
+
throw new WebFetchError('tls_error', `TLS 握手失败:${message}`, { url });
|
|
278
|
+
}
|
|
279
|
+
throw new WebFetchError('connect_failed', `连接失败:${message}`, { url });
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
/** 跟随重定向(每跳重查),返回最后一跳的响应。 */
|
|
283
|
+
const followRedirects = async (): Promise<RedirectOutcome> => {
|
|
284
|
+
const redirects: string[] = [];
|
|
285
|
+
let checked = checkUrl(requested, policy);
|
|
286
|
+
for (let hop = 0; ; hop += 1) {
|
|
287
|
+
await assertHostPublic(checked, resolveHost, config);
|
|
288
|
+
if (config.respectRobots) {
|
|
289
|
+
await assertRobotsAllowed(checked, config, robots, doFetch, controller.signal);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const response = await attempt(
|
|
293
|
+
() =>
|
|
294
|
+
doFetch(checked.url.href, {
|
|
295
|
+
method: 'GET',
|
|
296
|
+
redirect: 'manual',
|
|
297
|
+
headers: requestHeaders(config),
|
|
298
|
+
signal: controller.signal,
|
|
299
|
+
}),
|
|
300
|
+
(error) => toWebFetchError(error, checked.url.href),
|
|
301
|
+
);
|
|
302
|
+
|
|
303
|
+
const location = response.headers.get('location');
|
|
304
|
+
if (REDIRECT_STATUS.has(response.status) && location !== null && location !== '') {
|
|
305
|
+
if (hop >= config.maxRedirects) {
|
|
306
|
+
throw new WebFetchError('too_many_redirects', `重定向超过 ${config.maxRedirects} 跳`, {
|
|
307
|
+
url: checked.url.href,
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
// 每跳重查:Location 由远端控制,必须当成不可信输入再走一遍全套判定
|
|
311
|
+
const next = checkUrl(location, { ...policy, base: checked.url.href });
|
|
312
|
+
if (
|
|
313
|
+
checked.url.protocol === 'https:' &&
|
|
314
|
+
next.url.protocol === 'http:' &&
|
|
315
|
+
!config.allowHttpsToHttp
|
|
316
|
+
) {
|
|
317
|
+
throw new WebFetchError('blocked_url', '禁止从 https 降级重定向到 http', {
|
|
318
|
+
url: next.url.href,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
redirects.push(next.url.href);
|
|
322
|
+
checked = next;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
return { response, checked, redirects };
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
try {
|
|
330
|
+
const { response, checked, redirects } = await followRedirects();
|
|
331
|
+
const finalUrl = checked.url.href;
|
|
332
|
+
const status = response.status;
|
|
333
|
+
|
|
334
|
+
if (status >= 400) {
|
|
335
|
+
throw new WebFetchError('http_error', `HTTP ${status}`, { url: finalUrl, status });
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const contentTypeHeader = response.headers.get('content-type') ?? '';
|
|
339
|
+
const mime = (contentTypeHeader.split(';')[0] ?? '').trim().toLowerCase();
|
|
340
|
+
if (!isAllowedContentType(mime, config.allowedContentTypes)) {
|
|
341
|
+
throw new WebFetchError(
|
|
342
|
+
'unsupported_content_type',
|
|
343
|
+
`content-type 不在白名单:${mime === '' ? '(缺失)' : mime}`,
|
|
344
|
+
{ url: finalUrl, status },
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const declaredLength = Number(response.headers.get('content-length') ?? '');
|
|
349
|
+
if (Number.isFinite(declaredLength) && declaredLength > config.maxBytes) {
|
|
350
|
+
throw new WebFetchError(
|
|
351
|
+
'too_large',
|
|
352
|
+
`声明长度 ${declaredLength} 超过 ${config.maxBytes} 字节上限`,
|
|
353
|
+
{
|
|
354
|
+
url: finalUrl,
|
|
355
|
+
status,
|
|
356
|
+
},
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const bytes = await attempt(
|
|
361
|
+
() => readBodyLimited(response, config.maxBytes, finalUrl),
|
|
362
|
+
(error) => toWebFetchError(error, finalUrl),
|
|
363
|
+
);
|
|
364
|
+
|
|
365
|
+
// 只按 UTF-8 解:GBK/Shift-JIS 之类会乱码,M1 明确不做编码嗅探
|
|
366
|
+
const bodyText = new TextDecoder('utf-8', { fatal: false }).decode(bytes);
|
|
367
|
+
|
|
368
|
+
const isHtml = mime === 'text/html' || mime === 'application/xhtml+xml';
|
|
369
|
+
const extracted = isHtml
|
|
370
|
+
? await extractDocument(bodyText, checked.url, {
|
|
371
|
+
maxLinks: Math.max(config.linksLimit * 4, 40),
|
|
372
|
+
})
|
|
373
|
+
: { text: bodyText, title: '', links: [] };
|
|
374
|
+
|
|
375
|
+
// 截断标记统一(local 与 deepseek 用同一个函数):`…(省略 N 字符)`
|
|
376
|
+
const truncatedText = truncateText(extracted.text, config.maxChars);
|
|
377
|
+
const text = truncatedText.text;
|
|
378
|
+
if (text.trim() === '') {
|
|
379
|
+
throw new WebFetchError(
|
|
380
|
+
'extract_empty',
|
|
381
|
+
'正文为空(可能是纯 JS 渲染页面,M1 不做无头渲染)',
|
|
382
|
+
{
|
|
383
|
+
url: finalUrl,
|
|
384
|
+
status,
|
|
385
|
+
},
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
return {
|
|
390
|
+
ok: true,
|
|
391
|
+
url: finalUrl,
|
|
392
|
+
requested_url: requested,
|
|
393
|
+
status,
|
|
394
|
+
content_type: contentTypeHeader.trim() === '' ? mime : contentTypeHeader.trim(),
|
|
395
|
+
bytes: bytes.byteLength,
|
|
396
|
+
fetched_at: new Date(now()).toISOString(),
|
|
397
|
+
title: extracted.title,
|
|
398
|
+
text,
|
|
399
|
+
truncated: truncatedText.truncated,
|
|
400
|
+
links: filterSameOriginLinks(extracted.links, checked.url, config.linksLimit),
|
|
401
|
+
redirects,
|
|
402
|
+
// 0.56 如实标注(local 每一跳、每个字节都在我们眼里)
|
|
403
|
+
backend: 'local',
|
|
404
|
+
status_source: 'target',
|
|
405
|
+
format: 'text',
|
|
406
|
+
bytes_source: 'http-body',
|
|
407
|
+
links_source: 'backend',
|
|
408
|
+
redirects_known: true,
|
|
409
|
+
robots: config.respectRobots ? 'respected' : 'ignored (config)',
|
|
410
|
+
};
|
|
411
|
+
} finally {
|
|
412
|
+
clearTimeout(timer);
|
|
413
|
+
options.signal?.removeEventListener('abort', onOuterAbort);
|
|
414
|
+
}
|
|
415
|
+
}
|