dsh-fleetseek 0.2.0 → 0.3.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.
Potentially problematic release.
This version of dsh-fleetseek might be problematic. Click here for more details.
- package/README.md +27 -9
- 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 +8 -8
- package/docs/user/troubleshooting.md +17 -15
- package/docs/user/upgrade.md +21 -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 +1200 -120
- package/src/client.js +2 -2
- package/src/config.js +287 -17
- package/src/constants.js +158 -1
- package/src/fetch/chain.js +525 -0
- package/src/fetch/official-leg.js +53 -0
- package/src/fetch/provider.js +253 -0
- package/src/fetch/ssrf.js +181 -0
- package/src/host-log.js +132 -0
- package/src/index.js +189 -24
- package/src/official.js +1 -1
- package/src/search.js +663 -69
- package/src/settings/catalog.js +18 -5
- package/src/transport.js +97 -7
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// #87 fetch 提供方(D1 注入装配层 → 宿主 WebFetchProvider 接缝)。
|
|
2
|
+
// id=search-chain(FT-001#1 钉);available() 同步只读 live 开关(FT-003#5/6 选择语义);
|
|
3
|
+
// fetch(req, signal) = 预闸(FT-005 R 链)→ fetch 链(FT-002/004/006/008)→ 官方兜底腿(lead 裁决:
|
|
4
|
+
// 链侧网络/失败类终态 + fetchOfficialFallback=true → 官方 http 腿重试原始 URL;政策拒绝族不兜底)。
|
|
5
|
+
// 官方腿测试面:注入 officialFetchProvider(同形 WebFetchProvider);生产缺省 = 宿主公开类
|
|
6
|
+
// HttpFetchProvider 薄包装(official-leg.js,D-FT3 精确版本 dependency——lead PR #104 评论#3 批准;
|
|
7
|
+
// 限额/同源跳转/UA/超时语义随宿主类,腿超时取剩余 FB-003 预算)。
|
|
8
|
+
import {
|
|
9
|
+
CHAIN_CODES,
|
|
10
|
+
FETCH_CODES,
|
|
11
|
+
FETCH_MAX_BODY_CHARS,
|
|
12
|
+
WEB_CODES,
|
|
13
|
+
} from "../constants.js";
|
|
14
|
+
import { createFetchChain, FetchWebError } from "./chain.js";
|
|
15
|
+
import { GATE_CATEGORY, gateFetchUrl, FetchGateError } from "./ssrf.js";
|
|
16
|
+
import { officialFetch } from "./official-leg.js";
|
|
17
|
+
|
|
18
|
+
function nonblank(v) {
|
|
19
|
+
if (typeof v !== "string") return undefined;
|
|
20
|
+
const t = v.trim();
|
|
21
|
+
return t === "" ? undefined : t;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 把提取商回报映射为宿主 WebFetchResult(FT-008:kind 恒 text、url=回报终址、100k 截断)。
|
|
25
|
+
* P0⑥(sol-87b 终局裁):url 只取回报终址——禁止以请求 URL 顶替;缺/空(不可达:链侧协议闸
|
|
26
|
+
* 已拒)亦拒不顶(防御纵深,untrusted-input 原则;见 chain.js 回报段注释)。 */
|
|
27
|
+
function toWebFetchResult({ vendorStatus, item }) {
|
|
28
|
+
const url = nonblank(item.url);
|
|
29
|
+
if (url === undefined) {
|
|
30
|
+
throw new FetchGateError(WEB_CODES.PROVIDER_ERROR, "提取商响应缺少最终 URL(协议违例)");
|
|
31
|
+
}
|
|
32
|
+
const statusCode =
|
|
33
|
+
typeof item.response_code === "number" && Number.isFinite(item.response_code)
|
|
34
|
+
? item.response_code
|
|
35
|
+
: vendorStatus;
|
|
36
|
+
const content = typeof item.raw_content === "string" ? item.raw_content : "";
|
|
37
|
+
const truncated = content.length > FETCH_MAX_BODY_CHARS;
|
|
38
|
+
return {
|
|
39
|
+
url,
|
|
40
|
+
statusCode,
|
|
41
|
+
body: { kind: "text", content: truncated ? content.slice(0, FETCH_MAX_BODY_CHARS) : content },
|
|
42
|
+
truncated,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {object} deps
|
|
48
|
+
* @param {() => boolean} deps.getSwitch live 开关 raw 读(不经 normalizeConfig:FT-002 钉——
|
|
49
|
+
* 非法 fetch 条目配置下 available() 仍为 true,fetch 时才以 CONFIG_INVALID 字符串码终态)
|
|
50
|
+
* @param {() => object} deps.getConfig live 配置规范化快照(含 fetchTakeover/fetchEntries/fetchOfficialFallback/timeoutMs)
|
|
51
|
+
* @param {object} deps.fetchDeps D1 注入面:{ transport, clock, credentials, env, log?, dns?, officialFetchProvider?, spawnProcess? }
|
|
52
|
+
* @returns {{ provider: WebFetchProvider }}
|
|
53
|
+
*/
|
|
54
|
+
export function createFetchProvider({ getSwitch, getConfig, fetchDeps }) {
|
|
55
|
+
const chain = createFetchChain(fetchDeps);
|
|
56
|
+
const emit = makeEmit(fetchDeps.log);
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 官方兜底腿(timeoutMs=当下剩余预算,PR #104 预算窗口钉)。
|
|
60
|
+
* 注入优先(deps.fetchDeps.officialFetchProvider,OQ-O1..O8 注入面);缺省 = 宿主公开类
|
|
61
|
+
* HttpFetchProvider 薄包装(src/fetch/official-leg.js,D-FT3 复用不复刻)。
|
|
62
|
+
*/
|
|
63
|
+
async function officialLeg(url, remainingMs, signal) {
|
|
64
|
+
if (fetchDeps.officialFetchProvider) {
|
|
65
|
+
return fetchDeps.officialFetchProvider.fetch({ url }, signal);
|
|
66
|
+
}
|
|
67
|
+
return officialFetch(url, { timeoutMs: remainingMs, signal });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function fetch(req, signal) {
|
|
71
|
+
if (signal?.aborted) {
|
|
72
|
+
throw new FetchGateError(WEB_CODES.ABORTED, "web fetch 已取消");
|
|
73
|
+
}
|
|
74
|
+
const cfg = getConfig();
|
|
75
|
+
if (cfg?.fetchTakeover !== true) {
|
|
76
|
+
throw new FetchGateError(CHAIN_CODES.NOT_CONFIGURED, "fetch 接管未开启(fetchTakeover=false)");
|
|
77
|
+
}
|
|
78
|
+
const url = req?.url;
|
|
79
|
+
if (typeof url !== "string" || url.trim() === "") {
|
|
80
|
+
throw new FetchGateError(WEB_CODES.INVALID_URL, "URL 为空");
|
|
81
|
+
}
|
|
82
|
+
const budgetMs =
|
|
83
|
+
typeof cfg.timeoutMs === "number" && Number.isFinite(cfg.timeoutMs) && cfg.timeoutMs > 0
|
|
84
|
+
? cfg.timeoutMs
|
|
85
|
+
: 25_000;
|
|
86
|
+
const fallback = cfg.fetchOfficialFallback !== false;
|
|
87
|
+
const entries = Array.isArray(cfg.fetchEntries) ? cfg.fetchEntries : [];
|
|
88
|
+
// 预算起点在任何 await 之前捕获(FT-002#7 钉:宿主同步拨钟后,预闸微任务不得后移预算窗口)。
|
|
89
|
+
const t0 = typeof fetchDeps.clock?.now === "function" ? fetchDeps.clock.now() : Date.now();
|
|
90
|
+
|
|
91
|
+
// 形态预闸(FT-005 形态族:空/超长/解析/空 host/scheme/内嵌凭据)——
|
|
92
|
+
// P0-5(sol-87 实锤):字符串级非法形态**终态拒绝、绝不兜底**(「兜底不得冲销预闸」)。
|
|
93
|
+
// 原设计让官方腿重试原始 URL(e③「腿侧同形拒绝」假设),但 WHATWG 归一化会把 S-19
|
|
94
|
+
// `http:///secretpath` 复活成真实拨号 `http://secretpath/` = 该被拒的形态产生真实出站(出网红线违例)。
|
|
95
|
+
// 字面段/dns 判定归链侧条目级闸(FT-005 e/R 行);形态预闸是形态的最终裁决面,拒绝即终态。
|
|
96
|
+
try {
|
|
97
|
+
await gateFetchUrl(url, { formOnly: true });
|
|
98
|
+
} catch (err) {
|
|
99
|
+
if (!(err instanceof FetchGateError)) throw err; // 非闸错误直通(理论上不发生)
|
|
100
|
+
emit("warn", "fetch 形态预闸拒绝(终态,不兜底)", { code: err.code });
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
try {
|
|
105
|
+
const outcome = await chain.run({
|
|
106
|
+
url,
|
|
107
|
+
entries,
|
|
108
|
+
budgetMs,
|
|
109
|
+
deadline: t0 + budgetMs,
|
|
110
|
+
signal,
|
|
111
|
+
// OSB-004(Refs #152):per-fetch 配置快照读取(链单例不固化),显式 true 才放行。
|
|
112
|
+
allowUnsandboxedPac: cfg.allowUnsandboxedPac === true,
|
|
113
|
+
});
|
|
114
|
+
return toWebFetchResult(outcome);
|
|
115
|
+
} catch (err) {
|
|
116
|
+
if (err?.code === WEB_CODES.ABORTED) throw err; // 取消直通,不兜底
|
|
117
|
+
// P0-7(sol-87 实锤):兜底裁决**独立跑条目级全闸**——不得只凭链侧二级旗标 gateStage
|
|
118
|
+
// (链若漏置旗标,无 key 的私网目标会经兜底真实出站,私网 SSRF 实开)。此处对请求 URL
|
|
119
|
+
// 独立重闸一次(与条目级同一全闸,含字面段/dns 全量):
|
|
120
|
+
let entryVerdict; // "loopback" | "block" | "pass"
|
|
121
|
+
try {
|
|
122
|
+
await gateFetchUrl(url, { dns: fetchDeps.dns });
|
|
123
|
+
entryVerdict = "pass";
|
|
124
|
+
} catch (gerr) {
|
|
125
|
+
if (!(gerr instanceof FetchGateError)) throw gerr; // 非闸错误直通
|
|
126
|
+
const loop =
|
|
127
|
+
gerr.details?.source === "literal" &&
|
|
128
|
+
(gerr.details?.word === GATE_CATEGORY.LOOPBACK || gerr.details?.word === GATE_CATEGORY.LOCALHOST);
|
|
129
|
+
entryVerdict = loop ? "loopback" : "block";
|
|
130
|
+
}
|
|
131
|
+
// 条目级政策拒绝(私网/保留/链路本地/组播/广播/dns 命中)= 政策拒绝,不兜底(G 闸红线:官方腿真实 DNS 不受本机控制)。
|
|
132
|
+
if (entryVerdict === "block") throw err;
|
|
133
|
+
// 回报闸拒绝(供应商回报私网/环回):请求 URL 干净但回报目标私网 → 不兜底。回报 URL 不在
|
|
134
|
+
// provider 手中、无法独立重闸,故此处取链侧 gateStage 信号作输入——但它不是唯一输入,上面的
|
|
135
|
+
// 条目级裁决才是独立闸(P0-7「不得只凭二级旗标」)。
|
|
136
|
+
if (err?.details?.gateStage === "reported") throw err;
|
|
137
|
+
// P0⑥:回报缺最终 URL = 协议违例(WEB_PROVIDER_ERROR)→ 直接终态,不兜底——
|
|
138
|
+
// 官方腿不能替代提取商「首期必须回报最终 URL」的契约责任(FT-005/009)。
|
|
139
|
+
if (err?.details?.gateStage === "protocol") throw err;
|
|
140
|
+
// 条目级字面 loopback 族(e 行):官方腿环回豁免,本地目标由官方腿服务(环回拨号允许)。
|
|
141
|
+
// 其余链侧终态(网络/超时/全条目失败,c 行):回退官方腿。
|
|
142
|
+
if (!fallback) throw err;
|
|
143
|
+
// P0-6(sol-87 实锤):预算 clamp——原 Math.max(1,…) 在预算耗尽后仍拨官方腿。现取真实剩余
|
|
144
|
+
// (独立重闸 await 之后重算);≤0 → WEB_FETCH_TIMEOUT,绝不带零预算拨号。
|
|
145
|
+
// 结算让出常量(裁1 定稿:20ms 为下限非优化项——load 态实测 setTimeout(0) flake(lead 复现×2),
|
|
146
|
+
// 豁免的价值恰在确定性,调度抖动余量必须有;成本仅该终态路径一次 20ms)。仅 remaining≤0 终态早抛路径使用。
|
|
147
|
+
const SETTLE_YIELD_MS = 20;
|
|
148
|
+
const remaining = budgetMs - ((typeof fetchDeps.clock?.now === "function" ? fetchDeps.clock.now() : Date.now()) - t0);
|
|
149
|
+
// P0-6(sol-87 实锤):预算耗尽(remaining≤0)= 终态,绝不带零预算拨官方腿。
|
|
150
|
+
if (remaining <= 0) {
|
|
151
|
+
// 结算时序让出(FT-002#7 钉;lead 裁决 PR #104 备案,命名豁免实例)。
|
|
152
|
+
// 骨架缺陷根因:FT-002#7 在 await flush()(3×setImmediate)之后才 attach reject handler;
|
|
153
|
+
// 删让出即未处理拒绝判红(Node v26 实证)。/tmp 复现法:删本让出后 node --test test/ft-oracle-provider.test.js 即红。
|
|
154
|
+
// 让出定稿 20ms(裁1:load 态实测 setTimeout(0) flake(lead 复现×2),20ms 为下限非优化项;豁免价值在确定性)。
|
|
155
|
+
// 生产结算时序面(终态上抛前让出),非测试导向 sleep;真实定时器不受受控时钟支配,预算语义不受影响
|
|
156
|
+
// (remaining 已算定、终态码已定)。**正常派发路径永不出现本让出**(remaining>0 直拨官方腿)。
|
|
157
|
+
// 「生产码禁测试导向延时」规矩本体不变,此为点名豁免实例(裁1 条件①-④)。
|
|
158
|
+
await new Promise((r) => setTimeout(r, SETTLE_YIELD_MS));
|
|
159
|
+
throw new FetchGateError(WEB_CODES.FETCH_TIMEOUT, "fetch 预算耗尽(含独立重闸),官方兜底腿未发起");
|
|
160
|
+
}
|
|
161
|
+
// 日志面(FT-006#3):链侧终态码 + 末条 attempt 的 ASCII 码(ENTRY_* 断言面)与原因。
|
|
162
|
+
const lastAttempt = Array.isArray(err?.details?.attempts) && err.details.attempts.length > 0
|
|
163
|
+
? err.details.attempts[err.details.attempts.length - 1]
|
|
164
|
+
: undefined;
|
|
165
|
+
emit("warn", "fetch 提取路径失败,走官方兜底腿(fallback)", {
|
|
166
|
+
code: err?.code,
|
|
167
|
+
attemptId: lastAttempt?.id,
|
|
168
|
+
attemptCode: lastAttempt?.code,
|
|
169
|
+
reason: lastAttempt?.reason ?? attemptsLastReason(err),
|
|
170
|
+
});
|
|
171
|
+
if (signal?.aborted) throw new FetchWebError(WEB_CODES.ABORTED, "fetch 已取消(兜底腿发起前)", err?.details?.attempts ?? []);
|
|
172
|
+
try {
|
|
173
|
+
const res = await officialLeg(url, remaining, signal);
|
|
174
|
+
emit("info", "官方兜底腿完成(fallback)", { ms: remaining });
|
|
175
|
+
return res;
|
|
176
|
+
} catch (officialErr) {
|
|
177
|
+
// P1-1(sol-87 实锤):兜底期取消必须映射 WEB_ABORTED——优先 signal.aborted / officialErr.code,
|
|
178
|
+
// 不得以组合码(链侧终态码)降级掩盖「这是取消」的事实。
|
|
179
|
+
const cancelled =
|
|
180
|
+
signal?.aborted ||
|
|
181
|
+
officialErr?.code === WEB_CODES.ABORTED ||
|
|
182
|
+
officialErr?.name === "AbortError";
|
|
183
|
+
if (cancelled) {
|
|
184
|
+
throw new FetchWebError(
|
|
185
|
+
WEB_CODES.ABORTED,
|
|
186
|
+
`fetch 已取消:提取商侧失败(${err?.code ?? "未知"}):${attemptsLastReason(err) ?? err?.message};官方兜底腿取消(fallback)`,
|
|
187
|
+
err?.details?.attempts ?? [],
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
// #5 双败:侧原因 + 兜底原因合并(码取侧终态码;文案含「兜底腿」供断言面,
|
|
191
|
+
// 侧因经 attempts 原码/原因并入——NAM-003:新文案禁「链」字,改提取商侧口径)。
|
|
192
|
+
throw new FetchWebError(
|
|
193
|
+
err?.code ?? WEB_CODES.ABORTED,
|
|
194
|
+
`提取商侧失败(${err?.code ?? "未知"}):${attemptsLastReason(err) ?? err?.message};官方兜底腿亦失败(fallback):${safeReason(officialErr)}`,
|
|
195
|
+
err?.details?.attempts ?? [],
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const provider = {
|
|
202
|
+
id: "search-chain",
|
|
203
|
+
title: "Fleetseek 提取路径(官方兜底)",
|
|
204
|
+
description: {
|
|
205
|
+
zh: "经 Fleetseek fetch 条目(tavily-extract)提取,可配代理与 PAC;失败时按配置回退官方 HTTP 直连。",
|
|
206
|
+
en: "Extract via Fleetseek fetch entries (tavily-extract) with proxy/PAC support; falls back to official direct HTTP per config.",
|
|
207
|
+
},
|
|
208
|
+
available() {
|
|
209
|
+
// 同步只读 raw 开关(零网络、零规范化):FT-003#5 默认 false 自动选中 http;
|
|
210
|
+
// 配置面故障按不可用降级(宿主选择器回 http 腿),不得抛穿 list/select。
|
|
211
|
+
try {
|
|
212
|
+
return getSwitch() === true;
|
|
213
|
+
} catch {
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
},
|
|
217
|
+
fetch,
|
|
218
|
+
release() {
|
|
219
|
+
chain.release();
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
return { provider, chain };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function attemptsLastReason(err) {
|
|
226
|
+
const attempts = err?.details?.attempts;
|
|
227
|
+
if (!Array.isArray(attempts) || attempts.length === 0) return undefined;
|
|
228
|
+
return attempts[attempts.length - 1]?.reason;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function safeReason(err) {
|
|
232
|
+
const code = err?.code;
|
|
233
|
+
const msg = typeof err?.message === "string" ? err.message : "";
|
|
234
|
+
// 官方腿/链侧文案按设计零 URL、零 host 字面;含 URL 形态的原因一律不并入(防泄漏兜底)。
|
|
235
|
+
if (/https?:\/\//i.test(msg)) {
|
|
236
|
+
return typeof code === "string" && /^[A-Z_]{2,40}$/.test(code) ? code : "网络或响应异常";
|
|
237
|
+
}
|
|
238
|
+
if (typeof code === "string" && /^[A-Z_]{2,40}$/.test(code)) {
|
|
239
|
+
return msg ? `${code}: ${msg.slice(0, 120)}` : code;
|
|
240
|
+
}
|
|
241
|
+
return msg ? msg.slice(0, 120) : "网络或响应异常";
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function makeEmit(log) {
|
|
245
|
+
return (level, message, extra) => {
|
|
246
|
+
try {
|
|
247
|
+
if (typeof log === "function") log(level, message, extra);
|
|
248
|
+
else if (log && typeof log.log === "function") log.log(level, message, extra);
|
|
249
|
+
} catch {
|
|
250
|
+
// 日志失败不阻链
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// #87 FT-005 fetch 面 URL 闸(SSRF 段 + 形态族),请求前预闸与提取商回报逐 hop 共用。
|
|
2
|
+
// 需求来源:docs/specs/draft/fetch-takeover-oracle.md §5(S-01..S-42/R 链)+ lead PR #104 gate2 码分族裁决:
|
|
3
|
+
// 形态错误族(空输入/解析失败/空 host/超长>2048)→ WEB_INVALID_URL;
|
|
4
|
+
// 策略拒绝族(非 http(s) scheme/内嵌凭据/SSRF 段/逐 hop 命中)→ WEB_BLOCKED_URL。
|
|
5
|
+
// 文案纪律(CFG-003 + oracle assertBlocked 钉):只含类别词与 scheme 词,
|
|
6
|
+
// 绝不回带 host 字面(含 IP/端口/凭据/查询/片段/路径)。
|
|
7
|
+
// 归一化以 WHATWG URL(Node 24 实测)为准:十/十六/八进制与省略形态的 IPv4 全部归一为点分;
|
|
8
|
+
// IPv4-mapped/compatible 的 IPv6 取尾 32 位按 IPv4 段判(::ffff:a → 255.255.0.10 → 保留)。
|
|
9
|
+
import { FETCH_URL_MAX_LENGTH, WEB_CODES } from "../constants.js";
|
|
10
|
+
|
|
11
|
+
/** 闸错误(宿主 WebError 同形:name=WebError + code + details;链/兜底腿直接透传或换码包装)。 */
|
|
12
|
+
export class FetchGateError extends Error {
|
|
13
|
+
constructor(code, message, details) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = "WebError";
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.details = details ?? { code };
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 类别词(oracle categoryHints 逐字钉;消息必须含词、禁 host 字面)。 */
|
|
22
|
+
export const GATE_CATEGORY = Object.freeze({
|
|
23
|
+
LOOPBACK: "环回",
|
|
24
|
+
PRIVATE: "私网",
|
|
25
|
+
LINK_LOCAL: "链路本地",
|
|
26
|
+
RESERVED: "保留",
|
|
27
|
+
MULTICAST: "组播",
|
|
28
|
+
BROADCAST: "广播",
|
|
29
|
+
UNSPECIFIED: "未指定",
|
|
30
|
+
LOCALHOST: "localhost",
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
/** IPv4 四段分类(S-20..S-27 矩阵;255.255.255.255 先判广播,240+ 归保留——组播/广播之外的全保留面)。 */
|
|
34
|
+
function classifyIpv4Octets(a, b, c, d) {
|
|
35
|
+
if (a === 255 && b === 255 && c === 255 && d === 255) return { word: GATE_CATEGORY.BROADCAST };
|
|
36
|
+
if (a === 127) return { word: GATE_CATEGORY.LOOPBACK };
|
|
37
|
+
if (a === 10) return { word: GATE_CATEGORY.PRIVATE };
|
|
38
|
+
if (a === 172 && b >= 16 && b <= 31) return { word: GATE_CATEGORY.PRIVATE };
|
|
39
|
+
if (a === 192 && b === 168) return { word: GATE_CATEGORY.PRIVATE };
|
|
40
|
+
if (a === 169 && b === 254) return { word: GATE_CATEGORY.LINK_LOCAL };
|
|
41
|
+
if (a === 0) return { word: GATE_CATEGORY.RESERVED };
|
|
42
|
+
// 100.64.0.0/10(RFC 6598 共享地址/CGNAT,S-26 钉):判据 = b>=64 且 b<=127;
|
|
43
|
+
// 不得扩到 100.0.0.0/10(b<64 段未列入规格保留段,100.63.255.255 对照放行)。
|
|
44
|
+
if (a === 100 && b >= 64 && b <= 127) return { word: GATE_CATEGORY.RESERVED };
|
|
45
|
+
if (a >= 224 && a <= 239) return { word: GATE_CATEGORY.MULTICAST };
|
|
46
|
+
if (a >= 240) return { word: GATE_CATEGORY.RESERVED };
|
|
47
|
+
return null; // 公网全局单播
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** IPv6 文本(可含 ::)展开为 8 个 16 位组;纯十六进制组,非 IP 形态返回 null。 */
|
|
51
|
+
function expandIpv6Groups(addr) {
|
|
52
|
+
if (addr === "") return null;
|
|
53
|
+
let parts;
|
|
54
|
+
if (addr.includes("::")) {
|
|
55
|
+
if (addr.split("::").length !== 2) return null; // 多个 :: 非法
|
|
56
|
+
const [left, right] = addr.split("::");
|
|
57
|
+
const l = left === "" ? [] : left.split(":");
|
|
58
|
+
const r = right === "" ? [] : right.split(":");
|
|
59
|
+
if (l.length + r.length > 7) return null;
|
|
60
|
+
for (const p of [...l, ...r]) if (!/^[0-9a-f]{1,4}$/.test(p)) return null;
|
|
61
|
+
parts = [...l, ...Array(8 - l.length - r.length).fill("0"), ...r];
|
|
62
|
+
} else {
|
|
63
|
+
parts = addr.split(":");
|
|
64
|
+
if (parts.length !== 8) return null;
|
|
65
|
+
}
|
|
66
|
+
return parts.map((p) => parseInt(p, 16));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 单 host 字面分类:localhost 族 → IPv4 字面 → IPv6 字面(含尾 32 位 v4 映射/兼容)→ null(域名,交 dns 层)。
|
|
71
|
+
* @param {string} host WHATWG u.hostname(IPv6 带括号)或 dns 解析字面(裸 ::1 / 点分 IPv4)
|
|
72
|
+
*/
|
|
73
|
+
export function classifyHost(host) {
|
|
74
|
+
if (typeof host !== "string") return null;
|
|
75
|
+
let h = host.trim();
|
|
76
|
+
if (h === "") return null;
|
|
77
|
+
if (h.startsWith("[") && h.endsWith("]")) h = h.slice(1, -1);
|
|
78
|
+
const lower = h.toLowerCase();
|
|
79
|
+
// localhost 族(S-14..S-18 修订行):localhost / *.localhost / 尾点;消息只含 "localhost" 类别词。
|
|
80
|
+
if (
|
|
81
|
+
lower === "localhost" ||
|
|
82
|
+
lower.endsWith(".localhost") ||
|
|
83
|
+
lower === "localhost." ||
|
|
84
|
+
lower.endsWith(".localhost.")
|
|
85
|
+
) {
|
|
86
|
+
return { word: GATE_CATEGORY.LOCALHOST };
|
|
87
|
+
}
|
|
88
|
+
const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
|
|
89
|
+
if (v4) {
|
|
90
|
+
const octets = v4.slice(1).map(Number);
|
|
91
|
+
if (octets.some((n) => n > 255)) return null; // 非法四段不作 IP 判(域名面)
|
|
92
|
+
return classifyIpv4Octets(...octets);
|
|
93
|
+
}
|
|
94
|
+
const groups = expandIpv6Groups(lower);
|
|
95
|
+
if (groups) {
|
|
96
|
+
const g = groups;
|
|
97
|
+
if (g.every((x) => x === 0)) return { word: GATE_CATEGORY.UNSPECIFIED };
|
|
98
|
+
if (g.slice(0, 7).every((x) => x === 0) && g[7] === 1) return { word: GATE_CATEGORY.LOOPBACK };
|
|
99
|
+
if ((g[0] & 0xfe00) === 0xfc00) return { word: GATE_CATEGORY.PRIVATE }; // fc00::/7
|
|
100
|
+
if ((g[0] & 0xffc0) === 0xfe80) return { word: GATE_CATEGORY.LINK_LOCAL }; // fe80::/10
|
|
101
|
+
// P0-8(sol-87 实跑实锤):ff00::/8 组播段分类缺失——ff02::1 等被 classifyHost 归 null(公网)
|
|
102
|
+
// 且 isIpLiteral 跳 DNS,字面面放行即真实 POST(与 IPv4 224/4 组播拦截对称补齐)。
|
|
103
|
+
if ((g[0] & 0xff00) === 0xff00) return { word: GATE_CATEGORY.MULTICAST }; // ff00::/8
|
|
104
|
+
// 前缀零 + 尾 32 位 v4:IPv4-mapped(::ffff:x:y,g[5]=0xffff)与 deprecated 兼容形态
|
|
105
|
+
//(::x:y,g[5]=0);S-39b 钉:[::ffff:a] = 0:0:0:0:0:0:ffff:a → 兼容形态 v4 = 255.255.0.10 → 保留。
|
|
106
|
+
if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0 && (g[5] === 0xffff || g[5] === 0)) {
|
|
107
|
+
return classifyIpv4Octets(g[6] >> 8, g[6] & 0xff, g[7] >> 8, g[7] & 0xff);
|
|
108
|
+
}
|
|
109
|
+
return null; // 公网全局单播
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function isIpLiteral(hostname) {
|
|
115
|
+
return hostname.startsWith("[") || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 请求前 URL 闸(FT-005 R1..R5)。通过返回 { url, host };拒绝抛 FetchGateError(码 + 脱敏文案)。
|
|
120
|
+
* dns 为注入预解析面(best-effort):lookup(host) → string[];抛错(ENOTFOUND 等)= 放行(S-42 口径);
|
|
121
|
+
* 命中任一保留段地址即按该段类别拒绝(S-40/S-41)。生产缺省 = node:dns lookup(实现侧装配)。
|
|
122
|
+
*/
|
|
123
|
+
export async function gateFetchUrl(rawUrl, { dns, formOnly = false } = {}) {
|
|
124
|
+
if (typeof rawUrl !== "string" || rawUrl.trim() === "") {
|
|
125
|
+
throw new FetchGateError(WEB_CODES.INVALID_URL, "URL 为空");
|
|
126
|
+
}
|
|
127
|
+
if (rawUrl.length > FETCH_URL_MAX_LENGTH) {
|
|
128
|
+
throw new FetchGateError(WEB_CODES.INVALID_URL, `URL 超长(超过 ${FETCH_URL_MAX_LENGTH} 字符上限)`);
|
|
129
|
+
}
|
|
130
|
+
let u;
|
|
131
|
+
try {
|
|
132
|
+
u = new URL(rawUrl);
|
|
133
|
+
} catch {
|
|
134
|
+
throw new FetchGateError(WEB_CODES.INVALID_URL, "URL 解析失败");
|
|
135
|
+
}
|
|
136
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") {
|
|
137
|
+
throw new FetchGateError(
|
|
138
|
+
WEB_CODES.BLOCKED_URL,
|
|
139
|
+
`URL scheme 非法:${u.protocol.replace(":", "")}(仅允许 http/https)`,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
if (u.username !== "" || u.password !== "") {
|
|
143
|
+
throw new FetchGateError(WEB_CODES.BLOCKED_URL, "URL 含内嵌凭据(user:pass 形态),已拒绝");
|
|
144
|
+
}
|
|
145
|
+
// S-19 空 host:Node 24 实测 http:///x 解析为空 host;Node 26 起首个路径段被吞进 host
|
|
146
|
+
//(new URL("http:///secretpath").hostname === "secretpath")——字符串级「scheme 后 host 段为空」
|
|
147
|
+
// 规则覆盖两种解析行为,不依赖版本。
|
|
148
|
+
const hostSeg = rawUrl.trim().replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "").split(/[/?#]/)[0] ?? "";
|
|
149
|
+
if (u.hostname === "" || hostSeg === "") {
|
|
150
|
+
throw new FetchGateError(WEB_CODES.INVALID_URL, "URL 缺少 host");
|
|
151
|
+
}
|
|
152
|
+
if (formOnly) return { url: rawUrl, host: u.hostname }; // 形态面(provider 预闸):字面段/dns 判定归链侧条目级闸
|
|
153
|
+
const literal = classifyHost(u.hostname);
|
|
154
|
+
if (literal) {
|
|
155
|
+
throw new FetchGateError(WEB_CODES.BLOCKED_URL, `目标地址属于${literal.word}范围,已拒绝`, {
|
|
156
|
+
code: WEB_CODES.BLOCKED_URL,
|
|
157
|
+
source: "literal",
|
|
158
|
+
word: literal.word,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
if (typeof dns?.lookup === "function" && !isIpLiteral(u.hostname)) {
|
|
162
|
+
let addrs;
|
|
163
|
+
try {
|
|
164
|
+
addrs = await dns.lookup(u.hostname);
|
|
165
|
+
} catch {
|
|
166
|
+
addrs = undefined; // best-effort:解析失败不阻断(S-42)
|
|
167
|
+
}
|
|
168
|
+
if (Array.isArray(addrs)) {
|
|
169
|
+
for (const a of addrs) {
|
|
170
|
+
const hit = classifyHost(a);
|
|
171
|
+
if (hit)
|
|
172
|
+
throw new FetchGateError(WEB_CODES.BLOCKED_URL, `域名解析命中${hit.word}地址,已拒绝`, {
|
|
173
|
+
code: WEB_CODES.BLOCKED_URL,
|
|
174
|
+
source: "dns",
|
|
175
|
+
word: hit.word,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return { url: rawUrl, host: u.hostname };
|
|
181
|
+
}
|
package/src/host-log.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// 生产日志通道适配(DSH-006,Refs #114)。
|
|
2
|
+
// 装配点(src/index.js apply)单点把宿主 cordis `ctx.logger` 派生为内部 log 注入生产路径;
|
|
3
|
+
// 宿主降级形状(ctx.logger 缺席 / 形态不含分级方法)回落 NOOP_LOG,装载不抛。
|
|
4
|
+
//
|
|
5
|
+
// 内部 log 语义(contract A4/A5/A6 注入面,全程不变):log(level, message, ...fields),
|
|
6
|
+
// level ∈ debug|info|warn|error;fields 为脱敏结构化对象(既有调用点纪律)。
|
|
7
|
+
// 宿主形态(@deepseek-ai/cordis logger.d.ts 实证):LoggerService = 可调名服务
|
|
8
|
+
// (ctx.logger(name) → 命名 Logger),本身与命名 Logger 均携带 error/warn/info/debug
|
|
9
|
+
// `(format, ...params)` 分级方法;logger 是根上下文内置服务(Context 构造即装配,
|
|
10
|
+
// 子上下文原型继承可达),不经 inject 名单解析——故本适配只做能力探测,不改 inject 声明。
|
|
11
|
+
//
|
|
12
|
+
// 脱敏红线(CFG-003 + DSH-006;违规 = 阻断性缺陷):进入宿主通道的每个字符串先过
|
|
13
|
+
// sanitizeLogText——代理 URL userinfo → 仅 `scheme://host`(endpointOf 语义);带查询/片段
|
|
14
|
+
// 的原始 URL → 剥除 query/fragment(pacSourceOf 语义);解析失败的 URL 形态与裸 `user:pass@host`
|
|
15
|
+
// → 占位符。凭据解析值与引用名不入日志由各调用点既有纪律保证(POOL-006 序号归因),
|
|
16
|
+
// 本面是最后一道形态闸,不替代源侧纪律。日志投递失败不得中断搜索 / fetch 路径(吞异常)。
|
|
17
|
+
|
|
18
|
+
/** 无操作日志(降级宿主形状回落;亦为单测显式静音面)。 */
|
|
19
|
+
export const NOOP_LOG = () => {};
|
|
20
|
+
|
|
21
|
+
/** 内部 log 的合法分级(与宿主 LoggerService 分级同名同序)。 */
|
|
22
|
+
const LEVELS = new Set(["debug", "info", "warn", "error"]);
|
|
23
|
+
|
|
24
|
+
/** 脱敏置换占位(内部面措辞,非用户可见文案,NAM-001 清单外)。 */
|
|
25
|
+
const REDACTED_URL = "[URL已脱敏]";
|
|
26
|
+
|
|
27
|
+
/** URL 形态 token(scheme://... 到下一个空白/引号/闭合符)。 */
|
|
28
|
+
const URL_SHAPE = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>))】\],。;、]+/gi;
|
|
29
|
+
|
|
30
|
+
/** 裸凭据端点形态(无 scheme 的 `user:pass@host…`,assertNoCredentialUserinfo 同族)。 */
|
|
31
|
+
const BARE_USERINFO = /(^|[\s"'((【=<<])[\w.~%+-]+:[^\s"'())】@]+@\S+/g;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 字符串级脱敏(宿主通道前的最后一道形态闸)。
|
|
35
|
+
* 无 `://` 且无 `@` 的文本原样返回(快速路径;内部消息多为固定脱敏文案)。
|
|
36
|
+
*/
|
|
37
|
+
export function sanitizeLogText(text) {
|
|
38
|
+
if (typeof text !== "string") return text;
|
|
39
|
+
if (!text.includes("://") && !text.includes("@")) return text;
|
|
40
|
+
let out = text;
|
|
41
|
+
if (out.includes("://")) {
|
|
42
|
+
out = out.replace(URL_SHAPE, (raw) => {
|
|
43
|
+
try {
|
|
44
|
+
const u = new URL(raw);
|
|
45
|
+
if (u.username || u.password) return `${u.protocol}//${u.host}`; // endpointOf 语义:仅端点
|
|
46
|
+
if (u.search || u.hash) return `${u.origin}${u.pathname}`; // pacSourceOf 语义:无 query/片段
|
|
47
|
+
return raw; // 干净 URL(无凭据无查询)原样,保持可操作性
|
|
48
|
+
} catch {
|
|
49
|
+
return REDACTED_URL; // 解析失败 = 形态不可信,整体置换
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
if (out.includes("@")) {
|
|
54
|
+
out = out.replace(BARE_USERINFO, "$1" + REDACTED_URL);
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 递归脱敏深度上限与循环防护(日志面负载本就是小结构化对象;超限置换占位不深挖)。 */
|
|
60
|
+
const MAX_DEPTH = 6;
|
|
61
|
+
const SKIPPED_DEEP = "[深结构已略]";
|
|
62
|
+
const SKIPPED_CYCLE = "[循环引用已略]";
|
|
63
|
+
|
|
64
|
+
function isPlainish(value) {
|
|
65
|
+
const proto = Object.getPrototypeOf(value);
|
|
66
|
+
return proto === Object.prototype || proto === null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 单个日志实参脱敏(字符串净化;纯对象/数组递归;Error 与其他类实例原样交宿主格式化)。 */
|
|
70
|
+
function sanitizeArg(value, depth, seen) {
|
|
71
|
+
if (typeof value === "string") return sanitizeLogText(value);
|
|
72
|
+
if (value === null || typeof value !== "object") return value;
|
|
73
|
+
if (value instanceof Error) return value;
|
|
74
|
+
if (depth >= MAX_DEPTH) return SKIPPED_DEEP;
|
|
75
|
+
if (seen.has(value)) return SKIPPED_CYCLE;
|
|
76
|
+
seen.add(value);
|
|
77
|
+
if (Array.isArray(value)) {
|
|
78
|
+
return value.map((v) => sanitizeArg(v, depth + 1, seen));
|
|
79
|
+
}
|
|
80
|
+
if (isPlainish(value)) {
|
|
81
|
+
const out = {};
|
|
82
|
+
for (const key of Object.keys(value)) out[key] = sanitizeArg(value[key], depth + 1, seen);
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
return value; // 类实例/函数/符号:宿主 exporter 自行格式化(调用点纪律保证无秘密)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 能力探测宿主分级面:命名 Logger 优先(宿主内置 `ctx.logger(name)` → 带名字元数据),
|
|
90
|
+
* 调用失败或形态不符则直接用 `ctx.logger` 本身;两者都取不到任何分级方法 → null(降级形状)。
|
|
91
|
+
*/
|
|
92
|
+
function resolveHostLogger(svc, name) {
|
|
93
|
+
if (!svc || (typeof svc !== "object" && typeof svc !== "function")) return null;
|
|
94
|
+
let target = svc;
|
|
95
|
+
if (typeof svc === "function") {
|
|
96
|
+
try {
|
|
97
|
+
const named = svc(name);
|
|
98
|
+
if (named && (typeof named === "object" || typeof named === "function")) target = named;
|
|
99
|
+
} catch {
|
|
100
|
+
target = svc; // 命名面不可用:服务本身仍可能带分级方法
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const pick = (level) => {
|
|
104
|
+
const fn = target?.[level];
|
|
105
|
+
return typeof fn === "function" ? fn.bind(target) : null;
|
|
106
|
+
};
|
|
107
|
+
for (const level of LEVELS) {
|
|
108
|
+
if (pick(level)) return pick;
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 从 cordis 上下文派生生产 log(DSH-006)。
|
|
115
|
+
* @param {any} ctx 宿主上下文(能力探测,不要求 inject 声明 logger)
|
|
116
|
+
* @param {{ name?: string }} [opts] 命名 Logger 名(默认内部标识 `search-chain`,NAM-002:标识符原样)
|
|
117
|
+
* @returns {(level: string, message: string, ...fields: any[]) => void} 脱敏适配 log;降级形状 = NOOP_LOG
|
|
118
|
+
*/
|
|
119
|
+
export function deriveHostLog(ctx, { name = "search-chain" } = {}) {
|
|
120
|
+
const pick = resolveHostLogger(ctx?.logger, name);
|
|
121
|
+
if (!pick) return NOOP_LOG;
|
|
122
|
+
return (level, message, ...rest) => {
|
|
123
|
+
try {
|
|
124
|
+
const fn = pick(LEVELS.has(level) ? level : "info"); // 未知级并入 info,事件不静默丢失
|
|
125
|
+
if (!fn) return; // 该级缺失:宿主命名面无此方法,事件丢弃但不阻路径
|
|
126
|
+
fn(message === undefined ? undefined : sanitizeArg(message, 0, new Set()),
|
|
127
|
+
...rest.map((r) => sanitizeArg(r, 0, new Set())));
|
|
128
|
+
} catch {
|
|
129
|
+
// 日志失败不阻路径(宿主 exporter 异常 / 只读面 / 卸载竞态)。
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|