dsh-remote-vs 0.11.1 → 0.12.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.
package/src/routes.ts CHANGED
@@ -12,11 +12,12 @@ import type { Context } from '@deepseek-ai/cordis'
12
12
  import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
13
13
  import { readJsonBody, writeJson } from './http.ts'
14
14
  import { isLoopbackRequest } from './loopback.ts'
15
- import { REMOTE_API, type ExecStreamEvent, type ImportReport, type RemoteTimeouts } from './protocol.ts'
15
+ import { REMOTE_API, MAX_SELECTION_DOWNLOAD, selectionDownloadName, type ExecStreamEvent, type ImportReport, type RemoteTimeouts } from './protocol.ts'
16
16
  import type { HostPayload, RemoteStore } from './store.ts'
17
17
  import type { RemotePool } from './pool.ts'
18
18
  import type { RemoteWorlds } from './p2/worlds.ts'
19
- import { RemoteFiles } from './sftp.ts'
19
+ import { RemoteFiles, attachmentHeader } from './sftp.ts'
20
+ import { directoryArchiveCommand, directoryArchiveName, selectionArchiveCommand } from './archive.ts'
20
21
  import { bootstrap } from './keygen.ts'
21
22
  import { helperAvailability, probe, pushPipeline } from './deploy.ts'
22
23
  import { migrateDshSsh, parseSshConfig, readDefaultSshConfig, type ParsedImport } from './importers.ts'
@@ -144,6 +145,90 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
144
145
  const files = new RemoteFiles(pool)
145
146
  const terminalSessions = new TerminalSessionRegistry(pool)
146
147
 
148
+ /**
149
+ * Stream one remote `tar -czf -` command into a `.tar.gz` download response.
150
+ *
151
+ * Shared by the directory and multi-selection routes (they differ only in the
152
+ * command and the attachment name). The archive is produced remotely; the
153
+ * response has no length, backpressure pauses the channel, and a non-zero tar
154
+ * exit destroys the response with the stderr tail.
155
+ */
156
+ const streamArchive = async (alias: string, command: string, res: ServerResponse, downloadName: string): Promise<void> => {
157
+ let channel: Awaited<ReturnType<typeof pool.execChannel>>
158
+ try {
159
+ channel = await pool.execChannel(alias, command)
160
+ } catch (error) {
161
+ writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
162
+ return
163
+ }
164
+ res.writeHead(200, {
165
+ 'content-type': 'application/gzip',
166
+ 'content-disposition': attachmentHeader(downloadName),
167
+ 'cache-control': 'no-store',
168
+ 'x-content-type-options': 'nosniff',
169
+ })
170
+ let closed = false
171
+ /** `undefined` until the remote process reports one. */
172
+ let exitCode: number | null | undefined
173
+ let stderr = ''
174
+ /** Finish once: end on success, destroy on failure, close the remote channel either way. */
175
+ const stop = (error?: Error): void => {
176
+ if (closed) return
177
+ closed = true
178
+ try {
179
+ channel.close()
180
+ } catch {
181
+ // Channel already gone.
182
+ }
183
+ if (error === undefined) {
184
+ try {
185
+ res.end()
186
+ } catch {
187
+ // Already gone.
188
+ }
189
+ return
190
+ }
191
+ res.destroy(error)
192
+ }
193
+ channel.stdout.on('data', (chunk: Buffer) => {
194
+ if (closed) return
195
+ try {
196
+ // Backpressure reaches the remote tar via the channel window.
197
+ if (!res.write(chunk)) channel.stdout.pause()
198
+ } catch (error) {
199
+ stop(error instanceof Error ? error : new Error(String(error)))
200
+ }
201
+ })
202
+ res.on('drain', () => {
203
+ if (!closed) {
204
+ try {
205
+ channel.stdout.resume()
206
+ } catch {
207
+ // Already closed.
208
+ }
209
+ }
210
+ })
211
+ channel.stderr.on('data', (chunk: Buffer) => {
212
+ // Keep a bounded tail: it explains a non-zero tar exit to the client.
213
+ if (stderr.length < 16_384) stderr += chunk.toString('utf8')
214
+ })
215
+ channel.on('error', (error: Error) => stop(error))
216
+ ;(channel as unknown as { on(event: 'exit', listener: (code: number | null, signal?: string) => void): void })
217
+ .on('exit', (code) => {
218
+ exitCode = code
219
+ })
220
+ channel.on('close', () => {
221
+ if (closed) return
222
+ if (exitCode !== 0) {
223
+ const detail = stderr.trim() === '' ? 'no stderr' : stderr.trim().slice(0, 400)
224
+ stop(new Error(`tar failed (${exitCode === null ? 'signal' : exitCode}): ${detail}`))
225
+ return
226
+ }
227
+ stop()
228
+ })
229
+ res.on('close', () => stop())
230
+ }
231
+
147
232
  /** Apply parsed import payloads; per-entry errors become skips. */
148
233
  const applyImport = (parsed: ParsedImport): ImportReport => {
149
234
  const imported: string[] = []
@@ -553,6 +638,140 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
553
638
  }
554
639
  },
555
640
  },
641
+ // ----------------------------------------------------------- download
642
+ // Streaming binary download (the upload route's mirror): the response body
643
+ // IS the file, so a multi-GB file never passes through base64 or Host
644
+ // memory. The stat preflight lives in the client (`files` op=stat) so an
645
+ // error keeps a readable JSON body instead of a saved error page.
646
+ {
647
+ kind: 'exact',
648
+ path: REMOTE_API.download,
649
+ handler: async (req, res) => {
650
+ if (!isLoopbackRequest(req)) {
651
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
652
+ return
653
+ }
654
+ if (req.method !== 'GET') {
655
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` })
656
+ return
657
+ }
658
+ const url = new URL(req.url ?? '/', 'http://localhost')
659
+ const alias = url.searchParams.get('alias') ?? ''
660
+ const path = url.searchParams.get('path') ?? ''
661
+ if (alias === '' || path === '') {
662
+ writeJson(res, 400, { error: 'alias and path query parameters are required' })
663
+ return
664
+ }
665
+ if (!path.startsWith('/')) {
666
+ // The client passes an absolute remote path; a relative one would
667
+ // silently resolve against the SFTP home and download some other file.
668
+ writeJson(res, 400, { error: `path must be absolute: ${path}` })
669
+ return
670
+ }
671
+ try {
672
+ await files.download(alias, path, res)
673
+ } catch (error) {
674
+ const message = error instanceof Error ? error.message : String(error)
675
+ // The stat/stream start can still fail before any byte goes out, and
676
+ // then the client expects its JSON error; once the body started (or
677
+ // the connection is already gone) the only honest answer is closing
678
+ // the connection.
679
+ if (!res.headersSent && !res.destroyed) writeJson(res, 502, { error: message })
680
+ else res.destroy(error instanceof Error ? error : undefined)
681
+ }
682
+ },
683
+ },
684
+ // ---------------------------------------------- download (directory)
685
+ // A directory has no byte stream of its own: the archive is produced ON the
686
+ // remote host (`tar -czf -`) and piped straight into the response, so the
687
+ // Host never builds it in memory or on disk. The size is unknown (chunked),
688
+ // which the client renders as an indeterminate progress bar; the stat
689
+ // preflight keeps a missing path a JSON error instead of a truncated .tar.gz.
690
+ {
691
+ kind: 'exact',
692
+ path: REMOTE_API.downloadDir,
693
+ handler: async (req, res) => {
694
+ if (!isLoopbackRequest(req)) {
695
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
696
+ return
697
+ }
698
+ if (req.method !== 'GET') {
699
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` })
700
+ return
701
+ }
702
+ const url = new URL(req.url ?? '/', 'http://localhost')
703
+ const alias = url.searchParams.get('alias') ?? ''
704
+ const path = url.searchParams.get('path') ?? ''
705
+ if (alias === '' || path === '') {
706
+ writeJson(res, 400, { error: 'alias and path query parameters are required' })
707
+ return
708
+ }
709
+ if (!path.startsWith('/')) {
710
+ writeJson(res, 400, { error: `path must be absolute: ${path}` })
711
+ return
712
+ }
713
+ let command: string
714
+ try {
715
+ const entry = await files.stat(alias, path)
716
+ if (!entry.isDir) {
717
+ writeJson(res, 400, { error: `not a directory: ${path}` })
718
+ return
719
+ }
720
+ command = directoryArchiveCommand(path)
721
+ } catch (error) {
722
+ writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
723
+ return
724
+ }
725
+ await streamArchive(alias, command, res, directoryArchiveName(path))
726
+ },
727
+ },
728
+ // ---------------------------------------- download (multi selection)
729
+ // A selection is archived on the remote host as ONE tar stream (repeated
730
+ // `path` params): every entry is validated before the response starts, so
731
+ // the client shows one save dialog instead of N downloads and a missing
732
+ // entry is a JSON error rather than a truncated archive.
733
+ {
734
+ kind: 'exact',
735
+ path: REMOTE_API.downloadMany,
736
+ handler: async (req, res) => {
737
+ if (!isLoopbackRequest(req)) {
738
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
739
+ return
740
+ }
741
+ if (req.method !== 'GET') {
742
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` })
743
+ return
744
+ }
745
+ const url = new URL(req.url ?? '/', 'http://localhost')
746
+ const alias = url.searchParams.get('alias') ?? ''
747
+ const paths = url.searchParams.getAll('path')
748
+ if (alias === '' || paths.length === 0) {
749
+ writeJson(res, 400, { error: 'alias and at least one path query parameter are required' })
750
+ return
751
+ }
752
+ if (paths.length > MAX_SELECTION_DOWNLOAD) {
753
+ writeJson(res, 400, { error: `too many entries: ${paths.length} (max ${MAX_SELECTION_DOWNLOAD})` })
754
+ return
755
+ }
756
+ for (const path of paths) {
757
+ if (!path.startsWith('/')) {
758
+ writeJson(res, 400, { error: `path must be absolute: ${path}` })
759
+ return
760
+ }
761
+ }
762
+ let command: string
763
+ try {
764
+ // Validate every entry BEFORE the archive starts: a vanished/renamed
765
+ // entry would otherwise surface as a truncated download.
766
+ for (const path of paths) await files.stat(alias, path)
767
+ command = selectionArchiveCommand(paths)
768
+ } catch (error) {
769
+ writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
770
+ return
771
+ }
772
+ await streamArchive(alias, command, res, selectionDownloadName(paths.length))
773
+ },
774
+ },
556
775
  // -------------------------------------------------------- workspaces
557
776
  {
558
777
  kind: 'exact',
package/src/sftp.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  * remote host; every entry point validates before touching the wire.
4
4
  */
5
5
  import { randomBytes } from 'node:crypto'
6
+ import type { ServerResponse } from 'node:http'
6
7
  import { posix } from 'node:path'
7
8
  import type { SFTPWrapper, Stats } from 'ssh2'
8
9
  import type { RemotePool } from './pool.ts'
@@ -24,6 +25,19 @@ export const LIST_ENTRY_CAP = 20000
24
25
  /** Largest single upload accepted (matches the client-side planner cap). */
25
26
  export const UPLOAD_MAX_BYTES = 2 * 1024 * 1024 * 1024
26
27
 
28
+ /**
29
+ * How long one download stream may make no progress before it is failed.
30
+ *
31
+ * A download has no wall-clock budget for the same reason an upload does not: a
32
+ * big file on a slow link is healthy for minutes. What must never happen is a
33
+ * silently dead stream pinning the SFTP session (and its channel slot) forever,
34
+ * so progress is the bound — any chunk resets this clock.
35
+ */
36
+ export const DOWNLOAD_IDLE_MS = 60_000
37
+
38
+ /** Chunk size for one download stream (one SFTP read at a time). */
39
+ const DOWNLOAD_CHUNK_BYTES = 256 * 1024
40
+
27
41
  /**
28
42
  * Cap for both per-path memory sets below (levels confirmed to exist, listings
29
43
  * already reported as truncated). Each only ever saves round trips or a repeat
@@ -49,6 +63,22 @@ export function remotePath(path: string): string {
49
63
  return normalized
50
64
  }
51
65
 
66
+ /**
67
+ * `Content-Disposition` for one attachment (RFC 6266 + RFC 5987).
68
+ *
69
+ * Receivers prefer `filename*` when both forms are present (RFC 6266 §4.3),
70
+ * which is why a non-ASCII remote name survives the round trip; the quoted
71
+ * ASCII copy is the fallback for clients that do not understand the extended
72
+ * form. Quotes and backslashes are stripped from that fallback so they cannot
73
+ * break the header.
74
+ */
75
+ export function attachmentHeader(fileName: string): string {
76
+ // eslint-disable-next-line no-control-regex -- stripping control bytes is the point
77
+ const fallback = fileName.replace(/[^\u0020-\u007e]/g, '_').replace(/["\\]/g, '_')
78
+ const encoded = encodeURIComponent(fileName).replace(/['()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)
79
+ return `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`
80
+ }
81
+
52
82
  export class RemoteFiles {
53
83
  /**
54
84
  * `alias + level` pairs confirmed to exist on the remote (insertion order,
@@ -210,6 +240,132 @@ export class RemoteFiles {
210
240
  })
211
241
  }
212
242
 
243
+ /**
244
+ * Stream one remote file into an HTTP response (download to the local machine).
245
+ *
246
+ * Streaming, not `read()`: `read()` caps at 8 MiB because it answers a JSON
247
+ * editor read, while a download is whatever the user pointed at — a log, a
248
+ * binary, an artifact. The file is opened through one SFTP handle before the
249
+ * headers are written: symlinks are followed (lstat's size is the link
250
+ * target's string length, not the file's), directories are refused, and the
251
+ * content length comes from the same handle the body is read through. The
252
+ * session has no wall-clock deadline (see `DOWNLOAD_IDLE_MS`); the caller's
253
+ * response close and stream errors are both handled, so a cancelled download
254
+ * never leaves the SFTP session or its channel slot pinned.
255
+ *
256
+ * @param alias - host alias.
257
+ * @param file - absolute remote source path.
258
+ * @param res - HTTP response to write the file into.
259
+ */
260
+ async download(alias: string, file: string, res: ServerResponse): Promise<void> {
261
+ const path = remotePath(file)
262
+ await this.pool.withSftp(alias, async (sftp) => {
263
+ const link = await lstatAsync(sftp, path).catch(async (error: unknown) => {
264
+ throw (await explainSftpFailure(sftp, path, 'file', error)) ?? error
265
+ })
266
+ // Same pre-check as read(): asking SFTP to open a directory yields a bare
267
+ // "Failure", while the stat that was needed anyway already says what the
268
+ // path is.
269
+ if (isDir(link.mode)) throw new Error(`not a file: ${path} is a directory`)
270
+ // A symlink must be OPENED, not trusted: lstat reports the LINK's size
271
+ // (the target string), while the body comes from the file the link names.
272
+ // Framing one against the other breaks the response for every symlink,
273
+ // and a link to a directory only fails once opened. One handle supplies
274
+ // the real type and length, and the stream below is bounded by that
275
+ // length so a file that grows mid-transfer cannot overrun the framing.
276
+ const handle = await openAsync(sftp, path).catch(async (error: unknown) => {
277
+ throw (await explainFollowFailure(sftp, path, error)) ?? error
278
+ })
279
+ let streamed = false
280
+ try {
281
+ const attrs = await fstatAsync(sftp, handle)
282
+ if (isDir(attrs.mode)) throw new Error(`not a file: ${path} is a directory`)
283
+ // The client can disappear while the stat is in flight; there is nobody
284
+ // left to stream to, and writing headers to a closed response would turn
285
+ // "user cancelled" into a spurious Host error.
286
+ if (res.destroyed) return
287
+ res.writeHead(200, {
288
+ 'content-type': 'application/octet-stream',
289
+ 'content-length': String(attrs.size),
290
+ 'content-disposition': attachmentHeader(posix.basename(path)),
291
+ 'cache-control': 'no-store',
292
+ 'x-content-type-options': 'nosniff',
293
+ })
294
+ if (attrs.size <= 0) {
295
+ res.end()
296
+ return
297
+ }
298
+ // Ownership of the handle transfers to the stream: ssh2 closes it on
299
+ // end, error and destroy (see ReadStream._destroy), so the session
300
+ // below can end without leaking a file handle.
301
+ const stream = sftp.createReadStream(path, {
302
+ handle,
303
+ start: 0,
304
+ end: attrs.size - 1,
305
+ highWaterMark: DOWNLOAD_CHUNK_BYTES,
306
+ })
307
+ streamed = true
308
+ await new Promise<void>((resolve, reject) => {
309
+ let settled = false
310
+ let idle: ReturnType<typeof setTimeout> | undefined
311
+ const finish = (error?: Error): void => {
312
+ if (settled) return
313
+ settled = true
314
+ if (idle !== undefined) clearTimeout(idle)
315
+ if (error === undefined) {
316
+ resolve()
317
+ return
318
+ }
319
+ res.destroy(error)
320
+ reject(error)
321
+ }
322
+ const arm = (): void => {
323
+ if (idle !== undefined) clearTimeout(idle)
324
+ idle = setTimeout(() => {
325
+ // `data` pauses while the pipe applies backpressure, so a slow
326
+ // browser or local disk is not a dead transfer: re-arm while the
327
+ // consumer still has buffered bytes to drain.
328
+ if (stream.isPaused() || res.writableLength > 0) {
329
+ arm()
330
+ return
331
+ }
332
+ try {
333
+ stream.destroy()
334
+ } catch {
335
+ // Ignore close errors; finish() still rejects.
336
+ }
337
+ finish(new Error(`download stalled: no bytes for ${DOWNLOAD_IDLE_MS / 1000}s`))
338
+ }, DOWNLOAD_IDLE_MS)
339
+ }
340
+ stream.on('data', arm)
341
+ res.on('drain', arm)
342
+ stream.on('error', (error: unknown) => {
343
+ finish(error instanceof Error ? error : new Error(String(error)))
344
+ })
345
+ // A closed response is the user/browser going away, not a Host
346
+ // failure: stop reading and let the session close instead of
347
+ // reporting an error.
348
+ res.on('close', () => {
349
+ if (res.writableEnded) return
350
+ try {
351
+ stream.destroy()
352
+ } catch {
353
+ // Ignore close errors.
354
+ }
355
+ finish()
356
+ })
357
+ stream.on('end', () => finish())
358
+ arm()
359
+ stream.pipe(res)
360
+ })
361
+ } finally {
362
+ // Only a failure BEFORE the stream exists still owns the handle; a
363
+ // created stream closes it itself (including on abort/destroy).
364
+ if (!streamed) await closeAsync(sftp, handle)
365
+ }
366
+ }, { timeoutMs: 0 })
367
+ }
368
+
213
369
  async mkdir(alias: string, dir: string): Promise<void> {
214
370
  const path = remotePath(dir)
215
371
  await this.pool.withSftp(alias, async (sftp) => {
@@ -472,6 +628,63 @@ function lstatAsync(sftp: SFTPWrapper, path: string): Promise<Stats> {
472
628
  })
473
629
  }
474
630
 
631
+ function statAsync(sftp: SFTPWrapper, path: string): Promise<Stats> {
632
+ return new Promise((resolve, reject) => {
633
+ sftp.stat(path, (error, attrs) => {
634
+ if (error !== undefined && error !== null) reject(error)
635
+ else resolve(attrs)
636
+ })
637
+ })
638
+ }
639
+
640
+ function openAsync(sftp: SFTPWrapper, path: string): Promise<Buffer> {
641
+ return new Promise((resolve, reject) => {
642
+ sftp.open(path, 'r', (error, handle) => {
643
+ if (error !== undefined && error !== null) reject(error)
644
+ else resolve(handle)
645
+ })
646
+ })
647
+ }
648
+
649
+ function fstatAsync(sftp: SFTPWrapper, handle: Buffer): Promise<Stats> {
650
+ return new Promise((resolve, reject) => {
651
+ sftp.fstat(handle, (error, attrs) => {
652
+ if (error !== undefined && error !== null) reject(error)
653
+ else resolve(attrs)
654
+ })
655
+ })
656
+ }
657
+
658
+ function closeAsync(sftp: SFTPWrapper, handle: Buffer): Promise<void> {
659
+ return new Promise((resolve) => {
660
+ try {
661
+ sftp.close(handle, () => resolve())
662
+ } catch {
663
+ resolve()
664
+ }
665
+ })
666
+ }
667
+
668
+ /**
669
+ * Explain an `open` failure after lstat already saw a symlink: lstat reports
670
+ * the LINK's type, so "the thing at the end of the link is a directory" only
671
+ * shows up after the follow. `stat` follows the link and answers the question
672
+ * a raw SFTP status never does.
673
+ */
674
+ async function explainFollowFailure(sftp: SFTPWrapper, path: string, cause: unknown): Promise<Error | undefined> {
675
+ const code = (cause as { code?: number } | undefined)?.code
676
+ if (code !== SFTP_NO_SUCH_FILE && code !== SFTP_FAILURE) return undefined
677
+ let attrs: Stats
678
+ try {
679
+ attrs = await statAsync(sftp, path)
680
+ } catch (error) {
681
+ const followCode = (error as { code?: number } | undefined)?.code
682
+ return followCode === SFTP_NO_SUCH_FILE ? new Error(`no such file: ${path}`) : undefined
683
+ }
684
+ if (isDir(attrs.mode)) return new Error(`not a file: ${path} is a directory`)
685
+ return undefined
686
+ }
687
+
475
688
  /**
476
689
  * Read one window of a file.
477
690
  *