dsh-remote-deck 0.0.0-stage → 1.46.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 (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +227 -2
  3. package/README.zh-CN.md +201 -0
  4. package/client.js +8645 -0
  5. package/cordis.patch.yml +6 -0
  6. package/icon.svg +19 -0
  7. package/index.js +701 -0
  8. package/lib/api.js +1452 -0
  9. package/lib/bash-result.js +93 -0
  10. package/lib/connection.js +1133 -0
  11. package/lib/delete.js +199 -0
  12. package/lib/drafts.js +299 -0
  13. package/lib/encoding.js +247 -0
  14. package/lib/file-edit.js +339 -0
  15. package/lib/file-ops.js +402 -0
  16. package/lib/forwards.js +186 -0
  17. package/lib/fs-actions.js +235 -0
  18. package/lib/guide.js +162 -0
  19. package/lib/metrics.js +523 -0
  20. package/lib/remote-shells.js +320 -0
  21. package/lib/remote-terminal.js +427 -0
  22. package/lib/routing.js +695 -0
  23. package/lib/ssh-config.js +118 -0
  24. package/lib/terminal.js +123 -0
  25. package/lib/tool-forward.js +185 -0
  26. package/lib/transfer.js +235 -0
  27. package/lib/upload-chunks.js +306 -0
  28. package/lib/util.js +154 -0
  29. package/locale/README.md +160 -0
  30. package/locale/en-ui.json +477 -0
  31. package/locale/en.json +6 -0
  32. package/locale/zh.json +6 -0
  33. package/package.json +63 -4
  34. package/vendor/codemirror/LICENSE +21 -0
  35. package/vendor/codemirror/README.md +18 -0
  36. package/vendor/codemirror/addon/edit/closebrackets.min.js +8 -0
  37. package/vendor/codemirror/addon/edit/matchbrackets.min.js +8 -0
  38. package/vendor/codemirror/addon/search/search.min.js +8 -0
  39. package/vendor/codemirror/addon/search/searchcursor.min.js +8 -0
  40. package/vendor/codemirror/addon/selection/active-line.min.js +8 -0
  41. package/vendor/codemirror/lib/codemirror.css +344 -0
  42. package/vendor/codemirror/lib/codemirror.min.js +8 -0
  43. package/vendor/codemirror/mode/clike/clike.min.js +8 -0
  44. package/vendor/codemirror/mode/css/css.min.js +8 -0
  45. package/vendor/codemirror/mode/go/go.min.js +8 -0
  46. package/vendor/codemirror/mode/htmlmixed/htmlmixed.min.js +8 -0
  47. package/vendor/codemirror/mode/javascript/javascript.min.js +8 -0
  48. package/vendor/codemirror/mode/markdown/markdown.min.js +8 -0
  49. package/vendor/codemirror/mode/python/python.min.js +8 -0
  50. package/vendor/codemirror/mode/rust/rust.min.js +8 -0
  51. package/vendor/codemirror/mode/shell/shell.min.js +8 -0
  52. package/vendor/codemirror/mode/xml/xml.min.js +8 -0
  53. package/vendor/codemirror/mode/yaml/yaml.min.js +8 -0
  54. package/vendor/node_modules/asn1/Jenkinsfile +65 -0
  55. package/vendor/node_modules/asn1/LICENSE +19 -0
  56. package/vendor/node_modules/asn1/README.md +50 -0
  57. package/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
  58. package/vendor/node_modules/asn1/lib/ber/index.js +27 -0
  59. package/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
  60. package/vendor/node_modules/asn1/lib/ber/types.js +36 -0
  61. package/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
  62. package/vendor/node_modules/asn1/lib/index.js +20 -0
  63. package/vendor/node_modules/asn1/package.json +31 -0
  64. package/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
  65. package/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
  66. package/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
  67. package/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
  68. package/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
  69. package/vendor/node_modules/safer-buffer/LICENSE +21 -0
  70. package/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
  71. package/vendor/node_modules/safer-buffer/Readme.md +156 -0
  72. package/vendor/node_modules/safer-buffer/dangerous.js +58 -0
  73. package/vendor/node_modules/safer-buffer/package.json +34 -0
  74. package/vendor/node_modules/safer-buffer/safer.js +77 -0
  75. package/vendor/node_modules/safer-buffer/tests.js +406 -0
  76. package/vendor/node_modules/ssh2/LICENSE +19 -0
  77. package/vendor/node_modules/ssh2/README.md +1529 -0
  78. package/vendor/node_modules/ssh2/SFTP.md +413 -0
  79. package/vendor/node_modules/ssh2/lib/Channel.js +295 -0
  80. package/vendor/node_modules/ssh2/lib/agent.js +1123 -0
  81. package/vendor/node_modules/ssh2/lib/client.js +2176 -0
  82. package/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
  83. package/vendor/node_modules/ssh2/lib/index.js +44 -0
  84. package/vendor/node_modules/ssh2/lib/keygen.js +582 -0
  85. package/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
  86. package/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
  87. package/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
  88. package/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
  89. package/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
  90. package/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
  91. package/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
  92. package/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
  93. package/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
  94. package/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
  95. package/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
  96. package/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
  97. package/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
  98. package/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
  99. package/vendor/node_modules/ssh2/lib/server.js +1380 -0
  100. package/vendor/node_modules/ssh2/lib/utils.js +336 -0
  101. package/vendor/node_modules/ssh2/package.json +49 -0
  102. package/vendor/node_modules/tweetnacl/AUTHORS.md +28 -0
  103. package/vendor/node_modules/tweetnacl/CHANGELOG.md +221 -0
  104. package/vendor/node_modules/tweetnacl/LICENSE +24 -0
  105. package/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
  106. package/vendor/node_modules/tweetnacl/README.md +459 -0
  107. package/vendor/node_modules/tweetnacl/nacl-fast.js +2388 -0
  108. package/vendor/node_modules/tweetnacl/nacl-fast.min.js +2 -0
  109. package/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
  110. package/vendor/node_modules/tweetnacl/nacl.js +1175 -0
  111. package/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
  112. package/vendor/node_modules/tweetnacl/package.json +58 -0
  113. package/vendor/xterm/LICENSE.addon-fit +19 -0
  114. package/vendor/xterm/LICENSE.xterm +21 -0
  115. package/vendor/xterm/README.md +9 -0
  116. package/vendor/xterm/addon-fit.js +2 -0
  117. package/vendor/xterm/xterm.css +218 -0
  118. package/vendor/xterm/xterm.js +2 -0
@@ -0,0 +1,306 @@
1
+ /**
2
+ * Resumable uploads: the file page sends files larger than 8 MiB in 4 MiB
3
+ * parts, so a connection that drops mid-transfer can continue at the last byte
4
+ * the remote host actually has.
5
+ *
6
+ * The parts of one file collect in a temporary sibling of the destination:
7
+ * `<dir>/.dsh-part-<first 12 hex chars of sha1(name)>`. The name is hashed so a
8
+ * part file can never collide with the user's own `.dsh-part-*` file, and the
9
+ * directory keeps two same-named files in different folders apart. The
10
+ * protocol is the four routes in `lib/api.js`:
11
+ *
12
+ * - `status` only `stat`s the temporary file (`received` bytes, 0 when absent).
13
+ * - `part` writes one chunk at `offset`. Offset 0 recreates the file (a resumed
14
+ * upload may start over); every other offset must equal the current size or
15
+ * the request is refused with `OFFSET_MISMATCH` and the real byte count. A
16
+ * failed write leaves whatever the server accepted, and the next `status`
17
+ * tells the client where to continue — nothing here can create a hole.
18
+ * - `commit` renames the temporary file onto the destination. An existing
19
+ * destination is `EXISTS`, never a silent replacement (OpenSSH's rename would
20
+ * replace it), and a missing temporary file is `NOT_FOUND`.
21
+ * - `abort` deletes the temporary file and is idempotent.
22
+ *
23
+ * Path and name rules are the file page's own (`lib/fs-actions.js`), so a
24
+ * chunked upload accepts exactly what `rename`/`mkdir`/`touch` accept.
25
+ */
26
+ import { createHash } from 'node:crypto'
27
+ import { posix } from 'node:path'
28
+ import { entryKind } from './file-ops.js'
29
+ import { parseNameRequest } from './fs-actions.js'
30
+ import { sftpCall } from './util.js'
31
+
32
+ /** Largest part the `part` route accepts, in bytes. */
33
+ export const UPLOAD_PART_MAX_BYTES = 8 * 1024 * 1024
34
+ /** The temporary file's prefix inside the destination directory. */
35
+ export const UPLOAD_TEMP_PREFIX = '.dsh-part-'
36
+ /** How much of the name's SHA-1 the temporary file name carries. */
37
+ export const UPLOAD_TEMP_HASH_LENGTH = 12
38
+ /** No part carried any bytes. */
39
+ export const UPLOAD_EMPTY_PART_CODE = 'EMPTY_PART'
40
+ /** The part is larger than {@link UPLOAD_PART_MAX_BYTES}. */
41
+ export const UPLOAD_PART_TOO_LARGE_CODE = 'PART_TOO_LARGE'
42
+ /** `offset` was not a finite, non-negative integer. */
43
+ export const UPLOAD_BAD_OFFSET_CODE = 'BAD_OFFSET'
44
+ /** The remote temporary file is not where the client said it is. */
45
+ export const UPLOAD_OFFSET_MISMATCH_CODE = 'OFFSET_MISMATCH'
46
+ /** Something with the destination name is already there. */
47
+ export const UPLOAD_EXISTS_CODE = 'EXISTS'
48
+ /** The temporary file the commit/abort named is gone. */
49
+ export const UPLOAD_MISSING_CODE = 'NOT_FOUND'
50
+
51
+ /** SSH_FX_NO_SUCH_FILE, as ssh2 reports it. */
52
+ const SFTP_NO_SUCH_FILE = 2
53
+ /** `fsError('FS_NOT_FOUND')` from `sftpCall`, and the raw SFTP status code. */
54
+ const FS_NOT_FOUND = 'FS_NOT_FOUND'
55
+
56
+ function refuse(code, message) {
57
+ return { ok: false, code, message }
58
+ }
59
+
60
+ function isMissing(error) {
61
+ return Boolean(error) && (error.code === FS_NOT_FOUND || error.code === SFTP_NO_SUCH_FILE)
62
+ }
63
+
64
+ /**
65
+ * The temporary file one destination collects its parts in.
66
+ *
67
+ * @param {string} directory absolute remote POSIX directory
68
+ * @param {string} name one remote file name (only its hash reaches the path)
69
+ * @returns {string} absolute remote POSIX path
70
+ */
71
+ export function uploadTempPath(directory, name) {
72
+ const hash = createHash('sha1').update(String(name)).digest('hex').slice(0, UPLOAD_TEMP_HASH_LENGTH)
73
+ return posix.join(directory, UPLOAD_TEMP_PREFIX + hash)
74
+ }
75
+
76
+ /**
77
+ * Validate the `path` + `name` a status/part/commit/abort request names.
78
+ *
79
+ * @param {{ path?: unknown, name?: unknown }} value
80
+ * @returns {{ ok: true, dir: string, name: string, target: string, temp: string }
81
+ * | { ok: false, code: string, message: string }}
82
+ */
83
+ export function parseUploadTarget(value) {
84
+ const parsed = parseNameRequest(value)
85
+ if (parsed.ok !== true) return parsed
86
+ return {
87
+ ok: true,
88
+ dir: parsed.path,
89
+ name: parsed.name,
90
+ target: posix.join(parsed.path, parsed.name),
91
+ temp: uploadTempPath(parsed.path, parsed.name),
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Parse the `offset` query parameter. Query strings reach the route as text, so
97
+ * a run of digits is the only spelling accepted; a number (the module's own
98
+ * tests) must be a non-negative safe integer.
99
+ *
100
+ * @param {unknown} value
101
+ * @returns {{ ok: true, offset: number } | { ok: false, code: string, message: string }}
102
+ */
103
+ export function parseUploadOffset(value) {
104
+ let number = null
105
+ if (typeof value === 'number') number = value
106
+ else if (typeof value === 'string' && /^[0-9]+$/.test(value)) number = Number(value)
107
+ if (number === null || Number.isSafeInteger(number) !== true || number < 0) {
108
+ return refuse(UPLOAD_BAD_OFFSET_CODE, 'offset must be a non-negative integer.')
109
+ }
110
+ return { ok: true, offset: number }
111
+ }
112
+
113
+ function partBytes(data) {
114
+ if (data instanceof Uint8Array) return data
115
+ if (data instanceof ArrayBuffer) return new Uint8Array(data)
116
+ return null
117
+ }
118
+
119
+ /** Ask for a `stat`, folding "no such file" into `null`. */
120
+ async function statOrNull(invoke, sftp, path) {
121
+ try {
122
+ return await invoke(sftp, 'stat', path)
123
+ } catch (error) {
124
+ if (isMissing(error)) return null
125
+ throw error
126
+ }
127
+ }
128
+
129
+ /** Whether anything at all sits at `path`, links and dangling links included. */
130
+ async function pathExists(invoke, sftp, path) {
131
+ try {
132
+ await invoke(sftp, 'lstat', path)
133
+ return true
134
+ } catch (error) {
135
+ if (isMissing(error)) return false
136
+ throw error
137
+ }
138
+ }
139
+
140
+ /** The size `stat` reports, or 0 for a server that omits it. */
141
+ function sizeOf(attrs) {
142
+ const size = Number(attrs && attrs.size)
143
+ return Number.isFinite(size) && size > 0 ? Math.floor(size) : 0
144
+ }
145
+
146
+ /**
147
+ * How much of one file the remote already has.
148
+ *
149
+ * Read-only: a status for a file that was never started does not create the
150
+ * temporary file.
151
+ *
152
+ * @param {object} input `{ sftp, dir, name, call }`, `call` injectable for tests
153
+ * @returns {Promise<{ ok: true, exists: boolean, received: number }
154
+ * | { ok: false, code: string, message: string }>}
155
+ */
156
+ export async function readUploadStatus({ sftp, dir, name, call } = {}) {
157
+ const parsed = parseUploadTarget({ path: dir, name })
158
+ if (parsed.ok !== true) return parsed
159
+ const invoke = typeof call === 'function' ? call : sftpCall
160
+ const attrs = await statOrNull(invoke, sftp, parsed.temp)
161
+ if (attrs === null) return { ok: true, exists: false, received: 0 }
162
+ return { ok: true, exists: true, received: sizeOf(attrs) }
163
+ }
164
+
165
+ /**
166
+ * Write one part at `offset` of the file's temporary file.
167
+ *
168
+ * The current size is read first, so an offset that does not line up with the
169
+ * remote's file is refused before anything is written — the client's answer is
170
+ * always the byte count it should continue from. `offset === 0` recreates the
171
+ * temporary file (an explicit restart), every other offset appends.
172
+ *
173
+ * @param {object} input
174
+ * @param {object} input.sftp connected SFTP session
175
+ * @param {string} input.dir absolute remote POSIX directory
176
+ * @param {string} input.name destination file name
177
+ * @param {number|string} input.offset byte offset to write the chunk at
178
+ * @param {Uint8Array|ArrayBuffer} input.data raw chunk bytes
179
+ * @param {Function} [input.call] `sftpCall`, injectable for tests
180
+ * @returns {Promise<{ ok: true, received: number }
181
+ * | { ok: false, code: string, message: string, received?: number }>}
182
+ */
183
+ export async function writeUploadPart({ sftp, dir, name, offset, data, call } = {}) {
184
+ const parsed = parseUploadTarget({ path: dir, name })
185
+ if (parsed.ok !== true) return parsed
186
+ const position = parseUploadOffset(offset)
187
+ if (position.ok !== true) return position
188
+ const bytes = partBytes(data)
189
+ if (bytes === null) return refuse(UPLOAD_EMPTY_PART_CODE, 'A part body is required.')
190
+ if (bytes.length === 0) return refuse(UPLOAD_EMPTY_PART_CODE, 'A part cannot be empty.')
191
+ if (bytes.length > UPLOAD_PART_MAX_BYTES) {
192
+ return refuse(UPLOAD_PART_TOO_LARGE_CODE, `A part cannot be larger than ${UPLOAD_PART_MAX_BYTES} bytes.`)
193
+ }
194
+ const invoke = typeof call === 'function' ? call : sftpCall
195
+ const attrs = await statOrNull(invoke, sftp, parsed.temp)
196
+ const current = attrs === null ? 0 : sizeOf(attrs)
197
+ if (position.offset !== 0 && position.offset !== current) {
198
+ return {
199
+ ok: false,
200
+ code: UPLOAD_OFFSET_MISMATCH_CODE,
201
+ received: current,
202
+ message: `The remote has ${current} bytes; a part at ${position.offset} would leave a hole.`,
203
+ }
204
+ }
205
+ // `w` truncates and creates, `r+` keeps what is there and writes at a
206
+ // position. The stat above chose which one is correct.
207
+ const flags = position.offset === 0 ? 'w' : 'r+'
208
+ let handle
209
+ try {
210
+ handle = await invoke(sftp, 'open', parsed.temp, flags, 0o600)
211
+ } catch (error) {
212
+ if (isMissing(error)) {
213
+ // A missing parent directory is a real refusal: nothing could have been
214
+ // written, and no offset is right.
215
+ if (position.offset === 0) return refuse(UPLOAD_MISSING_CODE, 'The remote folder no longer exists.')
216
+ // Otherwise the temporary file vanished between the stat and the open:
217
+ // the client is as far behind as an empty file, and the answer says so.
218
+ return {
219
+ ok: false,
220
+ code: UPLOAD_OFFSET_MISMATCH_CODE,
221
+ received: 0,
222
+ message: 'The remote temporary file is gone; start from 0.',
223
+ }
224
+ }
225
+ throw error
226
+ }
227
+ try {
228
+ await invoke(sftp, 'write', handle, bytes, 0, bytes.length, position.offset)
229
+ } finally {
230
+ // A handle left open leaks an SFTP slot on the host; the write error is the
231
+ // one worth reporting, so a failing close stays silent.
232
+ await invoke(sftp, 'close', handle).catch(() => {})
233
+ }
234
+ return { ok: true, received: position.offset + bytes.length }
235
+ }
236
+
237
+ /**
238
+ * Rename the temporary file onto the destination.
239
+ *
240
+ * The destination is checked before the rename and again when the server
241
+ * refuses it, because OpenSSH's rename replaces silently and the rule here is
242
+ * that an existing name is reported, never replaced.
243
+ *
244
+ * @param {object} input `{ sftp, dir, name, call }`, as {@link readUploadStatus}
245
+ * @returns {Promise<{ ok: true, path: string } | { ok: false, code: string, message: string }>}
246
+ */
247
+ export async function commitUpload({ sftp, dir, name, overwrite, call } = {}) {
248
+ const parsed = parseUploadTarget({ path: dir, name })
249
+ if (parsed.ok !== true) return parsed
250
+ const invoke = typeof call === 'function' ? call : sftpCall
251
+ if (await pathExists(invoke, sftp, parsed.target)) {
252
+ // Never replace something unless the caller said so: the client asks the
253
+ // reader first and only then re-sends with `overwrite`.
254
+ if (overwrite !== true) {
255
+ return refuse(UPLOAD_EXISTS_CODE, `An entry named "${parsed.name}" is already there.`)
256
+ }
257
+ let existing = null
258
+ try {
259
+ existing = await invoke(sftp, 'lstat', parsed.target)
260
+ } catch (error) {
261
+ if (!isMissing(error)) throw error
262
+ }
263
+ if (existing !== null && entryKind(existing) !== 'file') {
264
+ return refuse(UPLOAD_EXISTS_CODE, `"${parsed.name}" is not a regular file; it will not be replaced.`)
265
+ }
266
+ try {
267
+ await invoke(sftp, 'unlink', parsed.target)
268
+ } catch (error) {
269
+ if (!isMissing(error)) throw error
270
+ }
271
+ }
272
+ if ((await pathExists(invoke, sftp, parsed.temp)) !== true) {
273
+ return refuse(UPLOAD_MISSING_CODE, 'The temporary upload file is not there any more.')
274
+ }
275
+ try {
276
+ await invoke(sftp, 'rename', parsed.temp, parsed.target)
277
+ } catch (error) {
278
+ // The rename may have failed for any reason; a destination that appeared
279
+ // meanwhile is the one outcome the client must not read as "server broken".
280
+ if (await pathExists(invoke, sftp, parsed.target)) {
281
+ return refuse(UPLOAD_EXISTS_CODE, `An entry named "${parsed.name}" is already there.`)
282
+ }
283
+ if (isMissing(error)) return refuse(UPLOAD_MISSING_CODE, 'The temporary upload file is not there any more.')
284
+ throw error
285
+ }
286
+ return { ok: true, path: parsed.target }
287
+ }
288
+
289
+ /**
290
+ * Delete the temporary file. Idempotent: aborting an upload that never started,
291
+ * or one that was already committed, still answers `ok`.
292
+ *
293
+ * @param {object} input `{ sftp, dir, name, call }`, as {@link readUploadStatus}
294
+ * @returns {Promise<{ ok: true }>}
295
+ */
296
+ export async function abortUpload({ sftp, dir, name, call } = {}) {
297
+ const parsed = parseUploadTarget({ path: dir, name })
298
+ if (parsed.ok !== true) return parsed
299
+ const invoke = typeof call === 'function' ? call : sftpCall
300
+ try {
301
+ await invoke(sftp, 'unlink', parsed.temp)
302
+ } catch (error) {
303
+ if (isMissing(error) !== true) throw error
304
+ }
305
+ return { ok: true }
306
+ }
package/lib/util.js ADDED
@@ -0,0 +1,154 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
3
+ import { basename, dirname, posix } from 'node:path'
4
+
5
+ export const MARKER = '.dsh-remote.json'
6
+ /** Upload and archive sizes are capped so one transfer cannot exhaust memory. */
7
+ export const MAX_TRANSFER_BYTES = 512 * 1024 * 1024
8
+ export const MAX_TEXT_BYTES = 8 * 1024 * 1024
9
+ export const HOST_COLORS = ['blue', 'teal', 'violet', 'amber', 'rose', 'cyan']
10
+
11
+ export function nowIso() {
12
+ return new Date().toISOString()
13
+ }
14
+
15
+ export function ensureDir(path) {
16
+ mkdirSync(path, { recursive: true })
17
+ }
18
+
19
+ export function readJsonFile(path, fallback) {
20
+ try {
21
+ const text = readFileSync(path, 'utf8')
22
+ return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text)
23
+ } catch {
24
+ return fallback
25
+ }
26
+ }
27
+
28
+ export function writeJsonFile(path, value, mode) {
29
+ ensureDir(dirname(path))
30
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode: mode || 0o600 })
31
+ }
32
+
33
+ export function fsError(code, message) {
34
+ const error = new Error(message)
35
+ error.code = code
36
+ return error
37
+ }
38
+
39
+ export function shellQuote(value) {
40
+ return `'${String(value).replace(/'/g, `'\\''`)}'`
41
+ }
42
+
43
+ /**
44
+ * A remote entry name that cannot escape the directory it is used in. Slashes,
45
+ * traversal pieces and control characters are rejected rather than rewritten.
46
+ */
47
+ export function safeRemoteName(value) {
48
+ const name = String(value ?? '').trim()
49
+ if (name.length === 0 || name === '.' || name === '..') return ''
50
+ if (/[\\/\u0000-\u001f]/.test(name)) return ''
51
+ return name
52
+ }
53
+
54
+ export function normalizeRemotePath(value) {
55
+ const normalized = posix.normalize(String(value || '/'))
56
+ return normalized.startsWith('/') ? normalized : `/${normalized}`
57
+ }
58
+
59
+ export function isPosixPath(value) {
60
+ return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//')
61
+ }
62
+
63
+ export function slugFor(remotePath) {
64
+ const base = basename(remotePath) || 'root'
65
+ const clean = base.replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 40) || 'root'
66
+ const hash = createHash('sha1').update(remotePath).digest('hex').slice(0, 8)
67
+ return `${clean}-${hash}`
68
+ }
69
+
70
+ export function statusSftpError(error) {
71
+ if (error === undefined || error === null) return fsError('FS_IO_ERROR', 'unknown SSH/SFTP failure')
72
+ const code = error.code
73
+ if (code === 2) return fsError('FS_NOT_FOUND', error.message || 'no such file')
74
+ if (code === 3) return fsError('FS_ACCESS_DENIED', error.message || 'permission denied')
75
+ if (code === 4) return fsError('FS_IO_ERROR', error.message || 'failure')
76
+ return fsError('FS_IO_ERROR', error.message || String(error))
77
+ }
78
+
79
+ /**
80
+ * Make a POSIX directory chain exist. Missing parents are created one level at
81
+ * a time so SFTP's non-recursive mkdir works on every sshd.
82
+ */
83
+ export async function ensureRemoteDir(sftp, target) {
84
+ const normalized = normalizeRemotePath(target)
85
+ const parts = normalized.split('/').filter(Boolean)
86
+ let current = ''
87
+ for (const part of parts) {
88
+ current += '/' + part
89
+ try {
90
+ const attrs = await sftpCall(sftp, 'stat', current)
91
+ if (attrsType(attrs) !== 'directory') throw fsError('REMOTE_DECK_NOT_DIR', `${current} is not a directory.`)
92
+ } catch (error) {
93
+ if (!(error && error.code === 'FS_NOT_FOUND')) throw error
94
+ try {
95
+ await sftpCall(sftp, 'mkdir', current)
96
+ } catch (mkdirError) {
97
+ const attrs = await sftpCall(sftp, 'stat', current).catch(() => null)
98
+ if (attrs === null || attrsType(attrs) !== 'directory') throw mkdirError
99
+ }
100
+ }
101
+ }
102
+ return normalized
103
+ }
104
+
105
+ /** SFTP operations get a finite deadline: a half-dead socket must not hang a
106
+ * filesystem tool (and the whole turn) forever. */
107
+ function sftpTimeoutMs() {
108
+ const raw = Number(process.env.DSH_REMOTE_DECK_SFTP_TIMEOUT_MS)
109
+ return Number.isFinite(raw) && raw > 0 ? raw : 60000
110
+ }
111
+
112
+ export function sftpCall(sftp, method, ...args) {
113
+ const timeoutMs = sftpTimeoutMs()
114
+ return new Promise((resolve, reject) => {
115
+ let settled = false
116
+ let timer = null
117
+ const fail = (error) => {
118
+ if (settled) return
119
+ settled = true
120
+ if (timer !== null) clearTimeout(timer)
121
+ reject(error)
122
+ }
123
+ const done = (error, value) => {
124
+ if (settled) return
125
+ settled = true
126
+ if (timer !== null) clearTimeout(timer)
127
+ if (error) reject(statusSftpError(error))
128
+ else resolve(value)
129
+ }
130
+ if (timeoutMs > 0) {
131
+ timer = setTimeout(() => fail(fsError('REMOTE_DECK_TIMEOUT', `SFTP ${method} did not finish within ${timeoutMs}ms`)), timeoutMs)
132
+ }
133
+ try {
134
+ sftp[method](...args, done)
135
+ } catch (error) {
136
+ fail(statusSftpError(error))
137
+ }
138
+ })
139
+ }
140
+
141
+ export function attrsVersion(attrs) {
142
+ return `${Math.floor((attrs.mtime || 0) * 1000)}:${attrs.size || 0}`
143
+ }
144
+
145
+ export function attrsType(attrs) {
146
+ if (attrs.isDirectory && attrs.isDirectory()) return 'directory'
147
+ if (attrs.isFile && attrs.isFile()) return 'file'
148
+ if (attrs.isSymbolicLink && attrs.isSymbolicLink()) return 'symlink'
149
+ return 'other'
150
+ }
151
+
152
+ export function errorText(error) {
153
+ return error instanceof Error ? error.message : String(error)
154
+ }
@@ -0,0 +1,160 @@
1
+ # 英文界面词条表(`locale/en-ui.json`)
2
+
3
+ Remote Deck 客户端(`client.js`)的中文界面文案 → 英文。运行时以**中文原文作为 key** 查表:命中显示英文,未命中回退中文原文。因此本文件只做"查表"用途,不改变任何代码行为。
4
+
5
+ - 词条数:**443** 条(完整字符串 339 条 + 参数化模板 104 条)
6
+ - 数据来源:`client.js` 的字符串字面量(生成时的快照;若之后代码新增中文文案,需要补词条)
7
+
8
+ ## 1. 格式
9
+
10
+ - 扁平 JSON 对象,`{ "中文原文": "English" }`,不嵌套、不带注释。
11
+ - UTF-8(无 BOM),2 空格缩进,末尾换行;key 按 Unicode 码点排序(JS `Array#sort` 的默认顺序),保证每次生成 diff 稳定。
12
+ - key 必须与 `client.js` 里的中文字符串**逐字符一致**,包括:全角标点(`():,。?!…`)、`·`、`「」`、数字区间里的 `–`、以及**首尾空格**。
13
+ - 少数 key 以空格开头/结尾(代码拼接时真实存在的形态),**不要 trim**:
14
+
15
+ | key | 说明 |
16
+ | --- | --- |
17
+ | `" 等"` | 列表后缀,如 `A、B、C` + `" 等"` |
18
+ | `" · 只读(编码无法无损写回)"` | 编辑器状态栏后缀,保留前导 ` · ` |
19
+ | `"已检测到 {n} 个密钥:{keys} · "` | 末尾 ` · ` 是分隔符 |
20
+
21
+ - 只收录含汉字的字符串;纯英文、技术标识、注释、正则表达式不在表内(见 §4)。插件元数据(`locale/en.json`、`locale/zh.json`)与本表无关,未改动。
22
+
23
+ ```json
24
+ {
25
+ "上传到此处": "Upload here",
26
+ "已上传 {n} 个文件": "Uploaded {n} files",
27
+ "保存中…": "Saving…"
28
+ }
29
+ ```
30
+
31
+ ## 2. 占位符规则
32
+
33
+ - 语法:`{name}`。名字以小写字母开头,只含字母/数字,语义化命名;不支持嵌套、默认值、转义或表达式。
34
+ - 同一个 key 中可以出现多个占位符;占位符之间可以夹中文标点或空格,这些字符原样保留在译文里。
35
+ - 运行时做一次全局替换即可(示意实现):
36
+
37
+ ```js
38
+ const t = (key, params) =>
39
+ (dict[key] ?? key).replace(/\{([a-z][A-Za-z0-9]*)\}/g, (m, name) => params?.[name] ?? m)
40
+ ```
41
+
42
+ - 参数名约定(同义场景保持同名):
43
+
44
+ | 占位符 | 含义 | 示例 |
45
+ | --- | --- | --- |
46
+ | `{n}` | 通用数量 | `已上传 {n}` / `{n} 个会话` |
47
+ | `{name}` | 文件名、主机名、对象名 | `{name} 上传失败` |
48
+ | `{path}` | 完整远端路径 | `已保存到 {path}` |
49
+ | `{dirname}` | 目录名/当前目录(较短) | `上传文件到 {dirname}` |
50
+ | `{size}` | 已格式化体积文本(如 `1.5 MiB`) | `超过 {size} 的文件…` |
51
+ | `{sent}` / `{total}` | 已传字节数 / 总字节数(已格式化) | `已传 {sent} / {total}` |
52
+ | `{percent}` | 百分比数值(不带 `%`) | `(已传 {percent}%,…)` |
53
+ | `{time}` | 时间文本(`clockOf()` 的输出) | `更新于 {time}` |
54
+ | `{host}` | 远端主机名 | `打开 {host} 的端口转发` |
55
+ | `{port}` | 端口号 | `已转发到 {port}` |
56
+ | `{limit}` | 上限的展示文本(如 `512 MB`) | `超过远端 {limit} 上限` |
57
+ | `{count}` / `{index}` | 次数 / 序号 | `连续 {count} 次上传失败` |
58
+ | `{message}` / `{reason}` | 错误详情文本 | `文件面板出错:{message}` |
59
+ | `{done}` / `{failed}` | 成功数 / 失败数 | `成功 {done} / 失败 {failed}` |
60
+ | `{files}` / `{dirs}` | 文件数 / 目录数 | `{files} 个文件、{dirs} 个目录` |
61
+ | `{keys}` | 密钥文件名列表(已 join) | `已检测到 {n} 个密钥:{keys}` |
62
+ | `{connected}` / `{workspaces}` | 在线主机数 / 工作区数 | `{connected} 台在线 · {workspaces} 个工作区` |
63
+ | `{lines}` | 行数 | `{lines} 行 · …` |
64
+ | `{status}` | 状态词(本身也是词条) | `{lines} 行 · {size} · {status}` |
65
+ | `{encoding}` | 编码名(`UTF-8`、`GBK` 等) | `按 {encoding} 打开` |
66
+ | `{section}` | 监控指标名(CPU / Memory / Disk 的词条) | `{section} 告警阈值` |
67
+ | `{value}` / `{threshold}` | 指标值 / 阈值 | `{section} {value} 超过 {threshold}%` |
68
+ | `{mount}` / `{available}` | 挂载点 / 可用空间 | `{mount} · {available} 可用 / {total}` |
69
+ | `{items}` | 已 join 的并列项 | `其中 {items} 将被跳过。` |
70
+ | `{state}` | 开关状态词(`开`/`关` 的词条) | `自动连接:{state}` |
71
+
72
+ - **参数值本身也要走同一张表**:`{state}` 传 `t('开')`,`{section}` 传 `t('内存')`,`{status}` 传 `t('已保存')`,`{reason}` / `{message}` 传已经翻译过的错误文本。否则英文句子里夹中文。
73
+ - 英文不做复数、时态、格的变化:模板按常见数量写(如 `{n} files`)。需要严格的单复数/`Moved` vs `Move` 时,在调用侧拆成两条 key 或单独处理。
74
+ - 参数缺失时,示例实现会保留 `{name}` 原样,便于暴露漏传。
75
+ - **模板 key 在 `client.js` 里不是整串字面量**,这是正常的。可验证性规则:去掉所有 `{…}` 后,剩下的每个中文字段都必须能在 `client.js` 的字符串字面量里找到;本文件即按此规则校验。
76
+
77
+ ## 3. 提取与过滤规则(本次生成方式)
78
+
79
+ 1. 对 `client.js` 做词法扫描:跳过 `//`、`/* */` 注释、正则字面量、模板字符串;收集单引号/双引号字符串字面量。
80
+ 2. 只保留含汉字的字符串(`[\u4e00-\u9fff]`),按**运行时值**(去转义后)去重。
81
+ 3. 对 `+` 拼接:只出现在拼接里的 **127** 个片段不单独立条,而是合并成 **104** 条带 `{占位符}` 的模板;完整字符串直接成条。
82
+ 4. 过滤掉:注释里的中文、正则里的中文、技术标识、纯英文/专有名词、无汉字的中文标点(详见 §4)。
83
+ 5. 生成后自检:JSON 可解析、无重复 key、无空值;每条 key 都能在 `client.js` 找到(完整字面量逐字匹配;模板按片段匹配);127 个拼接片段全部被模板覆盖。
84
+
85
+ ## 4. 有意不翻译的清单
86
+
87
+ 1. **代码注释**——不进入 UI。例如 `// The built-in 工作区文件 page offers an action slot…`、`// … offers 放弃修改并关闭 instead.`。
88
+ 2. **用于匹配后端错误文本的正则**——`/timeout|超时/`、`/transfer_too_large|too large|超过.*上限|512mb/`:必须保留中文才能命中,翻译会导致错误映射失效。
89
+ 3. **技术标识与协议字段**——`rd-*` / `remote-deck-*` 类名与 id、`data-*`(如 `data-rd-theme`)、`remote_forward`(工具名,出现在译文句子里时保留原样)、`dsh-resource://…`、`x-dsh-remote-token`、错误码(`EXISTS`、`OFFSET_MISMATCH`、`TRANSFER_TOO_LARGE` 等)、CodeMirror mode 名(`javascript`、`htmlmixed` 等)、文件扩展名列表。
90
+ 4. **专有名词与单位**——Remote Deck、DSH、SSH、SFTP、CodeMirror、CPU、Memory、Disk、MiB、MB、ms、%;以及 `~/.ssh/config`、`/etc/hosts`、`known_hosts`、`sshd` 等路径/命令名。这些在英文句子里原样保留,不改成"兆字节"之类的意译。
91
+ 5. **无汉字的中文标点连接符**——`','`(`parts.join(',')`)、`'、'`(列表 join)、`'。'`(打包摘要末尾句号)。它们不在词条表里,需要实现方在拼接处按语言替换(例如英文用 `", "`、`"."`)。`'('` / `')'` / `'「'` / `'」'` 大多已随模板 key 成对收录,只有独立拼接的括号需要单独处理。
92
+ 6. `aria-*` / `title` 中的中文是**用户可见**的提示与无障碍标签,**已收录翻译**;只有纯技术标识(如 `rd-set-field-…`)不收录。
93
+
94
+ ## 5. 运行时拼接 → 建议 key(40 条常见形式)
95
+
96
+ | 源码写法(示意) | 建议 key | English |
97
+ | --- | --- | --- |
98
+ | `'已上传 ' + done + ' 个文件'` | `已上传 {n} 个文件` | Uploaded {n} files |
99
+ | `'已上传 ' + done` | `已上传 {n}` | Uploaded {n} |
100
+ | `name + ' 上传失败'` | `{name} 上传失败` | {name} failed to upload |
101
+ | `'删除 ' + targets.length + ' 项'` | `删除 {n} 项` | Delete {n} items |
102
+ | `'已永久删除 ' + done + ' 项'` | `已永久删除 {n} 项` | Deleted {n} items permanently |
103
+ | `'已永久删除 ' + list[0].name` | `已永久删除 {name}` | Deleted {name} permanently |
104
+ | `'永久删除 ' + single.path` | `永久删除 {path}` | Permanently delete {path} |
105
+ | `'永久删除选中的 ' + targets.length + ' 项'` | `永久删除选中的 {n} 项` | Permanently delete the {n} selected items |
106
+ | `'永久删除 ' + targets.length + ' 项?'` | `永久删除 {n} 项?` | Permanently delete {n} items? |
107
+ | `'将永久删除 ' + targets.length + ' 项(含目录递归),不可恢复。'` | `将永久删除 {n} 项(含目录递归),不可恢复。` | This permanently deletes {n} items, including folders and everything inside them. It can't be undone. |
108
+ | `'已保存到 ' + result.localPath` | `已保存到 {path}` | Saved to {path} |
109
+ | `'已开始下载 ' + entry.name` | `已开始下载 {name}` | Downloading {name} |
110
+ | `'下载 ' + targets.length + ' 项(打包)'` | `下载 {n} 项(打包)` | Download {n} items (tar.gz) |
111
+ | `'已重命名为 ' + parsed.name` | `已重命名为 {name}` | Renamed to {name} |
112
+ | `'已新建文件夹 ' + parsed.name` | `已新建文件夹 {name}` | Created folder {name} |
113
+ | `'已新建文件 ' + parsed.name` | `已新建文件 {name}` | Created file {name} |
114
+ | `'上传中 ' + (done + failed + skipped) + '/' + list.length` | `上传中 {current}/{total}` | Uploading {current}/{total} |
115
+ | `'上传中 0/' + list.length` | `上传中 0/{total}` | Uploading 0/{total} |
116
+ | `'第 ' + (index + 1) + '/' + list.length + ' 个文件。可跳过此文件、跳过该目录,或停止本次上传。'` | `第 {index}/{total} 个文件。可跳过此文件、跳过该目录,或停止本次上传。` | File {index}/{total}. Skip this file, skip its folder, or stop the upload. |
117
+ | `'「' + name + '」超过远端 ' + uploadLimitLabel(...) + ' 上限,未上传。'` | `「{name}」超过远端 {limit} 上限,未上传。` | {name} exceeds the remote {limit} limit; not uploaded. |
118
+ | `'创建目录失败:' + message` | `创建目录失败:{message}` | Couldn't create folder: {message} |
119
+ | `'文件面板出错:' + friendlyText(error)` | `文件面板出错:{message}` | File panel error: {message} |
120
+ | `'其中 ' + skipped.join('、') + '将被跳过。'` | `其中 {items} 将被跳过。` | {items} will be skipped. |
121
+ | `'将打包 ' + countOf(scan.files) + ' 个文件' + (size ? '(约 ' + size + ')' : '') + '。'` | `将打包 {files} 个文件(约 {size})。` 或 `将打包 {files} 个文件。` | Archive {files} files (about {size}). |
122
+ | `'超过 ' + formatBytes(EDIT_MAX_BYTES) + ' 的文件不在编辑器里打开:只载入一部分会让保存截断原文件。'` | `超过 {size} 的文件不在编辑器里打开:只载入一部分会让保存截断原文件。` | Files larger than {size} don't open in the editor: loading only part of one would truncate it on save. |
123
+ | `'按 ' + guessedEncoding.toUpperCase() + ' 打开'` | `按 {encoding} 打开` | Open as {encoding} |
124
+ | `'检测到未保存的草稿(' + clockOf(draftOffer.savedAt) + ')'` | `检测到未保存的草稿({time})` | Found an unsaved draft ({time}) |
125
+ | `'在远端文件中打开 ' + (absolutePath \|\| remote.path)` | `在远端文件中打开 {path}` | Open in remote files: {path} |
126
+ | `'把 ' + entry.path + ' 添加为 DSH 工作区'` | `把 {path} 添加为 DSH 工作区` | Add {path} as a DSH workspace |
127
+ | `'上传文件到 ' + currentDir` | `上传文件到 {dirname}` | Upload files to {dirname} |
128
+ | `'打包下载 ' + currentDir + '(tar.gz)'` | `打包下载 {dirname}(tar.gz)` | Download {dirname} (tar.gz) |
129
+ | `'在 ' + currentDir + ' 下新建文件夹'` | `在 {dirname} 下新建文件夹` | New folder in {dirname} |
130
+ | `'正在打包 ' + paths.length + ' 项…'` | `正在打包 {n} 项…` | Archiving {n} items… |
131
+ | `'已选 ' + selection.length + ' 项'` | `已选 {n} 项` | {n} selected |
132
+ | `'已传 ' + formatBytes(task.sent) + ' / ' + formatBytes(task.total)` | `已传 {sent} / {total}` | {sent} of {total} uploaded |
133
+ | `job.name + '(已传 ' + percent + '%,请重新选择该文件继续)'` | `{name}(已传 {percent}%,请重新选择该文件继续)` | {name} ({percent}% uploaded; choose the same file to continue) |
134
+ | `name + ' 连续 ' + UPLOAD_RETRY_LIMIT + ' 次上传失败:' + reason` | `{name} 连续 {count} 次上传失败:{reason}` | {name} failed to upload {count} times in a row: {reason} |
135
+ | `'已' + verb + ' ' + ok + ' 项'`(verb 为 `'移动'` / `'复制'`) | `已移动 {n} 项` / `已复制 {n} 项` | Moved {n} items / Copied {n} items |
136
+ | `'重命名 ' + single.path + '(F2)'` | `重命名 {path}(F2)` | Rename {path} (F2) |
137
+ | `'已检测到 ' + config.keys.length + ' 个密钥:' + keys.join('、') + ' · '` | `已检测到 {n} 个密钥:{keys} · ` | Found {n} keys: {keys} · |
138
+
139
+ > 其余模板可直接在 `en-ui.json` 中搜索 `{` 查看;完整 104 条都已入表。
140
+
141
+ ## 6. 待确认 / 需要实现方留意的条目
142
+
143
+ 以下条目在源码里缺少完整上下文或依赖布局,译文按最合理理解给出,落地时建议复查:
144
+
145
+ - `{n} 个` → `{n}`:用作"工作区"标题旁的数量(`工作区 3 个` → `Workspaces 3`)。若英文布局需要单位,可改为 `{n} total`。
146
+ - `已在 {host} 的工作区 · {n}` → `In {host}'s workspaces · {n}`:中文省略了动词,指"该主机上已有 N 个工作区",英文措辞可再调整。
147
+ - `已转发` → `Active forwards`:作为列表小标题(原文直译是 "Forwarded"),按 UI 语境取了更自然的小标题。
148
+ - `确认移除` → `Remove`:原文带"确认"语气,但按钮在行内空间有限,按按钮惯例取 `Remove`。
149
+ - `开` / `关` → `On` / `Off`:只作为 `{state}` 参数使用。
150
+ - `" 等"` → `" and more"`:只作为 `A、B、C` 之后的后缀;英文保留前导空格,由调用方拼在前面。
151
+ - `正在加载 host…` → `Loading hosts…`:源码本身中英混排(`host` 是开发用词),译成自然英文。
152
+ - `未加载到编辑器组件` → `Editor component not loaded`:指 CodeMirror 引擎加载失败,如果更想强调引擎可改为 `Editor engine not loaded`。
153
+ - `远端工作台` → `Remote Deck`:这里指产品/设置分区名,不是字面的 "remote workbench"。
154
+ - `已移动 {n} 项` / `已复制 {n} 项`:源码是 `'已' + verb + ' ' + ok + ' 项'`,`verb` 由调用方传中文;建议把两个调用点直接改成这两条 key,不要保留动态中文动词(否则英文语序会错)。
155
+
156
+ ## 7. 维护方式
157
+
158
+ 1. 改 `client.js` 中文文案时同步改 key;新增"中文 + 变量 + 中文"的拼接时,补一条带 `{占位符}` 的模板,而不是把片段单独成条。
159
+ 2. 生成/校验步骤(可写成脚本):词法提取字符串字面量 → 过滤来源行是注释/正则的内容 → 去掉 `{…}` 后校验剩余片段都在 `client.js` 中 → 校验 127 个拼接片段全覆盖 → JSON 序列化(2 空格、排序、末尾换行)。
160
+ 3. 词条表与代码是**同一次提交**的关系:本表基于 `client.js` 的某一版快照生成;之后的 UI 文案变更需要重新跑一遍校验,否则会出现"新增中文没有英文"的回退显示(功能上安全,只是英文界面会露出中文)。