dsh-remote-go 0.0.1 → 0.1.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.
- package/README.md +126 -7
- package/client.js +5972 -0
- package/cordis.patch.yml +3 -0
- package/index.js +4 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +76 -3
- package/src/api.js +340 -0
- package/src/atomic-json.js +208 -0
- package/src/bootstrap.js +100 -0
- package/src/connect-log.js +39 -0
- package/src/connect-pipeline.js +463 -0
- package/src/connect-progress.js +135 -0
- package/src/constants.js +31 -0
- package/src/diagnostics.js +157 -0
- package/src/download-jobs.js +217 -0
- package/src/errors.js +316 -0
- package/src/host-lifecycle.js +187 -0
- package/src/host-registry.js +145 -0
- package/src/host-runtime.js +53 -0
- package/src/host-view.js +51 -0
- package/src/index.js +162 -0
- package/src/key-files.js +49 -0
- package/src/known-hosts.js +94 -0
- package/src/layout.js +35 -0
- package/src/local-download.js +162 -0
- package/src/local-ssh.js +27 -0
- package/src/local-version.js +88 -0
- package/src/node-runtime.js +521 -0
- package/src/probe.js +89 -0
- package/src/prompts.js +132 -0
- package/src/redact.js +54 -0
- package/src/remote-files.js +71 -0
- package/src/remote-path.js +73 -0
- package/src/remote-proc.js +208 -0
- package/src/remote-web.js +300 -0
- package/src/secrets.js +79 -0
- package/src/service.js +250 -0
- package/src/settings.js +135 -0
- package/src/ssh-config.js +271 -0
- package/src/ssh.js +652 -0
- package/src/store.js +143 -0
- package/src/tunnel.js +73 -0
- package/src/util.js +153 -0
- package/src/version.js +103 -0
- package/src/webapp.js +28 -0
- package/vendor/THIRD_PARTY_NOTICES.md +10 -0
- package/vendor/ssh2-entry.mjs +12 -0
- package/vendor/ssh2.bundle.cjs +25 -0
package/src/errors.js
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coded, bilingual errors; `toErrorView` is the only shape the Client ever sees.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
const ErrorCode = Object.freeze({
|
|
6
|
+
NETWORK: 'network',
|
|
7
|
+
AUTH: 'auth',
|
|
8
|
+
HOST_KEY_CHANGED: 'host-key-changed',
|
|
9
|
+
HOST_KEY_UNKNOWN: 'host-key-unknown',
|
|
10
|
+
REMOTE_DSH_MISSING: 'remote-dsh-missing',
|
|
11
|
+
REMOTE_NODE_INSTALL_FAILED: 'remote-node-install-failed',
|
|
12
|
+
REMOTE_DSH_START_FAILED: 'remote-dsh-start-failed',
|
|
13
|
+
REMOTE_DSH_RUNNING: 'remote-dsh-running',
|
|
14
|
+
REMOTE_UI_UNREACHABLE: 'remote-ui-unreachable',
|
|
15
|
+
REMOTE_FILE_UNAVAILABLE: 'remote-file-unavailable',
|
|
16
|
+
DOWNLOAD_NOT_READY: 'download-not-ready',
|
|
17
|
+
DOWNLOAD_BUSY: 'download-busy',
|
|
18
|
+
VERSION_MISMATCH: 'version-mismatch',
|
|
19
|
+
UNSUPPORTED_OS: 'unsupported-os',
|
|
20
|
+
INVALID_INPUT: 'invalid-input',
|
|
21
|
+
INTERNAL: 'internal',
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
const CODE_TABLE = {
|
|
25
|
+
[ErrorCode.NETWORK]: { retryable: true, title: { zh: '连不上这台服务器', en: 'Cannot reach this server' } },
|
|
26
|
+
[ErrorCode.AUTH]: { retryable: true, title: { zh: 'SSH 认证没有通过', en: 'SSH authentication failed' } },
|
|
27
|
+
[ErrorCode.HOST_KEY_CHANGED]: { retryable: false, title: { zh: '主机指纹变了', en: 'The host key changed' } },
|
|
28
|
+
[ErrorCode.HOST_KEY_UNKNOWN]: { retryable: true, title: { zh: '确认服务器指纹', en: 'Confirm the host key' } },
|
|
29
|
+
[ErrorCode.REMOTE_DSH_MISSING]: {
|
|
30
|
+
retryable: true,
|
|
31
|
+
title: { zh: '远端没有可用的 DSH', en: 'No usable DSH on the remote host' },
|
|
32
|
+
},
|
|
33
|
+
[ErrorCode.REMOTE_NODE_INSTALL_FAILED]: {
|
|
34
|
+
retryable: true,
|
|
35
|
+
title: { zh: '远端 Node 自动安装失败', en: 'Automatic Node installation failed' },
|
|
36
|
+
},
|
|
37
|
+
[ErrorCode.REMOTE_DSH_START_FAILED]: {
|
|
38
|
+
retryable: true,
|
|
39
|
+
title: { zh: '远端 DSH 启动失败', en: 'The remote DSH failed to start' },
|
|
40
|
+
},
|
|
41
|
+
[ErrorCode.REMOTE_DSH_RUNNING]: {
|
|
42
|
+
retryable: true,
|
|
43
|
+
title: { zh: '远端已有手工启动的 DSH', en: 'A manually started DSH is already running' },
|
|
44
|
+
},
|
|
45
|
+
[ErrorCode.REMOTE_UI_UNREACHABLE]: {
|
|
46
|
+
retryable: true,
|
|
47
|
+
title: { zh: '远端界面打不开', en: 'The remote interface is unreachable' },
|
|
48
|
+
},
|
|
49
|
+
[ErrorCode.REMOTE_FILE_UNAVAILABLE]: {
|
|
50
|
+
retryable: true,
|
|
51
|
+
title: { zh: '无法读取远端文件', en: 'Cannot read the remote file' },
|
|
52
|
+
},
|
|
53
|
+
[ErrorCode.DOWNLOAD_NOT_READY]: {
|
|
54
|
+
retryable: true,
|
|
55
|
+
title: { zh: '下载尚未准备好', en: 'The download is not ready' },
|
|
56
|
+
},
|
|
57
|
+
[ErrorCode.DOWNLOAD_BUSY]: {
|
|
58
|
+
retryable: true,
|
|
59
|
+
title: { zh: '下载任务太多', en: 'Too many downloads are running' },
|
|
60
|
+
},
|
|
61
|
+
[ErrorCode.VERSION_MISMATCH]: {
|
|
62
|
+
retryable: true,
|
|
63
|
+
title: { zh: '远端 DSH 版本与本机不一致', en: 'Remote DSH version differs from this machine' },
|
|
64
|
+
},
|
|
65
|
+
[ErrorCode.UNSUPPORTED_OS]: {
|
|
66
|
+
retryable: false,
|
|
67
|
+
title: { zh: '远端系统暂不支持', en: 'This remote system is not supported yet' },
|
|
68
|
+
},
|
|
69
|
+
[ErrorCode.INVALID_INPUT]: { retryable: false, title: { zh: '填写的信息有误', en: 'Some fields are invalid' } },
|
|
70
|
+
[ErrorCode.INTERNAL]: { retryable: true, title: { zh: '插件内部错误', en: 'Internal plugin error' } },
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class RemoteGoError extends Error {
|
|
74
|
+
constructor(code, detail, options = {}) {
|
|
75
|
+
super(`${code}: ${detail.en}`)
|
|
76
|
+
this.name = 'RemoteGoError'
|
|
77
|
+
this.code = code
|
|
78
|
+
this.detail = detail
|
|
79
|
+
this.nextSteps = options.nextSteps ?? []
|
|
80
|
+
this.technical = options.technical
|
|
81
|
+
this.retryable = options.retryable ?? CODE_TABLE[code]?.retryable ?? true
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const say = (zh, en) => ({ zh, en })
|
|
86
|
+
|
|
87
|
+
function fail(code, detail, steps, options = {}) {
|
|
88
|
+
return new RemoteGoError(code, detail, { nextSteps: steps.map(([zh, en]) => say(zh, en)), ...options })
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export const errors = {
|
|
92
|
+
network: (
|
|
93
|
+
detail = say(
|
|
94
|
+
'网络不可达,可能被防火墙拦截或地址写错。',
|
|
95
|
+
'The network is unreachable — check the address, port and firewall.',
|
|
96
|
+
),
|
|
97
|
+
options,
|
|
98
|
+
) =>
|
|
99
|
+
fail(
|
|
100
|
+
ErrorCode.NETWORK,
|
|
101
|
+
detail,
|
|
102
|
+
[
|
|
103
|
+
['检查地址、端口与网络连通性', 'Check the address, port and network reachability'],
|
|
104
|
+
['如果有跳板机,先确认跳板机可达', 'If a jump host is configured, verify it first'],
|
|
105
|
+
],
|
|
106
|
+
options,
|
|
107
|
+
),
|
|
108
|
+
auth: (detail = say('远端拒绝了这次 SSH 认证。', 'The remote host rejected this SSH authentication.'), options) =>
|
|
109
|
+
fail(
|
|
110
|
+
ErrorCode.AUTH,
|
|
111
|
+
detail,
|
|
112
|
+
[
|
|
113
|
+
['检查用户名与密钥 / SSH Agent', 'Check the user name and key / SSH agent'],
|
|
114
|
+
['确认密钥文件路径与权限(0600)', 'Confirm the key file path and its 0600 permissions'],
|
|
115
|
+
],
|
|
116
|
+
options,
|
|
117
|
+
),
|
|
118
|
+
hostKeyChanged: (pinned, actual) =>
|
|
119
|
+
fail(
|
|
120
|
+
ErrorCode.HOST_KEY_CHANGED,
|
|
121
|
+
say(
|
|
122
|
+
`主机指纹和已记录的不一致:记录 ${pinned},实际 ${actual}。`,
|
|
123
|
+
`The host key no longer matches the pinned value: pinned ${pinned}, actual ${actual}.`,
|
|
124
|
+
),
|
|
125
|
+
[
|
|
126
|
+
[
|
|
127
|
+
'确认服务器是否重装或更换了证书;确认后再更新指纹',
|
|
128
|
+
'Confirm the server was not reinstalled or tampered with before updating the pin',
|
|
129
|
+
],
|
|
130
|
+
],
|
|
131
|
+
{ retryable: false, technical: `pinned=${pinned} actual=${actual}` },
|
|
132
|
+
),
|
|
133
|
+
hostKeyUnknown: (fingerprint) =>
|
|
134
|
+
fail(
|
|
135
|
+
ErrorCode.HOST_KEY_UNKNOWN,
|
|
136
|
+
say(
|
|
137
|
+
`首次连接该服务器(指纹 ${fingerprint}),需要你确认。`,
|
|
138
|
+
`First connection to this host (fingerprint ${fingerprint}); confirmation required.`,
|
|
139
|
+
),
|
|
140
|
+
[['核对指纹后选择「接受并记住」或取消', 'Verify the fingerprint, then accept and remember it or cancel']],
|
|
141
|
+
),
|
|
142
|
+
remoteDshMissing: (detail) =>
|
|
143
|
+
fail(
|
|
144
|
+
ErrorCode.REMOTE_DSH_MISSING,
|
|
145
|
+
detail ??
|
|
146
|
+
say(
|
|
147
|
+
'远端没有找到可用的 DSH,本机也无法自动准备运行环境。',
|
|
148
|
+
'No usable DSH was found and the runtime could not be prepared automatically.',
|
|
149
|
+
),
|
|
150
|
+
[
|
|
151
|
+
['确认远端可以访问网络,或配置离线包', 'Check remote network access, or configure an offline package'],
|
|
152
|
+
['也可以在远端手动安装 DSH 后重试', 'You can also install DSH manually on the remote host and retry'],
|
|
153
|
+
],
|
|
154
|
+
),
|
|
155
|
+
nodeInstallFailed: (detail, options) =>
|
|
156
|
+
fail(
|
|
157
|
+
ErrorCode.REMOTE_NODE_INSTALL_FAILED,
|
|
158
|
+
detail ??
|
|
159
|
+
say(
|
|
160
|
+
'远端没有可用的 Node,自动安装也没有成功。',
|
|
161
|
+
'The remote has no usable Node and automatic installation did not succeed.',
|
|
162
|
+
),
|
|
163
|
+
[
|
|
164
|
+
[
|
|
165
|
+
'让远端可以访问 nodejs.org 或 npmmirror.com 后重试',
|
|
166
|
+
'Allow the remote to reach nodejs.org or npmmirror.com and retry',
|
|
167
|
+
],
|
|
168
|
+
[
|
|
169
|
+
'确认远端磁盘 ≥ 400 MB,且是受支持的 glibc 架构(musl/Alpine 不支持)',
|
|
170
|
+
'Make sure the remote has >= 400 MB free and a supported glibc architecture (musl/Alpine is not supported)',
|
|
171
|
+
],
|
|
172
|
+
],
|
|
173
|
+
options,
|
|
174
|
+
),
|
|
175
|
+
remoteDshRunning: (detail, options) =>
|
|
176
|
+
fail(
|
|
177
|
+
ErrorCode.REMOTE_DSH_RUNNING,
|
|
178
|
+
detail ??
|
|
179
|
+
say(
|
|
180
|
+
'远端检测到不是本插件启动的 DSH 进程,连接已按你的选择取消。',
|
|
181
|
+
'The remote has a DSH process this plugin did not start; the connection was cancelled as you chose.',
|
|
182
|
+
),
|
|
183
|
+
[
|
|
184
|
+
[
|
|
185
|
+
'重新连接,并选择「停止它并启动受管实例」或「保留它,另起一个」',
|
|
186
|
+
'Reconnect and choose "Stop it and start the managed instance" or "Keep it and start alongside"',
|
|
187
|
+
],
|
|
188
|
+
],
|
|
189
|
+
options,
|
|
190
|
+
),
|
|
191
|
+
remoteDshStartFailed: (tail) =>
|
|
192
|
+
fail(
|
|
193
|
+
ErrorCode.REMOTE_DSH_START_FAILED,
|
|
194
|
+
say(
|
|
195
|
+
'远端 DSH 进程没有成功打印 Web 地址,可能启动即失败。',
|
|
196
|
+
'The remote DSH process did not print its Web URL; startup likely failed.',
|
|
197
|
+
),
|
|
198
|
+
[
|
|
199
|
+
['查看诊断里的远端日志尾部', 'Inspect the remote log tail in diagnostics'],
|
|
200
|
+
['确认远端磁盘空间与端口可用', 'Check remote disk space and usable ports'],
|
|
201
|
+
[
|
|
202
|
+
'重试一次,若仍失败可手动在远端验证 `dsh --profile web --no-open`',
|
|
203
|
+
'Retry, or verify `dsh --profile web --no-open` manually on the remote host',
|
|
204
|
+
],
|
|
205
|
+
],
|
|
206
|
+
{ technical: tail },
|
|
207
|
+
),
|
|
208
|
+
remoteUiUnreachable: (detail) =>
|
|
209
|
+
fail(
|
|
210
|
+
ErrorCode.REMOTE_UI_UNREACHABLE,
|
|
211
|
+
detail ??
|
|
212
|
+
say(
|
|
213
|
+
'隧道的本地回环端口无法完成远端界面的鉴权握手。',
|
|
214
|
+
'The loopback tunnel could not complete the remote UI authentication handshake.',
|
|
215
|
+
),
|
|
216
|
+
[
|
|
217
|
+
['点「重连」重试一次', 'Retry with Reconnect'],
|
|
218
|
+
['查看诊断中的隧道与界面可达性检查', 'Check tunnel and UI reachability in diagnostics'],
|
|
219
|
+
],
|
|
220
|
+
),
|
|
221
|
+
remoteFileUnavailable: (detail, options) =>
|
|
222
|
+
fail(
|
|
223
|
+
ErrorCode.REMOTE_FILE_UNAVAILABLE,
|
|
224
|
+
detail ??
|
|
225
|
+
say(
|
|
226
|
+
'远端路径不存在、不可读,或无法写入本地保存位置。',
|
|
227
|
+
'The remote path does not exist, is not readable, or the local destination cannot be written.',
|
|
228
|
+
),
|
|
229
|
+
[
|
|
230
|
+
['确认文件仍在远端,且当前 SSH 用户可以读取', 'Confirm the file still exists and the SSH user can read it'],
|
|
231
|
+
[
|
|
232
|
+
'检查文件大小;过大的文件请先在远端压缩或拆分',
|
|
233
|
+
'Check the file size; compress or split large files on the remote first',
|
|
234
|
+
],
|
|
235
|
+
],
|
|
236
|
+
options,
|
|
237
|
+
),
|
|
238
|
+
downloadNotReady: (detail, options) =>
|
|
239
|
+
fail(
|
|
240
|
+
ErrorCode.DOWNLOAD_NOT_READY,
|
|
241
|
+
detail ??
|
|
242
|
+
say(
|
|
243
|
+
'这个下载还在准备中,或已经失效;请重新发起下载。',
|
|
244
|
+
'This download is still being prepared or has expired; start it again.',
|
|
245
|
+
),
|
|
246
|
+
[
|
|
247
|
+
['等待进度条完成后再试', 'Wait for the progress bar to finish and retry'],
|
|
248
|
+
['如果任务已失效,从远端文件树重新下载', 'If it expired, start the download again from the remote file tree'],
|
|
249
|
+
],
|
|
250
|
+
options,
|
|
251
|
+
),
|
|
252
|
+
downloadBusy: (detail, options) =>
|
|
253
|
+
fail(
|
|
254
|
+
ErrorCode.DOWNLOAD_BUSY,
|
|
255
|
+
detail ??
|
|
256
|
+
say(
|
|
257
|
+
'同时准备的下载任务过多,请等一个完成后再试。',
|
|
258
|
+
'Too many downloads are being prepared at once; wait for one to finish and retry.',
|
|
259
|
+
),
|
|
260
|
+
[['取消不需要的下载,或稍后重试', 'Cancel an unneeded download, or retry later']],
|
|
261
|
+
options,
|
|
262
|
+
),
|
|
263
|
+
versionMismatch: (local, remote) =>
|
|
264
|
+
fail(
|
|
265
|
+
ErrorCode.VERSION_MISMATCH,
|
|
266
|
+
say(
|
|
267
|
+
`本机 DSH 是 ${local},远端是 ${remote};界面可能不一致,默认不静默混用。`,
|
|
268
|
+
`This machine runs DSH ${local} while the remote runs ${remote}; the UI may differ and mixing silently is not allowed.`,
|
|
269
|
+
),
|
|
270
|
+
[
|
|
271
|
+
['选择「准备同版本运行时」后重试(推荐)', 'Prepare a matching runtime and retry (recommended)'],
|
|
272
|
+
['明确选择「沿用远端版本」继续', 'Explicitly continue with the remote version'],
|
|
273
|
+
],
|
|
274
|
+
),
|
|
275
|
+
unsupportedOs: (os) =>
|
|
276
|
+
fail(
|
|
277
|
+
ErrorCode.UNSUPPORTED_OS,
|
|
278
|
+
say(`V1 仅支持 Linux 远端,检测到 ${os}。`, `V1 supports Linux remotes only; detected ${os}.`),
|
|
279
|
+
[['换一台 Linux 服务器,或等待后续版本', 'Use a Linux server, or wait for a later release']],
|
|
280
|
+
{ retryable: false },
|
|
281
|
+
),
|
|
282
|
+
invalidInput: (field, detail) =>
|
|
283
|
+
fail(
|
|
284
|
+
ErrorCode.INVALID_INPUT,
|
|
285
|
+
detail ?? say(`字段「${field}」不合法。`, `The field "${field}" is invalid.`),
|
|
286
|
+
[['修正后重试', 'Fix it and retry']],
|
|
287
|
+
{ retryable: false },
|
|
288
|
+
),
|
|
289
|
+
internal: (cause) =>
|
|
290
|
+
fail(
|
|
291
|
+
ErrorCode.INTERNAL,
|
|
292
|
+
say('插件内部出现异常,可重试或查看诊断。', 'The plugin hit an internal error; retry or check diagnostics.'),
|
|
293
|
+
[],
|
|
294
|
+
{ technical: cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause ?? '') },
|
|
295
|
+
),
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export function toErrorView(error) {
|
|
299
|
+
if (error instanceof RemoteGoError) {
|
|
300
|
+
const table = CODE_TABLE[error.code] ?? { retryable: true, title: { zh: '未知错误', en: 'Unknown error' } }
|
|
301
|
+
const view = {
|
|
302
|
+
code: error.code,
|
|
303
|
+
title: table.title,
|
|
304
|
+
detail: error.detail,
|
|
305
|
+
nextSteps: error.nextSteps,
|
|
306
|
+
retryable: error.retryable,
|
|
307
|
+
}
|
|
308
|
+
if (error.technical) view.technical = error.technical
|
|
309
|
+
return view
|
|
310
|
+
}
|
|
311
|
+
return toErrorView(errors.internal(error))
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export function isRemoteGoError(error) {
|
|
315
|
+
return error instanceof RemoteGoError
|
|
316
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-host lifecycle: the reconnect backoff, the idle-stop timer and the single teardown path; the reconnect timer gets a callback, so this never imports the pipeline.
|
|
3
|
+
*/
|
|
4
|
+
import { DEFAULT_IDLE_MINUTES } from './constants.js'
|
|
5
|
+
import { errors, toErrorView } from './errors.js'
|
|
6
|
+
import { emptyRemote } from './host-runtime.js'
|
|
7
|
+
import { remoteLayout } from './layout.js'
|
|
8
|
+
import { cancelConflict } from './prompts.js'
|
|
9
|
+
import { messageOf, randomDelay } from './util.js'
|
|
10
|
+
|
|
11
|
+
export function cancelReconnect(runtime) {
|
|
12
|
+
if (runtime.reconnectTimer) {
|
|
13
|
+
clearTimeout(runtime.reconnectTimer)
|
|
14
|
+
runtime.reconnectTimer = null
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function cancelIdleStop(runtime) {
|
|
19
|
+
if (runtime.idleTimer) {
|
|
20
|
+
clearTimeout(runtime.idleTimer)
|
|
21
|
+
runtime.idleTimer = null
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Arm the next reconnect attempt, or give up once the configured budget is spent.
|
|
27
|
+
*/
|
|
28
|
+
export function scheduleReconnect(ctx, runtime, onDue) {
|
|
29
|
+
cancelReconnect(runtime)
|
|
30
|
+
const settings = ctx.settings()
|
|
31
|
+
if (!runtime.entry.autoReconnect || !settings.autoReconnect.enabled) {
|
|
32
|
+
ctx.progress.set(runtime, { status: 'disconnected' })
|
|
33
|
+
return
|
|
34
|
+
}
|
|
35
|
+
const maxAttempts = settings.autoReconnect.maxAttempts
|
|
36
|
+
if (runtime.reconnectAttempts >= maxAttempts) {
|
|
37
|
+
runtime.status = 'error'
|
|
38
|
+
runtime.error = toErrorView(
|
|
39
|
+
errors.network({
|
|
40
|
+
zh: `连接已断开,自动重连 ${maxAttempts} 次均失败。远端任务可能仍在运行。`,
|
|
41
|
+
en: `The connection dropped and ${maxAttempts} automatic retries failed. Remote tasks may still be running.`,
|
|
42
|
+
}),
|
|
43
|
+
)
|
|
44
|
+
runtime.progress = null
|
|
45
|
+
ctx.emitState()
|
|
46
|
+
return
|
|
47
|
+
}
|
|
48
|
+
runtime.reconnectAttempts += 1
|
|
49
|
+
const delay = randomDelay(
|
|
50
|
+
settings.autoReconnect.baseDelayMs,
|
|
51
|
+
settings.autoReconnect.baseDelayMs * 2 ** Math.min(runtime.reconnectAttempts, 4),
|
|
52
|
+
)
|
|
53
|
+
runtime.progress = { code: 'reconnecting', params: { attempt: runtime.reconnectAttempts, max: maxAttempts } }
|
|
54
|
+
ctx.progress.log(
|
|
55
|
+
runtime,
|
|
56
|
+
'warn',
|
|
57
|
+
`link lost; retrying in ${Math.round(delay / 100) / 10}s (attempt ${runtime.reconnectAttempts}/${maxAttempts})`,
|
|
58
|
+
)
|
|
59
|
+
ctx.emitState()
|
|
60
|
+
runtime.reconnectTimer = setTimeout(() => {
|
|
61
|
+
runtime.reconnectTimer = null
|
|
62
|
+
onDue()
|
|
63
|
+
}, delay)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function scheduleIdleStop(ctx, runtime) {
|
|
67
|
+
cancelIdleStop(runtime)
|
|
68
|
+
const minutes = Math.max(1, runtime.entry.idleMinutes ?? DEFAULT_IDLE_MINUTES)
|
|
69
|
+
runtime.idleTimer = setTimeout(() => {
|
|
70
|
+
runtime.idleTimer = null
|
|
71
|
+
void stopRemoteQuietly(ctx, runtime)
|
|
72
|
+
}, minutes * 60_000)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Best-effort stop of the remote web for the idle policy, then drop the transport. */
|
|
76
|
+
async function stopRemoteQuietly(ctx, runtime) {
|
|
77
|
+
try {
|
|
78
|
+
if (runtime.ssh?.connected) {
|
|
79
|
+
await ctx.deps.stopWeb(runtime.ssh, remoteLayout(runtime.facts?.home ?? null), {
|
|
80
|
+
pid: runtime.remote.pid ?? undefined,
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
} catch (error) {
|
|
84
|
+
ctx.progress.log(runtime, 'warn', 'idle stop failed:', messageOf(error))
|
|
85
|
+
} finally {
|
|
86
|
+
await disposeSsh(runtime)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function closeTunnel(runtime) {
|
|
91
|
+
const tunnel = runtime.tunnel
|
|
92
|
+
runtime.tunnel = null
|
|
93
|
+
if (tunnel) {
|
|
94
|
+
try {
|
|
95
|
+
await tunnel.close()
|
|
96
|
+
} catch {}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function disposeSsh(runtime) {
|
|
101
|
+
const ssh = runtime.ssh
|
|
102
|
+
runtime.ssh = null
|
|
103
|
+
const jump = runtime.jumpSsh
|
|
104
|
+
runtime.jumpSsh = null
|
|
105
|
+
if (ssh) {
|
|
106
|
+
try {
|
|
107
|
+
await ssh.dispose()
|
|
108
|
+
} catch {}
|
|
109
|
+
}
|
|
110
|
+
if (jump) {
|
|
111
|
+
try {
|
|
112
|
+
await jump.dispose()
|
|
113
|
+
} catch {}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The single teardown path. `stopRemote` also stops the remote web (keep-alive
|
|
119
|
+
* `stop`), `keepSshForIdle` leaves the transport up for a fast resume, and
|
|
120
|
+
* `keepRemote` preserves the remote facts so the card still describes what is
|
|
121
|
+
* running on the other side.
|
|
122
|
+
*/
|
|
123
|
+
export async function teardownRuntime(ctx, runtime, options = {}) {
|
|
124
|
+
cancelConflict(runtime)
|
|
125
|
+
runtime.closing = true
|
|
126
|
+
cancelIdleStop(runtime)
|
|
127
|
+
if (options.stopRemote && runtime.ssh?.connected) {
|
|
128
|
+
try {
|
|
129
|
+
await ctx.deps.stopWeb(runtime.ssh, remoteLayout(runtime.facts?.home ?? null), {
|
|
130
|
+
pid: runtime.remote.pid ?? undefined,
|
|
131
|
+
})
|
|
132
|
+
} catch (error) {
|
|
133
|
+
ctx.progress.log(runtime, 'warn', 'stop remote failed:', messageOf(error))
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
await closeTunnel(runtime)
|
|
137
|
+
if (!options.keepSshForIdle) await disposeSsh(runtime)
|
|
138
|
+
if (!options.keepRemote) {
|
|
139
|
+
runtime.remote = { ...emptyRemote(), version: runtime.remote.version }
|
|
140
|
+
runtime.token = null
|
|
141
|
+
runtime.facts = null
|
|
142
|
+
runtime.exchange = null
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Tear one host down and leave it idle: the keep-alive policy decides whether the
|
|
148
|
+
* remote web is stopped and whether the transport survives for a fast resume.
|
|
149
|
+
*/
|
|
150
|
+
export async function disconnectHost(ctx, runtime, options = {}) {
|
|
151
|
+
ctx.progress.log(runtime, 'info', `disconnect requested (keepAlive=${runtime.entry.keepAlive})`)
|
|
152
|
+
runtime.desired = 'idle'
|
|
153
|
+
cancelReconnect(runtime)
|
|
154
|
+
const policy = runtime.entry.keepAlive
|
|
155
|
+
const stopRemote = options.stopRemote === true || policy === 'stop'
|
|
156
|
+
await teardownRuntime(ctx, runtime, { stopRemote, keepSshForIdle: policy === 'idle' && !stopRemote })
|
|
157
|
+
runtime.status = 'disconnected'
|
|
158
|
+
runtime.phase = null
|
|
159
|
+
runtime.progress = null
|
|
160
|
+
runtime.remote.uiReady = false
|
|
161
|
+
runtime.remote.localPort = null
|
|
162
|
+
runtime.token = null
|
|
163
|
+
ctx.progress.set(runtime, {})
|
|
164
|
+
if (policy === 'idle' && !stopRemote) scheduleIdleStop(ctx, runtime)
|
|
165
|
+
return { ok: true }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Stop every host's timers and release its transport. The `stop` keep-alive
|
|
170
|
+
* policy also stops the remote web so nothing is left running unowned.
|
|
171
|
+
*/
|
|
172
|
+
export async function shutdownAll(ctx) {
|
|
173
|
+
for (const runtime of ctx.state.runtimes.values()) {
|
|
174
|
+
cancelReconnect(runtime)
|
|
175
|
+
cancelIdleStop(runtime)
|
|
176
|
+
try {
|
|
177
|
+
if (runtime.entry.keepAlive === 'stop') {
|
|
178
|
+
await stopRemoteQuietly(ctx, runtime)
|
|
179
|
+
} else {
|
|
180
|
+
await closeTunnel(runtime)
|
|
181
|
+
await disposeSsh(runtime)
|
|
182
|
+
}
|
|
183
|
+
} catch {
|
|
184
|
+
/* best effort on shutdown */
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host registry: the configured hosts, their runtime objects and the client-facing snapshot; reads are pure, writes re-emit the snapshot after `store`.
|
|
3
|
+
*/
|
|
4
|
+
import { homedir } from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import { errors } from './errors.js'
|
|
7
|
+
import { createHostRuntime } from './host-runtime.js'
|
|
8
|
+
import { hostView } from './host-view.js'
|
|
9
|
+
import { listKeyFiles as listKeyFilesInHome } from './key-files.js'
|
|
10
|
+
import { parseKnownHosts, summarizeKnownHosts } from './known-hosts.js'
|
|
11
|
+
import { cancelIdleStop, cancelReconnect, teardownRuntime } from './host-lifecycle.js'
|
|
12
|
+
import { discoverSshAliases as discoverAliasesFromConfig, parseSshConfig } from './ssh-config.js'
|
|
13
|
+
|
|
14
|
+
function ensureRuntime(ctx, host) {
|
|
15
|
+
const existing = ctx.state.runtimes.get(host.id)
|
|
16
|
+
if (existing) {
|
|
17
|
+
existing.entry = host
|
|
18
|
+
return existing
|
|
19
|
+
}
|
|
20
|
+
const runtime = createHostRuntime(host)
|
|
21
|
+
ctx.state.runtimes.set(host.id, runtime)
|
|
22
|
+
return runtime
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function runtimeOf(ctx, id) {
|
|
26
|
+
const runtime = ctx.state.runtimes.get(id)
|
|
27
|
+
if (!runtime) throw errors.invalidInput('id', { zh: `未知主机 ${id}`, en: `Unknown host ${id}` })
|
|
28
|
+
return runtime
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function initRegistry(ctx) {
|
|
32
|
+
if (ctx.state.initialized) return
|
|
33
|
+
await ctx.store.load()
|
|
34
|
+
for (const host of ctx.store.listHosts()) ensureRuntime(ctx, host)
|
|
35
|
+
ctx.state.initialized = true
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function hostViewFor(ctx, runtime) {
|
|
39
|
+
return hostView(runtime, {
|
|
40
|
+
targetVersion: ctx.localVersion(),
|
|
41
|
+
passwordStorageAvailable: ctx.secrets ? ctx.secrets.available() === true : false,
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Build the client-facing state snapshot (contract: docs/api.md). */
|
|
46
|
+
export function snapshot(ctx) {
|
|
47
|
+
const localVersion = ctx.localVersion()
|
|
48
|
+
const hosts = [...ctx.state.runtimes.values()].map((runtime) => hostViewFor(ctx, runtime))
|
|
49
|
+
return {
|
|
50
|
+
hostVersion: localVersion,
|
|
51
|
+
targetVersion: localVersion,
|
|
52
|
+
hosts,
|
|
53
|
+
settings: ctx.store.getSettings(),
|
|
54
|
+
activeHostId: ctx.state.activeHostId,
|
|
55
|
+
firstRun: hosts.length === 0,
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function saveHost(ctx, rawHost) {
|
|
60
|
+
await ctx.init()
|
|
61
|
+
let entry
|
|
62
|
+
try {
|
|
63
|
+
entry = await ctx.store.upsertHost(rawHost, { settings: ctx.store.getSettings() })
|
|
64
|
+
} catch (error) {
|
|
65
|
+
// The store's validators throw bare messages; map them to the client's field
|
|
66
|
+
// errors here so the contract stays typed.
|
|
67
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
68
|
+
if (message === 'address is required') {
|
|
69
|
+
throw errors.invalidInput('address', {
|
|
70
|
+
zh: '请填写服务器地址或 ~/.ssh/config 别名。',
|
|
71
|
+
en: 'Enter a server address or an ~/.ssh/config alias.',
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
if (message === 'address is invalid') {
|
|
75
|
+
throw errors.invalidInput('address', { zh: '服务器地址格式不正确。', en: 'The server address is not valid.' })
|
|
76
|
+
}
|
|
77
|
+
throw errors.invalidInput('host', {
|
|
78
|
+
zh: `主机配置不合法:${message}`,
|
|
79
|
+
en: `Invalid host entry: ${message}`,
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
ensureRuntime(ctx, entry)
|
|
83
|
+
ctx.emitState()
|
|
84
|
+
return hostViewFor(ctx, runtimeOf(ctx, entry.id))
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function removeHost(ctx, id) {
|
|
88
|
+
await ctx.init()
|
|
89
|
+
const runtime = ctx.state.runtimes.get(id)
|
|
90
|
+
if (runtime) {
|
|
91
|
+
// A deleted host must not be resurrected by a timer scheduled before deletion.
|
|
92
|
+
cancelReconnect(runtime)
|
|
93
|
+
cancelIdleStop(runtime)
|
|
94
|
+
await teardownRuntime(ctx, runtime, { stopRemote: runtime.entry.keepAlive === 'stop' })
|
|
95
|
+
}
|
|
96
|
+
ctx.state.runtimes.delete(id)
|
|
97
|
+
await ctx.store.removeHost(id)
|
|
98
|
+
if (ctx.state.activeHostId === id) ctx.state.activeHostId = null
|
|
99
|
+
ctx.emitState()
|
|
100
|
+
return { ok: true }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function setActiveHost(ctx, id) {
|
|
104
|
+
if (id !== null && !ctx.state.runtimes.has(id)) throw errors.invalidInput('id')
|
|
105
|
+
ctx.state.activeHostId = id
|
|
106
|
+
ctx.emitState()
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function saveSettings(ctx, patch) {
|
|
110
|
+
await ctx.init()
|
|
111
|
+
const settings = await ctx.store.saveSettings(patch)
|
|
112
|
+
ctx.emitState()
|
|
113
|
+
return settings
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Browse directories inside the user's home so the client can pick a private-key
|
|
118
|
+
* file instead of typing an absolute path. Read-only and home-confined.
|
|
119
|
+
*/
|
|
120
|
+
export async function listKeyFiles(ctx, dir) {
|
|
121
|
+
// The picker is rooted at the OS user home, not DSH_HOME: private keys live in
|
|
122
|
+
// `~/.ssh` of the account, while the service's `home` is the DSH state root.
|
|
123
|
+
const userHome = homedir()
|
|
124
|
+
const listing = await listKeyFilesInHome({ home: userHome, dir: typeof dir === 'string' ? dir : '' })
|
|
125
|
+
const settings = ctx.store.getSettings()
|
|
126
|
+
return { ...listing, defaultKeyPath: settings.defaultKeyPath, defaultDir: path.join(userHome, '.ssh') }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Read-only SSH discovery for the wizard (design §15.1). */
|
|
130
|
+
export async function discoverSshAliases(ctx) {
|
|
131
|
+
const material = await ctx.deps.loadSshMaterial({ home: ctx.userHome() })
|
|
132
|
+
const parsed = parseSshConfig(material.configText)
|
|
133
|
+
const aliases = discoverAliasesFromConfig(parsed, { home: ctx.userHome() })
|
|
134
|
+
const knownHosts = parseKnownHosts(material.knownHostsText)
|
|
135
|
+
return {
|
|
136
|
+
aliases: aliases.map((alias) => ({
|
|
137
|
+
alias: alias.alias,
|
|
138
|
+
host: alias.host,
|
|
139
|
+
user: alias.user,
|
|
140
|
+
port: alias.port,
|
|
141
|
+
source: 'config',
|
|
142
|
+
})),
|
|
143
|
+
knownHosts: summarizeKnownHosts(knownHosts),
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The per-host runtime object shared by the service and every helper.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export function emptyRemote() {
|
|
6
|
+
return {
|
|
7
|
+
version: null,
|
|
8
|
+
uiReady: false,
|
|
9
|
+
localPort: null,
|
|
10
|
+
port: null,
|
|
11
|
+
pid: null,
|
|
12
|
+
dshHome: null,
|
|
13
|
+
profile: null,
|
|
14
|
+
bootstrapLevel: null,
|
|
15
|
+
nodeVersion: null,
|
|
16
|
+
nodeSource: null,
|
|
17
|
+
startedAt: null,
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function createHostRuntime(host) {
|
|
22
|
+
return {
|
|
23
|
+
id: host.id,
|
|
24
|
+
entry: host,
|
|
25
|
+
status: 'unconfigured',
|
|
26
|
+
phase: null,
|
|
27
|
+
progress: null,
|
|
28
|
+
error: null,
|
|
29
|
+
warning: null,
|
|
30
|
+
fingerprint: host.pinnedFingerprint
|
|
31
|
+
? { sha256: host.pinnedFingerprint, keyType: 'pinned', status: 'pinned', pinned: host.pinnedFingerprint }
|
|
32
|
+
: null,
|
|
33
|
+
remote: emptyRemote(),
|
|
34
|
+
ssh: null,
|
|
35
|
+
jumpSsh: null,
|
|
36
|
+
tunnel: null,
|
|
37
|
+
token: null,
|
|
38
|
+
password: null,
|
|
39
|
+
facts: null,
|
|
40
|
+
exchange: null,
|
|
41
|
+
pendingHostKey: null,
|
|
42
|
+
pendingConflict: null,
|
|
43
|
+
conflict: null,
|
|
44
|
+
desired: 'idle',
|
|
45
|
+
reconnectAttempts: 0,
|
|
46
|
+
reconnectTimer: null,
|
|
47
|
+
idleTimer: null,
|
|
48
|
+
connectPromise: null,
|
|
49
|
+
closing: false,
|
|
50
|
+
logs: [],
|
|
51
|
+
logSeq: 0,
|
|
52
|
+
}
|
|
53
|
+
}
|