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/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as nodeModule from "node:module";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync, appendFileSync, copyFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync, appendFileSync, copyFileSync, createReadStream } from "node:fs";
3
3
  import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { spawn } from "node:child_process";
@@ -7,6 +7,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
7
7
  import { basename, dirname, join } from "node:path";
8
8
  import { tmpdir } from "node:os";
9
9
  import { fileURLToPath } from "node:url";
10
+ import { gunzipSync } from "node:zlib";
10
11
  import { isMap, isSeq, parseDocument } from "yaml";
11
12
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
12
13
  import { z } from "zod";
@@ -329,22 +330,251 @@ const HISTORY_MAX = 20;
329
330
  const AUTO_QUARANTINE_STREAK = 2;
330
331
  /** 来源标签(手动覆盖的合法值):npm / github / local / builtin。 */
331
332
  const SOURCE_LABELS = new Set(["npm", "github", "local", "builtin"]);
333
+ // 内置源只声明"名字/URL/类型":official 与 authoritative 一律由 normalizeSourceRecord 按白名单判定
334
+ // (所以这里不再写 official —— 那正是 1.0.2 允许客户端/侧车自报 official 的同一个来源)。
332
335
  const DEFAULT_SOURCES = [
333
- { name: "官方源 (npm)", url: "https://registry.npmjs.org", enabled: true, official: true, type: "registry" },
334
- { name: "插件超市 (dshfind)", url: "https://dshfind.com/zh/plugins", enabled: true, official: false, type: "dshfind" },
335
- { name: "GitHub 官方仓库", url: "https://github.com/deepseek-ai/deepseek-harness", enabled: false, official: true, type: "github" },
336
- { name: "npmmirror 镜像", url: "https://registry.npmmirror.com", enabled: false, official: false, type: "registry" }
336
+ { name: "官方源 (npm)", url: "https://registry.npmjs.org", enabled: true, type: "registry" },
337
+ { name: "GitHub 官方仓库", url: "https://github.com/deepseek-ai/deepseek-harness", enabled: false, type: "github" },
338
+ { name: "npmmirror 镜像", url: "https://registry.npmmirror.com", enabled: false, type: "registry" }
337
339
  ];
338
340
 
339
- /** 归一化源类型。 */
341
+ /**
342
+ * 1.0.3 安全修复(A 报告 S1)——**权威源白名单**。
343
+ *
344
+ * 只有内置的 npm 官方与 npmmirror 镜像默认属于权威层;`official` 也**只**按这个白名单判定,
345
+ * 客户端/侧车自报的 official 一律忽略。1.0.2 允许请求体带 `official:true`,再配合
346
+ * `normalizeSourceType` 把任何非 github 源归一成 registry —— 于是"加一个 http 源"
347
+ * 就接管了版本裁决(它返回的 dist-tags 直接决定 pnpm add 的版本与 tarball 来源)。
348
+ * URL 按规范化后比较(忽略结尾 `/`),避免 `https://registry.npmjs.org/` 之类绕过。
349
+ */
350
+ const AUTHORITATIVE_SOURCE_URLS = new Set(["https://registry.npmjs.org", "https://registry.npmmirror.com"]);
351
+ /** 下载目录 provenance:只保留最近 50 条、7 天内有效(过期记录自动清掉)。 */
352
+ const PENDING_DOWNLOAD_MAX = 50;
353
+ const PENDING_DOWNLOAD_TTL_MS = 7 * 24 * 60 * 60 * 1000;
354
+ /** 只有 @deepseek-ai/* 允许走 dist-tags.next 轨道(A 报告 S3);其余包只认 latest。 */
355
+ const DEEPSEEK_SCOPE_RE = /^@deepseek-ai\//;
356
+
357
+ /** URL 规范化:去首尾空白与结尾 `/`(白名单比较与源去重都走它)。 */
358
+ function normalizeSourceUrl(url) {
359
+ return String(url ?? "").trim().replace(/\/+$/, "");
360
+ }
361
+
362
+ /** 明文 http 源:传输可被中间人替换,默认只能当兜底。 */
363
+ function isInsecureSourceUrl(url) {
364
+ return /^http:\/\//i.test(String(url ?? ""));
365
+ }
366
+
367
+ /** 是否内置权威源(npm 官方 / npmmirror)。 */
368
+ function isBuiltinAuthoritativeUrl(url) {
369
+ return AUTHORITATIVE_SOURCE_URLS.has(normalizeSourceUrl(url));
370
+ }
371
+
372
+ /**
373
+ * 归一化单个更新源 —— 服务端唯一可信入口。
374
+ *
375
+ * official / authoritative / insecure 全部由这里判定,**绝不采信调用方自报的 official**:
376
+ * · 内置白名单 URL → official:true、authoritative:true;
377
+ * · 其它源默认 authoritative:false(custom 层,只在权威源拿不到版本时兜底);
378
+ * · 显式 `authoritative:true` 是"信任升级";若源是明文 http,还必须 `allowInsecure:true`,
379
+ * 否则降级为 false,并把原因写进 note 返回给调用方(不静默)。
380
+ */
381
+ function normalizeSourceRecord(raw) {
382
+ if (raw === null || typeof raw !== "object" || typeof raw.url !== "string") return null;
383
+ const url = normalizeSourceUrl(raw.url);
384
+ if (!/^https?:\/\//i.test(url)) return null;
385
+ const insecure = isInsecureSourceUrl(url);
386
+ const builtin = isBuiltinAuthoritativeUrl(url);
387
+ let authoritative = builtin;
388
+ let note = null;
389
+ if (!builtin && raw.authoritative === true) {
390
+ if (insecure && raw.allowInsecure !== true) {
391
+ authoritative = false;
392
+ note = "该源是明文 http://,升为权威需同时显式确认 allowInsecure:true;本次已降级为仅兜底(custom 层),不参与权威版本裁决。";
393
+ } else {
394
+ authoritative = true;
395
+ }
396
+ }
397
+ const name = (typeof raw.name === "string" ? raw.name.trim() : "").slice(0, 64) || url;
398
+ return {
399
+ name,
400
+ url,
401
+ enabled: raw.enabled !== false,
402
+ official: builtin,
403
+ authoritative,
404
+ insecure,
405
+ // 明文源只有"内置白名单"或"显式升权威 + 显式 allowInsecure"才记录放行;
406
+ // 侧车读回时据此重新判定,避免明文放行状态被静默继承。
407
+ allowInsecure: insecure && (builtin || (raw.authoritative === true && raw.allowInsecure === true)),
408
+ type: normalizeSourceType(raw.type),
409
+ ...(note === null ? {} : { note })
410
+ };
411
+ }
412
+
413
+ /** 源变更审计摘要(写入操作历史):前后 URL 集合、权威层、明文源。 */
414
+ function describeSourceChange(before, after) {
415
+ const beforeUrls = (before ?? []).map((s) => s.url);
416
+ const added = after.map((s) => s.url).filter((url) => !beforeUrls.includes(url));
417
+ const removed = beforeUrls.filter((url) => !after.some((s) => s.url === url));
418
+ const authoritative = after.filter((s) => s.authoritative === true).map((s) => s.name);
419
+ const insecure = after.filter((s) => s.insecure === true).map((s) => s.name);
420
+ return [
421
+ `源 ${beforeUrls.length} → ${after.length}`,
422
+ added.length > 0 ? `新增 ${added.join(", ")}` : "",
423
+ removed.length > 0 ? `移除 ${removed.join(", ")}` : "",
424
+ `权威层:${authoritative.length > 0 ? authoritative.join(", ") : "(无)"}`,
425
+ insecure.length > 0 ? `含明文源:${insecure.join(", ")}` : ""
426
+ ].filter((part) => part !== "").join(";");
427
+ }
428
+
429
+ /** 下载期望归一化:摘要字段只要非空就保留(格式错的留给校验阶段 fail-closed 拒绝),size 可选。 */
430
+ function normalizeDownloadExpect(expect) {
431
+ if (expect === null || typeof expect !== "object") return null;
432
+ const normalized = {};
433
+ if (typeof expect.integrity === "string" && expect.integrity.trim() !== "") {
434
+ normalized.integrity = expect.integrity.trim().toLowerCase();
435
+ } else if (typeof expect.shasum === "string" && expect.shasum.trim() !== "") {
436
+ normalized.shasum = expect.shasum.trim().toLowerCase();
437
+ }
438
+ if (Number.isInteger(expect.size) && expect.size > 0) normalized.size = expect.size;
439
+ return Object.keys(normalized).length > 0 ? normalized : null;
440
+ }
441
+
442
+ /** 读取侧车里的 pendingDownloads(外部可裁剪/损坏,读不到就丢弃)。 */
443
+ function normalizePendingDownloads(value) {
444
+ if (!Array.isArray(value)) return [];
445
+ return value
446
+ .filter((item) => item !== null && typeof item === "object" && typeof item.url === "string" && typeof item.packageName === "string" && typeof item.version === "string")
447
+ .map((item) => ({
448
+ url: item.url,
449
+ packageName: item.packageName,
450
+ version: item.version,
451
+ sourceName: typeof item.sourceName === "string" ? item.sourceName : null,
452
+ expect: normalizeDownloadExpect(item.expect),
453
+ at: typeof item.at === "string" && !Number.isNaN(Date.parse(item.at)) ? item.at : new Date(0).toISOString()
454
+ }))
455
+ .slice(-PENDING_DOWNLOAD_MAX);
456
+ }
457
+
458
+ /** 读 tar 头里的 NUL 结尾字符串。 */
459
+ function readTarString(buffer, offset, length) {
460
+ const slice = buffer.subarray(offset, offset + length);
461
+ const end = slice.indexOf(0);
462
+ const text = (end === -1 ? slice : slice.subarray(0, end)).toString("utf8");
463
+ return text;
464
+ }
465
+
466
+ /**
467
+ * 读取 npm 包归档内 `package/package.json`,返回 {name, version};读不到/不是 npm 归档返回 null。
468
+ * 用 node:zlib 直接解 tar.gz(不新增依赖,也不调外部 tar):downloads 目录的 provenance 判定
469
+ * 必须先知道"这个文件声称自己是哪个包哪个版本",才能去 pendingDownloads 里找来源记录。
470
+ */
471
+ function readArchivePackageManifest(file) {
472
+ let buffer;
473
+ try {
474
+ buffer = gunzipSync(readFileSync(file));
475
+ } catch {
476
+ return null;
477
+ }
478
+ let offset = 0;
479
+ while (offset + 512 <= buffer.length) {
480
+ const header = buffer.subarray(offset, offset + 512);
481
+ // 全零块 = 归档结束
482
+ if (header.every((byte) => byte === 0)) break;
483
+ const rawName = readTarString(header, 0, 100).trim();
484
+ const sizeText = readTarString(header, 124, 12).trim();
485
+ const size = sizeText === "" ? 0 : Number.parseInt(sizeText, 8);
486
+ if (!Number.isFinite(size) || size < 0) return null;
487
+ const type = String.fromCharCode(header[156] === 0 ? 48 : header[156]);
488
+ const name = rawName.replace(/^\.\//, "");
489
+ const dataStart = offset + 512;
490
+ const dataEnd = dataStart + size;
491
+ if (dataEnd > buffer.length) return null;
492
+ // 只认普通文件;PAX/GNU 扩展头(x/g/L)跳过,继续找真正的条目
493
+ if ((type === "0" || type === "\u0000" || type === "") && /(^|\/)package\/package\.json$/.test(name)) {
494
+ try {
495
+ const manifest = JSON.parse(buffer.subarray(dataStart, dataEnd).toString("utf8"));
496
+ if (typeof manifest?.name === "string" && typeof manifest.version === "string" && manifest.name !== "" && manifest.version !== "") {
497
+ return { name: manifest.name, version: manifest.version };
498
+ }
499
+ } catch {
500
+ return null;
501
+ }
502
+ return null;
503
+ }
504
+ offset = dataStart + Math.ceil(size / 512) * 512;
505
+ }
506
+ return null;
507
+ }
508
+
509
+ /**
510
+ * 流式校验归档摘要(expect.integrity / expect.shasum)。
511
+ * - 两者都没有 → `{ok:true, verified:false}`:来源记录本身就是入口凭证,但**不宣称已校验**;
512
+ * 只有 size 不算校验(size 是长度,不是内容摘要)。
513
+ * - 有摘要 → 必须一致,不一致直接拒绝(内容可能被替换,没有任何理由放行)。
514
+ */
515
+ async function verifyArchiveDigest(file, expect) {
516
+ const wanted = [];
517
+ if (typeof expect?.integrity === "string") {
518
+ const match = /^(sha1|sha256|sha512)-([0-9a-f]+)$/i.exec(expect.integrity.trim());
519
+ if (match === null) return { ok: false, verified: false, message: "来源记录里的完整性摘要格式无法识别,已拒绝安装(请重新生成下载链接)。" };
520
+ wanted.push({ algorithm: match[1].toLowerCase(), hex: match[2].toLowerCase() });
521
+ } else if (typeof expect?.shasum === "string") {
522
+ if (!/^[0-9a-f]{40}$/i.test(expect.shasum.trim())) return { ok: false, verified: false, message: "来源记录里的 shasum 格式无法识别,已拒绝安装(请重新生成下载链接)。" };
523
+ wanted.push({ algorithm: "sha1", hex: expect.shasum.trim().toLowerCase() });
524
+ }
525
+ if (wanted.length === 0) return { ok: true, verified: false, message: null };
526
+ const hashes = new Map(wanted.map((item) => [item.algorithm, createHash(item.algorithm)]));
527
+ await new Promise((resolve, reject) => {
528
+ const stream = createReadStream(file);
529
+ stream.on("data", (chunk) => {
530
+ for (const hash of hashes.values()) hash.update(chunk);
531
+ });
532
+ stream.on("error", reject);
533
+ stream.on("end", resolve);
534
+ });
535
+ for (const item of wanted) {
536
+ const actual = hashes.get(item.algorithm).digest("hex");
537
+ if (actual !== item.hex) {
538
+ return {
539
+ ok: false,
540
+ verified: false,
541
+ message: `归档摘要不匹配(${item.algorithm}:期望 ${item.hex.slice(0, 16)}…,实际 ${actual.slice(0, 16)}…),内容可能被篡改,已拒绝安装。`
542
+ };
543
+ }
544
+ }
545
+ return { ok: true, verified: true, message: null };
546
+ }
547
+
548
+ /**
549
+ * 安全修复(CWE-494 供应链投毒)——dshfind(插件超市)源**整体移除**,不再提供:
550
+ * 它把 `topic:dsh-plugin <包名>` 的 GitHub 搜索结果里**第一个同名仓库**当发布源
551
+ * (不校验 owner/repo、不比对 npm 登记的 repository、不查 provenance),
552
+ * 伪造一个同名仓库 + v999.0.0 release 就能在默认更新流程里赢过官方发布,
553
+ * 宿主再从该仓库取 release 资产/ torrent / codeload 交给下载器安装。
554
+ *
555
+ * 为什么不是"留着但默认关":它能带来的**唯一**增量是「包在 npm 上有、但只在 GitHub
556
+ * 发新版本」这一小类;而这类发布恰恰没有 npm 登记可做信任锚点,provenance 校验必然
557
+ * 拒掉 —— 也就是说加固后的 dshfind 对这类包等于不工作,对 registry 能管的包又纯属
558
+ * 重复。留一个"看起来能用、实则要么不安全要么无效"的源,比移除更容易误导用户。
559
+ * registry 源本身给权威版本;GitHub 源是用户显式配置的**固定仓库**,不是搜索出来的
560
+ * 发布源 —— 二者都不需要 dshfind。相关更新流程、缓存与测试夹具已一并删除。
561
+ */
562
+ /** 旧版内置 dshfind 源的残留识别(侧车文件里可能还存着 enabled:true 的条目)。 */
563
+ function isLegacyDshfindSource(source) {
564
+ if (source?.type === "dshfind") return true;
565
+ return /^https?:\/\/(?:www\.)?dshfind\.com(?:\/|$)/i.test(String(source?.url ?? ""));
566
+ }
567
+
568
+ /** 归一化源类型:只剩 registry / github 两类(旧 dshfind 值统一降级为 registry,侧车读取时会先剔除)。 */
340
569
  function normalizeSourceType(type) {
341
- return type === "github" || type === "dshfind" ? type : "registry";
570
+ return type === "github" ? "github" : "registry";
342
571
  }
343
572
 
344
573
  function defaultSidecarState() {
345
574
  return {
346
575
  version: SIDECAR_VERSION,
347
- sources: structuredClone(DEFAULT_SOURCES),
576
+ // 内置源也走服务端归一化:official/authoritative 一律由白名单判定,不沿用常量里的自报值
577
+ sources: DEFAULT_SOURCES.map((source) => normalizeSourceRecord(source)).filter((source) => source !== null),
348
578
  rescue: { autoQuarantine: false },
349
579
  // 来源人工修正:packageName -> 标签(npm / github / local / builtin)
350
580
  overrides: { source: {} },
@@ -354,6 +584,8 @@ function defaultSidecarState() {
354
584
  scenarios: [],
355
585
  // 卸载残留(Windows 文件锁导致的删除失败,下次启动重试)
356
586
  pendingRemovals: [],
587
+ // 下载目录 provenance:本管理器生成过下载链接的期望记录(checkDownloads 的唯一入口凭证)
588
+ pendingDownloads: [],
357
589
  // 自动隔离的连续失败计数:configId -> 次数(跨启动累计,H3)
358
590
  failureStreak: {}
359
591
  };
@@ -395,15 +627,19 @@ function readSidecarState(location) {
395
627
  try {
396
628
  const parsed = JSON.parse(readFileSync(join(location.directory, SIDECAR_FILENAME), "utf8"));
397
629
  if (Array.isArray(parsed?.sources)) {
398
- const sources = parsed.sources
399
- .filter((s) => s !== null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string" && /^https?:\/\//.test(s.url))
400
- .map((s) => ({
401
- name: (s.name.trim() || s.url).slice(0, 64),
402
- url: s.url.trim().replace(/\/+$/, ""),
403
- enabled: s.enabled !== false,
404
- official: s.official === true,
405
- type: normalizeSourceType(s.type)
406
- }));
630
+ const seenUrls = new Set();
631
+ const sources = [];
632
+ for (const s of parsed.sources) {
633
+ if (s === null || typeof s !== "object" || typeof s.name !== "string" || typeof s.url !== "string") continue;
634
+ // 安全修复:旧侧车里的 dshfind 条目直接丢弃 —— 该源的实现已移除,
635
+ // 留着它会被当成 registry 去请求 https://dshfind.com/...(永远 404 还污染版本缓存)。
636
+ if (isLegacyDshfindSource(s)) continue;
637
+ // official/authoritative/insecure 由服务端重新判定:侧车里的自报 official 不作数
638
+ const record = normalizeSourceRecord(s);
639
+ if (record === null || seenUrls.has(record.url)) continue;
640
+ seenUrls.add(record.url);
641
+ sources.push(record);
642
+ }
407
643
  if (sources.length > 0) state.sources = sources;
408
644
  }
409
645
  state.rescue = { autoQuarantine: parsed?.rescue?.autoQuarantine === true };
@@ -432,6 +668,8 @@ function readSidecarState(location) {
432
668
  if (Array.isArray(parsed?.pendingRemovals)) {
433
669
  state.pendingRemovals = parsed.pendingRemovals.filter((p) => typeof p === "string");
434
670
  }
671
+ // 下载目录 provenance 记录(旧侧车没有该字段 → 默认空数组:不认任何历史下载)
672
+ state.pendingDownloads = normalizePendingDownloads(parsed?.pendingDownloads);
435
673
  if (parsed?.failureStreak !== null && typeof parsed?.failureStreak === "object") {
436
674
  for (const [id, count] of Object.entries(parsed.failureStreak)) {
437
675
  if (typeof id === "string" && Number.isInteger(count) && count > 0) state.failureStreak[id] = Math.min(count, 16);
@@ -461,12 +699,12 @@ const VERSION_TTL_MS = 30 * 60 * 1000;
461
699
  * C-02:网络类失败**不允许**写 VERSION_CACHE —— 那等于把网络问题记成「无更新」30 分钟,
462
700
  * 用户网络恢复后点多少次「重试」都不会联网。失败只进这个 30 秒合流窗口,作用仅是让
463
701
  * 同一波并发/连点不重复打网络;任何显式重试(options.force === true)都会绕过它并真正联网。
464
- * 负缓存(VERSION_CACHE 的 latest=null / DSFFIND_SEARCH_CACHE)只允许记确定性结论。
702
+ * 负缓存(VERSION_CACHE 的 latest=null)只允许记确定性结论。
465
703
  */
466
704
  const VERSION_FAILURE_CACHE = new Map();
467
705
  const NEGATIVE_TTL_MS = 30 * 1000;
468
706
  const LATEST_CACHE = new Map();
469
- /** 源限流熔断:403/429 后冷却 10 分钟(github api 与 dshfind 共享键)。 */
707
+ /** 源限流熔断:403/429 后冷却 10 分钟(github api 限流)。 */
470
708
  const SOURCE_COOLDOWN = new Map();
471
709
  const COOLDOWN_MS = 10 * 60 * 1000;
472
710
  /**
@@ -503,9 +741,9 @@ const RUN_FAIL_LIMIT = 5;
503
741
  const REFRESH_BUDGET_DEFAULT_MS = 90 * 1000;
504
742
  let refreshBudgetMs = REFRESH_BUDGET_DEFAULT_MS;
505
743
 
506
- /** 限流冷却键:github/dshfind 共享 api.github.com 配额。 */
744
+ /** 限流冷却键:github 源共用 api.github.com 配额。 */
507
745
  function cooldownKey(source) {
508
- return source?.type === "github" || source?.type === "dshfind" ? "https://api.github.com" : source?.url ?? "";
746
+ return source?.type === "github" ? "https://api.github.com" : source?.url ?? "";
509
747
  }
510
748
 
511
749
  /** 该源是否处于限流冷却期。 */
@@ -611,14 +849,14 @@ function versionFailureText(reason) {
611
849
  }
612
850
 
613
851
  /**
614
- * 统一返回 {version, repo, reason}:repo 仅供 github/dshfind 源下载时使用,
852
+ * 统一返回 {version, repo, reason}:repo 仅供 github 源下载时使用,
615
853
  * reason 见 REASON(C-09:404 与网络异常在下游必须可区分)。
616
854
  */
617
855
  async function fetchLatestVersion(packageName, source, options) {
618
856
  // 同一包最近一次失败的具体原因(timeout/network/not-found)优先于「源级退避」返回:
619
857
  // 两者都不联网,但具体原因更可行动(「网络不可达」比「退避中」更清楚)。失败窗口只有 30 秒。
620
858
  if (options?.force !== true) {
621
- const recentKey = source.type === "dshfind" ? `dshfind\0${packageName}` : `${source.url}\0${packageName}`;
859
+ const recentKey = `${source.url}\0${packageName}`;
622
860
  const recent = VERSION_FAILURE_CACHE.get(recentKey);
623
861
  if (recent !== void 0 && Date.now() - recent.at < NEGATIVE_TTL_MS) return { version: null, repo: null, reason: recent.reason };
624
862
  }
@@ -627,7 +865,7 @@ async function fetchLatestVersion(packageName, source, options) {
627
865
  const inner = await fetchLatestGithubVersion(packageName, source.url, source, options);
628
866
  return { version: inner.version, repo: githubRepoOf(source.url), reason: inner.reason };
629
867
  }
630
- if (source.type === "dshfind") return fetchLatestDshfindVersion(packageName, source, options);
868
+ // 只剩 registry 与 github 两类源(dshfind 已随 CWE-494 修复移除,见 DEFAULT_SOURCES 注释)
631
869
  const key = `${source.url}\0${packageName}`;
632
870
  if (options?.force !== true) {
633
871
  const cached = VERSION_CACHE.get(key);
@@ -649,9 +887,18 @@ async function fetchLatestVersion(packageName, source, options) {
649
887
  });
650
888
  if (response.ok) {
651
889
  const meta = await response.json();
652
- const tags = meta["dist-tags"];
653
- // @deepseek-ai/* 的正式发布走 next 轨道(latest 停留在占位版)
654
- latest = tags?.next ?? tags?.latest ?? null;
890
+ const tags = meta["dist-tags"] ?? {};
891
+ // A 报告 S3:next 轨道只给「@deepseek-ai/* + 内置权威源」。
892
+ // 1.0.2 对所有包一律 `next ?? latest`,于是 RC(例如 drydock 自己的 1.1.0-rc)
893
+ // 会被 compareVersions 当成可升级版本推给用户并 pnpm add;自定义源还能改 next,
894
+ // 等于多一个可操纵字段。其余包只认 latest,且 prerelease(含 `-`)视为无可用版本。
895
+ const trustedNext = DEEPSEEK_SCOPE_RE.test(packageName) && (source.authoritative === true || isBuiltinAuthoritativeUrl(source.url));
896
+ if (trustedNext) {
897
+ latest = tags.next ?? tags.latest ?? null;
898
+ } else {
899
+ const candidate = typeof tags.latest === "string" ? tags.latest : null;
900
+ latest = candidate !== null && !candidate.includes("-") ? candidate : null;
901
+ }
655
902
  // 源明确答复但没有任何可用 tag:确定性「无更新」
656
903
  if (latest === null) reason = REASON.NOT_FOUND;
657
904
  } else if (response.status === 404) {
@@ -700,139 +947,73 @@ async function fetchGitHubRelease(repo) {
700
947
  }
701
948
 
702
949
  /**
703
- * 解析 github / dshfind 源的下载链接:
704
- * 优先 release 资产 .tgz -> .torrent -> release 说明里的 magnet -> codeload 兜底。
705
- * magnet / .torrent 交给通用下载器走 P2P(webtorrent 或本机 aria2c)。
950
+ * 从 GitHub release 资产推导下载校验期望(CWE-494 接线)。
951
+ *
952
+ * GitHub 的 releases API 会为每个资产给出 `digest`(形如 `sha256:<64 hex>`)与 `size`。
953
+ * 有 digest 就转成下载器认的 SRI 形态 `sha256-<64 hex>` 并强制校验;没有 digest 的旧资产
954
+ * 只能返回 null,由调用方决定「显式接受未校验」还是拒绝。
955
+ * @returns {{integrity: string, size?: number}|null}
706
956
  */
707
- async function resolveSourceDownloadUrl(source, best) {
708
- if (source.type === "github") {
709
- const repo = githubRepoOf(source.url) ?? best.repo;
710
- if (repo === null) return null;
711
- const release = await fetchGitHubRelease(repo);
712
- if (release !== null) {
713
- const tgz = (release.assets ?? []).find((a) => /\.(tgz|tar\.gz)$/i.test(a.name ?? ""));
714
- if (tgz?.browser_download_url) return tgz.browser_download_url;
715
- const torrent = (release.assets ?? []).find((a) => /\.torrent$/i.test(a.name ?? ""));
716
- if (torrent?.browser_download_url) return torrent.browser_download_url;
717
- const magnet = /(magnet:\?[^\s"'<>]+)/.exec(release.body ?? "");
718
- if (magnet) return magnet[1];
719
- }
720
- const [owner, repoName] = repo.split("/");
721
- return `https://codeload.github.com/${owner}/${repoName}/tar.gz/refs/tags/v${best.version}`;
722
- }
723
- if (source.type === "dshfind") {
724
- if (best.repo === null) return null;
725
- const release = await fetchGitHubRelease(best.repo);
726
- if (release !== null) {
727
- const tgz = (release.assets ?? []).find((a) => /\.(tgz|tar\.gz)$/i.test(a.name ?? ""));
728
- if (tgz?.browser_download_url) return tgz.browser_download_url;
729
- const torrent = (release.assets ?? []).find((a) => /\.torrent$/i.test(a.name ?? ""));
730
- if (torrent?.browser_download_url) return torrent.browser_download_url;
731
- const magnet = /(magnet:\?[^\s"'<>]+)/.exec(release.body ?? "");
732
- if (magnet) return magnet[1];
733
- }
734
- const [owner, repoName] = best.repo.split("/");
735
- return `https://codeload.github.com/${owner}/${repoName}/tar.gz/refs/tags/v${best.version}`;
736
- }
737
- return null;
957
+ function assetExpectOf(asset) {
958
+ const digest = typeof asset?.digest === "string" ? asset.digest : "";
959
+ const match = /^sha256:([0-9a-f]{64})$/i.exec(digest);
960
+ if (match === null) return null;
961
+ const expected = { integrity: `sha256-${match[1].toLowerCase()}` };
962
+ if (Number.isInteger(asset?.size) && asset.size > 0) expected.size = asset.size;
963
+ return expected;
738
964
  }
739
965
 
740
966
  /**
741
- * 插件超市(dshfind)源:本质是 GitHub dsh-plugin topic 的聚合。
742
- * 按包名搜索 topic 仓库(search API,10 次/分钟限流 —— 结果按包缓存),
743
- * 验证仓库根 package.json 的 name 匹配后取 releases/latest 版本。
967
+ * 解析 github 源的下载目标:release 资产 .tgz -> .torrent -> release 说明里的 magnet -> codeload 兜底。
968
+ * magnet / .torrent 交给通用下载器走 P2P(webtorrent 或本机 aria2c)。
969
+ * 只有 registry 源不是走这里(registry 直接用 pnpm add <pkg>@<version> --registry <url>)。
970
+ *
971
+ * 1.1.0 起返回 `{url, expect, allowUnverified, note}` 而不是裸字符串 —— 下载器
972
+ * (lib/downloader.js)默认对「明文 http / 无从校验 / 摘要不符」一律拒绝(fail-closed),
973
+ * 这里负责把**能校验的就校验**:
974
+ * · release 资产带 digest → 强制校验(expect 非空)
975
+ * · 资产无 digest / .torrent / magnet / codeload 兜底 → 无法校验,显式 allowUnverified
976
+ * 并在 note 里写清原因(UI 展示,用户能看到这次下载没做完整性校验)
977
+ *
978
+ * 已知残余风险(评估见交付说明):codeload 兜底用的是 movable tag
979
+ * `refs/tags/v<version>`,tag 可被重打/移动;更稳的做法是先经 GitHub API 把
980
+ * release.tag_name 解析成 commit SHA,再取 `codeload.../tar.gz/<sha>`。
981
+ * @param source - 更新源(目前只有 github 会走这里)。
982
+ * @param best - 聚合出的最新版本(带 repo / version)。
983
+ * @param options.allowUnverifiedFallback - 配置 `security.unverifiedDownloads === "allow"` 时为 true。
984
+ * 仅在**拿不到摘要**时起作用:false(默认)→ 下载器会 fail-closed 拒绝,并提示怎么开;
985
+ * true → 放行但 note 明确标注未校验。**摘要存在时永远强制校验,这个参数无效。**
986
+ * @returns {Promise<{url: string, expect?: object, allowUnverified?: boolean, note?: string}|null>}
744
987
  */
745
- const DSFFIND_SEARCH_CACHE = new Map();
746
- const DSFFIND_SEARCH_TTL_MS = 60 * 60 * 1000;
747
-
748
- async function fetchLatestDshfindVersion(packageName, source, options) {
749
- const key = `dshfind\0${packageName}`;
750
- if (options?.force !== true) {
751
- const cached = DSFFIND_SEARCH_CACHE.get(key);
752
- if (cached !== void 0 && Date.now() - cached.at < DSFFIND_SEARCH_TTL_MS) return { version: cached.latest, repo: cached.repo, reason: cached.latest === null ? REASON.NOT_FOUND : REASON.OK };
753
- const failure = VERSION_FAILURE_CACHE.get(key);
754
- if (failure !== void 0 && Date.now() - failure.at < NEGATIVE_TTL_MS) return { version: null, repo: null, reason: failure.reason };
755
- } else {
756
- VERSION_FAILURE_CACHE.delete(key);
757
- }
758
- // C-02:只有「搜索成功且没有网络类不确定」才是确定性结论,才允许写 1 小时负缓存。
759
- let result = { version: null, repo: null, reason: REASON.NOT_FOUND };
760
- let uncertain = null;
761
- try {
762
- const query = encodeURIComponent(`topic:dsh-plugin ${packageName}`);
763
- const searchSignal = budgetSignal(10000, options);
764
- if (searchSignal === null) return { version: null, repo: null, reason: REASON.TIMEOUT };
765
- const searchResponse = await fetch(`https://api.github.com/search/repositories?q=${query}&per_page=5&sort=updated`, {
766
- signal: searchSignal,
767
- headers: { "user-agent": "dsh-drydock", accept: "application/vnd.github+json" }
768
- });
769
- if (searchResponse.ok) {
770
- const data = await searchResponse.json();
771
- const repos = data?.items ?? [];
772
- for (const repo of repos) {
773
- const fullName = repo?.full_name;
774
- if (typeof fullName !== "string") continue;
775
- try {
776
- const manifestSignal = budgetSignal(8000, options);
777
- if (manifestSignal === null) {
778
- uncertain = REASON.TIMEOUT;
779
- break;
780
- }
781
- const manifestResponse = await fetch(`https://raw.githubusercontent.com/${fullName}/HEAD/package.json`, {
782
- signal: manifestSignal,
783
- headers: { "user-agent": "dsh-drydock" }
784
- });
785
- if (!manifestResponse.ok) continue;
786
- const manifest = await manifestResponse.json();
787
- if (manifest?.name !== packageName) continue;
788
- const releaseSignal = budgetSignal(8000, options);
789
- if (releaseSignal === null) {
790
- uncertain = REASON.TIMEOUT;
791
- break;
792
- }
793
- const releaseResponse = await fetch(`https://api.github.com/repos/${fullName}/releases/latest`, {
794
- signal: releaseSignal,
795
- headers: { "user-agent": "dsh-drydock", accept: "application/vnd.github+json" }
796
- });
797
- if (!releaseResponse.ok) {
798
- if (releaseResponse.status === 403 || releaseResponse.status === 429) {
799
- markCooldown(source, releaseResponse.status);
800
- uncertain = REASON.BACKOFF;
801
- } else if (releaseResponse.status >= 500) {
802
- uncertain = REASON.NETWORK;
803
- }
804
- // 404:该仓库确实没有 release —— 确定性,继续看下一个候选仓库
805
- continue;
806
- }
807
- const release = await releaseResponse.json();
808
- if (typeof release?.tag_name !== "string") continue;
809
- result = { version: release.tag_name.replace(/^v/, ""), repo: fullName, reason: REASON.OK };
810
- break;
811
- } catch (error) {
812
- uncertain = classifyFetchError(error);
813
- continue;
814
- }
815
- }
816
- } else if (searchResponse.status === 403 || searchResponse.status === 429) {
817
- markCooldown(source, searchResponse.status);
818
- uncertain = REASON.BACKOFF;
819
- } else {
820
- uncertain = REASON.NETWORK;
988
+ async function resolveSourceDownloadUrl(source, best, { allowUnverifiedFallback = false } = {}) {
989
+ if (source.type !== "github") return null;
990
+ const repo = githubRepoOf(source.url) ?? best.repo;
991
+ if (repo === null) return null;
992
+ /** 拿不到摘要时的统一出口:是否放行由调用方(配置)决定,但 note 必须说清后果。 */
993
+ const unverifiable = (url, why) => ({
994
+ url,
995
+ allowUnverified: allowUnverifiedFallback,
996
+ note: allowUnverifiedFallback
997
+ ? `${why},本次下载未做完整性校验(安全策略已设为 allow)。`
998
+ : `${why},按默认安全策略已拒绝下载。如确需继续,请在 profile 的 cordis.patch.yml 里为 dsh-drydock 设置 security.unverifiedDownloads: allow。`
999
+ });
1000
+ const release = await fetchGitHubRelease(repo);
1001
+ if (release !== null) {
1002
+ const tgz = (release.assets ?? []).find((a) => /\.(tgz|tar\.gz)$/i.test(a.name ?? ""));
1003
+ if (tgz?.browser_download_url) {
1004
+ const expect = assetExpectOf(tgz);
1005
+ return expect !== null ? { url: tgz.browser_download_url, expect } : unverifiable(tgz.browser_download_url, "该 release 资产没有摘要(digest)");
821
1006
  }
822
- } catch (error) {
823
- uncertain = classifyFetchError(error);
1007
+ const torrent = (release.assets ?? []).find((a) => /\.torrent$/i.test(a.name ?? ""));
1008
+ if (torrent?.browser_download_url) return unverifiable(torrent.browser_download_url, "该源只提供 .torrent,P2P 内容无法校验完整性");
1009
+ const magnet = /(magnet:\?[^\s"'<>]+)/.exec(release.body ?? "");
1010
+ if (magnet) return unverifiable(magnet[1], "该源只提供磁力链接,P2P 内容无法校验完整性");
824
1011
  }
825
- if (result.reason === REASON.OK || uncertain === null) {
826
- // 确定性结论(拿到版本 / 搜索与候选仓库都明确没有它)→ 允许 1 小时负缓存
827
- DSFFIND_SEARCH_CACHE.set(key, { at: Date.now(), latest: result.version, repo: result.repo });
828
- VERSION_FAILURE_CACHE.delete(key);
829
- if (result.reason === REASON.OK) markSourceSuccess(source, options);
830
- return result;
831
- }
832
- // 网络类不确定:不写 1 小时负缓存,只写 30 秒合流窗口(可被显式重试绕过)
833
- VERSION_FAILURE_CACHE.set(key, { at: Date.now(), reason: uncertain });
834
- if (NETWORK_REASONS.has(uncertain)) markSourceFailure(source, options);
835
- return { version: null, repo: null, reason: uncertain };
1012
+ const [owner, repoName] = repo.split("/");
1013
+ return unverifiable(
1014
+ `https://codeload.github.com/${owner}/${repoName}/tar.gz/refs/tags/v${best.version}`,
1015
+ "该仓库没有可校验的 release 资产,回退到源码归档下载(tag 可被移动)"
1016
+ );
836
1017
  }
837
1018
 
838
1019
  /**
@@ -906,10 +1087,19 @@ async function fetchLatestGithubVersion(packageName, repoUrl, source, options) {
906
1087
  return { version: latest, reason };
907
1088
  }
908
1089
 
909
- /** 在所有启用的源中取最高版本及其来源(并行查询;并列时随机,官方源权重一致)。 */
1090
+ /**
1091
+ * 在所有启用的源中取**可信**的最高版本及其来源(并行查询;并列时随机,源权重一致)。
1092
+ *
1093
+ * 安全修复(CWE-494)——**权威层由服务端判定**:1.0.2 按 `type==="registry"` 分级,
1094
+ * 但 `normalizeSourceType` 把任何非 github 源都归一成 registry,等于"加一个源就进权威层"。
1095
+ * 1.0.3 起由 lib/index.js 的服务端白名单/显式 authoritative 决定 `authoritative`,
1096
+ * 这里只负责把它传给 aggregateLatest:
1097
+ * · 有权威源给出确定版本 → 其它源(哪怕版本号更高)一律不参与,sourceTrust="authoritative";
1098
+ * · 权威源都没给出版本 → 才允许兜底,并标 degraded=true 供 UI 提示「版本来自非权威源」。
1099
+ */
910
1100
  async function fetchLatestAcross(packageName, sources, options) {
911
1101
  const enabled = (sources ?? []).filter((source) => source?.enabled === true);
912
- if (enabled.length === 0) return { version: null, sourceName: null, repo: null, reason: REASON.NO_SOURCE };
1102
+ if (enabled.length === 0) return { version: null, sourceName: null, repo: null, sourceTrust: null, degraded: false, reason: REASON.NO_SOURCE };
913
1103
  const results = await Promise.allSettled(
914
1104
  enabled.map((source) => fetchLatestVersion(packageName, source, options))
915
1105
  );
@@ -918,8 +1108,14 @@ async function fetchLatestAcross(packageName, sources, options) {
918
1108
  return {
919
1109
  version: value?.version ?? null,
920
1110
  sourceName: enabled[index].name,
1111
+ sourceUrl: enabled[index].url ?? null,
921
1112
  repo: value?.repo ?? null,
922
1113
  official: enabled[index].official === true,
1114
+ // 信任分级依据(1.0.3):只认服务端判定的 authoritative。旧夹具/旧调用没带该字段时
1115
+ // 保留 undefined,让 aggregateLatest 退化为 type==="registry" 的兼容语义。
1116
+ ...(typeof enabled[index].authoritative === "boolean" ? { authoritative: enabled[index].authoritative } : {}),
1117
+ // type 仍随结果带出:调用方按它决定安装路径(registry→pnpm / github→下载器)
1118
+ type: normalizeSourceType(enabled[index].type),
923
1119
  // rejected(理论上不会发生)也归为不确定的网络类:绝不冒充「无更新」
924
1120
  reason: value?.reason ?? REASON.NETWORK
925
1121
  };
@@ -1729,6 +1925,11 @@ let PluginManagerPro = (() => {
1729
1925
  // H1:收敛判据修正后,等待只用于「真的会收敛」的情况;0.1.7 引擎只在启动时套用
1730
1926
  // cordis.patch.yml(无文件监听),因此默认值从 8s 收紧到 2.5s,避免白等。
1731
1927
  this.settleTimeoutMs = config.settleTimeoutMs ?? 2500;
1928
+ // CWE-494:下载完整性策略。默认 deny(fail-closed),显式 allow 才放行「无摘要」下载;
1929
+ // 摘要不匹配与明文 http 是硬红线,不受此开关影响。
1930
+ this.security = {
1931
+ unverifiedDownloads: config.security?.unverifiedDownloads === "allow" ? "allow" : "deny"
1932
+ };
1732
1933
  // L9:卸载自身前的自启清理(默认 20s 超时,测试可注入更短的值)
1733
1934
  this.selfPackageDir = typeof config.selfPackageDir === "string" && config.selfPackageDir !== "" ? config.selfPackageDir : null;
1734
1935
  this.autostartTimeoutMs = Number.isFinite(config.autostartTimeoutMs) ? Number(config.autostartTimeoutMs) : 20000;
@@ -1817,23 +2018,29 @@ let PluginManagerPro = (() => {
1817
2018
  getSources() {
1818
2019
  return this.snapshot();
1819
2020
  }
1820
- /** 校验并保存更新源列表,随后立即重新检测所有包的最新版本。 */
2021
+ /**
2022
+ * 校验并保存更新源列表,随后立即重新检测所有包的最新版本。
2023
+ *
2024
+ * 1.0.3(A 报告 S1):所有信任字段由服务端 `normalizeSourceRecord` 判定 ——
2025
+ * 客户端提交的 `official` 被忽略;新增源默认非权威;升权威要显式 `authoritative:true`
2026
+ * (明文 http 还要 `allowInsecure:true`,否则降级并在 note 说明)。
2027
+ * 每次保存都写一条操作历史(前后 URL 集合 / 权威层变化 / 是否含明文源)。
2028
+ */
1821
2029
  async setSources(sources) {
1822
2030
  return await this.serialize(async () => {
2031
+ const before = this.sources.map((source) => ({ ...source }));
1823
2032
  const seen = new Set();
1824
2033
  const normalized = [];
1825
2034
  for (const s of sources ?? []) {
1826
2035
  if (s === null || typeof s !== "object" || typeof s.name !== "string" || typeof s.url !== "string") continue;
1827
- const url = s.url.trim().replace(/\/+$/, "");
1828
- if (!/^https?:\/\//.test(url) || seen.has(url)) continue;
1829
- seen.add(url);
1830
- normalized.push({
1831
- name: (s.name.trim() || url).slice(0, 64),
1832
- url,
1833
- enabled: s.enabled !== false,
1834
- official: s.official === true,
1835
- type: normalizeSourceType(s.type)
1836
- });
2036
+ // 安全修复:旧客户端仍可能提交 dshfind 类型的源 —— 直接丢弃(实现已移除,
2037
+ // 留着只会被当 registry 去请求 https://dshfind.com/...,永远 404)
2038
+ if (isLegacyDshfindSource(s)) continue;
2039
+ // 服务端归一化:official / authoritative / insecure 不采信客户端自报值
2040
+ const record = normalizeSourceRecord(s);
2041
+ if (record === null || seen.has(record.url)) continue;
2042
+ seen.add(record.url);
2043
+ normalized.push(record);
1837
2044
  }
1838
2045
  this.sources = normalized;
1839
2046
  this.sidecar.sources = normalized;
@@ -1843,6 +2050,8 @@ let PluginManagerPro = (() => {
1843
2050
  LATEST_CACHE.clear();
1844
2051
  SOURCE_BACKOFF.clear();
1845
2052
  await writeSidecarState(this.location, this.sidecar);
2053
+ // 变更审计:来源配置属于高影响写操作,前后差异必须留痕(进操作历史)
2054
+ await this.recordHistory("setSources", "更新源配置", describeSourceChange(before, normalized), null, "ok");
1846
2055
  // 全量重检放后台执行:不阻塞保存操作(并行化后约等于最慢源的一次往返)
1847
2056
  void this.refresh().catch((error) => this.log("refresh", `background refresh failed: ${error instanceof Error ? error.message : String(error)}`));
1848
2057
  return this.snapshot();
@@ -2383,7 +2592,7 @@ setTimeout(() => {
2383
2592
  async cleanupOwnAutostart() {
2384
2593
  const skipped = (message) => ({ status: "skipped", exitCode: null, message, command: null });
2385
2594
  const directory = this.ownPackageDirectory();
2386
- if (directory === null) return skipped("无法定位管理器包目录,跳过开机自启清理(可手动执行 dsh-pm-launcher --uninstall)。");
2595
+ if (directory === null) return skipped("无法定位管理器包目录,跳过开机自启清理(可手动执行 dsh-drydock --uninstall)。");
2387
2596
  const script = join(directory, "bin", "open-boot.mjs");
2388
2597
  if (!existsSync(script)) return skipped(`包内没有 bin/open-boot.mjs(旧版本),跳过开机自启清理:${script}`);
2389
2598
  let source = "";
@@ -2909,8 +3118,56 @@ setTimeout(() => {
2909
3118
  getRescueConfig() {
2910
3119
  return { autoQuarantine: this.rescueConfig?.autoQuarantine === true };
2911
3120
  }
3121
+ /**
3122
+ * 宿主准入:把 DSH Connection 的 Host/Origin 校验与浏览器认证应用到本插件的
3123
+ * Web 路由(/rescue、/plugins-launcher)。这两条路由经 webServer.register 直接
3124
+ * 暴露,不经过 /api 桥接;不校验的话,任何能访问 3080 的来源(含跨站页面)
3125
+ * 都能打开救援页并调用救援方法。
3126
+ *
3127
+ * 判定来源与 /api 完全一致(ctx.connection.requestRejection):
3128
+ * undefined → 放行;401 → 未认证;403 → Host/Origin 校验失败。
3129
+ * 宿主没有 Connection 服务(headless / 更早的引擎)时返回 null 保留旧行为,
3130
+ * 只记一次日志——救援页是恢复路径,不应因缺少可选服务而整体不可用。
3131
+ * 判定自身抛错时按拒绝处理(fail-closed),避免「校验坏了就敞开」。
3132
+ */
3133
+ hostAdmissionRejection(req) {
3134
+ let connection;
3135
+ try {
3136
+ connection = this.ctx.get("connection");
3137
+ } catch {
3138
+ connection = void 0;
3139
+ }
3140
+ if (connection === void 0 || typeof connection.requestRejection !== "function") {
3141
+ if (!this.admissionUnavailableLogged) {
3142
+ this.admissionUnavailableLogged = true;
3143
+ this.log("admission", "host admission unavailable (no ctx.connection.requestRejection) — /rescue and /plugins-launcher keep serving unauthenticated (loopback deployments only)");
3144
+ }
3145
+ return null;
3146
+ }
3147
+ try {
3148
+ return connection.requestRejection({ headers: req.headers }) ?? null;
3149
+ } catch (error) {
3150
+ this.log("admission", `check failed: ${error instanceof Error ? error.message : String(error)} — refusing (fail-closed)`);
3151
+ return 403;
3152
+ }
3153
+ }
3154
+ /** 拒绝一次请求:401 未认证 / 403 来源被拒(中文优先,救援场景更好读)。 */
3155
+ rejectForAdmission(res, status) {
3156
+ res.writeHead(status, {
3157
+ "content-type": "text/plain; charset=utf-8",
3158
+ "cache-control": "no-store"
3159
+ });
3160
+ res.end(status === 401
3161
+ ? "未认证:请先在本浏览器打开 DSH 应用(完成 ?token= 登录),再访问 /rescue。\nUnauthorized: open the DSH app in this browser first so it can issue your session cookie.\n"
3162
+ : "已拒绝:主机/来源准入校验失败(Host/Origin admission failed)。\nForbidden: Host/Origin admission failed.\n");
3163
+ }
2912
3164
  /** /rescue 救援页(独立 HTML,不依赖任何客户端插件)。 */
2913
3165
  serveRescue(req, res) {
3166
+ const rejection = this.hostAdmissionRejection(req);
3167
+ if (rejection !== null) {
3168
+ this.rejectForAdmission(res, rejection);
3169
+ return;
3170
+ }
2914
3171
  if (req.method !== "GET" && req.method !== "HEAD") {
2915
3172
  res.writeHead(405);
2916
3173
  res.end();
@@ -2934,8 +3191,13 @@ setTimeout(() => {
2934
3191
  } catch { /* 没有 pid 文件:启动器可能未通过 --ensure/--supervise 启动过 */ }
2935
3192
  return { ok: true, ...launcherUrlFrom({ pidInfo }) };
2936
3193
  }
2937
- /** GET /plugins-launcher → {ok, port, url}(只读,无令牌)。 */
3194
+ /** GET /plugins-launcher → {ok, port, url}(只读,无令牌;同样经过宿主准入)。 */
2938
3195
  serveLauncherInfo(req, res) {
3196
+ const rejection = this.hostAdmissionRejection(req);
3197
+ if (rejection !== null) {
3198
+ this.rejectForAdmission(res, rejection);
3199
+ return;
3200
+ }
2939
3201
  if (req.method !== "GET" && req.method !== "HEAD") {
2940
3202
  res.writeHead(405);
2941
3203
  res.end();
@@ -2957,12 +3219,59 @@ setTimeout(() => {
2957
3219
  return { dir: this.downloadDir() };
2958
3220
  }
2959
3221
  /**
2960
- * 扫描下载目录:新出现的 npm 包归档走「marketInstall 同款校验」后再安装(H4 修复)。
2961
- * 1) 只接受 npm 包归档(.tgz / .tar.gz);.zip 直接拒绝(pnpm 无法作为包安装)
2962
- * 2) 先复制到 profile 内的稳定暂存路径再交给 pnpm(同时规避 Windows cmd 的空白/% 展开面)
2963
- * 3) 装后校验:新装包必须声明 dsh.bundle / dsh.client,且 profile 启动前自检通过
2964
- * 4) 任一环节失败 -> 回滚(pnpm remove + 兜底删目录 + 复原 manifest)+ 写 .failed stamp,
2965
- * 失败文件不再每次点击都重试(删除 `.<name>.failed` 即可重试)
3222
+ * 记录一条下载期望(provenance)。
3223
+ *
3224
+ * updateBrowser / resolveDownloadUrl 生成下载链接时调用;浏览器/NDM 下载到
3225
+ * `$DSH_HOME/downloads` 后,checkDownloads 只接受能在 pendingDownloads 里找到
3226
+ * 同 name+version 记录的归档。按 packageName+version 去重,保留最近 PENDING_DOWNLOAD_MAX 条。
3227
+ */
3228
+ rememberPendingDownload({ url, packageName, version, sourceName, expect }) {
3229
+ const list = Array.isArray(this.sidecar.pendingDownloads) ? this.sidecar.pendingDownloads : [];
3230
+ const record = {
3231
+ url: String(url),
3232
+ packageName,
3233
+ version: String(version),
3234
+ sourceName: typeof sourceName === "string" ? sourceName : null,
3235
+ expect: normalizeDownloadExpect(expect),
3236
+ at: new Date().toISOString()
3237
+ };
3238
+ const kept = list.filter((item) => !(item?.packageName === packageName && item?.version === record.version));
3239
+ kept.push(record);
3240
+ this.sidecar.pendingDownloads = kept.slice(-PENDING_DOWNLOAD_MAX);
3241
+ return record;
3242
+ }
3243
+ /** 找一条未过期的下载期望记录(顺手清掉过期记录,避免侧车无限增长)。 */
3244
+ findPendingDownload(packageName, version) {
3245
+ const list = Array.isArray(this.sidecar.pendingDownloads) ? this.sidecar.pendingDownloads : [];
3246
+ const now = Date.now();
3247
+ const fresh = list.filter((item) => {
3248
+ const at = typeof item?.at === "string" ? Date.parse(item.at) : Number.NaN;
3249
+ return !Number.isNaN(at) && now - at <= PENDING_DOWNLOAD_TTL_MS;
3250
+ });
3251
+ if (fresh.length !== list.length) this.sidecar.pendingDownloads = fresh;
3252
+ return fresh.find((item) => item.packageName === packageName && item.version === version) ?? null;
3253
+ }
3254
+ /** 安装成功后移除该记录;失败的记录保留(不重复噪音,也不给"失败文件重试"留下歧义)。 */
3255
+ dropPendingDownload(record) {
3256
+ const list = Array.isArray(this.sidecar.pendingDownloads) ? this.sidecar.pendingDownloads : [];
3257
+ this.sidecar.pendingDownloads = list.filter((item) => !(item !== null && typeof item === "object" && item.packageName === record.packageName && item.version === record.version));
3258
+ }
3259
+ /**
3260
+ * 扫描下载目录并安装 **有 provenance 记录** 的 npm 包归档。
3261
+ *
3262
+ * 1.0.2 之前这里是"目录里任何 .tgz 都自动 pnpm add",等于给 $DSH_HOME/downloads
3263
+ * 开了一个免校验的代码投放口(B 报告 S1):能往该目录写文件的人(同机进程、同步盘、
3264
+ * 恶意 zip 解压)就能让 pnpm 在 host 里执行生命周期脚本,1.0.2 的摘要门禁在此完全旁路。
3265
+ *
3266
+ * 现在的判定顺序:
3267
+ * 1) 只接受 .tgz / .tar.gz(.zip 直接拒绝,pnpm 无法作为包安装);
3268
+ * 2) 用 node:zlib 读归档内 `package/package.json` → 得到它自称的 name/version;
3269
+ * 3) 在 sidecar.pendingDownloads 里找同 name+version 且未过期(7 天)的记录 ——
3270
+ * 没有记录 = 不是本管理器生成的下载链接 → 拒绝并写 .failed;
3271
+ * 4) 记录带摘要(integrity/shasum)→ 流式校验一致才继续;只有 size 不算校验;
3272
+ * 5) 之后才进入原有 installDownloadedArchive(稳定暂存 -> pnpm -> dsh 清单校验 ->
3273
+ * profile 自检 -> 失败回滚),成功后移除记录。
3274
+ * 失败文件写 `.failed` stamp:删掉 `.failed` 即"显式确认后重试"。
2966
3275
  */
2967
3276
  async checkDownloads() {
2968
3277
  return await this.serialize(async () => {
@@ -2992,15 +3301,40 @@ setTimeout(() => {
2992
3301
  reject("只支持 npm 包归档(.tgz / .tar.gz);.zip 不能作为 npm 包安装,已拒绝(删除该 .failed 标记可重试)。");
2993
3302
  continue;
2994
3303
  }
3304
+ // 步骤 2:读归档内 package.json —— 先确定"这个文件声称自己是哪个包哪个版本"
3305
+ const manifest = readArchivePackageManifest(file);
3306
+ if (manifest === null) {
3307
+ reject("不是有效的 npm 包归档(读不到 package/package.json),无法校验来源,已拒绝(删除该 .failed 标记可重试)。");
3308
+ continue;
3309
+ }
3310
+ // 步骤 3:provenance 记录是唯一入口凭证
3311
+ const record = this.findPendingDownload(manifest.name, manifest.version);
3312
+ if (record === null) {
3313
+ reject(`未找到来源记录(不是本管理器生成的下载链接):${manifest.name}@${manifest.version}。确认可信后再删除 .failed 重试(或先在管理器中重新生成该包的下载链接)。`);
3314
+ continue;
3315
+ }
3316
+ // 步骤 4:有摘要就流式校验(摘要不符 = 内容可能被替换,硬拒绝)
3317
+ const proof = await verifyArchiveDigest(file, record.expect);
3318
+ if (!proof.ok) {
3319
+ reject(proof.message ?? "归档摘要校验失败,已拒绝安装。");
3320
+ continue;
3321
+ }
2995
3322
  const outcome = await this.installDownloadedArchive(name, file);
2996
3323
  if (outcome.ok) {
2997
3324
  writeFileSync(stamp, new Date().toISOString(), "utf8");
2998
3325
  installed.push(name);
2999
- this.log("checkDownloads", `installed ${name}`);
3326
+ this.dropPendingDownload(record);
3327
+ this.log("checkDownloads", `installed ${name} (${manifest.name}@${manifest.version}${proof.verified ? ",摘要已校验" : ",来源记录无摘要"})`);
3000
3328
  } else {
3001
3329
  reject(outcome.message);
3002
3330
  }
3003
3331
  }
3332
+ // pendingDownloads 可能被安装成功/过期清理改动过 → 落盘(写失败不改变本次结果)
3333
+ try {
3334
+ await writeSidecarState(this.location, this.sidecar);
3335
+ } catch (error) {
3336
+ this.log("checkDownloads", `sidecar write failed: ${error instanceof Error ? error.message : String(error)}`);
3337
+ }
3004
3338
  return { installed, failed, message: null };
3005
3339
  });
3006
3340
  }
@@ -3163,17 +3497,44 @@ setTimeout(() => {
3163
3497
  this.profileDeps = readProfileDeps(this.location);
3164
3498
  return residuals;
3165
3499
  }
3166
- /** 解析某包在 github/dshfind 源的下载链接(供浏览器/NDM 手动下载)。 */
3500
+ /**
3501
+ * 安全修复(CWE-494)配套:按「刷新时命中的那个源」定位安装源。
3502
+ * 不能沿用 `sources.find(name)` + "查不到就随便拿一个启用源" 的兜底:源名称允许
3503
+ * 重复/可随时改,错配时会拿 github 源的版本用 registry 的 pnpm 装法去装(或反过来),
3504
+ * 等于绕过 registry 权威判定。这里按 URL(配置按 URL 去重)定位,再退回「名字唯一且
3505
+ * 类型一致」,都不行就明确报「配置已变更」,绝不乱猜。
3506
+ * @returns {{source?: object, message?: string}} source 为空时 message 是给用户看的中文原因。
3507
+ */
3508
+ bestSourceOf(best) {
3509
+ const enabled = this.sources.filter((s) => s?.enabled === true);
3510
+ if (enabled.length === 0) return { source: void 0, message: "没有启用的更新源。" };
3511
+ if (typeof best?.sourceUrl === "string" && best.sourceUrl !== "") {
3512
+ const exact = enabled.find((s) => s.url === best.sourceUrl);
3513
+ if (exact !== void 0) return { source: exact };
3514
+ }
3515
+ const wantedType = typeof best?.sourceType === "string" ? normalizeSourceType(best.sourceType) : null;
3516
+ const byName = enabled.filter((s) => s.name === best?.sourceName && (wantedType === null || normalizeSourceType(s.type) === wantedType));
3517
+ if (byName.length === 1) return { source: byName[0] };
3518
+ return { source: void 0, message: "找不到提供该版本的更新源(更新源配置可能已变更),请先重新检查更新。" };
3519
+ }
3520
+ /**
3521
+ * 解析某包在 github 源的下载链接(供浏览器/NDM 手动下载)。
3522
+ * 1.0.3:生成链接的同时把期望(URL + name@version + 摘要)写进 sidecar.pendingDownloads,
3523
+ * 下载到 $DSH_HOME/downloads 后 checkDownloads 只认这些记录(B 报告 S1 provenance)。
3524
+ */
3167
3525
  async resolveDownloadUrl(packageName) {
3168
- const best = LATEST_CACHE.get(packageName);
3169
- const info = packageInfoOf(packageName, this.baseUrl);
3170
- const source = best !== void 0 && best.sourceName !== null
3171
- ? this.sources.find((s) => s.enabled && s.name === best.sourceName)
3172
- : void 0;
3173
- if (source === void 0 || best === void 0) return { url: null, message: "没有可用的更新源信息,请先刷新检查更新。" };
3174
- const url = await resolveSourceDownloadUrl(source, best);
3175
- if (url === null) return { url: null, message: "无法解析下载链接(该源未提供发布资产)。" };
3176
- return { url, message: null, sourceName: source.name, installedVersion: info.installedVersion, latestVersion: best.version };
3526
+ return await this.serialize(async () => {
3527
+ const best = LATEST_CACHE.get(packageName);
3528
+ const info = packageInfoOf(packageName, this.baseUrl);
3529
+ if (best === void 0 || best.sourceName === null) return { url: null, message: "没有可用的更新源信息,请先刷新检查更新。" };
3530
+ const found = this.bestSourceOf(best);
3531
+ if (found.source === void 0) return { url: null, message: found.message };
3532
+ const target = await resolveSourceDownloadUrl(found.source, best, { allowUnverifiedFallback: this.security.unverifiedDownloads === "allow" });
3533
+ if (target === null) return { url: null, message: "无法解析下载链接(该源未提供发布资产)。" };
3534
+ this.rememberPendingDownload({ url: target.url, packageName, version: best.version, sourceName: found.source.name, expect: target.expect });
3535
+ await writeSidecarState(this.location, this.sidecar);
3536
+ return { url: target.url, message: target.note ?? null, sourceName: found.source.name, installedVersion: info.installedVersion, latestVersion: best.version };
3537
+ });
3177
3538
  }
3178
3539
  //#endregion
3179
3540
  //#region 启动前自检(自动化救援:坏 bundle 会在 boot 时让引擎起不来)
@@ -3230,7 +3591,7 @@ setTimeout(() => {
3230
3591
  });
3231
3592
  }
3232
3593
  //#endregion
3233
- /** 更新(内置下载器路径,registry 源 pnpm 直装;github/dshfind 走通用下载器)。 */
3594
+ /** 更新(内置下载器路径,registry 源 pnpm 直装;github 源走通用下载器)。 */
3234
3595
  async update(packageNames) {
3235
3596
  return await this.serialize(async () => {
3236
3597
  const items = [];
@@ -3277,25 +3638,29 @@ setTimeout(() => {
3277
3638
  items.push({ packageName, status: "up-to-date", url: null, sourceName: null, installedVersion: installed, latestVersion: best.version, message: null });
3278
3639
  continue;
3279
3640
  }
3280
- const source = this.sources.find((s) => s.enabled && s.name === best.sourceName) ?? this.sources.find((s) => s.enabled);
3281
- if (source === void 0) {
3282
- items.push({ packageName, status: "failed", url: null, sourceName: null, installedVersion: installed, latestVersion: best.version, message: "没有启用的更新源。" });
3641
+ const found = this.bestSourceOf(best);
3642
+ if (found.source === void 0) {
3643
+ items.push({ packageName, status: "failed", url: null, sourceName: null, installedVersion: installed, latestVersion: best.version, message: found.message });
3283
3644
  continue;
3284
3645
  }
3646
+ const source = found.source;
3285
3647
  if (source.type === "registry") {
3286
3648
  // registry 源直接用内置 pnpm 路径更可靠
3287
3649
  const item = await this.updateOne(packageName);
3288
3650
  items.push({ packageName, status: item.status === "updated" ? "up-to-date" : item.status === "failed" ? "failed" : "need-download", url: null, sourceName: source.name, installedVersion: item.installedVersion, latestVersion: item.latestVersion, message: item.message });
3289
3651
  continue;
3290
3652
  }
3291
- const url = await resolveSourceDownloadUrl(source, best);
3292
- if (url === null) {
3653
+ const target = await resolveSourceDownloadUrl(source, best, { allowUnverifiedFallback: this.security.unverifiedDownloads === "allow" });
3654
+ if (target === null) {
3293
3655
  items.push({ packageName, status: "failed", url: null, sourceName: source.name, installedVersion: installed, latestVersion: best.version, message: "无法解析下载链接(该源未提供发布资产)。" });
3294
3656
  continue;
3295
3657
  }
3296
- this.log("updateBrowser", `${packageName} -> ${url.slice(0, 120)}`);
3297
- items.push({ packageName, status: "need-download", url, sourceName: source.name, installedVersion: installed, latestVersion: best.version, message: "已生成下载链接,请用浏览器/NDM 下载后自动安装。" });
3658
+ this.log("updateBrowser", `${packageName} -> ${target.url.slice(0, 120)}`);
3659
+ // provenance:把本次下载的期望记进侧车,checkDownloads 只认这些记录
3660
+ this.rememberPendingDownload({ url: target.url, packageName, version: best.version, sourceName: source.name, expect: target.expect });
3661
+ items.push({ packageName, status: "need-download", url: target.url, sourceName: source.name, installedVersion: installed, latestVersion: best.version, message: target.note === undefined ? "已生成下载链接,请用浏览器/NDM 下载后自动安装。" : `已生成下载链接,请用浏览器/NDM 下载后自动安装。注意:${target.note}` });
3298
3662
  }
3663
+ await writeSidecarState(this.location, this.sidecar);
3299
3664
  return { items, snapshot: this.snapshot() };
3300
3665
  });
3301
3666
  }
@@ -3332,8 +3697,8 @@ setTimeout(() => {
3332
3697
  }
3333
3698
  /**
3334
3699
  * 拉取插件市场目录(一次全量,客户端本地过滤/分页)。
3335
- * 数据源:awesome-dsh-plugin 精选目录(就是 dshfind 的收录池),
3336
- * 带分类/本地化描述/npm 包名/stars/收录日期;在线失败时兜底 GitHub
3700
+ * 数据源:awesome-dsh-plugin 精选目录(即旧"插件超市"的收录池,GitHub topic:dsh-plugin
3701
+ * 的精编清单);带分类/本地化描述/npm 包名/stars/收录日期;在线失败时兜底 GitHub
3337
3702
  * topic:dsh-plugin 搜索(限流 10/min —— 目录已缓存 10 分钟,极少触发)。
3338
3703
  * @returns {source, updated, count, categories, items}
3339
3704
  */
@@ -3442,19 +3807,39 @@ setTimeout(() => {
3442
3807
  const pnpmArgs = npm !== null ? ["add", npm] : null;
3443
3808
  if (pnpmArgs === null) {
3444
3809
  const [owner, repoName] = repo[1].split("/");
3810
+ // CWE-494:市场一键安装同样要过完整性校验。能拿到 release 资产的 digest 就强制校验;
3811
+ // 拿不到(无 digest / 只能回退源码归档)时按 security.unverifiedDownloads 决定放不放行。
3812
+ const allowUnverified = this.security.unverifiedDownloads === "allow";
3445
3813
  let downloadUrl = null;
3814
+ let expect;
3815
+ let unverifiedNote = "该仓库没有可校验的 release 资产,回退到源码归档下载(分支内容随时可被替换)";
3446
3816
  try {
3447
3817
  const release = await fetchGitHubRelease(repo[1]);
3448
3818
  if (release !== null) {
3449
3819
  const tgz = (release.assets ?? []).find((a) => /\.(tgz|tar\.gz)$/i.test(a.name ?? ""));
3450
- if (tgz?.browser_download_url) downloadUrl = tgz.browser_download_url;
3820
+ if (tgz?.browser_download_url) {
3821
+ downloadUrl = tgz.browser_download_url;
3822
+ expect = assetExpectOf(tgz) ?? undefined;
3823
+ if (expect === undefined) unverifiedNote = "该 release 资产没有摘要(digest)";
3824
+ }
3451
3825
  }
3452
3826
  if (downloadUrl === null) downloadUrl = `https://codeload.github.com/${owner}/${repoName}/tar.gz/refs/heads/main`;
3453
3827
  } catch {
3454
3828
  downloadUrl = `https://codeload.github.com/${owner}/${repoName}/tar.gz/refs/heads/main`;
3455
3829
  }
3456
- this.log("marketInstall", `${packageName} downloading ${downloadUrl.slice(0, 120)}`);
3457
- const dl = await downloadPluginUrl(downloadUrl, (line) => this.log("market-download", line));
3830
+ const noteForUser = expect !== undefined
3831
+ ? ""
3832
+ : allowUnverified
3833
+ ? `(注意:${unverifiedNote},本次下载未做完整性校验)`
3834
+ : `(${unverifiedNote},按默认安全策略已拒绝下载:如需继续,请在 profile 的 cordis.patch.yml 里为 dsh-drydock 设置 security.unverifiedDownloads: allow)`;
3835
+ this.log("marketInstall", `${packageName} downloading ${downloadUrl.slice(0, 120)}${noteForUser}`);
3836
+ if (expect === undefined && !allowUnverified) {
3837
+ return { status: "failed", packageName, url: installUrl, method, message: `${unverifiedNote},按默认安全策略已拒绝下载。如确需继续,请在 profile 的 cordis.patch.yml 里为 dsh-drydock 设置 security.unverifiedDownloads: allow。` };
3838
+ }
3839
+ const dl = await downloadPluginUrl(downloadUrl, (line) => this.log("market-download", line), {
3840
+ expect,
3841
+ allowUnverified: expect === undefined && allowUnverified
3842
+ });
3458
3843
  if (dl.status !== "downloaded" || dl.file === null) {
3459
3844
  return { status: "failed", packageName, url: installUrl, method, message: dl.message ?? "下载失败" };
3460
3845
  }
@@ -3589,20 +3974,23 @@ setTimeout(() => {
3589
3974
  latestVersion: best.version
3590
3975
  };
3591
3976
  }
3592
- const source = this.sources.find((s) => s.enabled && s.name === best.sourceName) ?? this.sources.find((s) => s.enabled);
3593
- if (source === void 0) {
3977
+ const found = this.bestSourceOf(best);
3978
+ if (found.source === void 0) {
3594
3979
  return {
3595
3980
  packageName,
3596
3981
  status: "not-managed",
3597
- message: "没有启用的更新源。",
3982
+ message: found.message,
3598
3983
  installedVersion: installed,
3599
3984
  latestVersion: best.version
3600
3985
  };
3601
3986
  }
3602
- // github / dshfind 源:解析下载链接 -> 通用下载器(HTTP 直链 / magnet / torrent,支持 P2P)
3603
- if (source.type === "github" || source.type === "dshfind") {
3604
- const downloadUrl = await resolveSourceDownloadUrl(source, best);
3605
- if (downloadUrl === null) {
3987
+ const source = found.source;
3988
+ // github 源:解析下载链接 -> 通用下载器(HTTP 直链 / magnet / torrent,支持 P2P)
3989
+ // 注意:这里不再接受 dshfind —— 它的实现与默认源已随 CWE-494 修复移除,
3990
+ // 旧侧车里的 dshfind 条目在读取时就被剔除,不会走到这个分支。
3991
+ if (source.type === "github") {
3992
+ const target = await resolveSourceDownloadUrl(source, best, { allowUnverifiedFallback: this.security.unverifiedDownloads === "allow" });
3993
+ if (target === null) {
3606
3994
  return {
3607
3995
  packageName,
3608
3996
  status: "not-managed",
@@ -3611,8 +3999,13 @@ setTimeout(() => {
3611
3999
  latestVersion: best.version
3612
4000
  };
3613
4001
  }
3614
- this.log("update", `${packageName}: downloading via ${source.type} from ${downloadUrl.slice(0, 120)}`);
3615
- const dl = await downloadPluginUrl(downloadUrl, (line) => this.log("download", line));
4002
+ this.log("update", `${packageName}: downloading via ${source.type} from ${target.url.slice(0, 120)}${target.note === undefined ? "" : `(${target.note})`}`);
4003
+ // CWE-494:能拿到摘要就强制校验;拿不到时由 resolveSourceDownloadUrl 显式标 allowUnverified,
4004
+ // 下载器默认对「无从校验」一律拒绝(fail-closed),不会静默放行。
4005
+ const dl = await downloadPluginUrl(target.url, (line) => this.log("download", line), {
4006
+ expect: target.expect,
4007
+ allowUnverified: target.allowUnverified === true
4008
+ });
3616
4009
  if (dl.status !== "downloaded" || dl.file === null) {
3617
4010
  return {
3618
4011
  packageName,
@@ -3677,7 +4070,13 @@ setTimeout(() => {
3677
4070
  return {
3678
4071
  profileName: this.location.profileName,
3679
4072
  entries,
3680
- sources: this.sources.map((s) => ({ ...s })),
4073
+ // 1.0.3:official/authoritative/insecure 都在这里按服务端规则重算一遍,
4074
+ // 保证请求体/侧车里的自报 official 永远驱动不了「官方」徽标与信任层。
4075
+ sources: this.sources.map((source) => {
4076
+ const url = normalizeSourceUrl(source?.url);
4077
+ const official = isBuiltinAuthoritativeUrl(url);
4078
+ return { ...source, url, official, insecure: isInsecureSourceUrl(url), authoritative: source?.authoritative === true || official };
4079
+ }),
3681
4080
  // C-03/C-04:最近一次「检查更新」的预算执行结果(客户端据此提示「网络慢、已按预算中止」)
3682
4081
  lastRefresh: this.lastRefresh ?? null
3683
4082
  };
@@ -3729,6 +4128,12 @@ setTimeout(() => {
3729
4128
  installedVersion: installed,
3730
4129
  latestVersion: latest,
3731
4130
  updateSource: latestEntry?.sourceName ?? null,
4131
+ // 安全修复(CWE-494):版本来自哪一层信任 —— authoritative=服务端判定的权威源
4132
+ // (内置白名单或显式升级);fallback=权威源都没给出版本时用非权威源兜底
4133
+ // (updateDegraded=true,UI 应提示「版本来自非权威源、未经 npm 校验」)。
4134
+ // 旧缓存条目无此字段 → null/false。
4135
+ updateSourceTrust: latestEntry?.sourceTrust ?? null,
4136
+ updateDegraded: latestEntry?.degraded === true,
3732
4137
  // C-09:把「为什么没有版本信息」也带上(network/timeout/not-found/backoff),UI 才能说实话
3733
4138
  updateReason: latestEntry?.reason ?? null,
3734
4139
  needsUpdate,
@@ -3957,7 +4362,21 @@ export const Config = z.object({
3957
4362
  /** 额外受保护条目 id 列表(不会被管理器开关/隔离)。 */
3958
4363
  protectedEntries: z.array(z.string()).default([]),
3959
4364
  /** 开关状态变更后等待运行期收敛的超时(毫秒);0.1.7 引擎不热重载 cordis.patch.yml,故收紧默认值。 */
3960
- settleTimeoutMs: z.number().min(100).max(120000).default(2500)
4365
+ settleTimeoutMs: z.number().min(100).max(120000).default(2500),
4366
+ /**
4367
+ * 下载完整性策略(CWE-494,1.0.2 起)。
4368
+ *
4369
+ * 默认 `deny`(fail-closed):**拿不到可校验摘要的下载一律拒绝**,并给出可操作的中文提示。
4370
+ * 这是安全默认值 —— 更新模块允许自定义更新源,某些自建/老仓库确实不提供 digest,
4371
+ * 所以留了 `allow` 开关:显式开启后放行,但下载回执与界面会标注「未校验来源」。
4372
+ *
4373
+ * **以下两条不受此开关影响,永远拒绝**:
4374
+ * · 摘要不匹配(integrity / size 对不上)—— 内容已被篡改,没有任何理由放行;
4375
+ * · 明文 `http://`(含 https→http 重定向降级)—— 传输可被中间人替换。
4376
+ */
4377
+ security: z.object({
4378
+ unverifiedDownloads: z.enum(["deny", "allow"]).default("deny")
4379
+ }).default({})
3961
4380
  }).default({});
3962
4381
 
3963
4382
  /** 仅测试用内部工具(不参与 Cordis 装配,见 tools/test-host-fixes.mjs)。 */
@@ -3999,11 +4418,9 @@ export const __internals = {
3999
4418
  fetchLatestVersion,
4000
4419
  fetchLatestAcross,
4001
4420
  refreshLatest,
4002
- fetchLatestDshfindVersion,
4003
4421
  REASON,
4004
4422
  VERSION_TTL_MS,
4005
4423
  NEGATIVE_TTL_MS,
4006
- DSFFIND_SEARCH_TTL_MS,
4007
4424
  BACKOFF_BASE_MS,
4008
4425
  REFRESH_BUDGET_DEFAULT_MS,
4009
4426
  getRefreshBudgetMs: () => refreshBudgetMs,
@@ -4014,7 +4431,6 @@ export const __internals = {
4014
4431
  cacheSnapshot: () => ({
4015
4432
  version: [...VERSION_CACHE.entries()].map(([key, value]) => ({ key, latest: value.latest, at: value.at })),
4016
4433
  failures: [...VERSION_FAILURE_CACHE.entries()].map(([key, value]) => ({ key, reason: value.reason, at: value.at })),
4017
- dshfindSearch: [...DSFFIND_SEARCH_CACHE.entries()].map(([key, value]) => ({ key, latest: value.latest, at: value.at })),
4018
4434
  backoff: [...SOURCE_BACKOFF.entries()].map(([key, value]) => ({ key, streak: value.streak, until: value.until })),
4019
4435
  cooldown: [...SOURCE_COOLDOWN.entries()].map(([key, until]) => ({ key, until })),
4020
4436
  catalogAt: CATALOG_CACHE.at,
@@ -4025,7 +4441,6 @@ export const __internals = {
4025
4441
  VERSION_CACHE.clear();
4026
4442
  VERSION_FAILURE_CACHE.clear();
4027
4443
  LATEST_CACHE.clear();
4028
- DSFFIND_SEARCH_CACHE.clear();
4029
4444
  SOURCE_BACKOFF.clear();
4030
4445
  SOURCE_COOLDOWN.clear();
4031
4446
  CATALOG_CACHE.at = 0;