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/index.js CHANGED
@@ -331,14 +331,33 @@ const AUTO_QUARANTINE_STREAK = 2;
331
331
  const SOURCE_LABELS = new Set(["npm", "github", "local", "builtin"]);
332
332
  const DEFAULT_SOURCES = [
333
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
334
  { name: "GitHub 官方仓库", url: "https://github.com/deepseek-ai/deepseek-harness", enabled: false, official: true, type: "github" },
336
335
  { name: "npmmirror 镜像", url: "https://registry.npmmirror.com", enabled: false, official: false, type: "registry" }
337
336
  ];
338
337
 
339
- /** 归一化源类型。 */
338
+ /**
339
+ * 安全修复(CWE-494 供应链投毒)——dshfind(插件超市)源**整体移除**,不再提供:
340
+ * 它把 `topic:dsh-plugin <包名>` 的 GitHub 搜索结果里**第一个同名仓库**当发布源
341
+ * (不校验 owner/repo、不比对 npm 登记的 repository、不查 provenance),
342
+ * 伪造一个同名仓库 + v999.0.0 release 就能在默认更新流程里赢过官方发布,
343
+ * 宿主再从该仓库取 release 资产/ torrent / codeload 交给下载器安装。
344
+ *
345
+ * 为什么不是"留着但默认关":它能带来的**唯一**增量是「包在 npm 上有、但只在 GitHub
346
+ * 发新版本」这一小类;而这类发布恰恰没有 npm 登记可做信任锚点,provenance 校验必然
347
+ * 拒掉 —— 也就是说加固后的 dshfind 对这类包等于不工作,对 registry 能管的包又纯属
348
+ * 重复。留一个"看起来能用、实则要么不安全要么无效"的源,比移除更容易误导用户。
349
+ * registry 源本身给权威版本;GitHub 源是用户显式配置的**固定仓库**,不是搜索出来的
350
+ * 发布源 —— 二者都不需要 dshfind。相关更新流程、缓存与测试夹具已一并删除。
351
+ */
352
+ /** 旧版内置 dshfind 源的残留识别(侧车文件里可能还存着 enabled:true 的条目)。 */
353
+ function isLegacyDshfindSource(source) {
354
+ if (source?.type === "dshfind") return true;
355
+ return /^https?:\/\/(?:www\.)?dshfind\.com(?:\/|$)/i.test(String(source?.url ?? ""));
356
+ }
357
+
358
+ /** 归一化源类型:只剩 registry / github 两类(旧 dshfind 值统一降级为 registry,侧车读取时会先剔除)。 */
340
359
  function normalizeSourceType(type) {
341
- return type === "github" || type === "dshfind" ? type : "registry";
360
+ return type === "github" ? "github" : "registry";
342
361
  }
343
362
 
344
363
  function defaultSidecarState() {
@@ -397,6 +416,9 @@ function readSidecarState(location) {
397
416
  if (Array.isArray(parsed?.sources)) {
398
417
  const sources = parsed.sources
399
418
  .filter((s) => s !== null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string" && /^https?:\/\//.test(s.url))
419
+ // 安全修复:旧侧车里的 dshfind 条目直接丢弃 —— 该源的实现已移除,
420
+ // 留着它会被当成 registry 去请求 https://dshfind.com/...(永远 404 还污染版本缓存)。
421
+ .filter((s) => !isLegacyDshfindSource(s))
400
422
  .map((s) => ({
401
423
  name: (s.name.trim() || s.url).slice(0, 64),
402
424
  url: s.url.trim().replace(/\/+$/, ""),
@@ -461,12 +483,12 @@ const VERSION_TTL_MS = 30 * 60 * 1000;
461
483
  * C-02:网络类失败**不允许**写 VERSION_CACHE —— 那等于把网络问题记成「无更新」30 分钟,
462
484
  * 用户网络恢复后点多少次「重试」都不会联网。失败只进这个 30 秒合流窗口,作用仅是让
463
485
  * 同一波并发/连点不重复打网络;任何显式重试(options.force === true)都会绕过它并真正联网。
464
- * 负缓存(VERSION_CACHE 的 latest=null / DSFFIND_SEARCH_CACHE)只允许记确定性结论。
486
+ * 负缓存(VERSION_CACHE 的 latest=null)只允许记确定性结论。
465
487
  */
466
488
  const VERSION_FAILURE_CACHE = new Map();
467
489
  const NEGATIVE_TTL_MS = 30 * 1000;
468
490
  const LATEST_CACHE = new Map();
469
- /** 源限流熔断:403/429 后冷却 10 分钟(github api 与 dshfind 共享键)。 */
491
+ /** 源限流熔断:403/429 后冷却 10 分钟(github api 限流)。 */
470
492
  const SOURCE_COOLDOWN = new Map();
471
493
  const COOLDOWN_MS = 10 * 60 * 1000;
472
494
  /**
@@ -503,9 +525,9 @@ const RUN_FAIL_LIMIT = 5;
503
525
  const REFRESH_BUDGET_DEFAULT_MS = 90 * 1000;
504
526
  let refreshBudgetMs = REFRESH_BUDGET_DEFAULT_MS;
505
527
 
506
- /** 限流冷却键:github/dshfind 共享 api.github.com 配额。 */
528
+ /** 限流冷却键:github 源共用 api.github.com 配额。 */
507
529
  function cooldownKey(source) {
508
- return source?.type === "github" || source?.type === "dshfind" ? "https://api.github.com" : source?.url ?? "";
530
+ return source?.type === "github" ? "https://api.github.com" : source?.url ?? "";
509
531
  }
510
532
 
511
533
  /** 该源是否处于限流冷却期。 */
@@ -611,14 +633,14 @@ function versionFailureText(reason) {
611
633
  }
612
634
 
613
635
  /**
614
- * 统一返回 {version, repo, reason}:repo 仅供 github/dshfind 源下载时使用,
636
+ * 统一返回 {version, repo, reason}:repo 仅供 github 源下载时使用,
615
637
  * reason 见 REASON(C-09:404 与网络异常在下游必须可区分)。
616
638
  */
617
639
  async function fetchLatestVersion(packageName, source, options) {
618
640
  // 同一包最近一次失败的具体原因(timeout/network/not-found)优先于「源级退避」返回:
619
641
  // 两者都不联网,但具体原因更可行动(「网络不可达」比「退避中」更清楚)。失败窗口只有 30 秒。
620
642
  if (options?.force !== true) {
621
- const recentKey = source.type === "dshfind" ? `dshfind\0${packageName}` : `${source.url}\0${packageName}`;
643
+ const recentKey = `${source.url}\0${packageName}`;
622
644
  const recent = VERSION_FAILURE_CACHE.get(recentKey);
623
645
  if (recent !== void 0 && Date.now() - recent.at < NEGATIVE_TTL_MS) return { version: null, repo: null, reason: recent.reason };
624
646
  }
@@ -627,7 +649,7 @@ async function fetchLatestVersion(packageName, source, options) {
627
649
  const inner = await fetchLatestGithubVersion(packageName, source.url, source, options);
628
650
  return { version: inner.version, repo: githubRepoOf(source.url), reason: inner.reason };
629
651
  }
630
- if (source.type === "dshfind") return fetchLatestDshfindVersion(packageName, source, options);
652
+ // 只剩 registry 与 github 两类源(dshfind 已随 CWE-494 修复移除,见 DEFAULT_SOURCES 注释)
631
653
  const key = `${source.url}\0${packageName}`;
632
654
  if (options?.force !== true) {
633
655
  const cached = VERSION_CACHE.get(key);
@@ -700,139 +722,73 @@ async function fetchGitHubRelease(repo) {
700
722
  }
701
723
 
702
724
  /**
703
- * 解析 github / dshfind 源的下载链接:
704
- * 优先 release 资产 .tgz -> .torrent -> release 说明里的 magnet -> codeload 兜底。
705
- * magnet / .torrent 交给通用下载器走 P2P(webtorrent 或本机 aria2c)。
725
+ * 从 GitHub release 资产推导下载校验期望(CWE-494 接线)。
726
+ *
727
+ * GitHub 的 releases API 会为每个资产给出 `digest`(形如 `sha256:<64 hex>`)与 `size`。
728
+ * 有 digest 就转成下载器认的 SRI 形态 `sha256-<64 hex>` 并强制校验;没有 digest 的旧资产
729
+ * 只能返回 null,由调用方决定「显式接受未校验」还是拒绝。
730
+ * @returns {{integrity: string, size?: number}|null}
706
731
  */
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;
732
+ function assetExpectOf(asset) {
733
+ const digest = typeof asset?.digest === "string" ? asset.digest : "";
734
+ const match = /^sha256:([0-9a-f]{64})$/i.exec(digest);
735
+ if (match === null) return null;
736
+ const expected = { integrity: `sha256-${match[1].toLowerCase()}` };
737
+ if (Number.isInteger(asset?.size) && asset.size > 0) expected.size = asset.size;
738
+ return expected;
738
739
  }
739
740
 
740
741
  /**
741
- * 插件超市(dshfind)源:本质是 GitHub dsh-plugin topic 的聚合。
742
- * 按包名搜索 topic 仓库(search API,10 次/分钟限流 —— 结果按包缓存),
743
- * 验证仓库根 package.json 的 name 匹配后取 releases/latest 版本。
742
+ * 解析 github 源的下载目标:release 资产 .tgz -> .torrent -> release 说明里的 magnet -> codeload 兜底。
743
+ * magnet / .torrent 交给通用下载器走 P2P(webtorrent 或本机 aria2c)。
744
+ * 只有 registry 源不是走这里(registry 直接用 pnpm add <pkg>@<version> --registry <url>)。
745
+ *
746
+ * 1.1.0 起返回 `{url, expect, allowUnverified, note}` 而不是裸字符串 —— 下载器
747
+ * (lib/downloader.js)默认对「明文 http / 无从校验 / 摘要不符」一律拒绝(fail-closed),
748
+ * 这里负责把**能校验的就校验**:
749
+ * · release 资产带 digest → 强制校验(expect 非空)
750
+ * · 资产无 digest / .torrent / magnet / codeload 兜底 → 无法校验,显式 allowUnverified
751
+ * 并在 note 里写清原因(UI 展示,用户能看到这次下载没做完整性校验)
752
+ *
753
+ * 已知残余风险(评估见交付说明):codeload 兜底用的是 movable tag
754
+ * `refs/tags/v<version>`,tag 可被重打/移动;更稳的做法是先经 GitHub API 把
755
+ * release.tag_name 解析成 commit SHA,再取 `codeload.../tar.gz/<sha>`。
756
+ * @param source - 更新源(目前只有 github 会走这里)。
757
+ * @param best - 聚合出的最新版本(带 repo / version)。
758
+ * @param options.allowUnverifiedFallback - 配置 `security.unverifiedDownloads === "allow"` 时为 true。
759
+ * 仅在**拿不到摘要**时起作用:false(默认)→ 下载器会 fail-closed 拒绝,并提示怎么开;
760
+ * true → 放行但 note 明确标注未校验。**摘要存在时永远强制校验,这个参数无效。**
761
+ * @returns {Promise<{url: string, expect?: object, allowUnverified?: boolean, note?: string}|null>}
744
762
  */
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;
821
- }
822
- } catch (error) {
823
- uncertain = classifyFetchError(error);
824
- }
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;
763
+ async function resolveSourceDownloadUrl(source, best, { allowUnverifiedFallback = false } = {}) {
764
+ if (source.type !== "github") return null;
765
+ const repo = githubRepoOf(source.url) ?? best.repo;
766
+ if (repo === null) return null;
767
+ /** 拿不到摘要时的统一出口:是否放行由调用方(配置)决定,但 note 必须说清后果。 */
768
+ const unverifiable = (url, why) => ({
769
+ url,
770
+ allowUnverified: allowUnverifiedFallback,
771
+ note: allowUnverifiedFallback
772
+ ? `${why},本次下载未做完整性校验(安全策略已设为 allow)。`
773
+ : `${why},按默认安全策略已拒绝下载。如确需继续,请在 profile 的 cordis.patch.yml 里为 dsh-drydock 设置 security.unverifiedDownloads: allow。`
774
+ });
775
+ const release = await fetchGitHubRelease(repo);
776
+ if (release !== null) {
777
+ const tgz = (release.assets ?? []).find((a) => /\.(tgz|tar\.gz)$/i.test(a.name ?? ""));
778
+ if (tgz?.browser_download_url) {
779
+ const expect = assetExpectOf(tgz);
780
+ return expect !== null ? { url: tgz.browser_download_url, expect } : unverifiable(tgz.browser_download_url, "该 release 资产没有摘要(digest)");
781
+ }
782
+ const torrent = (release.assets ?? []).find((a) => /\.torrent$/i.test(a.name ?? ""));
783
+ if (torrent?.browser_download_url) return unverifiable(torrent.browser_download_url, "该源只提供 .torrent,P2P 内容无法校验完整性");
784
+ const magnet = /(magnet:\?[^\s"'<>]+)/.exec(release.body ?? "");
785
+ if (magnet) return unverifiable(magnet[1], "该源只提供磁力链接,P2P 内容无法校验完整性");
831
786
  }
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 };
787
+ const [owner, repoName] = repo.split("/");
788
+ return unverifiable(
789
+ `https://codeload.github.com/${owner}/${repoName}/tar.gz/refs/tags/v${best.version}`,
790
+ "该仓库没有可校验的 release 资产,回退到源码归档下载(tag 可被移动)"
791
+ );
836
792
  }
837
793
 
838
794
  /**
@@ -906,10 +862,19 @@ async function fetchLatestGithubVersion(packageName, repoUrl, source, options) {
906
862
  return { version: latest, reason };
907
863
  }
908
864
 
909
- /** 在所有启用的源中取最高版本及其来源(并行查询;并列时随机,官方源权重一致)。 */
865
+ /**
866
+ * 在所有启用的源中取**可信**的最高版本及其来源(并行查询;并列时随机,官方源权重一致)。
867
+ *
868
+ * 安全修复(CWE-494)——**为什么 registry 优先**:registry(npm 兼容源)给出的是包名到
869
+ * 版本的权威映射;github 源只是"用户配置的仓库的 release tag",任何人都能建一个同名仓库
870
+ * 发 v999.0.0,且它的版本号与 npm 上的真实发布没有任何绑定关系。所以聚合必须先问
871
+ * registry:registry 有确定版本时其它源一律不参与(sourceTrust="registry");
872
+ * 只有 registry 都没给出版本时才允许用其它源兜底,并标记 degraded=true 供 UI 提示
873
+ * 「版本来自非官方源、未经 npm 校验」。
874
+ */
910
875
  async function fetchLatestAcross(packageName, sources, options) {
911
876
  const enabled = (sources ?? []).filter((source) => source?.enabled === true);
912
- if (enabled.length === 0) return { version: null, sourceName: null, repo: null, reason: REASON.NO_SOURCE };
877
+ if (enabled.length === 0) return { version: null, sourceName: null, repo: null, sourceTrust: null, degraded: false, reason: REASON.NO_SOURCE };
913
878
  const results = await Promise.allSettled(
914
879
  enabled.map((source) => fetchLatestVersion(packageName, source, options))
915
880
  );
@@ -918,8 +883,11 @@ async function fetchLatestAcross(packageName, sources, options) {
918
883
  return {
919
884
  version: value?.version ?? null,
920
885
  sourceName: enabled[index].name,
886
+ sourceUrl: enabled[index].url ?? null,
921
887
  repo: value?.repo ?? null,
922
888
  official: enabled[index].official === true,
889
+ // 信任分级依据:aggregateLatest 只让 type==="registry" 的源进入权威层
890
+ type: normalizeSourceType(enabled[index].type),
923
891
  // rejected(理论上不会发生)也归为不确定的网络类:绝不冒充「无更新」
924
892
  reason: value?.reason ?? REASON.NETWORK
925
893
  };
@@ -1729,6 +1697,11 @@ let PluginManagerPro = (() => {
1729
1697
  // H1:收敛判据修正后,等待只用于「真的会收敛」的情况;0.1.7 引擎只在启动时套用
1730
1698
  // cordis.patch.yml(无文件监听),因此默认值从 8s 收紧到 2.5s,避免白等。
1731
1699
  this.settleTimeoutMs = config.settleTimeoutMs ?? 2500;
1700
+ // CWE-494:下载完整性策略。默认 deny(fail-closed),显式 allow 才放行「无摘要」下载;
1701
+ // 摘要不匹配与明文 http 是硬红线,不受此开关影响。
1702
+ this.security = {
1703
+ unverifiedDownloads: config.security?.unverifiedDownloads === "allow" ? "allow" : "deny"
1704
+ };
1732
1705
  // L9:卸载自身前的自启清理(默认 20s 超时,测试可注入更短的值)
1733
1706
  this.selfPackageDir = typeof config.selfPackageDir === "string" && config.selfPackageDir !== "" ? config.selfPackageDir : null;
1734
1707
  this.autostartTimeoutMs = Number.isFinite(config.autostartTimeoutMs) ? Number(config.autostartTimeoutMs) : 20000;
@@ -1824,6 +1797,9 @@ let PluginManagerPro = (() => {
1824
1797
  const normalized = [];
1825
1798
  for (const s of sources ?? []) {
1826
1799
  if (s === null || typeof s !== "object" || typeof s.name !== "string" || typeof s.url !== "string") continue;
1800
+ // 安全修复:旧客户端仍可能提交 dshfind 类型的源 —— 直接丢弃(实现已移除,
1801
+ // 留着只会被当 registry 去请求 https://dshfind.com/...,永远 404)
1802
+ if (isLegacyDshfindSource(s)) continue;
1827
1803
  const url = s.url.trim().replace(/\/+$/, "");
1828
1804
  if (!/^https?:\/\//.test(url) || seen.has(url)) continue;
1829
1805
  seen.add(url);
@@ -2383,7 +2359,7 @@ setTimeout(() => {
2383
2359
  async cleanupOwnAutostart() {
2384
2360
  const skipped = (message) => ({ status: "skipped", exitCode: null, message, command: null });
2385
2361
  const directory = this.ownPackageDirectory();
2386
- if (directory === null) return skipped("无法定位管理器包目录,跳过开机自启清理(可手动执行 dsh-pm-launcher --uninstall)。");
2362
+ if (directory === null) return skipped("无法定位管理器包目录,跳过开机自启清理(可手动执行 dsh-drydock --uninstall)。");
2387
2363
  const script = join(directory, "bin", "open-boot.mjs");
2388
2364
  if (!existsSync(script)) return skipped(`包内没有 bin/open-boot.mjs(旧版本),跳过开机自启清理:${script}`);
2389
2365
  let source = "";
@@ -3163,17 +3139,36 @@ setTimeout(() => {
3163
3139
  this.profileDeps = readProfileDeps(this.location);
3164
3140
  return residuals;
3165
3141
  }
3166
- /** 解析某包在 github/dshfind 源的下载链接(供浏览器/NDM 手动下载)。 */
3142
+ /**
3143
+ * 安全修复(CWE-494)配套:按「刷新时命中的那个源」定位安装源。
3144
+ * 不能沿用 `sources.find(name)` + "查不到就随便拿一个启用源" 的兜底:源名称允许
3145
+ * 重复/可随时改,错配时会拿 github 源的版本用 registry 的 pnpm 装法去装(或反过来),
3146
+ * 等于绕过 registry 权威判定。这里按 URL(配置按 URL 去重)定位,再退回「名字唯一且
3147
+ * 类型一致」,都不行就明确报「配置已变更」,绝不乱猜。
3148
+ * @returns {{source?: object, message?: string}} source 为空时 message 是给用户看的中文原因。
3149
+ */
3150
+ bestSourceOf(best) {
3151
+ const enabled = this.sources.filter((s) => s?.enabled === true);
3152
+ if (enabled.length === 0) return { source: void 0, message: "没有启用的更新源。" };
3153
+ if (typeof best?.sourceUrl === "string" && best.sourceUrl !== "") {
3154
+ const exact = enabled.find((s) => s.url === best.sourceUrl);
3155
+ if (exact !== void 0) return { source: exact };
3156
+ }
3157
+ const wantedType = typeof best?.sourceType === "string" ? normalizeSourceType(best.sourceType) : null;
3158
+ const byName = enabled.filter((s) => s.name === best?.sourceName && (wantedType === null || normalizeSourceType(s.type) === wantedType));
3159
+ if (byName.length === 1) return { source: byName[0] };
3160
+ return { source: void 0, message: "找不到提供该版本的更新源(更新源配置可能已变更),请先重新检查更新。" };
3161
+ }
3162
+ /** 解析某包在 github 源的下载链接(供浏览器/NDM 手动下载)。 */
3167
3163
  async resolveDownloadUrl(packageName) {
3168
3164
  const best = LATEST_CACHE.get(packageName);
3169
3165
  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 };
3166
+ if (best === void 0 || best.sourceName === null) return { url: null, message: "没有可用的更新源信息,请先刷新检查更新。" };
3167
+ const found = this.bestSourceOf(best);
3168
+ if (found.source === void 0) return { url: null, message: found.message };
3169
+ const target = await resolveSourceDownloadUrl(found.source, best, { allowUnverifiedFallback: this.security.unverifiedDownloads === "allow" });
3170
+ if (target === null) return { url: null, message: "无法解析下载链接(该源未提供发布资产)。" };
3171
+ return { url: target.url, message: target.note ?? null, sourceName: found.source.name, installedVersion: info.installedVersion, latestVersion: best.version };
3177
3172
  }
3178
3173
  //#endregion
3179
3174
  //#region 启动前自检(自动化救援:坏 bundle 会在 boot 时让引擎起不来)
@@ -3230,7 +3225,7 @@ setTimeout(() => {
3230
3225
  });
3231
3226
  }
3232
3227
  //#endregion
3233
- /** 更新(内置下载器路径,registry 源 pnpm 直装;github/dshfind 走通用下载器)。 */
3228
+ /** 更新(内置下载器路径,registry 源 pnpm 直装;github 源走通用下载器)。 */
3234
3229
  async update(packageNames) {
3235
3230
  return await this.serialize(async () => {
3236
3231
  const items = [];
@@ -3277,24 +3272,25 @@ setTimeout(() => {
3277
3272
  items.push({ packageName, status: "up-to-date", url: null, sourceName: null, installedVersion: installed, latestVersion: best.version, message: null });
3278
3273
  continue;
3279
3274
  }
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: "没有启用的更新源。" });
3275
+ const found = this.bestSourceOf(best);
3276
+ if (found.source === void 0) {
3277
+ items.push({ packageName, status: "failed", url: null, sourceName: null, installedVersion: installed, latestVersion: best.version, message: found.message });
3283
3278
  continue;
3284
3279
  }
3280
+ const source = found.source;
3285
3281
  if (source.type === "registry") {
3286
3282
  // registry 源直接用内置 pnpm 路径更可靠
3287
3283
  const item = await this.updateOne(packageName);
3288
3284
  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
3285
  continue;
3290
3286
  }
3291
- const url = await resolveSourceDownloadUrl(source, best);
3292
- if (url === null) {
3287
+ const target = await resolveSourceDownloadUrl(source, best, { allowUnverifiedFallback: this.security.unverifiedDownloads === "allow" });
3288
+ if (target === null) {
3293
3289
  items.push({ packageName, status: "failed", url: null, sourceName: source.name, installedVersion: installed, latestVersion: best.version, message: "无法解析下载链接(该源未提供发布资产)。" });
3294
3290
  continue;
3295
3291
  }
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 下载后自动安装。" });
3292
+ this.log("updateBrowser", `${packageName} -> ${target.url.slice(0, 120)}`);
3293
+ 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
3294
  }
3299
3295
  return { items, snapshot: this.snapshot() };
3300
3296
  });
@@ -3332,8 +3328,8 @@ setTimeout(() => {
3332
3328
  }
3333
3329
  /**
3334
3330
  * 拉取插件市场目录(一次全量,客户端本地过滤/分页)。
3335
- * 数据源:awesome-dsh-plugin 精选目录(就是 dshfind 的收录池),
3336
- * 带分类/本地化描述/npm 包名/stars/收录日期;在线失败时兜底 GitHub
3331
+ * 数据源:awesome-dsh-plugin 精选目录(即旧"插件超市"的收录池,GitHub topic:dsh-plugin
3332
+ * 的精编清单);带分类/本地化描述/npm 包名/stars/收录日期;在线失败时兜底 GitHub
3337
3333
  * topic:dsh-plugin 搜索(限流 10/min —— 目录已缓存 10 分钟,极少触发)。
3338
3334
  * @returns {source, updated, count, categories, items}
3339
3335
  */
@@ -3442,19 +3438,39 @@ setTimeout(() => {
3442
3438
  const pnpmArgs = npm !== null ? ["add", npm] : null;
3443
3439
  if (pnpmArgs === null) {
3444
3440
  const [owner, repoName] = repo[1].split("/");
3441
+ // CWE-494:市场一键安装同样要过完整性校验。能拿到 release 资产的 digest 就强制校验;
3442
+ // 拿不到(无 digest / 只能回退源码归档)时按 security.unverifiedDownloads 决定放不放行。
3443
+ const allowUnverified = this.security.unverifiedDownloads === "allow";
3445
3444
  let downloadUrl = null;
3445
+ let expect;
3446
+ let unverifiedNote = "该仓库没有可校验的 release 资产,回退到源码归档下载(分支内容随时可被替换)";
3446
3447
  try {
3447
3448
  const release = await fetchGitHubRelease(repo[1]);
3448
3449
  if (release !== null) {
3449
3450
  const tgz = (release.assets ?? []).find((a) => /\.(tgz|tar\.gz)$/i.test(a.name ?? ""));
3450
- if (tgz?.browser_download_url) downloadUrl = tgz.browser_download_url;
3451
+ if (tgz?.browser_download_url) {
3452
+ downloadUrl = tgz.browser_download_url;
3453
+ expect = assetExpectOf(tgz) ?? undefined;
3454
+ if (expect === undefined) unverifiedNote = "该 release 资产没有摘要(digest)";
3455
+ }
3451
3456
  }
3452
3457
  if (downloadUrl === null) downloadUrl = `https://codeload.github.com/${owner}/${repoName}/tar.gz/refs/heads/main`;
3453
3458
  } catch {
3454
3459
  downloadUrl = `https://codeload.github.com/${owner}/${repoName}/tar.gz/refs/heads/main`;
3455
3460
  }
3456
- this.log("marketInstall", `${packageName} downloading ${downloadUrl.slice(0, 120)}`);
3457
- const dl = await downloadPluginUrl(downloadUrl, (line) => this.log("market-download", line));
3461
+ const noteForUser = expect !== undefined
3462
+ ? ""
3463
+ : allowUnverified
3464
+ ? `(注意:${unverifiedNote},本次下载未做完整性校验)`
3465
+ : `(${unverifiedNote},按默认安全策略已拒绝下载:如需继续,请在 profile 的 cordis.patch.yml 里为 dsh-drydock 设置 security.unverifiedDownloads: allow)`;
3466
+ this.log("marketInstall", `${packageName} downloading ${downloadUrl.slice(0, 120)}${noteForUser}`);
3467
+ if (expect === undefined && !allowUnverified) {
3468
+ return { status: "failed", packageName, url: installUrl, method, message: `${unverifiedNote},按默认安全策略已拒绝下载。如确需继续,请在 profile 的 cordis.patch.yml 里为 dsh-drydock 设置 security.unverifiedDownloads: allow。` };
3469
+ }
3470
+ const dl = await downloadPluginUrl(downloadUrl, (line) => this.log("market-download", line), {
3471
+ expect,
3472
+ allowUnverified: expect === undefined && allowUnverified
3473
+ });
3458
3474
  if (dl.status !== "downloaded" || dl.file === null) {
3459
3475
  return { status: "failed", packageName, url: installUrl, method, message: dl.message ?? "下载失败" };
3460
3476
  }
@@ -3589,20 +3605,23 @@ setTimeout(() => {
3589
3605
  latestVersion: best.version
3590
3606
  };
3591
3607
  }
3592
- const source = this.sources.find((s) => s.enabled && s.name === best.sourceName) ?? this.sources.find((s) => s.enabled);
3593
- if (source === void 0) {
3608
+ const found = this.bestSourceOf(best);
3609
+ if (found.source === void 0) {
3594
3610
  return {
3595
3611
  packageName,
3596
3612
  status: "not-managed",
3597
- message: "没有启用的更新源。",
3613
+ message: found.message,
3598
3614
  installedVersion: installed,
3599
3615
  latestVersion: best.version
3600
3616
  };
3601
3617
  }
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) {
3618
+ const source = found.source;
3619
+ // github 源:解析下载链接 -> 通用下载器(HTTP 直链 / magnet / torrent,支持 P2P)
3620
+ // 注意:这里不再接受 dshfind —— 它的实现与默认源已随 CWE-494 修复移除,
3621
+ // 旧侧车里的 dshfind 条目在读取时就被剔除,不会走到这个分支。
3622
+ if (source.type === "github") {
3623
+ const target = await resolveSourceDownloadUrl(source, best, { allowUnverifiedFallback: this.security.unverifiedDownloads === "allow" });
3624
+ if (target === null) {
3606
3625
  return {
3607
3626
  packageName,
3608
3627
  status: "not-managed",
@@ -3611,8 +3630,13 @@ setTimeout(() => {
3611
3630
  latestVersion: best.version
3612
3631
  };
3613
3632
  }
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));
3633
+ this.log("update", `${packageName}: downloading via ${source.type} from ${target.url.slice(0, 120)}${target.note === undefined ? "" : `(${target.note})`}`);
3634
+ // CWE-494:能拿到摘要就强制校验;拿不到时由 resolveSourceDownloadUrl 显式标 allowUnverified,
3635
+ // 下载器默认对「无从校验」一律拒绝(fail-closed),不会静默放行。
3636
+ const dl = await downloadPluginUrl(target.url, (line) => this.log("download", line), {
3637
+ expect: target.expect,
3638
+ allowUnverified: target.allowUnverified === true
3639
+ });
3616
3640
  if (dl.status !== "downloaded" || dl.file === null) {
3617
3641
  return {
3618
3642
  packageName,
@@ -3729,6 +3753,11 @@ setTimeout(() => {
3729
3753
  installedVersion: installed,
3730
3754
  latestVersion: latest,
3731
3755
  updateSource: latestEntry?.sourceName ?? null,
3756
+ // 安全修复(CWE-494):版本来自哪一层信任 —— registry=官方/镜像 registry 权威源;
3757
+ // fallback=registry 都没给出版本时用 github 等源兜底(updateDegraded=true,
3758
+ // UI 应提示「版本来自非官方源、未经 npm 校验」)。旧缓存条目无此字段 → null/false。
3759
+ updateSourceTrust: latestEntry?.sourceTrust ?? null,
3760
+ updateDegraded: latestEntry?.degraded === true,
3732
3761
  // C-09:把「为什么没有版本信息」也带上(network/timeout/not-found/backoff),UI 才能说实话
3733
3762
  updateReason: latestEntry?.reason ?? null,
3734
3763
  needsUpdate,
@@ -3957,7 +3986,21 @@ export const Config = z.object({
3957
3986
  /** 额外受保护条目 id 列表(不会被管理器开关/隔离)。 */
3958
3987
  protectedEntries: z.array(z.string()).default([]),
3959
3988
  /** 开关状态变更后等待运行期收敛的超时(毫秒);0.1.7 引擎不热重载 cordis.patch.yml,故收紧默认值。 */
3960
- settleTimeoutMs: z.number().min(100).max(120000).default(2500)
3989
+ settleTimeoutMs: z.number().min(100).max(120000).default(2500),
3990
+ /**
3991
+ * 下载完整性策略(CWE-494,1.0.2 起)。
3992
+ *
3993
+ * 默认 `deny`(fail-closed):**拿不到可校验摘要的下载一律拒绝**,并给出可操作的中文提示。
3994
+ * 这是安全默认值 —— 更新模块允许自定义更新源,某些自建/老仓库确实不提供 digest,
3995
+ * 所以留了 `allow` 开关:显式开启后放行,但下载回执与界面会标注「未校验来源」。
3996
+ *
3997
+ * **以下两条不受此开关影响,永远拒绝**:
3998
+ * · 摘要不匹配(integrity / size 对不上)—— 内容已被篡改,没有任何理由放行;
3999
+ * · 明文 `http://`(含 https→http 重定向降级)—— 传输可被中间人替换。
4000
+ */
4001
+ security: z.object({
4002
+ unverifiedDownloads: z.enum(["deny", "allow"]).default("deny")
4003
+ }).default({})
3961
4004
  }).default({});
3962
4005
 
3963
4006
  /** 仅测试用内部工具(不参与 Cordis 装配,见 tools/test-host-fixes.mjs)。 */
@@ -3999,11 +4042,9 @@ export const __internals = {
3999
4042
  fetchLatestVersion,
4000
4043
  fetchLatestAcross,
4001
4044
  refreshLatest,
4002
- fetchLatestDshfindVersion,
4003
4045
  REASON,
4004
4046
  VERSION_TTL_MS,
4005
4047
  NEGATIVE_TTL_MS,
4006
- DSFFIND_SEARCH_TTL_MS,
4007
4048
  BACKOFF_BASE_MS,
4008
4049
  REFRESH_BUDGET_DEFAULT_MS,
4009
4050
  getRefreshBudgetMs: () => refreshBudgetMs,
@@ -4014,7 +4055,6 @@ export const __internals = {
4014
4055
  cacheSnapshot: () => ({
4015
4056
  version: [...VERSION_CACHE.entries()].map(([key, value]) => ({ key, latest: value.latest, at: value.at })),
4016
4057
  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
4058
  backoff: [...SOURCE_BACKOFF.entries()].map(([key, value]) => ({ key, streak: value.streak, until: value.until })),
4019
4059
  cooldown: [...SOURCE_COOLDOWN.entries()].map(([key, until]) => ({ key, until })),
4020
4060
  catalogAt: CATALOG_CACHE.at,
@@ -4025,7 +4065,6 @@ export const __internals = {
4025
4065
  VERSION_CACHE.clear();
4026
4066
  VERSION_FAILURE_CACHE.clear();
4027
4067
  LATEST_CACHE.clear();
4028
- DSFFIND_SEARCH_CACHE.clear();
4029
4068
  SOURCE_BACKOFF.clear();
4030
4069
  SOURCE_COOLDOWN.clear();
4031
4070
  CATALOG_CACHE.at = 0;