@andy.ian/dsh-homing 2.1.0 → 2.1.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.
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- // 守护进程入口(真正实现在 ../restart-daemon/main.mjs)
3
- import '../restart-daemon/main.mjs'
2
+ // 守护进程入口(真正实现在 ../restart/daemon/main.mjs)
3
+ import '../restart/daemon/main.mjs'
package/bin/restart.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- // 命令行入口(真正实现在 ../restart-daemon/cli.mjs)
3
- import '../restart-daemon/cli.mjs'
2
+ // 命令行入口(真正实现在 ../restart/daemon/cli.mjs)
3
+ import '../restart/daemon/cli.mjs'
package/index.js CHANGED
@@ -356,161 +356,14 @@ function createCookieMinter(credentials, getUpstreamPort) {
356
356
 
357
357
  const MOBILE_CSS = `html { -webkit-text-size-adjust: 100%; }
358
358
  @media (max-width: 760px) {
359
- [aria-label="打开右侧边栏"] { display: none !important; }
360
359
  [class*="_frame"] { min-width: 0; }
361
-
362
- /* 隐藏时只把侧边栏那一列压成 0,主内容自然占满;其余布局仍归应用自己算 */
363
- html[data-dsh-homing-nav="hidden"] [class*="_frame"] {
364
- grid-template-columns: 0 1fr 0 !important;
365
- transition: none !important;
366
- }
367
- html[data-dsh-homing-nav="hidden"] [class*="sidebarCol"] {
368
- min-width: 0 !important;
369
- overflow: hidden !important;
370
- }
371
-
372
- /* 侧边栏完全隐藏时,左上角探出的小耳朵(磁吸感):点它恢复完整侧边栏 */
373
- .dsh-homing-ear {
374
- position: fixed;
375
- left: 0;
376
- top: 16px;
377
- width: 16px;
378
- height: 40px;
379
- z-index: 62;
380
- display: none;
381
- align-items: center;
382
- justify-content: center;
383
- padding: 0;
384
- border: 1px solid rgba(255, 255, 255, 0.14);
385
- border-left: 0;
386
- border-radius: 0 10px 10px 0;
387
- background: rgba(30, 34, 42, 0.72);
388
- color: #aeb5c2;
389
- font-size: 14px;
390
- line-height: 1;
391
- box-shadow: 0 2px 10px rgba(0, 0, 0, 0.4);
392
- -webkit-tap-highlight-color: transparent;
393
- user-select: none;
394
- touch-action: manipulation;
395
- }
396
- .dsh-homing-ear:active { background: rgba(60, 66, 78, 0.95); color: #e8eaed; }
397
360
  }
398
361
  `;
399
362
 
400
363
  const MOBILE_JS = `(() => {
401
364
  const narrow = () => window.innerWidth <= 760
402
365
  const root = document.documentElement
403
- const frame = () => document.querySelector('[class*="_frame"]')
404
- const mainCol = () => { const f = frame(); return f ? f.children[1] : null }
405
366
  const sidebar = () => document.querySelector('[class*="sidebarCol"]')
406
- const openBtn = () => document.querySelector('[aria-label="打开侧边栏"]')
407
- const collapseBtn = () => document.querySelector('[aria-label="收起侧边栏"]')
408
- const isHidden = () => root.getAttribute('data-dsh-homing-nav') === 'hidden'
409
- // 我们自己去点应用按钮时,要绕过下面那个捕获拦截,否则会自己拦自己、无限递归
410
- let quietClick = false
411
- const clickQuietly = (btn) => {
412
- if (btn === null) return
413
- quietClick = true
414
- try { btn.click() } finally { setTimeout(() => { quietClick = false }, 0) }
415
- }
416
- const widthOf = (node) => (node ? node.getBoundingClientRect().width : 0)
417
-
418
- // 三态:expanded(完整) / rail(图标栏) / hidden(完全隐藏)
419
- const stateOf = () => {
420
- if (isHidden()) return 'hidden'
421
- return widthOf(sidebar()) > 70 ? 'expanded' : 'rail'
422
- }
423
-
424
- const hide = () => {
425
- if (!narrow()) return false
426
- const before = widthOf(mainCol())
427
- root.setAttribute('data-dsh-homing-nav', 'hidden')
428
- const after = widthOf(mainCol())
429
- if (!(after > before + 10)) {
430
- root.removeAttribute('data-dsh-homing-nav')
431
- console.warn('[dsh-homing] 侧边栏隐藏未生效,已自动撤销')
432
- updateEar()
433
- return false
434
- }
435
- updateEar()
436
- return true
437
- }
438
-
439
- const showAttribute = () => {
440
- root.removeAttribute('data-dsh-homing-nav')
441
- updateEar()
442
- }
443
-
444
- const toExpanded = () => {
445
- clickQuietly(openBtn())
446
- setTimeout(() => { showAttribute(); updateEar() }, 80)
447
- }
448
-
449
- const toRail = () => {
450
- showAttribute()
451
- clickQuietly(collapseBtn())
452
- }
453
-
454
- const toHidden = () => {
455
- clickQuietly(collapseBtn())
456
- hide()
457
- }
458
-
459
- // 应用自带的开关:按 完整 → 图标栏 → 隐藏 循环
460
- const cycle = () => {
461
- const state = stateOf()
462
- if (state === 'expanded') toRail()
463
- else if (state === 'rail') toHidden()
464
- else toExpanded()
465
- }
466
-
467
- // 隐藏时左上角探出的小耳朵,点它恢复完整侧边栏
468
- let ear = null
469
- const EAR_HEIGHT = 40
470
- // 对齐到应用自带开关的竖直中心(它在侧边栏里,即使侧边栏被压成 0 也能量到)
471
- const placeEar = () => {
472
- if (ear === null) return
473
- const anchor = collapseBtn() ?? openBtn()
474
- if (anchor === null) return
475
- const rect = anchor.getBoundingClientRect()
476
- if (rect.height === 0 && rect.width === 0) return
477
- const top = Math.round(rect.top + rect.height / 2 - EAR_HEIGHT / 2)
478
- ear.style.top = Math.max(2, top) + 'px'
479
- }
480
- const updateEar = () => {
481
- if (ear === null) return
482
- ear.style.display = narrow() && isHidden() ? 'flex' : 'none'
483
- placeEar()
484
- }
485
- const installEar = () => {
486
- ear = document.createElement('button')
487
- ear.type = 'button'
488
- ear.className = 'dsh-homing-ear'
489
- ear.setAttribute('aria-label', '展开侧边栏')
490
- ear.textContent = '›'
491
- ear.addEventListener('click', (event) => {
492
- event.preventDefault()
493
- event.stopPropagation()
494
- toExpanded()
495
- setTimeout(updateEar, 120)
496
- })
497
- document.body.appendChild(ear)
498
- placeEar()
499
- updateEar()
500
- }
501
-
502
- // 拦截应用自带开关的点击(捕获阶段,先于应用自己的处理)
503
- document.addEventListener('click', (event) => {
504
- if (quietClick) return
505
- if (!narrow()) return
506
- const target = event.target.closest('[aria-label="收起侧边栏"], [aria-label="打开侧边栏"]')
507
- if (target === null) return
508
- event.preventDefault()
509
- event.stopPropagation()
510
- cycle()
511
- setTimeout(updateEar, 200)
512
- }, true)
513
-
514
367
  // 记住最后点过的工作区:切换工作区必然有一次点击,这是最可靠的信号。
515
368
  // 存的只是名字,由服务端映射成路径;对不上就退回默认工作区。
516
369
  const LAST_WS_KEY = 'dsh-homing:last-workspace'
@@ -673,30 +526,88 @@ const MOBILE_JS = `(() => {
673
526
  button.click()
674
527
  }
675
528
 
676
- // 点侧边栏里的会话后,回到完全隐藏
677
- document.addEventListener('click', (event) => {
678
- if (!narrow() || isHidden()) return
679
- const side = sidebar()
680
- if (side === null || !side.contains(event.target)) return
681
- const collapse = collapseBtn()
682
- if (collapse !== null && collapse.contains(event.target)) return
683
- if (event.target.closest('[aria-label="收起侧边栏"], [aria-label="打开侧边栏"]')) return
684
- setTimeout(() => toHidden(), 260)
685
- }, false)
529
+ const start = () => {
530
+ closeRightBar()
531
+ }
686
532
 
687
- window.addEventListener('resize', () => { updateEar(); if (!narrow()) showAttribute() })
533
+ /* ---------- RESTART_MENU_ITEM ----------
534
+ * 在 DSH 会话「…」菜单里追加一项「重启 DSH / 守护进程」。
535
+ * 做法:复制一个已有的菜单项(连同图标与样式),只替换文字与图标路径,
536
+ * 这样配色/尺寸/间距完全跟随 DSH 自己的风格。
537
+ * 每次菜单变化先清掉旧项再插入,保证永远只有一项。
538
+ */
539
+ const MENU_HINT = /下载 Session 日志|复制会话为 Markdown|反馈/u
540
+ // Lucide rotate-ccw:与 DSH 菜单同尺寸的“重启”图标
541
+ const RESTART_ICON = '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'
542
+ let menuTimer = null
688
543
 
689
- const start = () => {
690
- if (!narrow()) { closeRightBar(); return }
691
- installEar()
692
- const collapse = collapseBtn()
693
- if (collapse !== null) collapse.click()
694
- setTimeout(() => {
695
- hide()
696
- closeRightBar()
697
- }, 350)
544
+ const textNodeMatching = (node, pattern) => {
545
+ const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT)
546
+ for (let current = walker.nextNode(); current !== null; current = walker.nextNode()) {
547
+ if (pattern.test(current.nodeValue || '')) return current
548
+ }
549
+ return null
698
550
  }
699
551
 
552
+ const enhanceMenus = () => {
553
+ // 每个 role=menu 容器只处理一次;注意菜单项外面可能还包了一层 wrapper,
554
+ // 所以必须向上找到真正的菜单容器,而不是用 item.parentElement。
555
+ const done = new Set()
556
+ for (const item of document.querySelectorAll('[role="menuitem"]')) {
557
+ const menu = item.closest('[role="menu"]') ?? item.parentElement
558
+ if (menu === null || done.has(menu)) continue
559
+ if (!MENU_HINT.test(menu.textContent || '')) continue
560
+ done.add(menu)
561
+
562
+ // 先清掉旧的(含 React 重渲染造成的重复),保证只有一项
563
+ for (const old of menu.querySelectorAll('[data-dsh-homing-restart]')) old.remove()
564
+
565
+ const items = [...menu.querySelectorAll('[role="menuitem"]')]
566
+ const template = items.find((node) => node.querySelector('svg')) ?? items[0]
567
+ if (!template) continue
568
+ const link = template.cloneNode(true)
569
+ link.setAttribute('role', 'menuitem')
570
+ link.setAttribute('data-dsh-homing-restart', '1')
571
+ link.setAttribute('href', '/dsh_homing/restart')
572
+ link.style.textDecoration = 'none'
573
+
574
+ const textNode = textNodeMatching(link, /反馈|下载 Session 日志|复制会话为 Markdown/u)
575
+ if (textNode !== null) textNode.nodeValue = '重启 DSH / 守护进程'
576
+ else link.textContent = '重启 DSH / 守护进程'
577
+
578
+ const svg = link.querySelector('svg')
579
+ if (svg !== null) {
580
+ // 图标按菜单项的描边风格来,避免 fill=currentColor 渲染成一坨实心圆
581
+ svg.innerHTML = RESTART_ICON
582
+ svg.setAttribute('viewBox', '0 0 24 24')
583
+ svg.setAttribute('fill', 'none')
584
+ svg.setAttribute('stroke', 'currentColor')
585
+ svg.setAttribute('stroke-width', '2')
586
+ svg.setAttribute('stroke-linecap', 'round')
587
+ svg.setAttribute('stroke-linejoin', 'round')
588
+ }
589
+
590
+ link.addEventListener('click', (event) => {
591
+ event.preventDefault()
592
+ event.stopPropagation()
593
+ window.location.assign('/dsh_homing/restart')
594
+ }, true)
595
+ menu.appendChild(link)
596
+ }
597
+ }
598
+
599
+ // 兜底:无论菜单容器怎么嵌套,页面上最多只保留一个
600
+ const pruneRestartItems = () => {
601
+ const all = [...document.querySelectorAll('[data-dsh-homing-restart]')]
602
+ for (let i = 0; i < all.length - 1; i += 1) all[i].remove()
603
+ }
604
+
605
+ const menuObserver = new MutationObserver(() => {
606
+ if (menuTimer) return
607
+ menuTimer = setTimeout(() => { menuTimer = null; enhanceMenus(); pruneRestartItems() }, 80)
608
+ })
609
+ menuObserver.observe(document.body, { childList: true, subtree: true })
610
+
700
611
  /* ---------- ALIVE_BEACON ----------
701
612
  * 告诉插件"用户正在操作":重启脚本据此判断能否安全重启。
702
613
  * 手机上打字/滑动手势不会修改会话文件,只有这个信标能反映"人在用"。
@@ -727,57 +638,6 @@ const MOBILE_JS = `(() => {
727
638
  else start()
728
639
  })();
729
640
 
730
- // 左侧「小耳朵」:插到侧边栏开关旁边(复用它的 class,尺寸/配色自动一致)
731
- (function () {
732
- if (window.__dshEar) return;
733
- window.__dshEar = true;
734
-
735
- var a = document.createElement('a');
736
- a.href = '/dsh_homing/restart';
737
- a.title = '重启 / 守护进程';
738
- a.textContent = '\u267B';
739
- a.id = 'dsh-ear';
740
- a.style.cssText = 'text-decoration:none;display:flex;align-items:center;justify-content:center;';
741
-
742
- function toggleEl() {
743
- return document.querySelector('[aria-label="收起侧边栏"],[title="收起侧边栏"],[aria-label="打开侧边栏"],[title="打开侧边栏"]');
744
- }
745
-
746
- // 把耳朵放到开关按钮的后面(同一容器、同一行/列),并复制它的 class 以继承尺寸
747
- function place() {
748
- var toggle = toggleEl();
749
- if (!toggle || !toggle.parentNode) return false;
750
- if (a.parentNode === toggle.parentNode) return true;
751
- a.className = toggle.className;
752
- // 尺寸跟随按钮,避免"探出太多"
753
- var r = toggle.getBoundingClientRect();
754
- if (r.width > 0) { a.style.width = Math.round(r.width) + 'px'; a.style.height = Math.round(r.height) + 'px'; }
755
- a.style.fontSize = Math.round((r.height || 32) * 0.5) + 'px';
756
- toggle.parentNode.insertBefore(a, toggle.nextSibling);
757
- return true;
758
- }
759
-
760
- // DSH 是 SPA,普通 <a> 点击会被它自己的路由吞掉 → 在 window 捕获阶段强制整页跳转
761
- function jump(event) {
762
- var target = event.target;
763
- var ear = target && target.closest ? target.closest('#dsh-ear') : null;
764
- if (!ear) return;
765
- event.preventDefault();
766
- event.stopImmediatePropagation();
767
- window.location.assign('/dsh_homing/restart');
768
- }
769
- window.addEventListener('click', jump, true);
770
- window.addEventListener('touchend', jump, true);
771
-
772
- place();
773
- // 侧边栏可能延迟渲染或 React 重渲染把节点冲掉:用 MutationObserver 兜底,但只在丢失时重插
774
- var timer = null;
775
- var obs = new MutationObserver(function () {
776
- if (timer) return;
777
- timer = setTimeout(function () { timer = null; place(); }, 400);
778
- });
779
- obs.observe(document.body, { childList: true, subtree: true });
780
- })();
781
641
  `;
782
642
 
783
643
  const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script defer src="/dsh_homing/mobile.js"></script>';
@@ -835,8 +695,6 @@ const restartService = createRestartService({
835
695
  postTimeoutMs: 5000,
836
696
  });
837
697
 
838
- const daemonStatus = () => restartService.status();
839
- const daemonPost = (pathAndQuery) => restartService.post(pathAndQuery);
840
698
 
841
699
  const LIVE_SCRIPT = `<div id="live" class="dim" style="margin-top:8px">脚本未加载</div>`
842
700
  + `<script src="/dsh_homing/restart.js"></script>`;
@@ -1138,7 +996,7 @@ function sessionRunning(dshHomeDir) {
1138
996
  }
1139
997
  async function collectRestartState(dataDir) {
1140
998
  const sessions = sessionRunning(path.resolve(dataDir, '..', '..'));
1141
- const status = await daemonStatus();
999
+ const status = await restartService.status();
1142
1000
  const policyStatus = restartPolicy.status();
1143
1001
  const config = policyStatus?.config ?? null;
1144
1002
  return {
@@ -1197,7 +1055,7 @@ const restartPolicy = createRestartPolicy({
1197
1055
  return Number(raw.at) || 0;
1198
1056
  } catch { return 0 }
1199
1057
  },
1200
- triggerRestart: () => daemonPost('/restart-now'),
1058
+ triggerRestart: () => restartService.post('/restart-now'),
1201
1059
  // 策略来自配置文件(可热更新;写坏时保留上次有效配置)
1202
1060
  specPath: path.join(dataDir(), 'policy.json'),
1203
1061
  log: (message) => appendAudit(dataDir(), 'restart-policy', { message }),
@@ -1664,15 +1522,21 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1664
1522
  // 攻击者注入的脚本没有 nonce,即使 HTML 转义出漏洞也跑不起来。
1665
1523
  const nonce = crypto.randomBytes(16).toString('base64url');
1666
1524
  let responseType = '';
1525
+ let ownHtml = false; // 只给插件自身渲染的页面加 nonce,DSH 页面原样透传
1667
1526
  const rawWriteHead = res.writeHead.bind(res);
1668
1527
  res.writeHead = (status, headers, ...rest) => {
1669
1528
  if (headers && typeof headers === 'object' && typeof headers['content-type'] === 'string') {
1670
1529
  responseType = headers['content-type'];
1671
1530
  }
1672
- if (headers && typeof headers === 'object' && typeof headers['content-security-policy'] === 'string') {
1531
+ let csp = '';
1532
+ if (headers && typeof headers === 'object') csp = String(headers['content-security-policy'] ?? '');
1533
+ // 只有插件自己的页面以 default-src 'none' 开头;DSH 前端页面不能改写,
1534
+ // 否则会破坏 0.2.2 动态生成的 <script> 模板。
1535
+ if (csp.includes("default-src 'none'")) {
1536
+ ownHtml = true;
1673
1537
  headers = {
1674
1538
  ...headers,
1675
- 'content-security-policy': headers['content-security-policy'].replace(
1539
+ 'content-security-policy': csp.replace(
1676
1540
  "script-src 'self'",
1677
1541
  `script-src 'self' 'nonce-${nonce}'`,
1678
1542
  ),
@@ -1683,7 +1547,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1683
1547
  const rawEnd = res.end.bind(res);
1684
1548
  res.end = (body, ...rest) => {
1685
1549
  const type = responseType || String(res.getHeader('content-type') ?? '');
1686
- if (typeof body === 'string' && type.includes('text/html')) {
1550
+ if (ownHtml && typeof body === 'string' && type.includes('text/html')) {
1687
1551
  body = body.replaceAll('<script', `<script nonce="${nonce}"`);
1688
1552
  }
1689
1553
  return rawEnd(body, ...rest);
@@ -1938,7 +1802,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1938
1802
  // 重启界面:服务端渲染 + 表单提交(无内联脚本)
1939
1803
  if (url.pathname === '/dsh_homing/restart' && req.method === 'GET') {
1940
1804
  const sessions = sessionRunning(path.resolve(dataDir(), '..', '..'));
1941
- const status = await daemonStatus();
1805
+ const status = await restartService.status();
1942
1806
  const message = url.searchParams.get('m') ?? '';
1943
1807
  res.writeHead(200, {
1944
1808
  'content-type': 'text/html; charset=utf-8',
@@ -1969,7 +1833,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1969
1833
  } else if (action === 'force') {
1970
1834
  if (sessions.length > 0 && form.get('confirm') !== '1') {
1971
1835
  // 繁忙:先渲染二次确认页,列出正在运行的会话
1972
- const status = await daemonStatus();
1836
+ const status = await restartService.status();
1973
1837
  res.writeHead(200, {
1974
1838
  'content-type': 'text/html; charset=utf-8',
1975
1839
  'cache-control': 'no-store',
@@ -1986,11 +1850,11 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1986
1850
  if (!Number.isFinite(minutes) || minutes <= 0) {
1987
1851
  message = '暂停失败:请填写正整数分钟';
1988
1852
  } else {
1989
- const r = await daemonPost('/pause?minutes=' + minutes);
1853
+ const r = await restartService.post('/pause?minutes=' + minutes);
1990
1854
  message = r.ok ? ('已暂停自动拉起 ' + minutes + ' 分钟') : '暂停失败:守护进程未运行';
1991
1855
  }
1992
1856
  } else if (action === 'resume') {
1993
- const r = await daemonPost('/resume');
1857
+ const r = await restartService.post('/resume');
1994
1858
  message = r.ok ? '已恢复自动拉起' : '恢复失败:守护进程未运行';
1995
1859
  }
1996
1860
  void broadcastRestartState(dataDir(), { event: 'restart-accepted', action });
@@ -2000,7 +1864,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2000
1864
  }
2001
1865
 
2002
1866
  if (url.pathname === '/dsh_homing/restart/state' && req.method === 'GET') {
2003
- const sup = await daemonStatus();
1867
+ const sup = await restartService.status();
2004
1868
  const sessions = sessionRunning(path.resolve(dataDir(), '..', '..'));
2005
1869
  const payload = JSON.stringify({
2006
1870
  daemon: sup ? { running: sup.running, restarts: sup.daemon?.restarts ?? 0, paused: sup.paused ?? false, pausedSecondsLeft: sup.pausedSecondsLeft ?? 0, probeAgeSeconds: sup.probeAgeSeconds ?? null, lastProbeAt: sup.lastProbeAt ?? null } : null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.1.0",
3
+ "version": "2.1.2",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [
@@ -44,7 +44,6 @@
44
44
  "bin/nginx-ws-map.conf",
45
45
  "lib/*.mjs",
46
46
  "lib/*.js",
47
- "restart-daemon/**",
48
47
  "cordis.patch.yml",
49
48
  "locale/*.json",
50
49
  "icon.svg",
@@ -1,11 +1,20 @@
1
1
  # 守护进程(restart-daemon)
2
2
 
3
- DSH 崩溃/退出后负责把它重新拉起的后台进程。**不在 DSH 的进程树里**,因此 `taskkill /T` 杀不到它。
3
+ DSH 崩溃/退出后负责把它重新拉起的后台进程。
4
+
5
+ 进程关系是**单向**的,两个方向都要记住:
6
+
7
+ | 方向 | 事实 | 后果 |
8
+ |---|---|---|
9
+ | DSH → 守护进程 | 守护进程**不在** DSH 的进程树里 | `taskkill /T` 杀掉 DSH 时,守护进程不受影响(它还能把 DSH 拉回来) |
10
+ | 守护进程 → DSH | DSH **是**守护进程的子进程(由它启动) | 停止守护进程时**不能**用 `/T` 或"结束进程树",否则会把 DSH 一起杀掉 |
11
+
12
+ 停止守护进程的安全做法见下文《DSH 是它的子进程》。
4
13
 
5
14
  ## 目录结构
6
15
 
7
16
  ```
8
- restart-daemon/
17
+ restart/daemon/
9
18
  ├─ main.mjs 守护进程本体(探测、重启、升级等待、控制口)
10
19
  ├─ cli.mjs 命令行:install / start / status / stop / restart / remove
11
20
  └─ lib/
@@ -50,13 +59,40 @@ VBScript 已弃用,代码中不再生成 VBS。
50
59
  - 变更加操作必须满足:**请求来源 PID == 插件宿主 PID**(监听 8787 的进程),且该 PID 属于 DSH 进程集合
51
60
  - 外部进程调用 `/restart-now` 一律 403
52
61
 
62
+ ### DSH 是它的子进程
63
+
64
+ DSH 由守护进程启动,因此**是守护进程的子进程**。这带来一条硬性约束:
65
+
66
+ > **停止守护进程时,绝对不能用"杀进程树"的方式。**
67
+
68
+ 用 `taskkill /T /PID <守护进程PID>` 或在任务管理器里"结束进程树",
69
+ 会把正在运行的 DSH(以及它的渲染进程)一起杀掉。
70
+
71
+ | 停止方式 | 对 DSH 的影响 |
72
+ |---|---|
73
+ | `node bin/restart.mjs stop` | ✅ 安全:先 HTTP `/stop` 优雅退出,失败则按 PID 单杀 |
74
+ | `Stop-Process -Id <守护进程PID>` | ✅ 安全:只结束单个进程 |
75
+ | `process.kill(<守护进程PID>)` | ✅ 安全:同上 |
76
+ | `taskkill /T /PID <守护进程PID>` | ❌ 会连带杀掉 DSH |
77
+ | 任务管理器 → 结束进程树 | ❌ 会连带杀掉 DSH |
78
+
79
+ `cli.mjs` 的 `stopDaemonSafely()` 实现了安全停止:
80
+
81
+ 1. 请求 `HTTP /stop`,让守护进程自己退出;
82
+ 2. 失败(未授权/不可达)时读取 `~/.dsh/restart-daemon/restart-daemon.pid`,
83
+ 用 `/health` 核对 PID 一致后才 `process.kill(pid)`;
84
+ 3. PID 不一致直接拒绝,避免 pid 文件过期导致杀错进程。
85
+
86
+ 回归测试 `test/unit.daemon-stop.test.mjs` 会校验:
87
+ CLI 可执行代码不含 `taskkill /T`,且 `main.mjs` 里杀 DSH 的全部 `taskkill` 调用均为逐 PID。
88
+
53
89
  ## 常用命令
54
90
 
55
91
  ```bash
56
92
  node bin/restart.mjs install # 安装开机自启
57
93
  node bin/restart.mjs start # 启动(CIM 优先)
58
94
  node bin/restart.mjs status # 状态(含自启项校验)
59
- node bin/restart.mjs stop # 停止
95
+ node bin/restart.mjs stop # 停止(安全:不杀进程树)
60
96
  ```
61
97
 
62
98
  ## 测试
@@ -284,21 +284,66 @@ async function start() {
284
284
  async function restart() {
285
285
  try {
286
286
  const res = await call('/restart-now', 'POST', {})
287
- console.log(res.status === 202 ? ' 已请求立即重启(策略层不参与,慎用)' : ` 请求被拒绝(HTTP ${res.status})`)
287
+ if (res.status === 202) console.log(' 已请求立即重启 DSH(不经过策略层,慎用)')
288
+ else console.log(' 请求被拒绝(HTTP ' + res.status + '):重启 DSH 需要插件宿主发起,请用页面或策略接口')
288
289
  } catch {
289
290
  console.error('守护进程没在运行。先 install 或手动启动 bin/restart-daemon.mjs --detach。')
290
291
  process.exit(1)
291
292
  }
292
293
  }
293
294
 
294
- async function stop() {
295
+ /**
296
+ * 安全停止守护进程。
297
+ *
298
+ * 铁律:绝不能用"杀进程树"(taskkill /T)——
299
+ * 因为 DSH 是由守护进程启动的,是它的**子进程**;
300
+ * 杀树会把正在运行的 DSH 一起带走。
301
+ *
302
+ * 策略:
303
+ * 1. 先请求 HTTP /stop,让守护进程自己优雅退出(最安全)
304
+ * 2. 失败(未授权/不可达)时,读 pid 文件,确认该 PID 就是守护进程,再单杀该 PID
305
+ */
306
+ async function stopDaemonSafely() {
307
+ // ① 优雅退出
295
308
  try {
296
- await call('/stop')
297
- console.log(' 守护进程已退出(不会自动拉起 DSH)')
298
- } catch {
299
- console.error('守护进程没在运行')
309
+ const res = await call('/stop')
310
+ if (res.status === 200) return { ok: true, how: 'http-stop' }
311
+ } catch { /* 继续走 PID 路径 */ }
312
+
313
+ // ② 按 PID 单杀(不碰子进程)
314
+ const pidFile = path.join(process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'), 'restart-daemon', 'restart-daemon.pid')
315
+ let pid = 0
316
+ try { pid = Number(fs.readFileSync(pidFile, 'utf8').trim()) } catch { /* 没有 pid 文件 */ }
317
+
318
+ // 用 /health 核对 PID,防止 pid 文件过期导致杀错进程
319
+ try {
320
+ const health = await call('/health', 'GET')
321
+ if (health.status === 200) {
322
+ const body = JSON.parse(health.body ?? '{}')
323
+ if (body.pid && body.pid !== pid) {
324
+ return { ok: false, reason: 'pid-mismatch', healthPid: body.pid, pidFilePid: pid }
325
+ }
326
+ pid = body.pid
327
+ }
328
+ } catch { /* 端口不通,继续用 pid 文件 */ }
329
+
330
+ if (!Number.isFinite(pid) || pid <= 0) return { ok: false, reason: 'no-pid' }
331
+
332
+ try {
333
+ process.kill(pid) // 只杀这一个进程,子进程(DSH)不受影响
334
+ return { ok: true, how: 'pid-kill', pid }
335
+ } catch (error) {
336
+ return { ok: false, reason: error.code ?? error.message, pid }
337
+ }
338
+ }
339
+
340
+ async function stop() {
341
+ const result = await stopDaemonSafely()
342
+ if (!result.ok) {
343
+ console.error(' 停止失败:' + (result.reason ?? '未知原因'))
300
344
  process.exit(1)
301
345
  }
346
+ console.log(' 守护进程已停止(方式:' + result.how + ';DSH 子进程不受影响)')
302
347
  }
303
348
 
304
349
  switch (command) {
File without changes