dsh-drydock 1.0.1 → 1.0.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/lib/downloader.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
- import { createWriteStream, mkdirSync, unlinkSync } from "node:fs";
3
- import { randomUUID } from "node:crypto";
2
+ import { createReadStream, createWriteStream, mkdirSync, unlinkSync } from "node:fs";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { once } from "node:events";
4
5
  import { join } from "node:path";
5
6
  import { tmpdir } from "node:os";
6
7
  import { spawn } from "node:child_process";
@@ -9,18 +10,42 @@ const require = createRequire(import.meta.url);
9
10
 
10
11
  /**
11
12
  * 通用下载器:适配主流下载链接方式。
12
- * - http(s) 直链 -> fetch 流式下载
13
+ * - http(s) 直链 -> fetch 流式下载(边写盘边算摘要,不整体读进内存)
13
14
  * - magnet / .torrent -> P2P(优先本机 aria2c 外部进程,否则内置 webtorrent)
14
15
  * - 外部下载器检测:aria2c(HTTP/magnet/torrent 全支持)、比特彗星等(无 CLI 时提示用户手动导入)
16
+ *
17
+ * 安全模型(CWE-494,配合 GitHub PR #4 的供应链加固;本文件负责「下载物完整性」这一环):
18
+ * 门禁 1 `allowInsecure`(默认 false):明文 `http://` 默认拒绝 —— 连接不加密,内容可在传输中被篡改/劫持。
19
+ * 重定向按 `redirect:"manual"` 逐跳校验(最多 5 跳):任何一跳降级成明文都立刻拒绝,
20
+ * 而不是只看跟随重定向后的最终 URL —— `https→http→https` 这种中间降级以前会漏掉(B 报告 S4-2)。
21
+ * 门禁 2 `allowUnverified`(默认 false):没有**内容摘要**(integrity/shasum)的下载默认拒绝 ——
22
+ * 只给 `size` 不算校验:字节数不是内容摘要,控制内容的一方补齐长度即可通过(B 报告 S4-1);
23
+ * 显式 allowUnverified 放行时,回执只写「仅核对大小,未校验内容摘要」。
24
+ * P2P(magnet/.torrent)没有可比的摘要,同样默认拒绝。
25
+ * 门禁 3 校验执行(只要给了期望就是强制):下载完成即校验;摘要或大小不匹配 -> 删除已下载文件 + 失败。
26
+ *
27
+ * 返回值恒为 `{ status, file, message, code }`:
28
+ * - status: "downloaded" | "blocked" | "failed"
29
+ * - code: "ok" | "insecure-url" | "unverified" | "invalid-expect" | "integrity-mismatch" |
30
+ * "size-mismatch" | "download-failed" | "p2p-unavailable" | "p2p-timeout" | "p2p-failed" |
31
+ * "unsupported-url" | null(历史路径未标注时)
15
32
  */
16
33
 
17
- /** 下载结果。 */
18
- function makeResult(status, file, message) {
19
- return { status, file: file ?? null, message: message ?? null };
34
+ /** 下载结果(保持 {status,file,message} 三字段兼容,额外附加 code 供机器判别)。 */
35
+ function makeResult(status, file, message, code = null) {
36
+ return { status, file: file ?? null, message: message ?? null, code };
20
37
  }
21
38
 
39
+ /** 摘要算法参数(长度以字节计)。 */
40
+ const DIGEST_BYTES = { sha512: 64, sha384: 48, sha256: 32, sha1: 20 };
41
+ /** 算法强度排序:SRI 多个算法并存时取最强可用者。 */
42
+ const ALGO_STRENGTH = { sha512: 4, sha384: 3, sha256: 2, sha1: 1 };
43
+
44
+ const DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000;
45
+ const P2P_TIMEOUT_MS = 10 * 60 * 1000;
46
+
22
47
  /** 判断链接类型。 */
23
- function classifyUrl(url) {
48
+ export function classifyUrl(url) {
24
49
  if (typeof url !== "string" || url === "") return "unknown";
25
50
  if (url.startsWith("magnet:")) return "magnet";
26
51
  const lower = url.toLowerCase();
@@ -31,6 +56,184 @@ function classifyUrl(url) {
31
56
  return "unknown";
32
57
  }
33
58
 
59
+ /** 日志/消息里截断超长 URL。 */
60
+ function shortenUrl(url) {
61
+ const text = String(url ?? "");
62
+ return text.length > 160 ? `${text.slice(0, 157)}…` : text;
63
+ }
64
+
65
+ /** 超时时长的中文展示。 */
66
+ function humanMs(ms) {
67
+ if (ms >= 60000 && ms % 60000 === 0) return `${ms / 60000} 分钟`;
68
+ if (ms >= 1000) return `${ms / 1000} 秒`;
69
+ return `${ms} 毫秒`;
70
+ }
71
+
72
+ /** 删除文件(失败忽略)。 */
73
+ function safeUnlink(file) {
74
+ try {
75
+ unlinkSync(file);
76
+ } catch {
77
+ // ignore
78
+ }
79
+ }
80
+
81
+ /** 门禁拒绝(在下载过程中发现,需要回传 code)。 */
82
+ class BlockedError extends Error {
83
+ constructor(code, message) {
84
+ super(message);
85
+ this.name = "BlockedError";
86
+ this.code = code;
87
+ }
88
+ }
89
+
90
+ // ---------- 摘要解析:npm SRI / shasum ----------
91
+
92
+ /** 去掉 SRI 选项后缀(`sha512-xxx?foo` 里的 `?foo`)。 */
93
+ function stripSriOptions(payload) {
94
+ const text = String(payload ?? "");
95
+ const q = text.indexOf("?");
96
+ return q === -1 ? text : text.slice(0, q);
97
+ }
98
+
99
+ /** 宽松 base64 解码(容忍缺省 padding 与 base64url 字符);不是 base64 形态返回 null。 */
100
+ function decodeBase64Loose(text) {
101
+ let body = String(text ?? "").trim().replace(/-/g, "+").replace(/_/g, "/");
102
+ if (body === "" || !/^[A-Za-z0-9+/]+={0,2}$/.test(body)) return null;
103
+ if (body.length % 4 !== 0) body += "=".repeat(4 - (body.length % 4));
104
+ try {
105
+ return Buffer.from(body, "base64");
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * 把「某算法 + 摘要载荷」归一成 `{algo, hex}`;载荷既可以是十六进制,也可以是 base64。
113
+ * 无法归一(长度/字符集/算法不支持)返回 null。
114
+ */
115
+ function normalizeDigest(algo, payload) {
116
+ const bytes = DIGEST_BYTES[algo];
117
+ if (bytes === undefined) return null;
118
+ const body = stripSriOptions(payload).trim();
119
+ if (body === "") return null;
120
+ // 1) 十六进制:长度正好等于 2*bytes 且全为 hex 字符
121
+ if (body.length === bytes * 2 && /^[0-9a-fA-F]+$/.test(body)) return { algo, hex: body.toLowerCase() };
122
+ // 2) base64 族:解出来正好 bytes 字节
123
+ const decoded = decodeBase64Loose(body);
124
+ if (decoded !== null && decoded.length === bytes) return { algo, hex: decoded.toString("hex") };
125
+ return null;
126
+ }
127
+
128
+ /**
129
+ * 解析 npm 风格 SRI 字符串:`sha512-<base64>`、`sha1-<base64>`,多个算法用空格分隔。
130
+ * 返回全部可解析的条目(未排序,由调用方取最强)。
131
+ */
132
+ function parseIntegrity(integrity) {
133
+ if (typeof integrity !== "string" || integrity.trim() === "") return [];
134
+ const entries = [];
135
+ for (const token of integrity.trim().split(/\s+/)) {
136
+ const match = /^(sha512|sha384|sha256|sha1)-(.+)$/i.exec(token);
137
+ if (match === null) continue;
138
+ const normalized = normalizeDigest(match[1].toLowerCase(), match[2]);
139
+ if (normalized !== null) entries.push(normalized);
140
+ }
141
+ return entries;
142
+ }
143
+
144
+ /** 取最强算法(SRI 语义:支持的算法里最强的一个说了算)。 */
145
+ function pickStrongest(entries) {
146
+ let best = null;
147
+ for (const entry of entries) {
148
+ if (best === null || ALGO_STRENGTH[entry.algo] > ALGO_STRENGTH[best.algo]) best = entry;
149
+ }
150
+ return best;
151
+ }
152
+
153
+ /**
154
+ * 把调用方给的 `expect` 变成可执行的校验计划。
155
+ * 返回 `{ size, hashes, problems, provided }`:
156
+ * - `provided:false` 表示调用方没给任何期望(门禁 2 会拒绝)
157
+ * - `problems` 非空表示期望本身不可用(如 integrity 拼错)—— 失败关闭,绝不当成「没给」
158
+ */
159
+ function buildVerificationPlan(expect) {
160
+ const plan = { size: null, hashes: [], problems: [], provided: false };
161
+ if (expect === undefined || expect === null) return plan;
162
+ if (typeof expect !== "object") {
163
+ plan.provided = true;
164
+ plan.problems.push("expect 必须是对象({ integrity, shasum, size })");
165
+ return plan;
166
+ }
167
+ const given = (name) => expect[name] !== undefined && expect[name] !== null;
168
+ if (!given("integrity") && !given("shasum") && !given("size")) return plan;
169
+ plan.provided = true;
170
+ if (given("size")) {
171
+ const n = Number(expect.size);
172
+ if (!Number.isInteger(n) || n < 0) plan.problems.push(`expect.size 不是非负整数(收到 ${JSON.stringify(expect.size)})`);
173
+ else plan.size = n;
174
+ }
175
+ if (given("shasum")) {
176
+ const normalized = normalizeDigest("sha1", expect.shasum);
177
+ if (normalized === null) plan.problems.push("expect.shasum 无法解析(应为 sha1 的 40 位十六进制,或等价的 base64)");
178
+ else plan.hashes.push({ ...normalized, source: "expect.shasum" });
179
+ }
180
+ if (given("integrity")) {
181
+ const parsed = parseIntegrity(expect.integrity);
182
+ const strongest = pickStrongest(parsed);
183
+ if (strongest === null) {
184
+ plan.problems.push("expect.integrity 无法解析(应为 npm 风格 SRI,如 sha512-<base64> 或 sha1-<base64>,多算法空格分隔,取最强者)");
185
+ } else {
186
+ plan.hashes.push({ ...strongest, source: `expect.integrity(${strongest.algo})` });
187
+ }
188
+ }
189
+ return plan;
190
+ }
191
+
192
+ /**
193
+ * 校验下载结果。
194
+ * @returns `{ok, code, message, verifiedAlgos}`;不匹配时 message 已说明「文件已删除」。
195
+ */
196
+ function verifyDownload(outcome, plan) {
197
+ const verifiedAlgos = [];
198
+ if (plan.size !== null && outcome.bytes !== plan.size) {
199
+ return {
200
+ ok: false,
201
+ code: "size-mismatch",
202
+ verifiedAlgos,
203
+ message: `校验失败:文件大小不匹配(期望 ${plan.size} 字节,实际 ${outcome.bytes} 字节)。已删除下载文件,未安装。`
204
+ };
205
+ }
206
+ for (const entry of plan.hashes) {
207
+ const actual = outcome.digests[entry.algo];
208
+ if (typeof actual !== "string") {
209
+ return {
210
+ ok: false,
211
+ code: "integrity-mismatch",
212
+ verifiedAlgos,
213
+ message: `校验失败:运行时无法计算 ${entry.algo} 摘要。已删除下载文件,未安装。`
214
+ };
215
+ }
216
+ if (actual !== entry.hex) {
217
+ return {
218
+ ok: false,
219
+ code: "integrity-mismatch",
220
+ verifiedAlgos,
221
+ message: `校验失败:${entry.algo} 摘要不匹配(期望 ${entry.hex.slice(0, 16)}…(来自 ${entry.source}),实际 ${actual.slice(0, 16)}…)。已删除下载文件,未安装。`
222
+ };
223
+ }
224
+ verifiedAlgos.push(entry.algo);
225
+ }
226
+ return { ok: true, code: "ok", verifiedAlgos, message: null };
227
+ }
228
+
229
+ /** 在结果 message 后追加说明(不改 status/file/code)。 */
230
+ function decorate(result, suffix) {
231
+ if (suffix === "" || result.message === null || result.message === undefined) return result;
232
+ return { ...result, message: result.message + suffix };
233
+ }
234
+
235
+ // ---------- 外部下载器探测 / P2P ----------
236
+
34
237
  /** 检测外部下载器(返回可执行名)。跨平台:Windows `where`,Linux/macOS `which`。 */
35
238
  function detectExternal() {
36
239
  const lookup = process.platform === "win32" ? "where" : "which";
@@ -47,15 +250,77 @@ function detectExternal() {
47
250
  return null;
48
251
  }
49
252
 
50
- /** HTTP(S) 直链下载(fetch 流式,最多 10 分钟)。 */
51
- async function downloadHttp(url, destFile, log) {
52
- const response = await fetch(url, { signal: AbortSignal.timeout(10 * 60 * 1000) });
253
+ // ---------- 下载实现 ----------
254
+
255
+ /** 重定向跳数上限(含相对 Location)。 */
256
+ const MAX_REDIRECTS = 5;
257
+
258
+ /** HTTP 3xx 才算重定向(其余交给下面的状态码判定)。 */
259
+ function isRedirectStatus(status) {
260
+ return status >= 300 && status < 400;
261
+ }
262
+
263
+ /**
264
+ * HTTP(S) 直链下载:fetch 流式写盘,同时**边写边算**摘要(不把响应体整体读进内存)。
265
+ *
266
+ * 重定向用 `redirect:"manual"` 自己逐跳跟随:原生 `redirect:"follow"` 会把
267
+ * `https→http→https` 这样的中间降级直接抹平,只能看到最终 URL,降级就漏检了(B 报告 S4-2)。
268
+ * 跨 host 不禁止(CDN 正常跳转),但每一跳都要过协议门禁;最终落盘仍按调用方给的摘要/大小校验。
269
+ * @returns `{bytes, digests}`:实际字节数与各算法摘要(hex)。
270
+ */
271
+ async function downloadHttp(url, destFile, log, hashes, allowInsecure) {
272
+ let current = url; // 第 1 跳 = 调用方给的 URL
273
+ let redirects = 0;
274
+ let response = null;
275
+ // 所有跳共用同一个超时信号:总预算仍是 10 分钟,不会因为多跳变成 N 倍
276
+ const signal = AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS);
277
+ for (;;) {
278
+ response = await fetch(current, { signal, redirect: "manual" });
279
+ if (!isRedirectStatus(response.status)) break;
280
+ const location = response.headers.get("location");
281
+ // 本跳的响应体不读,显式 cancel,避免连接/流悬挂
282
+ try {
283
+ await response.body?.cancel();
284
+ } catch {
285
+ // ignore
286
+ }
287
+ if (location === null || location === "") throw new Error(`HTTP ${response.status} 重定向缺少 Location`);
288
+ if (redirects >= MAX_REDIRECTS) {
289
+ throw new Error(`重定向次数超过上限(${MAX_REDIRECTS} 跳),已中止(下一跳:${shortenUrl(location)})`);
290
+ }
291
+ let next;
292
+ try {
293
+ // 相对 Location 必须按当前跳解析(RFC 7231 语义),不能字符串拼接
294
+ next = new URL(location, current);
295
+ } catch {
296
+ throw new Error(`重定向目标无法解析:${shortenUrl(location)}`);
297
+ }
298
+ if (next.protocol !== "http:" && next.protocol !== "https:") {
299
+ throw new Error(`重定向到不支持的协议 ${next.protocol}(${shortenUrl(next.href)})`);
300
+ }
301
+ redirects += 1;
302
+ const hopNo = redirects + 1; // 即将请求的那一跳(第 1 跳是调用方给的 URL)
303
+ // 逐跳门禁 1:任何一跳降级成明文都立刻拒绝,并说明是第几跳
304
+ if (!allowInsecure && next.protocol === "http:") {
305
+ throw new BlockedError(
306
+ "insecure-url",
307
+ `已拒绝下载:第 ${hopNo} 跳重定向降级为明文 HTTP(${shortenUrl(next.href)}),连接未加密,内容可能被篡改。如确需下载请显式传入 allowInsecure: true。`
308
+ );
309
+ }
310
+ log(`跟随重定向(第 ${hopNo} 跳):${shortenUrl(next.href)}`);
311
+ current = next.href;
312
+ }
53
313
  if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`);
54
314
  if (response.body === null) throw new Error("空响应体");
315
+ const hashStates = new Map(hashes.map((entry) => [entry.algo, createHash(entry.algo)]));
55
316
  const writer = createWriteStream(destFile);
317
+ let bytes = 0;
56
318
  try {
57
319
  for await (const chunk of response.body) {
58
- writer.write(chunk);
320
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
321
+ bytes += buf.length;
322
+ for (const hash of hashStates.values()) hash.update(buf);
323
+ if (!writer.write(buf)) await once(writer, "drain");
59
324
  }
60
325
  await new Promise((resolve, reject) => {
61
326
  writer.end((error) => (error ? reject(error) : resolve()));
@@ -64,10 +329,27 @@ async function downloadHttp(url, destFile, log) {
64
329
  writer.destroy();
65
330
  throw error;
66
331
  }
332
+ const digests = {};
333
+ for (const [algo, hash] of hashStates) digests[algo] = hash.digest("hex");
334
+ log(`HTTP 下载完成:${bytes} 字节${hashStates.size > 0 ? `,已流式计算 ${[...hashStates.keys()].join("/")}` : ""}`);
335
+ return { bytes, digests };
336
+ }
337
+
338
+ /** 对已落盘文件做流式摘要(P2P 路径在调用方给了期望时用)。 */
339
+ async function hashFile(file, hashes) {
340
+ const hashStates = new Map(hashes.map((entry) => [entry.algo, createHash(entry.algo)]));
341
+ let bytes = 0;
342
+ for await (const chunk of createReadStream(file)) {
343
+ bytes += chunk.length;
344
+ for (const hash of hashStates.values()) hash.update(chunk);
345
+ }
346
+ const digests = {};
347
+ for (const [algo, hash] of hashStates) digests[algo] = hash.digest("hex");
348
+ return { bytes, digests };
67
349
  }
68
350
 
69
351
  /** 通过外部下载器(aria2c)下载 http/magnet/torrent。 */
70
- function downloadExternal(tool, url, destDir, log) {
352
+ function downloadExternal(tool, url, destDir, log, timeoutMs) {
71
353
  return new Promise((resolve) => {
72
354
  const args = ["--dir", destDir, "--out", "p2p-download.bin", "--max-connection-per-server=16", "--seed-time=0", url];
73
355
  const child = spawn(tool, args, { windowsHide: true });
@@ -81,32 +363,32 @@ function downloadExternal(tool, url, destDir, log) {
81
363
  } catch {
82
364
  // ignore
83
365
  }
84
- resolve(makeResult("failed", null, "外部下载器超时(10 分钟)"));
85
- }, 10 * 60 * 1000);
366
+ resolve(makeResult("failed", null, `外部下载器超时(${humanMs(timeoutMs)})`, "p2p-timeout"));
367
+ }, timeoutMs);
86
368
  child.on("error", (error) => {
87
369
  clearTimeout(timer);
88
- resolve(makeResult("failed", null, `无法启动 ${tool}: ${error.message}`));
370
+ resolve(makeResult("failed", null, `无法启动 ${tool}: ${error.message}`, "p2p-failed"));
89
371
  });
90
372
  child.on("close", (code) => {
91
373
  clearTimeout(timer);
92
374
  const file = join(destDir, "p2p-download.bin");
93
375
  if (code === 0) {
94
- resolve(makeResult("downloaded", file, `已通过 ${tool} 下载`));
376
+ resolve(makeResult("downloaded", file, `已通过 ${tool} 下载`, "ok"));
95
377
  } else {
96
- resolve(makeResult("failed", null, `${tool} 退出码 ${code}${stderrTail ? `:${stderrTail}` : ""}`));
378
+ resolve(makeResult("failed", null, `${tool} 退出码 ${code}${stderrTail ? `:${stderrTail}` : ""}`, "p2p-failed"));
97
379
  }
98
380
  });
99
381
  });
100
382
  }
101
383
 
102
384
  /** 通过内置 webtorrent 下载 magnet/.torrent。 */
103
- function downloadWebTorrent(url, destDir, log) {
385
+ function downloadWebTorrent(url, destDir, log, timeoutMs) {
104
386
  return new Promise((resolve) => {
105
387
  let WebTorrent;
106
388
  try {
107
389
  WebTorrent = require("webtorrent");
108
390
  } catch {
109
- resolve(makeResult("failed", null, `未安装内置 P2P 客户端。请任选其一:\n1) 安装 aria2c 后重试(支持 HTTP/磁力/种子)\n2) 用比特彗星(BitComet)等下载工具手动导入:${url}\n3) 在插件目录执行 npm install webtorrent 启用内置 P2P`));
391
+ resolve(makeResult("failed", null, `未安装内置 P2P 客户端。请任选其一:\n1) 安装 aria2c 后重试(支持 HTTP/磁力/种子)\n2) 用比特彗星(BitComet)等下载工具手动导入:${url}\n3) 在插件目录执行 npm install webtorrent 启用内置 P2P`, "p2p-unavailable"));
110
392
  return;
111
393
  }
112
394
  const client = new WebTorrent({ dht: false });
@@ -116,8 +398,8 @@ function downloadWebTorrent(url, destDir, log) {
116
398
  } catch {
117
399
  // ignore
118
400
  }
119
- resolve(makeResult("failed", null, "P2P 下载超时(10 分钟,可能无做种者)"));
120
- }, 10 * 60 * 1000);
401
+ resolve(makeResult("failed", null, `P2P 下载超时(${humanMs(timeoutMs)},可能无做种者)`, "p2p-timeout"));
402
+ }, timeoutMs);
121
403
  client.on("error", (error) => {
122
404
  clearTimeout(timer);
123
405
  try {
@@ -125,7 +407,7 @@ function downloadWebTorrent(url, destDir, log) {
125
407
  } catch {
126
408
  // ignore
127
409
  }
128
- resolve(makeResult("failed", null, `P2P 客户端错误: ${error.message}`));
410
+ resolve(makeResult("failed", null, `P2P 客户端错误: ${error.message}`, "p2p-failed"));
129
411
  });
130
412
  try {
131
413
  client.add(url, { path: destDir }, (torrent) => {
@@ -139,11 +421,11 @@ function downloadWebTorrent(url, destDir, log) {
139
421
  } catch {
140
422
  // ignore
141
423
  }
142
- resolve(makeResult("downloaded", file, "已通过内置 P2P 下载"));
424
+ resolve(makeResult("downloaded", file, "已通过内置 P2P 下载", "ok"));
143
425
  });
144
426
  torrent.on("error", (error) => {
145
427
  clearTimeout(timer);
146
- resolve(makeResult("failed", null, `P2P 种子错误: ${error.message}`));
428
+ resolve(makeResult("failed", null, `P2P 种子错误: ${error.message}`, "p2p-failed"));
147
429
  });
148
430
  });
149
431
  } catch (error) {
@@ -153,43 +435,158 @@ function downloadWebTorrent(url, destDir, log) {
153
435
  } catch {
154
436
  // ignore
155
437
  }
156
- resolve(makeResult("failed", null, `P2P 添加种子失败: ${error.message}`));
438
+ resolve(makeResult("failed", null, `P2P 添加种子失败: ${error.message}`, "p2p-failed"));
157
439
  }
158
440
  });
159
441
  }
160
442
 
443
+ // ---------- 统一入口 ----------
444
+
445
+ /** 创建本次下载的临时目录(门禁拒绝时不会创建,便于证明「没有碰网络/文件」)。 */
446
+ function makeDestDir() {
447
+ const destDir = join(tmpdir(), `dsh-dl-${process.pid}-${randomUUID()}`);
448
+ mkdirSync(destDir, { recursive: true });
449
+ return destDir;
450
+ }
451
+
452
+ /** 归一超时参数(非法值回落默认)。 */
453
+ function normalizeTimeoutMs(value, fallback) {
454
+ const n = Number(value);
455
+ if (!Number.isFinite(n) || n <= 0) return fallback;
456
+ return Math.min(Math.max(Math.floor(n), 100), 60 * 60 * 1000);
457
+ }
458
+
161
459
  /**
162
- * 下载一个链接到临时目录。
163
- * @param url - http(s) / magnet / .torrent 链接。
164
- * @param log - 日志函数。
165
- * @returns {Promise<{status, file, message}>}
460
+ * 下载一个链接到临时目录(带完整性门禁)。
461
+ *
462
+ * @param {string} url - http(s) / magnet / .torrent 链接。
463
+ * @param {(line: string) => void} [log] - 日志函数。
464
+ * @param {object} [options] - 安全选项(全部可选,缺省即最严格):
465
+ * @param {{integrity?: string, shasum?: string, size?: number}} [options.expect]
466
+ * npm 风格内容期望:`integrity` 为 SRI(如 `sha512-<base64>`,可多算法空格分隔,取最强可解析者);
467
+ * `shasum` 为 npm 的 `dist.shasum`(sha1,十六进制或等价 base64);`size` 为字节数(给了就校验)。
468
+ * 注意:**只有 integrity/shasum 才算「已校验」**,单独给 size 仍按未校验走门禁 2(大小不是内容摘要)。
469
+ * @param {boolean} [options.allowInsecure=false] - 允许明文 `http://`(放行后 message 会标注「未经加密,内容可能被篡改」)。
470
+ * @param {boolean} [options.allowUnverified=false] - 允许「没有内容摘要」的下载(message 会标注「未校验来源」或「仅核对大小」)。
471
+ * @param {number} [options.p2pTimeoutMs] - P2P 下载超时(默认 10 分钟;主要给测试/快速探测用)。
472
+ * @returns {Promise<{status: "downloaded"|"blocked"|"failed", file: string|null, message: string|null, code: string|null}>}
166
473
  */
167
- export async function downloadUrl(url, log = () => {}) {
474
+ export async function downloadUrl(url, log = () => {}, options = {}) {
475
+ const opts = options !== null && typeof options === "object" ? options : {};
168
476
  const kind = classifyUrl(url);
169
- if (kind === "unknown") return makeResult("failed", null, `不支持的下载链接:${url}`);
170
- const destDir = join(tmpdir(), `dsh-dl-${process.pid}-${randomUUID()}`);
171
- try {
172
- mkdirSync(destDir, { recursive: true });
173
- } catch {
174
- // ignore
477
+ if (kind === "unknown") return makeResult("failed", null, `不支持的下载链接:${shortenUrl(url)}`, "unsupported-url");
478
+
479
+ const allowInsecure = opts.allowInsecure === true;
480
+ const allowUnverified = opts.allowUnverified === true;
481
+ const p2pTimeoutMs = normalizeTimeoutMs(opts.p2pTimeoutMs, P2P_TIMEOUT_MS);
482
+
483
+ // 门禁 1:明文 HTTP(连接未加密 -> 内容可在传输中被篡改)
484
+ if (/^http:\/\//i.test(url) && !allowInsecure) {
485
+ const message = `已拒绝明文 HTTP 链接:${shortenUrl(url)}。连接未加密,下载内容可能在传输中被篡改或劫持,无法证明与发布者声明一致。如确需下载,请显式传入 allowInsecure: true;该链接未经加密,内容可能被篡改。`;
486
+ log(message);
487
+ return makeResult("blocked", null, message, "insecure-url");
488
+ }
489
+
490
+ // 期望解析:给了期望就必须能执行;期望本身坏了就失败关闭(绝不当成「没给」)
491
+ const plan = buildVerificationPlan(opts.expect);
492
+ if (plan.problems.length > 0) {
493
+ const message = `未开始下载:期望的校验信息无法使用(${plan.problems.join(";")})。已中止,未下载任何文件。`;
494
+ log(message);
495
+ return makeResult("failed", null, message, "invalid-expect");
496
+ }
497
+ const usable = plan.hashes.length > 0; // 「可用校验」只认内容摘要:size 不是摘要(见门禁 2)
498
+ const sizeOnly = !usable && plan.size !== null;
499
+ const isP2P = kind === "magnet" || kind === "torrent";
500
+
501
+ // 门禁 2:无从校验(没有内容摘要)
502
+ if (!usable && !allowUnverified) {
503
+ let message;
504
+ if (isP2P) {
505
+ message = `已拒绝未校验的 P2P 下载(${kind}):P2P 内容无法校验 —— 没有可与发布者声明比对的摘要,无法发现投毒或替换。放行方式:显式传入 allowUnverified: true(接受未校验来源),或改用能提供摘要的 HTTPS 直链并在 expect.integrity/expect.shasum 里给出摘要。`;
506
+ } else if (sizeOnly) {
507
+ // 只给 size:字节数不是内容摘要,控制内容的一方可轻易补齐相同长度 -> 等同于未校验
508
+ message = `已拒绝未校验的下载:${shortenUrl(url)} 只给了大小(${plan.size} 字节),大小不是内容摘要 —— 控制内容的一方补齐相同长度即可通过,无法证明下载物与发布者声明一致(CWE-494)。放行方式:改用 npm 的 dist.integrity(SRI,如 sha512-<base64>)或 dist.shasum(sha1)作为 expect.integrity / expect.shasum;确实拿不到摘要时,显式传入 allowUnverified: true(回执只标注「仅核对大小,未校验内容摘要」)。`;
509
+ } else {
510
+ message = `已拒绝未校验的下载:${shortenUrl(url)} 未提供任何内容期望(expect.integrity / expect.shasum / expect.size),无法确认下载物与发布者声明一致,存在供应链投毒(CWE-494)风险。放行方式:调用方传入 npm 的 dist.integrity(SRI,如 sha512-<base64>)或 dist.shasum(sha1)作为 expect.integrity / expect.shasum;确实拿不到摘要时,显式传入 allowUnverified: true(接受未校验来源)。`;
511
+ }
512
+ log(message);
513
+ return makeResult("blocked", null, message, "unverified");
175
514
  }
515
+
516
+ const destDir = makeDestDir();
517
+
176
518
  if (kind === "http") {
177
519
  const destFile = join(destDir, "package.tgz");
520
+ log(`${usable ? "校验下载" : sizeOnly ? "下载(仅核对大小,不校验内容摘要)" : "下载"}:${shortenUrl(url)}`);
521
+ let outcome;
178
522
  try {
179
- await downloadHttp(url, destFile, log);
180
- return makeResult("downloaded", destFile, "已通过 HTTP 直链下载");
523
+ outcome = await downloadHttp(url, destFile, log, plan.hashes, allowInsecure);
181
524
  } catch (error) {
182
- return makeResult("failed", null, `HTTP 下载失败: ${error instanceof Error ? error.message : String(error)}`);
525
+ safeUnlink(destFile);
526
+ if (error instanceof BlockedError) {
527
+ log(error.message);
528
+ return makeResult("blocked", null, error.message, error.code);
529
+ }
530
+ return makeResult("failed", null, `HTTP 下载失败: ${error instanceof Error ? error.message : String(error)}`, "download-failed");
183
531
  }
532
+ const verified = verifyDownload(outcome, plan);
533
+ if (!verified.ok) {
534
+ // 校验失败必须删掉已下载文件,避免未校验内容留在磁盘上被误用
535
+ safeUnlink(destFile);
536
+ log(verified.message);
537
+ return makeResult("failed", null, verified.message, verified.code);
538
+ }
539
+ const notes = [];
540
+ if (verified.verifiedAlgos.length > 0) notes.push(`已通过 ${verified.verifiedAlgos.join("/")} 摘要校验`);
541
+ // 有摘要时 size 是第二重校验;只有 size 时不能写成「校验通过」,只能如实写「仅核对大小」
542
+ if (plan.size !== null) {
543
+ notes.push(verified.verifiedAlgos.length > 0
544
+ ? `大小 ${outcome.bytes} 字节符合期望`
545
+ : `仅核对大小 ${outcome.bytes} 字节,未校验内容摘要(调用方显式放行 allowUnverified)`);
546
+ } else if (!usable) {
547
+ notes.push("未校验来源(调用方显式放行 allowUnverified)");
548
+ }
549
+ if (allowInsecure && /^http:\/\//i.test(url)) notes.push("明文 HTTP 未经加密,内容可能被篡改");
550
+ const message = `已通过 HTTP 直链下载${notes.length > 0 ? `(${notes.join(";")})` : ""}`;
551
+ return makeResult("downloaded", destFile, message, "ok");
184
552
  }
553
+
185
554
  // magnet / torrent:优先外部下载器(aria2c),否则内置 webtorrent
186
555
  const external = detectExternal();
556
+ let result;
187
557
  if (external !== null) {
188
558
  log(`使用外部下载器 ${external} 下载 P2P 链接`);
189
- return await downloadExternal(external, url, destDir, log);
559
+ result = await downloadExternal(external, url, destDir, log, p2pTimeoutMs);
560
+ } else {
561
+ log("未检测到外部下载器(aria2c),使用内置 webtorrent 下载 P2P 链接");
562
+ result = await downloadWebTorrent(url, destDir, log, p2pTimeoutMs);
563
+ }
564
+ if (result.status !== "downloaded" || result.file === null) return result;
565
+ // 给了期望就照样校验 P2P 产物(比门禁放行更严格)
566
+ if (plan.hashes.length > 0 || plan.size !== null) {
567
+ let outcome;
568
+ try {
569
+ outcome = await hashFile(result.file, plan.hashes);
570
+ } catch (error) {
571
+ safeUnlink(result.file);
572
+ return makeResult("failed", null, `P2P 产物校验失败: ${error instanceof Error ? error.message : String(error)}`, "integrity-mismatch");
573
+ }
574
+ const verified = verifyDownload(outcome, plan);
575
+ if (!verified.ok) {
576
+ safeUnlink(result.file);
577
+ log(verified.message);
578
+ return makeResult("failed", null, verified.message, verified.code);
579
+ }
580
+ const notes = [];
581
+ if (verified.verifiedAlgos.length > 0) notes.push(`已通过 ${verified.verifiedAlgos.join("/")} 摘要校验`);
582
+ if (plan.size !== null) {
583
+ notes.push(verified.verifiedAlgos.length > 0
584
+ ? `大小 ${outcome.bytes} 字节符合期望`
585
+ : `仅核对大小 ${outcome.bytes} 字节,未校验内容摘要(调用方显式放行 allowUnverified)`);
586
+ }
587
+ return decorate(result, `(${notes.join(";")})`);
190
588
  }
191
- log("未检测到外部下载器(aria2c),使用内置 webtorrent 下载 P2P 链接");
192
- return await downloadWebTorrent(url, destDir, log);
589
+ return decorate(result, "(未校验来源:调用方显式放行 allowUnverified;P2P 内容无法校验)");
193
590
  }
194
591
 
195
592
  /** 下载完成后清理临时文件。 */