@andy.ian/dsh-homing 2.1.4 → 2.1.6

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.
Files changed (122) hide show
  1. package/README.md +42 -0
  2. package/SECURITY.md +90 -0
  3. package/bin/backup.mjs +3 -2
  4. package/bin/bootstrap-server.mjs +2 -1
  5. package/bin/inbox.mjs +46 -0
  6. package/bin/renew-cert.mjs +2 -1
  7. package/bin/window-agent-daemon.mjs +268 -0
  8. package/index.js +686 -87
  9. package/lib/compress.mjs +29 -5
  10. package/lib/exec-path.mjs +85 -0
  11. package/lib/files-page.mjs +27 -2
  12. package/lib/files.mjs +3 -2
  13. package/lib/git.mjs +5 -2
  14. package/lib/guard.mjs +43 -0
  15. package/lib/local-socket.mjs +50 -0
  16. package/lib/log-file.mjs +50 -0
  17. package/lib/node-runtime.mjs +44 -0
  18. package/lib/office.mjs +133 -0
  19. package/lib/orientation.mjs +158 -0
  20. package/lib/pty.mjs +6 -3
  21. package/lib/secret.mjs +46 -0
  22. package/lib/shells.mjs +2 -1
  23. package/lib/term-page.mjs +2 -0
  24. package/lib/vendor/des-vnc.mjs +266 -0
  25. package/lib/vendor/novnc/LICENSE.txt +62 -0
  26. package/lib/vendor/novnc/core/base64.js +104 -0
  27. package/lib/vendor/novnc/core/crypto/aes.js +178 -0
  28. package/lib/vendor/novnc/core/crypto/bigint.js +34 -0
  29. package/lib/vendor/novnc/core/crypto/crypto.js +90 -0
  30. package/lib/vendor/novnc/core/crypto/des.js +330 -0
  31. package/lib/vendor/novnc/core/crypto/dh.js +55 -0
  32. package/lib/vendor/novnc/core/crypto/md5.js +82 -0
  33. package/lib/vendor/novnc/core/crypto/rsa.js +132 -0
  34. package/lib/vendor/novnc/core/decoders/copyrect.js +27 -0
  35. package/lib/vendor/novnc/core/decoders/h264.js +321 -0
  36. package/lib/vendor/novnc/core/decoders/hextile.js +181 -0
  37. package/lib/vendor/novnc/core/decoders/jpeg.js +161 -0
  38. package/lib/vendor/novnc/core/decoders/raw.js +59 -0
  39. package/lib/vendor/novnc/core/decoders/rre.js +44 -0
  40. package/lib/vendor/novnc/core/decoders/tight.js +393 -0
  41. package/lib/vendor/novnc/core/decoders/tightpng.js +27 -0
  42. package/lib/vendor/novnc/core/decoders/zlib.js +51 -0
  43. package/lib/vendor/novnc/core/decoders/zrle.js +185 -0
  44. package/lib/vendor/novnc/core/deflator.js +84 -0
  45. package/lib/vendor/novnc/core/display.js +578 -0
  46. package/lib/vendor/novnc/core/encodings.js +54 -0
  47. package/lib/vendor/novnc/core/inflator.js +65 -0
  48. package/lib/vendor/novnc/core/input/domkeytable.js +311 -0
  49. package/lib/vendor/novnc/core/input/fixedkeys.js +129 -0
  50. package/lib/vendor/novnc/core/input/gesturehandler.js +567 -0
  51. package/lib/vendor/novnc/core/input/keyboard.js +294 -0
  52. package/lib/vendor/novnc/core/input/keysym.js +616 -0
  53. package/lib/vendor/novnc/core/input/keysymdef.js +688 -0
  54. package/lib/vendor/novnc/core/input/util.js +191 -0
  55. package/lib/vendor/novnc/core/input/vkeys.js +116 -0
  56. package/lib/vendor/novnc/core/input/xtscancodes.js +173 -0
  57. package/lib/vendor/novnc/core/ra2.js +312 -0
  58. package/lib/vendor/novnc/core/rfb.js +3420 -0
  59. package/lib/vendor/novnc/core/util/browser.js +233 -0
  60. package/lib/vendor/novnc/core/util/cursor.js +249 -0
  61. package/lib/vendor/novnc/core/util/element.js +32 -0
  62. package/lib/vendor/novnc/core/util/events.js +138 -0
  63. package/lib/vendor/novnc/core/util/eventtarget.js +35 -0
  64. package/lib/vendor/novnc/core/util/int.js +15 -0
  65. package/lib/vendor/novnc/core/util/logging.js +56 -0
  66. package/lib/vendor/novnc/core/util/strings.js +28 -0
  67. package/lib/vendor/novnc/core/websock.js +369 -0
  68. package/lib/vendor/novnc/vendor/pako/LICENSE +21 -0
  69. package/lib/vendor/novnc/vendor/pako/README.md +6 -0
  70. package/lib/vendor/novnc/vendor/pako/lib/utils/common.js +45 -0
  71. package/lib/vendor/novnc/vendor/pako/lib/zlib/adler32.js +27 -0
  72. package/lib/vendor/novnc/vendor/pako/lib/zlib/constants.js +47 -0
  73. package/lib/vendor/novnc/vendor/pako/lib/zlib/crc32.js +36 -0
  74. package/lib/vendor/novnc/vendor/pako/lib/zlib/deflate.js +1846 -0
  75. package/lib/vendor/novnc/vendor/pako/lib/zlib/gzheader.js +35 -0
  76. package/lib/vendor/novnc/vendor/pako/lib/zlib/inffast.js +324 -0
  77. package/lib/vendor/novnc/vendor/pako/lib/zlib/inflate.js +1527 -0
  78. package/lib/vendor/novnc/vendor/pako/lib/zlib/inftrees.js +322 -0
  79. package/lib/vendor/novnc/vendor/pako/lib/zlib/messages.js +11 -0
  80. package/lib/vendor/novnc/vendor/pako/lib/zlib/trees.js +1195 -0
  81. package/lib/vendor/novnc/vendor/pako/lib/zlib/zstream.js +24 -0
  82. package/lib/vendor/vnc.bundle.js +14592 -0
  83. package/lib/vendor/ws/LICENSE +20 -0
  84. package/lib/vendor/ws/index.js +22 -0
  85. package/lib/vendor/ws/lib/buffer-util.js +142 -0
  86. package/lib/vendor/ws/lib/constants.js +19 -0
  87. package/lib/vendor/ws/lib/event-target.js +292 -0
  88. package/lib/vendor/ws/lib/extension.js +203 -0
  89. package/lib/vendor/ws/lib/limiter.js +55 -0
  90. package/lib/vendor/ws/lib/permessage-deflate.js +530 -0
  91. package/lib/vendor/ws/lib/receiver.js +743 -0
  92. package/lib/vendor/ws/lib/sender.js +610 -0
  93. package/lib/vendor/ws/lib/stream.js +161 -0
  94. package/lib/vendor/ws/lib/subprotocol.js +62 -0
  95. package/lib/vendor/ws/lib/validation.js +152 -0
  96. package/lib/vendor/ws/lib/websocket-server.js +562 -0
  97. package/lib/vendor/ws/lib/websocket.js +1426 -0
  98. package/lib/vendor/ws/package.json +74 -0
  99. package/lib/vendor/ws/wrapper.mjs +21 -0
  100. package/lib/vnc-app.js +567 -0
  101. package/lib/vnc-auth-proxy.mjs +179 -0
  102. package/lib/vnc-boot.js +45 -0
  103. package/lib/vnc-page.mjs +77 -0
  104. package/lib/vnc-pointer.mjs +17 -0
  105. package/lib/vnc.mjs +75 -0
  106. package/lib/window-app.js +155 -0
  107. package/lib/window-page.mjs +111 -0
  108. package/lib/window-remote.mjs +227 -0
  109. package/lib/ws-bridge.mjs +130 -0
  110. package/package.json +6 -2
  111. package/permissions.json +91 -0
  112. package/restart/client.mjs +85 -19
  113. package/restart/daemon/cli.mjs +55 -13
  114. package/restart/daemon/lib/detach.mjs +3 -2
  115. package/restart/daemon/lib/process-tree.mjs +17 -3
  116. package/restart/daemon/lib/restart-flow.mjs +36 -0
  117. package/restart/daemon/main.mjs +299 -80
  118. package/restart/engine.mjs +24 -8
  119. package/restart/port.mjs +88 -0
  120. package/restart/runner.mjs +4 -3
  121. package/restart/service.mjs +8 -5
  122. package/restart/watchdog.mjs +134 -0
package/README.md CHANGED
@@ -44,6 +44,48 @@
44
44
  | `legacyFunc` | 是否仍接受旧版 `?func=` 常量暗号(默认 `false`) | `false` |
45
45
  | `login` | 是否要求账号密码 | `true` |
46
46
 
47
+ ## 桌面共享(VNC,跨平台)
48
+
49
+ `/vnc` 页面内置 noVNC(MIT/MPL 开源),连接本机 VNC 服务端,20–30fps:
50
+
51
+ - 只连本机回环(默认 `127.0.0.1:5900`),必须登录插件页面才能访问
52
+ - 支持密码认证、缩放视口、触摸/键盘/剪贴板(noVNC 自带)
53
+ - 无VNC服务端时页面会提示连接失败,不影响其它功能
54
+ - 配置:`settings.json` 的 `vnc.host` / `vnc.port`
55
+
56
+ 各平台装服务端(一次性):
57
+
58
+ | 平台 | 服务端 | 要点 |
59
+ |---|---|---|
60
+ | Windows | TightVNC / UltraVNC | 设密码;勾选"仅接受本机连接"(Access Control → localhost) |
61
+ | Linux X11 | x11vnc / TigerVNC | `x11vnc -localhost -forever -shared -rfbauth ~/.vnc/passwd` |
62
+ | Linux Wayland | wayvnc | 绑定 127.0.0.1,设密码 |
63
+ | macOS | 系统设置 → 通用 → 共享 → 屏幕共享 | 打开后即监听 5900,可设密码 |
64
+
65
+ ## 窗口共享(手机操作 PC 窗口)
66
+
67
+ `/remote` 页面列出 PC 上所有可见窗口,点一个就共享它的实时画面:
68
+
69
+ - 手机上看该窗口画面(约 2 帧/秒,PrintWindow 抓取,最小化窗口抓不到)
70
+ - 点击 = 在窗口对应位置点击;支持右键、滚轮、回车/退格/Esc/Tab
71
+ - 文字输入支持中文(SendInput Unicode)
72
+ - 换窗口:返回列表重选;适合 WPS 弹窗、安装向导等场景
73
+ - 实现:PowerShell 代理(`lib/window-agent.ps1`)+ 行-JSON 协议,仅本机、需登录
74
+
75
+ > 为什么按窗口而不是整个桌面:手机屏幕小,一次只看一个窗口更清楚;
76
+ > 但要注意 WPS 的"另存为"等对话框是独立窗口,需要回列表重新选择。
77
+
78
+ ## Office / PDF 预览
79
+
80
+ 文件页里点开 `docx / xlsx / pptx / odt / ods / odp / rtf / pdf` 会直接在线预览:
81
+
82
+ - PDF:原样流式返回,浏览器内置阅读器打开
83
+ - Office:用 **DSH 自带的 LibreOffice 引擎**在本机转成 PDF(无需另装 LibreOffice/Office/WPS),
84
+ 同一文件按「路径 + 大小 + 修改时间」缓存,只转一次
85
+ - 首次转换约 2–5 秒;失败时给出下载链接(可用 WPS/Office 打开)
86
+ - 找不到引擎(非常规安装)时可用环境变量 `DSH_HOMING_OFFICE_KIT` 指定
87
+ `@deepseek-ai/libreoffice-kit/lib/index.js` 的路径
88
+
47
89
  ## 远程终端
48
90
 
49
91
  **跨平台自动探测**(插件启动时按当前系统扫描,不需要模型去猜):
package/SECURITY.md ADDED
@@ -0,0 +1,90 @@
1
+ # 安全说明(dsh-homing)
2
+
3
+ 本文件面向使用者和插件市场审核:说明插件的能力、数据流向、凭据处理、网络暴露面、已知限制与漏洞报告方式。
4
+
5
+ ## 1. 漏洞报告
6
+
7
+ - 请通过私有渠道报告(仓库 Issue 中只写"有安全问题,已私信"),附版本号、复现步骤、影响面。
8
+ - 支持的最新版本:见 `package.json` 的 `version`;旧版本只修复高危问题。
9
+ - 我们会在确认后 7 天内给出处理计划。
10
+
11
+ ## 2. 插件做什么
12
+
13
+ 把本机 DSH 通过 **SSH 反向隧道** 安全地开放给手机/微信浏览器访问:
14
+
15
+ - 本机监听一个桥接端口(默认 8787),前面有登录页 + TOTP + 设备白名单
16
+ - 用系统自带 `ssh` 建立反向隧道到用户自己的服务器(TLS 由服务器 nginx 终结)
17
+ - 提供文件、Git、终端、桌面共享(noVNC)、窗口操作等页面
18
+ - 「重启守护进程」:独立 Node 进程监视 DSH,崩溃后自动拉起、支持手动重启
19
+
20
+ ## 3. 能力声明(权限清单)
21
+
22
+ 完整机器可读版本:`permissions.json`。
23
+
24
+ | 能力 | 级别 | 默认 | 说明 |
25
+ |---|---|---|---|
26
+ | `network.inbound_bridge` | 中 | 开启 | 本机监听桥接端口(默认 8787),带登录与设备校验 |
27
+ | `network.tunnel` | 高 | 需用户配置 | 用 ssh 建立反向隧道,把本机服务暴露到用户自己的服务器 |
28
+ | `network.outbound` | 中 | 开启 | 访问用户配置的服务器/SSH 端口;不向第三方上报 |
29
+ | `filesystem.read_write` | 中 | 开启 | 文件页/备份/解压需要;限制在用户可访问范围内 |
30
+ | `process.launch` | 中 | 开启 | 打开文件、启动终端 shell、重启守护进程 |
31
+ | `desktop.control` | 高 | 关闭 | 窗口截图/点击/键盘、VNC 桌面共享;需显式开启 |
32
+ | `credentials.store` | 中 | 开启 | 登录密码哈希、TOTP 密钥、VNC 密码(DPAPI/系统钥匙串加密)、SSH 私钥路径 |
33
+ | `local.socket` | 中 | 开启 | 窗口代理/重启守护进程使用本地套接字 + token |
34
+
35
+ ## 4. 数据流向
36
+
37
+ | 数据 | 流向 | 说明 |
38
+ |---|---|---|
39
+ | 浏览器页面/文件内容 | 手机 ↔ 本机桥接端口(经用户自己的 SSH 隧道与 TLS) | 端到端 TLS;服务器只透传 |
40
+ | 登录密码 | 只在本机校验(scrypt 哈希) | 不落明文、不发送到服务器 |
41
+ | TOTP 密钥 | 本机配置 | 仅在登录时本地校验 |
42
+ | VNC 密码 | 本机 DPAPI 加密存储 | 服务端代认证,**不下发浏览器** |
43
+ | SSH 私钥 | 本机文件 | 仅 ssh 进程读取;插件只传路径 |
44
+ | 审计日志 | 本机 `~/.dsh/integrations/dsh-homing/audit.log` | 不自动上传 |
45
+
46
+ ## 5. 凭据与密钥
47
+
48
+ - 登录密码:scrypt 加盐哈希
49
+ - 会话:HMAC 签名 Cookie,绑定设备;设备可单独吊销
50
+ - VNC 密码:Windows DPAPI(CurrentUser)/ 跨平台加密后写入 settings
51
+ - 本地守护进程 token:`%LOCALAPPDATA%\dsh-homing\agent.token`(仅当前用户可读)
52
+ - 控制端口只监听 `127.0.0.1`;带 Origin 的请求一律拒绝
53
+
54
+ ## 6. 网络暴露面
55
+
56
+ | 端口 | 绑定 | 保护 |
57
+ |---|---|---|
58
+ | 桥接端口(默认 8787) | 可配置本机地址 | 登录 + TOTP + 设备白名单 + 入口令牌 |
59
+ | 重启守护进程(默认 8790) | 127.0.0.1 | 来源进程校验(PID)+ 受管进程树校验 |
60
+ | VNC(默认 5900) | 127.0.0.1 | 服务端代认证;仅本机可连 |
61
+ | SSH 隧道 | 出站 | 仅用户配置的服务器 |
62
+
63
+ ## 7. 已知限制
64
+
65
+ - **管理员权限窗口**(UAC 提升)不可操作:Windows UIPI 限制,属于系统安全设计
66
+ - **锁屏 / UAC 安全桌面**不可操作
67
+ - **RDP/多会话**:只能操作当前会话的桌面
68
+ - **同用户恶意程序**:可读 token、可注入进程,超出插件防护范围(系统级信任边界)
69
+ - 受保护进程(DRM/反作弊)可能无法截图
70
+
71
+ ## 8. 安全默认值
72
+
73
+ - 桌面共享(VNC)与窗口控制默认关闭,需显式开启
74
+ - 入口需要登录 + TOTP(可配置)
75
+ - 失败登录有退避与限流;关键操作写审计
76
+ - 所有外部命令使用系统绝对路径,防 PATH 劫持
77
+
78
+ ## 9. 发布与供应链
79
+
80
+ - 发布包只含源码与纯 JS 依赖(noVNC、ws),无原生二进制
81
+ - 依赖锁定版本;发布前跑全量测试
82
+ - 建议发布时附构建产物哈希与 npm provenance 签名
83
+
84
+ ## 10. 加固建议(部署方)
85
+
86
+ 1. 使用强密码并开启 TOTP
87
+ 2. 设备丢失时在账户页吊销该设备
88
+ 3. 服务器侧只允许必要的来源 IP / 端口
89
+ 4. 不把桥接端口直接暴露到公网(应只经 SSH 隧道)
90
+ 5. 定期查看审计日志与设备列表
package/bin/backup.mjs CHANGED
@@ -11,6 +11,7 @@
11
11
  * 备份里含私钥和 CA 私钥,别放到公共位置。
12
12
  */
13
13
  import fs from 'node:fs';
14
+ import { opensslExe, tarExe } from '../lib/exec-path.mjs'
14
15
  import os from 'node:os';
15
16
  import path from 'node:path';
16
17
  import { spawnSync } from 'node:child_process';
@@ -68,9 +69,9 @@ function backup() {
68
69
  // 可选加密包
69
70
  const password = process.env.DSH_HOMING_BACKUP_PASS;
70
71
  if (password) {
71
- const openssl = process.platform === 'win32' ? 'openssl.exe' : 'openssl';
72
+ const openssl = opensslExe();
72
73
  const archive = `${target}.enc.tgz`;
73
- const tar = spawnSync('tar', ['-czf', '-', '-C', target, '.'], { maxBuffer: 64 * 1024 * 1024 });
74
+ const tar = spawnSync(tarExe(), ['-czf', '-', '-C', target, '.'], { maxBuffer: 64 * 1024 * 1024 });
74
75
  if (tar.status === 0) {
75
76
  const enc = spawnSync(openssl, ['enc', '-aes-256-cbc', '-pbkdf2', '-salt', '-pass', 'env:DSH_HOMING_BACKUP_PASS'], {
76
77
  input: tar.stdout,
@@ -17,6 +17,7 @@
17
17
  * --email you@example.com Let's Encrypt 通知邮箱(可省)
18
18
  */
19
19
  import fs from 'node:fs';
20
+ import { sshExe } from '../lib/exec-path.mjs'
20
21
  import os from 'node:os';
21
22
  import path from 'node:path';
22
23
  import net from 'node:net';
@@ -63,7 +64,7 @@ const passthrough = args.passthrough === true;
63
64
  /** 跨平台找 ssh 可执行文件。 */
64
65
  function findSsh() {
65
66
  const candidates = process.platform === 'win32'
66
- ? [path.join(process.env.WINDIR ?? 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe'), 'ssh.exe', 'ssh']
67
+ ? [path.join(process.env.WINDIR ?? 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe'), sshExe()]
67
68
  : ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh', 'ssh'];
68
69
  for (const candidate of candidates) {
69
70
  if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
package/bin/inbox.mjs ADDED
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 调试收件箱的命令行工具(给会话侧使用)。
4
+ *
5
+ * node bin/inbox.mjs list 列出消息(默认只列等待回复的)
6
+ * node bin/inbox.mjs list --all 列出全部
7
+ * node bin/inbox.mjs reply <id> <文本>
8
+ * node bin/inbox.mjs read <id> 显示单条
9
+ *
10
+ * 数据位置:<DSH_HOME>/integrations/dsh-homing/debug-inbox/messages.json
11
+ */
12
+ import fs from 'node:fs'
13
+ import os from 'node:os'
14
+ import path from 'node:path'
15
+
16
+ const dshHome = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
17
+ const file = path.join(dshHome, 'integrations', 'dsh-homing', 'debug-inbox', 'messages.json')
18
+ const read = () => { try { const v = JSON.parse(fs.readFileSync(file, 'utf8')); return Array.isArray(v) ? v : [] } catch { return [] } }
19
+ const write = (v) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(v, null, 2), 'utf8') }
20
+
21
+ const args = process.argv.slice(2)
22
+ const command = args[0] ?? 'list'
23
+
24
+ if (command === 'list') {
25
+ const all = read()
26
+ const rows = args.includes('--all') ? all : all.filter((m) => !m.reply)
27
+ if (rows.length === 0) { console.log('没有待处理消息。'); process.exit(0) }
28
+ for (const m of rows) {
29
+ console.log(`[${m.id}] ${m.at} 会话=${m.sessionTitle || m.sessionId || '-'} 图片=${m.images?.length ?? 0}`)
30
+ console.log(' ' + String(m.text || '').replaceAll('\n', '\n '))
31
+ }
32
+ } else if (command === 'read') {
33
+ const m = read().find((x) => x.id === args[1])
34
+ if (!m) { console.log('找不到消息:', args[1]); process.exit(1) }
35
+ console.log(JSON.stringify(m, null, 2))
36
+ } else if (command === 'reply') {
37
+ const all = read()
38
+ const m = all.find((x) => x.id === args[1])
39
+ if (!m) { console.log('找不到消息:', args[1]); process.exit(1) }
40
+ m.reply = args.slice(2).join(' ') || '(空回复)'
41
+ m.repliedAt = new Date().toISOString().replace('T', ' ').slice(0, 19)
42
+ write(all)
43
+ console.log('已回复', m.id)
44
+ } else {
45
+ console.log('用法: node bin/inbox.mjs list [--all] | read <id> | reply <id> <文本>')
46
+ }
@@ -10,6 +10,7 @@
10
10
  * 用 CSR 模式可以把私钥永远留在本机,服务器上不存任何私钥。
11
11
  */
12
12
  import fs from 'node:fs';
13
+ import { sshExe } from '../lib/exec-path.mjs'
13
14
  import os from 'node:os';
14
15
  import path from 'node:path';
15
16
  import { spawn, spawnSync } from 'node:child_process';
@@ -88,7 +89,7 @@ sudo rm -f /tmp/dsh-renew.csr /tmp/dsh-renew.crt /tmp/dsh-renew.chain /tmp/dsh-r
88
89
  `;
89
90
 
90
91
  console.log('==> 请服务器走 ACME 签发');
91
- const child = spawn('ssh', [
92
+ const child = spawn(sshExe(), [
92
93
  '-i', sshKey,
93
94
  '-p', String(sshPort),
94
95
  '-o', 'BatchMode=yes',
@@ -0,0 +1,268 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 窗口代理守护进程(Node 实现)。
4
+ *
5
+ * 对外:本地套接字(Windows 命名管道 / POSIX UDS),行 JSON 请求。
6
+ * 对内:
7
+ * - Windows 的窗口操作(list/capture/click/key/...)代理给常驻的
8
+ * PowerShell 工作进程(window-agent.ps1 的 stdio 模式)执行;
9
+ * - 转屏按平台分派:Windows 走工作进程(ChangeDisplaySettingsEx),
10
+ * Linux 走 xrandr,macOS 走 displayplacer。
11
+ *
12
+ * 单实例由套接字名独占保证;空闲超时自动退出;请求带 token。
13
+ */
14
+ import { execFile, spawn } from 'node:child_process'
15
+ import fs from 'node:fs'
16
+ import net from 'node:net'
17
+ import path from 'node:path'
18
+ import readline from 'node:readline'
19
+ import { fileURLToPath } from 'node:url'
20
+
21
+ import { agentDir, loadOrCreateToken, removeStaleSocket, socketName, socketPath } from '../lib/local-socket.mjs'
22
+ import { powershellExe } from '../lib/exec-path.mjs'
23
+ import { createLogWriter } from '../lib/log-file.mjs'
24
+
25
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
26
+ const WORKER = path.join(HERE, '..', 'lib', 'window-agent.ps1')
27
+
28
+ const NAME = process.env.DSH_AGENT_PIPE || socketName()
29
+ const SOCKET = socketPath(NAME)
30
+ const TOKEN = process.env.DSH_AGENT_TOKEN || loadOrCreateToken()
31
+ const IDLE_SECONDS = Math.max(10, Number(process.env.DSH_AGENT_IDLE_SECONDS) || 300)
32
+ const LOG_FILE = path.join(agentDir(), 'window-agent.log')
33
+
34
+ const writeLogLine = createLogWriter(LOG_FILE)
35
+
36
+ function log(message) {
37
+ writeLogLine(`${new Date().toISOString()} [node-daemon] ${message}\n`)
38
+ }
39
+
40
+ const isWindows = process.platform === 'win32'
41
+
42
+ // ---------------- PowerShell 工作进程(仅 Windows) ----------------
43
+
44
+ let worker = null
45
+ let workerReader = null
46
+ let workerSeq = 0
47
+ const workerPending = new Map()
48
+
49
+ function ensureWorker() {
50
+ if (!isWindows) throw new Error('窗口操作仅支持 Windows')
51
+ if (worker !== null && worker.exitCode === null) return worker
52
+ const child = spawn(powershellExe(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', WORKER], {
53
+ windowsHide: true,
54
+ stdio: ['pipe', 'pipe', 'pipe'],
55
+ // stdio 工作进程只被守护进程使用,不需要 token(避免二次鉴权)
56
+ env: { ...process.env, DSH_AGENT_TOKEN: '' },
57
+ })
58
+ child.stderr.on('data', () => { /* 工作进程 stderr 忽略 */ })
59
+ workerReader = readline.createInterface({ input: child.stdout })
60
+ workerReader.on('line', (line) => {
61
+ const text = line.trim()
62
+ if (!text.startsWith('{')) return
63
+ let message = null
64
+ try { message = JSON.parse(text) } catch { return }
65
+ const resolve = workerPending.get(message.id)
66
+ if (resolve === undefined) return
67
+ workerPending.delete(message.id)
68
+ resolve(message)
69
+ })
70
+ const failPending = () => {
71
+ for (const [, resolve] of workerPending) resolve({ ok: false, error: '窗口工作进程已退出' })
72
+ workerPending.clear()
73
+ worker = null
74
+ }
75
+ child.on('exit', () => { log('worker exit'); failPending() })
76
+ child.on('error', () => { log('worker error'); failPending() })
77
+ worker = child
78
+ return child
79
+ }
80
+
81
+ function workerCall(request, timeoutMs = 20_000) {
82
+ const child = ensureWorker()
83
+ const id = String(++workerSeq)
84
+ return new Promise((resolve) => {
85
+ const timer = setTimeout(() => {
86
+ workerPending.delete(id)
87
+ resolve({ ok: false, error: 'timeout' })
88
+ }, timeoutMs)
89
+ workerPending.set(id, (message) => {
90
+ clearTimeout(timer)
91
+ resolve(message)
92
+ })
93
+ try {
94
+ child.stdin.write(JSON.stringify({ id, ...request }) + '\n')
95
+ } catch (error) {
96
+ clearTimeout(timer)
97
+ workerPending.delete(id)
98
+ resolve({ ok: false, error: String(error?.message ?? error) })
99
+ }
100
+ })
101
+ }
102
+
103
+ // ---------------- 转屏(跨平台分派) ----------------
104
+
105
+ const run = (command, args, timeoutMs = 20_000) => new Promise((resolve) => {
106
+ execFile(command, args, { windowsHide: true, timeout: timeoutMs }, (error, stdout, stderr) => {
107
+ resolve({ error, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })
108
+ })
109
+ })
110
+
111
+ async function linuxPrimaryOutput() {
112
+ const { stdout, error } = await run('xrandr', ['--query'])
113
+ if (error) return null
114
+ const lines = stdout.split('\n')
115
+ const line = lines.find((item) => /\bconnected\s+primary\b/u.test(item))
116
+ ?? lines.find((item) => /\bconnected\b/u.test(item))
117
+ if (!line) return null
118
+ return line.split(/\s+/u)[0] ?? null
119
+ }
120
+
121
+ async function linuxScreenSize() {
122
+ const { stdout } = await run('xrandr', ['--query'])
123
+ const line = stdout.split('\n').find((item) => /\bconnected\s+primary\b/u.test(item))
124
+ ?? stdout.split('\n').find((item) => /\bconnected\b/u.test(item))
125
+ const match = line?.match(/(\d+)x(\d+)\+/u)
126
+ if (!match) return { width: 0, height: 0 }
127
+ return { width: Number(match[1]), height: Number(match[2]) }
128
+ }
129
+
130
+ async function rotatePlatform(mode) {
131
+ const portrait = mode === 'portrait'
132
+ if (isWindows) {
133
+ const result = await workerCall({ cmd: 'rotate', mode: portrait ? 'portrait' : 'landscape' })
134
+ return {
135
+ ok: result.ok === true,
136
+ result: result.result ?? null,
137
+ screen: { width: Number(result.screenWidth) || 0, height: Number(result.screenHeight) || 0 },
138
+ detail: `windows result=${result.result ?? '?'}`,
139
+ }
140
+ }
141
+ if (process.platform === 'linux') {
142
+ const output = await linuxPrimaryOutput()
143
+ if (output === null) return { ok: false, detail: 'no connected output (xrandr)' }
144
+ const { error } = await run('xrandr', ['--output', output, '--rotate', portrait ? 'left' : 'normal'])
145
+ if (error) return { ok: false, detail: String(error.message ?? error).slice(0, 200) }
146
+ return { ok: true, result: 0, screen: await linuxScreenSize(), detail: `${output} -> ${portrait ? 'left' : 'normal'}` }
147
+ }
148
+ if (process.platform === 'darwin') {
149
+ const list = await run('displayplacer', ['list'])
150
+ if (list.error) return { ok: false, detail: 'displayplacer not installed' }
151
+ const idMatch = list.stdout.match(/Persistent screen id:\s*(\S+)/u)
152
+ if (!idMatch) return { ok: false, detail: 'screen id not found' }
153
+ const rotation = portrait ? 'rotation:90' : 'rotation:0'
154
+ const applied = await run('displayplacer', [`id:${idMatch[1]}`, rotation, 'scaling:on'])
155
+ if (applied.error) return { ok: false, detail: String(applied.error.message ?? applied.error).slice(0, 200) }
156
+ return { ok: true, result: 0, detail: `${idMatch[1]} -> ${rotation}` }
157
+ }
158
+ return { ok: false, detail: 'unsupported platform' }
159
+ }
160
+
161
+ // ---------------- 请求处理 ----------------
162
+
163
+ let queue = Promise.resolve()
164
+
165
+ async function handle(request) {
166
+ const cmd = String(request.cmd ?? '')
167
+ if (cmd === 'ping') return { ok: true, pong: true }
168
+ if (cmd === 'version') {
169
+ return { ok: true, version: '2', platform: process.platform, pid: process.pid, pipe: NAME }
170
+ }
171
+ if (cmd === 'shutdown') {
172
+ setTimeout(() => process.exit(0), 50)
173
+ return { ok: true, shutdown: true }
174
+ }
175
+ if (cmd === 'rotate') {
176
+ const mode = request.mode === 'landscape' ? 'landscape' : 'portrait'
177
+ return rotatePlatform(mode)
178
+ }
179
+ // 其余窗口操作:Windows 交给工作进程
180
+ if (!isWindows) return { ok: false, error: '窗口操作仅支持 Windows' }
181
+ const { id: _ignoredId, token: _ignoredToken, ...payload } = request
182
+ return workerCall(payload, 25_000)
183
+ }
184
+
185
+ const server = net.createServer((socket) => {
186
+ let buffer = ''
187
+ socket.setEncoding('utf8')
188
+ socket.on('data', (chunk) => {
189
+ buffer += chunk
190
+ while (true) {
191
+ const index = buffer.indexOf('\n')
192
+ if (index < 0) break
193
+ const line = buffer.slice(0, index).trim()
194
+ buffer = buffer.slice(index + 1)
195
+ if (line === '') continue
196
+ let request = null
197
+ try { request = JSON.parse(line) } catch {
198
+ socket.write(JSON.stringify({ ok: false, error: 'bad json' }) + '\n')
199
+ continue
200
+ }
201
+ if (String(request.token ?? '') !== TOKEN) {
202
+ socket.write(JSON.stringify({ id: request.id, ok: false, error: 'unauthorized' }) + '\n')
203
+ continue
204
+ }
205
+ const id = request.id
206
+ queue = queue.then(async () => {
207
+ let result
208
+ try {
209
+ result = await handle(request)
210
+ } catch (error) {
211
+ result = { ok: false, error: String(error?.message ?? error) }
212
+ }
213
+ try { socket.write(JSON.stringify({ id, ...result }) + '\n') } catch { /* 已断开 */ }
214
+ })
215
+ }
216
+ })
217
+ socket.on('error', () => { /* 忽略 */ })
218
+ })
219
+
220
+ function start() {
221
+ removeStaleSocket(SOCKET)
222
+ server.once('error', (error) => {
223
+ if (error.code === 'EADDRINUSE') {
224
+ log('socket busy, another daemon is running')
225
+ process.exit(3)
226
+ }
227
+ log('listen error: ' + String(error.message ?? error))
228
+ process.exit(1)
229
+ })
230
+ server.listen(SOCKET, () => {
231
+ log(`listen ${SOCKET} pid=${process.pid}`)
232
+ })
233
+ }
234
+
235
+ // 空闲退出:没有活动连接时计时
236
+ let idleTimer = null
237
+ let clients = 0
238
+
239
+ function armIdle() {
240
+ if (clients > 0) return
241
+ if (idleTimer !== null) clearTimeout(idleTimer)
242
+ idleTimer = setTimeout(() => {
243
+ log('idle exit')
244
+ try { worker?.kill() } catch { /* 忽略 */ }
245
+ try { server.close() } catch { /* 忽略 */ }
246
+ process.exit(0)
247
+ }, IDLE_SECONDS * 1000)
248
+ idleTimer.unref?.()
249
+ }
250
+
251
+ server.on('connection', (socket) => {
252
+ clients += 1
253
+ if (idleTimer !== null) {
254
+ clearTimeout(idleTimer)
255
+ idleTimer = null
256
+ }
257
+ socket.on('close', () => {
258
+ clients -= 1
259
+ armIdle()
260
+ })
261
+ })
262
+
263
+ process.on('exit', () => {
264
+ try { worker?.kill() } catch { /* 忽略 */ }
265
+ removeStaleSocket(SOCKET)
266
+ })
267
+
268
+ start()