dsh-remote-go 0.2.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 (134) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7710 -8182
  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/{src → dist/src}/constants.js +30 -56
  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 +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/diagnostics.js +0 -160
  100. package/src/download-jobs.js +0 -234
  101. package/src/errors.js +0 -412
  102. package/src/host-lifecycle.js +0 -604
  103. package/src/host-registry.js +0 -217
  104. package/src/host-runtime.js +0 -127
  105. package/src/host-view.js +0 -75
  106. package/src/index.js +0 -206
  107. package/src/key-files.js +0 -54
  108. package/src/known-hosts.js +0 -133
  109. package/src/layout.js +0 -53
  110. package/src/local-download.js +0 -381
  111. package/src/local-ssh.js +0 -27
  112. package/src/local-version.js +0 -88
  113. package/src/node-runtime.js +0 -521
  114. package/src/probe.js +0 -101
  115. package/src/prompts.js +0 -229
  116. package/src/redact.js +0 -68
  117. package/src/remote-files.js +0 -71
  118. package/src/remote-path.js +0 -137
  119. package/src/remote-proc.js +0 -343
  120. package/src/remote-proxy.js +0 -815
  121. package/src/remote-web.js +0 -751
  122. package/src/request-trust.js +0 -89
  123. package/src/secrets.js +0 -109
  124. package/src/service.js +0 -459
  125. package/src/settings.js +0 -163
  126. package/src/ssh-config.js +0 -271
  127. package/src/ssh.js +0 -731
  128. package/src/store.js +0 -193
  129. package/src/tools.js +0 -386
  130. package/src/tunnel.js +0 -132
  131. package/src/util.js +0 -153
  132. package/src/version.js +0 -103
  133. package/src/webapp.js +0 -43
  134. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
package/src/prompts.js DELETED
@@ -1,229 +0,0 @@
1
- /**
2
- * The two prompts a connection can pause on (unknown host key, foreign DSH already running) and the answers the Client sends back; each settles exactly once.
3
- */
4
- import { errors, toErrorView } from './errors.js'
5
- import { createDecision, nowIso } from './util.js'
6
-
7
- /**
8
- * Park the SSH handshake until the user answers the fingerprint prompt.
9
- *
10
- * A jump host and the target are different machines with different keys: the `role`
11
- * decides which context the answer belongs to, so a jump-host confirmation can never be
12
- * mistaken for the target's (B1).
13
- *
14
- * @param {object} ctx - service context.
15
- * @param {object} runtime - host runtime.
16
- * @param {{ sha256: string, keyType?: string }} info - the advertised host key.
17
- * @param {{ role?: 'target' | 'jump', host?: string | null }} [options]
18
- * @returns {Promise<boolean>} whether the user accepted the key.
19
- */
20
- export function requestHostKey(ctx, runtime, info, options = {}) {
21
- const role = options.role === 'jump' ? 'jump' : 'target'
22
- const isJump = role === 'jump'
23
- // A per-host policy describes the target the user saved. A jump host has its own
24
- // security context, so only the global policy applies to it.
25
- const policy = isJump
26
- ? (ctx.settings()?.hostKeyPolicy ?? 'first-use')
27
- : (runtime.entry.hostKeyPolicy ?? ctx.settings()?.hostKeyPolicy ?? 'first-use')
28
- if (policy === 'strict') throw errors.hostKeyUnknown(info.sha256)
29
- const hostLabel = isJump && options.host ? ` ${options.host}` : ''
30
- ctx.progress.log(
31
- runtime,
32
- 'info',
33
- `waiting for the ${isJump ? `jump host${hostLabel}` : 'host'} key to be confirmed (${
34
- info.keyType
35
- } ${info.sha256}); the SSH handshake is paused`,
36
- )
37
- const pending = {
38
- sha256: info.sha256,
39
- keyType: info.keyType,
40
- role,
41
- host: typeof options.host === 'string' && options.host !== '' ? options.host : null,
42
- port: Number(options.port) || 22,
43
- resolve: null,
44
- }
45
- const decision = createDecision(
46
- ctx.timers.hostKeyConfirmMs,
47
- () => {
48
- // A prompt whose link already went away must not overwrite the state of that teardown.
49
- if (runtime.pendingHostKey !== pending) return false
50
- runtime.pendingHostKey = null
51
- if (runtime.desired !== 'connected' || runtime.closing === true) return false
52
- runtime.connectCancelled = true
53
- ctx.progress.set(runtime, {
54
- status: 'error',
55
- phase: null,
56
- progress: null,
57
- error: toErrorView(errors.hostKeyUnknown(info.sha256)),
58
- })
59
- return false
60
- },
61
- () => {
62
- if (runtime.pendingHostKey === pending) runtime.pendingHostKey = null
63
- },
64
- )
65
- pending.resolve = decision.settle
66
- runtime.pendingHostKey = pending
67
- const fingerprint = { sha256: info.sha256, keyType: info.keyType, status: 'pending', pinned: null }
68
- if (isJump) {
69
- // The jump pin belongs to *this* jump host: an edited `jumpHost` must not be checked
70
- // against the previous machine's key (review blocker 3).
71
- runtime.jumpFingerprint = { ...fingerprint, host: pending.host, port: pending.port }
72
- // The Client's dialog renders `HostView.fingerprint`, so the key being confirmed right now
73
- // has to be the one shown there - even though the pin it may produce stays separate (B1).
74
- runtime.fingerprint = { ...fingerprint }
75
- } else {
76
- runtime.fingerprint = fingerprint
77
- }
78
- runtime.status = 'fingerprint-pending'
79
- runtime.phase = 'ssh'
80
- // The role only travels for a jump host: the target prompt keeps its original shape.
81
- runtime.progress = isJump
82
- ? {
83
- code: 'host-key-confirm',
84
- params: { sha256: info.sha256, keyType: info.keyType, role: 'jump', host: pending.host },
85
- }
86
- : { code: 'host-key-confirm', params: { sha256: info.sha256, keyType: info.keyType } }
87
- ctx.emitState()
88
- return decision.promise
89
- }
90
-
91
- /**
92
- * Answer the host-key prompt. Pinning is written straight through to the store so
93
- * a failed first attempt still remembers the key the user accepted.
94
- *
95
- * A jump host's key is remembered in memory only (`runtime.jumpFingerprint`): the store's
96
- * `pinnedFingerprint` describes the target, and writing a jump key there would pin the
97
- * target to the wrong machine forever (B1).
98
- */
99
- export async function confirmHostKey(ctx, runtime, decision) {
100
- const pending = runtime.pendingHostKey
101
- if (!pending) {
102
- throw errors.invalidInput('fingerprint', {
103
- zh: '没有待确认的主机指纹。',
104
- en: 'No host key is pending confirmation.',
105
- })
106
- }
107
- // A prompt is only answerable while it is the live one: a timeout, a disconnect or a
108
- // replacement attempt already settled it, and a late answer must not revive it (M1).
109
- if (runtime.status !== 'fingerprint-pending') {
110
- throw errors.invalidInput('fingerprint', {
111
- zh: '这个指纹提示已经失效,请在下次连接时重新确认。',
112
- en: 'This host-key prompt is no longer active; confirm the key on the next connection.',
113
- })
114
- }
115
- if (decision.sha256 && pending.sha256 && decision.sha256 !== pending.sha256) {
116
- throw errors.invalidInput('fingerprint', {
117
- zh: '确认的指纹与待确认的不一致。',
118
- en: 'The confirmed fingerprint does not match the pending one.',
119
- })
120
- }
121
- if (decision.accept !== true) runtime.connectCancelled = true
122
- if (decision.accept && decision.remember && pending.role !== 'jump') {
123
- await ctx.store.patchHost(runtime.id, { pinnedFingerprint: pending.sha256 })
124
- runtime.entry = { ...runtime.entry, pinnedFingerprint: pending.sha256 }
125
- }
126
- const fingerprint = {
127
- sha256: pending.sha256,
128
- keyType: pending.keyType,
129
- status: 'pinned',
130
- pinned: decision.remember ? pending.sha256 : null,
131
- }
132
- if (pending.role === 'jump') {
133
- // Keep the identity with the pin: the same remembered pin may only be used for the same
134
- // jump host and port (review blocker 3).
135
- runtime.jumpFingerprint = { ...fingerprint, host: pending.host, port: pending.port }
136
- // The dialog that asked about the jump host must not start describing the target as soon
137
- // as it is answered: keep showing what was confirmed until the target is dialled.
138
- runtime.fingerprint = { ...fingerprint }
139
- ctx.progress.log(
140
- runtime,
141
- 'info',
142
- `jump host key accepted${decision.remember ? ' and remembered for this session' : ''} (${
143
- pending.host ?? 'jump host'
144
- }: ${pending.sha256})`,
145
- )
146
- } else {
147
- runtime.fingerprint = fingerprint
148
- }
149
- runtime.pendingHostKey = null
150
- runtime.status = 'connecting'
151
- runtime.progress = { code: 'auth-checking' }
152
- pending.resolve(decision.accept === true)
153
- ctx.emitState()
154
- return { ok: true }
155
- }
156
-
157
- /**
158
- * Abandon a pending host-key prompt (teardown, host removal, lost transport). Resolving it
159
- * with `false` makes the stalled `verifyHostKey` throw instead of holding the connect
160
- * promise open until the prompt times out (M1).
161
- * @param {object} runtime - host runtime.
162
- */
163
- export function cancelHostKeyPrompt(runtime) {
164
- const pending = runtime.pendingHostKey
165
- runtime.pendingHostKey = null
166
- if (pending) pending.resolve(false)
167
- }
168
-
169
- /**
170
- * Pause the pipeline for a decision about foreign remote processes.
171
- * Mirrors the host-key prompt: a status, a promise, and a bounded timeout.
172
- */
173
- export function askConflict(ctx, runtime, processes) {
174
- runtime.status = 'conflict-pending'
175
- runtime.progress = { code: 'remote-dsh-running', params: { count: processes.length } }
176
- runtime.conflict = {
177
- detectedAt: nowIso(),
178
- processes: processes.slice(0, 20).map((process) => ({
179
- pid: process.pid,
180
- command: String(process.command ?? '').slice(0, 400),
181
- })),
182
- }
183
- ctx.emitState()
184
- const decision = createDecision(
185
- ctx.timers.conflictConfirmMs,
186
- () => ({ action: 'cancel', timedOut: true }),
187
- () => {
188
- if (runtime.pendingConflict?.resolve === decision.settle) runtime.pendingConflict = null
189
- runtime.conflict = null
190
- if (runtime.desired === 'connected') {
191
- runtime.status = 'connecting'
192
- runtime.progress = { code: 'probing' }
193
- }
194
- ctx.emitState()
195
- },
196
- )
197
- runtime.pendingConflict = { processes, resolve: decision.settle }
198
- return decision.promise
199
- }
200
-
201
- export function confirmConflict(runtime, decision) {
202
- const pending = runtime.pendingConflict
203
- if (!pending) {
204
- throw errors.invalidInput('conflict', {
205
- zh: '没有待确认的远端 DSH 冲突。',
206
- en: 'No remote DSH conflict is pending confirmation.',
207
- })
208
- }
209
- const action = decision?.action
210
- if (action !== 'stop' && action !== 'alongside' && action !== 'cancel') {
211
- throw errors.invalidInput('conflict', {
212
- zh: '请选择停止手工实例、与它并存,或取消连接。',
213
- en: 'Choose whether to stop the manual instance, keep it alongside, or cancel.',
214
- })
215
- }
216
- pending.resolve({ action })
217
- return { ok: true }
218
- }
219
-
220
- /**
221
- * Abandon a pending conflict prompt (teardown). Resolving it with `cancel` makes
222
- * the stalled `askConflict` call return instead of holding the pipeline open.
223
- */
224
- export function cancelConflict(runtime) {
225
- const pending = runtime.pendingConflict
226
- runtime.pendingConflict = null
227
- runtime.conflict = null
228
- if (pending) pending.resolve({ action: 'cancel' })
229
- }
package/src/redact.js DELETED
@@ -1,68 +0,0 @@
1
- /**
2
- * Diagnostics redaction: tokens, passwords and private keys never leave the machine in a diagnostic package.
3
- */
4
-
5
- const SECRET_QUERY_KEYS = ['token', 'access_token', 'api_key', 'apikey', 'key', 'secret', 'password', 'passwd', 'auth']
6
- const SECRET_HEADER_RE = /\b(authorization|cookie|set-cookie|x-api-key|proxy-authorization)\s*:\s*[^\r\n]+/gi
7
- /** Custom authentication headers (`x-auth-token`, `x-dsh-session-key`, …) are secrets too. */
8
- const SECRET_CUSTOM_HEADER_RE = /\b(x-[a-z0-9-]*(?:token|key|secret|auth)[a-z0-9-]*)\s*:\s*[^\r\n]+/gi
9
- const BEARER_RE = /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/g
10
- const TOKEN_QUERY_RE = new RegExp(`([?&](?:${SECRET_QUERY_KEYS.join('|')})=)[^&#\\s"']+`, 'gi')
11
- /**
12
- * A bare `token=…` outside a query string (log lines, `#fragment`, key=value dumps). The
13
- * value never contains `<`/`>` so an already-redacted `<redacted>` is left alone.
14
- */
15
- const BARE_TOKEN_KEYS = ['token', 'access_token', 'api_key', 'apikey', 'secret', 'password', 'passwd']
16
- const BARE_TOKEN_RE = new RegExp(`\\b((?:${BARE_TOKEN_KEYS.join('|')})\\s*=\\s*)[^\\s&;,'"<>]+`, 'gi')
17
- const PRIVATE_KEY_RE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g
18
- /**
19
- * `--password X`, `password=X` and the short `-p X` form. The short form is also ssh's
20
- * port flag (`ssh -p 2222`), so a bare number is left alone: a port is not a secret and
21
- * mangling it would make the technical detail unreadable.
22
- */
23
- const PASSWORD_FLAG_RE = /(--password[=\s]+|password[=:]\s*|-p\s+(?!\d+\b))(\S+)/gi
24
- const DSH_TOKEN_LINE_RE = /(dsh web:\s*\S*?\?token=)[A-Za-z0-9._~+/=-]+/g
25
-
26
- export function redactText(text, options = {}) {
27
- if (typeof text !== 'string' || text === '') return text
28
- let out = text
29
- out = out.replace(PRIVATE_KEY_RE, '-----BEGIN PRIVATE KEY-----<redacted>-----END PRIVATE KEY-----')
30
- out = out.replace(SECRET_HEADER_RE, (match) => `${match.split(':')[0]}: <redacted>`)
31
- out = out.replace(SECRET_CUSTOM_HEADER_RE, (match) => `${match.split(':')[0]}: <redacted>`)
32
- out = out.replace(BEARER_RE, (_match, scheme) => `${scheme} <redacted>`)
33
- out = out.replace(TOKEN_QUERY_RE, '$1<redacted>')
34
- out = out.replace(DSH_TOKEN_LINE_RE, '$1<redacted>')
35
- out = out.replace(BARE_TOKEN_RE, '$1<redacted>')
36
- out = out.replace(PASSWORD_FLAG_RE, '$1<redacted>')
37
- if (!options.keepPaths) {
38
- // Home directories of the remote account are not secrets, but avoid leaking
39
- // arbitrary local user names into exported diagnostics.
40
- out = out.replace(/(\/home\/)[^/\s]+/g, '$1<user>')
41
- out = out.replace(/(\/Users\/)[^/\s]+/g, '$1<user>')
42
- out = out.replace(/\b(C:\\Users\\)[^\\\s]+/gi, '$1<user>')
43
- }
44
- return out
45
- }
46
-
47
- function redactValue(key, value) {
48
- const lowered = String(key).toLowerCase()
49
- if (typeof value === 'string') {
50
- if (/(password|token|secret|passphrase|authorization|apikey|api_key|privatekey|cookie)/.test(lowered))
51
- return '<redacted>'
52
- return redactText(value)
53
- }
54
- if (Array.isArray(value)) return value.map((item) => redactValue(key, item))
55
- if (value && typeof value === 'object') return redactObject(value)
56
- return value
57
- }
58
-
59
- /**
60
- * Deep-redact a JSON-compatible value.
61
- */
62
- export function redactObject(value) {
63
- if (Array.isArray(value)) return /** @type {T} */ (value.map((item) => redactValue('', item)))
64
- if (!value || typeof value !== 'object') return value
65
- const out = {}
66
- for (const [key, item] of Object.entries(value)) out[key] = redactValue(key, item)
67
- return /** @type {T} */ (out)
68
- }
@@ -1,71 +0,0 @@
1
- /**
2
- * Remote download entry: validate an absolute Linux path, inspect it, then hand it
3
- * to the local writer. Both files and folders stream directly to disk; no bytes are
4
- * buffered in the Host and no ZIP is created.
5
- */
6
- import { errors, isRemoteGoError } from './errors.js'
7
- import { requireDestination, saveHostFile, saveHostFolder } from './local-download.js'
8
- import { normalizeRemoteFilePath } from './remote-path.js'
9
-
10
- export { normalizeRemoteFilePath, remoteFileName } from './remote-path.js'
11
-
12
- /**
13
- * Save one file or one folder for a download job.
14
- * @param {object} runtime - the connected host runtime.
15
- * @param {unknown} rawPath - the requested absolute remote path.
16
- * @param {{ destination?: string, home?: string, onProgress?: Function, onInventory?: Function,
17
- * isCancelled?: () => boolean }} [options]
18
- * @returns {Promise<{ path: string, kind: 'file'|'folder', name: string,
19
- * destination: string, totalBytes: number, files: number, cancelled?: boolean }>}
20
- */
21
- export async function readHostDownload(runtime, rawPath, options = {}) {
22
- if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
23
- throw errors.remoteFileUnavailable({
24
- zh: '这台主机还没有连接,无法读取远端内容。',
25
- en: 'This host is not connected, so the remote content cannot be read.',
26
- })
27
- }
28
- const remotePath = normalizeRemoteFilePath(rawPath)
29
- const ssh = runtime.ssh
30
- if (typeof ssh.inspectRemotePath !== 'function') {
31
- throw errors.internal('the SSH transport does not support path inspection')
32
- }
33
- let destination
34
- try {
35
- const info = await ssh.inspectRemotePath(remotePath)
36
- destination = await requireDestination(options.destination, { home: options.home })
37
- if (info.isFile) return await saveHostFile(runtime, remotePath, destination, options)
38
- if (info.isDirectory) return await saveHostFolder(runtime, remotePath, destination, options)
39
- throw errors.remoteFileUnavailable({
40
- zh: '这个远端路径既不是普通文件,也不是文件夹。',
41
- en: 'This remote path is neither a regular file nor a folder.',
42
- })
43
- } catch (error) {
44
- if (isRemoteGoError(error)) throw error
45
- throw toRemoteFileError(error)
46
- }
47
- }
48
-
49
- /**
50
- * Classify an SFTP failure without leaking transport internals to the client.
51
- * @param {unknown} error - the transport error.
52
- * @returns {import('./errors.js').RemoteGoError} a client-safe error.
53
- */
54
- export function toRemoteFileError(error) {
55
- if (isRemoteGoError(error)) return error
56
- const code = Number(/** @type {any} */ (error)?.code)
57
- const message = String(/** @type {any} */ (error?.message ?? error ?? ''))
58
- if (code === 2 || /no such file|not found/i.test(message)) {
59
- return errors.remoteFileUnavailable({
60
- zh: '远端文件不存在或已经被移动。',
61
- en: 'The remote file no longer exists or was moved.',
62
- })
63
- }
64
- if (code === 3 || /permission denied|access denied/i.test(message)) {
65
- return errors.remoteFileUnavailable({
66
- zh: '当前 SSH 用户没有读取这个远端路径的权限。',
67
- en: 'The SSH user is not allowed to read this remote path.',
68
- })
69
- }
70
- return errors.remoteFileUnavailable(undefined, { technical: message.slice(0, 300) })
71
- }
@@ -1,137 +0,0 @@
1
- /** Validation and naming for absolute remote POSIX paths. */
2
- import path from 'node:path'
3
- import { errors } from './errors.js'
4
-
5
- /** Longest accepted path, matching the remote contract of ordinary POSIX tools. */
6
- const MAX_PATH_CHARS = 4096
7
-
8
- /**
9
- * Validate and normalize a remote file path.
10
- * @param {unknown} value - path from the client request.
11
- * @returns {string} a normalized absolute POSIX path.
12
- */
13
- export function normalizeRemoteFilePath(value) {
14
- if (typeof value !== 'string') {
15
- throw errors.invalidInput('path', {
16
- zh: '远端文件路径必须是字符串。',
17
- en: 'The remote file path must be a string.',
18
- })
19
- }
20
- const text = value
21
- if (text === '') {
22
- throw errors.invalidInput('path', {
23
- zh: '远端文件路径不能为空。',
24
- en: 'The remote file path must not be empty.',
25
- })
26
- }
27
- if (text.length > MAX_PATH_CHARS) {
28
- throw errors.invalidInput('path', {
29
- zh: '远端文件路径过长。',
30
- en: 'The remote file path is too long.',
31
- })
32
- }
33
- if (text.includes('\0') || text.includes('\r') || text.includes('\n')) {
34
- throw errors.invalidInput('path', {
35
- zh: '远端文件路径包含不可用的控制字符。',
36
- en: 'The remote file path contains unsupported control characters.',
37
- })
38
- }
39
- if (!text.startsWith('/')) {
40
- throw errors.invalidInput('path', {
41
- zh: '远端文件路径必须是绝对路径。',
42
- en: 'The remote file path must be absolute.',
43
- })
44
- }
45
- const normalized = path.posix.normalize(text)
46
- if (!normalized.startsWith('/')) {
47
- throw errors.invalidInput('path', {
48
- zh: '远端文件路径必须是绝对路径。',
49
- en: 'The remote file path must be absolute.',
50
- })
51
- }
52
- return normalized
53
- }
54
-
55
- /**
56
- * The suggested download name for a remote path.
57
- * @param {string} remotePath - a normalized absolute path.
58
- * @returns {string} the last path segment, or a safe generic name.
59
- */
60
- export function remoteFileName(remotePath) {
61
- const name = path.posix.basename(remotePath)
62
- return name === '' || name === '/' || name === '.' || name === '..' ? 'download' : name
63
- }
64
-
65
- /** One local filename segment; Windows-safe so the same code works on every Desktop. */
66
- export function safeLocalSegment(value) {
67
- let text = String(value ?? '')
68
- .replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_')
69
- .replace(/[. ]+$/, '')
70
- if (text === '' || text === '.' || text === '..') text = '_'
71
- if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(text)) text = '_' + text
72
- return text
73
- }
74
-
75
- /**
76
- * Windows treats these names as its own metadata or as shell entries: writing them into
77
- * a download either corrupts a folder view (`desktop.ini`, `thumbs.db`) or leaves a file
78
- * that a double click executes instead of showing (`.lnk`, `.url`). A remote host never
79
- * gets to plant one in a local download.
80
- */
81
- const IGNORED_LOCAL_NAMES = new Set(['desktop.ini', 'thumbs.db', 'ehthumbs.db', '.ds_store'])
82
- const IGNORED_LOCAL_SUFFIXES = ['.lnk', '.url']
83
-
84
- /**
85
- * Whether a remote name must be left out of a local folder download.
86
- * @param {unknown} value - one remote path segment (file or directory name).
87
- * @returns {boolean}
88
- */
89
- export function isIgnoredLocalName(value) {
90
- const name = String(value ?? '')
91
- .trim()
92
- .toLowerCase()
93
- if (name === '') return false
94
- if (IGNORED_LOCAL_NAMES.has(name)) return true
95
- return IGNORED_LOCAL_SUFFIXES.some((suffix) => name.endsWith(suffix))
96
- }
97
-
98
- /**
99
- * Pick a local path that no earlier member of the same download already claimed.
100
- *
101
- * A case-insensitive filesystem (the Windows/macOS defaults) maps `Report.md` and
102
- * `report.md` to one file: keeping both names would silently drop one of the two remote
103
- * files. The later one is renamed `report (2).md` instead, so the file count on disk
104
- * matches the inventory.
105
- *
106
- * @param {string} desired - absolute local path the member maps to.
107
- * @param {Set<string>} taken - keys of the paths already claimed (use {@link localPathKey}).
108
- * @param {{ caseInsensitive?: boolean }} [options]
109
- * @returns {string} the chosen path (equal to `desired` when it is free).
110
- */
111
- export function uniqueLocalPath(desired, taken, options = {}) {
112
- const key = (value) => localPathKey(value, options)
113
- if (!taken.has(key(desired))) return desired
114
- const directory = path.dirname(desired)
115
- const extension = path.extname(desired)
116
- const base = path.basename(desired, extension)
117
- for (let index = 2; index < 1000; index += 1) {
118
- const candidate = path.join(directory, `${base} (${index})${extension}`)
119
- if (!taken.has(key(candidate))) return candidate
120
- }
121
- throw errors.remoteFileUnavailable({
122
- zh: '远端有太多文件映射到同一个本地文件名,无法安全保存。',
123
- en: 'Too many remote files map to the same local file name to save them safely.',
124
- })
125
- }
126
-
127
- /**
128
- * The collision key of a local path: separator-normalized, and lowercased when the local
129
- * filesystem ignores case.
130
- * @param {string} value - absolute or relative local path.
131
- * @param {{ caseInsensitive?: boolean }} [options]
132
- * @returns {string}
133
- */
134
- export function localPathKey(value, options = {}) {
135
- const text = String(value ?? '').replace(/\\/g, '/')
136
- return options.caseInsensitive === true ? text.toLowerCase() : text
137
- }