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

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 (226) 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/watchdog.mjs +158 -0
  12. package/cordis.patch.yml +30 -0
  13. package/icon.svg +9 -0
  14. package/index.js +3339 -0
  15. package/lib/csrf.mjs +60 -0
  16. package/lib/devices.mjs +221 -0
  17. package/lib/files-page.mjs +391 -0
  18. package/lib/files.mjs +464 -0
  19. package/lib/git.mjs +154 -0
  20. package/lib/limits.mjs +135 -0
  21. package/lib/pty.mjs +354 -0
  22. package/lib/session.mjs +216 -0
  23. package/lib/shell-page.mjs +430 -0
  24. package/lib/shell.mjs +274 -0
  25. package/lib/term-app.js +318 -0
  26. package/lib/term-page.mjs +117 -0
  27. package/lib/vendor/fonts/JetBrainsMono-Regular.ttf +0 -0
  28. package/lib/vendor/fonts/jetbrains-mono-400.woff2 +0 -0
  29. package/lib/vendor/fonts/jetbrains-mono-700.woff2 +0 -0
  30. package/lib/vendor/node_modules/@xterm/addon-fit/LICENSE +19 -0
  31. package/lib/vendor/node_modules/@xterm/addon-fit/README.md +24 -0
  32. package/lib/vendor/node_modules/@xterm/addon-fit/lib/addon-fit.js +2 -0
  33. package/lib/vendor/node_modules/@xterm/addon-fit/lib/addon-fit.js.map +1 -0
  34. package/lib/vendor/node_modules/@xterm/addon-fit/package.json +26 -0
  35. package/lib/vendor/node_modules/@xterm/addon-fit/src/FitAddon.ts +90 -0
  36. package/lib/vendor/node_modules/@xterm/addon-fit/typings/addon-fit.d.ts +55 -0
  37. package/lib/vendor/node_modules/asn1/Jenkinsfile +65 -0
  38. package/lib/vendor/node_modules/asn1/LICENSE +19 -0
  39. package/lib/vendor/node_modules/asn1/README.md +50 -0
  40. package/lib/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
  41. package/lib/vendor/node_modules/asn1/lib/ber/index.js +27 -0
  42. package/lib/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
  43. package/lib/vendor/node_modules/asn1/lib/ber/types.js +36 -0
  44. package/lib/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
  45. package/lib/vendor/node_modules/asn1/lib/index.js +20 -0
  46. package/lib/vendor/node_modules/asn1/package.json +31 -0
  47. package/lib/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
  48. package/lib/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
  49. package/lib/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
  50. package/lib/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
  51. package/lib/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
  52. package/lib/vendor/node_modules/safer-buffer/LICENSE +21 -0
  53. package/lib/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
  54. package/lib/vendor/node_modules/safer-buffer/Readme.md +156 -0
  55. package/lib/vendor/node_modules/safer-buffer/dangerous.js +58 -0
  56. package/lib/vendor/node_modules/safer-buffer/package.json +34 -0
  57. package/lib/vendor/node_modules/safer-buffer/safer.js +77 -0
  58. package/lib/vendor/node_modules/safer-buffer/tests.js +406 -0
  59. package/lib/vendor/node_modules/ssh2/.eslintignore +4 -0
  60. package/lib/vendor/node_modules/ssh2/.eslintrc.js +5 -0
  61. package/lib/vendor/node_modules/ssh2/.github/workflows/ci.yml +110 -0
  62. package/lib/vendor/node_modules/ssh2/.github/workflows/lint.yml +27 -0
  63. package/lib/vendor/node_modules/ssh2/LICENSE +19 -0
  64. package/lib/vendor/node_modules/ssh2/README.md +1529 -0
  65. package/lib/vendor/node_modules/ssh2/SFTP.md +413 -0
  66. package/lib/vendor/node_modules/ssh2/examples/server-chat.js +238 -0
  67. package/lib/vendor/node_modules/ssh2/examples/sftp-server-download-only.js +134 -0
  68. package/lib/vendor/node_modules/ssh2/install.js +27 -0
  69. package/lib/vendor/node_modules/ssh2/lib/Channel.js +295 -0
  70. package/lib/vendor/node_modules/ssh2/lib/agent.js +1123 -0
  71. package/lib/vendor/node_modules/ssh2/lib/client.js +2176 -0
  72. package/lib/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
  73. package/lib/vendor/node_modules/ssh2/lib/index.js +44 -0
  74. package/lib/vendor/node_modules/ssh2/lib/keygen.js +582 -0
  75. package/lib/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
  76. package/lib/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
  77. package/lib/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
  78. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
  79. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
  80. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
  81. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
  82. package/lib/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
  83. package/lib/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
  84. package/lib/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
  85. package/lib/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
  86. package/lib/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
  87. package/lib/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
  88. package/lib/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
  89. package/lib/vendor/node_modules/ssh2/lib/server.js +1380 -0
  90. package/lib/vendor/node_modules/ssh2/lib/utils.js +336 -0
  91. package/lib/vendor/node_modules/ssh2/package.json +49 -0
  92. package/lib/vendor/node_modules/ssh2/test/common.js +316 -0
  93. package/lib/vendor/node_modules/ssh2/test/fixtures/bad_rsa_private_key +26 -0
  94. package/lib/vendor/node_modules/ssh2/test/fixtures/https_cert.pem +33 -0
  95. package/lib/vendor/node_modules/ssh2/test/fixtures/https_key.pem +52 -0
  96. package/lib/vendor/node_modules/ssh2/test/fixtures/id_dsa +12 -0
  97. package/lib/vendor/node_modules/ssh2/test/fixtures/id_ecdsa +5 -0
  98. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa +15 -0
  99. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa.ppk +26 -0
  100. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa_enc +30 -0
  101. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +21 -0
  102. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +1 -0
  103. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +7 -0
  104. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +7 -0
  105. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +22 -0
  106. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +1 -0
  107. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +7 -0
  108. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +7 -0
  109. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +23 -0
  110. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +1 -0
  111. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +7 -0
  112. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +7 -0
  113. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +9 -0
  114. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +1 -0
  115. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +7 -0
  116. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +7 -0
  117. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +10 -0
  118. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +1 -0
  119. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +8 -0
  120. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +7 -0
  121. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +10 -0
  122. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +1 -0
  123. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +8 -0
  124. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +7 -0
  125. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +7 -0
  126. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +1 -0
  127. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +7 -0
  128. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +7 -0
  129. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +27 -0
  130. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +1 -0
  131. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +7 -0
  132. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +7 -0
  133. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +28 -0
  134. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +1 -0
  135. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +8 -0
  136. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +7 -0
  137. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +29 -0
  138. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +1 -0
  139. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +8 -0
  140. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +7 -0
  141. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +12 -0
  142. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +1 -0
  143. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +7 -0
  144. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +7 -0
  145. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +15 -0
  146. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +1 -0
  147. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +8 -0
  148. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +7 -0
  149. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +5 -0
  150. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +1 -0
  151. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +7 -0
  152. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +7 -0
  153. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +8 -0
  154. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +1 -0
  155. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +8 -0
  156. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +7 -0
  157. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa +27 -0
  158. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +1 -0
  159. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +7 -0
  160. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +7 -0
  161. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +30 -0
  162. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +1 -0
  163. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +8 -0
  164. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +7 -0
  165. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +54 -0
  166. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +1 -0
  167. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +6 -0
  168. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +6 -0
  169. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +17 -0
  170. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +7 -0
  171. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +26 -0
  172. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +7 -0
  173. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +18 -0
  174. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +7 -0
  175. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +9 -0
  176. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +7 -0
  177. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +10 -0
  178. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +7 -0
  179. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +11 -0
  180. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +7 -0
  181. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +11 -0
  182. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +7 -0
  183. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +8 -0
  184. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +7 -0
  185. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +13 -0
  186. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +7 -0
  187. package/lib/vendor/node_modules/ssh2/test/fixtures/openssh_new_rsa +27 -0
  188. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +12 -0
  189. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +5 -0
  190. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +15 -0
  191. package/lib/vendor/node_modules/ssh2/test/test-exec.js +578 -0
  192. package/lib/vendor/node_modules/ssh2/test/test-integration-openssh.js +486 -0
  193. package/lib/vendor/node_modules/ssh2/test/test-keygen.js +60 -0
  194. package/lib/vendor/node_modules/ssh2/test/test-misc-client-server.js +1460 -0
  195. package/lib/vendor/node_modules/ssh2/test/test-openssh.js +261 -0
  196. package/lib/vendor/node_modules/ssh2/test/test-protocol-crypto.js +631 -0
  197. package/lib/vendor/node_modules/ssh2/test/test-protocol-keyparser.js +177 -0
  198. package/lib/vendor/node_modules/ssh2/test/test-server-hostkeys.js +138 -0
  199. package/lib/vendor/node_modules/ssh2/test/test-sftp.js +842 -0
  200. package/lib/vendor/node_modules/ssh2/test/test-shell.js +109 -0
  201. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent-openssh.js +110 -0
  202. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent.js +171 -0
  203. package/lib/vendor/node_modules/ssh2/test/test-userauth.js +611 -0
  204. package/lib/vendor/node_modules/ssh2/test/test-worker-imports.js +25 -0
  205. package/lib/vendor/node_modules/ssh2/test/test.js +20 -0
  206. package/lib/vendor/node_modules/ssh2/util/build_pagent.bat +2 -0
  207. package/lib/vendor/node_modules/ssh2/util/pagent.c +88 -0
  208. package/lib/vendor/node_modules/ssh2/util/pagent.exe +0 -0
  209. package/lib/vendor/node_modules/tweetnacl/AUTHORS.md +27 -0
  210. package/lib/vendor/node_modules/tweetnacl/CHANGELOG.md +283 -0
  211. package/lib/vendor/node_modules/tweetnacl/LICENSE +24 -0
  212. package/lib/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
  213. package/lib/vendor/node_modules/tweetnacl/README.md +494 -0
  214. package/lib/vendor/node_modules/tweetnacl/nacl-fast.js +2391 -0
  215. package/lib/vendor/node_modules/tweetnacl/nacl-fast.min.js +1 -0
  216. package/lib/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
  217. package/lib/vendor/node_modules/tweetnacl/nacl.js +1178 -0
  218. package/lib/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
  219. package/lib/vendor/node_modules/tweetnacl/package.json +56 -0
  220. package/lib/vendor/xterm.css +218 -0
  221. package/lib/vendor/xterm.js +2 -0
  222. package/locale/en.json +6 -0
  223. package/locale/zh.json +6 -0
  224. package/ops/watchdog/dsh-watchdog.ps1 +105 -0
  225. package/ops/watchdog/restart-now.ps1 +247 -0
  226. package/package.json +69 -4
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-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,354 @@
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-mobile\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()) => path.join(dshHome, 'integrations', 'dsh-mobile', 'terminal')
78
+
79
+ export const ensureKeyPair = (dir) => {
80
+ const key = path.join(dir, 'id_ed25519')
81
+ if (fs.existsSync(key) && fs.existsSync(key + '.pub')) return key
82
+ fs.mkdirSync(dir, { recursive: true })
83
+ const result = spawnSync(KEYGEN_EXE, ['-t', 'ed25519', '-N', '', '-C', 'dsh-mobile-terminal', '-f', key], {
84
+ encoding: 'utf8',
85
+ timeout: 20000,
86
+ windowsHide: true,
87
+ })
88
+ if (result.status !== 0) throw new Error('生成密钥失败:' + String(result.stderr ?? '').slice(0, 200))
89
+ return key
90
+ }
91
+
92
+ export const ensureSshd = async ({ dshHome = resolveDshHome(), startPort = 22222, maxTries = 30 } = {}) => {
93
+ const dir = terminalDir(dshHome)
94
+ fs.mkdirSync(dir, { recursive: true })
95
+ const key = ensureKeyPair(dir)
96
+ const hostKey = path.join(dir, 'host_ed25519')
97
+ if (!fs.existsSync(hostKey)) {
98
+ const gen = spawnSync(KEYGEN_EXE, ['-t', 'ed25519', '-N', '', '-f', hostKey], { encoding: 'utf8', timeout: 20000, windowsHide: true })
99
+ if (gen.status !== 0) throw new Error('生成 host key 失败:' + String(gen.stderr ?? '').slice(0, 200))
100
+ }
101
+ const authorized = path.join(dir, 'authorized_keys')
102
+ const pub = fs.readFileSync(key + '.pub', 'utf8').trim()
103
+ if (!fs.existsSync(authorized) || !fs.readFileSync(authorized, 'utf8').includes(pub)) {
104
+ fs.writeFileSync(authorized, pub + '\n', 'utf8')
105
+ }
106
+
107
+ const stateFile = path.join(dir, 'sshd.state.json')
108
+ try {
109
+ const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
110
+ if (state.port && (await canConnect(state.port))) return { port: state.port, started: false }
111
+ } catch {
112
+ // 没有状态文件
113
+ }
114
+
115
+ let port = null
116
+ for (let i = 0; i < maxTries; i += 1) {
117
+ const candidate = startPort + i
118
+ if (await portFree(candidate)) { port = candidate; break }
119
+ }
120
+ if (port === null) throw new Error('找不到空闲端口给 sshd')
121
+
122
+ const config = path.join(dir, 'sshd_config')
123
+ fs.writeFileSync(config, [
124
+ `Port ${port}`,
125
+ 'ListenAddress 127.0.0.1',
126
+ `HostKey ${hostKey.replaceAll('\\', '/')}`,
127
+ `AuthorizedKeysFile ${authorized.replaceAll('\\', '/')}`,
128
+ 'PasswordAuthentication no',
129
+ 'PubkeyAuthentication yes',
130
+ 'KbdInteractiveAuthentication no',
131
+ 'StrictModes no',
132
+ 'UseDNS no',
133
+ 'PermitRootLogin no',
134
+ `PidFile ${path.join(dir, 'sshd.pid').replaceAll('\\', '/')}`,
135
+ 'LogLevel INFO',
136
+ ].join('\r\n'), 'utf8')
137
+
138
+ const logFile = path.join(dir, 'sshd.log')
139
+ const child = spawn(SSHD_EXE, ['-D', '-f', config, '-E', logFile], {
140
+ windowsHide: true,
141
+ stdio: ['ignore', 'ignore', 'ignore'],
142
+ })
143
+ child.on('error', () => {})
144
+ const up = await waitFor(() => canConnect(port), 10000)
145
+ if (!up) throw new Error('sshd 启动失败,详见 ' + logFile)
146
+ fs.writeFileSync(stateFile, JSON.stringify({ port, pid: child.pid, startedAt: Date.now() }), 'utf8')
147
+ return { port, started: true }
148
+ }
149
+
150
+ /**
151
+ * 一个交互式 PTY 会话(ssh2 + 远端 bash)。
152
+ * 输出用带序号的环形缓冲保存,前端可用 since=<seq> 补发。
153
+ */
154
+ export class PtyTerminal {
155
+ constructor({ port, dshHome = resolveDshHome(), cwd = null, maxBuffered = 512 * 1024, cols = 80, rows = 24 } = {}) {
156
+ this.port = port
157
+ this.dshHome = dshHome
158
+ this.cwd = cwd
159
+ this.cols = cols
160
+ this.rows = rows
161
+ this.client = null
162
+ this.stream = null
163
+ this.maxBuffered = maxBuffered
164
+ this.chunks = []
165
+ this.seq = 0
166
+ this.bytes = 0
167
+ this.listeners = new Set()
168
+ this.closed = false
169
+ }
170
+
171
+ async start() {
172
+ if (this.stream !== null) return this
173
+ const ssh2 = loadSsh2()
174
+ if (ssh2 === null) throw new Error('ssh2 未找到(vendor/node_modules/ssh2)')
175
+ const dir = terminalDir(this.dshHome)
176
+ const privateKey = fs.readFileSync(path.join(dir, 'id_ed25519'))
177
+ const username = process.env.USERNAME ?? ''
178
+
179
+ const push = (chunk) => {
180
+ const text = chunk.toString('utf8')
181
+ this.seq += 1
182
+ this.chunks.push({ seq: this.seq, text })
183
+ this.bytes += text.length
184
+ while (this.bytes > this.maxBuffered && this.chunks.length > 1) {
185
+ const dropped = this.chunks.shift()
186
+ this.bytes -= dropped.text.length
187
+ }
188
+ for (const listener of this.listeners) {
189
+ try {
190
+ listener(text, this.seq)
191
+ } catch {
192
+ // 单个订阅者出错不影响别人
193
+ }
194
+ }
195
+ }
196
+
197
+ const client = new ssh2.Client()
198
+ this.client = client
199
+
200
+ await new Promise((resolve, reject) => {
201
+ const timer = setTimeout(() => reject(new Error('SSH 连接超时')), 15000)
202
+ client.on('ready', () => {
203
+ // 用 exec + pty 启动 Git Bash(client.shell() 会落到系统默认的 cmd.exe)
204
+ const command = '"C:/Program Files/Git/bin/bash.exe" -l'
205
+ client.exec(command, {
206
+ pty: { term: 'xterm-256color', cols: this.cols, rows: this.rows },
207
+ }, (error, stream) => {
208
+ clearTimeout(timer)
209
+ if (error) {
210
+ reject(error)
211
+ return
212
+ }
213
+ this.stream = stream
214
+ this.closed = false
215
+ stream.on('data', push)
216
+ stream.stderr.on('data', push)
217
+ stream.on('close', () => {
218
+ this.closed = true
219
+ push('\r\n[会话已结束]\r\n')
220
+ })
221
+ resolve()
222
+ })
223
+ })
224
+ client.on('error', (error) => {
225
+ clearTimeout(timer)
226
+ reject(error)
227
+ })
228
+ client.on('close', () => {
229
+ clearTimeout(timer)
230
+ this.closed = true
231
+ })
232
+ client.connect({
233
+ host: '127.0.0.1',
234
+ port: this.port,
235
+ username,
236
+ privateKey,
237
+ readyTimeout: 15000,
238
+ keepaliveInterval: 15000,
239
+ })
240
+ })
241
+
242
+ if (typeof this.cwd === 'string' && this.cwd !== '') this.changeDir(this.cwd)
243
+ return this
244
+ }
245
+
246
+ /** 往终端写(键盘输入、粘贴、Ctrl 组合键) */
247
+ write(data) {
248
+ if (this.stream === null || this.closed) return false
249
+ try {
250
+ this.stream.write(data)
251
+ return true
252
+ } catch {
253
+ return false
254
+ }
255
+ }
256
+
257
+ /**
258
+ * 改变远端 PTY 的窗口尺寸 —— 等价于拖拽 Git Bash 窗口。
259
+ * 走 SSH 的 window-change 通道消息,sshd 收到后会 ResizePseudoConsole。
260
+ */
261
+ resize(cols, rows) {
262
+ const nextCols = Math.max(20, Math.min(Number(cols) || 80, 400))
263
+ const nextRows = Math.max(5, Math.min(Number(rows) || 24, 200))
264
+ this.cols = nextCols
265
+ this.rows = nextRows
266
+ if (this.stream === null) return false
267
+ try {
268
+ this.stream.setWindow(nextRows, nextCols, 0, 0)
269
+ return true
270
+ } catch {
271
+ return false
272
+ }
273
+ }
274
+
275
+ /** 切换工作目录(会话是常驻的,所以只发一条 cd) */
276
+ changeDir(winPath) {
277
+ if (typeof winPath !== 'string' || winPath.trim() === '') return false
278
+ const match = /^([A-Za-z]):[\\/]?(.*)$/u.exec(winPath.trim())
279
+ const target = match === null
280
+ ? winPath.trim()
281
+ : '/' + match[1].toLowerCase() + (match[2] === '' ? '' : '/' + match[2].replaceAll('\\', '/'))
282
+ this.cwd = winPath.trim()
283
+ return this.write('cd "' + target.replaceAll('"', '\\"') + '"\r')
284
+ }
285
+
286
+ subscribe(listener) {
287
+ this.listeners.add(listener)
288
+ return () => this.listeners.delete(listener)
289
+ }
290
+
291
+ since(seq = 0) {
292
+ return this.chunks.filter((item) => item.seq > seq).map((item) => item.text).join('')
293
+ }
294
+
295
+ get latestSeq() {
296
+ return this.seq
297
+ }
298
+
299
+ get size() {
300
+ return { cols: this.cols, rows: this.rows }
301
+ }
302
+
303
+ stop() {
304
+ this.closed = true
305
+ try {
306
+ this.stream?.end()
307
+ this.stream?.destroy?.()
308
+ } catch {
309
+ // 已关闭
310
+ }
311
+ try {
312
+ this.client?.end()
313
+ this.client?.destroy?.()
314
+ } catch {
315
+ // 已关闭
316
+ }
317
+ this.stream = null
318
+ this.client = null
319
+ }
320
+ }
321
+
322
+ let sharedTerminal = null
323
+
324
+ export const sharedPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null } = {}) => {
325
+ const { port } = await ensureSshd({ dshHome })
326
+ if (sharedTerminal === null || sharedTerminal.closed) {
327
+ sharedTerminal = new PtyTerminal({ port, dshHome, cwd })
328
+ await sharedTerminal.start()
329
+ }
330
+ return sharedTerminal
331
+ }
332
+
333
+ export const resetPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null } = {}) => {
334
+ if (sharedTerminal !== null) sharedTerminal.stop()
335
+ sharedTerminal = null
336
+ return sharedPtyTerminal({ dshHome, cwd })
337
+ }
338
+
339
+ export const stopSshd = (dshHome = resolveDshHome()) => {
340
+ try {
341
+ const stateFile = path.join(terminalDir(dshHome), 'sshd.state.json')
342
+ const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
343
+ if (state.pid) {
344
+ // Windows 上用 taskkill 连子进程一起收:只 kill 父进程会留下 per-connection 的 sshd
345
+ const result = spawnSync('taskkill', ['/F', '/T', '/PID', String(state.pid)], { windowsHide: true, encoding: 'utf8' })
346
+ if (result.status !== 0) {
347
+ try { process.kill(state.pid) } catch { /* 已退出 */ }
348
+ }
349
+ }
350
+ fs.rmSync(stateFile, { force: true })
351
+ } catch {
352
+ // 没在跑
353
+ }
354
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * 常驻 shell 会话:让手机终端像真 bash 一样保留状态(cwd / 环境变量 / 函数)。
3
+ *
4
+ * 关键设计(踩过的坑写在这里):
5
+ * 1. 不用 PTY:Git Bash 自带的 winpty 在无控制台进程里断言失败;真 PTY 要 ConPTY + 原生模块。
6
+ * 2. 一个 bash 进程从 stdin 顺序读命令,命令前后打标记,一次往返拿到「输出 + 退出码 + $PWD」。
7
+ * 3. **子进程退出回调必须校验"我还当权吗"**:
8
+ * 旧进程的 exit 事件是异步投递的,若回调无条件把 this.child 置空,
9
+ * 会把刚重启的新进程引用清掉,导致"永远显示会话已退出"的假死循环。
10
+ */
11
+ import { spawn } from 'node:child_process'
12
+ import { findBash } from './shell.mjs'
13
+
14
+ /** Git Bash 的 /d/x 转回 D:\\x(Git Bash 也认 D:/x,所以转换后可直接 cd) */
15
+ function toWindowsPath(value) {
16
+ const text = String(value ?? '').trim()
17
+ // pwd -W 给的是 C:/Users/... 形式,统一成反斜杠,和 path.resolve 比较时不打架
18
+ if (/^[A-Za-z]:[\\/]/u.test(text)) return text.replaceAll('/', '\\')
19
+ const match = /^\/([A-Za-z])(?:\/(.*))?$/u.exec(text)
20
+ if (match === null) return text
21
+ const drive = match[1].toUpperCase()
22
+ const rest = (match[2] ?? '').replaceAll('/', '\\')
23
+ return rest === '' ? drive + ':\\' : drive + ':\\' + rest
24
+ }
25
+
26
+ const MAX_OUTPUT = 64 * 1024
27
+ const DEFAULT_TIMEOUT = 30_000
28
+
29
+ export class ShellSession {
30
+ constructor(cwd) {
31
+ // spawn 必须用 Windows 路径;bash 的 $PWD(/d/xxx)只用于显示
32
+ this.winCwd = cwd
33
+ this.cwd = cwd
34
+ this.child = null
35
+ this.queue = Promise.resolve()
36
+ this.startedAt = 0
37
+ this.commandCount = 0
38
+ this.buffer = ''
39
+ // 终端页的滚动记录(最近 100 条),页面刷新后还能看到上下文
40
+ this.transcript = []
41
+ }
42
+
43
+ get running() {
44
+ const child = this.child
45
+ return child !== null && child.exitCode === null && !child.killed
46
+ }
47
+
48
+ start() {
49
+ const bash = findBash()
50
+ if (bash === null) throw new Error('找不到 Git Bash')
51
+ const child = spawn(bash, ['--noprofile', '--norc'], {
52
+ cwd: this.winCwd,
53
+ env: {
54
+ ...process.env,
55
+ TERM: 'dumb',
56
+ PAGER: 'cat',
57
+ GIT_PAGER: 'cat',
58
+ GIT_TERMINAL_PROMPT: '0',
59
+ LANG: 'C.UTF-8',
60
+ },
61
+ stdio: ['pipe', 'pipe', 'pipe'],
62
+ windowsHide: true,
63
+ })
64
+ this.child = child
65
+ this.buffer = ''
66
+ this.startedAt = Date.now()
67
+ this.commandCount = 0
68
+
69
+ child.stdout.on('data', (chunk) => { this.buffer += chunk.toString('utf8') })
70
+ child.stderr.on('data', (chunk) => { this.buffer += chunk.toString('utf8') })
71
+ // 只清理"自己这一代"的引用:否则旧进程的退出事件会把新进程清掉
72
+ const clearIfCurrent = () => {
73
+ if (this.child === child) this.child = null
74
+ }
75
+ child.on('error', clearIfCurrent)
76
+ child.on('exit', clearIfCurrent)
77
+ return this
78
+ }
79
+
80
+ record(entry) {
81
+ this.transcript.push(entry)
82
+ if (this.transcript.length > 100) this.transcript.shift()
83
+ }
84
+
85
+ /**
86
+ * 中断当前命令(相当于 Ctrl+C)。
87
+ *
88
+ * 注意:bash 的 stdin 是管道而不是终端,写 \x03 不会产生 SIGINT信号,
89
+ * 所以这里直接杀掉 bash 进程(连同它启动的子进程树),再起一个新的。
90
+ * 代价是 cwd / 环境变量会被重置 —— 这和"卡死的命令必须停下来"相比是值得的。
91
+ */
92
+ interrupt() {
93
+ this.reset()
94
+ return { ok: true, code: null, output: '(已中断,会话已重启)', cwd: this.winCwd }
95
+ }
96
+
97
+ reset() {
98
+ this.kill()
99
+ this.start()
100
+ return this
101
+ }
102
+
103
+ kill() {
104
+ const child = this.child
105
+ this.child = null
106
+ try {
107
+ child?.kill()
108
+ } catch {
109
+ // 已退出
110
+ }
111
+ }
112
+
113
+ /** 串行执行(同一个 shell 不能并发写 stdin) */
114
+ run(command) {
115
+ const job = () => this.#runOnce(command)
116
+ this.queue = this.queue.then(job, job)
117
+ return this.queue
118
+ }
119
+
120
+ #runOnce(command) {
121
+ const text = String(command ?? '').trim()
122
+ if (text === '') return Promise.resolve({ ok: false, error: '命令为空', cwd: this.cwd })
123
+
124
+ // exit 会真的结束 shell:直接当作"重置会话",并如实返回退出码
125
+ const exitMatch = /^exit(?:\s+(\d+))?\s*$/u.exec(text)
126
+ if (exitMatch !== null) {
127
+ const code = exitMatch[1] === undefined ? 0 : Number(exitMatch[1])
128
+ this.reset()
129
+ return Promise.resolve({
130
+ ok: code === 0,
131
+ code,
132
+ output: '(会话已重启:环境变量清空,当前目录保持)',
133
+ cwd: this.cwd,
134
+ })
135
+ }
136
+
137
+ if (!this.running) this.start()
138
+
139
+ const id = `m${Math.random().toString(36).slice(2, 10)}`
140
+ const startTag = `<<${id}S>>`
141
+ const endTag = `<<${id}E:`
142
+ this.buffer = ''
143
+ this.child.stdin.write(`printf '${startTag}\\n'\n${text}\nprintf '${endTag}%s|%s>>\\n' "$?" "$(pwd -W 2>/dev/null || pwd)"\n`)
144
+ this.commandCount += 1
145
+
146
+ const started = Date.now()
147
+ return new Promise((resolve) => {
148
+ const timer = setInterval(() => {
149
+ const endIndex = this.buffer.indexOf(endTag)
150
+ if (endIndex >= 0) {
151
+ clearInterval(timer)
152
+ const after = this.buffer.slice(endIndex + endTag.length)
153
+ const closeIndex = after.indexOf('>>')
154
+ if (closeIndex < 0) return
155
+ const [codeText, cwdText] = after.slice(0, closeIndex).split('|')
156
+ const startIndex = this.buffer.indexOf(startTag)
157
+ const output = startIndex >= 0
158
+ ? this.buffer.slice(startIndex + startTag.length, endIndex).replace(/^\r?\n/u, '')
159
+ : this.buffer.slice(0, endIndex)
160
+ if (cwdText) {
161
+ this.cwd = cwdText
162
+ this.winCwd = toWindowsPath(cwdText)
163
+ }
164
+ const code = Number(codeText)
165
+ resolve({
166
+ ok: code === 0,
167
+ code,
168
+ output: output.length > MAX_OUTPUT
169
+ ? output.slice(0, MAX_OUTPUT)
170
+ : (output.trim() === '' ? '(无输出)' : output),
171
+ cwd: this.winCwd,
172
+ bashCwd: this.cwd,
173
+ truncated: output.length > MAX_OUTPUT,
174
+ })
175
+ return
176
+ }
177
+ if (Date.now() - started > DEFAULT_TIMEOUT) {
178
+ clearInterval(timer)
179
+ this.kill()
180
+ resolve({
181
+ ok: false,
182
+ code: null,
183
+ timeout: true,
184
+ output: this.buffer.slice(0, 2000) + '\n(超时 30 秒,会话已重启)',
185
+ cwd: this.winCwd,
186
+ })
187
+ }
188
+ }, 30)
189
+ })
190
+ }
191
+
192
+ info() {
193
+ return {
194
+ running: this.running,
195
+ cwd: this.winCwd,
196
+ bashCwd: this.cwd,
197
+ commands: this.commandCount,
198
+ transcript: this.transcript.slice(-100),
199
+ uptimeMs: this.startedAt === 0 ? 0 : Date.now() - this.startedAt,
200
+ }
201
+ }
202
+ }
203
+
204
+ let shared = null
205
+
206
+ export function sharedSession(cwd) {
207
+ if (shared === null || !shared.running) {
208
+ shared = new ShellSession(cwd)
209
+ shared.start()
210
+ }
211
+ return shared
212
+ }
213
+
214
+ export function resetSharedSession() {
215
+ if (shared !== null) shared.reset()
216
+ }