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,402 @@
1
+ /**
2
+ * Remote copy and move for the file page: clipboard (copy / cut / paste) and
3
+ * drag-and-drop both land here.
4
+ *
5
+ * Rules that shape this module:
6
+ *
7
+ * - **The batch never fails as a whole.** One entry that cannot be transferred
8
+ * is one `ok: false` row; the remaining entries still run. Only a malformed
9
+ * request is refused outright, and it is refused before any filesystem work.
10
+ * - **Nothing is overwritten.** An existing destination is an `EXISTS` row,
11
+ * which the browser half turns into "already there, pick another name".
12
+ * - **Symbolic links are recreated, never followed**: `readlink` then `symlink`
13
+ * at the new location, so a link to a directory copies as a link.
14
+ * - **FIFOs, sockets and devices are never read.** They are `UNSUPPORTED` when
15
+ * requested directly, and skipped when met inside a directory being copied.
16
+ * - **A move tries `rename` first.** SFTP cannot report EXDEV apart from any
17
+ * other failure (OpenSSH maps it to `SSH_FX_FAILURE` with no message), so any
18
+ * rename failure that is not "the source is gone" falls back to copy-then-
19
+ * delete, which reuses the delete walk's no-follow semantics.
20
+ * - **Cancellation is checked before every operation** and between file chunks:
21
+ * the browser stops a transfer by aborting the HTTP request.
22
+ */
23
+ import { posix } from 'node:path'
24
+ import { removeRemoteTree } from './delete.js'
25
+ import { sftpCall } from './util.js'
26
+
27
+ /** How many paths one copy/move request may carry. */
28
+ export const TRANSFER_MAX_PATHS = 200
29
+ /** The path is not a plain absolute remote POSIX path. */
30
+ export const TRANSFER_INVALID_CODE = 'NOT_REMOTE_PATH'
31
+ /** The paste target is not an existing directory. */
32
+ export const TRANSFER_NOT_DIR_CODE = 'NOT_REMOTE_DIR'
33
+ /** The paste target sits inside a directory that is being transferred. */
34
+ export const TRANSFER_INSIDE_SOURCE_CODE = 'DEST_INSIDE_SOURCE'
35
+ /** More paths than {@link TRANSFER_MAX_PATHS}. */
36
+ export const TRANSFER_TOO_MANY_CODE = 'TOO_MANY_PATHS'
37
+ /** The client went away; nothing is written back. */
38
+ export const TRANSFER_CANCELLED_CODE = 'REMOTE_DECK_TRANSFER_CANCELLED'
39
+
40
+ /** FS_NOT_FOUND from `sftpCall`, and the raw SFTP status code for it. */
41
+ const FS_NOT_FOUND = 'FS_NOT_FOUND'
42
+ const SFTP_NO_SUCH_FILE = 2
43
+
44
+ function coded(code, message) {
45
+ const error = new Error(message)
46
+ error.code = code
47
+ return error
48
+ }
49
+
50
+ /** A refusal the route answers with 400. */
51
+ function refuse(code, message) {
52
+ return { ok: false, code, message }
53
+ }
54
+
55
+ /** One failed entry inside an otherwise successful batch. */
56
+ function failed(entry, code, message) {
57
+ return { path: entry.path, name: entry.name, ok: false, code, message }
58
+ }
59
+
60
+ function succeeded(entry) {
61
+ return { path: entry.path, name: entry.name, ok: true }
62
+ }
63
+
64
+ function errorText(error) {
65
+ return error instanceof Error ? error.message : String(error)
66
+ }
67
+
68
+ function isMissing(error) {
69
+ return Boolean(error) && (error.code === FS_NOT_FOUND || error.code === SFTP_NO_SUCH_FILE)
70
+ }
71
+
72
+ function isCancelledError(error) {
73
+ return Boolean(error) && error.code === TRANSFER_CANCELLED_CODE
74
+ }
75
+
76
+ /** A plain absolute remote path: no relative spelling, no `..`, no `//`. */
77
+ export function isPlainRemotePath(value) {
78
+ if (typeof value !== 'string' || value.length === 0) return false
79
+ if (!value.startsWith('/') || value.startsWith('//')) return false
80
+ return !value.split('/').includes('..')
81
+ }
82
+
83
+ /** Normalized, and without the trailing slash `posix.normalize` keeps. */
84
+ export function canonicalRemotePath(value) {
85
+ const normalized = posix.normalize(String(value))
86
+ return normalized.length > 1 ? normalized.replace(/\/+$/, '') : normalized
87
+ }
88
+
89
+ /**
90
+ * Whether `child` is `parent` itself or below it.
91
+ *
92
+ * Compares the canonical spellings, so `/a/b/` cannot slip past as "not inside".
93
+ * Both arguments must already be canonical and absolute.
94
+ */
95
+ export function isInside(parent, child) {
96
+ if (parent === child) return true
97
+ const prefix = parent === '/' ? '/' : `${parent}/`
98
+ return child.startsWith(prefix)
99
+ }
100
+
101
+ /**
102
+ * The kind of one entry, from its SFTP attrs.
103
+ *
104
+ * The POSIX type bits decide first: ssh2's predicates are not reliable for every
105
+ * type (a unix socket and a block device both report their predicate false), and
106
+ * misreading a socket as a regular file here would mean trying to read it. The
107
+ * predicate chain stays as the fallback for a server that sends no mode, and a
108
+ * link always wins, so nothing is ever followed.
109
+ */
110
+ export function entryKind(attrs) {
111
+ const mode = Number(attrs?.mode)
112
+ if (Number.isFinite(mode)) {
113
+ switch (mode & 0o170000) {
114
+ case 0o120000: return 'link'
115
+ case 0o040000: return 'dir'
116
+ case 0o010000: return 'fifo'
117
+ case 0o140000: return 'socket'
118
+ case 0o020000: return 'char'
119
+ case 0o060000: return 'block'
120
+ case 0o100000: return 'file'
121
+ default: break
122
+ }
123
+ }
124
+ const flag = (name) => typeof attrs?.[name] === 'function' && attrs[name]() === true
125
+ if (flag('isSymbolicLink')) return 'link'
126
+ if (flag('isDirectory')) return 'dir'
127
+ if (flag('isFIFO')) return 'fifo'
128
+ if (flag('isSocket')) return 'socket'
129
+ if (flag('isCharacterDevice')) return 'char'
130
+ if (flag('isBlockDevice')) return 'block'
131
+ return 'file'
132
+ }
133
+
134
+ /** Directory entries that must never be re-joined. */
135
+ function usableName(entry) {
136
+ const name = entry !== null && typeof entry === 'object' ? entry.filename : undefined
137
+ if (typeof name !== 'string' || name.length === 0) return null
138
+ if (name === '.' || name === '..' || name.includes('/')) return null
139
+ return name
140
+ }
141
+
142
+ /**
143
+ * Validate the request itself — no filesystem access.
144
+ *
145
+ * @param {unknown} body parsed JSON body
146
+ * @returns {{ ok: true, paths: string[], toDir: string, move: boolean } | { ok: false, code: string, message: string }}
147
+ */
148
+ export function parseTransferRequest(body) {
149
+ const source = body !== null && typeof body === 'object' ? body : {}
150
+ if (!isPlainRemotePath(source.toDir)) {
151
+ return refuse(TRANSFER_INVALID_CODE, 'A remote POSIX target directory is required.')
152
+ }
153
+ const toDir = canonicalRemotePath(source.toDir)
154
+ const paths = Array.isArray(source.paths) ? source.paths : []
155
+ if (paths.length === 0) return refuse(TRANSFER_INVALID_CODE, 'At least one remote path is required.')
156
+ if (paths.length > TRANSFER_MAX_PATHS) {
157
+ return refuse(TRANSFER_TOO_MANY_CODE, `At most ${TRANSFER_MAX_PATHS} paths can be transferred at once.`)
158
+ }
159
+ const clean = []
160
+ const seen = new Set()
161
+ for (const value of paths) {
162
+ if (!isPlainRemotePath(value)) return refuse(TRANSFER_INVALID_CODE, 'Not a remote POSIX path.')
163
+ const path = canonicalRemotePath(value)
164
+ if (posix.basename(path) === '') return refuse(TRANSFER_INVALID_CODE, 'Cannot transfer that path.')
165
+ if (path === toDir) return refuse(TRANSFER_INVALID_CODE, 'A path cannot be transferred into itself.')
166
+ if (seen.has(path)) continue
167
+ seen.add(path)
168
+ clean.push(path)
169
+ }
170
+ return { ok: true, paths: clean, toDir, move: source.move === true }
171
+ }
172
+
173
+ /**
174
+ * Read the request against the host: the target must be a directory, and no
175
+ * directory may be copied or moved into itself.
176
+ *
177
+ * @returns {Promise<{ ok: true, entries: object[] } | { ok: false, code: string, message: string }>}
178
+ */
179
+ async function preflight({ sftp, paths, toDir, invoke, guard }) {
180
+ guard()
181
+ let targetAttrs = null
182
+ try {
183
+ targetAttrs = await invoke(sftp, 'stat', toDir)
184
+ } catch (error) {
185
+ if (isMissing(error)) return refuse(TRANSFER_NOT_DIR_CODE, 'The target directory does not exist.')
186
+ throw error
187
+ }
188
+ if (entryKind(targetAttrs) !== 'dir') return refuse(TRANSFER_NOT_DIR_CODE, 'The target is not a directory.')
189
+
190
+ const entries = []
191
+ for (const path of paths) {
192
+ guard()
193
+ let attrs = null
194
+ try {
195
+ attrs = await invoke(sftp, 'lstat', path)
196
+ } catch (error) {
197
+ if (!isMissing(error)) throw error
198
+ }
199
+ entries.push({ path, name: posix.basename(path), attrs })
200
+ }
201
+ for (const entry of entries) {
202
+ // A link is copied as a link, so only a real directory can swallow the
203
+ // target. Copy and move are both checked: either one would recurse forever.
204
+ if (entry.attrs !== null && entryKind(entry.attrs) === 'dir' && isInside(entry.path, toDir)) {
205
+ return refuse(TRANSFER_INSIDE_SOURCE_CODE, 'The target directory is inside a folder being transferred.')
206
+ }
207
+ }
208
+ return { ok: true, entries }
209
+ }
210
+
211
+ /** Whether anything already sits at the destination, links included. */
212
+ async function destinationExists(invoke, sftp, path) {
213
+ try {
214
+ await invoke(sftp, 'lstat', path)
215
+ return true
216
+ } catch (error) {
217
+ if (isMissing(error)) return false
218
+ throw error
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Stream one regular file.
224
+ *
225
+ * `pipe` carries the backpressure; both ends are destroyed on any failure, and a
226
+ * half-written destination is unlinked so a failed copy never leaves something
227
+ * that looks complete.
228
+ */
229
+ function copyFile({ sftp, source, destination, guard, isCancelled }) {
230
+ return new Promise((resolve, reject) => {
231
+ let settled = false
232
+ let read = null
233
+ let write = null
234
+ const finish = (error) => {
235
+ if (settled) return
236
+ settled = true
237
+ try {
238
+ read?.destroy()
239
+ } catch {
240
+ /* already gone */
241
+ }
242
+ try {
243
+ write?.destroy()
244
+ } catch {
245
+ /* already gone */
246
+ }
247
+ if (error === null || error === undefined) {
248
+ resolve()
249
+ return
250
+ }
251
+ sftp.unlink(destination, () => reject(error))
252
+ }
253
+ try {
254
+ read = sftp.createReadStream(source)
255
+ write = sftp.createWriteStream(destination)
256
+ } catch (error) {
257
+ finish(error)
258
+ return
259
+ }
260
+ read.on('data', () => {
261
+ if (!settled && isCancelled()) finish(coded(TRANSFER_CANCELLED_CODE, 'The transfer was cancelled.'))
262
+ })
263
+ read.on('error', (error) => finish(error))
264
+ write.on('error', (error) => finish(error))
265
+ write.on('close', () => finish(null))
266
+ read.pipe(write)
267
+ })
268
+ }
269
+
270
+ /**
271
+ * Copy one entry, recursing through real directories only.
272
+ *
273
+ * @param {object} input
274
+ * @param {'file'|'dir'|'link'} input.kind already classified by {@link entryKind}
275
+ */
276
+ async function copyEntry({ sftp, source, destination, kind, invoke, guard, isCancelled }) {
277
+ guard()
278
+ if (kind === 'link') {
279
+ const target = await invoke(sftp, 'readlink', source)
280
+ guard()
281
+ await invoke(sftp, 'symlink', target, destination)
282
+ return
283
+ }
284
+ if (kind !== 'dir') {
285
+ await copyFile({ sftp, source, destination, guard, isCancelled })
286
+ return
287
+ }
288
+ await invoke(sftp, 'mkdir', destination)
289
+ const entries = await invoke(sftp, 'readdir', source)
290
+ for (const entry of Array.isArray(entries) ? entries : []) {
291
+ const name = usableName(entry)
292
+ if (name === null) continue
293
+ const attrs = entry !== null && typeof entry === 'object' ? entry.attrs : undefined
294
+ // `readdir` reports the mode of every entry; a server that sends none gets
295
+ // one `lstat`, which keeps a socket from being streamed as a file.
296
+ const childKind = attrs === undefined || attrs === null
297
+ ? entryKind(await invoke(sftp, 'lstat', posix.join(source, name)))
298
+ : entryKind(attrs)
299
+ if (childKind !== 'file' && childKind !== 'dir' && childKind !== 'link') continue
300
+ await copyEntry({
301
+ sftp,
302
+ source: posix.join(source, name),
303
+ destination: posix.join(destination, name),
304
+ kind: childKind,
305
+ invoke,
306
+ guard,
307
+ isCancelled,
308
+ })
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Copy or move every requested path into `toDir`.
314
+ *
315
+ * @param {object} input
316
+ * @param {object} input.sftp connected SFTP session
317
+ * @param {unknown} input.body the request body
318
+ * @param {() => boolean} [input.isCancelled] asked before every operation
319
+ * @param {Function} [input.call] `sftpCall`, injectable for tests
320
+ * @returns {Promise<{ ok: true, results: object[] } | { ok: false, code: string, message: string } | { cancelled: true, results: object[] }>}
321
+ */
322
+ export async function transferRemotePaths({ sftp, body, isCancelled, call } = {}) {
323
+ const invoke = typeof call === 'function' ? call : sftpCall
324
+ const cancelled = typeof isCancelled === 'function' ? isCancelled : () => false
325
+ const guard = () => {
326
+ if (cancelled()) throw coded(TRANSFER_CANCELLED_CODE, 'The transfer was cancelled.')
327
+ }
328
+
329
+ const parsed = parseTransferRequest(body)
330
+ if (parsed.ok !== true) return parsed
331
+
332
+ let planned
333
+ try {
334
+ planned = await preflight({ sftp, paths: parsed.paths, toDir: parsed.toDir, invoke, guard })
335
+ } catch (error) {
336
+ if (isCancelledError(error)) return { cancelled: true, results: [] }
337
+ throw error
338
+ }
339
+ if (planned.ok !== true) return planned
340
+
341
+ const results = []
342
+ for (const entry of planned.entries) {
343
+ try {
344
+ guard()
345
+ results.push(await transferEntry({ sftp, entry, toDir: parsed.toDir, move: parsed.move, invoke, guard, isCancelled: cancelled }))
346
+ } catch (error) {
347
+ if (isCancelledError(error)) return { cancelled: true, results }
348
+ // Anything unexpected is this entry's failure, never the batch's.
349
+ results.push(failed(entry, 'FAILED', errorText(error)))
350
+ }
351
+ }
352
+ return { ok: true, results }
353
+ }
354
+
355
+ /** One row of the batch. */
356
+ async function transferEntry({ sftp, entry, toDir, move, invoke, guard, isCancelled }) {
357
+ if (entry.attrs === null) return failed(entry, 'MISSING', 'No such remote path.')
358
+ const kind = entryKind(entry.attrs)
359
+ if (kind !== 'file' && kind !== 'dir' && kind !== 'link') {
360
+ return failed(entry, 'UNSUPPORTED', 'That kind of entry cannot be copied.')
361
+ }
362
+ const destination = posix.join(toDir, entry.name)
363
+ // Checked before a rename as well: OpenSSH's rename overwrites, and the rule
364
+ // is that an existing entry is reported, never replaced.
365
+ guard()
366
+ if (await destinationExists(invoke, sftp, destination)) {
367
+ return failed(entry, 'EXISTS', 'An entry with that name is already there.')
368
+ }
369
+
370
+ if (move) {
371
+ try {
372
+ guard()
373
+ await invoke(sftp, 'rename', entry.path, destination)
374
+ return succeeded(entry)
375
+ } catch (error) {
376
+ if (isMissing(error)) return failed(entry, 'MISSING', 'No such remote path.')
377
+ // Cross-filesystem renames land here too: SFTP reports them as a plain
378
+ // failure, so the copy-then-delete path is the only way to tell.
379
+ }
380
+ }
381
+
382
+ try {
383
+ await copyEntry({ sftp, source: entry.path, destination, kind, invoke, guard, isCancelled })
384
+ } catch (error) {
385
+ if (isCancelledError(error)) throw error
386
+ return failed(entry, 'FAILED', errorText(error))
387
+ }
388
+ if (!move) return succeeded(entry)
389
+
390
+ try {
391
+ await removeRemoteTree({ sftp, path: entry.path, isCancelled, call: invoke })
392
+ } catch (error) {
393
+ if (isCancelledError(error)) throw error
394
+ if (Boolean(error) && error.code === 'REMOTE_DECK_DELETE_CANCELLED') {
395
+ throw coded(TRANSFER_CANCELLED_CODE, 'The transfer was cancelled.')
396
+ }
397
+ // The copy is safely in place, but leaving the source behind would look
398
+ // like a successful move: report the half-done state instead.
399
+ return failed(entry, 'FAILED', `copied, but the source could not be removed: ${errorText(error)}`)
400
+ }
401
+ return succeeded(entry)
402
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Local port forwarding over SSH.
3
+ *
4
+ * A forward listens on 127.0.0.1 and pipes each accepted socket through an
5
+ * ssh2 direct-tcpip channel to a port on the remote host. Saved forwards are
6
+ * restored when their connection comes back, and each one remembers whether the
7
+ * console or the agent opened it.
8
+ */
9
+ import net from 'node:net'
10
+ import { randomUUID } from 'node:crypto'
11
+ import { join } from 'node:path'
12
+ import { readJsonFile, writeJsonFile } from './util.js'
13
+
14
+ export function parseListeningPorts(text) {
15
+ const ports = new Set()
16
+ for (const line of String(text).split(/\r?\n/)) {
17
+ const trimmed = line.trim()
18
+ if (trimmed.length === 0 || /^State/i.test(trimmed)) continue
19
+ if (!/LISTEN/i.test(trimmed) && !/^tcp/i.test(trimmed)) continue
20
+ for (const token of trimmed.split(/\s+/)) {
21
+ if (!token.includes(':') || token.endsWith(':*')) continue
22
+ const match = /:(\d{1,5})$/.exec(token)
23
+ if (match === null) continue
24
+ const port = Number(match[1])
25
+ if (Number.isInteger(port) && port > 0 && port < 65536) {
26
+ ports.add(port)
27
+ break
28
+ }
29
+ }
30
+ }
31
+ return [...ports].sort((a, b) => a - b)
32
+ }
33
+
34
+ export class ForwardManager {
35
+ constructor({ hostFor, secrets, dataDir, onLog }) {
36
+ this.hostFor = hostFor
37
+ this.secrets = secrets
38
+ this.file = join(dataDir, 'forwards.json')
39
+ this.onLog = onLog ?? (() => {})
40
+ this.forwards = new Map()
41
+ const saved = readJsonFile(this.file, null)
42
+ this.saved = saved !== null && Array.isArray(saved.forwards) ? saved.forwards : []
43
+ }
44
+
45
+ #view(record) {
46
+ return {
47
+ id: record.id,
48
+ connectionId: record.connectionId,
49
+ remotePort: record.remotePort,
50
+ localPort: record.localPort,
51
+ origin: record.origin === 'agent' ? 'agent' : 'user',
52
+ createdAt: record.createdAt,
53
+ url: 'http://127.0.0.1:' + record.localPort,
54
+ }
55
+ }
56
+
57
+ list() {
58
+ return [...this.forwards.values()].map((record) => this.#view(record))
59
+ }
60
+
61
+ #persist() {
62
+ const rows = this.list().map((row) => ({
63
+ connectionId: row.connectionId,
64
+ remotePort: row.remotePort,
65
+ localPort: row.localPort,
66
+ origin: row.origin,
67
+ }))
68
+ writeJsonFile(this.file, { version: 1, forwards: rows })
69
+ this.saved = rows
70
+ }
71
+
72
+ async start(connectionId, remotePort, localPort, origin) {
73
+ const host = this.hostFor(connectionId)
74
+ if (host === undefined) throw new Error('connection not found')
75
+ const port = Number(remotePort)
76
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) throw new Error('invalid remote port')
77
+ await host.connect(this.secrets)
78
+
79
+ const sockets = new Set()
80
+ const server = net.createServer((socket) => {
81
+ sockets.add(socket)
82
+ socket.on('close', () => sockets.delete(socket))
83
+ // Defence in depth: a forwarded port serves whoever knocks, including while
84
+ // the SSH session is still coming up. Nothing that happens here may reach
85
+ // the process, or the app dies with the socket.
86
+ let pending
87
+ try {
88
+ pending = host.forwardOut('127.0.0.1', socket.remotePort || 0, '127.0.0.1', port)
89
+ } catch {
90
+ socket.destroy()
91
+ return
92
+ }
93
+ pending
94
+ .then((stream) => {
95
+ socket.pipe(stream).pipe(socket)
96
+ socket.on('error', () => stream.destroy())
97
+ stream.on('error', () => socket.destroy())
98
+ stream.on('close', () => socket.destroy())
99
+ })
100
+ .catch(() => {
101
+ socket.destroy()
102
+ })
103
+ })
104
+ const bindPort = Number(localPort) > 0 ? Number(localPort) : 0
105
+ await new Promise((resolve, reject) => {
106
+ const fail = (error) => reject(error)
107
+ server.once('error', fail)
108
+ server.listen(bindPort, '127.0.0.1', () => {
109
+ server.removeListener('error', fail)
110
+ resolve()
111
+ })
112
+ })
113
+ const actual = server.address().port
114
+ const record = {
115
+ id: randomUUID(),
116
+ connectionId,
117
+ remotePort: port,
118
+ localPort: actual,
119
+ origin: origin === 'agent' ? 'agent' : 'user',
120
+ createdAt: Date.now(),
121
+ server,
122
+ sockets,
123
+ }
124
+ server.on('error', (error) => this.onLog('forward error', connectionId, String(error && error.message ? error.message : error)))
125
+ this.forwards.set(record.id, record)
126
+ this.#persist()
127
+ this.onLog('forward start', connectionId, ':' + port, '->', actual)
128
+ return this.#view(record)
129
+ }
130
+
131
+ stop(id) {
132
+ const record = this.forwards.get(id)
133
+ if (record === undefined) return false
134
+ try {
135
+ record.server.close()
136
+ } catch {
137
+ /* ignore */
138
+ }
139
+ for (const socket of record.sockets ?? []) {
140
+ try {
141
+ socket.destroy()
142
+ } catch {
143
+ /* ignore */
144
+ }
145
+ }
146
+ this.forwards.delete(id)
147
+ this.#persist()
148
+ return true
149
+ }
150
+
151
+ stopForConnection(connectionId) {
152
+ for (const record of [...this.forwards.values()]) {
153
+ if (record.connectionId === connectionId) this.stop(record.id)
154
+ }
155
+ }
156
+
157
+ async restoreFor(connectionId) {
158
+ for (const row of this.saved) {
159
+ if (row.connectionId !== connectionId) continue
160
+ const already = [...this.forwards.values()].some((record) => record.connectionId === connectionId && record.remotePort === row.remotePort)
161
+ if (already) continue
162
+ try {
163
+ await this.start(connectionId, row.remotePort, row.localPort, row.origin)
164
+ } catch (error) {
165
+ this.onLog('forward restore failed', connectionId, row.remotePort, String(error && error.message ? error.message : error))
166
+ }
167
+ }
168
+ }
169
+
170
+ async detect(connectionId) {
171
+ const host = this.hostFor(connectionId)
172
+ if (host === undefined) throw new Error('connection not found')
173
+ await host.connect(this.secrets)
174
+ const result = await host.runCommand('ss -ltn 2>/dev/null || netstat -ltn 2>/dev/null', null, { maxBytes: 256 * 1024 })
175
+ const ports = parseListeningPorts(result.stdout)
176
+ const forwarded = new Map()
177
+ for (const record of this.forwards.values()) {
178
+ if (record.connectionId === connectionId) forwarded.set(record.remotePort, record.localPort)
179
+ }
180
+ return ports.map((port) => ({ port, localPort: forwarded.get(port) ?? null }))
181
+ }
182
+
183
+ closeAll() {
184
+ for (const id of [...this.forwards.keys()]) this.stop(id)
185
+ }
186
+ }