dsh-ssh-hub 0.0.0-stage → 0.2.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 (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +271 -2
  3. package/cordis.patch.yml +16 -0
  4. package/icon.svg +3 -0
  5. package/lib/client.js +13975 -0
  6. package/lib/index.js +6908 -0
  7. package/lib/types/activity/history.d.ts +50 -0
  8. package/lib/types/alerting/notify.d.ts +89 -0
  9. package/lib/types/alerting/prompt-summary.d.ts +28 -0
  10. package/lib/types/alerting/rules.d.ts +135 -0
  11. package/lib/types/alerting/tools.d.ts +30 -0
  12. package/lib/types/audit/audit-log.d.ts +84 -0
  13. package/lib/types/audit/recorder.d.ts +50 -0
  14. package/lib/types/client/api.d.ts +222 -0
  15. package/lib/types/client/index.d.ts +45 -0
  16. package/lib/types/client/locales.d.ts +319 -0
  17. package/lib/types/client/native-panel.d.ts +70 -0
  18. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  19. package/lib/types/client/panel/DeployTab.d.ts +10 -0
  20. package/lib/types/client/panel/FleetTab.d.ts +10 -0
  21. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  22. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  23. package/lib/types/client/panel/LogsTab.d.ts +10 -0
  24. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  25. package/lib/types/client/panel/TerminalTab.d.ts +27 -0
  26. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  27. package/lib/types/client/panel/TunnelEditDialog.d.ts +15 -0
  28. package/lib/types/client/panel/TunnelsTab.d.ts +27 -0
  29. package/lib/types/client/panel/controller.d.ts +253 -0
  30. package/lib/types/client/panel/helpers.d.ts +45 -0
  31. package/lib/types/client/panel/tabs.d.ts +62 -0
  32. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  33. package/lib/types/client/settings-binding.d.ts +71 -0
  34. package/lib/types/deploy/orchestrator.d.ts +158 -0
  35. package/lib/types/deploy/tools.d.ts +14 -0
  36. package/lib/types/dsh-home.d.ts +16 -0
  37. package/lib/types/engine/cluster.d.ts +19 -0
  38. package/lib/types/engine/connection-pool.d.ts +183 -0
  39. package/lib/types/engine/proxy-command.d.ts +36 -0
  40. package/lib/types/engine/pty.d.ts +32 -0
  41. package/lib/types/engine/sftp.d.ts +20 -0
  42. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  43. package/lib/types/engine/tunnel-discovery.d.ts +89 -0
  44. package/lib/types/engine/tunnel-remarks.d.ts +49 -0
  45. package/lib/types/engine/tunnel.d.ts +76 -0
  46. package/lib/types/engine.d.ts +103 -0
  47. package/lib/types/http.d.ts +59 -0
  48. package/lib/types/index.d.ts +128 -0
  49. package/lib/types/inspect/checks.d.ts +118 -0
  50. package/lib/types/inspect/inspection.d.ts +111 -0
  51. package/lib/types/inspect/tools.d.ts +50 -0
  52. package/lib/types/logs/search.d.ts +131 -0
  53. package/lib/types/logs/tools.d.ts +6 -0
  54. package/lib/types/loopback.d.ts +64 -0
  55. package/lib/types/monitor/loop.d.ts +133 -0
  56. package/lib/types/monitor/metrics.d.ts +151 -0
  57. package/lib/types/mount-once.d.ts +55 -0
  58. package/lib/types/protocol.d.ts +524 -0
  59. package/lib/types/routes.d.ts +82 -0
  60. package/lib/types/security/known-hosts.d.ts +153 -0
  61. package/lib/types/security/master-secret.d.ts +157 -0
  62. package/lib/types/security/redact.d.ts +44 -0
  63. package/lib/types/security/secrets.d.ts +70 -0
  64. package/lib/types/ssh-config.d.ts +42 -0
  65. package/lib/types/store.d.ts +183 -0
  66. package/lib/types/tool-surface.d.ts +72 -0
  67. package/lib/types/tools.d.ts +56 -0
  68. package/locale/en.json +6 -0
  69. package/locale/zh.json +6 -0
  70. package/package.json +126 -6
  71. package/src/activity/history.ts +117 -0
  72. package/src/alerting/notify.ts +212 -0
  73. package/src/alerting/prompt-summary.ts +71 -0
  74. package/src/alerting/rules.ts +281 -0
  75. package/src/alerting/tools.ts +263 -0
  76. package/src/audit/audit-log.ts +199 -0
  77. package/src/audit/recorder.ts +73 -0
  78. package/src/client/api.ts +782 -0
  79. package/src/client/css-modules.d.ts +5 -0
  80. package/src/client/index.ts +150 -0
  81. package/src/client/locales.ts +654 -0
  82. package/src/client/native-panel.tsx +141 -0
  83. package/src/client/panel/ClusterTab.tsx +141 -0
  84. package/src/client/panel/DeployTab.tsx +314 -0
  85. package/src/client/panel/FleetTab.tsx +494 -0
  86. package/src/client/panel/HostFormDialog.tsx +289 -0
  87. package/src/client/panel/HostsTab.tsx +395 -0
  88. package/src/client/panel/LogsTab.tsx +208 -0
  89. package/src/client/panel/SshPanel.tsx +105 -0
  90. package/src/client/panel/TerminalTab.tsx +550 -0
  91. package/src/client/panel/TransferTab.tsx +238 -0
  92. package/src/client/panel/TunnelEditDialog.tsx +174 -0
  93. package/src/client/panel/TunnelsTab.tsx +328 -0
  94. package/src/client/panel/controller.ts +507 -0
  95. package/src/client/panel/helpers.ts +84 -0
  96. package/src/client/panel/panel.module.css +1734 -0
  97. package/src/client/panel/tabs.ts +52 -0
  98. package/src/client/panel/xterm.css.ts +2 -0
  99. package/src/client/settings-binding.ts +184 -0
  100. package/src/deploy/orchestrator.ts +326 -0
  101. package/src/deploy/tools.ts +225 -0
  102. package/src/dsh-home.ts +42 -0
  103. package/src/engine/cluster.ts +60 -0
  104. package/src/engine/connection-pool.ts +721 -0
  105. package/src/engine/proxy-command.ts +248 -0
  106. package/src/engine/pty.ts +78 -0
  107. package/src/engine/sftp.ts +229 -0
  108. package/src/engine/terminal-sessions.ts +280 -0
  109. package/src/engine/tunnel-discovery.ts +353 -0
  110. package/src/engine/tunnel-remarks.ts +120 -0
  111. package/src/engine/tunnel.ts +300 -0
  112. package/src/engine.ts +195 -0
  113. package/src/http.ts +127 -0
  114. package/src/index.ts +690 -0
  115. package/src/inspect/checks.ts +251 -0
  116. package/src/inspect/inspection.ts +321 -0
  117. package/src/inspect/tools.ts +366 -0
  118. package/src/logs/search.ts +251 -0
  119. package/src/logs/tools.ts +160 -0
  120. package/src/loopback.ts +119 -0
  121. package/src/monitor/loop.ts +265 -0
  122. package/src/monitor/metrics.ts +333 -0
  123. package/src/mount-once.ts +142 -0
  124. package/src/protocol.ts +534 -0
  125. package/src/routes.ts +998 -0
  126. package/src/security/known-hosts.ts +342 -0
  127. package/src/security/master-secret.ts +334 -0
  128. package/src/security/redact.ts +119 -0
  129. package/src/security/secrets.ts +152 -0
  130. package/src/ssh-config.ts +182 -0
  131. package/src/store.ts +757 -0
  132. package/src/tool-surface.ts +96 -0
  133. package/src/tools.ts +550 -0
package/src/index.ts ADDED
@@ -0,0 +1,690 @@
1
+ /**
2
+ * dsh-ssh — host half. Mounts the SSH engine (persistent ssh2 connection
3
+ * pool, exec / PTY shell / SFTP / tunnels / cluster), the /api/dsh-ssh route
4
+ * family plus the terminal WebSocket upgrade, the agent tools (ssh_list,
5
+ * ssh_exec, ssh_upload, ssh_download, ssh_tunnel, ssh_cluster), and a
6
+ * system-prompt announcement. The browser half (./client) renders the host
7
+ * manager and web terminal. Everything rides official NPM SDK packages —
8
+ * no dsh source changes.
9
+ */
10
+
11
+ import type { Context, Fiber } from '@deepseek-ai/cordis'
12
+ import { readFileSync } from 'node:fs'
13
+ import z from '@deepseek-ai/schemastery'
14
+ import type {} from '@deepseek-ai/dsh-host-webserver'
15
+ import type {} from '@deepseek-ai/dsh-system-prompt'
16
+ import type {} from '@deepseek-ai/dsh-tools'
17
+ import type {} from '@deepseek-ai/cordis-plugin-timer'
18
+ import { SshEngine } from './engine.ts'
19
+ import { DEFAULT_CONNECT_TIMEOUT_MS } from './engine/connection-pool.ts'
20
+ import { makeRoutes } from './routes.ts'
21
+ import { HostStore, type SecretProtector } from './store.ts'
22
+ import { sshClusterTool, sshDownloadTool, sshExecTool, sshListTool, sshTunnelTool, sshUploadTool } from './tools.ts'
23
+ import { Inspector } from './inspect/inspection.ts'
24
+ import { findCheck } from './inspect/checks.ts'
25
+ import { hubInspectCatalogTool, hubInspectDiffTool, hubInspectTool, hubMonitorTool } from './inspect/tools.ts'
26
+ import { AlertEngine } from './alerting/rules.ts'
27
+ import { hubAlertRulesTool, hubAlertsTool, hubAlertTestTool, defaultRules, type AlertEvent } from './alerting/tools.ts'
28
+ import { notifyAll, type NotifyChannel } from './alerting/notify.ts'
29
+ import { renderAlertSummary } from './alerting/prompt-summary.ts'
30
+ import { hubDeployTool } from './deploy/tools.ts'
31
+ import { hubLogSearchTool } from './logs/tools.ts'
32
+ import { Monitor } from './monitor/loop.ts'
33
+ import { MetricStore, samplesFromRound } from './monitor/metrics.ts'
34
+ import type { DeployRunRow, LogSearchRow } from './protocol.ts'
35
+ import { mountOnce } from './mount-once.ts'
36
+ import { PLUGIN_TOOL_SECTION_ORDERS, visibleToolText } from './tool-surface.ts'
37
+ import { defaultKnownHostsPath } from './security/known-hosts.ts'
38
+ import { isSealed, open, seal } from './security/secrets.ts'
39
+ import {
40
+ SECRET_ENV,
41
+ SECRET_FILE_ENV,
42
+ defaultKeyPath,
43
+ findPlaintextEntries,
44
+ generateSecret,
45
+ masterSecretSource,
46
+ readMasterSecret,
47
+ removeMasterKey,
48
+ rotateSecrets,
49
+ writeMasterKey,
50
+ } from './security/master-secret.ts'
51
+ import { ActivityHistory } from './activity/history.ts'
52
+ import { dshHome } from './dsh-home.ts'
53
+ import { join } from 'node:path'
54
+ import { AuditLog } from './audit/audit-log.ts'
55
+ import { AuditRecorder } from './audit/recorder.ts'
56
+
57
+ /** Stable cordis plugin name. */
58
+ export const name = 'ssh'
59
+
60
+ /**
61
+ * Services required before the SSH surfaces can mount.
62
+ *
63
+ * `timer` is required rather than optional: the monitoring loop is armed
64
+ * through it, and a plugin that silently fell back to a bare setInterval
65
+ * would leave a probe timer running after the plugin unloaded. Requiring it
66
+ * makes a profile without the timer service fail to activate this row
67
+ * instead of leaking timers.
68
+ */
69
+ export const inject = ['webServer', 'tools', 'systemPrompt', 'timer']
70
+
71
+ declare module '@deepseek-ai/cordis' {
72
+ interface Events {
73
+ /**
74
+ * Volatile config values were committed into the running instance without a
75
+ * remount (cordis-plugin-loader); dispatched to the owning fiber only.
76
+ * @param paths - the changed config paths, as key arrays.
77
+ * @mode emit
78
+ */
79
+ 'loader/volatile-update'(paths: readonly (readonly string[])[]): void
80
+ }
81
+ }
82
+
83
+ /** Plugin config as a profile patch declares it, before schema resolution. */
84
+ export interface Config {
85
+ /**
86
+ * When true, a system-prompt section announces the SSH plugin to every agent
87
+ * (tools + host store). Off by default to keep prompts clean.
88
+ */
89
+ announceToAgent?: boolean
90
+ /** Master switch for the plugin (routes, tools, prompt section). */
91
+ enabled?: boolean
92
+ /**
93
+ * xterm `fontFamily` for the web terminal (issue #577). Empty (default)
94
+ * defers to the CSS chain: `--dsh-ssh-terminal-font`, then the official
95
+ * `--ds-font-family-code` token, then the built-in monospace stack. Set a
96
+ * Nerd Font stack here to render powerline/Nerd glyphs.
97
+ */
98
+ terminalFontFamily?: string
99
+ /**
100
+ * Ceiling for the whole pre-ready SSH sequence in milliseconds: TCP
101
+ * connect, key exchange and user authentication (default 30000). Raise it
102
+ * for hosts whose password authentication is slow (for example PAM / LDAP
103
+ * behind a distant directory service).
104
+ */
105
+ connectTimeoutMs?: number
106
+ }
107
+
108
+ /** The stable reference a `volatile()` config field resolves to; its owner updates it in place. */
109
+ interface ConfigRef<T> {
110
+ /** @returns the field's current value. */
111
+ get(): T
112
+ }
113
+
114
+ /** One resolved config field: a live reference, or a plain value from a hand-built context. */
115
+ type ConfigField<T> = ConfigRef<T> | T
116
+
117
+ /** The config the Host hands to {@link apply} — the runtime face of {@link Config}. */
118
+ export interface ResolvedConfig {
119
+ announceToAgent?: ConfigField<boolean>
120
+ enabled?: ConfigField<boolean>
121
+ terminalFontFamily?: ConfigField<string>
122
+ connectTimeoutMs?: ConfigField<number>
123
+ hostKeyPolicy?: ConfigField<'off' | 'tofu' | 'strict'>
124
+ knownHostsPath?: ConfigField<string>
125
+ encryptCredentials?: ConfigField<boolean>
126
+ auditEnabled?: ConfigField<boolean>
127
+ monitorEnabled?: ConfigField<boolean>
128
+ monitorIntervalMs?: ConfigField<number>
129
+ monitorChecks?: ConfigField<string>
130
+ }
131
+
132
+ /**
133
+ * Plugin config schema. Under the 0.1.7 settings model this schema IS the
134
+ * entry's settings page: the Host derives one form per profile entry from it
135
+ * and serves it through the shared configuration forms. Every field is
136
+ * `volatile()`, which is what puts it on that page and what lets an edit reach
137
+ * a running instance without a remount: the loader commits the new value into
138
+ * the field's reference and announces `loader/volatile-update` on this fiber.
139
+ */
140
+ export const Config = z.object({
141
+ announceToAgent: z.boolean().default(false).volatile(),
142
+ enabled: z.boolean().default(true).volatile(),
143
+ terminalFontFamily: z.string().default('').volatile(),
144
+ connectTimeoutMs: z.number().step(1).min(1_000).max(600_000).default(DEFAULT_CONNECT_TIMEOUT_MS).volatile()
145
+ .description('TCP connect, SSH key exchange and user authentication timeout in milliseconds; raise it for hosts whose authentication is slow.'),
146
+ hostKeyPolicy: z.union(['off', 'tofu', 'strict'] as const).default('off').volatile()
147
+ .description('Host-key verification against ~/.ssh/known_hosts. "off" accepts any key (the legacy behaviour); "tofu" records an unknown host and refuses a changed key; "strict" refuses anything not already trusted. A changed or revoked key is refused under every policy.'),
148
+ knownHostsPath: z.string().default('').volatile()
149
+ .description('Path to the known_hosts file used for host-key verification. Empty uses ~/.ssh/known_hosts.'),
150
+ encryptCredentials: z.boolean().default(false).volatile()
151
+ .description('Encrypt stored passwords and key passphrases. Needs DSH_SSH_HUB_SECRET in the environment as the master secret; there is deliberately no default, because a default master secret is a backdoor. With no master secret the secrets stay in plaintext, exactly as before.'),
152
+ auditEnabled: z.boolean().default(true).volatile()
153
+ .description('Record every operation (exec, cluster, transfer, deploy, credential change) in an append-only audit log under $DSH_HOME/dsh-ssh-hub/audit.log. Secrets are redacted before a record is written.'),
154
+ monitorEnabled: z.boolean().default(false).volatile()
155
+ .description('Run fleet inspection on a timer and feed the alert rules. Off by default: a monitoring loop that starts probing servers the moment the plugin is enabled is a surprise, and the operator should choose when the fleet starts being watched. Requires at least one configured host.'),
156
+ monitorIntervalMs: z.number().step(1000).min(10_000).max(3_600_000).default(60_000).volatile()
157
+ .description('How often the monitor runs an inspection round, in milliseconds. Default 60s. A round that outlasts the interval skips the next tick rather than running two rounds at once.'),
158
+ monitorChecks: z.string().default('').volatile()
159
+ .description('Comma-separated check ids the monitor runs (default: all built-in checks). Empty means every check; call hub_inspect_catalog for the ids.'),
160
+ })
161
+
162
+ /** Schema defaults, re-read for hand-built test contexts (the loader applies them normally). */
163
+ const DEFAULT_ANNOUNCE = false
164
+ const DEFAULT_ENABLED = true
165
+
166
+ /** Read one resolved config field, following the live reference the schema produces. */
167
+ function readConfigField<T>(field: ConfigField<T> | undefined, fallback: T): T {
168
+ if (field === undefined) return fallback
169
+ if (typeof field === 'object' && field !== null && typeof (field as ConfigRef<T>).get === 'function') {
170
+ const value = (field as ConfigRef<T>).get()
171
+ return value === undefined ? fallback : value
172
+ }
173
+ return field as T
174
+ }
175
+
176
+ /**
177
+ * Parse the comma-separated check list config.
178
+ *
179
+ * An empty string means "all checks", not "no checks": an operator who
180
+ * cleared the field wants the default set, and running zero checks on a
181
+ * timer would be a monitor that watches nothing.
182
+ *
183
+ * @param raw - the config string.
184
+ * @returns the check ids, or undefined for "all".
185
+ */
186
+ function parseCheckList(raw: string): string[] | undefined {
187
+ const ids = raw.split(',').map(id => id.trim()).filter(id => id !== '')
188
+ return ids.length === 0 ? undefined : ids
189
+ }
190
+
191
+ /**
192
+ * The master secret used to encrypt stored credentials.
193
+ *
194
+ * Two sources, in priority order:
195
+ *
196
+ * 1. `DSH_SSH_HUB_SECRET` — the secret itself in the environment.
197
+ * 2. `DSH_SSH_HUB_SECRET_FILE` — a path to a file containing the secret.
198
+ *
199
+ * The second exists because the first is a poor fit for a long-running
200
+ * desktop profile: an environment variable has to be set in whatever
201
+ * launches DSH, which means it lands in shell profiles and shortcut
202
+ * properties, where it is readable by anything running as the same user and
203
+ * gets copied into screenshots of the launcher. A 0600 file is easier to
204
+ * protect and easier to back up.
205
+ *
206
+ * Neither is a default. With no secret configured the store keeps
207
+ * plaintext, which is exactly what the operator chose by not configuring
208
+ * one; a built-in default key would be a backdoor, not a convenience.
209
+ *
210
+ * The DSH credentials service was the intended third source, but it is an
211
+ * async service and this plugin's apply is synchronous, and reading an
212
+ * undeclared service off the context throws at mount time. A secret that
213
+ * cannot be read at mount time cannot protect a store that is opened at
214
+ * mount time.
215
+ *
216
+ * A third source exists now: the key file the panel writes, at
217
+ * `<dsh home>/dsh-ssh-master.key`. It is consulted only when neither
218
+ * environment variable names a secret, so an explicit environment
219
+ * configuration always wins over a file the plugin created.
220
+ *
221
+ * @param keyPath - the key file the panel manages.
222
+ * @returns the master secret, or undefined when none is configured.
223
+ */
224
+ function resolveMasterSecret(keyPath: string): string | undefined {
225
+ return readMasterSecret(keyPath)
226
+ }
227
+
228
+ /**
229
+ * Describe where the master secret came from, for the settings panel.
230
+ *
231
+ * The panel must be able to tell an operator *whether* encryption is active
232
+ * and *why not* — "encryptCredentials is on but nothing is encrypted" is
233
+ * the single most confusing state this plugin can present.
234
+ *
235
+ * @param keyPath - the key file the panel manages.
236
+ * @returns the source label and whether a secret is available.
237
+ */
238
+ function masterSecretStatus(keyPath: string): { available: boolean; source: 'env' | 'file' | 'none' } {
239
+ const source = masterSecretSource(keyPath)
240
+ return { available: source !== 'none', source }
241
+ }
242
+
243
+ /**
244
+ * The known_hosts file to consult.
245
+ *
246
+ * @param configured - the configured path (empty means the default).
247
+ * @returns the resolved path.
248
+ */
249
+ function resolveKnownHostsPath(configured: string): string {
250
+ return configured.trim() === '' ? defaultKnownHostsPath() : configured.trim()
251
+ }
252
+
253
+ /**
254
+ * The loader's own record of the profile entry this instance was activated
255
+ * from, which carries the row's raw config — the user's own declaration, as
256
+ * opposed to the schema defaults and the inherited bundle layers. Absent on a
257
+ * host without the loader, which reads as "the profile declares nothing".
258
+ */
259
+ interface LoaderEntry {
260
+ options?: { config?: unknown }
261
+ }
262
+
263
+ /** Raw config the profile declares for this entry, when the loader exposes it. */
264
+ function profileConfig(ctx: Context): Record<string, unknown> | undefined {
265
+ const entry = (ctx.fiber as Fiber & { entry?: LoaderEntry }).entry
266
+ const config = entry?.options?.config
267
+ if (typeof config !== 'object' || config === null || Array.isArray(config)) return undefined
268
+ return config as Record<string, unknown>
269
+ }
270
+
271
+ /** Order of the announcement section within the shared tool-guidance band. */
272
+ const SECTION_ORDER = PLUGIN_TOOL_SECTION_ORDERS.ssh
273
+
274
+ /**
275
+ * The twelve agent-tool names this plugin's announcement describes.
276
+ *
277
+ * The first six are the base plugin's; the rest are the fleet-operations
278
+ * layer added here.
279
+ */
280
+ const SSH_TOOL_NAMES = [
281
+ 'ssh_list', 'ssh_exec', 'ssh_upload', 'ssh_download', 'ssh_tunnel', 'ssh_cluster',
282
+ 'hub_inspect', 'hub_inspect_catalog', 'hub_inspect_diff', 'hub_monitor',
283
+ 'hub_alerts', 'hub_alert_rules', 'hub_alert_test',
284
+ 'hub_deploy', 'hub_log_search',
285
+ ] as const
286
+
287
+ /** Model-facing announcement: plugin presence, capabilities, and limits. */
288
+ export const SSH_GUIDANCE = [
289
+ '本机已安装 dsh-ssh-hub 插件(DSH 远程 SSH 车队运维):侧边栏「SSH」入口。',
290
+ '能力:主机配置存 $DSH_HOME/dsh-ssh.json(默认 ~/.dsh),可从 ~/.ssh/config 导入;',
291
+ '持久连接池复用长连接(空闲 30 分钟自动断开);',
292
+ 'ssh_list 列出主机、ssh_exec 执行远程命令、ssh_upload/ssh_download 传输文件、',
293
+ 'ssh_tunnel 本地端口转发、ssh_cluster 按 aliases/environment/tags 至少一种非空 selector 集群并发执行;',
294
+ 'hub_inspect 运行内置巡检项(磁盘/负载/内存/inode/运行时长/sshd/失败单元/内核)并留存本轮结果,',
295
+ 'hub_inspect_diff 对比上一轮找出变化(值漂移、新增超限、已恢复),hub_inspect_catalog 列出巡检项,',
296
+ 'hub_monitor 报告定时监控是否在跑(监控未启动时告警列表为空并不代表机群健康);',
297
+ 'hub_alerts 查看告警状态与事件、hub_alert_rules 调整规则、hub_alert_test 测试通知渠道;',
298
+ 'hub_deploy 分批部署并做健康检查、失败自动回滚、跳过未部署主机;',
299
+ 'hub_log_search 跨机检索 journald 或日志目录,结果按主机限量并提示截断。',
300
+ '内置巡检项均为只读 POSIX 命令,不在远程安装任何东西。',
301
+ '限制:主机操作由用户在 GUI 中配置后 agent 方可使用;',
302
+ '凭据在配置了 DSH_SSH_HUB_SECRET 时以 AES-256-GCM 加密落盘,未配置时保持明文(插件会提示不要在无密钥时保存密码);',
303
+ '主机指纹可按 hostKeyPolicy=tofu/strict 对照 known_hosts 校验;',
304
+ '命令输出在返回前经脱敏(密码/token/私钥/连接串/云密钥),但脱敏是安全网不是保证;',
305
+ '断线重连可能重放非幂等命令;传输/执行消耗真实远程资源,先确认再操作。',
306
+ '路径区分:本机(dsh host)上的文件与命令一律用本地工具(read / write / edit / bash),ssh_* 工具只针对远程主机上的路径。',
307
+ '用户提到「SSH / 远程服务器 / 服务器操作 / 跳板机 / 隧道 / 部署 / 巡检 / 告警 / 日志检索 / 上传下载」时即指本插件,请据此协作。',
308
+ ].join('')
309
+
310
+ /**
311
+ * Mount the SSH engine, routes, tools, and announcement.
312
+ *
313
+ * The mount guard keys on THIS package's identity, not the upstream one:
314
+ * both plugins register the same HTTP route prefix and the same sidebar
315
+ * row, so they must never share a mount slot — and if an operator has both
316
+ * installed, only one of them may own the routes.
317
+ *
318
+ * @param ctx - host plugin context carrying webServer/tools/systemPrompt.
319
+ * @param config - resolved plugin config (schema defaults applied by the loader).
320
+ */
321
+ export const apply = mountOnce('dsh-ssh-hub', applyImpl)
322
+
323
+ function applyImpl(ctx: Context, config?: ResolvedConfig): void {
324
+ // The master secret for credential encryption. There is deliberately no
325
+ // default: a default master secret would be a backdoor, and falling back
326
+ // to plaintext would defeat the point of encrypting at all. With no
327
+ // secret configured the store keeps the base plugin's plaintext
328
+ // behaviour, so enabling encryption is a deliberate act.
329
+ // The key file the panel writes. Resolved once at mount: the panel's
330
+ // secret route reports the file it would write, so the two must name the
331
+ // same path.
332
+ const keyPath = defaultKeyPath(dshHome())
333
+ const encryptCredentials = readConfigField(config?.encryptCredentials, false)
334
+
335
+ /**
336
+ * Is encryption active right now?
337
+ *
338
+ * Two ways to consent, because there are two ways to configure a key:
339
+ * - `encryptCredentials` plus an environment/file secret, the original path;
340
+ * - a key the operator set through the panel, which is itself the consent.
341
+ *
342
+ * The second matters: without it, setting a key in the panel would write a
343
+ * file and change nothing, leaving the operator staring at "encryption
344
+ * configured, nothing encrypted" — the exact state this feature exists to
345
+ * end. A stray environment variable still cannot rewrite the store, because
346
+ * it needs the explicit config flag.
347
+ *
348
+ * @returns whether credentials should be sealed.
349
+ */
350
+ const encryptionActive = (): boolean => {
351
+ const source = masterSecretSource(keyPath)
352
+ if (source === 'none') return false
353
+ // A key file this plugin manages is the panel's own consent.
354
+ const panelKey = source === 'file'
355
+ && (process.env[SECRET_FILE_ENV] === undefined || process.env[SECRET_FILE_ENV] === '')
356
+ return encryptCredentials || panelKey
357
+ }
358
+
359
+ /**
360
+ * A protector that reads the live secret on every operation.
361
+ *
362
+ * The secret is resolved per call rather than captured at mount, so setting
363
+ * or rotating it from the panel takes effect on the next store write without
364
+ * a restart. A protector captured once would keep sealing with the old key
365
+ * after a rotation and lock the operator out of their own credentials.
366
+ */
367
+ const protector: SecretProtector = {
368
+ seal: (plaintext) => {
369
+ const secret = resolveMasterSecret(keyPath)
370
+ if (secret === undefined || !encryptionActive()) return plaintext
371
+ return seal(plaintext, secret)
372
+ },
373
+ open: (stored) => {
374
+ if (!isSealed(stored)) return undefined
375
+ const secret = resolveMasterSecret(keyPath)
376
+ // A sealed value with no key is unreadable, and saying so is better than
377
+ // returning the envelope as if it were the password.
378
+ if (secret === undefined) return undefined
379
+ return open(stored, secret)
380
+ },
381
+ }
382
+
383
+ const store = new HostStore(undefined, undefined, protector)
384
+ const engine = new SshEngine(store, {
385
+ connectTimeoutMs: readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS),
386
+ hostKeyPolicy: readConfigField(config?.hostKeyPolicy, 'off'),
387
+ knownHostsPath: resolveKnownHostsPath(readConfigField(config?.knownHostsPath, '')),
388
+ })
389
+ ctx.effect(() => () => { engine.dispose() }, 'dsh-ssh: engine')
390
+
391
+ // The audit trail: every mutation of the fleet and every command that
392
+ // changes a remote host is recorded. It is on by default, because an
393
+ // operator cannot retroactively decide to have had an audit log.
394
+ const audit = readConfigField(config?.auditEnabled, true) ? new AuditLog() : undefined
395
+
396
+ // The inspection layer: retained rounds of the built-in fleet checks.
397
+ const inspector = new Inspector()
398
+
399
+ // The alerting layer: rule state plus the recent event feed.
400
+ const alertEngine = new AlertEngine()
401
+ const alertRules = defaultRules()
402
+ const alertEvents: AlertEvent[] = []
403
+ const notifyChannels: NotifyChannel[] = []
404
+
405
+ // The metric store: tiered history behind the inspection rounds.
406
+ const metricStore = new MetricStore()
407
+
408
+ // Operator-action history: deployment runs and cross-host log searches.
409
+ // Both outlive the panel session that produced them, which is the point —
410
+ // "what did that rollout do" is asked after the fact.
411
+ const hubHome = join(dshHome(), 'dsh-ssh-hub')
412
+ const deployHistory = new ActivityHistory<DeployRunRow>(hubHome, 'deploys')
413
+ const logHistory = new ActivityHistory<LogSearchRow>(hubHome, 'logs')
414
+
415
+ // The monitoring loop: inspection on a timer, feeding the alert rules.
416
+ // It is created unconditionally but only armed when the config asks for
417
+ // it, so the status route can report "configured but off" rather than
418
+ // making the panel guess why nothing is happening.
419
+ const monitor = new Monitor(
420
+ engine,
421
+ inspector,
422
+ alertEngine,
423
+ alertEvents,
424
+ {
425
+ intervalMs: readConfigField(config?.monitorIntervalMs, 60_000),
426
+ checks: parseCheckList(readConfigField(config?.monitorChecks, '')),
427
+ rules: alertRules,
428
+ targets: () => store.list().map(host => host.alias),
429
+ },
430
+ async (notification) => {
431
+ await notifyAll(notifyChannels, notification, {
432
+ '#RULE.NAME#': notification.title,
433
+ '#STATE#': notification.kind === 'trigger' ? '告警' : '已恢复',
434
+ '#MESSAGE#': `${notification.alias} ${notification.title}: ${notification.kind === 'trigger' ? '告警' : '已恢复'} (${notification.value})`,
435
+ })
436
+ },
437
+ )
438
+
439
+ // Every completed round feeds the metric store, so the history tiers stay
440
+ // current whether the round came from the timer or from a hub_inspect call.
441
+ inspector.onRound = (round) => {
442
+ for (const alias of round.targets) {
443
+ const results = round.results.filter(result => result.alias === alias)
444
+ if (results.length === 0) continue
445
+ metricStore.record(alias, samplesFromRound(round.startedAt, results, checkId => findCheck(checkId)?.kind))
446
+ }
447
+ }
448
+
449
+ const resolve = (): { announceToAgent: boolean; enabled: boolean } => {
450
+ let enabled = readConfigField(config?.enabled, DEFAULT_ENABLED)
451
+ // When dsh-ssh was seeded with enabled: false (e.g. from an aggregate profile
452
+ // line), but the profile's own entry config never set the switch AND the user
453
+ // already has active host records in dsh-ssh.json, keep the plugin enabled so
454
+ // existing users are not broken upon upgrade (#1250).
455
+ if (enabled === false && profileConfig(ctx)?.enabled === undefined && store.list().length > 0) {
456
+ enabled = true
457
+ }
458
+ return {
459
+ announceToAgent: readConfigField(config?.announceToAgent, DEFAULT_ANNOUNCE),
460
+ enabled,
461
+ }
462
+ }
463
+
464
+ // The /api/dsh-ssh route family + terminal upgrade.
465
+ const { routes, upgrade, terminalSessions } = makeRoutes({
466
+ store,
467
+ engine,
468
+ monitor,
469
+ metrics: metricStore,
470
+ inspector,
471
+ alerts: alertEngine,
472
+ alertEvents,
473
+ security: () => ({
474
+ // The effective state, not just the config switch. A panel key makes
475
+ // encryption active on its own, and reporting the switch alone would
476
+ // show "encryption off" while the store is in fact encrypted — the
477
+ // single most confusing state this plugin can present.
478
+ encryptConfigured: encryptionActive(),
479
+ secret: masterSecretStatus(keyPath),
480
+ hostKeyPolicy: readConfigField(config?.hostKeyPolicy, 'off'),
481
+ auditEnabled: readConfigField(config?.auditEnabled, true),
482
+ }),
483
+ // The panel's secret management: status of the plaintext side, plus the
484
+ // two mutating operations. Each is a callback so the route always reads
485
+ // the live store rather than a snapshot taken at mount.
486
+ keyPath,
487
+ plaintext: () => findPlaintextEntries(store.path),
488
+ deployHistory,
489
+ logHistory,
490
+ setSecret: (payload) => {
491
+ if (payload.action === 'clear') {
492
+ // Deleting the key while anything is sealed would leave every stored
493
+ // credential unreadable. Refuse unless the operator explicitly accepts
494
+ // that, which is what confirmPlaintext carries.
495
+ const stillPlaintext = findPlaintextEntries(store.path).aliases
496
+ if (stillPlaintext.length === 0 && payload.confirmPlaintext !== true) {
497
+ return {
498
+ ok: false,
499
+ source: masterSecretSource(keyPath),
500
+ rotated: 0,
501
+ error: 'clearing the key would make every encrypted credential unreadable; decrypt or re-enter them first, then pass confirmPlaintext',
502
+ }
503
+ }
504
+ const removed = removeMasterKey(keyPath)
505
+ return {
506
+ ok: removed.ok,
507
+ source: masterSecretSource(keyPath),
508
+ rotated: 0,
509
+ ...(removed.error === undefined ? {} : { error: removed.error }),
510
+ }
511
+ }
512
+ const next = typeof payload.secret === 'string' && payload.secret.length > 0
513
+ ? payload.secret
514
+ : generateSecret()
515
+ const current = resolveMasterSecret(keyPath)
516
+ const hadKey = masterSecretSource(keyPath) === 'file'
517
+ const wasActive = encryptionActive()
518
+ // Plaintext entries must be sealed by this call, otherwise setting a key
519
+ // changes nothing on disk and the panel keeps reporting plaintext
520
+ // credentials — the confusing state this whole feature exists to end.
521
+ const plaintextBefore = findPlaintextEntries(store.path).aliases
522
+
523
+ // Case 1: rotating an existing key. Verify + reseal under the new secret
524
+ // with the new key committed mid-way, so a failure leaves the file
525
+ // readable with the key that is on disk.
526
+ if (current !== undefined && current !== next && wasActive) {
527
+ const rotated = rotateSecrets(store, current, next, secret => writeMasterKey(keyPath, secret, true))
528
+ return {
529
+ ok: rotated.ok,
530
+ source: masterSecretSource(keyPath),
531
+ rotated: rotated.rotated,
532
+ ...(rotated.error === undefined ? {} : { error: rotated.error }),
533
+ }
534
+ }
535
+
536
+ // Case 2: first key, or rotating a key that was not active. Write the key
537
+ // first; the live protector reads it on the next operation.
538
+ const written = writeMasterKey(keyPath, next, hadKey)
539
+ if (!written.ok) {
540
+ return {
541
+ ok: false,
542
+ source: masterSecretSource(keyPath),
543
+ rotated: 0,
544
+ error: written.error ?? 'the key file could not be written',
545
+ }
546
+ }
547
+ // Re-seal whatever is still plaintext, under the key that is now on disk.
548
+ let rotated = 0
549
+ if (plaintextBefore.length > 0) {
550
+ try {
551
+ const entries = store.list()
552
+ store.resealAll(entries)
553
+ rotated = entries.length
554
+ } catch (error) {
555
+ // The key exists but sealing failed: report it rather than claiming
556
+ // success, and leave the plaintext store intact (it is still usable).
557
+ return {
558
+ ok: false,
559
+ source: masterSecretSource(keyPath),
560
+ rotated: 0,
561
+ error: `the key was stored but existing credentials could not be re-encrypted: ${error instanceof Error ? error.message : String(error)}`,
562
+ }
563
+ }
564
+ }
565
+ return { ok: true, source: masterSecretSource(keyPath), rotated }
566
+ },
567
+ })
568
+ let disposeRoutes: (() => void) | undefined
569
+ let disposeMonitor: (() => void) | undefined
570
+
571
+ // Agent tools + their prompt sections.
572
+ const recorder = new AuditRecorder(audit)
573
+ const tools = [
574
+ sshListTool(engine),
575
+ sshExecTool(engine, recorder),
576
+ sshUploadTool(engine, recorder),
577
+ sshDownloadTool(engine, recorder),
578
+ sshTunnelTool(engine, recorder),
579
+ sshClusterTool(engine, recorder),
580
+ hubInspectTool(engine, inspector),
581
+ hubInspectCatalogTool(),
582
+ hubMonitorTool(monitor),
583
+ hubInspectDiffTool(inspector),
584
+ hubAlertsTool(alertEngine, alertEvents),
585
+ hubAlertRulesTool(alertRules),
586
+ hubAlertTestTool(notifyChannels),
587
+ hubDeployTool(engine, recorder),
588
+ hubLogSearchTool(engine),
589
+ ]
590
+ let disposeTools: (() => void) | undefined
591
+
592
+ // System-prompt announcement.
593
+ let disposeSection: (() => void) | undefined
594
+
595
+ // Register (or drop) every surface to match the resolved config. Each group
596
+ // is kept under one disposer: re-registering first tears the old one down
597
+ // so duplicate-name registrations never throw.
598
+ const sync = (): void => {
599
+ // A settings edit reaches this instance without a remount; apply the
600
+ // connection ceiling before re-deriving the surfaces so connections opened
601
+ // by the request that follows use the new value.
602
+ engine.setConnectTimeout(readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS))
603
+ const value = resolve()
604
+ if (disposeSection !== undefined) {
605
+ disposeSection()
606
+ disposeSection = undefined
607
+ }
608
+ if (disposeRoutes !== undefined) {
609
+ disposeRoutes()
610
+ disposeRoutes = undefined
611
+ }
612
+ if (disposeTools !== undefined) {
613
+ disposeTools()
614
+ disposeTools = undefined
615
+ }
616
+ // The loop is stopped before the surfaces are re-derived, so a settings
617
+ // edit cannot leave the old interval running alongside a new one (two
618
+ // timers would double every probe against the fleet).
619
+ if (disposeMonitor !== undefined) {
620
+ disposeMonitor()
621
+ disposeMonitor = undefined
622
+ }
623
+ if (!value.enabled) return
624
+ if (value.announceToAgent) {
625
+ const guidance = visibleToolText(ctx.tools, SSH_TOOL_NAMES, SSH_GUIDANCE)
626
+ disposeSection = ctx.systemPrompt.section({
627
+ name: 'plugin:dsh-ssh',
628
+ order: SECTION_ORDER,
629
+ // The announcement names the ssh_* tools, so it renders only while at
630
+ // least one of them is reachable: a restriction that removes the tool
631
+ // surface must take the guidance with it, instead of telling the model
632
+ // to call tools this session cannot see.
633
+ //
634
+ // The live alert summary is appended to the same section rather than
635
+ // registered as a second one: it is the same subject, and a separate
636
+ // section would need its own ordering decision and its own visibility
637
+ // gate for no benefit.
638
+ text: (context) => {
639
+ const base = guidance(context)
640
+ if (base === '') return ''
641
+ // A quiet fleet adds nothing. An empty list is only meaningful when
642
+ // something is actually watching, which `renderAlertSummary` states
643
+ // explicitly rather than leaving the model to infer health from
644
+ // silence.
645
+ const summary = renderAlertSummary(alertEngine, monitor)
646
+ return summary === '' ? base : `${base}\n\n${summary}`
647
+ },
648
+ })
649
+ }
650
+ disposeRoutes = ctx.effect(
651
+ () => {
652
+ const disposers = routes.map(route => ctx.webServer.register(route))
653
+ const upgradeDisposer = ctx.webServer.registerUpgrade(upgrade)
654
+ return () => {
655
+ for (const dispose of disposers) dispose()
656
+ upgradeDisposer()
657
+ // Dropping the routes also ends the terminal sessions they served:
658
+ // a live shell must not outlive the surface that can reach it.
659
+ terminalSessions.dispose()
660
+ }
661
+ },
662
+ 'dsh-ssh: routes',
663
+ )
664
+ disposeTools = ctx.effect(
665
+ () => {
666
+ const disposers = tools.map(tool => ctx.tools.register(tool))
667
+ return () => { for (const dispose of disposers) dispose() }
668
+ },
669
+ 'dsh-ssh: tools',
670
+ )
671
+ // Arm the monitoring loop last, so its first round runs against a fully
672
+ // registered surface. A loop that starts before the tools exist would
673
+ // record rounds no tool can read.
674
+ if (readConfigField(config?.monitorEnabled, false)) {
675
+ monitor.start(ctx.timer)
676
+ // The loop owns no effect of its own; this one carries the interval
677
+ // disposer onto the plugin fiber, so disabling the plugin stops the
678
+ // probing instead of leaving an orphan timer watching the fleet.
679
+ disposeMonitor = ctx.effect(() => () => { monitor.stop() }, 'dsh-ssh: monitor')
680
+ }
681
+ }
682
+
683
+ // A settings edit is committed into this instance's config references and
684
+ // announced on the owning fiber (the entry is not remounted), so the
685
+ // surfaces are re-derived from the new values here.
686
+ ctx.on('loader/volatile-update', () => { sync() })
687
+
688
+ // Initial registration from the config the Host activated this row with.
689
+ sync()
690
+ }