dsh-remote-go 0.1.0 → 0.3.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/README.md +64 -95
  2. package/{client.js → dist/client.js} +7805 -5486
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +46 -0
  5. package/dist/src/api.js +442 -0
  6. package/dist/src/atomic-json.js +235 -0
  7. package/dist/src/bootstrap.js +106 -0
  8. package/dist/src/connect/attach.js +43 -0
  9. package/dist/src/connect/bootstrap.js +14 -0
  10. package/dist/src/connect/failures.js +44 -0
  11. package/dist/src/connect/guards.js +31 -0
  12. package/dist/src/connect/launch.js +80 -0
  13. package/dist/src/connect/links.js +70 -0
  14. package/dist/src/connect/ownership.js +220 -0
  15. package/dist/src/connect/pipeline.js +473 -0
  16. package/dist/src/connect/reattach.js +215 -0
  17. package/dist/src/connect/registry.js +11 -0
  18. package/dist/src/connect/repair.js +126 -0
  19. package/dist/src/connect/restart.js +316 -0
  20. package/dist/src/connect/stop.js +198 -0
  21. package/dist/src/connect/transport.js +109 -0
  22. package/dist/src/connect/verify.js +39 -0
  23. package/dist/src/connect/watchdog.js +76 -0
  24. package/dist/src/connect-log.js +162 -0
  25. package/dist/src/connect-progress.js +142 -0
  26. package/dist/src/constants.js +67 -0
  27. package/dist/src/context.js +117 -0
  28. package/dist/src/diagnostics.js +102 -0
  29. package/dist/src/download-jobs.js +230 -0
  30. package/dist/src/errors.js +243 -0
  31. package/dist/src/events.js +390 -0
  32. package/dist/src/host-lifecycle.js +504 -0
  33. package/dist/src/host-registry.js +232 -0
  34. package/dist/src/host-runtime.js +86 -0
  35. package/dist/src/host-view.js +75 -0
  36. package/dist/src/index.js +216 -0
  37. package/dist/src/kernel-adapter.js +434 -0
  38. package/dist/src/key-files.js +52 -0
  39. package/dist/src/known-hosts.js +125 -0
  40. package/dist/src/layout.js +43 -0
  41. package/dist/src/local-download.js +380 -0
  42. package/dist/src/local-ssh.js +30 -0
  43. package/dist/src/local-version.js +101 -0
  44. package/dist/src/node/download.js +160 -0
  45. package/dist/src/node-runtime.js +346 -0
  46. package/dist/src/probe.js +96 -0
  47. package/dist/src/prompts.js +270 -0
  48. package/dist/src/proxy/cookies.js +136 -0
  49. package/dist/src/proxy/headers.js +262 -0
  50. package/dist/src/proxy/http.js +142 -0
  51. package/dist/src/proxy/index.js +135 -0
  52. package/dist/src/proxy/limits.js +8 -0
  53. package/dist/src/proxy/routes.js +39 -0
  54. package/dist/src/proxy/upgrade.js +175 -0
  55. package/dist/src/redact.js +104 -0
  56. package/dist/src/remote-files.js +72 -0
  57. package/dist/src/remote-path.js +123 -0
  58. package/dist/src/remote-proc.js +339 -0
  59. package/dist/src/remote-web/registry.js +147 -0
  60. package/dist/src/remote-web/resolve.js +310 -0
  61. package/dist/src/remote-web/start.js +227 -0
  62. package/dist/src/remote-web/stop.js +93 -0
  63. package/dist/src/request-trust.js +87 -0
  64. package/dist/src/runtime/dispatch.js +310 -0
  65. package/dist/src/runtime/effects.js +91 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +120 -0
  68. package/dist/src/runtime/rules.js +565 -0
  69. package/dist/src/secrets.js +142 -0
  70. package/dist/src/service.js +406 -0
  71. package/dist/src/settings.js +144 -0
  72. package/dist/src/ssh-config.js +276 -0
  73. package/dist/src/ssh-failures.js +122 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +297 -0
  76. package/dist/src/ssh.js +477 -0
  77. package/dist/src/store.js +191 -0
  78. package/dist/src/tool-shared.js +181 -0
  79. package/dist/src/tools-exec-policy.js +167 -0
  80. package/dist/src/tools-exec.js +371 -0
  81. package/dist/src/tools-report.js +424 -0
  82. package/dist/src/tools.js +411 -0
  83. package/dist/src/tunnel.js +129 -0
  84. package/dist/src/util.js +149 -0
  85. package/dist/src/version.js +114 -0
  86. package/dist/src/watchdog-bus.js +29 -0
  87. package/dist/src/watchdog.js +156 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +2 -2
  90. package/locale/zh.json +2 -2
  91. package/package.json +40 -21
  92. package/vendor/THIRD_PARTY_NOTICES.md +27 -1
  93. package/src/api.js +0 -340
  94. package/src/atomic-json.js +0 -208
  95. package/src/bootstrap.js +0 -100
  96. package/src/connect-log.js +0 -39
  97. package/src/connect-pipeline.js +0 -463
  98. package/src/connect-progress.js +0 -135
  99. package/src/constants.js +0 -31
  100. package/src/diagnostics.js +0 -157
  101. package/src/download-jobs.js +0 -217
  102. package/src/errors.js +0 -316
  103. package/src/host-lifecycle.js +0 -187
  104. package/src/host-registry.js +0 -145
  105. package/src/host-runtime.js +0 -53
  106. package/src/host-view.js +0 -51
  107. package/src/index.js +0 -162
  108. package/src/key-files.js +0 -49
  109. package/src/known-hosts.js +0 -94
  110. package/src/layout.js +0 -35
  111. package/src/local-download.js +0 -162
  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 -89
  116. package/src/prompts.js +0 -132
  117. package/src/redact.js +0 -54
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -73
  120. package/src/remote-proc.js +0 -208
  121. package/src/remote-web.js +0 -300
  122. package/src/secrets.js +0 -79
  123. package/src/service.js +0 -250
  124. package/src/settings.js +0 -135
  125. package/src/ssh-config.js +0 -271
  126. package/src/ssh.js +0 -652
  127. package/src/store.js +0 -143
  128. package/src/tunnel.js +0 -73
  129. package/src/util.js +0 -153
  130. package/src/version.js +0 -103
  131. package/src/webapp.js +0 -28
  132. package/vendor/ssh2-entry.mjs +0 -12
  133. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -1,157 +0,0 @@
1
- /**
2
- * The diagnostic checklist: read-only, opens no new connections.
3
- */
4
- import { isNodeVersionSupported, versionParity } from './version.js'
5
- import { nowIso } from './util.js'
6
- import { redactObject } from './redact.js'
7
-
8
- /** Check labels, so each `push` below is only about status and detail. */
9
- const TITLES = {
10
- 'ssh-reachable': { zh: 'SSH 可达性', en: 'SSH reachability' },
11
- auth: { zh: '认证方式', en: 'Authentication' },
12
- 'host-key': { zh: '主机指纹', en: 'Host key' },
13
- tunnel: { zh: '本地回环隧道', en: 'Loopback tunnel' },
14
- 'remote-service': { zh: '远端 DSH 服务', en: 'Remote DSH service' },
15
- 'remote-ui': { zh: '远端界面可达性', en: 'Remote UI reachability' },
16
- 'remote-node': { zh: '远端 Node 运行时', en: 'Remote Node runtime' },
17
- 'remote-version': { zh: '远端 DSH 版本', en: 'Remote DSH version' },
18
- 'model-credentials': { zh: '模型凭据', en: 'Model credentials' },
19
- 'desktop-guard': { zh: '远端桌面功能检查', en: 'Remote desktop guard' },
20
- }
21
-
22
- const NOT_PROBED = { zh: '未探测远端环境。', en: 'Remote environment has not been probed.' }
23
-
24
- const t = (zh, en) => ({ zh, en })
25
-
26
- export async function diagnoseHost(runtime, ctx) {
27
- const checks = []
28
- const push = (id, status, detail) => checks.push({ id, title: TITLES[id], status, detail })
29
- const entry = runtime.entry
30
- const facts = runtime.facts
31
- const sshLive = Boolean(runtime.ssh?.connected)
32
-
33
- push(
34
- 'ssh-reachable',
35
- sshLive ? 'pass' : runtime.error ? 'fail' : 'unknown',
36
- sshLive
37
- ? t(`已连接 ${entry.address}`, `Connected to ${entry.address}`)
38
- : (runtime.error?.detail ?? t('尚未连接,请先连接一次。', 'Not connected yet; connect once first.')),
39
- )
40
-
41
- const authType = entry.auth?.type ?? 'agent'
42
- push(
43
- 'auth',
44
- sshLive ? 'pass' : 'unknown',
45
- sshLive
46
- ? t(`认证方式:${authType}(凭据不会保存在本机)`, `Method: ${authType} (no credentials are stored locally)`)
47
- : t('连接后检查', 'Checked after connecting'),
48
- )
49
-
50
- const pinned = entry.pinnedFingerprint
51
- const liveFingerprint = runtime.fingerprint?.sha256 ?? null
52
- const keyStatus = pinned && liveFingerprint ? (pinned === liveFingerprint ? 'pass' : 'fail') : 'unknown'
53
- let keyDetail = t('尚未记录指纹,首次连接时会询问。', 'No host key recorded yet; it is asked on first connect.')
54
- if (pinned) {
55
- const session = liveFingerprint ? `,本次 ${liveFingerprint}` : ''
56
- keyDetail = t(
57
- `已记录 ${pinned}${session}`,
58
- `Pinned ${pinned}${liveFingerprint ? `, this session ${liveFingerprint}` : ''}`,
59
- )
60
- } else if (liveFingerprint) {
61
- keyDetail = t(`本次会话 ${liveFingerprint}(尚未记录)`, `This session ${liveFingerprint} (not pinned yet)`)
62
- }
63
- push('host-key', keyStatus, keyDetail)
64
-
65
- const tunnel = runtime.tunnel
66
- push(
67
- 'tunnel',
68
- tunnel ? 'pass' : 'fail',
69
- tunnel
70
- ? t(
71
- `127.0.0.1:${tunnel.localPort} → 远端 127.0.0.1:${runtime.remote.port ?? '未知'}`,
72
- `127.0.0.1:${tunnel.localPort} → remote 127.0.0.1:${runtime.remote.port ?? 'unknown'}`,
73
- )
74
- : t('隧道未建立(连接断开或尚未连接)。', 'The tunnel is not established (disconnected or not connected yet).'),
75
- )
76
-
77
- const remoteAlive = sshLive && runtime.exchange?.status === 200
78
- push(
79
- 'remote-service',
80
- remoteAlive ? 'pass' : sshLive ? 'fail' : 'unknown',
81
- remoteAlive
82
- ? t(
83
- `远端进程 pid=${runtime.remote.pid ?? '未知'},本地端口 ${runtime.remote.localPort ?? '未知'}`,
84
- `Remote pid ${runtime.remote.pid ?? 'unknown'}, local port ${runtime.remote.localPort ?? 'unknown'}`,
85
- )
86
- : t('远端服务未确认在运行。', 'The remote service is not confirmed running.'),
87
- )
88
-
89
- push(
90
- 'remote-ui',
91
- runtime.exchange?.ok ? 'pass' : sshLive ? 'fail' : 'unknown',
92
- runtime.exchange?.ok
93
- ? t(`页面标题:${runtime.exchange.title ?? '(无)'}`, `Page title: ${runtime.exchange.title ?? '(none)'}`)
94
- : t('尚未完成远端界面的鉴权握手。', 'The remote UI authentication handshake has not completed.'),
95
- )
96
-
97
- const nodeVersion = facts?.nodeVersion ?? null
98
- const nodeOk = isNodeVersionSupported(nodeVersion) && Boolean(facts?.npxPath)
99
- let nodeDetail = NOT_PROBED
100
- if (facts) {
101
- nodeDetail = nodeOk
102
- ? t(`Node ${nodeVersion}(插件托管),npx 可用`, `Node ${nodeVersion} (plugin-managed) with npx available`)
103
- : t(
104
- `Node ${nodeVersion ?? '未检测到'}${facts.npxPath ? '' : ',缺少 npx'},不满足 ≥ 24.9。`,
105
- `Node ${nodeVersion ?? 'not detected'}${facts.npxPath ? '' : ' (npx missing)'} does not meet >= 24.9.`,
106
- )
107
- }
108
- push('remote-node', facts ? (nodeOk ? 'pass' : 'fail') : 'unknown', nodeDetail)
109
-
110
- const parity = versionParity(ctx.targetVersion, runtime.remote.version ?? null)
111
- push('remote-version', parity.status === 'same' ? 'pass' : parity.status === 'different' ? 'fail' : 'unknown', {
112
- zh: parity.message.zh,
113
- en: parity.message.en,
114
- })
115
-
116
- const credentials = facts
117
- ? Boolean(facts.credentialsFile || facts.deepseekKeyEnv || facts.providerEnvKeys.length > 0)
118
- : false
119
- push(
120
- 'model-credentials',
121
- facts ? (credentials ? 'pass' : 'unknown') : 'unknown',
122
- facts
123
- ? credentials
124
- ? t('远端已检测到模型凭据配置。', 'Remote model credentials were detected.')
125
- : t('未检测到模型凭据;请在远端界面里配置。', 'No model credentials detected; configure them in the remote UI.')
126
- : NOT_PROBED,
127
- )
128
-
129
- push(
130
- 'desktop-guard',
131
- facts ? (facts.sshConnection ? 'pass' : 'unknown') : 'unknown',
132
- facts
133
- ? facts.sshConnection
134
- ? t(
135
- '远端 DSH 经 SSH 会话启动,宿主桌面功能已关闭。',
136
- 'The remote DSH runs inside an SSH session, so host desktop features stay off.',
137
- )
138
- : t(
139
- '远端未检测到 SSH 会话标记,目录对话框可能弹在远端屏幕上。',
140
- 'No SSH session marker on the remote; directory dialogs may appear on the remote screen.',
141
- )
142
- : NOT_PROBED,
143
- )
144
-
145
- const failed = checks.filter((check) => check.status === 'fail').length
146
- const unknown = checks.filter((check) => check.status === 'unknown').length
147
- const summary = failed > 0 ? 'error' : unknown > 0 ? 'warning' : 'ok'
148
- // Redaction is the contract of the exported report: tokens, passwords, private
149
- // keys and home directories never leave the machine.
150
- return redactObject({
151
- summary,
152
- checks,
153
- redacted: true,
154
- generatedAt: nowIso(),
155
- logs: runtime.logs.slice(-40).map((entry) => entry.line),
156
- })
157
- }
@@ -1,217 +0,0 @@
1
- /**
2
- * Host-side download jobs. Each job streams one remote file or folder directly into
3
- * the local directory the user chose; nothing is buffered in the Host. Jobs publish
4
- * progress and expire so a closed browser cannot pin job slots forever.
5
- */
6
- import { randomUUID } from 'node:crypto'
7
- import { errors, toErrorView } from './errors.js'
8
- import { normalizeRemoteFilePath, readHostDownload, remoteFileName } from './remote-files.js'
9
-
10
- /** How long a finished job remains inspectable before it is pruned. */
11
- export const DOWNLOAD_JOB_TTL_MS = 10 * 60 * 1000
12
- /** Maximum jobs retained at once (preparing + ready). */
13
- export const MAX_DOWNLOAD_JOBS = 4
14
- /** Maximum jobs allowed to read SFTP at the same time. */
15
- export const MAX_PREPARING_DOWNLOADS = 2
16
- /** Minimum interval between progress frames for one job. */
17
- const PROGRESS_INTERVAL_MS = 120
18
-
19
- /**
20
- * @param {{ emit: (job: object) => void, logger?: object, readDownload?: Function,
21
- * ttlMs?: number, maxJobs?: number, maxPreparing?: number, now?: () => number }} options
22
- */
23
- export function createDownloadJobs(options) {
24
- const emit = typeof options.emit === 'function' ? options.emit : () => {}
25
- const logger = options.logger ?? console
26
- const readDownload = typeof options.readDownload === 'function' ? options.readDownload : readHostDownload
27
- const ttlMs = Number.isSafeInteger(options.ttlMs) && options.ttlMs > 0 ? options.ttlMs : DOWNLOAD_JOB_TTL_MS
28
- const maxJobs = Number.isSafeInteger(options.maxJobs) && options.maxJobs > 0 ? options.maxJobs : MAX_DOWNLOAD_JOBS
29
- const maxPreparing =
30
- Number.isSafeInteger(options.maxPreparing) && options.maxPreparing > 0
31
- ? options.maxPreparing
32
- : MAX_PREPARING_DOWNLOADS
33
- const now = typeof options.now === 'function' ? options.now : Date.now
34
- const jobs = new Map()
35
-
36
- const preparingCount = () => [...jobs.values()].filter((job) => job.phase === 'preparing').length
37
-
38
- const view = (job) => ({
39
- id: job.id,
40
- hostId: job.hostId,
41
- path: job.path,
42
- name: job.name,
43
- kind: job.kind,
44
- phase: job.phase,
45
- totalBytes: job.totalBytes,
46
- doneBytes: job.doneBytes,
47
- totalFiles: job.totalFiles,
48
- doneFiles: job.doneFiles,
49
- destination: job.destination ?? null,
50
- startedAt: job.startedAt,
51
- error: job.error,
52
- })
53
-
54
- const publish = (job, force = false) => {
55
- if (job.cancelled || !jobs.has(job.id)) return
56
- const stamp = now()
57
- if (!force && stamp - job.lastEmit < PROGRESS_INTERVAL_MS) return
58
- job.lastEmit = stamp
59
- try {
60
- emit(view(job))
61
- } catch (error) {
62
- logger.warn?.('[dsh-remote-go] download progress listener failed:', error)
63
- }
64
- }
65
-
66
- const clearTimer = (job) => {
67
- if (job.timer !== null && typeof clearTimeout === 'function') clearTimeout(job.timer)
68
- job.timer = null
69
- }
70
-
71
- const scheduleExpiry = (job) => {
72
- clearTimer(job)
73
- job.timer = setTimeout(() => {
74
- if (jobs.get(job.id) === job) {
75
- jobs.delete(job.id)
76
- logger.debug?.('[dsh-remote-go] download job expired:', job.id)
77
- }
78
- }, ttlMs)
79
- job.timer.unref?.()
80
- }
81
-
82
- const failJob = (job, error) => {
83
- if (job.cancelled) return
84
- job.phase = 'error'
85
- job.error = toErrorView(error)
86
- clearTimer(job)
87
- publish(job, true)
88
- scheduleExpiry(job)
89
- }
90
-
91
- const prepare = async (runtime, job) => {
92
- try {
93
- const result = await readDownload(runtime, job.path, {
94
- destination: job.destination ?? undefined,
95
- isCancelled: () => job.cancelled === true,
96
- onInventory: (info) => {
97
- if (job.cancelled) return
98
- if (Number.isFinite(info?.totalBytes)) job.totalBytes = Math.max(0, Number(info.totalBytes))
99
- if (Number.isFinite(info?.totalFiles)) job.totalFiles = Math.max(0, Number(info.totalFiles))
100
- publish(job)
101
- },
102
- onProgress: (info) => {
103
- if (job.cancelled) return
104
- if (Number.isFinite(info?.doneBytes)) job.doneBytes = Math.max(0, Number(info.doneBytes))
105
- if (Number.isFinite(info?.totalBytes)) job.totalBytes = Math.max(0, Number(info.totalBytes))
106
- if (Number.isFinite(info?.doneFiles)) job.doneFiles = Math.max(0, Number(info.doneFiles))
107
- if (Number.isFinite(info?.totalFiles)) job.totalFiles = Math.max(0, Number(info.totalFiles))
108
- publish(job)
109
- },
110
- })
111
- if (job.cancelled) return
112
- job.kind = result.kind
113
- job.name = result.name || remoteFileName(job.path)
114
- job.destination = result.destination ?? job.destination
115
- job.totalBytes = Number(result.totalBytes ?? result.size ?? job.totalBytes ?? 0)
116
- job.doneBytes = job.totalBytes
117
- job.totalFiles = Number(result.files ?? job.totalFiles ?? 0)
118
- job.doneFiles = job.totalFiles
119
- job.phase = 'ready'
120
- clearTimer(job)
121
- publish(job, true)
122
- scheduleExpiry(job)
123
- } catch (error) {
124
- if (job.cancelled) return
125
- logger.warn?.('[dsh-remote-go] download preparation failed:', error)
126
- failJob(job, error)
127
- }
128
- }
129
-
130
- return {
131
- /**
132
- * Create and start a download job.
133
- * @param {object} runtime - connected host runtime.
134
- * @param {unknown} rawPath - absolute remote file or folder path.
135
- * @param {{ destination?: string }} [options] - local destination for a folder job.
136
- * @returns {object} the initial job view (phase `preparing`).
137
- */
138
- start(runtime, rawPath, options = {}) {
139
- const path = normalizeRemoteFilePath(rawPath)
140
- if (jobs.size >= maxJobs) {
141
- throw errors.downloadBusy({
142
- zh: `最多同时保留 ${maxJobs} 个下载任务,请先完成或取消一个。`,
143
- en: `At most ${maxJobs} download jobs can be kept; finish or cancel one first.`,
144
- })
145
- }
146
- if (preparingCount() >= maxPreparing) {
147
- throw errors.downloadBusy({
148
- zh: `正在准备 ${maxPreparing} 个下载,请等一个完成后再试。`,
149
- en: `${maxPreparing} downloads are already being prepared; wait for one to finish.`,
150
- })
151
- }
152
- if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
153
- throw errors.remoteFileUnavailable({
154
- zh: '这台主机还没有连接,无法读取远端文件。',
155
- en: 'This host is not connected, so the remote file cannot be read.',
156
- })
157
- }
158
- const job = {
159
- id: 'dl_' + randomUUID(),
160
- hostId: runtime.id,
161
- path,
162
- name: remoteFileName(path),
163
- kind: null,
164
- phase: 'preparing',
165
- totalBytes: 0,
166
- doneBytes: 0,
167
- totalFiles: 0,
168
- doneFiles: 0,
169
- destination: typeof options.destination === 'string' && options.destination !== '' ? options.destination : null,
170
- startedAt: new Date(now()).toISOString(),
171
- error: null,
172
- timer: null,
173
- lastEmit: 0,
174
- cancelled: false,
175
- }
176
- jobs.set(job.id, job)
177
- publish(job, true)
178
- void prepare(runtime, job)
179
- return view(job)
180
- },
181
-
182
- /** Current status of one job. */
183
- status(id) {
184
- const job = typeof id === 'string' ? jobs.get(id) : undefined
185
- if (!job) {
186
- throw errors.downloadNotReady({
187
- zh: '这个下载任务不存在或已过期,请重新发起下载。',
188
- en: 'This download job no longer exists or expired; start the download again.',
189
- })
190
- }
191
- return view(job)
192
- },
193
-
194
- /** Cancel one preparing/ready job. Returns false when it was already gone. */
195
- cancel(id) {
196
- const job = typeof id === 'string' ? jobs.get(id) : undefined
197
- if (!job) return false
198
- job.cancelled = true
199
- clearTimer(job)
200
- jobs.delete(job.id)
201
- return true
202
- },
203
-
204
- /** Number of retained jobs, for tests/diagnostics. */
205
- get size() {
206
- return jobs.size
207
- },
208
-
209
- dispose() {
210
- for (const job of jobs.values()) {
211
- job.cancelled = true
212
- clearTimer(job)
213
- }
214
- jobs.clear()
215
- },
216
- }
217
- }
package/src/errors.js DELETED
@@ -1,316 +0,0 @@
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
- }