dsh-drydock 1.0.2 → 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
@@ -16,8 +16,12 @@ const require = createRequire(import.meta.url);
16
16
  *
17
17
  * 安全模型(CWE-494,配合 GitHub PR #4 的供应链加固;本文件负责「下载物完整性」这一环):
18
18
  * 门禁 1 `allowInsecure`(默认 false):明文 `http://` 默认拒绝 —— 连接不加密,内容可在传输中被篡改/劫持。
19
- * 门禁 2 `allowUnverified`(默认 false):没有任何内容期望(integrity/shasum/size)的下载默认拒绝 ——
20
- * 无法证明下载物与发布者声明一致;P2P(magnet/.torrent)没有可比的摘要,同样默认拒绝。
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)没有可比的摘要,同样默认拒绝。
21
25
  * 门禁 3 校验执行(只要给了期望就是强制):下载完成即校验;摘要或大小不匹配 -> 删除已下载文件 + 失败。
22
26
  *
23
27
  * 返回值恒为 `{ status, file, message, code }`:
@@ -248,21 +252,66 @@ function detectExternal() {
248
252
 
249
253
  // ---------- 下载实现 ----------
250
254
 
255
+ /** 重定向跳数上限(含相对 Location)。 */
256
+ const MAX_REDIRECTS = 5;
257
+
258
+ /** HTTP 3xx 才算重定向(其余交给下面的状态码判定)。 */
259
+ function isRedirectStatus(status) {
260
+ return status >= 300 && status < 400;
261
+ }
262
+
251
263
  /**
252
264
  * HTTP(S) 直链下载:fetch 流式写盘,同时**边写边算**摘要(不把响应体整体读进内存)。
265
+ *
266
+ * 重定向用 `redirect:"manual"` 自己逐跳跟随:原生 `redirect:"follow"` 会把
267
+ * `https→http→https` 这样的中间降级直接抹平,只能看到最终 URL,降级就漏检了(B 报告 S4-2)。
268
+ * 跨 host 不禁止(CDN 正常跳转),但每一跳都要过协议门禁;最终落盘仍按调用方给的摘要/大小校验。
253
269
  * @returns `{bytes, digests}`:实际字节数与各算法摘要(hex)。
254
270
  */
255
271
  async function downloadHttp(url, destFile, log, hashes, allowInsecure) {
256
- const response = await fetch(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS), redirect: "follow" });
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
+ }
257
313
  if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`);
258
314
  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
315
  const hashStates = new Map(hashes.map((entry) => [entry.algo, createHash(entry.algo)]));
267
316
  const writer = createWriteStream(destFile);
268
317
  let bytes = 0;
@@ -416,8 +465,9 @@ function normalizeTimeoutMs(value, fallback) {
416
465
  * @param {{integrity?: string, shasum?: string, size?: number}} [options.expect]
417
466
  * npm 风格内容期望:`integrity` 为 SRI(如 `sha512-<base64>`,可多算法空格分隔,取最强可解析者);
418
467
  * `shasum` 为 npm 的 `dist.shasum`(sha1,十六进制或等价 base64);`size` 为字节数(给了就校验)。
468
+ * 注意:**只有 integrity/shasum 才算「已校验」**,单独给 size 仍按未校验走门禁 2(大小不是内容摘要)。
419
469
  * @param {boolean} [options.allowInsecure=false] - 允许明文 `http://`(放行后 message 会标注「未经加密,内容可能被篡改」)。
420
- * @param {boolean} [options.allowUnverified=false] - 允许「没有任何内容期望」的下载(message 会标注「未校验来源」)。
470
+ * @param {boolean} [options.allowUnverified=false] - 允许「没有内容摘要」的下载(message 会标注「未校验来源」或「仅核对大小」)。
421
471
  * @param {number} [options.p2pTimeoutMs] - P2P 下载超时(默认 10 分钟;主要给测试/快速探测用)。
422
472
  * @returns {Promise<{status: "downloaded"|"blocked"|"failed", file: string|null, message: string|null, code: string|null}>}
423
473
  */
@@ -444,14 +494,21 @@ export async function downloadUrl(url, log = () => {}, options = {}) {
444
494
  log(message);
445
495
  return makeResult("failed", null, message, "invalid-expect");
446
496
  }
447
- const usable = plan.size !== null || plan.hashes.length > 0;
497
+ const usable = plan.hashes.length > 0; // 「可用校验」只认内容摘要:size 不是摘要(见门禁 2)
498
+ const sizeOnly = !usable && plan.size !== null;
448
499
  const isP2P = kind === "magnet" || kind === "torrent";
449
500
 
450
- // 门禁 2:无从校验(无任何内容期望)
501
+ // 门禁 2:无从校验(没有内容摘要)
451
502
  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(接受未校验来源)。`;
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
+ }
455
512
  log(message);
456
513
  return makeResult("blocked", null, message, "unverified");
457
514
  }
@@ -460,7 +517,7 @@ export async function downloadUrl(url, log = () => {}, options = {}) {
460
517
 
461
518
  if (kind === "http") {
462
519
  const destFile = join(destDir, "package.tgz");
463
- log(`${plan.hashes.length > 0 ? "校验下载" : "下载"}:${shortenUrl(url)}`);
520
+ log(`${usable ? "校验下载" : sizeOnly ? "下载(仅核对大小,不校验内容摘要)" : "下载"}:${shortenUrl(url)}`);
464
521
  let outcome;
465
522
  try {
466
523
  outcome = await downloadHttp(url, destFile, log, plan.hashes, allowInsecure);
@@ -481,8 +538,14 @@ export async function downloadUrl(url, log = () => {}, options = {}) {
481
538
  }
482
539
  const notes = [];
483
540
  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)");
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
+ }
486
549
  if (allowInsecure && /^http:\/\//i.test(url)) notes.push("明文 HTTP 未经加密,内容可能被篡改");
487
550
  const message = `已通过 HTTP 直链下载${notes.length > 0 ? `(${notes.join(";")})` : ""}`;
488
551
  return makeResult("downloaded", destFile, message, "ok");
@@ -516,7 +579,11 @@ export async function downloadUrl(url, log = () => {}, options = {}) {
516
579
  }
517
580
  const notes = [];
518
581
  if (verified.verifiedAlgos.length > 0) notes.push(`已通过 ${verified.verifiedAlgos.join("/")} 摘要校验`);
519
- if (plan.size !== null) notes.push(`大小 ${outcome.bytes} 字节符合期望`);
582
+ if (plan.size !== null) {
583
+ notes.push(verified.verifiedAlgos.length > 0
584
+ ? `大小 ${outcome.bytes} 字节符合期望`
585
+ : `仅核对大小 ${outcome.bytes} 字节,未校验内容摘要(调用方显式放行 allowUnverified)`);
586
+ }
520
587
  return decorate(result, `(${notes.join(";")})`);
521
588
  }
522
589
  return decorate(result, "(未校验来源:调用方显式放行 allowUnverified;P2P 内容无法校验)");