@andy.ian/dsh-homing 2.1.4 → 2.1.5

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 (120) 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/renew-cert.mjs +2 -1
  6. package/index.js +686 -87
  7. package/lib/compress.mjs +29 -5
  8. package/lib/exec-path.mjs +85 -0
  9. package/lib/files-page.mjs +27 -2
  10. package/lib/files.mjs +3 -2
  11. package/lib/git.mjs +5 -2
  12. package/lib/guard.mjs +43 -0
  13. package/lib/local-socket.mjs +50 -0
  14. package/lib/log-file.mjs +50 -0
  15. package/lib/node-runtime.mjs +44 -0
  16. package/lib/office.mjs +133 -0
  17. package/lib/orientation.mjs +158 -0
  18. package/lib/pty.mjs +6 -3
  19. package/lib/secret.mjs +46 -0
  20. package/lib/shells.mjs +2 -1
  21. package/lib/term-page.mjs +2 -0
  22. package/lib/vendor/des-vnc.mjs +266 -0
  23. package/lib/vendor/novnc/LICENSE.txt +62 -0
  24. package/lib/vendor/novnc/core/base64.js +104 -0
  25. package/lib/vendor/novnc/core/crypto/aes.js +178 -0
  26. package/lib/vendor/novnc/core/crypto/bigint.js +34 -0
  27. package/lib/vendor/novnc/core/crypto/crypto.js +90 -0
  28. package/lib/vendor/novnc/core/crypto/des.js +330 -0
  29. package/lib/vendor/novnc/core/crypto/dh.js +55 -0
  30. package/lib/vendor/novnc/core/crypto/md5.js +82 -0
  31. package/lib/vendor/novnc/core/crypto/rsa.js +132 -0
  32. package/lib/vendor/novnc/core/decoders/copyrect.js +27 -0
  33. package/lib/vendor/novnc/core/decoders/h264.js +321 -0
  34. package/lib/vendor/novnc/core/decoders/hextile.js +181 -0
  35. package/lib/vendor/novnc/core/decoders/jpeg.js +161 -0
  36. package/lib/vendor/novnc/core/decoders/raw.js +59 -0
  37. package/lib/vendor/novnc/core/decoders/rre.js +44 -0
  38. package/lib/vendor/novnc/core/decoders/tight.js +393 -0
  39. package/lib/vendor/novnc/core/decoders/tightpng.js +27 -0
  40. package/lib/vendor/novnc/core/decoders/zlib.js +51 -0
  41. package/lib/vendor/novnc/core/decoders/zrle.js +185 -0
  42. package/lib/vendor/novnc/core/deflator.js +84 -0
  43. package/lib/vendor/novnc/core/display.js +578 -0
  44. package/lib/vendor/novnc/core/encodings.js +54 -0
  45. package/lib/vendor/novnc/core/inflator.js +65 -0
  46. package/lib/vendor/novnc/core/input/domkeytable.js +311 -0
  47. package/lib/vendor/novnc/core/input/fixedkeys.js +129 -0
  48. package/lib/vendor/novnc/core/input/gesturehandler.js +567 -0
  49. package/lib/vendor/novnc/core/input/keyboard.js +294 -0
  50. package/lib/vendor/novnc/core/input/keysym.js +616 -0
  51. package/lib/vendor/novnc/core/input/keysymdef.js +688 -0
  52. package/lib/vendor/novnc/core/input/util.js +191 -0
  53. package/lib/vendor/novnc/core/input/vkeys.js +116 -0
  54. package/lib/vendor/novnc/core/input/xtscancodes.js +173 -0
  55. package/lib/vendor/novnc/core/ra2.js +312 -0
  56. package/lib/vendor/novnc/core/rfb.js +3420 -0
  57. package/lib/vendor/novnc/core/util/browser.js +233 -0
  58. package/lib/vendor/novnc/core/util/cursor.js +249 -0
  59. package/lib/vendor/novnc/core/util/element.js +32 -0
  60. package/lib/vendor/novnc/core/util/events.js +138 -0
  61. package/lib/vendor/novnc/core/util/eventtarget.js +35 -0
  62. package/lib/vendor/novnc/core/util/int.js +15 -0
  63. package/lib/vendor/novnc/core/util/logging.js +56 -0
  64. package/lib/vendor/novnc/core/util/strings.js +28 -0
  65. package/lib/vendor/novnc/core/websock.js +369 -0
  66. package/lib/vendor/novnc/vendor/pako/LICENSE +21 -0
  67. package/lib/vendor/novnc/vendor/pako/README.md +6 -0
  68. package/lib/vendor/novnc/vendor/pako/lib/utils/common.js +45 -0
  69. package/lib/vendor/novnc/vendor/pako/lib/zlib/adler32.js +27 -0
  70. package/lib/vendor/novnc/vendor/pako/lib/zlib/constants.js +47 -0
  71. package/lib/vendor/novnc/vendor/pako/lib/zlib/crc32.js +36 -0
  72. package/lib/vendor/novnc/vendor/pako/lib/zlib/deflate.js +1846 -0
  73. package/lib/vendor/novnc/vendor/pako/lib/zlib/gzheader.js +35 -0
  74. package/lib/vendor/novnc/vendor/pako/lib/zlib/inffast.js +324 -0
  75. package/lib/vendor/novnc/vendor/pako/lib/zlib/inflate.js +1527 -0
  76. package/lib/vendor/novnc/vendor/pako/lib/zlib/inftrees.js +322 -0
  77. package/lib/vendor/novnc/vendor/pako/lib/zlib/messages.js +11 -0
  78. package/lib/vendor/novnc/vendor/pako/lib/zlib/trees.js +1195 -0
  79. package/lib/vendor/novnc/vendor/pako/lib/zlib/zstream.js +24 -0
  80. package/lib/vendor/vnc.bundle.js +14592 -0
  81. package/lib/vendor/ws/LICENSE +20 -0
  82. package/lib/vendor/ws/index.js +22 -0
  83. package/lib/vendor/ws/lib/buffer-util.js +142 -0
  84. package/lib/vendor/ws/lib/constants.js +19 -0
  85. package/lib/vendor/ws/lib/event-target.js +292 -0
  86. package/lib/vendor/ws/lib/extension.js +203 -0
  87. package/lib/vendor/ws/lib/limiter.js +55 -0
  88. package/lib/vendor/ws/lib/permessage-deflate.js +530 -0
  89. package/lib/vendor/ws/lib/receiver.js +743 -0
  90. package/lib/vendor/ws/lib/sender.js +610 -0
  91. package/lib/vendor/ws/lib/stream.js +161 -0
  92. package/lib/vendor/ws/lib/subprotocol.js +62 -0
  93. package/lib/vendor/ws/lib/validation.js +152 -0
  94. package/lib/vendor/ws/lib/websocket-server.js +562 -0
  95. package/lib/vendor/ws/lib/websocket.js +1426 -0
  96. package/lib/vendor/ws/package.json +74 -0
  97. package/lib/vendor/ws/wrapper.mjs +21 -0
  98. package/lib/vnc-app.js +567 -0
  99. package/lib/vnc-auth-proxy.mjs +179 -0
  100. package/lib/vnc-boot.js +45 -0
  101. package/lib/vnc-page.mjs +77 -0
  102. package/lib/vnc-pointer.mjs +17 -0
  103. package/lib/vnc.mjs +75 -0
  104. package/lib/window-app.js +155 -0
  105. package/lib/window-page.mjs +111 -0
  106. package/lib/window-remote.mjs +226 -0
  107. package/lib/ws-bridge.mjs +130 -0
  108. package/package.json +4 -2
  109. package/permissions.json +91 -0
  110. package/restart/client.mjs +85 -19
  111. package/restart/daemon/cli.mjs +55 -13
  112. package/restart/daemon/lib/detach.mjs +3 -2
  113. package/restart/daemon/lib/process-tree.mjs +17 -3
  114. package/restart/daemon/lib/restart-flow.mjs +36 -0
  115. package/restart/daemon/main.mjs +299 -80
  116. package/restart/engine.mjs +24 -8
  117. package/restart/port.mjs +88 -0
  118. package/restart/runner.mjs +4 -3
  119. package/restart/service.mjs +8 -5
  120. package/restart/watchdog.mjs +134 -0
package/lib/compress.mjs CHANGED
@@ -48,10 +48,32 @@ const TOOL_DIRS = () => {
48
48
  ].filter(Boolean)
49
49
  }
50
50
 
51
- const which = (name) => {
52
- const probe = spawnSync(name, ['--help'], { encoding: 'utf8', windowsHide: true, timeout: 8000 })
53
- // 有的工具 --help 返回非 0,但只要能执行起来(不是 ENOENT)就算找到
54
- return probe.error ? null : name
51
+ // 在 PATH 目录里"查找文件",而不是执行它 —— 避免探测命令本身被 PATH 劫持
52
+ function findOnPath(name) {
53
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat'] : ['']
54
+ const dirs = String(process.env.PATH ?? '').split(path.delimiter).filter(Boolean)
55
+ for (const dir of dirs) {
56
+ for (const ext of exts) {
57
+ const full = path.join(dir, name + ext)
58
+ try {
59
+ if (fs.statSync(full).isFile()) return full
60
+ } catch { /* 不存在 */ }
61
+ }
62
+ }
63
+ return null
64
+ }
65
+
66
+ // 常见安装目录:优先于 PATH
67
+ function extraToolDirs() {
68
+ if (process.platform !== 'win32') return ['/usr/bin', '/usr/local/bin', '/opt/homebrew/bin']
69
+ const programFiles = process.env.ProgramFiles ?? 'C:\\Program Files'
70
+ const programFilesX86 = process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)'
71
+ return [
72
+ path.join(programFiles, '7-Zip'),
73
+ path.join(programFilesX86, '7-Zip'),
74
+ path.join(programFiles, 'WinRAR'),
75
+ path.join(programFiles, 'NanaZip'),
76
+ ]
55
77
  }
56
78
 
57
79
  /** 在指定目录里找可执行文件(Windows 补 .exe) */
@@ -80,7 +102,9 @@ export function availableBackends() {
80
102
  for (const name of backend.bins) {
81
103
  const local = findInDirs(dirs, name)
82
104
  if (local) binaries.push(local)
83
- const onPath = which(name)
105
+ const extra = findInDirs(extraToolDirs(), name)
106
+ if (extra) binaries.push(extra)
107
+ const onPath = findOnPath(name)
84
108
  if (onPath) binaries.push(onPath)
85
109
  }
86
110
  const unique = [...new Set(binaries)]
@@ -0,0 +1,85 @@
1
+ /**
2
+ * 外部命令解析:优先使用系统目录的绝对路径,避免 PATH 劫持。
3
+ *
4
+ * 背景:守护进程/插件会 spawn 系统工具(netstat/tasklist/taskkill/reg/ps/ssh...)。
5
+ * 如果按名字调用,Windows 会先搜索"当前目录、应用目录、PATH",攻击者只要
6
+ * 在可写目录放一个同名 exe,就能劫持。
7
+ *
8
+ * 策略:优先绝对路径;找不到再回退为原名(保持功能可用),
9
+ * 但所有安全敏感调用点都应使用这里的解析结果。
10
+ */
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+
14
+ const SYSTEM_ROOT = process.env.SystemRoot ?? process.env.WINDIR ?? 'C:\\Windows'
15
+
16
+ function firstExisting(candidates, fallback) {
17
+ for (const candidate of candidates) {
18
+ try {
19
+ if (fs.statSync(candidate).isFile()) return candidate
20
+ } catch { /* 继续尝试 */ }
21
+ }
22
+ return fallback
23
+ }
24
+
25
+ /** Windows 用 System32;POSIX 用标准 bin 目录 */
26
+ export function systemExe(name) {
27
+ if (process.platform === 'win32') {
28
+ return firstExisting([
29
+ path.join(SYSTEM_ROOT, 'System32', name + '.exe'),
30
+ path.join(SYSTEM_ROOT, 'System32', name),
31
+ ], name)
32
+ }
33
+ return firstExisting([
34
+ '/usr/bin/' + name,
35
+ '/bin/' + name,
36
+ '/usr/sbin/' + name,
37
+ '/sbin/' + name,
38
+ '/usr/local/bin/' + name,
39
+ ], name)
40
+ }
41
+
42
+ export function powershellExe() {
43
+ if (process.platform !== 'win32') return systemExe('pwsh')
44
+ return firstExisting([
45
+ path.join(SYSTEM_ROOT, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
46
+ path.join(SYSTEM_ROOT, 'System32', 'powershell.exe'),
47
+ ], 'powershell.exe')
48
+ }
49
+
50
+ /** OpenSSH 客户端:System32\OpenSSH 优先 */
51
+ export function sshExe() {
52
+ if (process.platform !== 'win32') return systemExe('ssh')
53
+ return firstExisting([
54
+ path.join(SYSTEM_ROOT, 'System32', 'OpenSSH', 'ssh.exe'),
55
+ path.join(SYSTEM_ROOT, 'System32', 'ssh.exe'),
56
+ ], 'ssh')
57
+ }
58
+
59
+ /** OpenSSL:尽量用 Git 自带或系统目录,最后才回退 PATH */
60
+ export function opensslExe() {
61
+ if (process.platform !== 'win32') return systemExe('openssl')
62
+ const programFiles = process.env.ProgramFiles ?? 'C:\\Program Files'
63
+ return firstExisting([
64
+ path.join(programFiles, 'Git', 'usr', 'bin', 'openssl.exe'),
65
+ path.join(programFiles, 'Git', 'mingw64', 'bin', 'openssl.exe'),
66
+ path.join(SYSTEM_ROOT, 'System32', 'openssl.exe'),
67
+ ], 'openssl.exe')
68
+ }
69
+
70
+ /** tar:Windows 10+ 自带 bsdtar,位于 System32 */
71
+ export function tarExe() {
72
+ if (process.platform !== 'win32') return systemExe('tar')
73
+ return firstExisting([path.join(SYSTEM_ROOT, 'System32', 'tar.exe')], 'tar')
74
+ }
75
+
76
+ /** git:常见安装位置优先,最后回退 PATH */
77
+ export function gitExe() {
78
+ if (process.platform !== 'win32') return systemExe('git')
79
+ const programFiles = process.env.ProgramFiles ?? 'C:\\Program Files'
80
+ return firstExisting([
81
+ path.join(programFiles, 'Git', 'cmd', 'git.exe'),
82
+ path.join(programFiles, 'Git', 'bin', 'git.exe'),
83
+ path.join(process.env.LOCALAPPDATA ?? '', 'Programs', 'Git', 'cmd', 'git.exe'),
84
+ ], 'git')
85
+ }
@@ -125,6 +125,21 @@ const MENU_JS = `<script>
125
125
  location.href = '/files/compress?path=' + encodeURIComponent(path);
126
126
  return;
127
127
  }
128
+ if (kind === 'preview') {
129
+ location.href = '/files/pdf?path=' + encodeURIComponent(path);
130
+ return;
131
+ }
132
+ if (kind === 'openpc') {
133
+ fetch('/remote/input', {
134
+ method: 'POST',
135
+ headers: { 'content-type': 'application/json' },
136
+ body: JSON.stringify({ kind: 'open', path: path }),
137
+ }).then(function (res) { return res.json() }).then(function (data) {
138
+ if (!data.ok) { alert('打开失败:' + (data.error || '未知原因')); return }
139
+ if (data.hwnd) location.href = '/vnc?focus=' + encodeURIComponent(data.hwnd)
140
+ }).catch(function (error) { alert('打开失败:' + error.message) })
141
+ return;
142
+ }
128
143
  if (kind === 'copy' || kind === 'cut') {
129
144
  try { localStorage.setItem('dsh-files-clip', JSON.stringify({ path: path, op: kind === 'cut' ? 'cut' : 'copy' })); } catch (error) { /* 忽略 */ }
130
145
  return;
@@ -220,12 +235,17 @@ const MENU_JS = `<script>
220
235
  })();
221
236
  </script>`;
222
237
 
238
+ const TEXT_FILE_RE = /\.(txt|md|markdown|json|jsonc|js|mjs|cjs|ts|tsx|jsx|css|scss|less|html|htm|xml|yml|yaml|toml|ini|conf|cfg|log|csv|tsv|sh|bash|ps1|bat|cmd|py|rb|go|rs|java|c|h|cpp|hpp|cs|php|sql|env)$/iu
239
+
240
+ /** 文件页渲染 */
223
241
  export function renderListing({ info, message, isError, home, dataDir, workspaces = [] }) {
224
242
  const menuFor = (entry) => `<span class="mm">
225
243
  <button type="button" class="mm-btn" aria-haspopup="menu" title="更多操作">\u22ef</button>
226
244
  <span class="rowmenu" hidden role="menu">
227
- ${entry.dir ? '' : `<a class="mi" role="menuitem" data-act="edit" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u270F\uFE0F</span>编辑</a>`}
245
+ ${entry.dir || !TEXT_FILE_RE.test(entry.name) ? '' : `<a class="mi" role="menuitem" data-act="edit" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u270F\uFE0F</span>编辑</a>`}
246
+ ${entry.dir ? '' : `<a class="mi" role="menuitem" data-act="openpc" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F5A5}\uFE0F</span>在电脑打开</a>`}
228
247
  ${entry.dir ? '' : `<a class="mi" role="menuitem" data-act="download" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u2B07\uFE0F</span>下载</a>`}
248
+ ${/\\.(docx?|xlsx?|pptx?|odt|ods|odp|rtf|pdf)$/iu.test(entry.name) ? `<a class="mi" role="menuitem" data-act="preview" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F441}\uFE0F</span>预览</a>` : ''}
229
249
  <a class="mi" role="menuitem" data-act="compress" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F512}</span>加密压缩</a>
230
250
  ${entry.runnable ? `<a class="mi" role="menuitem" data-act="run" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u25B6\uFE0F</span>执行</a>` : ''}
231
251
  <a class="mi" role="menuitem" data-act="rename" data-path="${escapeHtml(entry.path)}" data-name="${escapeHtml(entry.name)}" href="#"><span class="ico">\u{1F3F7}\uFE0F</span>重命名</a>
@@ -242,9 +262,12 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
242
262
  const rows = info.entries.map((entry) => {
243
263
  const label = escapeHtml(entry.name);
244
264
  const icon = entry.dir ? '\u{1F4C1}' : (entry.runnable ? '\u2699\uFE0F' : '\u{1F4C4}');
265
+ const previewable = /\\.(docx?|xlsx?|pptx?|odt|ods|odp|rtf|pdf)$/iu.test(entry.name)
245
266
  const nameHtml = entry.dir
246
267
  ? `<a class="fname dir" href="/files?path=${encodeURIComponent(entry.path)}">${label}</a>`
247
- : `<a class="fname${entry.runnable ? ' exe' : ''}" href="/files/view?path=${encodeURIComponent(entry.path)}">${label}</a>`;
268
+ : previewable
269
+ ? `<a class="fname${entry.runnable ? ' exe' : ''}" href="/files/pdf?path=${encodeURIComponent(entry.path)}">${label}</a>`
270
+ : `<a class="fname${entry.runnable ? ' exe' : ''}" href="/files/view?path=${encodeURIComponent(entry.path)}">${label}</a>`;
248
271
  return `<div class="fitem" data-path="${escapeHtml(entry.path)}" data-name="${escapeHtml(entry.name)}" data-dir="${entry.dir ? 1 : 0}" data-size="${Number(entry.size) || 0}" data-time="${Number(entry.mtimeMs) || 0}">
249
272
  <div class="fico">${icon}</div>
250
273
  <div class="fsize">${escapeHtml(entry.sizeText ?? '')}</div>
@@ -271,6 +294,8 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
271
294
  <div style="flex:1 1 auto;display:flex;align-items:center;justify-content:flex-end;gap:4px;flex-wrap:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none">
272
295
  <a class="btn ghost" href="/" style="${navStyle}">DSH</a>
273
296
  <a class="btn ghost" href="/term" style="${navStyle}">终端</a>
297
+ <a class="btn ghost" href="/remote" style="${navStyle}">窗口</a>
298
+ <a class="btn ghost" href="/vnc" style="${navStyle}">桌面</a>
274
299
  <a class="btn ghost" href="/git?path=${encodeURIComponent(info.path)}" style="${navStyle}">Git</a>
275
300
  <a class="btn ghost" href="/files?path=${encodeURIComponent(home)}" style="${navStyle}">HOME</a>
276
301
  <a class="btn ghost" href="/files?path=${encodeURIComponent(dataDir)}" style="${navStyle}">配置</a>
package/lib/files.mjs CHANGED
@@ -11,6 +11,7 @@ import fs from 'node:fs'
11
11
  import os from 'node:os'
12
12
  import path from 'node:path'
13
13
  import { spawn, spawnSync } from 'node:child_process'
14
+ import { systemExe } from './exec-path.mjs'
14
15
 
15
16
  const MAX_READ = 512 * 1024
16
17
  const MAX_OUTPUT = 64 * 1024
@@ -348,7 +349,7 @@ export function writeTextFile(absPath, text, limit = MAX_READ) {
348
349
  /** 判断命令是否可用(跨平台:Windows 查 where,其他查 PATH) */
349
350
  function commandExists(name) {
350
351
  try {
351
- const checker = process.platform === 'win32' ? 'where' : 'sh';
352
+ const checker = process.platform === 'win32' ? systemExe('where') : systemExe('sh');
352
353
  const args = process.platform === 'win32' ? [name] : ['-c', 'command -v ' + JSON.stringify(name)];
353
354
  const out = spawnSync(checker, args, { encoding: 'utf8', windowsHide: true, timeout: 4000 });
354
355
  return out.status === 0 && String(out.stdout ?? '').trim().length > 0;
@@ -455,7 +456,7 @@ export function runFile(absPath, args = '', { timeoutMs = 15_000, cwd } = {}) {
455
456
  const timer = setTimeout(() => {
456
457
  try {
457
458
  if (process.platform === 'win32' && child.pid) {
458
- spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
459
+ spawn(systemExe('taskkill'), ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
459
460
  } else {
460
461
  child.kill('SIGKILL');
461
462
  }
package/lib/git.mjs CHANGED
@@ -10,8 +10,11 @@
10
10
  import fs from 'node:fs'
11
11
  import path from 'node:path'
12
12
  import { spawn } from 'node:child_process'
13
+ import { gitExe, systemExe } from './exec-path.mjs'
13
14
  import { splitArgs } from './files.mjs'
14
15
 
16
+ const GIT_EXE = gitExe()
17
+ const TASKKILL = systemExe('taskkill')
15
18
  const MAX_OUTPUT = 64 * 1024
16
19
  const DEFAULT_TIMEOUT = 20_000
17
20
 
@@ -51,7 +54,7 @@ export function runGit(cwd, args, { timeoutMs = DEFAULT_TIMEOUT } = {}) {
51
54
  return new Promise((resolve) => {
52
55
  let child
53
56
  try {
54
- child = spawn('git', argList, {
57
+ child = spawn(GIT_EXE, argList, {
55
58
  cwd,
56
59
  windowsHide: true,
57
60
  env: {
@@ -101,7 +104,7 @@ export function runGit(cwd, args, { timeoutMs = DEFAULT_TIMEOUT } = {}) {
101
104
  const timer = setTimeout(() => {
102
105
  try {
103
106
  if (process.platform === 'win32' && child.pid) {
104
- spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
107
+ spawn(TASKKILL, ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
105
108
  } else {
106
109
  child.kill('SIGKILL')
107
110
  }
package/lib/guard.mjs ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * 桌面控制的输入校验(纯函数,便于单测)。
3
+ *
4
+ * 背景:/remote/input 能以用户权限操作桌面,必须限制"打开什么文件"和"结束什么进程"。
5
+ */
6
+ import path from 'node:path'
7
+
8
+ /** 可用系统默认程序打开、但绝不应由远程页面触发的可执行/脚本类后缀 */
9
+ const BLOCKED_EXT = new Set([
10
+ '.exe', '.com', '.scr', '.pif', '.msi', '.msp', '.cpl',
11
+ '.bat', '.cmd', '.ps1', '.psm1', '.psd1', '.vbs', '.vbe', '.wsf', '.wsh', '.hta',
12
+ '.js', '.jse', '.mjs', '.jar', '.reg', '.lnk', '.url', '.chm',
13
+ ])
14
+
15
+ /** 结束进程时的保护名单(系统关键进程 + DSH 自身) */
16
+ const PROTECTED_PROCESSES = new Set([
17
+ 'system', 'idle', 'registry', 'smss', 'csrss', 'wininit', 'winlogon', 'services', 'lsass',
18
+ 'svchost', 'dwm', 'explorer', 'fontdrvhost', 'spoolsv', 'audiodg', 'sihost', 'ctfmon',
19
+ 'deepseek harness', 'searchhost', 'startmenuexperiencehost', 'shellexperiencehost',
20
+ ])
21
+
22
+ /**
23
+ * 校验"在电脑打开"的路径。
24
+ * @returns {{ok: true, path: string} | {ok: false, reason: string}}
25
+ */
26
+ export function validateOpenPath(input) {
27
+ if (typeof input !== 'string' || input.trim() === '') {
28
+ return { ok: false, reason: 'empty' }
29
+ }
30
+ const resolved = path.resolve(input)
31
+ const ext = path.extname(resolved).toLowerCase()
32
+ if (BLOCKED_EXT.has(ext)) {
33
+ return { ok: false, reason: 'blocked-extension:' + ext }
34
+ }
35
+ return { ok: true, path: resolved }
36
+ }
37
+
38
+ /** 进程名(不带 .exe)是否受保护 */
39
+ export function isProtectedProcess(processName) {
40
+ if (typeof processName !== 'string') return false
41
+ const name = processName.toLowerCase().replace(/\.exe$/u, '').trim()
42
+ return PROTECTED_PROCESSES.has(name)
43
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * 本地套接字工具:Windows 命名管道 / POSIX Unix domain socket。
3
+ *
4
+ * Node 的 net 模块在 Windows 上用命名管道实现 listen/connect,
5
+ * 因此对上层的接口是统一的"流"。
6
+ */
7
+ import crypto from 'node:crypto'
8
+ import fs from 'node:fs'
9
+ import os from 'node:os'
10
+ import path from 'node:path'
11
+
12
+ const sanitize = (value) => String(value).replace(/[^A-Za-z0-9_.-]/gu, '_')
13
+
14
+ /** 本机唯一的套接字名(按用户区分,避免多用户互相干扰) */
15
+ export function socketName(prefix = 'dsh-homing-window-agent', user = os.userInfo().username) {
16
+ return `${prefix}-${sanitize(user)}`
17
+ }
18
+
19
+ /** Windows 返回 \\.\pipe\name;其它平台返回临时目录下的 .sock 路径 */
20
+ export function socketPath(name) {
21
+ if (process.platform === 'win32') return '\\\\.\\pipe\\' + name
22
+ return path.join(os.tmpdir(), name + '.sock')
23
+ }
24
+
25
+ export function agentDir() {
26
+ const base = process.env.LOCALAPPDATA || process.env.XDG_RUNTIME_DIR || os.tmpdir()
27
+ return path.join(base, 'dsh-homing')
28
+ }
29
+
30
+ export function tokenFile() {
31
+ return path.join(agentDir(), 'agent.token')
32
+ }
33
+
34
+ /** 读取或生成 token(32 字节随机,十六进制;POSIX 下权限 0600) */
35
+ export function loadOrCreateToken(file = tokenFile()) {
36
+ try { fs.mkdirSync(path.dirname(file), { recursive: true }) } catch { /* 忽略 */ }
37
+ try {
38
+ const existing = fs.readFileSync(file, 'utf8').trim()
39
+ if (existing.length >= 32) return existing
40
+ } catch { /* 不存在则生成 */ }
41
+ const token = crypto.randomBytes(32).toString('hex')
42
+ try { fs.writeFileSync(file, token, { mode: 0o600 }) } catch { /* 忽略 */ }
43
+ return token
44
+ }
45
+
46
+ /** POSIX 下清理上次异常退出留下的 socket 文件 */
47
+ export function removeStaleSocket(file) {
48
+ if (process.platform === 'win32') return
49
+ try { fs.rmSync(file, { force: true }) } catch { /* 忽略 */ }
50
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * 简单日志轮转(零依赖)
3
+ *
4
+ * 背景:守护进程日志长期追加,没有上限会一直涨。
5
+ * 策略:单文件超过 maxBytes 时轮转:file → file.1 → ...,最多保留 backups 个备份。
6
+ */
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+
10
+ export const DEFAULT_MAX_BYTES = 2 * 1024 * 1024
11
+ export const DEFAULT_BACKUPS = 2
12
+
13
+ function rotate(file, backups) {
14
+ for (let index = backups; index >= 1; index -= 1) {
15
+ const from = index === 1 ? file : `${file}.${index - 1}`
16
+ const to = `${file}.${index}`
17
+ try {
18
+ fs.rmSync(to, { force: true })
19
+ fs.renameSync(from, to)
20
+ } catch { /* 备份不存在或重命名失败:忽略 */ }
21
+ }
22
+ }
23
+
24
+ /**
25
+ * 创建日志写入函数。
26
+ * @param {string} file 日志路径
27
+ * @param {{ maxBytes?: number, backups?: number }} [options]
28
+ * @returns {(line: string) => void}
29
+ */
30
+ export function createLogWriter(file, { maxBytes = DEFAULT_MAX_BYTES, backups = DEFAULT_BACKUPS } = {}) {
31
+ let size = 0
32
+ try {
33
+ size = fs.statSync(file).size
34
+ } catch {
35
+ size = 0
36
+ }
37
+ return function write(line) {
38
+ const text = String(line)
39
+ const bytes = Buffer.byteLength(text)
40
+ try {
41
+ fs.mkdirSync(path.dirname(file), { recursive: true })
42
+ if (size > 0 && size + bytes > maxBytes) {
43
+ rotate(file, backups)
44
+ size = 0
45
+ }
46
+ fs.appendFileSync(file, text)
47
+ size += bytes
48
+ } catch { /* 日志写不了不影响主流程 */ }
49
+ }
50
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * 找到可用的 Node 运行时。
3
+ *
4
+ * 背景:插件代码跑在 DSH 的 Electron 进程里,`process.execPath` 是
5
+ * "DeepSeek Harness.exe",不是 node。用它去 spawn CLI/守护进程,
6
+ * 实际上会再启动一个 DSH 实例(曾导致点"重启守护进程"却把 DSH 重启)。
7
+ */
8
+ import fs from 'node:fs'
9
+ import os from 'node:os'
10
+ import path from 'node:path'
11
+
12
+ function dshHome() {
13
+ return process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
14
+ }
15
+
16
+ /** 候选 Node 可执行文件,按优先级排列 */
17
+ export function nodeRuntimeCandidates() {
18
+ const exe = process.platform === 'win32' ? 'node.exe' : 'node'
19
+ const candidates = []
20
+ const fromEnv = process.env.DSH_HOMING_NODE?.trim() || process.env.DSH_NODE_BIN?.trim()
21
+ if (fromEnv) candidates.push(fromEnv)
22
+
23
+ const runtimesRoot = path.join(dshHome(), 'dsh-runtimes')
24
+ try {
25
+ for (const dir of fs.readdirSync(runtimesRoot)) {
26
+ candidates.push(path.join(runtimesRoot, dir, 'dependencies', 'node', 'bin', exe))
27
+ }
28
+ } catch { /* 没有 dsh-runtimes 目录 */ }
29
+
30
+ // 当前进程本身就运行在 node 上时直接可用
31
+ if (/node(\.exe)?$/iu.test(process.execPath)) candidates.push(process.execPath)
32
+
33
+ return candidates
34
+ }
35
+
36
+ export function findNodeRuntime() {
37
+ for (const candidate of nodeRuntimeCandidates()) {
38
+ try {
39
+ if (candidate && fs.statSync(candidate).isFile()) return candidate
40
+ } catch { /* 继续找 */ }
41
+ }
42
+ // 最后回退:让系统 PATH 找 node(仍比误用 DSH exe 安全)
43
+ return process.platform === 'win32' ? 'node.exe' : 'node'
44
+ }
package/lib/office.mjs ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Office 文档预览:用 DSH 自带的 LibreOffice 引擎把 docx/xlsx/pptx 转成 PDF。
3
+ *
4
+ * 为什么复用 DSH 的引擎:
5
+ * - DSH 安装包已经带 @deepseek-ai/libreoffice-kit(Windows/macOS 原生、Linux WASM),
6
+ * 再装一份 LibreOffice 既大又重复;
7
+ * - 转换保真度高(就是 LibreOffice 引擎),不需要 Office/WPS 参与;
8
+ * - 只在本机跑一次转换,产物缓存到临时目录,同一文件只转一次。
9
+ *
10
+ * 找不到引擎时优雅降级:返回错误,页面提示"下载后用 WPS 打开"。
11
+ */
12
+ import fs from 'node:fs'
13
+ import os from 'node:os'
14
+ import path from 'node:path'
15
+ import crypto from 'node:crypto'
16
+ import { pathToFileURL } from 'node:url'
17
+
18
+ const OFFICE_EXT = new Set(['.docx', '.doc', '.xlsx', '.xls', '.pptx', '.ppt', '.odt', '.ods', '.odp', '.rtf'])
19
+ const PDF_EXT = new Set(['.pdf'])
20
+
21
+ export const isPdfFile = (name) => PDF_EXT.has(path.extname(String(name ?? '')).toLowerCase())
22
+ export const isOfficeFile = (name) => OFFICE_EXT.has(path.extname(String(name ?? '')).toLowerCase())
23
+
24
+ const exists = (file) => {
25
+ try { return fs.statSync(file).isFile() } catch { return false }
26
+ }
27
+
28
+ /** 找 DSH 自带的 libreoffice-kit 入口;找不到返回 null */
29
+ export function findOfficeKit() {
30
+ const explicit = process.env.DSH_HOMING_OFFICE_KIT?.trim()
31
+ if (explicit && exists(explicit)) return explicit
32
+
33
+ // Electron 主进程:process.resourcesPath 直接指向 resources/
34
+ const candidates = []
35
+ const resources = process.resourcesPath
36
+ if (typeof resources === 'string' && resources !== '') {
37
+ candidates.push(path.join(resources, 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
38
+ candidates.push(path.join(resources, 'app', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
39
+ }
40
+ // 常见安装位置(当前用户安装 / 全机安装)
41
+ const local = process.env.LOCALAPPDATA
42
+ const pf = process.env.ProgramFiles || 'C:\\Program Files'
43
+ if (local) candidates.push(path.join(local, 'Programs', 'DeepSeek Harness', 'resources', 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
44
+ candidates.push(path.join(pf, 'DeepSeek Harness', 'resources', 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
45
+
46
+ // 兜底:从可执行文件位置向上找
47
+ const exeDir = path.dirname(process.execPath)
48
+ candidates.push(
49
+ path.join(exeDir, 'resources', 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'),
50
+ path.join(exeDir, 'resources', 'app', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'),
51
+ path.join(exeDir, 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'),
52
+ )
53
+
54
+ // 便携版/自定义安装:向上找 3 层,常见目录结构
55
+ let cursor = exeDir
56
+ for (let i = 0; i < 4; i += 1) {
57
+ candidates.push(path.join(cursor, 'resources', 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
58
+ cursor = path.dirname(cursor)
59
+ }
60
+
61
+ return candidates.find(exists) ?? null
62
+ }
63
+
64
+ let converterPromise = null
65
+ let converter = null
66
+
67
+ async function getConverter() {
68
+ if (converter !== null) return converter
69
+ if (converterPromise === null) {
70
+ converterPromise = (async () => {
71
+ const entry = findOfficeKit()
72
+ if (entry === null) throw new Error('未找到 DSH 自带的 LibreOffice 引擎')
73
+ const mod = await import(pathToFileURL(entry).href)
74
+ if (typeof mod.createConverter !== 'function') throw new Error('LibreOffice 引擎接口不可用')
75
+ const created = await mod.createConverter({ timeoutMs: 180_000 })
76
+ converter = created
77
+ return created
78
+ })().catch((error) => {
79
+ converterPromise = null
80
+ throw error
81
+ })
82
+ }
83
+ return converterPromise
84
+ }
85
+
86
+ /** 缓存目录:<temp>/dsh-homing-office */
87
+ export function cacheDir() {
88
+ return path.join(os.tmpdir(), 'dsh-homing-office')
89
+ }
90
+
91
+ /** 同一文件(路径 + 大小 + mtime)只转一次 */
92
+ export function cacheKey(absPath) {
93
+ const stat = fs.statSync(absPath)
94
+ return crypto.createHash('sha1')
95
+ .update(`${path.resolve(absPath)}\0${stat.size}\0${stat.mtimeMs}`)
96
+ .digest('hex')
97
+ }
98
+
99
+ /**
100
+ * 把 Office 文件转成 PDF(带缓存)。
101
+ * 返回 { ok, path, bytes, cached, error }
102
+ */
103
+ export async function renderPdf(inputPath) {
104
+ if (!exists(inputPath)) return { ok: false, error: '文件不存在' }
105
+ const dir = cacheDir()
106
+ const key = cacheKey(inputPath)
107
+ const target = path.join(dir, `${key}.pdf`)
108
+
109
+ try {
110
+ if (exists(target)) return { ok: true, path: target, bytes: fs.statSync(target).size, cached: true }
111
+ } catch { /* 缓存坏了就重转 */ }
112
+
113
+ try {
114
+ const kit = await getConverter()
115
+ fs.mkdirSync(dir, { recursive: true })
116
+ const temp = path.join(dir, `${key}.${process.pid}.tmp.pdf`)
117
+ await kit.render({ inputPath: path.resolve(inputPath), outputPath: temp })
118
+ if (!exists(temp)) return { ok: false, error: '转换没有生成 PDF' }
119
+ fs.renameSync(temp, target)
120
+ return { ok: true, path: target, bytes: fs.statSync(target).size, cached: false }
121
+ } catch (error) {
122
+ return { ok: false, error: String(error?.message ?? error), code: error?.code ?? null }
123
+ }
124
+ }
125
+
126
+ /** 释放转换器(进程退出/测试用) */
127
+ export async function disposeOffice() {
128
+ if (converter !== null) {
129
+ try { await converter.dispose() } catch { /* 忽略 */ }
130
+ converter = null
131
+ }
132
+ converterPromise = null
133
+ }