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/bin/open-boot.mjs CHANGED
@@ -6,6 +6,18 @@
6
6
  * 自动 verify → 有问题自动 fix(隔离坏 bundle)→ 拉起 `dsh web` → 跳转 3080。
7
7
  *
8
8
  * 设计取舍:
9
+ * - 1.0.3(安全性能审查 S3/S4/P1/P2):
10
+ * · **Host 头校验(S3)**:请求入口只接受 `127.0.0.1:<port>` / `localhost:<port>` / `[::1]:<port>`
11
+ * (带端口、大小写不敏感),其余 421 JSON —— 挡住"攻击者域名解析到 127.0.0.1 后同源读接口"
12
+ * 的 DNS 重绑定;校验在**路由之前**。
13
+ * · **统一安全响应头(S4)**:CSP(default-src 'none' + script/style 'unsafe-inline' + connect-src 'self'
14
+ * + frame-ancestors 'none' + base-uri 'none')、X-Frame-Options DENY、nosniff、Referrer-Policy
15
+ * no-referrer,覆盖 sendHtml/sendJson/救援页/404/421;页面内联脚本样式照常可跑。
16
+ * · **bundles GET 也过 Origin+令牌(S3 附带)**:已装插件清单不再裸奔(页面 api() 本就带令牌)。
17
+ * · **updates 缓存 + 单飞(P1)**:30 分钟缓存(key=profile,另存 pnpm-lock.yaml 的 mtime+size 失效)、
18
+ * 并发共用 in-flight Promise(不再重复起 pnpm)、`pnpm --version` 成功结果进程内缓存 → 热调用 < 10ms。
19
+ * · **runPnpm 有界缓冲(P2)**:stdout/stderr 只保末尾 16KB + `<...已截断 N 字节>` 标记,长驻守护不再堆峰值。
20
+ * · **启动页 log() 改逐行 DOM(S4)**:textContent 追加,不再 innerHTML 拼接。
9
21
  * - 3081 独立入口,无端口争抢(v0.7.0 的 3080 接管模式已移除)。
10
22
  * - **平时隐藏,拉起引擎时弹窗**:常驻守护自身无任何窗口;
11
23
  * 只有当引擎(3080)真的不在时,才弹出一个**可见的启动窗口**,
@@ -1522,13 +1534,36 @@ pre{background:#0b0d11;border:1px solid #2a2e38;border-radius:8px;padding:12px;f
1522
1534
  <h1>${drydockLogoMarkSvg(20)} 🚀 DSH 启动器</h1>
1523
1535
  <div class="sub">正在执行 自检 → 修复 → 启动,完成后自动打开主界面…</div>
1524
1536
  <div class="spinner" id="spin"></div>
1537
+ <div class="sub" id="elapsed" aria-live="polite" style="margin:-6px 0 10px;font-size:12.5px"></div>
1525
1538
  <pre id="out"></pre>
1526
1539
  <div class="sub" style="margin:16px 0 0"><a href="/rescue">救援中心</a>(检查 / 修复 / 启动 / 停止 / 状态)· <a href="/plugins">插件管理</a>(启停 mod / 重启引擎 / 停止启动器)</div>
1527
1540
  <script>
1528
1541
  const out = document.getElementById("out");
1542
+ const spin = document.getElementById("spin");
1543
+ const elapsedEl = document.getElementById("elapsed");
1529
1544
  const TOKEN = (document.querySelector('meta[name="dsh-pm-token"]') || {}).content || "";
1530
- function log(line, cls){ out.innerHTML += (cls?'<span class="'+cls+'">':'') + String(line).replace(/</g,'&lt;') + (cls?'</span>':'') + "\\n"; }
1545
+ // U1:启动流程是一个长请求(自检→修复→启动),中间没有任何服务端事件 —— 用计时器证明"页面没卡住"
1546
+ let waited = 0;
1547
+ const ticker = setInterval(function(){
1548
+ waited++;
1549
+ elapsedEl.textContent = "已等待 " + waited + " 秒" + (waited >= 15 ? "(首次启动或修复较慢,页面没有卡住,请勿关闭)" : "…");
1550
+ }, 1000);
1551
+ function stopSpin(){
1552
+ clearInterval(ticker);
1553
+ spin.style.display = "none";
1554
+ if (waited > 0) elapsedEl.textContent = "本次等待 " + waited + " 秒";
1555
+ }
1556
+ // S4:逐行 DOM 追加(textContent),不再 innerHTML += —— 日志里出现什么字符都不会被解析成 HTML,
1557
+ // 也省掉手工转义(旧实现只转义 "<","&" 与属性上下文仍是缺口)。样式沿用 span.cls。
1558
+ function log(line, cls){
1559
+ var row = document.createElement("div");
1560
+ if (cls) { var span = document.createElement("span"); span.className = cls; span.textContent = String(line); row.appendChild(span); }
1561
+ else { row.textContent = String(line); }
1562
+ out.appendChild(row);
1563
+ out.scrollTop = out.scrollHeight;
1564
+ }
1531
1565
  function goEntry(r){
1566
+ stopSpin();
1532
1567
  if (r && r.entryUrl) { location.href = r.entryUrl; return; }
1533
1568
  // G03:entryUrl=null(引擎本次启动没打印/没写可读的 token 行)→ 降级指引,不渲染假 token 链接。
1534
1569
  log("⚠ 未捕获到本次启动的登录链接(entryUrl=null,引擎可能没有把 token 行写进 web.log)。", "warn");
@@ -1539,7 +1574,7 @@ function goEntry(r){
1539
1574
  link.textContent = "→ 打开 http://127.0.0.1:${enginePort}/";
1540
1575
  out.appendChild(document.createElement("br"));
1541
1576
  out.appendChild(link);
1542
- document.getElementById("spin").style.display = "none";
1577
+ stopSpin();
1543
1578
  }
1544
1579
  (async () => {
1545
1580
  try {
@@ -1549,22 +1584,28 @@ function goEntry(r){
1549
1584
  goEntry(r);
1550
1585
  return;
1551
1586
  }
1552
- if (r.code === 409) { log("⚠ " + (r.error || "已有启动流程在执行中"), "warn"); return; }
1587
+ if (r.code === 409) {
1588
+ // U1:原本这里只写一行日志就 return,转圈图标永远转下去 → 看起来像卡死
1589
+ log("⚠ " + (r.error || "已有启动流程在执行中"), "warn");
1590
+ log("本页不会自动跳转;可等它完成,或打开 " + location.origin + "/rescue 救援中心看状态。", "warn");
1591
+ stopSpin();
1592
+ return;
1593
+ }
1553
1594
  if (r.verifyOk === false) log("自检:⚠ 发现 " + (r.issues||[]).length + " 个问题", "warn");
1554
1595
  else if (r.verifyOk === true) log("自检:✓ 配置正常", "ok");
1555
1596
  if (r.fixed) log("修复:" + (r.fixed.message || "完成"), "ok");
1556
1597
  if (r.window && r.window.ok) log("⧉ " + r.window.message + "(窗口里可看到完整进度,结束时按任意键关闭)", "warn");
1557
- if (r.ok) { log("✓ " + (r.message || "引擎已启动"), "ok"); setTimeout(() => goEntry(r), 600); }
1558
- else if (r.quarantined && r.quarantined.length) { log("⚠ 运行期失败条目已自动隔离:" + r.quarantined.join(", "), "bad"); log("✓ " + (r.message || "重试成功"), "ok"); setTimeout(() => goEntry(r), 600); }
1598
+ if (r.ok) { log("✓ " + (r.message || "引擎已启动"), "ok"); stopSpin(); setTimeout(() => goEntry(r), 600); }
1599
+ else if (r.quarantined && r.quarantined.length) { log("⚠ 运行期失败条目已自动隔离:" + r.quarantined.join(", "), "bad"); log("✓ " + (r.message || "重试成功"), "ok"); stopSpin(); setTimeout(() => goEntry(r), 600); }
1559
1600
  else {
1560
1601
  log("✗ " + (r.message || JSON.stringify(r)), "bad");
1561
1602
  if (r.logPath) log("日志:" + r.logPath, "warn");
1562
1603
  log("可运行 node bin/open-boot.mjs --status 查看启动器/守护/引擎状态,或打开 " + location.origin + "/rescue 救援中心", "warn");
1563
- document.getElementById("spin").style.display = "none";
1604
+ stopSpin();
1564
1605
  }
1565
1606
  } catch (e) {
1566
1607
  log("✗ 请求失败:" + e.message, "bad");
1567
- document.getElementById("spin").style.display = "none";
1608
+ stopSpin();
1568
1609
  }
1569
1610
  })();
1570
1611
  </script>
@@ -1666,6 +1707,31 @@ function userBundleNames(profile) {
1666
1707
  return Object.keys(manifest.dependencies ?? {}).filter((name) => !CORE_BUNDLES.includes(name)).sort();
1667
1708
  }
1668
1709
 
1710
+ /**
1711
+ * P2:pnpm 输出缓冲上限 = 保留末尾 16 KB。调用方普遍只用 `slice(-400)`(错误摘录),
1712
+ * 大 profile 的 `pnpm outdated --json` / `pnpm install` 输出可达 MB 级,长驻守护里是无上限的堆峰值。
1713
+ */
1714
+ const PNPM_OUTPUT_CAP = 16 * 1024;
1715
+
1716
+ /**
1717
+ * 有界输出缓冲(P2):超出上限时丢**头部**、只留末尾 cap 个字符,并记下丢弃字节数;
1718
+ * 取值时前置 `<...已截断 N 字节>` 标记,让读日志的人知道"这里不是开头"。
1719
+ * 返回值仍是完整字符串(末尾语义不变),所以 `slice(-400)` 这类调用方无需改动。
1720
+ */
1721
+ function createBoundedBuffer(cap = PNPM_OUTPUT_CAP) {
1722
+ let tail = "";
1723
+ let dropped = 0;
1724
+ return {
1725
+ append(chunk) {
1726
+ tail += String(chunk);
1727
+ if (tail.length > cap) { dropped += tail.length - cap; tail = tail.slice(-cap); }
1728
+ },
1729
+ toString() { return dropped === 0 ? tail : `<...已截断 ${dropped} 字节>${tail}`; },
1730
+ get dropped() { return dropped; },
1731
+ get size() { return tail.length; }
1732
+ };
1733
+ }
1734
+
1669
1735
  /**
1670
1736
  * 以「pnpm 命令 + 白名单参数」的方式跑子进程(rc.2 P1-4:exec → spawn 拿 pid)。
1671
1737
  * resolve 永不 reject,失败也返回结构化结果 { code, stdout, stderr, timedOut, state }:
@@ -1674,6 +1740,7 @@ function userBundleNames(profile) {
1674
1740
  * 调用方(卸载事务)据此不做回滚/继续,直接报告 unknown 请人工确认。
1675
1741
  * 超时杀的是**本函数自己启动**的子树(taskkill /PID <pid> /T /F),与 P0-1「不 /T 连坐别人」不冲突。
1676
1742
  * 测试逃生门:DSH_PM_PNPM_TIMEOUT_MS 环境变量可整体下调默认超时(不设 = 180000)。
1743
+ * P2:stdout/stderr 走有界环形缓冲(保末尾 16KB + 截断标记),不再无上限累积。
1677
1744
  */
1678
1745
  function runPnpm(pnpmArgs, { cwd, timeoutMs } = {}) {
1679
1746
  const defaultTimeout = Number(process.env.DSH_PM_PNPM_TIMEOUT_MS);
@@ -1689,15 +1756,16 @@ function runPnpm(pnpmArgs, { cwd, timeoutMs } = {}) {
1689
1756
  resolveRun({ code: 1, stdout: "", stderr: `pnpm spawn 失败:${error.message}`, timedOut: false, state: "done" });
1690
1757
  return;
1691
1758
  }
1692
- let stdout = "";
1693
- let stderr = "";
1759
+ // P2:有界缓冲(保末尾 16KB);返回值语义与旧版一致(末尾内容不变)
1760
+ const stdoutBuf = createBoundedBuffer();
1761
+ const stderrBuf = createBoundedBuffer();
1694
1762
  let settled = false;
1695
1763
  let timedOut = false;
1696
1764
  const finish = (code, state) => {
1697
1765
  if (settled) return;
1698
1766
  settled = true;
1699
1767
  clearTimeout(timer);
1700
- resolveRun({ code, stdout, stderr, timedOut, state });
1768
+ resolveRun({ code, stdout: stdoutBuf.toString(), stderr: stderrBuf.toString(), timedOut, state });
1701
1769
  };
1702
1770
  const killTree = () => {
1703
1771
  timedOut = true;
@@ -1719,10 +1787,10 @@ function runPnpm(pnpmArgs, { cwd, timeoutMs } = {}) {
1719
1787
  const timer = setTimeout(() => {
1720
1788
  if (!settled && child.pid) killTree();
1721
1789
  }, timeout);
1722
- child.stdout?.on("data", (d) => { stdout += d; });
1723
- child.stderr?.on("data", (d) => { stderr += d; });
1790
+ child.stdout?.on("data", (d) => { stdoutBuf.append(d); });
1791
+ child.stderr?.on("data", (d) => { stderrBuf.append(d); });
1724
1792
  child.on("error", (error) => {
1725
- stderr += `\n${error.message}`;
1793
+ stderrBuf.append(`\n${error.message}`);
1726
1794
  finish(1, "done");
1727
1795
  });
1728
1796
  child.on("close", (code) => finish(typeof code === "number" ? code : 1, "done"));
@@ -1912,29 +1980,78 @@ async function uninstallPackageTransactional(args, pkgName) {
1912
1980
  };
1913
1981
  }
1914
1982
 
1915
- /** 检查用户插件更新:一次 pnpm outdated --json,再投影到用户 bundle(核心组件不参与)。 */
1916
- async function checkUpdates(args) {
1983
+ /**
1984
+ * P1:updates 结果缓存(key = profile,TTL 30 分钟)。
1985
+ * 另存 `pnpm-lock.yaml` 的 mtime+size 作失效键:lockfile 一变(用户装了/卸了包、改了依赖树)
1986
+ * 立刻重算,不让 30 分钟缓存把"刚装的插件"藏起来。只缓存**成功**结果——失败(pnpm 缺失/输出异常)
1987
+ * 留给用户重试,不把一个可修的故障钉在缓存里半小时。
1988
+ */
1989
+ const UPDATES_CACHE_MS = 30 * 60 * 1000;
1990
+ const updatesCache = new Map();
1991
+ /** P1:单飞——同一 profile 的并发请求共用同一个 in-flight Promise(复用同一结果,不是 409)。 */
1992
+ const updatesInflight = new Map();
1993
+ /** P1:`pnpm --version` 成功结果模块级缓存(失败不缓存:装好 pnpm 后下一次就能恢复)。 */
1994
+ let pnpmVersionCache = null;
1995
+
1996
+ /** lockfile 指纹:mtimeMs + size(文件不存在记 "absent",仍然稳定可比)。 */
1997
+ function lockfileStamp(profile) {
1998
+ try {
1999
+ const st = statSync(join(profile, "pnpm-lock.yaml"));
2000
+ return `${st.mtimeMs}:${st.size}`;
2001
+ } catch { return "absent"; }
2002
+ }
2003
+
2004
+ /** 测试面:清空 updates 缓存 / 单飞 / 版本缓存(生产路径不调用)。 */
2005
+ function resetUpdatesCacheForTests() {
2006
+ updatesCache.clear();
2007
+ updatesInflight.clear();
2008
+ pnpmVersionCache = null;
2009
+ }
2010
+
2011
+ /**
2012
+ * 检查用户插件更新:一次 pnpm outdated --json,再投影到用户 bundle(核心组件不参与)。
2013
+ * P1:30 分钟缓存(key=profile + lockfile 指纹)+ 并发单飞 + pnpm --version 进程内缓存;
2014
+ * `run`/`now` 是测试注入点(默认就是 runPnpm / Date.now)。
2015
+ * 热调用目标 < 10ms:命中缓存时不 spawn 任何子进程。
2016
+ */
2017
+ async function checkUpdates(args, { run = runPnpm, now = Date.now } = {}) {
1917
2018
  const profile = args.profile;
1918
2019
  const users = userBundleNames(profile);
1919
2020
  if (users.length === 0) return { ok: true, updates: [], message: "profile 没有用户插件。" };
1920
- const ping = await runPnpm(["--version"], { cwd: profile, timeoutMs: 15000 });
1921
- if (ping.code !== 0) return { ok: false, error: `pnpm 不可用(exit ${ping.code}):${(ping.stderr || ping.stdout).slice(-200)}` };
1922
- const out = await runPnpm(["outdated", "--json"], { cwd: profile, timeoutMs: 120000 });
1923
- let table = {};
1924
- try { table = JSON.parse(out.stdout || "{}") || {}; }
1925
- catch {
1926
- return { ok: false, error: `pnpm outdated 输出无法解析(exit ${out.code}):${(out.stderr || out.stdout).slice(-300)}` };
1927
- }
1928
- const updates = users.map((name) => {
1929
- const row = table[name] || table[`./${name}`] || null;
1930
- return {
1931
- name,
1932
- current: row?.current ?? null,
1933
- latest: row?.latest ?? null,
1934
- needsUpdate: Boolean(row && row.latest && row.current !== row.latest)
1935
- };
1936
- });
1937
- return { ok: true, updates };
2021
+ const lock = lockfileStamp(profile);
2022
+ const cached = updatesCache.get(profile);
2023
+ if (cached && now() - cached.at < UPDATES_CACHE_MS && cached.lock === lock) return cached.result;
2024
+ // 并发进来时复用同一个 Promise:不会重复拉起 pnpm,也不会把第二个请求判成 409
2025
+ const pending = updatesInflight.get(profile);
2026
+ if (pending) return pending;
2027
+ const task = (async () => {
2028
+ if (pnpmVersionCache === null) {
2029
+ const ping = await run(["--version"], { cwd: profile, timeoutMs: 15000 });
2030
+ if (ping.code !== 0) return { ok: false, error: `pnpm 不可用(exit ${ping.code}):${(ping.stderr || ping.stdout).slice(-200)}` };
2031
+ pnpmVersionCache = (ping.stdout || "").trim();
2032
+ }
2033
+ const out = await run(["outdated", "--json"], { cwd: profile, timeoutMs: 120000 });
2034
+ let table = {};
2035
+ try { table = JSON.parse(out.stdout || "{}") || {}; }
2036
+ catch {
2037
+ return { ok: false, error: `pnpm outdated 输出无法解析(exit ${out.code}):${(out.stderr || out.stdout).slice(-300)}` };
2038
+ }
2039
+ const updates = users.map((name) => {
2040
+ const row = table[name] || table[`./${name}`] || null;
2041
+ return {
2042
+ name,
2043
+ current: row?.current ?? null,
2044
+ latest: row?.latest ?? null,
2045
+ needsUpdate: Boolean(row && row.latest && row.current !== row.latest)
2046
+ };
2047
+ });
2048
+ const result = { ok: true, updates };
2049
+ updatesCache.set(profile, { at: now(), lock, result });
2050
+ return result;
2051
+ })();
2052
+ updatesInflight.set(profile, task);
2053
+ try { return await task; }
2054
+ finally { updatesInflight.delete(profile); }
1938
2055
  }
1939
2056
 
1940
2057
  /** 更新单个用户插件(与卸载同一套 EBUSY 引导 + P1-3 fail-closed:握手失败但端口有监听者 → 拒绝)。 */
@@ -2238,6 +2355,9 @@ button.danger:hover{background:var(--bad-bg);color:var(--bad)}
2238
2355
  .toggle input:checked + .knob{background:var(--accent)}
2239
2356
  .toggle input:checked + .knob::after{left:18px}
2240
2357
  .toggle input:disabled + .knob{opacity:.45;cursor:not-allowed}
2358
+ /* U1:禁用的 input 会吞掉鼠标事件(点击落在它身上就什么都不发生)→ 让事件落到 label/knob 上,
2359
+ 这样"点核心组件开关"能弹 toast 解释为什么不能点,而不是一片死寂。 */
2360
+ .toggle input:disabled{pointer-events:none}
2241
2361
  .hint{color:var(--dim);font-size:12px;line-height:1.6}
2242
2362
  .hint a{color:var(--accent)}
2243
2363
  .dim{color:var(--dim)}
@@ -2246,7 +2366,7 @@ pre.log{background:var(--bg);border:1px solid var(--border);border-radius:8px;pa
2246
2366
  .dot{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:7px;vertical-align:baseline}
2247
2367
  .dot.ok{background:var(--ok)}.dot.suspect{background:var(--warn)}.dot.broken{background:var(--bad)}
2248
2368
  /* toast */
2249
- #toasts{position:fixed;top:16px;left:50%;transform:translateX(-50%);z-index:60;display:flex;flex-direction:column;gap:8px;align-items:center}
2369
+ #toasts{position:fixed;top:16px;left:50%;transform:translateX(-50%);z-index:60;display:flex;flex-direction:column;gap:8px;align-items:center;pointer-events:none}
2250
2370
  .toast{background:var(--card);border:1px solid var(--border);border-left:4px solid var(--accent);border-radius:8px;padding:9px 16px;font-size:13px;box-shadow:0 4px 14px rgba(0,0,0,.14);max-width:520px}
2251
2371
  .toast.ok{border-left-color:var(--ok)}.toast.bad{border-left-color:var(--bad)}.toast.warn{border-left-color:var(--warn)}
2252
2372
  /* 确认框 */
@@ -2258,6 +2378,12 @@ pre.log{background:var(--bg);border:1px solid var(--border);border-radius:8px;pa
2258
2378
  #confirmBox .btns{display:flex;justify-content:flex-end;gap:8px}
2259
2379
  .panel{display:none}
2260
2380
  .panel.open{display:block}
2381
+ /* U1:结果卡片落点 —— 操作完成后滚动到位 + 闪一下,避免"结果在视口外 = 按钮没反应" */
2382
+ @keyframes cardflash{0%{box-shadow:0 0 0 0 rgba(59,110,246,0)}35%{box-shadow:0 0 0 3px var(--accent)}100%{box-shadow:0 0 0 0 rgba(59,110,246,0)}}
2383
+ .card.flash{animation:cardflash 1.6s ease-out}
2384
+ /* U1:按钮 loading 态(发起反馈) */
2385
+ button.busy{cursor:progress;opacity:.65}
2386
+ .rowitem.busy{opacity:.6}
2261
2387
  </style></head><body><div class="wrap">
2262
2388
  <header>
2263
2389
  <div>
@@ -2283,17 +2409,6 @@ pre.log{background:var(--bg);border:1px solid var(--border);border-radius:8px;pa
2283
2409
  <div class="hint" style="margin-top:10px"><span id="engstate" class="dim">引擎状态检测中…</span> · 改动启用状态后需重启引擎生效(写前自动备份 package.json)。</div>
2284
2410
  </div>
2285
2411
 
2286
- <div class="card">
2287
- <p class="sect">核心组件(引擎必需,不允许禁用)</p>
2288
- <div class="rows" id="coreRows"></div>
2289
- </div>
2290
-
2291
- <div class="card">
2292
- <p class="sect">用户插件</p>
2293
- <div class="rows" id="userRows"></div>
2294
- <div class="hint" style="margin-top:8px">配置入口在各插件的行内设置(主界面 → 插件管理 → 行内 ⚙);「市场详情」打开主界面市场页。</div>
2295
- </div>
2296
-
2297
2412
  <div class="card panel" id="updPanel">
2298
2413
  <p class="sect">更新检查结果</p>
2299
2414
  <div class="rows" id="updRows"></div>
@@ -2310,6 +2425,17 @@ pre.log{background:var(--bg);border:1px solid var(--border);border-radius:8px;pa
2310
2425
  <div class="rows" id="stepRows"></div>
2311
2426
  </div>
2312
2427
 
2428
+ <div class="card">
2429
+ <p class="sect">核心组件(引擎必需,不允许禁用)</p>
2430
+ <div class="rows" id="coreRows"></div>
2431
+ </div>
2432
+
2433
+ <div class="card">
2434
+ <p class="sect">用户插件</p>
2435
+ <div class="rows" id="userRows"></div>
2436
+ <div class="hint" style="margin-top:8px">配置入口在各插件的行内设置(主界面 → 插件管理 → 行内 ⚙);「市场详情」打开主界面市场页。</div>
2437
+ </div>
2438
+
2313
2439
  <div class="hint" style="margin-top:16px">管理器不能在自身管理界面(引擎 ${enginePort})中停用自己;如需禁用或卸载,请前往启动器兜底页(本页 ${launcherPort} /plugins)或使用 dsh 命令行——兜底页独立于引擎存活,禁用后仍可恢复。<b>可事务性自卸载</b>(含开机自启清理指引)。卸载/更新前若引擎正占用目标包,会引导你先禁用并重启引擎,而不是硬删。</div>
2314
2440
  </div>
2315
2441
 
@@ -2356,6 +2482,7 @@ themeBtn.addEventListener("click", function(){
2356
2482
  var next = document.documentElement.getAttribute("data-theme") === "dark" ? "light" : "dark";
2357
2483
  try { localStorage.setItem(THEME_KEY, next); } catch (e) { /* 写不进去就只在本会话生效 */ }
2358
2484
  applyTheme();
2485
+ toast("主题已切换为" + (next === "dark" ? "深色" : "浅色") + "(本页记忆;长按主题按钮复位为自动)", "ok");
2359
2486
  });
2360
2487
  themeBtn.addEventListener("pointerdown", function(){
2361
2488
  themeLongPressed = false;
@@ -2379,10 +2506,54 @@ function toast(text, cls){
2379
2506
  var box = document.getElementById("toasts");
2380
2507
  var el = document.createElement("div");
2381
2508
  el.className = "toast " + (cls || "");
2509
+ el.setAttribute("role", "status");
2382
2510
  el.textContent = text;
2383
2511
  box.appendChild(el);
2384
2512
  setTimeout(function(){ el.remove(); }, 5200);
2385
2513
  }
2514
+ // —— U1:发起反馈 / 落点反馈的统一实现 ——
2515
+ /** 按钮 loading 态:禁用 + 改文案,结束后逐字还原(防重复点击 + 用户能看出"点到了")。 */
2516
+ function setBusy(btn, busy, label){
2517
+ if (!btn) return;
2518
+ if (busy) {
2519
+ if (btn.dataset.idleText === undefined) btn.dataset.idleText = btn.textContent;
2520
+ btn.disabled = true;
2521
+ btn.classList.add("busy");
2522
+ btn.setAttribute("aria-busy", "true");
2523
+ if (label) btn.textContent = label;
2524
+ } else {
2525
+ btn.disabled = false;
2526
+ btn.classList.remove("busy");
2527
+ btn.removeAttribute("aria-busy");
2528
+ if (btn.dataset.idleText !== undefined) { btn.textContent = btn.dataset.idleText; delete btn.dataset.idleText; }
2529
+ }
2530
+ }
2531
+ async function withBusy(btn, label, fn){
2532
+ setBusy(btn, true, label);
2533
+ try { return await fn(); } finally { setBusy(btn, false); }
2534
+ }
2535
+ /** 结果卡片落点:打开 → 滚进视口(block:nearest,不把页面顶跳)→ 高亮闪一下;toast 是"感知",这是"眼睛的落点"。 */
2536
+ function revealPanel(id){
2537
+ var panel = document.getElementById(id);
2538
+ if (!panel) return;
2539
+ panel.classList.add("open");
2540
+ panel.classList.remove("flash");
2541
+ try { void panel.offsetWidth; } catch (e) { /* 强制重排以重放动画 */ }
2542
+ panel.classList.add("flash");
2543
+ if (panel._flashTimer) clearTimeout(panel._flashTimer);
2544
+ panel._flashTimer = setTimeout(function(){ panel.classList.remove("flash"); }, 1700);
2545
+ try {
2546
+ // 卡片比视口还高时(体检 20+ 行 / 长列表后的步骤日志)nearest 可能只对齐底边,
2547
+ // 标题被切掉一半 → 这种情况对齐卡片顶部,保证"体检结果"这个标题一定在屏幕里。
2548
+ var tall = panel.getBoundingClientRect().height > window.innerHeight * 0.85;
2549
+ panel.scrollIntoView({ block: tall ? "start" : "nearest", behavior: "smooth" });
2550
+ } catch (e) { try { panel.scrollIntoView(false); } catch (e2) { /* 老浏览器不支持时退化为仅高亮 */ } }
2551
+ }
2552
+ /** 失败 toast 必须带原因:服务端没给原因也要说清"没给原因",不许只说"失败"。 */
2553
+ function failText(prefix, r){
2554
+ return prefix + ":" + ((r && r.error) ? r.error : "服务端未返回原因(可看「操作步骤日志」或重启启动器后重试)");
2555
+ }
2556
+
2386
2557
  function confirmBox(title, text, okLabel){
2387
2558
  return new Promise(function(resolveCF){
2388
2559
  var mask = document.getElementById("mask");
@@ -2434,6 +2605,13 @@ function toggleHtml(b){
2434
2605
  input.dataset.name = b.name;
2435
2606
  var knob = document.createElement("span"); knob.className = "knob";
2436
2607
  label.appendChild(input); label.appendChild(knob);
2608
+ if (b.core) {
2609
+ // 核心组件的开关是 disabled 的:点它原本毫无反应(用户以为坏了)→ 现在明确说明为什么不能点
2610
+ label.addEventListener("click", function(ev){
2611
+ ev.preventDefault();
2612
+ toast(b.name + " 是引擎必需的核心组件,不能在这里禁用;确需停用请走救援中心 /rescue 或手工改 profile。", "warn");
2613
+ });
2614
+ }
2437
2615
  return label;
2438
2616
  }
2439
2617
  function renderRows(){
@@ -2476,7 +2654,13 @@ function renderRows(){
2476
2654
  var mk = el("button", null, "市场详情");
2477
2655
  mk.title = "打开主界面(引擎未运行时置灰)";
2478
2656
  mk.disabled = !engineUp;
2479
- mk.addEventListener("click", function(){ window.open("http://127.0.0.1:" + ENGINE_PORT + "/", "_blank"); });
2657
+ mk.addEventListener("click", function(){
2658
+ var url = "http://127.0.0.1:" + ENGINE_PORT + "/";
2659
+ var w = null;
2660
+ try { w = window.open(url, "_blank"); } catch (e) { w = null; }
2661
+ if (!w) toast("浏览器拦截了新标签页:请允许本站弹窗,或手动打开 " + url, "warn");
2662
+ else toast("已在新标签页打开主界面(" + url + ")", "ok");
2663
+ });
2480
2664
  row.appendChild(mk);
2481
2665
  (b.core ? coreRows : userRows).appendChild(row);
2482
2666
  });
@@ -2522,67 +2706,89 @@ function renderSteps(steps){
2522
2706
  });
2523
2707
  }
2524
2708
  async function doUpdate(name, btn){
2525
- btn.disabled = true;
2709
+ setBusy(btn, true, "更新中…");
2526
2710
  await guard(async function(){
2527
2711
  var okGo = await confirmBox("更新 " + name, "将运行 pnpm update --latest。若引擎正在运行且该插件已启用,会拒绝并引导你先禁用。", "更新");
2528
- if (!okGo) return;
2712
+ if (!okGo) { toast("已取消更新 " + name, "warn"); return; }
2713
+ toast("正在更新 " + name + "(pnpm update --latest,可能 10-60s)…", "warn");
2529
2714
  var r = await api("/plugins/api/update", { name: name });
2530
- if (!r.ok) { toast(r.error || "更新失败", r.blocked === "engine-busy" ? "warn" : "bad"); return; }
2531
- toast(r.message || "已更新", "ok");
2532
- await refreshUpdates(false);
2715
+ if (!r.ok) {
2716
+ toast(failText("更新 " + name + " 失败", r) + (r.blocked === "engine-busy" ? "(引擎正占用该包:先禁用该插件并重启引擎,再更新)" : ""), r.blocked === "engine-busy" ? "warn" : "bad");
2717
+ return;
2718
+ }
2719
+ toast("已更新 " + name + (r.message ? ":" + r.message : "(重启引擎后生效)"), "ok");
2720
+ // 刷新更新面板并 revealPanel("updPanel")(refreshUpdates 内部负责滚到位;失败时不会掀出空卡片)
2721
+ await refreshUpdates({ showPanel: true, announce: false });
2533
2722
  });
2534
- btn.disabled = false;
2723
+ setBusy(btn, false);
2535
2724
  }
2536
2725
  async function doUninstall(b, btn){
2537
- btn.disabled = true;
2726
+ setBusy(btn, true, "卸载中…");
2538
2727
  await guard(async function(){
2539
2728
  var warnText = b.self
2540
2729
  ? "这是管理器自身:卸载后引擎 ${enginePort} 内的插件管理界面消失;启动器 ${launcherPort} 本兜底页存活到启动器进程结束;之后请运行 node bin/open-boot.mjs --uninstall 清理开机自启。确定继续?"
2541
2730
  : "将执行事务性卸载:备份清单与 cordis.patch.yml → pnpm remove → 清理补丁行 → 验证;每一步都会留下回滚记录。确定继续?";
2542
2731
  var okGo = await confirmBox("卸载 " + b.name, warnText, "卸载");
2543
- if (!okGo) return;
2732
+ if (!okGo) { toast("已取消卸载 " + b.name, "warn"); return; }
2733
+ toast("正在卸载 " + b.name + "(事务性:备份 → pnpm remove → 清理补丁 → 验证)…", "warn");
2544
2734
  var r = await api("/plugins/api/uninstall", { name: b.name });
2545
- if (!r.ok) { toast(r.error || "卸载失败", r.blocked === "engine-busy" ? "warn" : "bad"); return; }
2546
- toast(r.message || "已卸载", "ok");
2547
- if (Array.isArray(r.steps)) renderSteps(r.steps);
2735
+ if (!r.ok) {
2736
+ toast(failText("卸载 " + b.name + " 失败", r) + (r.blocked === "engine-busy" ? "(引擎正占用该包:先禁用该插件并重启引擎,再卸载)" : ""), r.blocked === "engine-busy" ? "warn" : "bad");
2737
+ return;
2738
+ }
2739
+ toast("已卸载 " + b.name + (r.message ? ":" + r.message : "(重启引擎后生效)"), "ok");
2740
+ if (Array.isArray(r.steps)) { renderSteps(r.steps); revealPanel("stepPanel"); }
2548
2741
  await loadBundles();
2549
2742
  });
2550
- btn.disabled = false;
2743
+ setBusy(btn, false);
2551
2744
  }
2552
- async function loadBundles(){
2745
+ async function loadBundles(announce){
2553
2746
  return guard(async function(){
2554
2747
  var r = await api("/plugins/api/bundles");
2555
- if (!r.ok) { toast(r.error || "读取 bundle 失败", "bad"); return; }
2748
+ if (!r.ok) { toast(failText("读取插件列表失败", r), "bad"); return; }
2556
2749
  bundles = (r.bundles || []).map(function(b){ return { name: b.name, enabled: b.enabled, core: b.core, self: b.name === "dsh-drydock" }; });
2557
2750
  renderRows();
2751
+ if (announce) {
2752
+ var users = bundles.filter(function(b){ return !b.core; }).length;
2753
+ var on = bundles.filter(function(b){ return b.enabled; }).length;
2754
+ toast("已刷新:共 " + bundles.length + " 个组件(用户插件 " + users + " 个,已启用 " + on + " 个)", "ok");
2755
+ }
2558
2756
  });
2559
2757
  }
2560
- async function refreshUpdates(showPanel){
2758
+ async function refreshUpdates(opts){
2759
+ opts = opts || {};
2760
+ var showPanel = opts.showPanel !== false;
2761
+ var announce = opts.announce !== false;
2561
2762
  return guard(async function(){
2562
- var btn = document.getElementById("checkUpdBtn");
2563
- btn.disabled = true;
2763
+ if (announce) toast("正在检查更新:逐个比对用户插件的最新版本…", "warn");
2564
2764
  var r = await api("/plugins/api/updates");
2565
- btn.disabled = false;
2566
- if (!r.ok) { toast(r.error || "检查更新失败", "bad"); return; }
2765
+ if (!r.ok) { toast(failText("检查更新失败", r), "bad"); return; }
2567
2766
  updates = r.updates || [];
2568
- var n = updates.filter(function(u){ return u.needsUpdate; }).length;
2569
- toast(n ? "发现 " + n + " 个可更新插件" : "全部用户插件已是最新", n ? "warn" : "ok");
2767
+ var pending = updates.filter(function(u){ return u.needsUpdate; });
2768
+ var n = pending.length;
2769
+ if (announce) {
2770
+ var names = pending.slice(0, 3).map(function(u){ return u.name; }).join("、");
2771
+ toast(n
2772
+ ? "发现 " + n + " 个可更新插件:" + names + (n > 3 ? " 等" : "") + "(结果在「更新检查结果」卡片)"
2773
+ : "全部 " + updates.length + " 个用户插件已是最新", n ? "warn" : "ok");
2774
+ }
2570
2775
  renderRows();
2571
- if (showPanel !== false) renderUpdateRows();
2776
+ if (showPanel) renderUpdateRows();
2777
+ if (showPanel) revealPanel("updPanel");
2572
2778
  });
2573
2779
  }
2574
2780
  async function runHealth(){
2575
2781
  return guard(async function(){
2576
- var btn = document.getElementById("healthBtn");
2577
- btn.disabled = true;
2782
+ toast("正在做 mod 体检(只读:preflight 校验 + 引擎日志末尾 256KB)…", "warn");
2578
2783
  var r = await api("/plugins/api/health");
2579
- btn.disabled = false;
2580
- if (!r.ok) { toast(r.error || "体检失败", "bad"); return; }
2784
+ if (!r.ok) { toast(failText("mod 体检失败", r), "bad"); return; }
2785
+ var reportRows = r.rows || [];
2786
+ var gi = r.globalIssues || [];
2787
+ var broken = reportRows.filter(function(x){ return x.verdict === "broken"; });
2788
+ var suspect = reportRows.filter(function(x){ return x.verdict === "suspect"; });
2581
2789
  var rows = document.getElementById("healthRows");
2582
- var panel = document.getElementById("healthPanel");
2583
2790
  rows.textContent = "";
2584
- panel.classList.add("open");
2585
- (r.rows || []).forEach(function(row){
2791
+ reportRows.forEach(function(row){
2586
2792
  var item = el("div", "rowitem");
2587
2793
  var meta = el("div", "meta");
2588
2794
  var line = el("div", "name", null);
@@ -2596,7 +2802,6 @@ async function runHealth(){
2596
2802
  rows.appendChild(item);
2597
2803
  });
2598
2804
  // rc.2 P2-4:非 bundle 归属的 preflight 问题与未识别日志错误 → 单独区块
2599
- var gi = r.globalIssues || [];
2600
2805
  if (gi.length) {
2601
2806
  var ghead = el("div", "rowitem");
2602
2807
  ghead.appendChild(el("b", "warn", "⚠ 全局问题(不属于任何已装 bundle,勿按插件处理)"));
@@ -2611,46 +2816,71 @@ async function runHealth(){
2611
2816
  });
2612
2817
  }
2613
2818
  document.getElementById("healthHint").textContent = "日志:" + (r.logPath || "") + ";体检只读(preflight 校验 + 日志末尾 256KB 聚合,30s 缓存),不改任何文件。";
2819
+ var healthy = reportRows.length - broken.length - suspect.length;
2820
+ var head = "体检完成:" + reportRows.length + " 个组件(正常 " + healthy + " / 可疑 " + suspect.length + " / 异常 " + broken.length + ")" + (gi.length ? ",另有 " + gi.length + " 条全局问题" : "");
2821
+ if (!reportRows.length) toast("体检完成:profile 里没有已装组件(「用户插件」列表为空就是原因)", "warn");
2822
+ else if (broken.length) toast(head + ";异常:" + broken.slice(0, 3).map(function(x){ return x.name; }).join("、") + (broken.length > 3 ? " 等" : ""), "bad");
2823
+ else if (suspect.length || gi.length) toast(head, "warn");
2824
+ else toast(head + ",全部正常", "ok");
2825
+ revealPanel("healthPanel");
2614
2826
  });
2615
2827
  }
2616
2828
  document.getElementById("q").addEventListener("input", renderRows);
2617
- document.getElementById("refreshBtn").addEventListener("click", loadBundles);
2618
- document.getElementById("checkUpdBtn").addEventListener("click", function(){ refreshUpdates(true); });
2619
- document.getElementById("healthBtn").addEventListener("click", runHealth);
2829
+ document.getElementById("refreshBtn").addEventListener("click", function(){
2830
+ return withBusy(this, "刷新中…", function(){ return loadBundles(true); });
2831
+ });
2832
+ document.getElementById("checkUpdBtn").addEventListener("click", function(){
2833
+ return withBusy(this, "检查中…", function(){ return refreshUpdates({ showPanel: true, announce: true }); });
2834
+ });
2835
+ document.getElementById("healthBtn").addEventListener("click", function(){
2836
+ return withBusy(this, "体检中…", function(){ return runHealth(); });
2837
+ });
2620
2838
  document.getElementById("restartBtn").addEventListener("click", async function(){
2621
- this.disabled = true;
2622
- await guard(async function(){
2623
- var okGo = await confirmBox("重启引擎", "停旧引擎 → 拉起新引擎(失败条目自动隔离一次)→ 等握手。期间引擎 ${enginePort} 会短暂不可用。", "重启");
2624
- if (!okGo) { document.getElementById("restartBtn").disabled = false; return; }
2625
- toast("重启引擎中…", "warn");
2626
- var r = await api("/plugins/api/engine/restart", {});
2627
- toast(r.message || (r.ok ? "引擎已重启。" : "重启失败。"), r.ok ? "ok" : "bad");
2628
- setEngineState(r.ok);
2629
- // G03:entryUrl=null 时的降级指引(不渲染假 token 链接)
2630
- if (r.ok && r.entryUrl) toast("登录链接已就绪(含 token),可直接打开主界面。", "ok");
2631
- else if (r.ok) toast("未捕获到本次启动的登录链接:① 已登录过的浏览器直接打开 http://127.0.0.1:" + ENGINE_PORT + "/(cookie 仍有效);② 新浏览器请看引擎控制台输出的 dsh web: …?token=…,或到 ~/.dsh/logs/web.log 末尾查找最后一次启动追加的链接。", "warn");
2632
- });
2633
- document.getElementById("restartBtn").disabled = false;
2839
+ setBusy(this, true, "重启中…");
2840
+ try {
2841
+ await guard(async function(){
2842
+ var okGo = await confirmBox("重启引擎", "停旧引擎 → 拉起新引擎(失败条目自动隔离一次)→ 等握手。期间引擎 ${enginePort} 会短暂不可用。", "重启");
2843
+ if (!okGo) { toast("已取消重启引擎", "warn"); return; }
2844
+ toast("正在重启引擎(停旧 → 拉起 → 握手,最长约 30s)…", "warn");
2845
+ var r = await api("/plugins/api/engine/restart", {});
2846
+ if (r.ok) toast("引擎已重启,http://127.0.0.1:" + ENGINE_PORT + "/ 可访问" + (r.entryUrl ? ";登录链接已就绪,可直接打开主界面。" : "。"), "ok");
2847
+ else toast(failText("重启引擎失败", r), "bad");
2848
+ setEngineState(r.ok);
2849
+ // G03:entryUrl=null 时的降级指引(不渲染假 token 链接)
2850
+ if (r.ok && !r.entryUrl) toast("未捕获到本次启动的登录链接:① 已登录过的浏览器直接打开 http://127.0.0.1:" + ENGINE_PORT + "/(cookie 仍有效);② 新浏览器请看引擎控制台输出的 dsh web: …?token=…,或到 ~/.dsh/logs/web.log 末尾查找最后一次启动追加的链接。", "warn");
2851
+ });
2852
+ } finally {
2853
+ setBusy(document.getElementById("restartBtn"), false);
2854
+ }
2634
2855
  });
2635
2856
  document.getElementById("stopBtn").addEventListener("click", async function(){
2636
- this.disabled = true;
2637
- await guard(async function(){
2638
- var okGo = await confirmBox("停止本启动器", "启动器进程将优雅退出并清理 pid 文件;引擎与本页面不受影响,重新打开 ${launcherPort} 会重新拉起启动器。", "停止");
2639
- if (!okGo) { document.getElementById("stopBtn").disabled = false; return; }
2640
- var r = await api("/api/launcher/stop", {});
2641
- toast(r.message || "启动器即将退出。", "warn");
2642
- setTimeout(function(){ location.reload(); }, 1200);
2643
- });
2644
- document.getElementById("stopBtn").disabled = false;
2857
+ setBusy(this, true, "停止中…");
2858
+ try {
2859
+ await guard(async function(){
2860
+ var okGo = await confirmBox("停止本启动器", "启动器进程将优雅退出并清理 pid 文件;引擎与本页面不受影响,重新打开 ${launcherPort} 会重新拉起启动器。", "停止");
2861
+ if (!okGo) { toast("已取消停止启动器", "warn"); return; }
2862
+ toast("正在停止本启动器(引擎与本页面不受影响)…", "warn");
2863
+ var r = await api("/api/launcher/stop", {});
2864
+ toast(r.message || "启动器即将退出;重新打开本页地址会重新拉起启动器。", r.ok === false ? "bad" : "warn");
2865
+ setTimeout(function(){ location.reload(); }, 1200);
2866
+ });
2867
+ } finally {
2868
+ setBusy(document.getElementById("stopBtn"), false);
2869
+ }
2645
2870
  });
2646
2871
  document.getElementById("userRows").addEventListener("change", async function(ev){
2647
2872
  var input = ev.target;
2648
2873
  if (!input || input.dataset.name === undefined) return;
2874
+ var name = input.dataset.name;
2875
+ var want = Boolean(input.checked);
2876
+ var row = input.closest ? input.closest(".rowitem") : null;
2649
2877
  input.disabled = true;
2878
+ if (row) row.classList.add("busy");
2879
+ toast((want ? "正在启用 " : "正在禁用 ") + name + "…", "warn");
2650
2880
  await guard(async function(){
2651
- var r = await api("/plugins/api/bundles", { name: input.dataset.name, action: input.checked ? "enable" : "disable" });
2652
- if (!r.ok) { toast(r.error || "操作失败", "bad"); }
2653
- else toast(r.message || "已更新(重启引擎后生效)", r.changed === false ? "warn" : "ok");
2881
+ var r = await api("/plugins/api/bundles", { name: name, action: want ? "enable" : "disable" });
2882
+ if (!r.ok) toast(failText((want ? "启用 " : "禁用 ") + name + " 失败", r), "bad");
2883
+ else toast((want ? "已启用 " : "已禁用 ") + name + (r.changed === false ? "(本来就是这个状态,未改动)" : ",重启引擎后生效"), r.changed === false ? "warn" : "ok");
2654
2884
  });
2655
2885
  await loadBundles();
2656
2886
  });
@@ -2669,7 +2899,12 @@ async function loadEngine(){
2669
2899
  });
2670
2900
  }
2671
2901
  loadBundles(); loadEngine();
2902
+ // U1:结果区(#updPanel / #healthPanel / #stepPanel)已前移到用户插件列表之上,
2903
+ // 因此 #health 直达既能看见结果,也不会被长列表顶出视口;再靠 revealPanel 的滚动+高亮给落点。
2672
2904
  if (location.hash === "#health") runHealth(); // 3080 RescuePanel 的「mod 体检」入口直达(/plugins#health)
2905
+ window.addEventListener("hashchange", function(){
2906
+ if (location.hash === "#health") runHealth();
2907
+ });
2673
2908
  </script>
2674
2909
  </div></body></html>`;
2675
2910
  }
@@ -2702,6 +2937,47 @@ function readJsonBody(req) {
2702
2937
  });
2703
2938
  }
2704
2939
 
2940
+ /**
2941
+ * S3:Host 头校验(DNS 重绑定防护)。只接受带端口的回环主机名 ——
2942
+ * 攻击者把 `evil.example` 解析到 127.0.0.1 后,浏览器发出的请求 Host 仍是 `evil.example`,
2943
+ * 只看 Origin/令牌挡不住"读接口被同源化"(/api/status 会暴露 profile 绝对路径 / pid / 版本)。
2944
+ * 严格按审查报告:必须带端口、大小写不敏感、只认这三种回环写法。
2945
+ */
2946
+ function isAllowedHost(hostHeader, port) {
2947
+ if (typeof hostHeader !== "string" || hostHeader.trim() === "") return false;
2948
+ const host = hostHeader.trim().toLowerCase();
2949
+ return host === `127.0.0.1:${port}` || host === `localhost:${port}` || host === `[::1]:${port}`;
2950
+ }
2951
+
2952
+ /**
2953
+ * S4:统一安全响应头。页面是内联 `<script>` + 内联 `<style>`,因此保留 `'unsafe-inline'`
2954
+ * (nonce 化要同时改三个页面模板 + 救援页,1.0.3 不做);其余全部收紧:
2955
+ * default-src 'none' —— 默认不许加载任何东西;
2956
+ * connect-src 'self' —— 3081 页只能同源 fetch(/plugins/api/*、/rescue/api/*);
2957
+ * img-src 'self' data: —— 内联 favicon 是 data: URI;
2958
+ * frame-ancestors 'none' / X-Frame-Options: DENY —— 禁止被嵌框(点劫持);
2959
+ * base-uri 'none' —— 防 <base> 改写相对地址;
2960
+ * nosniff / Referrer-Policy: no-referrer —— 防 MIME 嗅探与地址外泄。
2961
+ */
2962
+ const SECURITY_HEADERS = {
2963
+ "X-Content-Type-Options": "nosniff",
2964
+ "X-Frame-Options": "DENY",
2965
+ "Referrer-Policy": "no-referrer",
2966
+ "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'"
2967
+ };
2968
+
2969
+ /**
2970
+ * 给响应挂上安全头并返回可交给 writeHead 的 headers。
2971
+ * 也在请求入口先 `setHeader` 一次:这样 lib/rescue 的 handleRescueApi 自己 writeHead 的
2972
+ * JSON 响应(本仓库文件范围外)同样带上安全头。
2973
+ */
2974
+ function applySecurityHeaders(res, extra = {}) {
2975
+ if (res && typeof res.setHeader === "function" && !res.headersSent) {
2976
+ for (const [name, value] of Object.entries(SECURITY_HEADERS)) res.setHeader(name, value);
2977
+ }
2978
+ return { ...SECURITY_HEADERS, ...extra };
2979
+ }
2980
+
2705
2981
  function startServer(args) {
2706
2982
  const startedAt = new Date().toISOString();
2707
2983
  // 1.0.0-rc.1:每次启动器进程起来都重写 dsh-launcher.cmd(重装/升级后自愈,路径全部来自当前实况)
@@ -2714,7 +2990,7 @@ function startServer(args) {
2714
2990
  const pluginsFlight = createSingleFlight("open-boot:plugins");
2715
2991
  const rescueCtx = { profile: args.profile, dsh: args.dsh, cwd: args.cwd, port: args.port, flight };
2716
2992
  const sendJson = (res, code, body) => {
2717
- res.writeHead(code, { "Content-Type": "application/json; charset=utf-8" });
2993
+ res.writeHead(code, applySecurityHeaders(res, { "Content-Type": "application/json; charset=utf-8" }));
2718
2994
  res.end(JSON.stringify(body));
2719
2995
  };
2720
2996
  /** L11 ①②:写接口的 Origin + 令牌检查。返回 true 表示已拒绝并应答。 */
@@ -2725,11 +3001,18 @@ function startServer(args) {
2725
3001
  return true;
2726
3002
  };
2727
3003
  const sendHtml = (res, html) => {
2728
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
3004
+ res.writeHead(200, applySecurityHeaders(res, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }));
2729
3005
  res.end(html);
2730
3006
  };
2731
3007
 
2732
3008
  const server = createServer(async (req, res) => {
3009
+ // S4:先挂安全头(任何分支、含救援 API 自己的 writeHead 都继承)
3010
+ applySecurityHeaders(res);
3011
+ // S3:Host 校验放在**路由之前**——DNS 重绑定请求在这里就该被 421 挡掉
3012
+ if (!isAllowedHost(req.headers.host, args.port)) {
3013
+ sendJson(res, 421, { ok: false, code: 421, error: "Host 不被允许(仅接受回环地址)" });
3014
+ return;
3015
+ }
2733
3016
  const url = new URL(req.url, "http://127.0.0.1");
2734
3017
  const pathname = url.pathname;
2735
3018
  if (pathname === "/") {
@@ -2758,6 +3041,9 @@ function startServer(args) {
2758
3041
  return;
2759
3042
  }
2760
3043
  if (pathname === "/plugins/api/bundles" && req.method === "GET") {
3044
+ // S3 附带:已装插件清单不该裸奔给任意本地网页(DNS 重绑定后可读),GET 也过 Origin+令牌。
3045
+ // 页面侧 api() 对 GET 已经带 X-DSH-PM-Token(loadBundles 走 api()),不需要额外改动。
3046
+ if (rejectWrite(req, res)) return;
2761
3047
  sendJson(res, 200, listBundles(args.profile));
2762
3048
  return;
2763
3049
  }
@@ -2894,7 +3180,7 @@ function startServer(args) {
2894
3180
  });
2895
3181
  return;
2896
3182
  }
2897
- res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
3183
+ res.writeHead(404, applySecurityHeaders(res, { "Content-Type": "text/plain; charset=utf-8" }));
2898
3184
  res.end("not found");
2899
3185
  });
2900
3186
 
@@ -2923,7 +3209,8 @@ function startServer(args) {
2923
3209
  console.log(`[open-boot] profile: ${args.profile};引擎端口: ${ENGINE_PORT};拉起引擎时${args.window ? "弹窗显示进度" : "静默启动"};cwd: ${process.cwd()}`);
2924
3210
  console.log(`[open-boot] 救援能力(唯一网页入口):http://127.0.0.1:${args.port}/rescue(/rescue/api/*:verify|fix|start|stop|status);` +
2925
3211
  `rescue-daemon 备份入口默认 ${RESCUE_DAEMON_PORT}(不再抢占 ${args.port})`);
2926
- console.log(`[open-boot] 写接口防护:/api/boot 与 /rescue/api/* 的 POST 需同源 Origin + 一次性令牌(页面自动带上,不写日志/不落盘)`);
3212
+ console.log(`[open-boot] 写接口防护:/api/boot 与 /rescue/api/* 的 POST 需同源 Origin + 一次性令牌(页面自动带上,不写日志/不落盘);` +
3213
+ `入口 Host 仅接受回环地址 127.0.0.1/localhost/[::1]:${args.port}(其余 421)`);
2927
3214
  });
2928
3215
  return server;
2929
3216
  }
@@ -2998,5 +3285,9 @@ export {
2998
3285
  main, parseArgs, reportStatus, startServer, uninstallAutostart, writeShim,
2999
3286
  // rc.2 测试面:单测直接驱动这些函数(不经过 HTTP)
3000
3287
  CORE_BUNDLES, MANAGER_SELF_NAME, PKG_NAME_RE, runPnpm, writeFileAtomic, engineBusyGate,
3001
- uninstallPackageTransactional, updatePackage, checkUpdates, healthReport, restartEngine, ensureLauncherCmd
3288
+ uninstallPackageTransactional, updatePackage, checkUpdates, healthReport, restartEngine, ensureLauncherCmd,
3289
+ // 1.0.3 任务 C 测试面:Host 校验 / 安全响应头 / 有界缓冲 / updates 缓存
3290
+ isAllowedHost, SECURITY_HEADERS, PNPM_OUTPUT_CAP, createBoundedBuffer, lockfileStamp, resetUpdatesCacheForTests,
3291
+ // U1 测试面:兜底页 HTML 静态断言(test-ux.mjs)直接检查页面结构,不用起浏览器
3292
+ pluginsPageHtml
3002
3293
  };