@andy.ian/dsh-homing 0.0.0-stage → 2.0.1

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 (230) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +71 -2
  3. package/bin/auth.mjs +159 -0
  4. package/bin/backup.mjs +118 -0
  5. package/bin/bootstrap-server.mjs +436 -0
  6. package/bin/entry-link.mjs +69 -0
  7. package/bin/nginx-dsh.template.conf +91 -0
  8. package/bin/nginx-gate.conf +9 -0
  9. package/bin/nginx-ws-map.conf +5 -0
  10. package/bin/renew-cert.mjs +127 -0
  11. package/bin/supervisor.mjs +488 -0
  12. package/bin/watchdog.mjs +163 -0
  13. package/client.js +79 -0
  14. package/cordis.patch.yml +30 -0
  15. package/icon.svg +9 -0
  16. package/index.js +3526 -0
  17. package/lib/csrf.mjs +60 -0
  18. package/lib/devices.mjs +221 -0
  19. package/lib/files-page.mjs +592 -0
  20. package/lib/files.mjs +551 -0
  21. package/lib/git.mjs +154 -0
  22. package/lib/limits.mjs +135 -0
  23. package/lib/pty.mjs +361 -0
  24. package/lib/session.mjs +216 -0
  25. package/lib/shell-page.mjs +430 -0
  26. package/lib/shell.mjs +274 -0
  27. package/lib/term-app.js +318 -0
  28. package/lib/term-page.mjs +117 -0
  29. package/lib/vendor/fonts/JetBrainsMono-Regular.ttf +0 -0
  30. package/lib/vendor/fonts/jetbrains-mono-400.woff2 +0 -0
  31. package/lib/vendor/fonts/jetbrains-mono-700.woff2 +0 -0
  32. package/lib/vendor/node_modules/@xterm/addon-fit/LICENSE +19 -0
  33. package/lib/vendor/node_modules/@xterm/addon-fit/README.md +24 -0
  34. package/lib/vendor/node_modules/@xterm/addon-fit/lib/addon-fit.js +2 -0
  35. package/lib/vendor/node_modules/@xterm/addon-fit/lib/addon-fit.js.map +1 -0
  36. package/lib/vendor/node_modules/@xterm/addon-fit/package.json +26 -0
  37. package/lib/vendor/node_modules/@xterm/addon-fit/src/FitAddon.ts +90 -0
  38. package/lib/vendor/node_modules/@xterm/addon-fit/typings/addon-fit.d.ts +55 -0
  39. package/lib/vendor/node_modules/asn1/Jenkinsfile +65 -0
  40. package/lib/vendor/node_modules/asn1/LICENSE +19 -0
  41. package/lib/vendor/node_modules/asn1/README.md +50 -0
  42. package/lib/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
  43. package/lib/vendor/node_modules/asn1/lib/ber/index.js +27 -0
  44. package/lib/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
  45. package/lib/vendor/node_modules/asn1/lib/ber/types.js +36 -0
  46. package/lib/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
  47. package/lib/vendor/node_modules/asn1/lib/index.js +20 -0
  48. package/lib/vendor/node_modules/asn1/package.json +31 -0
  49. package/lib/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
  50. package/lib/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
  51. package/lib/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
  52. package/lib/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
  53. package/lib/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
  54. package/lib/vendor/node_modules/safer-buffer/LICENSE +21 -0
  55. package/lib/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
  56. package/lib/vendor/node_modules/safer-buffer/Readme.md +156 -0
  57. package/lib/vendor/node_modules/safer-buffer/dangerous.js +58 -0
  58. package/lib/vendor/node_modules/safer-buffer/package.json +34 -0
  59. package/lib/vendor/node_modules/safer-buffer/safer.js +77 -0
  60. package/lib/vendor/node_modules/safer-buffer/tests.js +406 -0
  61. package/lib/vendor/node_modules/ssh2/.eslintignore +4 -0
  62. package/lib/vendor/node_modules/ssh2/.eslintrc.js +5 -0
  63. package/lib/vendor/node_modules/ssh2/.github/workflows/ci.yml +110 -0
  64. package/lib/vendor/node_modules/ssh2/.github/workflows/lint.yml +27 -0
  65. package/lib/vendor/node_modules/ssh2/LICENSE +19 -0
  66. package/lib/vendor/node_modules/ssh2/README.md +1529 -0
  67. package/lib/vendor/node_modules/ssh2/SFTP.md +413 -0
  68. package/lib/vendor/node_modules/ssh2/examples/server-chat.js +238 -0
  69. package/lib/vendor/node_modules/ssh2/examples/sftp-server-download-only.js +134 -0
  70. package/lib/vendor/node_modules/ssh2/install.js +27 -0
  71. package/lib/vendor/node_modules/ssh2/lib/Channel.js +295 -0
  72. package/lib/vendor/node_modules/ssh2/lib/agent.js +1123 -0
  73. package/lib/vendor/node_modules/ssh2/lib/client.js +2176 -0
  74. package/lib/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
  75. package/lib/vendor/node_modules/ssh2/lib/index.js +44 -0
  76. package/lib/vendor/node_modules/ssh2/lib/keygen.js +582 -0
  77. package/lib/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
  78. package/lib/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
  79. package/lib/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
  80. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
  81. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
  82. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
  83. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
  84. package/lib/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
  85. package/lib/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
  86. package/lib/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
  87. package/lib/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
  88. package/lib/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
  89. package/lib/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
  90. package/lib/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
  91. package/lib/vendor/node_modules/ssh2/lib/server.js +1380 -0
  92. package/lib/vendor/node_modules/ssh2/lib/utils.js +336 -0
  93. package/lib/vendor/node_modules/ssh2/package.json +49 -0
  94. package/lib/vendor/node_modules/ssh2/test/common.js +316 -0
  95. package/lib/vendor/node_modules/ssh2/test/fixtures/bad_rsa_private_key +26 -0
  96. package/lib/vendor/node_modules/ssh2/test/fixtures/https_cert.pem +33 -0
  97. package/lib/vendor/node_modules/ssh2/test/fixtures/https_key.pem +52 -0
  98. package/lib/vendor/node_modules/ssh2/test/fixtures/id_dsa +12 -0
  99. package/lib/vendor/node_modules/ssh2/test/fixtures/id_ecdsa +5 -0
  100. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa +15 -0
  101. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa.ppk +26 -0
  102. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa_enc +30 -0
  103. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +21 -0
  104. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +1 -0
  105. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +7 -0
  106. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +7 -0
  107. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +22 -0
  108. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +1 -0
  109. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +7 -0
  110. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +7 -0
  111. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +23 -0
  112. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +1 -0
  113. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +7 -0
  114. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +7 -0
  115. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +9 -0
  116. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +1 -0
  117. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +7 -0
  118. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +7 -0
  119. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +10 -0
  120. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +1 -0
  121. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +8 -0
  122. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +7 -0
  123. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +10 -0
  124. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +1 -0
  125. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +8 -0
  126. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +7 -0
  127. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +7 -0
  128. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +1 -0
  129. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +7 -0
  130. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +7 -0
  131. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +27 -0
  132. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +1 -0
  133. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +7 -0
  134. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +7 -0
  135. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +28 -0
  136. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +1 -0
  137. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +8 -0
  138. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +7 -0
  139. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +29 -0
  140. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +1 -0
  141. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +8 -0
  142. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +7 -0
  143. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +12 -0
  144. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +1 -0
  145. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +7 -0
  146. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +7 -0
  147. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +15 -0
  148. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +1 -0
  149. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +8 -0
  150. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +7 -0
  151. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +5 -0
  152. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +1 -0
  153. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +7 -0
  154. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +7 -0
  155. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +8 -0
  156. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +1 -0
  157. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +8 -0
  158. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +7 -0
  159. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa +27 -0
  160. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +1 -0
  161. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +7 -0
  162. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +7 -0
  163. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +30 -0
  164. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +1 -0
  165. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +8 -0
  166. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +7 -0
  167. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +54 -0
  168. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +1 -0
  169. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +6 -0
  170. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +6 -0
  171. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +17 -0
  172. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +7 -0
  173. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +26 -0
  174. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +7 -0
  175. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +18 -0
  176. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +7 -0
  177. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +9 -0
  178. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +7 -0
  179. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +10 -0
  180. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +7 -0
  181. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +11 -0
  182. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +7 -0
  183. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +11 -0
  184. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +7 -0
  185. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +8 -0
  186. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +7 -0
  187. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +13 -0
  188. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +7 -0
  189. package/lib/vendor/node_modules/ssh2/test/fixtures/openssh_new_rsa +27 -0
  190. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +12 -0
  191. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +5 -0
  192. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +15 -0
  193. package/lib/vendor/node_modules/ssh2/test/test-exec.js +578 -0
  194. package/lib/vendor/node_modules/ssh2/test/test-integration-openssh.js +486 -0
  195. package/lib/vendor/node_modules/ssh2/test/test-keygen.js +60 -0
  196. package/lib/vendor/node_modules/ssh2/test/test-misc-client-server.js +1460 -0
  197. package/lib/vendor/node_modules/ssh2/test/test-openssh.js +261 -0
  198. package/lib/vendor/node_modules/ssh2/test/test-protocol-crypto.js +631 -0
  199. package/lib/vendor/node_modules/ssh2/test/test-protocol-keyparser.js +177 -0
  200. package/lib/vendor/node_modules/ssh2/test/test-server-hostkeys.js +138 -0
  201. package/lib/vendor/node_modules/ssh2/test/test-sftp.js +842 -0
  202. package/lib/vendor/node_modules/ssh2/test/test-shell.js +109 -0
  203. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent-openssh.js +110 -0
  204. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent.js +171 -0
  205. package/lib/vendor/node_modules/ssh2/test/test-userauth.js +611 -0
  206. package/lib/vendor/node_modules/ssh2/test/test-worker-imports.js +25 -0
  207. package/lib/vendor/node_modules/ssh2/test/test.js +20 -0
  208. package/lib/vendor/node_modules/ssh2/util/build_pagent.bat +2 -0
  209. package/lib/vendor/node_modules/ssh2/util/pagent.c +88 -0
  210. package/lib/vendor/node_modules/ssh2/util/pagent.exe +0 -0
  211. package/lib/vendor/node_modules/tweetnacl/AUTHORS.md +27 -0
  212. package/lib/vendor/node_modules/tweetnacl/CHANGELOG.md +283 -0
  213. package/lib/vendor/node_modules/tweetnacl/LICENSE +24 -0
  214. package/lib/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
  215. package/lib/vendor/node_modules/tweetnacl/README.md +494 -0
  216. package/lib/vendor/node_modules/tweetnacl/nacl-fast.js +2391 -0
  217. package/lib/vendor/node_modules/tweetnacl/nacl-fast.min.js +1 -0
  218. package/lib/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
  219. package/lib/vendor/node_modules/tweetnacl/nacl.js +1178 -0
  220. package/lib/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
  221. package/lib/vendor/node_modules/tweetnacl/package.json +56 -0
  222. package/lib/vendor/xterm.css +218 -0
  223. package/lib/vendor/xterm.js +2 -0
  224. package/locale/en.json +6 -0
  225. package/locale/zh.json +6 -0
  226. package/ops/watchdog/dsh-watchdog.ps1 +105 -0
  227. package/ops/watchdog/restart-hidden.vbs +7 -0
  228. package/ops/watchdog/restart-now.ps1 +261 -0
  229. package/ops/watchdog/run-hidden.vbs +4 -0
  230. package/package.json +71 -4
package/lib/git.mjs ADDED
@@ -0,0 +1,154 @@
1
+ /**
2
+ * git 命令执行:给 /git 页面用。
3
+ *
4
+ * 安全边界:
5
+ * - 只执行 git 本身(不做 shell 拼接),参数由 splitArgs 分词后作为 argv 传入;
6
+ * - 关掉交互:GIT_TERMINAL_PROMPT=0、GIT_ASKPASS=echo、GIT_PAGER=cat、GIT_EDITOR=true,
7
+ * 避免命令卡在等输入(页面是同步请求,卡住就是 15 秒超时);
8
+ * - 有超时与输出上限;每条命令都写审计(在路由层)。
9
+ */
10
+ import fs from 'node:fs'
11
+ import path from 'node:path'
12
+ import { spawn } from 'node:child_process'
13
+ import { splitArgs } from './files.mjs'
14
+
15
+ const MAX_OUTPUT = 64 * 1024
16
+ const DEFAULT_TIMEOUT = 20_000
17
+
18
+ /** 是不是一个 git 仓库的根目录(有 .git 目录或 gitfile) */
19
+ export function isRepo(dir) {
20
+ try {
21
+ return fs.existsSync(path.join(dir, '.git'))
22
+ } catch {
23
+ return false
24
+ }
25
+ }
26
+
27
+ /** 仓库概况:分支、是否干净、远端、最近一条提交 */
28
+ export async function repoSummary(dir) {
29
+ const [branch, status, remote, last, branches] = await Promise.all([
30
+ runGit(dir, ['rev-parse', '--abbrev-ref', 'HEAD']),
31
+ runGit(dir, ['status', '--porcelain']),
32
+ runGit(dir, ['remote', '-v']),
33
+ runGit(dir, ['log', '-1', '--pretty=%h %ad %s', '--date=format:%m-%d %H:%M']),
34
+ runGit(dir, ['branch', '-a', '--format=%(refname:short)']),
35
+ ])
36
+ const dirty = status.ok ? status.output.trim().split('\n').filter(Boolean) : []
37
+ return {
38
+ branch: branch.ok ? branch.output.trim() : '',
39
+ dirty,
40
+ remote: remote.ok ? remote.output.trim().split('\n')[0] ?? '' : '',
41
+ last: last.ok ? last.output.trim() : '',
42
+ branches: branches.ok
43
+ ? branches.output.split('\n').map((line) => line.trim()).filter((line) => line !== '' && !line.includes('HEAD'))
44
+ : [],
45
+ }
46
+ }
47
+
48
+ /** 执行 git 子命令,返回 { ok, code, output } */
49
+ export function runGit(cwd, args, { timeoutMs = DEFAULT_TIMEOUT } = {}) {
50
+ const argList = Array.isArray(args) ? args : splitArgs(args)
51
+ return new Promise((resolve) => {
52
+ let child
53
+ try {
54
+ child = spawn('git', argList, {
55
+ cwd,
56
+ windowsHide: true,
57
+ env: {
58
+ ...process.env,
59
+ GIT_TERMINAL_PROMPT: '0',
60
+ GIT_ASKPASS: 'echo',
61
+ GIT_PAGER: 'cat',
62
+ GIT_EDITOR: 'true',
63
+ LC_ALL: 'C.UTF-8',
64
+ },
65
+ stdio: ['ignore', 'pipe', 'pipe'],
66
+ })
67
+ } catch (error) {
68
+ resolve({ ok: false, error: `启动失败:${error.message}` })
69
+ return
70
+ }
71
+
72
+ let settled = false
73
+ const finish = (value) => {
74
+ if (settled) return
75
+ settled = true
76
+ resolve(value)
77
+ }
78
+
79
+ const chunks = []
80
+ let total = 0
81
+ const collect = (chunk) => {
82
+ if (total >= MAX_OUTPUT) return
83
+ chunks.push(chunk)
84
+ total += chunk.length
85
+ }
86
+ child.stdout.on('data', collect)
87
+ child.stderr.on('data', collect)
88
+
89
+ const decode = () => {
90
+ // git 的输出基本都是 ASCII/UTF-8;路径在这种环境下也很少出现 GBK
91
+ const buffer = Buffer.concat(chunks).subarray(0, MAX_OUTPUT)
92
+ const utf8 = buffer.toString('utf8')
93
+ if (!utf8.includes('\uFFFD')) return utf8
94
+ try {
95
+ return new TextDecoder('gbk').decode(buffer)
96
+ } catch {
97
+ return utf8
98
+ }
99
+ }
100
+
101
+ const timer = setTimeout(() => {
102
+ try {
103
+ if (process.platform === 'win32' && child.pid) {
104
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
105
+ } else {
106
+ child.kill('SIGKILL')
107
+ }
108
+ } catch { /* 已退出 */ }
109
+ finish({ ok: false, timeout: true, code: null, output: decode() + '\n(超时,已终止)' })
110
+ }, timeoutMs)
111
+
112
+ child.on('error', (error) => {
113
+ clearTimeout(timer)
114
+ finish({ ok: false, error: `启动 git 失败:${error.message}` })
115
+ })
116
+ child.on('close', (code) => {
117
+ clearTimeout(timer)
118
+ const output = decode()
119
+ finish({ ok: code === 0, code, output: output === '' ? '(无输出)' : output })
120
+ })
121
+ })
122
+ }
123
+
124
+ /** 补全候选:常用子命令 + 仓库里的分支(分支放前面,切换更常用) */
125
+ const COMMON_GIT = [
126
+ 'status --short --branch',
127
+ 'log --oneline -20',
128
+ 'log --graph --oneline --all -20',
129
+ 'diff',
130
+ 'diff --stat',
131
+ 'add -A',
132
+ 'commit -m ""',
133
+ 'commit --amend --no-edit',
134
+ 'pull',
135
+ 'push',
136
+ 'fetch --all',
137
+ 'branch',
138
+ 'checkout',
139
+ 'switch',
140
+ 'stash',
141
+ 'stash pop',
142
+ 'merge',
143
+ 'rebase',
144
+ 'tag',
145
+ 'remote -v',
146
+ 'reset --soft HEAD~1',
147
+ 'restore',
148
+ 'show --stat',
149
+ ];
150
+
151
+ export function suggestionsFor(summary) {
152
+ const branches = (summary && Array.isArray(summary.branches)) ? summary.branches : [];
153
+ return [...branches, ...COMMON_GIT];
154
+ }
package/lib/limits.mjs ADDED
@@ -0,0 +1,135 @@
1
+ /**
2
+ * 登录节流与请求体上限。
3
+ *
4
+ * 为什么不用「按 IP 硬锁」:
5
+ * 这个插件跑在 TLS 透传后面,所有外部请求都会从隧道口(回环地址)进来,
6
+ * 客户端 IP 无法真实区分。若按 IP 直接锁定,攻击者只要故意失败几次就能
7
+ * 把主人锁在门外。
8
+ *
9
+ * 因此分两层:
10
+ * 1) 按「设备桶」计数(有 dsh-homing-device 就按设备 id,没有就归到 unpaired),
11
+ * 桶内失败到阈值后只锁这一个桶 —— 攻击者锁不到别人的桶;
12
+ * 2) 全局失败计数只做**延迟**(封顶 maxDelayMs),不做阻断 ——
13
+ * 这样跨桶跳着猜也快不起来,但任何人都不至于被永久拒之门外。
14
+ */
15
+
16
+ export const DEFAULTS = Object.freeze({
17
+ /** 失败计数的时间窗 */
18
+ windowMs: 15 * 60 * 1000,
19
+ /** 单个桶内失败多少次后锁定该桶 */
20
+ perKeyMax: 8,
21
+ /** 首次锁定时长 */
22
+ perKeyBlockMs: 5 * 60 * 1000,
23
+ /** 锁定次数的指数上限(防止无限增长) */
24
+ perKeyMaxBlocks: 4,
25
+ /** 递进延迟的封顶 */
26
+ maxDelayMs: 8000,
27
+ /** 请求体上限,与改造前 nginx 的 client_max_body_size 300m 对齐 */
28
+ maxBodyBytes: 300 * 1024 * 1024,
29
+ })
30
+
31
+ /** 第 n 次失败要等多久:0, 1s, 2s, 4s, 8s(封顶)。 */
32
+ export function delayForFailures(count, maxDelayMs = DEFAULTS.maxDelayMs) {
33
+ if (!Number.isFinite(count) || count <= 1) return 0
34
+ return Math.min(1000 * 2 ** (count - 1), maxDelayMs)
35
+ }
36
+
37
+ /** 这个桶现在是否处于锁定期。 */
38
+ export function isBlocked(entry, now = Date.now()) {
39
+ return Boolean(entry && Number.isFinite(entry.blockedUntil) && entry.blockedUntil > now)
40
+ }
41
+
42
+ /** 锁定期还剩多少秒(向上取整,最少 1)。 */
43
+ export function blockSecondsLeft(entry, now = Date.now()) {
44
+ if (!isBlocked(entry, now)) return 0
45
+ return Math.max(1, Math.ceil((entry.blockedUntil - now) / 1000))
46
+ }
47
+
48
+ /**
49
+ * 记一次失败,返回更新后的桶。
50
+ * @param {object|undefined} entry 现有条目
51
+ * @param {number} now 当前时间
52
+ */
53
+ export function registerFailure(entry, now = Date.now(), options = {}) {
54
+ const windowMs = options.windowMs ?? DEFAULTS.windowMs
55
+ const perKeyMax = options.perKeyMax ?? DEFAULTS.perKeyMax
56
+ const perKeyBlockMs = options.perKeyBlockMs ?? DEFAULTS.perKeyBlockMs
57
+ const maxBlocks = options.perKeyMaxBlocks ?? DEFAULTS.perKeyMaxBlocks
58
+
59
+ const fresh = !entry || !Number.isFinite(entry.first) || now - entry.first > windowMs
60
+ const count = fresh ? 1 : entry.count + 1
61
+ const first = fresh ? now : entry.first
62
+ const blocks = fresh ? 0 : (entry.blocks ?? 0)
63
+
64
+ if (count >= perKeyMax) {
65
+ const nextBlocks = Math.min(blocks + 1, maxBlocks)
66
+ const blockMs = Math.min(perKeyBlockMs * 2 ** (nextBlocks - 1), 60 * 60 * 1000)
67
+ return { count: 0, first: now, blocks: nextBlocks, blockedUntil: now + blockMs }
68
+ }
69
+ return { count, first, blocks, blockedUntil: 0 }
70
+ }
71
+
72
+ /** 登录成功后该桶清零。 */
73
+ export function registerSuccess() {
74
+ return { count: 0, first: 0, blocks: 0, blockedUntil: 0 }
75
+ }
76
+
77
+ /**
78
+ * 只递增计数、不加锁(全局桶用)。全局桶只参与「递进延迟」,
79
+ * 绝不进入锁定状态,避免有人用它把主人挡在门外。
80
+ */
81
+ export function bumpCounter(entry, now = Date.now(), windowMs = DEFAULTS.windowMs) {
82
+ const fresh = !entry || !Number.isFinite(entry.first) || now - entry.first > windowMs
83
+ return { count: fresh ? 1 : entry.count + 1, first: fresh ? now : entry.first }
84
+ }
85
+
86
+ /**
87
+ * 清理过期的桶,防止 map 随设备数量长期增长。
88
+ * 跳过全局桶和仍在锁定期内的桶。
89
+ * @returns {number} 删掉的条数
90
+ */
91
+ export function pruneEntries(map, now = Date.now(), windowMs = DEFAULTS.windowMs) {
92
+ if (!map || typeof map.delete !== 'function') return 0
93
+ let removed = 0
94
+ for (const [key, entry] of map) {
95
+ if (key === '__global__') continue
96
+ if (isBlocked(entry, now)) continue
97
+ if (!entry || !Number.isFinite(entry.first) || now - entry.first > windowMs) {
98
+ map.delete(key)
99
+ removed += 1
100
+ }
101
+ }
102
+ return removed
103
+ }
104
+
105
+ /**
106
+ * 体积检查:声明长度是否超限。
107
+ * @returns {{ over: boolean, limit: number, declared: number }}
108
+ */
109
+ export function checkDeclaredLength(declared, limit = DEFAULTS.maxBodyBytes) {
110
+ const value = Number(declared)
111
+ return {
112
+ over: Number.isFinite(value) && value > limit,
113
+ limit,
114
+ declared: Number.isFinite(value) ? value : -1,
115
+ }
116
+ }
117
+
118
+ /**
119
+ * 流式累计器:分块喂入,超限即返回 true(调用方负责断开)。
120
+ */
121
+ export function createByteCounter(limit = DEFAULTS.maxBodyBytes) {
122
+ let total = 0
123
+ return {
124
+ add(bytes) {
125
+ total += Number(bytes) || 0
126
+ return total > limit
127
+ },
128
+ get total() {
129
+ return total
130
+ },
131
+ get limit() {
132
+ return limit
133
+ },
134
+ }
135
+ }
package/lib/pty.mjs ADDED
@@ -0,0 +1,361 @@
1
+ /**
2
+ * 真终端(PTY)—— 「远程登录到 Git Bash」。
3
+ *
4
+ * 架构:
5
+ * 浏览器(xterm.js) ──SSE/POST── 插件 ──ssh2── 本机 sshd ── ConPTY ── bash
6
+ *
7
+ * 为什么用 ssh2 而不是 ssh.exe:
8
+ * - ssh.exe 在本地没有 tty 时只能请求默认窗口尺寸,之后也没法发 window-change,
9
+ * 所以手机端无论怎么缩放,远端一直是固定列数(vim/top 排版会错);
10
+ * - ssh2 是纯 JS 客户端,可以直接指定 pty 尺寸(cols/rows),
11
+ * 并在本地 xterm 尺寸变化时调用 stream.setWindow(rows, cols) 真正改变 ConPTY 大小。
12
+ *
13
+ * 为什么自己起一份 sshd(而不是用系统那个):
14
+ * - 系统 sshd 的密钥文件在 ProgramData(当前用户在 Administrator 组 → 要管理员权限);
15
+ * - 我们这份以当前用户身份运行,只监听 127.0.0.1 的高端口,密钥都在 DSH_HOME 下。
16
+ */
17
+ import fs from 'node:fs'
18
+ import net from 'node:net'
19
+ import path from 'node:path'
20
+ import { spawn, spawnSync } from 'node:child_process'
21
+ import { createRequire } from 'node:module'
22
+ import { fileURLToPath } from 'node:url'
23
+
24
+ const require = createRequire(import.meta.url)
25
+ const here = path.dirname(fileURLToPath(import.meta.url))
26
+
27
+ /** 从 vendor 里加载 ssh2(纯 JS,无原生依赖) */
28
+ export const loadSsh2 = () => {
29
+ const candidates = [
30
+ path.join(here, 'vendor', 'node_modules', 'ssh2'),
31
+ path.join(here, 'vendor', 'ssh2'),
32
+ ]
33
+ for (const candidate of candidates) {
34
+ try {
35
+ return require(candidate)
36
+ } catch {
37
+ // 试下一个
38
+ }
39
+ }
40
+ return null
41
+ }
42
+
43
+ const SSHD_EXE = 'C:/Windows/System32/OpenSSH/sshd.exe'
44
+ const KEYGEN_EXE = 'C:/Windows/System32/OpenSSH/ssh-keygen.exe'
45
+
46
+ /**
47
+ * DSH_HOME:优先用插件传进来的值。
48
+ * 不能从代码位置推(仓库里是 D:\...\plugin\lib,部署后是 <DSH_HOME>\plugins\dsh-homing\lib),
49
+ * 所以这里只在调用方没传时用环境变量兜底。
50
+ */
51
+ export const resolveDshHome = () => process.env.DSH_HOME ?? path.resolve(here, '..', '..', '..')
52
+
53
+ const portFree = (port) => new Promise((resolve) => {
54
+ const server = net.createServer()
55
+ server.once('error', () => resolve(false))
56
+ server.once('listening', () => server.close(() => resolve(true)))
57
+ server.listen(port, '127.0.0.1')
58
+ })
59
+
60
+ const canConnect = (port) => new Promise((resolve) => {
61
+ const socket = net.connect({ port, host: '127.0.0.1' })
62
+ socket.setTimeout(800)
63
+ socket.once('connect', () => { socket.destroy(); resolve(true) })
64
+ socket.once('timeout', () => { socket.destroy(); resolve(false) })
65
+ socket.once('error', () => resolve(false))
66
+ })
67
+
68
+ const waitFor = async (predicate, timeoutMs = 8000) => {
69
+ const started = Date.now()
70
+ while (Date.now() - started < timeoutMs) {
71
+ if (await predicate()) return true
72
+ await new Promise((r) => setTimeout(r, 200))
73
+ }
74
+ return false
75
+ }
76
+
77
+ export const terminalDir = (dshHome = resolveDshHome()) => {
78
+ const dir = path.join(dshHome, 'integrations', 'dsh-homing', 'terminal')
79
+ // 老版本把 sshd 的密钥/配置放在 dsh-homing/terminal 下;新目录没有就沿用旧的,
80
+ // 避免改名后终端连不上(密钥变了 sshd 得重建,会话会断一下)。
81
+ const legacy = path.join(dshHome, 'integrations', 'dsh-homing', 'terminal')
82
+ if (!fs.existsSync(dir) && fs.existsSync(legacy)) return legacy
83
+ return dir
84
+ }
85
+
86
+ export const ensureKeyPair = (dir) => {
87
+ const key = path.join(dir, 'id_ed25519')
88
+ if (fs.existsSync(key) && fs.existsSync(key + '.pub')) return key
89
+ fs.mkdirSync(dir, { recursive: true })
90
+ const result = spawnSync(KEYGEN_EXE, ['-t', 'ed25519', '-N', '', '-C', 'dsh-homing-terminal', '-f', key], {
91
+ encoding: 'utf8',
92
+ timeout: 20000,
93
+ windowsHide: true,
94
+ })
95
+ if (result.status !== 0) throw new Error('生成密钥失败:' + String(result.stderr ?? '').slice(0, 200))
96
+ return key
97
+ }
98
+
99
+ export const ensureSshd = async ({ dshHome = resolveDshHome(), startPort = 22222, maxTries = 30 } = {}) => {
100
+ const dir = terminalDir(dshHome)
101
+ fs.mkdirSync(dir, { recursive: true })
102
+ const key = ensureKeyPair(dir)
103
+ const hostKey = path.join(dir, 'host_ed25519')
104
+ if (!fs.existsSync(hostKey)) {
105
+ const gen = spawnSync(KEYGEN_EXE, ['-t', 'ed25519', '-N', '', '-f', hostKey], { encoding: 'utf8', timeout: 20000, windowsHide: true })
106
+ if (gen.status !== 0) throw new Error('生成 host key 失败:' + String(gen.stderr ?? '').slice(0, 200))
107
+ }
108
+ const authorized = path.join(dir, 'authorized_keys')
109
+ const pub = fs.readFileSync(key + '.pub', 'utf8').trim()
110
+ if (!fs.existsSync(authorized) || !fs.readFileSync(authorized, 'utf8').includes(pub)) {
111
+ fs.writeFileSync(authorized, pub + '\n', 'utf8')
112
+ }
113
+
114
+ const stateFile = path.join(dir, 'sshd.state.json')
115
+ try {
116
+ const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
117
+ if (state.port && (await canConnect(state.port))) return { port: state.port, started: false }
118
+ } catch {
119
+ // 没有状态文件
120
+ }
121
+
122
+ let port = null
123
+ for (let i = 0; i < maxTries; i += 1) {
124
+ const candidate = startPort + i
125
+ if (await portFree(candidate)) { port = candidate; break }
126
+ }
127
+ if (port === null) throw new Error('找不到空闲端口给 sshd')
128
+
129
+ const config = path.join(dir, 'sshd_config')
130
+ fs.writeFileSync(config, [
131
+ `Port ${port}`,
132
+ 'ListenAddress 127.0.0.1',
133
+ `HostKey ${hostKey.replaceAll('\\', '/')}`,
134
+ `AuthorizedKeysFile ${authorized.replaceAll('\\', '/')}`,
135
+ 'PasswordAuthentication no',
136
+ 'PubkeyAuthentication yes',
137
+ 'KbdInteractiveAuthentication no',
138
+ 'StrictModes no',
139
+ 'UseDNS no',
140
+ 'PermitRootLogin no',
141
+ `PidFile ${path.join(dir, 'sshd.pid').replaceAll('\\', '/')}`,
142
+ 'LogLevel INFO',
143
+ ].join('\r\n'), 'utf8')
144
+
145
+ const logFile = path.join(dir, 'sshd.log')
146
+ const child = spawn(SSHD_EXE, ['-D', '-f', config, '-E', logFile], {
147
+ windowsHide: true,
148
+ stdio: ['ignore', 'ignore', 'ignore'],
149
+ })
150
+ child.on('error', () => {})
151
+ const up = await waitFor(() => canConnect(port), 10000)
152
+ if (!up) throw new Error('sshd 启动失败,详见 ' + logFile)
153
+ fs.writeFileSync(stateFile, JSON.stringify({ port, pid: child.pid, startedAt: Date.now() }), 'utf8')
154
+ return { port, started: true }
155
+ }
156
+
157
+ /**
158
+ * 一个交互式 PTY 会话(ssh2 + 远端 bash)。
159
+ * 输出用带序号的环形缓冲保存,前端可用 since=<seq> 补发。
160
+ */
161
+ export class PtyTerminal {
162
+ constructor({ port, dshHome = resolveDshHome(), cwd = null, maxBuffered = 512 * 1024, cols = 80, rows = 24 } = {}) {
163
+ this.port = port
164
+ this.dshHome = dshHome
165
+ this.cwd = cwd
166
+ this.cols = cols
167
+ this.rows = rows
168
+ this.client = null
169
+ this.stream = null
170
+ this.maxBuffered = maxBuffered
171
+ this.chunks = []
172
+ this.seq = 0
173
+ this.bytes = 0
174
+ this.listeners = new Set()
175
+ this.closed = false
176
+ }
177
+
178
+ async start() {
179
+ if (this.stream !== null) return this
180
+ const ssh2 = loadSsh2()
181
+ if (ssh2 === null) throw new Error('ssh2 未找到(vendor/node_modules/ssh2)')
182
+ const dir = terminalDir(this.dshHome)
183
+ const privateKey = fs.readFileSync(path.join(dir, 'id_ed25519'))
184
+ const username = process.env.USERNAME ?? ''
185
+
186
+ const push = (chunk) => {
187
+ const text = chunk.toString('utf8')
188
+ this.seq += 1
189
+ this.chunks.push({ seq: this.seq, text })
190
+ this.bytes += text.length
191
+ while (this.bytes > this.maxBuffered && this.chunks.length > 1) {
192
+ const dropped = this.chunks.shift()
193
+ this.bytes -= dropped.text.length
194
+ }
195
+ for (const listener of this.listeners) {
196
+ try {
197
+ listener(text, this.seq)
198
+ } catch {
199
+ // 单个订阅者出错不影响别人
200
+ }
201
+ }
202
+ }
203
+
204
+ const client = new ssh2.Client()
205
+ this.client = client
206
+
207
+ await new Promise((resolve, reject) => {
208
+ const timer = setTimeout(() => reject(new Error('SSH 连接超时')), 15000)
209
+ client.on('ready', () => {
210
+ // 用 exec + pty 启动 Git Bash(client.shell() 会落到系统默认的 cmd.exe)
211
+ const command = '"C:/Program Files/Git/bin/bash.exe" -l'
212
+ client.exec(command, {
213
+ pty: { term: 'xterm-256color', cols: this.cols, rows: this.rows },
214
+ }, (error, stream) => {
215
+ clearTimeout(timer)
216
+ if (error) {
217
+ reject(error)
218
+ return
219
+ }
220
+ this.stream = stream
221
+ this.closed = false
222
+ stream.on('data', push)
223
+ stream.stderr.on('data', push)
224
+ stream.on('close', () => {
225
+ this.closed = true
226
+ push('\r\n[会话已结束]\r\n')
227
+ })
228
+ resolve()
229
+ })
230
+ })
231
+ client.on('error', (error) => {
232
+ clearTimeout(timer)
233
+ reject(error)
234
+ })
235
+ client.on('close', () => {
236
+ clearTimeout(timer)
237
+ this.closed = true
238
+ })
239
+ client.connect({
240
+ host: '127.0.0.1',
241
+ port: this.port,
242
+ username,
243
+ privateKey,
244
+ readyTimeout: 15000,
245
+ keepaliveInterval: 15000,
246
+ })
247
+ })
248
+
249
+ if (typeof this.cwd === 'string' && this.cwd !== '') this.changeDir(this.cwd)
250
+ return this
251
+ }
252
+
253
+ /** 往终端写(键盘输入、粘贴、Ctrl 组合键) */
254
+ write(data) {
255
+ if (this.stream === null || this.closed) return false
256
+ try {
257
+ this.stream.write(data)
258
+ return true
259
+ } catch {
260
+ return false
261
+ }
262
+ }
263
+
264
+ /**
265
+ * 改变远端 PTY 的窗口尺寸 —— 等价于拖拽 Git Bash 窗口。
266
+ * 走 SSH 的 window-change 通道消息,sshd 收到后会 ResizePseudoConsole。
267
+ */
268
+ resize(cols, rows) {
269
+ const nextCols = Math.max(20, Math.min(Number(cols) || 80, 400))
270
+ const nextRows = Math.max(5, Math.min(Number(rows) || 24, 200))
271
+ this.cols = nextCols
272
+ this.rows = nextRows
273
+ if (this.stream === null) return false
274
+ try {
275
+ this.stream.setWindow(nextRows, nextCols, 0, 0)
276
+ return true
277
+ } catch {
278
+ return false
279
+ }
280
+ }
281
+
282
+ /** 切换工作目录(会话是常驻的,所以只发一条 cd) */
283
+ changeDir(winPath) {
284
+ if (typeof winPath !== 'string' || winPath.trim() === '') return false
285
+ const match = /^([A-Za-z]):[\\/]?(.*)$/u.exec(winPath.trim())
286
+ const target = match === null
287
+ ? winPath.trim()
288
+ : '/' + match[1].toLowerCase() + (match[2] === '' ? '' : '/' + match[2].replaceAll('\\', '/'))
289
+ this.cwd = winPath.trim()
290
+ return this.write('cd "' + target.replaceAll('"', '\\"') + '"\r')
291
+ }
292
+
293
+ subscribe(listener) {
294
+ this.listeners.add(listener)
295
+ return () => this.listeners.delete(listener)
296
+ }
297
+
298
+ since(seq = 0) {
299
+ return this.chunks.filter((item) => item.seq > seq).map((item) => item.text).join('')
300
+ }
301
+
302
+ get latestSeq() {
303
+ return this.seq
304
+ }
305
+
306
+ get size() {
307
+ return { cols: this.cols, rows: this.rows }
308
+ }
309
+
310
+ stop() {
311
+ this.closed = true
312
+ try {
313
+ this.stream?.end()
314
+ this.stream?.destroy?.()
315
+ } catch {
316
+ // 已关闭
317
+ }
318
+ try {
319
+ this.client?.end()
320
+ this.client?.destroy?.()
321
+ } catch {
322
+ // 已关闭
323
+ }
324
+ this.stream = null
325
+ this.client = null
326
+ }
327
+ }
328
+
329
+ let sharedTerminal = null
330
+
331
+ export const sharedPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null } = {}) => {
332
+ const { port } = await ensureSshd({ dshHome })
333
+ if (sharedTerminal === null || sharedTerminal.closed) {
334
+ sharedTerminal = new PtyTerminal({ port, dshHome, cwd })
335
+ await sharedTerminal.start()
336
+ }
337
+ return sharedTerminal
338
+ }
339
+
340
+ export const resetPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null } = {}) => {
341
+ if (sharedTerminal !== null) sharedTerminal.stop()
342
+ sharedTerminal = null
343
+ return sharedPtyTerminal({ dshHome, cwd })
344
+ }
345
+
346
+ export const stopSshd = (dshHome = resolveDshHome()) => {
347
+ try {
348
+ const stateFile = path.join(terminalDir(dshHome), 'sshd.state.json')
349
+ const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
350
+ if (state.pid) {
351
+ // Windows 上用 taskkill 连子进程一起收:只 kill 父进程会留下 per-connection 的 sshd
352
+ const result = spawnSync('taskkill', ['/F', '/T', '/PID', String(state.pid)], { windowsHide: true, encoding: 'utf8' })
353
+ if (result.status !== 0) {
354
+ try { process.kill(state.pid) } catch { /* 已退出 */ }
355
+ }
356
+ }
357
+ fs.rmSync(stateFile, { force: true })
358
+ } catch {
359
+ // 没在跑
360
+ }
361
+ }