dsh-remote-go 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7144 -8367
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +21 -0
  5. package/dist/src/api.js +380 -0
  6. package/dist/src/atomic-json.js +201 -0
  7. package/dist/src/bootstrap.js +96 -0
  8. package/dist/src/connect/attach.js +21 -0
  9. package/dist/src/connect/bootstrap.js +8 -0
  10. package/dist/src/connect/failures.js +29 -0
  11. package/dist/src/connect/guards.js +36 -0
  12. package/dist/src/connect/launch.js +70 -0
  13. package/dist/src/connect/links.js +54 -0
  14. package/dist/src/connect/ownership.js +139 -0
  15. package/dist/src/connect/pipeline.js +376 -0
  16. package/dist/src/connect/reattach.js +191 -0
  17. package/dist/src/connect/registry.js +10 -0
  18. package/dist/src/connect/repair.js +97 -0
  19. package/dist/src/connect/restart.js +255 -0
  20. package/dist/src/connect/stop.js +164 -0
  21. package/dist/src/connect/transport.js +101 -0
  22. package/dist/src/connect/verify.js +30 -0
  23. package/dist/src/connect/watchdog.js +44 -0
  24. package/dist/src/connect-log.js +137 -0
  25. package/dist/src/connect-progress.js +110 -0
  26. package/dist/src/constants.js +29 -0
  27. package/dist/src/context.js +96 -0
  28. package/dist/src/diagnostics.js +133 -0
  29. package/dist/src/download-jobs.js +221 -0
  30. package/dist/src/errors.js +228 -0
  31. package/dist/src/events.js +326 -0
  32. package/dist/src/host-lifecycle.js +368 -0
  33. package/dist/src/host-registry.js +181 -0
  34. package/dist/src/host-runtime.js +77 -0
  35. package/dist/src/host-view.js +52 -0
  36. package/dist/src/index.js +196 -0
  37. package/dist/src/kernel-adapter.js +388 -0
  38. package/dist/src/key-files.js +39 -0
  39. package/dist/src/known-hosts.js +104 -0
  40. package/dist/src/layout.js +26 -0
  41. package/dist/src/local-download.js +311 -0
  42. package/dist/src/local-ssh.js +23 -0
  43. package/dist/src/local-version.js +87 -0
  44. package/dist/src/node/download.js +157 -0
  45. package/dist/src/node-runtime.js +327 -0
  46. package/dist/src/probe.js +95 -0
  47. package/dist/src/prompts.js +198 -0
  48. package/dist/src/proxy/cookies.js +102 -0
  49. package/dist/src/proxy/headers.js +167 -0
  50. package/dist/src/proxy/http.js +134 -0
  51. package/dist/src/proxy/index.js +121 -0
  52. package/dist/src/proxy/limits.js +6 -0
  53. package/dist/src/proxy/routes.js +32 -0
  54. package/dist/src/proxy/upgrade.js +160 -0
  55. package/dist/src/redact.js +85 -0
  56. package/dist/src/remote-files.js +60 -0
  57. package/dist/src/remote-path.js +82 -0
  58. package/dist/src/remote-proc.js +271 -0
  59. package/dist/src/remote-web/registry.js +107 -0
  60. package/dist/src/remote-web/resolve.js +229 -0
  61. package/dist/src/remote-web/start.js +190 -0
  62. package/dist/src/remote-web/stop.js +74 -0
  63. package/dist/src/request-trust.js +70 -0
  64. package/dist/src/runtime/dispatch.js +200 -0
  65. package/dist/src/runtime/effects.js +81 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +70 -0
  68. package/dist/src/runtime/rules.js +480 -0
  69. package/dist/src/secrets.js +119 -0
  70. package/dist/src/service.js +300 -0
  71. package/dist/src/settings.js +143 -0
  72. package/dist/src/ssh-config.js +257 -0
  73. package/dist/src/ssh-failures.js +71 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +258 -0
  76. package/dist/src/ssh.js +395 -0
  77. package/dist/src/store.js +174 -0
  78. package/dist/src/tool-shared.js +146 -0
  79. package/dist/src/tools-exec-policy.js +121 -0
  80. package/dist/src/tools-exec.js +307 -0
  81. package/dist/src/tools-report.js +357 -0
  82. package/dist/src/tools.js +337 -0
  83. package/dist/src/tunnel.js +111 -0
  84. package/dist/src/util.js +112 -0
  85. package/dist/src/version.js +108 -0
  86. package/dist/src/watchdog-bus.js +21 -0
  87. package/dist/src/watchdog.js +116 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +1 -1
  90. package/locale/zh.json +1 -1
  91. package/package.json +37 -19
  92. package/src/admission.js +0 -43
  93. package/src/api.js +0 -536
  94. package/src/atomic-json.js +0 -225
  95. package/src/bootstrap.js +0 -113
  96. package/src/connect-log.js +0 -176
  97. package/src/connect-pipeline.js +0 -1900
  98. package/src/connect-progress.js +0 -155
  99. package/src/constants.js +0 -93
  100. package/src/diagnostics.js +0 -160
  101. package/src/download-jobs.js +0 -234
  102. package/src/errors.js +0 -412
  103. package/src/host-lifecycle.js +0 -604
  104. package/src/host-registry.js +0 -217
  105. package/src/host-runtime.js +0 -127
  106. package/src/host-view.js +0 -75
  107. package/src/index.js +0 -206
  108. package/src/key-files.js +0 -54
  109. package/src/known-hosts.js +0 -133
  110. package/src/layout.js +0 -53
  111. package/src/local-download.js +0 -381
  112. package/src/local-ssh.js +0 -27
  113. package/src/local-version.js +0 -88
  114. package/src/node-runtime.js +0 -521
  115. package/src/probe.js +0 -101
  116. package/src/prompts.js +0 -229
  117. package/src/redact.js +0 -68
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -137
  120. package/src/remote-proc.js +0 -343
  121. package/src/remote-proxy.js +0 -815
  122. package/src/remote-web.js +0 -751
  123. package/src/request-trust.js +0 -89
  124. package/src/secrets.js +0 -109
  125. package/src/service.js +0 -459
  126. package/src/settings.js +0 -163
  127. package/src/ssh-config.js +0 -271
  128. package/src/ssh.js +0 -731
  129. package/src/store.js +0 -193
  130. package/src/tools.js +0 -386
  131. package/src/tunnel.js +0 -132
  132. package/src/util.js +0 -153
  133. package/src/version.js +0 -103
  134. package/src/webapp.js +0 -43
  135. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -0,0 +1,221 @@
1
+ // Host-side download jobs: each job streams one remote file or folder straight to the chosen local
2
+ // directory, publishing progress as it goes, and expires so a closed browser cannot pin a slot.
3
+ import { randomUUID } from 'node:crypto';
4
+ import { errors, toErrorView } from './errors.js';
5
+ import { normalizeRemoteFilePath, remoteFileName } from './remote-path.js';
6
+ import { readHostDownload } from './remote-files.js';
7
+ /** How long a finished job remains inspectable before it is pruned. */
8
+ export const DOWNLOAD_JOB_TTL_MS = 10 * 60 * 1000;
9
+ /** Maximum jobs retained at once (preparing + ready). */
10
+ export const MAX_DOWNLOAD_JOBS = 4;
11
+ /** Maximum jobs allowed to read SFTP at the same time. */
12
+ export const MAX_PREPARING_DOWNLOADS = 2;
13
+ /** Minimum interval between progress frames for one job. */
14
+ const PROGRESS_INTERVAL_MS = 120;
15
+ /** A positive safe integer override, or the production default. */
16
+ function positiveInt(value, fallback) {
17
+ return Number.isSafeInteger(value) && value > 0 ? value : fallback;
18
+ }
19
+ export function createDownloadJobs(options) {
20
+ const emit = typeof options.emit === 'function' ? options.emit : () => { };
21
+ const logger = options.logger ?? console;
22
+ const readDownload = typeof options.readDownload === 'function' ? options.readDownload : readHostDownload;
23
+ const ttlMs = positiveInt(options.ttlMs, DOWNLOAD_JOB_TTL_MS);
24
+ const maxJobs = positiveInt(options.maxJobs, MAX_DOWNLOAD_JOBS);
25
+ const maxPreparing = positiveInt(options.maxPreparing, MAX_PREPARING_DOWNLOADS);
26
+ const now = typeof options.now === 'function' ? options.now : Date.now;
27
+ const jobs = new Map();
28
+ const preparingCount = () => [...jobs.values()].filter((job) => job.phase === 'preparing').length;
29
+ const view = (job) => ({
30
+ id: job.id,
31
+ hostId: job.hostId,
32
+ path: job.path,
33
+ name: job.name,
34
+ kind: job.kind,
35
+ phase: job.phase,
36
+ totalBytes: job.totalBytes,
37
+ doneBytes: job.doneBytes,
38
+ totalFiles: job.totalFiles,
39
+ doneFiles: job.doneFiles,
40
+ ignoredNames: Array.isArray(job.ignoredNames) ? job.ignoredNames : [],
41
+ destination: job.destination ?? null,
42
+ startedAt: job.startedAt,
43
+ error: job.error,
44
+ });
45
+ const publish = (job, force = false) => {
46
+ if (job.cancelled || !jobs.has(job.id))
47
+ return;
48
+ const stamp = now();
49
+ if (!force && stamp - job.lastEmit < PROGRESS_INTERVAL_MS)
50
+ return;
51
+ job.lastEmit = stamp;
52
+ try {
53
+ emit(view(job));
54
+ }
55
+ catch (error) {
56
+ logger.warn?.('[dsh-remote-go] download progress listener failed:', error);
57
+ }
58
+ };
59
+ const clearTimer = (job) => {
60
+ if (job.timer !== null && typeof clearTimeout === 'function')
61
+ clearTimeout(job.timer);
62
+ job.timer = null;
63
+ };
64
+ const scheduleExpiry = (job) => {
65
+ clearTimer(job);
66
+ job.timer = setTimeout(() => {
67
+ if (jobs.get(job.id) === job) {
68
+ jobs.delete(job.id);
69
+ logger.debug?.('[dsh-remote-go] download job expired:', job.id);
70
+ }
71
+ }, ttlMs);
72
+ job.timer.unref?.();
73
+ };
74
+ const failJob = (job, error) => {
75
+ if (job.cancelled)
76
+ return;
77
+ job.phase = 'error';
78
+ job.error = toErrorView(error);
79
+ clearTimer(job);
80
+ publish(job, true);
81
+ scheduleExpiry(job);
82
+ };
83
+ const prepare = async (runtime, job) => {
84
+ try {
85
+ const result = await readDownload(runtime, job.path, {
86
+ destination: job.destination ?? undefined,
87
+ // The same home root the API pre-flight used; the write is judged by it again.
88
+ home: job.home,
89
+ isCancelled: () => job.cancelled === true,
90
+ onInventory: (info) => {
91
+ if (job.cancelled)
92
+ return;
93
+ if (Number.isFinite(info?.totalBytes))
94
+ job.totalBytes = Math.max(0, Number(info.totalBytes));
95
+ if (Number.isFinite(info?.totalFiles))
96
+ job.totalFiles = Math.max(0, Number(info.totalFiles));
97
+ publish(job);
98
+ },
99
+ onProgress: (info) => {
100
+ if (job.cancelled)
101
+ return;
102
+ if (Number.isFinite(info?.doneBytes))
103
+ job.doneBytes = Math.max(0, Number(info.doneBytes));
104
+ if (Number.isFinite(info?.totalBytes))
105
+ job.totalBytes = Math.max(0, Number(info.totalBytes));
106
+ if (Number.isFinite(info?.doneFiles))
107
+ job.doneFiles = Math.max(0, Number(info.doneFiles));
108
+ if (Number.isFinite(info?.totalFiles))
109
+ job.totalFiles = Math.max(0, Number(info.totalFiles));
110
+ publish(job);
111
+ },
112
+ // Folder downloads report the names they skipped (Windows-only metadata/shortcuts);
113
+ // `saveHostFolder` forwards this options object to the SSH layer unchanged.
114
+ onIgnored: (names) => {
115
+ if (job.cancelled || !Array.isArray(names))
116
+ return;
117
+ job.ignoredNames = names.slice(0, 200).map((name) => String(name));
118
+ publish(job);
119
+ },
120
+ });
121
+ if (job.cancelled)
122
+ return;
123
+ job.kind = result.kind;
124
+ job.name = result.name || remoteFileName(job.path);
125
+ job.destination = result.destination ?? job.destination;
126
+ job.totalBytes = Number(result.totalBytes ?? result.size ?? job.totalBytes ?? 0);
127
+ job.doneBytes = job.totalBytes;
128
+ job.totalFiles = Number(result.files ?? job.totalFiles ?? 0);
129
+ job.doneFiles = job.totalFiles;
130
+ job.phase = 'ready';
131
+ clearTimer(job);
132
+ publish(job, true);
133
+ scheduleExpiry(job);
134
+ }
135
+ catch (error) {
136
+ if (job.cancelled)
137
+ return;
138
+ logger.warn?.('[dsh-remote-go] download preparation failed:', error);
139
+ failJob(job, error);
140
+ }
141
+ };
142
+ return {
143
+ /** Create and start a download job; returns the initial view (phase `preparing`). */
144
+ start(runtime, rawPath, options = {}) {
145
+ const path = normalizeRemoteFilePath(rawPath);
146
+ if (jobs.size >= maxJobs) {
147
+ throw errors.downloadBusy({
148
+ zh: `最多同时保留 ${maxJobs} 个下载任务,请先完成或取消一个。`,
149
+ en: `At most ${maxJobs} download jobs can be kept; finish or cancel one first.`,
150
+ });
151
+ }
152
+ if (preparingCount() >= maxPreparing) {
153
+ throw errors.downloadBusy({
154
+ zh: `正在准备 ${maxPreparing} 个下载,请等一个完成后再试。`,
155
+ en: `${maxPreparing} downloads are already being prepared; wait for one to finish.`,
156
+ });
157
+ }
158
+ if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
159
+ throw errors.remoteFileUnavailable({
160
+ zh: '这台主机还没有连接,无法读取远端文件。',
161
+ en: 'This host is not connected, so the remote file cannot be read.',
162
+ });
163
+ }
164
+ const job = {
165
+ id: 'dl_' + randomUUID(),
166
+ hostId: runtime.id,
167
+ path,
168
+ name: remoteFileName(path),
169
+ kind: null,
170
+ phase: 'preparing',
171
+ totalBytes: 0,
172
+ doneBytes: 0,
173
+ totalFiles: 0,
174
+ doneFiles: 0,
175
+ ignoredNames: [],
176
+ destination: typeof options.destination === 'string' && options.destination !== '' ? options.destination : null,
177
+ home: typeof options.home === 'string' && options.home !== '' ? options.home : undefined,
178
+ startedAt: new Date(now()).toISOString(),
179
+ error: null,
180
+ timer: null,
181
+ lastEmit: 0,
182
+ cancelled: false,
183
+ };
184
+ jobs.set(job.id, job);
185
+ publish(job, true);
186
+ void prepare(runtime, job);
187
+ return view(job);
188
+ },
189
+ /** Current status of one job. */
190
+ status(id) {
191
+ const job = typeof id === 'string' ? jobs.get(id) : undefined;
192
+ if (!job) {
193
+ throw errors.downloadNotReady({
194
+ zh: '这个下载任务不存在或已过期,请重新发起下载。',
195
+ en: 'This download job no longer exists or expired; start the download again.',
196
+ });
197
+ }
198
+ return view(job);
199
+ },
200
+ /** Cancel one preparing/ready job. Returns false when it was already gone. */
201
+ cancel(id) {
202
+ const job = typeof id === 'string' ? jobs.get(id) : undefined;
203
+ if (!job)
204
+ return false;
205
+ job.cancelled = true;
206
+ clearTimer(job);
207
+ jobs.delete(job.id);
208
+ return true;
209
+ },
210
+ get size() {
211
+ return jobs.size;
212
+ },
213
+ dispose() {
214
+ for (const job of jobs.values()) {
215
+ job.cancelled = true;
216
+ clearTimer(job);
217
+ }
218
+ jobs.clear();
219
+ },
220
+ };
221
+ }
@@ -0,0 +1,228 @@
1
+ /** Coded, bilingual errors; `toErrorView` is the only shape the Client ever sees. */
2
+ import { redactObject, redactText } from './redact.js';
3
+ import { headTail } from './util.js';
4
+ const say = (zh, en) => ({ zh, en });
5
+ /** Every coded error: the Client's title, the retry default, and the detail and steps a bare call renders. */
6
+ const CATALOGUE = {
7
+ network: {
8
+ title: say('连不上这台服务器', 'Cannot reach this server'),
9
+ detail: say('网络不可达,可能被防火墙拦截或地址写错。', 'The network is unreachable — check the address, port and firewall.'),
10
+ steps: [
11
+ ['检查地址、端口与网络连通性', 'Check the address, port and network reachability'],
12
+ ['如果有跳板机,先确认跳板机可达', 'If a jump host is configured, verify it first'],
13
+ ],
14
+ },
15
+ auth: {
16
+ title: say('SSH 认证没有通过', 'SSH authentication failed'),
17
+ detail: say('远端拒绝了这次 SSH 认证。', 'The remote host rejected this SSH authentication.'),
18
+ steps: [
19
+ ['检查用户名与密钥 / SSH Agent', 'Check the user name and key / SSH agent'],
20
+ ['确认密钥文件路径与权限(0600)', 'Confirm the key file path and its 0600 permissions'],
21
+ ],
22
+ },
23
+ 'host-key-changed': {
24
+ retryable: false,
25
+ title: say('主机指纹变了', 'The host key changed'),
26
+ },
27
+ 'host-key-unknown': {
28
+ title: say('确认服务器指纹', 'Confirm the host key'),
29
+ },
30
+ 'remote-dsh-missing': {
31
+ title: say('远端没有可用的 DSH', 'No usable DSH on the remote host'),
32
+ detail: say('远端没有找到可用的 DSH,本机也无法自动准备运行环境。', 'No usable DSH was found and the runtime could not be prepared automatically.'),
33
+ steps: [
34
+ ['确认远端可以访问网络,或配置离线包', 'Check remote network access, or configure an offline package'],
35
+ ['也可以在远端手动安装 DSH 后重试', 'You can also install DSH manually on the remote host and retry'],
36
+ ],
37
+ },
38
+ 'remote-node-install-failed': {
39
+ title: say('远端 Node 自动安装失败', 'Automatic Node installation failed'),
40
+ detail: say('远端没有可用的 Node,自动安装也没有成功。', 'The remote has no usable Node and automatic installation did not succeed.'),
41
+ steps: [
42
+ [
43
+ '让远端可以访问 nodejs.org 或 npmmirror.com 后重试',
44
+ 'Allow the remote to reach nodejs.org or npmmirror.com and retry',
45
+ ],
46
+ [
47
+ '确认远端磁盘 ≥ 400 MB,且是受支持的 glibc 架构(musl/Alpine 不支持)',
48
+ 'Make sure the remote has >= 400 MB free and a supported glibc architecture (musl/Alpine is not supported)',
49
+ ],
50
+ ],
51
+ },
52
+ 'remote-dsh-start-failed': {
53
+ title: say('远端 DSH 启动失败', 'The remote DSH failed to start'),
54
+ },
55
+ 'remote-dsh-running': {
56
+ title: say('远端已有手工启动的 DSH', 'A manually started DSH is already running'),
57
+ detail: say('远端检测到不是本插件启动的 DSH 进程,连接已按你的选择取消。', 'The remote has a DSH process this plugin did not start; the connection was cancelled as you chose.'),
58
+ steps: [
59
+ [
60
+ '重新连接,并选择「停止它并启动受管实例」或「保留它,另起一个」',
61
+ 'Reconnect and choose "Stop it and start the managed instance" or "Keep it and start alongside"',
62
+ ],
63
+ ],
64
+ },
65
+ 'remote-ui-unreachable': {
66
+ title: say('远端界面打不开', 'The remote interface is unreachable'),
67
+ detail: say('隧道的本地回环端口无法完成远端界面的鉴权握手。', 'The loopback tunnel could not complete the remote UI authentication handshake.'),
68
+ steps: [
69
+ ['点「重连」重试一次', 'Retry with Reconnect'],
70
+ ['查看诊断中的隧道与界面可达性检查', 'Check tunnel and UI reachability in diagnostics'],
71
+ ],
72
+ },
73
+ 'remote-unreachable': {
74
+ title: say('远端 DSH 已不在运行', 'The remote DSH is no longer running'),
75
+ detail: say('远端 DSH 已经停止响应,而且没有找到可以重新挂载的实例;主机配置保留。', 'The remote DSH stopped responding and no instance could be re-attached to; the host configuration is kept.'),
76
+ steps: [
77
+ [
78
+ '点「重启」用同一份配置重新拉起远端进程',
79
+ 'Use "Restart" to start the remote process again with the same settings',
80
+ ],
81
+ ['点「重连」按存活策略重新连接', 'Use Reconnect to connect again under the keep-alive policy'],
82
+ ],
83
+ },
84
+ 'restart-unavailable': {
85
+ title: say('现在不能重启远端 DSH', 'The remote DSH cannot be restarted now'),
86
+ detail: say('只有已连接、或远端不可达但仍保留 SSH 连接的主机才能重启远端 DSH。', 'The remote DSH can only be restarted while this host is connected, or after a remote-unreachable failure that kept the SSH session.'),
87
+ steps: [
88
+ ['先连接这台主机,再点「重启」', 'Connect the host first, then use "Restart"'],
89
+ ['如果连接已断开,点「重连」重新建立连接', 'If the link dropped, use Reconnect to establish it again'],
90
+ ],
91
+ },
92
+ 'stop-unavailable': {
93
+ title: say('现在不能关闭远端 DSH', 'The remote DSH cannot be stopped now'),
94
+ detail: say('只有已连接、或远端不可达但仍保留 SSH 连接的主机才能关闭远端 DSH,而且只能关闭本连接启动或接管的那一个进程。', 'The remote DSH can only be stopped while this host is connected (or after a remote-unreachable failure that kept the SSH session), and only when it is the process this connection launched or took over.'),
95
+ steps: [
96
+ ['先连接这台主机,再点「关闭」', 'Connect the host first, then use "Stop"'],
97
+ [
98
+ '如果强烈怀疑远端进程不属于本连接,点「重连」重建连接后再试',
99
+ 'If the remote process may not belong to this connection, use Reconnect and try again',
100
+ ],
101
+ ],
102
+ },
103
+ 'remote-file-unavailable': {
104
+ title: say('无法读取远端文件', 'Cannot read the remote file'),
105
+ detail: say('远端路径不存在、不可读,或无法写入本地保存位置。', 'The remote path does not exist, is not readable, or the local destination cannot be written.'),
106
+ steps: [
107
+ ['确认文件仍在远端,且当前 SSH 用户可以读取', 'Confirm the file still exists and the SSH user can read it'],
108
+ [
109
+ '检查文件大小;过大的文件请先在远端压缩或拆分',
110
+ 'Check the file size; compress or split large files on the remote first',
111
+ ],
112
+ ],
113
+ },
114
+ 'download-not-ready': {
115
+ title: say('下载尚未准备好', 'The download is not ready'),
116
+ detail: say('这个下载还在准备中,或已经失效;请重新发起下载。', 'This download is still being prepared or has expired; start it again.'),
117
+ steps: [
118
+ ['等待进度条完成后再试', 'Wait for the progress bar to finish and retry'],
119
+ ['如果任务已失效,从远端文件树重新下载', 'If it expired, start the download again from the remote file tree'],
120
+ ],
121
+ },
122
+ 'download-busy': {
123
+ title: say('下载任务太多', 'Too many downloads are running'),
124
+ detail: say('同时准备的下载任务过多,请等一个完成后再试。', 'Too many downloads are being prepared at once; wait for one to finish and retry.'),
125
+ steps: [['取消不需要的下载,或稍后重试', 'Cancel an unneeded download, or retry later']],
126
+ },
127
+ 'version-mismatch': {
128
+ title: say('远端 DSH 版本与本机不一致', 'Remote DSH version differs from this machine'),
129
+ },
130
+ 'unsupported-os': {
131
+ retryable: false,
132
+ title: say('远端系统暂不支持', 'This remote system is not supported yet'),
133
+ },
134
+ 'invalid-input': {
135
+ retryable: false,
136
+ title: say('填写的信息有误', 'Some fields are invalid'),
137
+ },
138
+ internal: {
139
+ title: say('插件内部错误', 'Internal plugin error'),
140
+ },
141
+ };
142
+ /** One catalogue row by code, or `undefined` for a code this build does not know. */
143
+ function rowOf(code) {
144
+ return code in CATALOGUE ? CATALOGUE[code] : undefined;
145
+ }
146
+ export class RemoteGoError extends Error {
147
+ constructor(code, detail, options = {}) {
148
+ super(`${code}: ${detail.en}`);
149
+ this.name = 'RemoteGoError';
150
+ this.code = code;
151
+ this.detail = detail;
152
+ this.nextSteps = options.nextSteps ?? [];
153
+ this.technical = options.technical;
154
+ this.retryable = options.retryable ?? rowOf(code)?.retryable ?? true;
155
+ }
156
+ }
157
+ function fail(code, detail, steps, options = {}) {
158
+ return new RemoteGoError(code, detail, { nextSteps: steps.map(([zh, en]) => say(zh, en)), ...options });
159
+ }
160
+ /** The entry for one plain catalogue row: a caller-supplied detail wins over the default. */
161
+ function plain(code) {
162
+ const row = CATALOGUE[code];
163
+ return (detail = { ...row.detail }, options) => fail(code, detail, row.steps, options);
164
+ }
165
+ export const errors = {
166
+ network: plain('network'),
167
+ auth: plain('auth'),
168
+ hostKeyChanged: (pinned, actual) => fail('host-key-changed', say(`主机指纹和已记录的不一致:记录 ${pinned},实际 ${actual}。`, `The host key no longer matches the pinned value: pinned ${pinned}, actual ${actual}.`), [
169
+ [
170
+ '确认服务器是否重装或更换了证书;确认后再更新指纹',
171
+ 'Confirm the server was not reinstalled or tampered with before updating the pin',
172
+ ],
173
+ ], { retryable: false, technical: `pinned=${pinned} actual=${actual}` }),
174
+ hostKeyUnknown: (fingerprint) => fail('host-key-unknown', say(`首次连接该服务器(指纹 ${fingerprint}),需要你确认。`, `First connection to this host (fingerprint ${fingerprint}); confirmation required.`), [['核对指纹后选择「接受并记住」或取消', 'Verify the fingerprint, then accept and remember it or cancel']]),
175
+ remoteDshMissing: plain('remote-dsh-missing'),
176
+ nodeInstallFailed: plain('remote-node-install-failed'),
177
+ remoteDshRunning: plain('remote-dsh-running'),
178
+ remoteDshStartFailed: (tail) => fail('remote-dsh-start-failed', say('远端 DSH 进程没有成功打印 Web 地址,可能启动即失败。', 'The remote DSH process did not print its Web URL; startup likely failed.'), [
179
+ ['查看诊断里的远端日志尾部', 'Inspect the remote log tail in diagnostics'],
180
+ ['确认远端磁盘空间与端口可用', 'Check remote disk space and usable ports'],
181
+ [
182
+ '重试一次,若仍失败可手动在远端验证 `dsh --profile web --no-open`',
183
+ 'Retry, or verify `dsh --profile web --no-open` manually on the remote host',
184
+ ],
185
+ ], { technical: tail }),
186
+ remoteUiUnreachable: plain('remote-ui-unreachable'),
187
+ // Kept apart from `remote-ui-unreachable`: here the tunnel may be fine and the process is what is
188
+ // missing, which is what the restart button exists for.
189
+ remoteUnreachable: plain('remote-unreachable'),
190
+ // A restart is only offered while the host is connected or its SSH session survived a failure.
191
+ restartUnavailable: plain('restart-unavailable'),
192
+ // A stop must also prove the remote pid is the process this connection launched or took over.
193
+ stopRemoteUnavailable: plain('stop-unavailable'),
194
+ remoteFileUnavailable: plain('remote-file-unavailable'),
195
+ downloadNotReady: plain('download-not-ready'),
196
+ downloadBusy: plain('download-busy'),
197
+ versionMismatch: (local, remote) => fail('version-mismatch', say(`本机 DSH 是 ${local},远端是 ${remote};界面可能不一致,默认不静默混用。`, `This machine runs DSH ${local} while the remote runs ${remote}; the UI may differ and mixing silently is not allowed.`), [
198
+ ['选择「准备同版本运行时」后重试(推荐)', 'Prepare a matching runtime and retry (recommended)'],
199
+ ['明确选择「沿用远端版本」继续', 'Explicitly continue with the remote version'],
200
+ ]),
201
+ unsupportedOs: (os) => fail('unsupported-os', say(`V1 仅支持 Linux 远端,检测到 ${os}。`, `V1 supports Linux remotes only; detected ${os}.`), [['换一台 Linux 服务器,或等待后续版本', 'Use a Linux server, or wait for a later release']], { retryable: false }),
202
+ invalidInput: (field, detail) => fail('invalid-input', detail ?? say(`字段「${field}」不合法。`, `The field "${field}" is invalid.`), [['修正后重试', 'Fix it and retry']], { retryable: false }),
203
+ internal: (cause) => fail('internal', say('插件内部出现异常,可重试或查看诊断。', 'The plugin hit an internal error; retry or check diagnostics.'), [], { technical: cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause ?? '') }),
204
+ };
205
+ /** How much of one `ErrorView.technical` string the API will carry: producers hand over captured process output. */
206
+ export const TECHNICAL_LIMIT = 1200;
207
+ /** The only ErrorView a caller may send: redaction is part of the contract, not an opt-in. `technical` is the risky
208
+ * field — the first line of a remote `web.log` is the launch URL with its session token — so it is redacted and
209
+ * length-capped first, then the whole view crosses `redactObject` so a detail quoting such a line is covered too. */
210
+ export function toErrorView(error) {
211
+ if (error instanceof RemoteGoError) {
212
+ const row = rowOf(error.code);
213
+ const view = {
214
+ code: error.code,
215
+ title: row?.title ?? say('未知错误', 'Unknown error'),
216
+ detail: error.detail,
217
+ nextSteps: error.nextSteps,
218
+ retryable: error.retryable,
219
+ };
220
+ if (error.technical)
221
+ view.technical = headTail(redactText(error.technical), TECHNICAL_LIMIT);
222
+ return redactObject(view);
223
+ }
224
+ return toErrorView(errors.internal(error));
225
+ }
226
+ export function isRemoteGoError(error) {
227
+ return error instanceof RemoteGoError;
228
+ }