dsh-remote-vs 0.11.1 → 0.13.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',