dsh-fleetseek 0.2.0 → 0.3.1
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 +26 -8
- package/docs/README.md +1 -1
- package/docs/user/README.md +2 -1
- package/docs/user/fetch-takeover.md +64 -0
- package/docs/user/getting-started.md +7 -7
- package/docs/user/troubleshooting.md +14 -14
- package/docs/user/upgrade.md +15 -5
- package/package.json +10 -2
- package/src/backends/bing.js +10 -5
- package/src/backends/exa.js +5 -3
- package/src/client-entry.js +1086 -120
- package/src/client.js +2 -2
- package/src/config.js +281 -17
- package/src/constants.js +149 -1
- package/src/fetch/chain.js +522 -0
- package/src/fetch/official-leg.js +53 -0
- package/src/fetch/provider.js +245 -0
- package/src/fetch/ssrf.js +181 -0
- package/src/host-log.js +132 -0
- package/src/index.js +163 -24
- package/src/official.js +1 -1
- package/src/search.js +648 -69
- package/src/settings/catalog.js +18 -5
- package/src/transport.js +84 -6
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
// #87 fetch 链(FT-002/FT-004/FT-006/FT-008):tavily-extract 提取商按条目降级 + 预算 + 取消 + 回报逐 hop 过闸。
|
|
2
|
+
// 需求来源:docs/specs/draft/fetch-takeover-oracle.md §1/§4/§5 + PR #104 裁决(超时终码 WEB_FETCH_TIMEOUT;
|
|
3
|
+
// 新契约字段族违规=预检抛错,同 #88 PX 修订注所立分叉规则)。
|
|
4
|
+
// 路由/PAC/代理归因复用 src/transport.js createEntryTransport(与搜索链同构:init.route 标记、
|
|
5
|
+
// 子进程 PAC worker、endpointOf 脱敏);本链只负责 key 解析、预算、提取商语义与回报闸。
|
|
6
|
+
// 红线:零真实出站由测试注入面保证(transport 工厂/受控时钟/假凭据);日志与错误只含条目名与脱敏原因。
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import {
|
|
9
|
+
bodyTooLargeMessage,
|
|
10
|
+
carriesPassthroughCode,
|
|
11
|
+
CHAIN_CODES,
|
|
12
|
+
ENTRY_CODES,
|
|
13
|
+
FETCH_CODES,
|
|
14
|
+
FETCH_ENTRY_CODES,
|
|
15
|
+
FETCH_KEY_ENV_BY_TYPE,
|
|
16
|
+
MAX_RESPONSE_BYTES,
|
|
17
|
+
readBoundedText,
|
|
18
|
+
SKIPPED_NO_KEY,
|
|
19
|
+
TRUSTED_ENV_KEYS,
|
|
20
|
+
WEB_CODES,
|
|
21
|
+
} from "../constants.js";
|
|
22
|
+
import { TransportError, createEntryTransport } from "../transport.js";
|
|
23
|
+
import { FetchGateError, gateFetchUrl } from "./ssrf.js";
|
|
24
|
+
|
|
25
|
+
/** 提取商端点(OQ-O3 假定面:results[].url/raw_content/response_code/redirect_hops;fixture 记录于 test/fixtures)。 */
|
|
26
|
+
const TAVILY_EXTRACT_URL = "https://api.tavily.com/extract";
|
|
27
|
+
|
|
28
|
+
/** 条目级失败(链内私有;code 为 ENTRY_*、PAC_*、WEB_* 族之一,reason 已脱敏)。 */
|
|
29
|
+
class EntryFailure extends Error {
|
|
30
|
+
constructor(code, reason, protocol = false) {
|
|
31
|
+
super(reason);
|
|
32
|
+
this.name = "EntryFailure";
|
|
33
|
+
this.code = code;
|
|
34
|
+
if (protocol) this.protocol = true; // P0⑥ 协议违例标记(回报缺最终 URL);终态码族由 runner 裁决
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 终态 WebError(与 search 链 A7 同形:code + details.attempts)。 */
|
|
39
|
+
export class FetchWebError extends Error {
|
|
40
|
+
constructor(code, message, attempts, extra) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.name = "WebError";
|
|
43
|
+
this.code = code;
|
|
44
|
+
this.details = { attempts: attempts.map((a) => ({ ...a })), ...(extra ?? {}) };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function abortError() {
|
|
49
|
+
const err = new Error("fetch 已取消");
|
|
50
|
+
err.name = "AbortError";
|
|
51
|
+
return err;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function isAbort(err, signal) {
|
|
55
|
+
return (
|
|
56
|
+
(typeof signal?.aborted === "boolean" && signal.aborted) ||
|
|
57
|
+
err?.name === "AbortError" ||
|
|
58
|
+
(err instanceof DOMException && err.name === "AbortError")
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function nonblank(v) {
|
|
63
|
+
if (typeof v !== "string") return undefined;
|
|
64
|
+
const t = v.trim();
|
|
65
|
+
return t === "" ? undefined : t;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* CFG-002 fetch 面 key 解析(条目引用 → 环境变量 → 托管引用):
|
|
70
|
+
* - 引用命中 → 带 key;
|
|
71
|
+
* - 引用为受信 env 名(真宿主「引用即环境名」语义)→ env 层,空则无 key 继续(提取商自决 401);
|
|
72
|
+
* - 托管路径引用未命中 → FB-001 跳过零出站(SKIPPED_NO_KEY);
|
|
73
|
+
* - 无引用 → 类型 env 名层 → 托管层 → 无 key 继续。
|
|
74
|
+
* @returns {Promise<{ key: string | null, skip: boolean }>}
|
|
75
|
+
*/
|
|
76
|
+
async function resolveFetchKey(entry, { env, credentials }) {
|
|
77
|
+
const savedRef = entry.credentialRef;
|
|
78
|
+
// 层序(与 config.js resolveEntryApiKey 同口径 + fetch 面 id 命名空间层):
|
|
79
|
+
// ① 条目落盘 credentialRef(write-gate 保证非空);
|
|
80
|
+
// ② 插件命名空间 ref `fleetseek/fetch/<entry.id>`——设置面板为该条目保存 key 的宿主引用
|
|
81
|
+
// (FT-004#3 钉:条目 fe-1 的 key 出自该命名空间;鉴权头只含本条目 key,其他条目零携带);
|
|
82
|
+
// ③ 类型对应受信环境变量(FETCH_KEY_ENV_BY_TYPE);④ 同名 DSH 托管 ref。
|
|
83
|
+
// 超语法值(R-1)视为该层未命中;合法引用读取故障 = 配置错误。
|
|
84
|
+
const refLayers = [savedRef, entry.id ? `fleetseek/fetch/${entry.id}` : undefined].filter(Boolean);
|
|
85
|
+
for (const ref of refLayers) {
|
|
86
|
+
let hit;
|
|
87
|
+
try {
|
|
88
|
+
hit = await credentials.resolve(ref);
|
|
89
|
+
} catch (cause) {
|
|
90
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(ref) || !(cause instanceof TypeError)) {
|
|
91
|
+
const err = new Error(`条目「${entry.name ?? entry.id}」的凭据引用无法读取,请在设置中重新保存该条目的 API key`);
|
|
92
|
+
err.code = "CONFIG_CREDENTIALS_UNREADABLE";
|
|
93
|
+
err.cause = cause;
|
|
94
|
+
throw err;
|
|
95
|
+
}
|
|
96
|
+
hit = undefined;
|
|
97
|
+
}
|
|
98
|
+
const key = nonblank(hit?.value);
|
|
99
|
+
if (key) return { key, skip: false };
|
|
100
|
+
}
|
|
101
|
+
const envNames = [FETCH_KEY_ENV_BY_TYPE[entry.type], savedRef].filter(
|
|
102
|
+
(name) => name && TRUSTED_ENV_KEYS.includes(name),
|
|
103
|
+
);
|
|
104
|
+
for (const name of envNames) {
|
|
105
|
+
const key = nonblank(env?.[name]);
|
|
106
|
+
if (key) return { key, skip: false };
|
|
107
|
+
}
|
|
108
|
+
const envName = FETCH_KEY_ENV_BY_TYPE[entry.type];
|
|
109
|
+
if (envName && typeof credentials?.resolve === "function") {
|
|
110
|
+
let hosted;
|
|
111
|
+
try {
|
|
112
|
+
hosted = await credentials.resolve(envName);
|
|
113
|
+
} catch {
|
|
114
|
+
hosted = undefined;
|
|
115
|
+
}
|
|
116
|
+
const hostedKey = nonblank(hosted?.value);
|
|
117
|
+
if (hostedKey) return { key: hostedKey, skip: false };
|
|
118
|
+
}
|
|
119
|
+
// 全层 miss:落盘 ref 为受信环境变量名 = 免 key 形态(keyless 放行,FT-002#5);
|
|
120
|
+
// 否则 = 该条目缺 key → SKIPPED_NO_KEY(零出站,FB-001 / FT-006#11)。
|
|
121
|
+
if (savedRef && TRUSTED_ENV_KEYS.includes(savedRef)) return { key: null, skip: false };
|
|
122
|
+
return { key: null, skip: true };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// P0-2(sol-87 实锤):删除「字符串面缩水版」回报闸——原 gateReportedUrl 只判字面段与形态、
|
|
126
|
+
// 不做 dns:原请求 public.example 过闸、提取商回报 private.example(DNS 注入/重绑定)时本地
|
|
127
|
+
// 兜底腿照拨(LEAK-MARKER 原样入结果)。现回报 hop/终址与直连跳**共用同一全闸**
|
|
128
|
+
// gateFetchUrl({dns})(含 resolver/私网/环回全量,零豁免),见 attemptEntry 的 R 链段。
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* 受控时钟竞速:perEntry 毫秒到点即以 ENTRY_TIMEOUT 落定;signal 中止即 AbortError。
|
|
132
|
+
* P0-1(sol-87 实锤):超时到点必须同步经 onTimeout 中止本条目的 AbortController——
|
|
133
|
+
* 只 reject 不 abort 会让慢 credentials.resolve / DNS 的 continuation 在终态后仍 transport.open+POST
|
|
134
|
+
* (带 key 与 URL 的迟到拨号,FT-002/FB-003「超时后零新出站」红线违例)。
|
|
135
|
+
*/
|
|
136
|
+
function raceEntry(promise, perEntry, clock, signal, onTimeout) {
|
|
137
|
+
if (signal?.aborted) {
|
|
138
|
+
promise.catch(() => {});
|
|
139
|
+
return Promise.reject(abortError());
|
|
140
|
+
}
|
|
141
|
+
if (typeof clock?.setTimeout !== "function" || perEntry <= 0) return promise;
|
|
142
|
+
return new Promise((resolve, reject) => {
|
|
143
|
+
let settled = false;
|
|
144
|
+
let timer = null;
|
|
145
|
+
const onAbort = () => {
|
|
146
|
+
if (settled) return;
|
|
147
|
+
settled = true;
|
|
148
|
+
if (timer) clock.clearTimeout(timer);
|
|
149
|
+
signal?.removeEventListener("abort", onAbort);
|
|
150
|
+
reject(abortError());
|
|
151
|
+
};
|
|
152
|
+
const done = (fn) => (value) => {
|
|
153
|
+
if (settled) return;
|
|
154
|
+
settled = true;
|
|
155
|
+
if (timer) clock.clearTimeout(timer);
|
|
156
|
+
signal?.removeEventListener("abort", onAbort);
|
|
157
|
+
fn(value);
|
|
158
|
+
};
|
|
159
|
+
if (signal) signal.addEventListener("abort", onAbort, { once: true });
|
|
160
|
+
timer = clock.setTimeout(() => {
|
|
161
|
+
if (settled) return;
|
|
162
|
+
settled = true;
|
|
163
|
+
signal?.removeEventListener("abort", onAbort);
|
|
164
|
+
onTimeout?.(); // P0-1:超时即 abort 条目控制器(见 run 的 attemptCtl 装配)
|
|
165
|
+
reject(new EntryFailure(ENTRY_CODES.TIMEOUT, "条目请求超时(预算内未响应)"));
|
|
166
|
+
}, perEntry);
|
|
167
|
+
promise.then(
|
|
168
|
+
done(resolve),
|
|
169
|
+
done(reject),
|
|
170
|
+
);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function makeEmit(log) {
|
|
175
|
+
return (level, message, extra) => {
|
|
176
|
+
try {
|
|
177
|
+
if (typeof log === "function") log(level, message, extra);
|
|
178
|
+
else if (log && typeof log.log === "function") log.log(level, message, extra);
|
|
179
|
+
} catch {
|
|
180
|
+
// 日志失败不阻链
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* 创建 fetch 链。deps = { transport, clock, log?, env, credentials, dns?, spawnProcess?, officialFetchProvider? }
|
|
187
|
+
* (D1 注入面:transport 工厂 open(entry, opts) → handle.{fetch, close};测试注入面与生产同形)。
|
|
188
|
+
* @returns {{ run: (req) => Promise<{ vendorStatus, item }>, release: () => void }}
|
|
189
|
+
*/
|
|
190
|
+
export function createFetchChain(deps) {
|
|
191
|
+
const { transport, clock, env = {}, credentials, dns, spawnProcess = spawn } = deps;
|
|
192
|
+
if (typeof transport?.open !== "function") throw new TypeError("createFetchChain 需要注入 transport 工厂");
|
|
193
|
+
const emit = makeEmit(deps.log);
|
|
194
|
+
const now = () => (typeof clock?.now === "function" ? clock.now() : Date.now());
|
|
195
|
+
let released = false;
|
|
196
|
+
const openHandles = new Set();
|
|
197
|
+
const closeOpenHandles = () => {
|
|
198
|
+
for (const h of [...openHandles]) {
|
|
199
|
+
try {
|
|
200
|
+
h.close();
|
|
201
|
+
} catch {}
|
|
202
|
+
openHandles.delete(h);
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
// P0-1 三源统一 abort 面:每 attempt 一个 AbortController,注册于此;release() 时统一中止
|
|
206
|
+
// (释放也是取消源之一——在途慢 continuation 不得在释放后迟到拨号)。
|
|
207
|
+
const activeCtls = new Set();
|
|
208
|
+
const abortActiveAttempts = () => {
|
|
209
|
+
for (const c of [...activeCtls]) {
|
|
210
|
+
try {
|
|
211
|
+
c.abort();
|
|
212
|
+
} catch {}
|
|
213
|
+
activeCtls.delete(c);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* P0-1 教训级注释(sol-87 实锤):**每个 await 即检查点**——任何 pending continuation(慢
|
|
219
|
+
* credentials.resolve / DNS 预解析 / 供应商响应 / 回报闸 dns)在终态后落定时,恢复处必须先重验
|
|
220
|
+
* signal.aborted 与剩余预算,才允许继续到下一次同步出站(拨号)。abort 事件与 continuation 的
|
|
221
|
+
* 竞态同样在此拦截(abort 已置位但 continuation 尚未恢复的窗口)。
|
|
222
|
+
*/
|
|
223
|
+
const ensureLive = (sig, deadlineMs) => {
|
|
224
|
+
if (sig?.aborted) throw abortError();
|
|
225
|
+
if (typeof deadlineMs === "number" && Number.isFinite(deadlineMs) && now() >= deadlineMs) {
|
|
226
|
+
throw new EntryFailure(ENTRY_CODES.TIMEOUT, "条目预算耗尽(含凭据/闸门 await 面)");
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
async function attemptEntry(entry, { url, signal, enabledLeft, attempts, budgetMs, deadline }) {
|
|
231
|
+
// P0-7(sol-87 实锤):条目 URL 政策裁决**先于** key 遍历——原序 key-skip 先于闸,无 key 时
|
|
232
|
+
// 10.0.0.1 竟以「缺 key 跳过」绕过闸、终态无 gateStage 旗标 → 兜底腿真实拨号(私网 SSRF 实开)。
|
|
233
|
+
// 现无论有无 key 都先过政策闸;条目级拒绝零出站。loopback 族(环回/localhost)允许官方腿兜底
|
|
234
|
+
// (官方腿环回豁免),私网族/dns 命中 = 政策拒绝不兜底(G 闸红线:官方腿真实 DNS 不受本机控制)。
|
|
235
|
+
try {
|
|
236
|
+
await gateFetchUrl(url, { dns });
|
|
237
|
+
} catch (err) {
|
|
238
|
+
if (!(err instanceof FetchGateError)) throw err;
|
|
239
|
+
attempts.push({ id: entry.id, code: FETCH_ENTRY_CODES.BLOCKED_URL, reason: err.message });
|
|
240
|
+
return {
|
|
241
|
+
failed: err.code,
|
|
242
|
+
gateBlocked: true,
|
|
243
|
+
reason: err.message,
|
|
244
|
+
gateSource: err.details?.source,
|
|
245
|
+
gateWord: err.details?.word,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
ensureLive(signal, deadline); // P0-1 检查点(闸门 await 后)
|
|
249
|
+
let keyInfo;
|
|
250
|
+
try {
|
|
251
|
+
keyInfo = await resolveFetchKey(entry, { env, credentials });
|
|
252
|
+
} catch (err) {
|
|
253
|
+
throw err; // 配置错误(凭据服务故障)直通上抛,非条目级降级
|
|
254
|
+
}
|
|
255
|
+
ensureLive(signal, deadline); // P0-1 检查点(凭据 await 后)
|
|
256
|
+
if (keyInfo.skip) {
|
|
257
|
+
attempts.push({ id: entry.id, code: SKIPPED_NO_KEY, reason: "条目 key 未解析(引用未命中,零出站跳过)" });
|
|
258
|
+
return "skipped";
|
|
259
|
+
}
|
|
260
|
+
const headers = { "content-type": "application/json" };
|
|
261
|
+
if (keyInfo.key) headers.authorization = `Bearer ${keyInfo.key}`;
|
|
262
|
+
let handle;
|
|
263
|
+
let t;
|
|
264
|
+
try {
|
|
265
|
+
ensureLive(signal, deadline); // P0-1 拨号前同步双校验(与拨号间无 await,拦截 abort/continuation 竞态窗口)
|
|
266
|
+
handle = transport.open(entry, { url, budgetMs });
|
|
267
|
+
openHandles.add(handle);
|
|
268
|
+
t = createEntryTransport(entry, {
|
|
269
|
+
fetch: handle.fetch,
|
|
270
|
+
clock,
|
|
271
|
+
log: (level, message) => emit(level, message),
|
|
272
|
+
spawnProcess,
|
|
273
|
+
});
|
|
274
|
+
const body = JSON.stringify({ urls: [url] });
|
|
275
|
+
// 预算竞速由 run() 层统一包裹(含 key 解析面);此处不再二次竞速。
|
|
276
|
+
const resp = await t.fetch(TAVILY_EXTRACT_URL, { method: "POST", headers, body, signal });
|
|
277
|
+
if (isAbort(resp, signal)) throw abortError();
|
|
278
|
+
const status = resp?.status;
|
|
279
|
+
if (status === 401) throw new EntryFailure(ENTRY_CODES.CREDENTIALS, "提取商鉴权失败(HTTP 401)");
|
|
280
|
+
if (status === 429) throw new EntryFailure(ENTRY_CODES.RATE_LIMITED, "提取商限流(HTTP 429)");
|
|
281
|
+
if (typeof status !== "number" || status < 200 || status >= 300) {
|
|
282
|
+
throw new EntryFailure(
|
|
283
|
+
typeof status === "number" && status >= 500 ? ENTRY_CODES.NETWORK : ENTRY_CODES.BAD_RESPONSE,
|
|
284
|
+
`提取商异常响应(HTTP ${typeof status === "number" ? status : "未知"})`,
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
const bounded = await readBoundedText(resp, { maxBytes: MAX_RESPONSE_BYTES });
|
|
288
|
+
if (bounded.tooLarge) throw new EntryFailure(ENTRY_CODES.BAD_RESPONSE, bodyTooLargeMessage(bounded.limit));
|
|
289
|
+
let parsed;
|
|
290
|
+
try {
|
|
291
|
+
parsed = JSON.parse(bounded.text);
|
|
292
|
+
} catch {
|
|
293
|
+
throw new EntryFailure(ENTRY_CODES.BAD_RESPONSE, "提取商响应不是合法 JSON");
|
|
294
|
+
}
|
|
295
|
+
const item = Array.isArray(parsed?.results) ? parsed.results[0] : undefined;
|
|
296
|
+
if (item === undefined || item === null || typeof item !== "object") {
|
|
297
|
+
throw new EntryFailure(ENTRY_CODES.BAD_RESPONSE, "提取商响应缺少 results 条目");
|
|
298
|
+
}
|
|
299
|
+
// FT-005 R 链 + P0-2(sol-87 实锤):回报逐 hop + 终址**共用与直连跳同一全闸** gateFetchUrl({dns})
|
|
300
|
+
//(含 resolver/私网/环回/组播/形态全量,零豁免,预算/取消内)——「回报」的 URL 一律视同不可信输入:
|
|
301
|
+
// 原请求 public.example 过闸、回报 private.example(DNS 注入/重绑定)时在此拒绝,正文零透传、
|
|
302
|
+
// 本地兜底腿零拨号。非法回报 fail-closed(解析失败/非 http(s) 亦拒,不再按脏数据透传)。
|
|
303
|
+
// P0⑥(sol-87b 终局裁):最终 URL 为协议必备字段——响应项缺最终 URL = 协议违例直接拒
|
|
304
|
+
//(禁变空 finals、provider 侧禁 reqUrl 顶替);空串/非法形态由下方回报闸同拒
|
|
305
|
+
//(WEB_INVALID_URL,正文零透传)。FT-005/009:首期必须回报最终 URL,内容真实来源
|
|
306
|
+
// 未审即入违例(untrusted-input 原则;「真实供应商未必返回该形态」的诚实注记保留在 PR 备案,
|
|
307
|
+
// 防御纵深按不可信输入原则)。
|
|
308
|
+
if (typeof item.url !== "string" || item.url.trim() === "") {
|
|
309
|
+
throw new EntryFailure(ENTRY_CODES.BAD_RESPONSE, "提取商响应缺少最终 URL(协议违例)", true);
|
|
310
|
+
}
|
|
311
|
+
const hops = Array.isArray(item.redirect_hops) ? item.redirect_hops.filter((h) => typeof h === "string") : [];
|
|
312
|
+
const finals = [item.url];
|
|
313
|
+
for (const h of [...hops, ...finals]) {
|
|
314
|
+
ensureLive(signal, deadline); // P0-1 检查点(每 hop 闸 await 前)
|
|
315
|
+
await gateFetchUrl(h, { dns });
|
|
316
|
+
}
|
|
317
|
+
return { vendorStatus: status, item };
|
|
318
|
+
} catch (err) {
|
|
319
|
+
if (isAbort(err, signal)) return { __aborted: true };
|
|
320
|
+
let code;
|
|
321
|
+
let reason;
|
|
322
|
+
if (err instanceof EntryFailure) {
|
|
323
|
+
code = err.code;
|
|
324
|
+
reason = err.message;
|
|
325
|
+
} else if (err instanceof FetchGateError) {
|
|
326
|
+
code = err.code;
|
|
327
|
+
reason = err.message;
|
|
328
|
+
} else if (err instanceof TransportError || carriesPassthroughCode(err)) {
|
|
329
|
+
code = err.code;
|
|
330
|
+
reason = err.message;
|
|
331
|
+
} else if (err?.name === "AbortError") {
|
|
332
|
+
return { __aborted: true };
|
|
333
|
+
} else {
|
|
334
|
+
code = entry.proxy ? ENTRY_CODES.PROXY : ENTRY_CODES.NETWORK;
|
|
335
|
+
reason = "条目请求失败(网络或响应异常)";
|
|
336
|
+
}
|
|
337
|
+
attempts.push({
|
|
338
|
+
id: entry.id,
|
|
339
|
+
code,
|
|
340
|
+
reason,
|
|
341
|
+
...(err instanceof EntryFailure && err.protocol === true ? { protocol: true } : {}),
|
|
342
|
+
});
|
|
343
|
+
return { failed: code };
|
|
344
|
+
} finally {
|
|
345
|
+
openHandles.delete(handle);
|
|
346
|
+
try {
|
|
347
|
+
t?.close();
|
|
348
|
+
} catch {}
|
|
349
|
+
try {
|
|
350
|
+
handle?.close();
|
|
351
|
+
} catch {}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function run({ url, entries, budgetMs, deadline, signal }) {
|
|
356
|
+
if (released) throw new FetchWebError(CHAIN_CODES.NOT_CONFIGURED, "fetch 已释放,提取路径不可用", []);
|
|
357
|
+
if (signal?.aborted) throw new FetchWebError(WEB_CODES.ABORTED, "fetch 已取消", []);
|
|
358
|
+
const enabled = entries.filter((e) => e.enabled !== false);
|
|
359
|
+
if (enabled.length === 0) {
|
|
360
|
+
throw new FetchWebError(CHAIN_CODES.NOT_CONFIGURED, "未配置可用提取商:列表为空或全部条目已停用", []);
|
|
361
|
+
}
|
|
362
|
+
// deadline 绝对窗口(provider 在首个 await 前捕获起点,FT-002#7 钉);缺省 = 本调用起算 budgetMs。
|
|
363
|
+
const totalDeadline = typeof deadline === "number" && Number.isFinite(deadline) ? deadline : now() + budgetMs;
|
|
364
|
+
const attempts = [];
|
|
365
|
+
let aborted = false;
|
|
366
|
+
let gateBlock = null; // 条目级闸拒绝现场({reason, source, word})
|
|
367
|
+
|
|
368
|
+
for (let i = 0; i < enabled.length; i += 1) {
|
|
369
|
+
if (signal?.aborted) {
|
|
370
|
+
aborted = true;
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
const entry = enabled[i];
|
|
374
|
+
const enabledLeft = enabled.length - i;
|
|
375
|
+
const remaining = totalDeadline - now();
|
|
376
|
+
const perEntry = Math.floor(remaining / enabledLeft);
|
|
377
|
+
if (perEntry <= 0) break; // FB-003:无可用时间不得发出请求
|
|
378
|
+
emit("debug", "fetch 尝试条目", { entryId: entry.id, type: entry.type });
|
|
379
|
+
// 条目全程(key 解析 + PAC 求值 + 供应商请求 + 回报闸)纳入预算竞速:
|
|
380
|
+
// 异步凭据读悬挂不占死链(#88 教训:resolve 悬挂须在预算/取消内竞速,勿裸 await)。
|
|
381
|
+
// P0-1 三源统一 abort(超时 / 宿主取消 / release):每 attempt 一个 AbortController;
|
|
382
|
+
// attemptEntry 收到的是本 attempt 的 signal(宿主取消经下方监听器传导),raceEntry 超时经
|
|
383
|
+
// onTimeout 同步 abort 本控制器——慢 continuation 恢复处必见 signal.aborted=true,迟到拨号被拦。
|
|
384
|
+
const attemptCtl = new AbortController();
|
|
385
|
+
activeCtls.add(attemptCtl);
|
|
386
|
+
const onHostAbort = () => attemptCtl.abort(signal?.reason);
|
|
387
|
+
if (signal) {
|
|
388
|
+
if (signal.aborted) attemptCtl.abort(signal.reason);
|
|
389
|
+
else signal.addEventListener("abort", onHostAbort, { once: true });
|
|
390
|
+
}
|
|
391
|
+
let outcome;
|
|
392
|
+
let raceErr = null;
|
|
393
|
+
try {
|
|
394
|
+
outcome = await raceEntry(
|
|
395
|
+
attemptEntry(entry, {
|
|
396
|
+
url,
|
|
397
|
+
signal: attemptCtl.signal,
|
|
398
|
+
enabledLeft,
|
|
399
|
+
attempts,
|
|
400
|
+
budgetMs: perEntry * enabledLeft,
|
|
401
|
+
deadline: totalDeadline,
|
|
402
|
+
}),
|
|
403
|
+
perEntry,
|
|
404
|
+
clock,
|
|
405
|
+
attemptCtl.signal,
|
|
406
|
+
() => attemptCtl.abort(new Error("fetch 条目预算到期")),
|
|
407
|
+
);
|
|
408
|
+
} catch (e) {
|
|
409
|
+
raceErr = e;
|
|
410
|
+
} finally {
|
|
411
|
+
activeCtls.delete(attemptCtl);
|
|
412
|
+
if (signal) signal.removeEventListener("abort", onHostAbort);
|
|
413
|
+
}
|
|
414
|
+
if (raceErr) {
|
|
415
|
+
if (raceErr.name === "AbortError" || signal?.aborted) {
|
|
416
|
+
aborted = true;
|
|
417
|
+
attempts.push({ id: entry.id, code: WEB_CODES.ABORTED, reason: "宿主取消" });
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
if (raceErr.code === ENTRY_CODES.TIMEOUT) {
|
|
421
|
+
attempts.push({ id: entry.id, code: ENTRY_CODES.TIMEOUT, reason: "条目预算内未完成(含凭据解析)" });
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
throw raceErr; // 配置错误(CONFIG_CREDENTIALS_UNREADABLE 等)直通
|
|
425
|
+
}
|
|
426
|
+
if (outcome === "skipped") continue;
|
|
427
|
+
if (outcome && outcome.__aborted) {
|
|
428
|
+
aborted = true;
|
|
429
|
+
attempts.push({ id: entry.id, code: WEB_CODES.ABORTED, reason: "宿主取消" });
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
if (outcome && outcome.vendorStatus !== undefined) {
|
|
433
|
+
emit("debug", "fetch 条目命中", { entryId: entry.id, type: entry.type });
|
|
434
|
+
return outcome;
|
|
435
|
+
}
|
|
436
|
+
if (outcome && outcome.gateBlocked) {
|
|
437
|
+
// 条目级预供应商闸拒绝:目标对所有条目同一,不再尝试后续条目(零出站已保证)。
|
|
438
|
+
gateBlock = { reason: outcome.reason, source: outcome.gateSource, word: outcome.gateWord };
|
|
439
|
+
break;
|
|
440
|
+
}
|
|
441
|
+
if (outcome && outcome.failed === WEB_CODES.BLOCKED_URL) {
|
|
442
|
+
// 政策拒绝终态(回报闸命中):不再降级,直接终态(FT-005 R 链:正文零透传、零兜底)。
|
|
443
|
+
break;
|
|
444
|
+
}
|
|
445
|
+
if (signal?.aborted) {
|
|
446
|
+
aborted = true;
|
|
447
|
+
break;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
closeOpenHandles(); // 终态后清理滞留句柄(挂起条目:悬挂 fetch 永不落定时 close 兜底,防泄漏钉)
|
|
452
|
+
if (aborted) throw new FetchWebError(WEB_CODES.ABORTED, "fetch 已取消", attempts);
|
|
453
|
+
if (now() >= totalDeadline - 1 && attempts.length === 0) {
|
|
454
|
+
// 预算窗口在首条尝试前即耗尽(provider 预闸微任务 + 宿主拨钟):零尝试亦是超时终态(FT-002#7)。
|
|
455
|
+
throw new FetchWebError(
|
|
456
|
+
WEB_CODES.FETCH_TIMEOUT,
|
|
457
|
+
`总预算 ${budgetMs}ms 已耗尽且未获得有效来源(见 details.attempts 的逐条原因)`,
|
|
458
|
+
attempts,
|
|
459
|
+
);
|
|
460
|
+
}
|
|
461
|
+
if (gateBlock) {
|
|
462
|
+
// 条目级预供应商闸拒绝:码 = WEB_BLOCKED_URL(宿主契约),gateStage/source/word 供 provider
|
|
463
|
+
// 兜底裁决(loopback 字面族允许官方腿;私网族/dns 命中不兜底)。
|
|
464
|
+
throw new FetchWebError(WEB_CODES.BLOCKED_URL, gateBlock.reason, attempts, {
|
|
465
|
+
gateStage: "entry",
|
|
466
|
+
source: gateBlock.source,
|
|
467
|
+
word: gateBlock.word,
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
if (attempts.some((a) => a.code === WEB_CODES.BLOCKED_URL || a.code === WEB_CODES.INVALID_URL)) {
|
|
471
|
+
const culprit = attempts.find((a) => a.code === WEB_CODES.BLOCKED_URL || a.code === WEB_CODES.INVALID_URL);
|
|
472
|
+
throw new FetchWebError(
|
|
473
|
+
culprit.code,
|
|
474
|
+
`提取商回报未通过 URL 闸:${culprit.reason}(见 details.attempts 的逐条原因)`,
|
|
475
|
+
attempts,
|
|
476
|
+
{ gateStage: "reported" },
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
if (attempts.some((a) => a.protocol === true)) {
|
|
480
|
+
// P0⑥:回报缺最终 URL = 协议违例 → 终态直接拒(WEB_PROVIDER_ERROR 族、脱敏——
|
|
481
|
+
// reason 零内容回带);官方兜底腿不能替代提取商回报终址的契约责任
|
|
482
|
+
//(gateStage: "protocol" 供 provider 兜底裁决 = 不兜底)。
|
|
483
|
+
const culprit = attempts.find((a) => a.protocol === true);
|
|
484
|
+
throw new FetchWebError(
|
|
485
|
+
WEB_CODES.PROVIDER_ERROR,
|
|
486
|
+
`${culprit.reason}(见 details.attempts 的逐条原因)`,
|
|
487
|
+
attempts,
|
|
488
|
+
{ gateStage: "protocol" },
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
const anyRealFailure = attempts.some((a) => a.code !== SKIPPED_NO_KEY);
|
|
492
|
+
if (!anyRealFailure) {
|
|
493
|
+
throw new FetchWebError(FETCH_CODES.KEY_MISSING, "fetch 条目均未解析到 key(见 details.attempts)", attempts);
|
|
494
|
+
}
|
|
495
|
+
const timedOut = attempts.some((a) => a.code === ENTRY_CODES.TIMEOUT);
|
|
496
|
+
const budgetExhausted = now() >= totalDeadline - 1;
|
|
497
|
+
if (timedOut && budgetExhausted && attempts.every((a) => a.code === ENTRY_CODES.TIMEOUT || a.code === SKIPPED_NO_KEY)) {
|
|
498
|
+
// PR #104 OQ-O4 裁决:总预算超时唯一终码 = WEB_FETCH_TIMEOUT。
|
|
499
|
+
throw new FetchWebError(
|
|
500
|
+
WEB_CODES.FETCH_TIMEOUT,
|
|
501
|
+
`总预算 ${budgetMs}ms 已耗尽且未获得有效来源(见 details.attempts 的逐条原因)`,
|
|
502
|
+
attempts,
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
throw new FetchWebError(
|
|
506
|
+
CHAIN_CODES.UPSTREAM_FAILURES,
|
|
507
|
+
"全部提取路径未获得有效来源:尝试过的条目均失败或被跳过(见 details.attempts 的逐条原因)",
|
|
508
|
+
attempts,
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
return {
|
|
513
|
+
run,
|
|
514
|
+
release() {
|
|
515
|
+
released = true;
|
|
516
|
+
abortActiveAttempts(); // P0-1:release 是取消源之一——中止在途 attempt,防释放后迟到拨号
|
|
517
|
+
closeOpenHandles();
|
|
518
|
+
},
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export { gateFetchUrl, FetchGateError };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// #87 官方兜底腿(D-FT3,Refs #87)。
|
|
2
|
+
// lead PR #104 评论#3 批准形态:以精确版本 dependency 安装宿主发布线同包的官方 provider,
|
|
3
|
+
// 兜底腿 = 构造宿主公开类 HttpFetchProvider(@deepseek-ai/dsh-web-fetch-http 0.0.1-rc.5),
|
|
4
|
+
// 限额/同源重定向/UA/正文限界/超时语义全部随宿主类——本文件只剩薄包装:
|
|
5
|
+
// - 超时取剩余 FB-003 预算(每次调用以剩余毫秒构造 limits.timeoutMs,官方默认 30s 为上限);
|
|
6
|
+
// - 宿主取消 signal 透传(宿主类经 deadline 组合外部 signal);
|
|
7
|
+
// - 宿主类 WebError 统一转 OfficialLegError(码直通;含 URL 形态的文案退化为短文本——
|
|
8
|
+
// 泄漏红线:官方类个别文案携带 URL 原文,包装层一律不并入)。
|
|
9
|
+
// key 零渲染零日志:腿不接触凭据(鉴权只发生在链侧条目头)。
|
|
10
|
+
import { HttpFetchProvider } from "@deepseek-ai/dsh-web-fetch-http";
|
|
11
|
+
import { WEB_CODES } from "../constants.js";
|
|
12
|
+
|
|
13
|
+
/** 官方限额(宿主类 Config 缺省值:2048/5e6/1e5/3e4/5 + 产品 UA 缺省)。 */
|
|
14
|
+
const OFFICIAL_LIMITS = Object.freeze({
|
|
15
|
+
maxUrlLength: 2048,
|
|
16
|
+
maxResponseBytes: 5_000_000,
|
|
17
|
+
maxBodyChars: 100_000,
|
|
18
|
+
timeoutMs: 30_000,
|
|
19
|
+
maxRedirects: 5,
|
|
20
|
+
userAgent: "deepseek-harness/0.0.1 (+https://github.com/deepseek-ai)",
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
export class OfficialLegError extends Error {
|
|
24
|
+
constructor(code, message) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = "WebError";
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.details = { attempts: [] };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 执行一次官方腿抓取(宿主 HttpFetchProvider 公开类,D-FT3 复用不复刻)。
|
|
34
|
+
* @param {string} url
|
|
35
|
+
* @param {{ timeoutMs?: number, signal?: AbortSignal }} [opts]
|
|
36
|
+
* @returns {Promise<{url:string,statusCode:number,body:{kind:string,content:string},truncated:boolean}>}
|
|
37
|
+
*/
|
|
38
|
+
export async function officialFetch(url, { timeoutMs, signal } = {}) {
|
|
39
|
+
// FB-003 预算联动:腿超时 = 当时剩余预算(封顶官方 30s 缺省;下限 1ms,Node 定时器口径)。
|
|
40
|
+
const clamped = Math.max(1, Math.min(OFFICIAL_LIMITS.timeoutMs, Number.isFinite(timeoutMs) ? timeoutMs : OFFICIAL_LIMITS.timeoutMs));
|
|
41
|
+
const provider = new HttpFetchProvider({ ...OFFICIAL_LIMITS, timeoutMs: clamped });
|
|
42
|
+
try {
|
|
43
|
+
// statusCode 为结果非异常(官方同形):网络失败/超时/取消/形态政策由宿主类抛 WebError 带码。
|
|
44
|
+
return await provider.fetch({ url }, signal);
|
|
45
|
+
} catch (err) {
|
|
46
|
+
const hostCode = typeof err?.code === "string" ? err.code : WEB_CODES.PROVIDER_ERROR;
|
|
47
|
+
// 泄漏红线:宿主类个别文案含 URL 原文(invalid URL: … / cross-origin redirect to … origin)——
|
|
48
|
+
// 含 URL 形态的消息一律退化为短文本;key 面不受影响(腿不接触凭据)。
|
|
49
|
+
const raw = String(err?.message ?? err);
|
|
50
|
+
const safe = /https?:\/\//i.test(raw) ? "web fetch failed" : raw.slice(0, 200);
|
|
51
|
+
throw new OfficialLegError(hostCode, safe);
|
|
52
|
+
}
|
|
53
|
+
}
|