dsh-drydock 1.0.1 → 1.0.2

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