dsh-drydock 1.0.2 → 1.0.4

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,12 +330,221 @@ 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: "GitHub 官方仓库", url: "https://github.com/deepseek-ai/deepseek-harness", enabled: false, official: true, type: "github" },
335
- { 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" }
336
339
  ];
337
340
 
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
+
338
548
  /**
339
549
  * 安全修复(CWE-494 供应链投毒)——dshfind(插件超市)源**整体移除**,不再提供:
340
550
  * 它把 `topic:dsh-plugin <包名>` 的 GitHub 搜索结果里**第一个同名仓库**当发布源
@@ -363,7 +573,8 @@ function normalizeSourceType(type) {
363
573
  function defaultSidecarState() {
364
574
  return {
365
575
  version: SIDECAR_VERSION,
366
- sources: structuredClone(DEFAULT_SOURCES),
576
+ // 内置源也走服务端归一化:official/authoritative 一律由白名单判定,不沿用常量里的自报值
577
+ sources: DEFAULT_SOURCES.map((source) => normalizeSourceRecord(source)).filter((source) => source !== null),
367
578
  rescue: { autoQuarantine: false },
368
579
  // 来源人工修正:packageName -> 标签(npm / github / local / builtin)
369
580
  overrides: { source: {} },
@@ -373,6 +584,8 @@ function defaultSidecarState() {
373
584
  scenarios: [],
374
585
  // 卸载残留(Windows 文件锁导致的删除失败,下次启动重试)
375
586
  pendingRemovals: [],
587
+ // 下载目录 provenance:本管理器生成过下载链接的期望记录(checkDownloads 的唯一入口凭证)
588
+ pendingDownloads: [],
376
589
  // 自动隔离的连续失败计数:configId -> 次数(跨启动累计,H3)
377
590
  failureStreak: {}
378
591
  };
@@ -414,18 +627,19 @@ function readSidecarState(location) {
414
627
  try {
415
628
  const parsed = JSON.parse(readFileSync(join(location.directory, SIDECAR_FILENAME), "utf8"));
416
629
  if (Array.isArray(parsed?.sources)) {
417
- const sources = parsed.sources
418
- .filter((s) => s !== null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string" && /^https?:\/\//.test(s.url))
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;
419
634
  // 安全修复:旧侧车里的 dshfind 条目直接丢弃 —— 该源的实现已移除,
420
635
  // 留着它会被当成 registry 去请求 https://dshfind.com/...(永远 404 还污染版本缓存)。
421
- .filter((s) => !isLegacyDshfindSource(s))
422
- .map((s) => ({
423
- name: (s.name.trim() || s.url).slice(0, 64),
424
- url: s.url.trim().replace(/\/+$/, ""),
425
- enabled: s.enabled !== false,
426
- official: s.official === true,
427
- type: normalizeSourceType(s.type)
428
- }));
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
+ }
429
643
  if (sources.length > 0) state.sources = sources;
430
644
  }
431
645
  state.rescue = { autoQuarantine: parsed?.rescue?.autoQuarantine === true };
@@ -454,6 +668,8 @@ function readSidecarState(location) {
454
668
  if (Array.isArray(parsed?.pendingRemovals)) {
455
669
  state.pendingRemovals = parsed.pendingRemovals.filter((p) => typeof p === "string");
456
670
  }
671
+ // 下载目录 provenance 记录(旧侧车没有该字段 → 默认空数组:不认任何历史下载)
672
+ state.pendingDownloads = normalizePendingDownloads(parsed?.pendingDownloads);
457
673
  if (parsed?.failureStreak !== null && typeof parsed?.failureStreak === "object") {
458
674
  for (const [id, count] of Object.entries(parsed.failureStreak)) {
459
675
  if (typeof id === "string" && Number.isInteger(count) && count > 0) state.failureStreak[id] = Math.min(count, 16);
@@ -671,9 +887,18 @@ async function fetchLatestVersion(packageName, source, options) {
671
887
  });
672
888
  if (response.ok) {
673
889
  const meta = await response.json();
674
- const tags = meta["dist-tags"];
675
- // @deepseek-ai/* 的正式发布走 next 轨道(latest 停留在占位版)
676
- 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
+ }
677
902
  // 源明确答复但没有任何可用 tag:确定性「无更新」
678
903
  if (latest === null) reason = REASON.NOT_FOUND;
679
904
  } else if (response.status === 404) {
@@ -863,14 +1088,14 @@ async function fetchLatestGithubVersion(packageName, repoUrl, source, options) {
863
1088
  }
864
1089
 
865
1090
  /**
866
- * 在所有启用的源中取**可信**的最高版本及其来源(并行查询;并列时随机,官方源权重一致)。
1091
+ * 在所有启用的源中取**可信**的最高版本及其来源(并行查询;并列时随机,源权重一致)。
867
1092
  *
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 校验」。
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 提示「版本来自非权威源」。
874
1099
  */
875
1100
  async function fetchLatestAcross(packageName, sources, options) {
876
1101
  const enabled = (sources ?? []).filter((source) => source?.enabled === true);
@@ -886,7 +1111,10 @@ async function fetchLatestAcross(packageName, sources, options) {
886
1111
  sourceUrl: enabled[index].url ?? null,
887
1112
  repo: value?.repo ?? null,
888
1113
  official: enabled[index].official === true,
889
- // 信任分级依据:aggregateLatest 只让 type==="registry" 的源进入权威层
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→下载器)
890
1118
  type: normalizeSourceType(enabled[index].type),
891
1119
  // rejected(理论上不会发生)也归为不确定的网络类:绝不冒充「无更新」
892
1120
  reason: value?.reason ?? REASON.NETWORK
@@ -1554,6 +1782,29 @@ const DEFAULT_PROTECTED_IDS = new Set([
1554
1782
  "drydock"
1555
1783
  ]);
1556
1784
 
1785
+ /**
1786
+ * 救援路由统一安全响应头(1.0.4 攻击测试残留收口)。
1787
+ *
1788
+ * 适用范围:/rescue 200、/rescue 401/403、/plugins-launcher 200。
1789
+ * - CSP:`default-src 'none'` 全禁;救援页脚本/样式都是内联的,所以保留
1790
+ * `script-src 'unsafe-inline'` / `style-src 'unsafe-inline'`;图片只允许 self/data;
1791
+ * `connect-src 'self'` 放行同源 RPC(页面用 fetch 调同源救援 API);
1792
+ * `frame-ancestors 'none'` / `base-uri 'none'` 防嵌套与 base 劫持。
1793
+ * - X-Frame-Options: DENY(老浏览器兼容 CSP frame-ancestors)。
1794
+ * - X-Content-Type-Options: nosniff(禁止 MIME 嗅探)。
1795
+ * - Referrer-Policy: no-referrer(页面 URL 不外泄给第三方)。
1796
+ *
1797
+ * 注意:bin/rescue-daemon.mjs 里定义了一份**相同的副本**(3082 独立入口不经本插件导入;
1798
+ * 该入口被 open-boot 复用时也不应依赖插件模块),两处必须保持一致,
1799
+ * test-daemon-security.mjs 会校验 3082 侧。
1800
+ */
1801
+ export const RESCUE_SECURITY_HEADERS = Object.freeze({
1802
+ "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'",
1803
+ "x-frame-options": "DENY",
1804
+ "x-content-type-options": "nosniff",
1805
+ "referrer-policy": "no-referrer"
1806
+ });
1807
+
1557
1808
  /** 本地插件管理器宿主服务。 */
1558
1809
  let PluginManagerPro = (() => {
1559
1810
  let _classSuper = TypertRemoteService;
@@ -1790,9 +2041,17 @@ let PluginManagerPro = (() => {
1790
2041
  getSources() {
1791
2042
  return this.snapshot();
1792
2043
  }
1793
- /** 校验并保存更新源列表,随后立即重新检测所有包的最新版本。 */
2044
+ /**
2045
+ * 校验并保存更新源列表,随后立即重新检测所有包的最新版本。
2046
+ *
2047
+ * 1.0.3(A 报告 S1):所有信任字段由服务端 `normalizeSourceRecord` 判定 ——
2048
+ * 客户端提交的 `official` 被忽略;新增源默认非权威;升权威要显式 `authoritative:true`
2049
+ * (明文 http 还要 `allowInsecure:true`,否则降级并在 note 说明)。
2050
+ * 每次保存都写一条操作历史(前后 URL 集合 / 权威层变化 / 是否含明文源)。
2051
+ */
1794
2052
  async setSources(sources) {
1795
2053
  return await this.serialize(async () => {
2054
+ const before = this.sources.map((source) => ({ ...source }));
1796
2055
  const seen = new Set();
1797
2056
  const normalized = [];
1798
2057
  for (const s of sources ?? []) {
@@ -1800,16 +2059,11 @@ let PluginManagerPro = (() => {
1800
2059
  // 安全修复:旧客户端仍可能提交 dshfind 类型的源 —— 直接丢弃(实现已移除,
1801
2060
  // 留着只会被当 registry 去请求 https://dshfind.com/...,永远 404)
1802
2061
  if (isLegacyDshfindSource(s)) continue;
1803
- const url = s.url.trim().replace(/\/+$/, "");
1804
- if (!/^https?:\/\//.test(url) || seen.has(url)) continue;
1805
- seen.add(url);
1806
- normalized.push({
1807
- name: (s.name.trim() || url).slice(0, 64),
1808
- url,
1809
- enabled: s.enabled !== false,
1810
- official: s.official === true,
1811
- type: normalizeSourceType(s.type)
1812
- });
2062
+ // 服务端归一化:official / authoritative / insecure 不采信客户端自报值
2063
+ const record = normalizeSourceRecord(s);
2064
+ if (record === null || seen.has(record.url)) continue;
2065
+ seen.add(record.url);
2066
+ normalized.push(record);
1813
2067
  }
1814
2068
  this.sources = normalized;
1815
2069
  this.sidecar.sources = normalized;
@@ -1819,6 +2073,8 @@ let PluginManagerPro = (() => {
1819
2073
  LATEST_CACHE.clear();
1820
2074
  SOURCE_BACKOFF.clear();
1821
2075
  await writeSidecarState(this.location, this.sidecar);
2076
+ // 变更审计:来源配置属于高影响写操作,前后差异必须留痕(进操作历史)
2077
+ await this.recordHistory("setSources", "更新源配置", describeSourceChange(before, normalized), null, "ok");
1822
2078
  // 全量重检放后台执行:不阻塞保存操作(并行化后约等于最慢源的一次往返)
1823
2079
  void this.refresh().catch((error) => this.log("refresh", `background refresh failed: ${error instanceof Error ? error.message : String(error)}`));
1824
2080
  return this.snapshot();
@@ -2885,14 +3141,71 @@ setTimeout(() => {
2885
3141
  getRescueConfig() {
2886
3142
  return { autoQuarantine: this.rescueConfig?.autoQuarantine === true };
2887
3143
  }
3144
+ //#region 救援路由安全响应头(1.0.4)
3145
+ /* 常量本身在模块顶层(RESCUE_SECURITY_HEADERS),这里只做使用说明:
3146
+ * /rescue 200、/rescue 401/403、/plugins-launcher 200 统一附加。
3147
+ * 注意:bin/rescue-daemon.mjs 里同样定义了一份(3082 独立入口不经本插件导入),
3148
+ * 两处必须保持一致;test-daemon-security.mjs 会校验 3082 侧。 */
3149
+ //#endregion
3150
+
3151
+ /**
3152
+ * 宿主准入:把 DSH Connection 的 Host/Origin 校验与浏览器认证应用到本插件的
3153
+ * Web 路由(/rescue、/plugins-launcher)。这两条路由经 webServer.register 直接
3154
+ * 暴露,不经过 /api 桥接;不校验的话,任何能访问 3080 的来源(含跨站页面)
3155
+ * 都能打开救援页并调用救援方法。
3156
+ *
3157
+ * 判定来源与 /api 完全一致(ctx.connection.requestRejection):
3158
+ * undefined → 放行;401 → 未认证;403 → Host/Origin 校验失败。
3159
+ * 宿主没有 Connection 服务(headless / 更早的引擎)时返回 null 保留旧行为,
3160
+ * 只记一次日志——救援页是恢复路径,不应因缺少可选服务而整体不可用。
3161
+ * 判定自身抛错时按拒绝处理(fail-closed),避免「校验坏了就敞开」。
3162
+ */
3163
+ hostAdmissionRejection(req) {
3164
+ let connection;
3165
+ try {
3166
+ connection = this.ctx.get("connection");
3167
+ } catch {
3168
+ connection = void 0;
3169
+ }
3170
+ if (connection === void 0 || typeof connection.requestRejection !== "function") {
3171
+ if (!this.admissionUnavailableLogged) {
3172
+ this.admissionUnavailableLogged = true;
3173
+ this.log("admission", "host admission unavailable (no ctx.connection.requestRejection) — /rescue and /plugins-launcher keep serving unauthenticated (loopback deployments only)");
3174
+ }
3175
+ return null;
3176
+ }
3177
+ try {
3178
+ return connection.requestRejection({ headers: req.headers }) ?? null;
3179
+ } catch (error) {
3180
+ this.log("admission", `check failed: ${error instanceof Error ? error.message : String(error)} — refusing (fail-closed)`);
3181
+ return 403;
3182
+ }
3183
+ }
3184
+ /** 拒绝一次请求:401 未认证 / 403 来源被拒(中文优先,救援场景更好读)。 */
3185
+ rejectForAdmission(res, status) {
3186
+ res.writeHead(status, {
3187
+ ...RESCUE_SECURITY_HEADERS,
3188
+ "content-type": "text/plain; charset=utf-8",
3189
+ "cache-control": "no-store"
3190
+ });
3191
+ res.end(status === 401
3192
+ ? "未认证:请先在本浏览器打开 DSH 应用(完成 ?token= 登录),再访问 /rescue。\nUnauthorized: open the DSH app in this browser first so it can issue your session cookie.\n"
3193
+ : "已拒绝:主机/来源准入校验失败(Host/Origin admission failed)。\nForbidden: Host/Origin admission failed.\n");
3194
+ }
2888
3195
  /** /rescue 救援页(独立 HTML,不依赖任何客户端插件)。 */
2889
3196
  serveRescue(req, res) {
3197
+ const rejection = this.hostAdmissionRejection(req);
3198
+ if (rejection !== null) {
3199
+ this.rejectForAdmission(res, rejection);
3200
+ return;
3201
+ }
2890
3202
  if (req.method !== "GET" && req.method !== "HEAD") {
2891
3203
  res.writeHead(405);
2892
3204
  res.end();
2893
3205
  return;
2894
3206
  }
2895
3207
  res.writeHead(200, {
3208
+ ...RESCUE_SECURITY_HEADERS,
2896
3209
  "content-type": "text/html; charset=utf-8",
2897
3210
  "cache-control": "no-store"
2898
3211
  });
@@ -2910,14 +3223,20 @@ setTimeout(() => {
2910
3223
  } catch { /* 没有 pid 文件:启动器可能未通过 --ensure/--supervise 启动过 */ }
2911
3224
  return { ok: true, ...launcherUrlFrom({ pidInfo }) };
2912
3225
  }
2913
- /** GET /plugins-launcher → {ok, port, url}(只读,无令牌)。 */
3226
+ /** GET /plugins-launcher → {ok, port, url}(只读,无令牌;同样经过宿主准入)。 */
2914
3227
  serveLauncherInfo(req, res) {
3228
+ const rejection = this.hostAdmissionRejection(req);
3229
+ if (rejection !== null) {
3230
+ this.rejectForAdmission(res, rejection);
3231
+ return;
3232
+ }
2915
3233
  if (req.method !== "GET" && req.method !== "HEAD") {
2916
3234
  res.writeHead(405);
2917
3235
  res.end();
2918
3236
  return;
2919
3237
  }
2920
3238
  res.writeHead(200, {
3239
+ ...RESCUE_SECURITY_HEADERS,
2921
3240
  "content-type": "application/json; charset=utf-8",
2922
3241
  "cache-control": "no-store"
2923
3242
  });
@@ -2933,12 +3252,59 @@ setTimeout(() => {
2933
3252
  return { dir: this.downloadDir() };
2934
3253
  }
2935
3254
  /**
2936
- * 扫描下载目录:新出现的 npm 包归档走「marketInstall 同款校验」后再安装(H4 修复)。
2937
- * 1) 只接受 npm 包归档(.tgz / .tar.gz);.zip 直接拒绝(pnpm 无法作为包安装)
2938
- * 2) 先复制到 profile 内的稳定暂存路径再交给 pnpm(同时规避 Windows cmd 的空白/% 展开面)
2939
- * 3) 装后校验:新装包必须声明 dsh.bundle / dsh.client,且 profile 启动前自检通过
2940
- * 4) 任一环节失败 -> 回滚(pnpm remove + 兜底删目录 + 复原 manifest)+ 写 .failed stamp,
2941
- * 失败文件不再每次点击都重试(删除 `.<name>.failed` 即可重试)
3255
+ * 记录一条下载期望(provenance)。
3256
+ *
3257
+ * updateBrowser / resolveDownloadUrl 生成下载链接时调用;浏览器/NDM 下载到
3258
+ * `$DSH_HOME/downloads` 后,checkDownloads 只接受能在 pendingDownloads 里找到
3259
+ * 同 name+version 记录的归档。按 packageName+version 去重,保留最近 PENDING_DOWNLOAD_MAX 条。
3260
+ */
3261
+ rememberPendingDownload({ url, packageName, version, sourceName, expect }) {
3262
+ const list = Array.isArray(this.sidecar.pendingDownloads) ? this.sidecar.pendingDownloads : [];
3263
+ const record = {
3264
+ url: String(url),
3265
+ packageName,
3266
+ version: String(version),
3267
+ sourceName: typeof sourceName === "string" ? sourceName : null,
3268
+ expect: normalizeDownloadExpect(expect),
3269
+ at: new Date().toISOString()
3270
+ };
3271
+ const kept = list.filter((item) => !(item?.packageName === packageName && item?.version === record.version));
3272
+ kept.push(record);
3273
+ this.sidecar.pendingDownloads = kept.slice(-PENDING_DOWNLOAD_MAX);
3274
+ return record;
3275
+ }
3276
+ /** 找一条未过期的下载期望记录(顺手清掉过期记录,避免侧车无限增长)。 */
3277
+ findPendingDownload(packageName, version) {
3278
+ const list = Array.isArray(this.sidecar.pendingDownloads) ? this.sidecar.pendingDownloads : [];
3279
+ const now = Date.now();
3280
+ const fresh = list.filter((item) => {
3281
+ const at = typeof item?.at === "string" ? Date.parse(item.at) : Number.NaN;
3282
+ return !Number.isNaN(at) && now - at <= PENDING_DOWNLOAD_TTL_MS;
3283
+ });
3284
+ if (fresh.length !== list.length) this.sidecar.pendingDownloads = fresh;
3285
+ return fresh.find((item) => item.packageName === packageName && item.version === version) ?? null;
3286
+ }
3287
+ /** 安装成功后移除该记录;失败的记录保留(不重复噪音,也不给"失败文件重试"留下歧义)。 */
3288
+ dropPendingDownload(record) {
3289
+ const list = Array.isArray(this.sidecar.pendingDownloads) ? this.sidecar.pendingDownloads : [];
3290
+ this.sidecar.pendingDownloads = list.filter((item) => !(item !== null && typeof item === "object" && item.packageName === record.packageName && item.version === record.version));
3291
+ }
3292
+ /**
3293
+ * 扫描下载目录并安装 **有 provenance 记录** 的 npm 包归档。
3294
+ *
3295
+ * 1.0.2 之前这里是"目录里任何 .tgz 都自动 pnpm add",等于给 $DSH_HOME/downloads
3296
+ * 开了一个免校验的代码投放口(B 报告 S1):能往该目录写文件的人(同机进程、同步盘、
3297
+ * 恶意 zip 解压)就能让 pnpm 在 host 里执行生命周期脚本,1.0.2 的摘要门禁在此完全旁路。
3298
+ *
3299
+ * 现在的判定顺序:
3300
+ * 1) 只接受 .tgz / .tar.gz(.zip 直接拒绝,pnpm 无法作为包安装);
3301
+ * 2) 用 node:zlib 读归档内 `package/package.json` → 得到它自称的 name/version;
3302
+ * 3) 在 sidecar.pendingDownloads 里找同 name+version 且未过期(7 天)的记录 ——
3303
+ * 没有记录 = 不是本管理器生成的下载链接 → 拒绝并写 .failed;
3304
+ * 4) 记录带摘要(integrity/shasum)→ 流式校验一致才继续;只有 size 不算校验;
3305
+ * 5) 之后才进入原有 installDownloadedArchive(稳定暂存 -> pnpm -> dsh 清单校验 ->
3306
+ * profile 自检 -> 失败回滚),成功后移除记录。
3307
+ * 失败文件写 `.failed` stamp:删掉 `.failed` 即"显式确认后重试"。
2942
3308
  */
2943
3309
  async checkDownloads() {
2944
3310
  return await this.serialize(async () => {
@@ -2968,15 +3334,40 @@ setTimeout(() => {
2968
3334
  reject("只支持 npm 包归档(.tgz / .tar.gz);.zip 不能作为 npm 包安装,已拒绝(删除该 .failed 标记可重试)。");
2969
3335
  continue;
2970
3336
  }
3337
+ // 步骤 2:读归档内 package.json —— 先确定"这个文件声称自己是哪个包哪个版本"
3338
+ const manifest = readArchivePackageManifest(file);
3339
+ if (manifest === null) {
3340
+ reject("不是有效的 npm 包归档(读不到 package/package.json),无法校验来源,已拒绝(删除该 .failed 标记可重试)。");
3341
+ continue;
3342
+ }
3343
+ // 步骤 3:provenance 记录是唯一入口凭证
3344
+ const record = this.findPendingDownload(manifest.name, manifest.version);
3345
+ if (record === null) {
3346
+ reject(`未找到来源记录(不是本管理器生成的下载链接):${manifest.name}@${manifest.version}。确认可信后再删除 .failed 重试(或先在管理器中重新生成该包的下载链接)。`);
3347
+ continue;
3348
+ }
3349
+ // 步骤 4:有摘要就流式校验(摘要不符 = 内容可能被替换,硬拒绝)
3350
+ const proof = await verifyArchiveDigest(file, record.expect);
3351
+ if (!proof.ok) {
3352
+ reject(proof.message ?? "归档摘要校验失败,已拒绝安装。");
3353
+ continue;
3354
+ }
2971
3355
  const outcome = await this.installDownloadedArchive(name, file);
2972
3356
  if (outcome.ok) {
2973
3357
  writeFileSync(stamp, new Date().toISOString(), "utf8");
2974
3358
  installed.push(name);
2975
- this.log("checkDownloads", `installed ${name}`);
3359
+ this.dropPendingDownload(record);
3360
+ this.log("checkDownloads", `installed ${name} (${manifest.name}@${manifest.version}${proof.verified ? ",摘要已校验" : ",来源记录无摘要"})`);
2976
3361
  } else {
2977
3362
  reject(outcome.message);
2978
3363
  }
2979
3364
  }
3365
+ // pendingDownloads 可能被安装成功/过期清理改动过 → 落盘(写失败不改变本次结果)
3366
+ try {
3367
+ await writeSidecarState(this.location, this.sidecar);
3368
+ } catch (error) {
3369
+ this.log("checkDownloads", `sidecar write failed: ${error instanceof Error ? error.message : String(error)}`);
3370
+ }
2980
3371
  return { installed, failed, message: null };
2981
3372
  });
2982
3373
  }
@@ -3159,16 +3550,24 @@ setTimeout(() => {
3159
3550
  if (byName.length === 1) return { source: byName[0] };
3160
3551
  return { source: void 0, message: "找不到提供该版本的更新源(更新源配置可能已变更),请先重新检查更新。" };
3161
3552
  }
3162
- /** 解析某包在 github 源的下载链接(供浏览器/NDM 手动下载)。 */
3553
+ /**
3554
+ * 解析某包在 github 源的下载链接(供浏览器/NDM 手动下载)。
3555
+ * 1.0.3:生成链接的同时把期望(URL + name@version + 摘要)写进 sidecar.pendingDownloads,
3556
+ * 下载到 $DSH_HOME/downloads 后 checkDownloads 只认这些记录(B 报告 S1 provenance)。
3557
+ */
3163
3558
  async resolveDownloadUrl(packageName) {
3164
- const best = LATEST_CACHE.get(packageName);
3165
- const info = packageInfoOf(packageName, this.baseUrl);
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 };
3559
+ return await this.serialize(async () => {
3560
+ const best = LATEST_CACHE.get(packageName);
3561
+ const info = packageInfoOf(packageName, this.baseUrl);
3562
+ if (best === void 0 || best.sourceName === null) return { url: null, message: "没有可用的更新源信息,请先刷新检查更新。" };
3563
+ const found = this.bestSourceOf(best);
3564
+ if (found.source === void 0) return { url: null, message: found.message };
3565
+ const target = await resolveSourceDownloadUrl(found.source, best, { allowUnverifiedFallback: this.security.unverifiedDownloads === "allow" });
3566
+ if (target === null) return { url: null, message: "无法解析下载链接(该源未提供发布资产)。" };
3567
+ this.rememberPendingDownload({ url: target.url, packageName, version: best.version, sourceName: found.source.name, expect: target.expect });
3568
+ await writeSidecarState(this.location, this.sidecar);
3569
+ return { url: target.url, message: target.note ?? null, sourceName: found.source.name, installedVersion: info.installedVersion, latestVersion: best.version };
3570
+ });
3172
3571
  }
3173
3572
  //#endregion
3174
3573
  //#region 启动前自检(自动化救援:坏 bundle 会在 boot 时让引擎起不来)
@@ -3290,8 +3689,11 @@ setTimeout(() => {
3290
3689
  continue;
3291
3690
  }
3292
3691
  this.log("updateBrowser", `${packageName} -> ${target.url.slice(0, 120)}`);
3692
+ // provenance:把本次下载的期望记进侧车,checkDownloads 只认这些记录
3693
+ this.rememberPendingDownload({ url: target.url, packageName, version: best.version, sourceName: source.name, expect: target.expect });
3293
3694
  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}` });
3294
3695
  }
3696
+ await writeSidecarState(this.location, this.sidecar);
3295
3697
  return { items, snapshot: this.snapshot() };
3296
3698
  });
3297
3699
  }
@@ -3701,7 +4103,13 @@ setTimeout(() => {
3701
4103
  return {
3702
4104
  profileName: this.location.profileName,
3703
4105
  entries,
3704
- sources: this.sources.map((s) => ({ ...s })),
4106
+ // 1.0.3:official/authoritative/insecure 都在这里按服务端规则重算一遍,
4107
+ // 保证请求体/侧车里的自报 official 永远驱动不了「官方」徽标与信任层。
4108
+ sources: this.sources.map((source) => {
4109
+ const url = normalizeSourceUrl(source?.url);
4110
+ const official = isBuiltinAuthoritativeUrl(url);
4111
+ return { ...source, url, official, insecure: isInsecureSourceUrl(url), authoritative: source?.authoritative === true || official };
4112
+ }),
3705
4113
  // C-03/C-04:最近一次「检查更新」的预算执行结果(客户端据此提示「网络慢、已按预算中止」)
3706
4114
  lastRefresh: this.lastRefresh ?? null
3707
4115
  };
@@ -3753,9 +4161,10 @@ setTimeout(() => {
3753
4161
  installedVersion: installed,
3754
4162
  latestVersion: latest,
3755
4163
  updateSource: latestEntry?.sourceName ?? null,
3756
- // 安全修复(CWE-494):版本来自哪一层信任 —— registry=官方/镜像 registry 权威源;
3757
- // fallback=registry 都没给出版本时用 github 等源兜底(updateDegraded=true,
3758
- // UI 应提示「版本来自非官方源、未经 npm 校验」)。旧缓存条目无此字段 → null/false。
4164
+ // 安全修复(CWE-494):版本来自哪一层信任 —— authoritative=服务端判定的权威源
4165
+ // (内置白名单或显式升级);fallback=权威源都没给出版本时用非权威源兜底
4166
+ // (updateDegraded=true,UI 应提示「版本来自非权威源、未经 npm 校验」)。
4167
+ // 旧缓存条目无此字段 → null/false。
3759
4168
  updateSourceTrust: latestEntry?.sourceTrust ?? null,
3760
4169
  updateDegraded: latestEntry?.degraded === true,
3761
4170
  // C-09:把「为什么没有版本信息」也带上(network/timeout/not-found/backoff),UI 才能说实话