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,118 @@
1
+ /**
2
+ * Minimal ~/.ssh/config reader for the import list.
3
+ *
4
+ * Handles the options a developer actually uses for a dev box: Host, HostName,
5
+ * Port, User, IdentityFile, ProxyJump, ProxyCommand. Wildcard aliases and
6
+ * `Match` blocks are skipped; `Include` is ignored rather than guessed at.
7
+ */
8
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
11
+
12
+ const KEY_FILE = /^(id_[a-z0-9_]+|.*\.pem)$/i
13
+
14
+ function expandHome(value) {
15
+ if (typeof value !== 'string') return ''
16
+ if (value.startsWith('~/')) return join(homedir(), value.slice(2))
17
+ return value
18
+ }
19
+
20
+ export function parseSshConfig(text) {
21
+ const entries = new Map()
22
+ const current = []
23
+ let skipping = false
24
+
25
+ for (const raw of String(text).split(/\r?\n/)) {
26
+ const line = raw.replace(/#.*$/, '').trim()
27
+ if (line.length === 0) continue
28
+ const match = /^(\S+)\s*(.*)$/.exec(line)
29
+ if (match === null) continue
30
+ const key = match[1].toLowerCase()
31
+ const rest = match[2].trim()
32
+
33
+ if (key === 'host') {
34
+ skipping = false
35
+ current.length = 0
36
+ for (const alias of rest.split(/\s+/)) {
37
+ if (alias.length === 0 || /[*?]/.test(alias)) {
38
+ skipping = true
39
+ continue
40
+ }
41
+ if (!entries.has(alias)) entries.set(alias, { alias, host: alias, port: 22, user: '', identityFile: '', proxy: '' })
42
+ current.push(alias)
43
+ }
44
+ continue
45
+ }
46
+ if (key === 'match') {
47
+ skipping = true
48
+ continue
49
+ }
50
+ if (skipping || current.length === 0) continue
51
+
52
+ for (const alias of current) {
53
+ const entry = entries.get(alias)
54
+ if (key === 'hostname') entry.host = rest
55
+ else if (key === 'port') entry.port = Number(rest) || 22
56
+ else if (key === 'user') entry.user = rest
57
+ else if (key === 'identityfile') entry.identityFile = expandHome(rest.split(/\s+/)[0])
58
+ else if (key === 'proxyjump') entry.proxy = 'jump:' + rest
59
+ else if (key === 'proxycommand') entry.proxy = 'proxy:' + rest
60
+ }
61
+ }
62
+
63
+ return [...entries.values()]
64
+ }
65
+
66
+ /**
67
+ * Rank a key file for the default order: `id_rsa` first, then the other
68
+ * `id_rsa*` files (its backups and variants), then everything else.
69
+ */
70
+ export function keyRank(name) {
71
+ const base = String(name).toLowerCase()
72
+ if (base === 'id_rsa') return 0
73
+ if (base.startsWith('id_rsa')) return 1
74
+ return 2
75
+ }
76
+
77
+ /**
78
+ * Sort key paths by that rank, then a-z inside each group, so the first entry —
79
+ * the one a dialog offers as the default — is the key every other tool reaches
80
+ * for. Sorting is case-insensitive and ignores the directory.
81
+ */
82
+ export function sortSshKeys(paths) {
83
+ const baseOf = (value) => String(value).slice(Math.max(String(value).lastIndexOf('/'), String(value).lastIndexOf('\\')) + 1)
84
+ return [...paths].sort((left, right) => {
85
+ const byRank = keyRank(baseOf(left)) - keyRank(baseOf(right))
86
+ if (byRank !== 0) return byRank
87
+ return baseOf(left).localeCompare(baseOf(right), 'en', { sensitivity: 'base' })
88
+ })
89
+ }
90
+
91
+ export function listSshKeys() {
92
+ const dir = join(homedir(), '.ssh')
93
+ if (!existsSync(dir)) return []
94
+ try {
95
+ const files = readdirSync(dir)
96
+ .filter((name) => KEY_FILE.test(name) && !name.endsWith('.pub') && !name.startsWith('known_hosts'))
97
+ .map((name) => join(dir, name))
98
+ return sortSshKeys(files)
99
+ } catch {
100
+ return []
101
+ }
102
+ }
103
+
104
+ export function readSshConfig() {
105
+ const path = join(homedir(), '.ssh', 'config')
106
+ let text = ''
107
+ try {
108
+ text = readFileSync(path, 'utf8')
109
+ } catch {
110
+ text = ''
111
+ }
112
+ return {
113
+ path,
114
+ exists: existsSync(path),
115
+ hosts: parseSshConfig(text),
116
+ keys: listSshKeys(),
117
+ }
118
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Remote PTY sessions.
3
+ *
4
+ * Each terminal is one ssh2 shell channel on the host's persistent client.
5
+ * Output is buffered (bounded) so a reconnecting page can replay what it
6
+ * missed; the API streams it as server-sent events.
7
+ */
8
+ import { randomUUID } from 'node:crypto'
9
+
10
+ const MAX_BUFFER = 256 * 1024
11
+
12
+ export class TerminalManager {
13
+ constructor({ hostFor, secrets, onLog }) {
14
+ this.hostFor = hostFor
15
+ this.secrets = secrets
16
+ this.onLog = onLog ?? (() => {})
17
+ this.terminals = new Map()
18
+ }
19
+
20
+ list() {
21
+ return [...this.terminals.values()].map((term) => ({
22
+ id: term.id,
23
+ connectionId: term.connectionId,
24
+ cols: term.cols,
25
+ rows: term.rows,
26
+ createdAt: term.createdAt,
27
+ exitCode: term.exitCode,
28
+ title: term.title,
29
+ }))
30
+ }
31
+
32
+ async open(connectionId, options = {}) {
33
+ const host = this.hostFor(connectionId)
34
+ if (host === undefined) throw new Error('connection not found')
35
+ await host.connect(this.secrets)
36
+ const cols = Number(options.cols) || 120
37
+ const rows = Number(options.rows) || 30
38
+ const stream = await host.shell({ cols, rows })
39
+ const term = {
40
+ id: randomUUID(),
41
+ connectionId,
42
+ stream,
43
+ cols,
44
+ rows,
45
+ createdAt: Date.now(),
46
+ exitCode: null,
47
+ title: options.title || 'bash',
48
+ buffer: [],
49
+ bufferBytes: 0,
50
+ listeners: new Set(),
51
+ }
52
+ const push = (chunk) => {
53
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
54
+ term.buffer.push(buffer)
55
+ term.bufferBytes += buffer.length
56
+ while (term.bufferBytes > MAX_BUFFER && term.buffer.length > 1) {
57
+ term.bufferBytes -= term.buffer.shift().length
58
+ }
59
+ const payload = { type: 'data', b64: buffer.toString('base64') }
60
+ for (const listener of term.listeners) listener(payload)
61
+ }
62
+ stream.on('data', push)
63
+ if (stream.stderr) stream.stderr.on('data', push)
64
+ stream.on('close', (code) => {
65
+ term.exitCode = typeof code === 'number' ? code : null
66
+ for (const listener of term.listeners) listener({ type: 'exit', code: term.exitCode })
67
+ term.listeners.clear()
68
+ // Keep the short replay for a reconnecting page, then release the buffer.
69
+ const cleanup = setTimeout(() => this.terminals.delete(term.id), 60000)
70
+ cleanup.unref?.()
71
+ })
72
+ stream.on('error', (error) => {
73
+ for (const listener of term.listeners) listener({ type: 'error', message: String(error && error.message ? error.message : error) })
74
+ })
75
+ this.terminals.set(term.id, term)
76
+ this.onLog('terminal open', connectionId, term.id)
77
+ return { id: term.id, cols, rows }
78
+ }
79
+
80
+ write(id, data) {
81
+ const term = this.terminals.get(id)
82
+ if (term === undefined) throw new Error('terminal not found')
83
+ if (term.exitCode !== null) return
84
+ term.stream.write(String(data))
85
+ }
86
+
87
+ resize(id, cols, rows) {
88
+ const term = this.terminals.get(id)
89
+ if (term === undefined) return
90
+ term.cols = Number(cols) || term.cols
91
+ term.rows = Number(rows) || term.rows
92
+ try {
93
+ term.stream.setWindow(term.rows, term.cols, 0, 0)
94
+ } catch {
95
+ /* some servers refuse window changes */
96
+ }
97
+ }
98
+
99
+ close(id) {
100
+ const term = this.terminals.get(id)
101
+ if (term === undefined) return
102
+ try {
103
+ term.stream.end()
104
+ } catch {
105
+ /* ignore */
106
+ }
107
+ this.terminals.delete(id)
108
+ }
109
+
110
+ /** Replay the buffer, then stream live events. Returns a detach function. */
111
+ attach(id, onEvent) {
112
+ const term = this.terminals.get(id)
113
+ if (term === undefined) return null
114
+ for (const chunk of term.buffer) onEvent({ type: 'data', b64: chunk.toString('base64') })
115
+ if (term.exitCode !== null) onEvent({ type: 'exit', code: term.exitCode })
116
+ term.listeners.add(onEvent)
117
+ return () => term.listeners.delete(onEvent)
118
+ }
119
+
120
+ closeAll() {
121
+ for (const id of [...this.terminals.keys()]) this.close(id)
122
+ }
123
+ }
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Agent tool: remote port forwarding.
3
+ *
4
+ * Exposes ForwardManager to the model: list the active forwards, detect which
5
+ * ports listen on a remote host, open a new forward to the DSH machine's
6
+ * loopback address, or close one by id. A forward binds 127.0.0.1 only, is
7
+ * persisted to forwards.json, and is rebuilt when the SSH connection returns.
8
+ *
9
+ * detect and start need a host (explicit connectionId, else the current remote
10
+ * workspace); list and stop work without any host context, because a forward
11
+ * id is unique and list spans every host.
12
+ */
13
+ import { errorText } from './util.js'
14
+
15
+ const ACTIONS = ['list', 'detect', 'start', 'stop']
16
+ const MAX_DETECT_PORTS = 40
17
+
18
+ /** Render a rejected argument value inside an error message. */
19
+ function show(value) {
20
+ if (value === undefined) return 'undefined'
21
+ if (typeof value === 'number' && Number.isNaN(value)) return 'NaN'
22
+ return JSON.stringify(value)
23
+ }
24
+
25
+ function isRemotePort(value) {
26
+ return Number.isInteger(value) && value >= 1 && value <= 65535
27
+ }
28
+
29
+ function ok(text) {
30
+ return { text, exitCode: 0 }
31
+ }
32
+
33
+ function fail(text) {
34
+ return { text, exitCode: 1 }
35
+ }
36
+
37
+ function explicitConnectionId(args) {
38
+ return typeof args.connectionId === 'string' && args.connectionId.trim().length > 0 ? args.connectionId.trim() : null
39
+ }
40
+
41
+ export function portForwardToolSpec({ resolveSession, forwards, hostNameFor }) {
42
+ const hostLabel = (connectionId) => {
43
+ const name = typeof hostNameFor === 'function' ? hostNameFor(connectionId) : undefined
44
+ return typeof name === 'string' && name.trim().length > 0 ? name.trim() : connectionId
45
+ }
46
+
47
+ const resolveConnectionId = async (args, exec) => {
48
+ const explicit = explicitConnectionId(args)
49
+ if (explicit !== null) return explicit
50
+ const session = typeof resolveSession === 'function' ? await resolveSession(exec) : null
51
+ const id = session === null || session === undefined ? undefined : session.connectionId
52
+ return typeof id === 'string' && id.trim().length > 0 ? id.trim() : null
53
+ }
54
+
55
+ /** Best effort lookup for read-only actions: a local or broken session must not fail them. */
56
+ const resolveQuietly = async (args, exec) => {
57
+ try {
58
+ return await resolveConnectionId(args, exec)
59
+ } catch {
60
+ return null
61
+ }
62
+ }
63
+
64
+ const runList = (connectionId) => {
65
+ const rows = forwards.list()
66
+ const lines = rows.length === 0
67
+ ? ['no active forwards']
68
+ : rows.map(
69
+ (row) => `${hostLabel(row.connectionId)} ${row.remotePort} -> 127.0.0.1:${row.localPort} [${row.url}] id=${row.id}`,
70
+ )
71
+ if (connectionId === null) {
72
+ lines.push('(no remote workspace in this session: listing forwards for every host; pass connectionId to detect or start one)')
73
+ }
74
+ return ok(lines.join('\n'))
75
+ }
76
+
77
+ const runDetect = async (connectionId) => {
78
+ const ports = await forwards.detect(connectionId)
79
+ if (ports.length === 0) return ok(`no listening ports detected on ${hostLabel(connectionId)}`)
80
+ const shown = ports.slice(0, MAX_DETECT_PORTS)
81
+ const lines = shown.map((row) =>
82
+ isRemotePort(row.localPort) ? `${row.port} (forwarded -> ${row.localPort})` : `${row.port} (not forwarded)`,
83
+ )
84
+ if (ports.length > shown.length) {
85
+ lines.push(`... ${ports.length - shown.length} more ports omitted (showing the first ${shown.length} of ${ports.length})`)
86
+ }
87
+ lines.push('Forward one to 127.0.0.1 on this machine with remote_forward action:"start" and that remotePort (omit localPort for a random free port).')
88
+ return ok(`Listening ports on ${hostLabel(connectionId)}:\n${lines.join('\n')}`)
89
+ }
90
+
91
+ const runStart = async (connectionId, args) => {
92
+ if (!isRemotePort(args.remotePort)) {
93
+ return fail(`remotePort must be an integer between 1 and 65535 (got ${show(args.remotePort)}).`)
94
+ }
95
+ let localPort = 0
96
+ if (args.localPort !== undefined && args.localPort !== null) {
97
+ if (!Number.isInteger(args.localPort) || args.localPort < 0 || args.localPort > 65535) {
98
+ return fail(`localPort must be an integer between 0 and 65535, where 0 means a random free port (got ${show(args.localPort)}).`)
99
+ }
100
+ localPort = args.localPort
101
+ }
102
+ const view = await forwards.start(connectionId, args.remotePort, localPort, 'agent')
103
+ return ok(
104
+ [
105
+ `Forwarding ${hostLabel(connectionId)} port ${view.remotePort} -> 127.0.0.1:${view.localPort}`,
106
+ `URL: ${view.url}`,
107
+ `id: ${view.id}`,
108
+ 'The forward is saved and is rebuilt automatically when the SSH connection comes back; it also shows in the plugin SSH console on the port-forwarding tab, marked as created by the agent, and is counted on the Session header pill.',
109
+ `Stop it with remote_forward action:"stop" id:"${view.id}".`,
110
+ ].join('\n'),
111
+ )
112
+ }
113
+
114
+ const runStop = (args) => {
115
+ const id = typeof args.id === 'string' ? args.id.trim() : ''
116
+ if (id.length === 0) return fail('remote_forward action:"stop" needs the id of the forward to close; get it from action:"list".')
117
+ const named = explicitConnectionId(args)
118
+ const where = named === null ? '' : ` on ${hostLabel(named)}`
119
+ if (!forwards.stop(id)) {
120
+ return fail(`no forward with id ${show(id)}${where} (it may already be stopped; run action:"list" to see what is active).`)
121
+ }
122
+ return ok(`Stopped forward ${id}${where}.`)
123
+ }
124
+
125
+ return {
126
+ name: 'remote_forward',
127
+ description:
128
+ 'Forward a TCP port on a remote SSH host to 127.0.0.1 on the machine running DSH, and manage existing forwards. ' +
129
+ 'A forward listens only on the loopback address (127.0.0.1:<localPort>), so it is reachable from DSH itself and never exposed to the network. ' +
130
+ 'Forwards are persisted and are rebuilt automatically after an SSH reconnect; they also appear in the plugin SSH console on the port-forwarding tab, and action:"stop" closes one. ' +
131
+ 'Actions: "list" shows the active forwards of every host; "detect" lists ports listening on a host and marks the ones already forwarded; ' +
132
+ '"start" opens a forward for remotePort (localPort is optional: omit it or pass 0 for a random free port); "stop" closes one by id. ' +
133
+ 'detect and start need a host: they use the current remote workspace unless connectionId names another connected host. ' +
134
+ 'list and stop need no host context, because a forward id is unique and list covers every host. ' +
135
+ 'Use it to reach a remote dev server, notebook or database from the DSH machine.',
136
+ parameters: {
137
+ type: 'object',
138
+ properties: {
139
+ action: {
140
+ type: 'string',
141
+ enum: ACTIONS,
142
+ description: 'list active forwards, detect listening remote ports, start a forward, or stop one by id.',
143
+ },
144
+ remotePort: { type: 'number', description: 'Port on the remote host to forward; required for action:"start".' },
145
+ localPort: {
146
+ type: 'number',
147
+ description: 'Loopback port on the DSH machine; optional, 0 or omitted picks a random free port.',
148
+ },
149
+ id: { type: 'string', description: 'Id of the forward to close; required for action:"stop".' },
150
+ connectionId: {
151
+ type: 'string',
152
+ description: 'Optional SSH host id; defaults to the current remote workspace host for detect and start.',
153
+ },
154
+ },
155
+ required: ['action'],
156
+ additionalProperties: false,
157
+ },
158
+ output: {
159
+ schema: {
160
+ type: 'object',
161
+ properties: { text: { type: 'string' }, exitCode: { type: 'integer' } },
162
+ required: ['text', 'exitCode'],
163
+ additionalProperties: false,
164
+ },
165
+ render: (_args, value) => [{ type: 'text', text: value.text }],
166
+ },
167
+ async execute(args, exec) {
168
+ const input = args !== null && typeof args === 'object' ? args : {}
169
+ try {
170
+ const action = typeof input.action === 'string' ? input.action : ''
171
+ if (!ACTIONS.includes(action)) {
172
+ return fail(`unknown action ${show(input.action)}; expected one of ${ACTIONS.map((name) => `"${name}"`).join(', ')}.`)
173
+ }
174
+ if (action === 'list') return runList(await resolveQuietly(input, exec))
175
+ if (action === 'stop') return runStop(input)
176
+ const connectionId = await resolveConnectionId(input, exec)
177
+ if (connectionId === null) return fail('remote_forward needs a remote workspace or an explicit connectionId')
178
+ if (action === 'detect') return await runDetect(connectionId)
179
+ return await runStart(connectionId, input)
180
+ } catch (error) {
181
+ return fail('remote_forward failed: ' + errorText(error))
182
+ }
183
+ },
184
+ }
185
+ }
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Remote transfer commands and the parsing of their output.
3
+ *
4
+ * Both the shell handed to SSH and the reading of what comes back live here as
5
+ * pure functions, so quoting, the archive flags and the scan counters can be
6
+ * unit tested without a remote machine.
7
+ *
8
+ * Two rules shape the archive: symbolic links are never followed (they are not
9
+ * even listed) and the walk stops at filesystem boundaries, so neither a
10
+ * symlink cycle nor a mount point can make a download hang or grow forever.
11
+ */
12
+ import { posix } from 'node:path'
13
+ import { shellQuote } from './util.js'
14
+
15
+ /** Wall-clock budget for the remote scan, in seconds. */
16
+ export const SCAN_TIMEOUT_SECONDS = 20
17
+
18
+ const BYTES_MARKER = 'rdscan-bytes'
19
+ const DONE_MARKER = 'rdscan-done'
20
+ const TIMEOUT_MARKER = 'rdscan-timeout'
21
+
22
+ /**
23
+ * `find` reads an operand that starts with a dash as an option. The archive
24
+ * route already rejects such names, but the command builder stays honest on
25
+ * its own, without relying on a caller's validation.
26
+ */
27
+ function findTarget(value) {
28
+ const name = String(value ?? '')
29
+ return name.startsWith('-') ? `./${name}` : name
30
+ }
31
+
32
+ /**
33
+ * Archive a single directory, to be run with the remote working directory set
34
+ * to its parent. `find` feeds `tar` an explicit list of regular files and
35
+ * directories only, which keeps symlinks, sockets, FIFOs and devices out of the
36
+ * archive; `-xdev` keeps the walk on one filesystem; `-print0`/`--null` keep
37
+ * unusual names intact. `--no-recursion` is what makes the explicit list the whole
38
+ * truth: without it `tar` would re-walk every directory it is handed and add the
39
+ * very symlinks the list left out. GNU tar gets `--ignore-failed-read` so a single
40
+ * unreadable file is skipped rather than failing the whole download; BSD tar
41
+ * has no such flag and does not need it.
42
+ *
43
+ * A tar without `--null` (BusyBox, for one) cannot take that list at all, so it
44
+ * is probed first and falls back to plain recursion from the working directory:
45
+ * links are then stored as links instead of being skipped, but the download
46
+ * still arrives instead of failing outright.
47
+ */
48
+ export function archiveCommand(base) {
49
+ const target = shellQuote(findTarget(base))
50
+ return [
51
+ 'extra=""',
52
+ 'case "$(tar --version 2>/dev/null | head -1)" in *GNU*) extra="--ignore-failed-read";; esac',
53
+ 'if tar --null --no-recursion -cf /dev/null -T /dev/null 2>/dev/null; then',
54
+ ` find ${target} -xdev \\( -type f -o -type d \\) -print0 | tar czf - --null --no-recursion $extra -T -`,
55
+ 'else',
56
+ ` tar czf - $extra ${target}`,
57
+ 'fi',
58
+ ].join('\n')
59
+ }
60
+
61
+ /** The deepest directory that contains every given directory. */
62
+ function commonParent(parents) {
63
+ let shared = String(parents[0] ?? '/').split('/').filter((part) => part.length > 0)
64
+ for (const parent of parents.slice(1)) {
65
+ const parts = String(parent).split('/').filter((part) => part.length > 0)
66
+ let index = 0
67
+ while (index < shared.length && index < parts.length && shared[index] === parts[index]) index += 1
68
+ shared = shared.slice(0, index)
69
+ }
70
+ return `/${shared.join('/')}`
71
+ }
72
+
73
+ /**
74
+ * Archive several absolute paths into one flat archive, to be run without a
75
+ * working directory.
76
+ *
77
+ * Every path contributes `-C <its parent>` plus a `-T` list holding the names
78
+ * *relative to that parent*, so the members are `app/...` and `notes.txt`
79
+ * rather than `home/alice/app/...`. The lists are NUL-delimited `find` output kept
80
+ * in a private temporary directory: `-C` is order sensitive and only affects the
81
+ * names that follow it, and a run needs one group per parent, which no single
82
+ * `-T -` pipe could carry. One `tar` invocation keeps the result a single gzip
83
+ * stream. A path that is gone is skipped with find's own line on stderr (and an
84
+ * empty list), so one deleted file cannot fail the whole download.
85
+ *
86
+ * A tar without `--null` cannot take those lists at all (BusyBox, for one) and
87
+ * falls back to recursion. Such a tar also honours only the last `-C` it is
88
+ * given (verified on BusyBox 1.30), so the fallback archives the whole selection
89
+ * from the deepest directory that contains every path: one `tar` call, names
90
+ * relative to that directory — flat when the selection shares a parent, one
91
+ * level deeper per extra parent otherwise. Links are then stored as links,
92
+ * exactly as the single-path fallback does.
93
+ */
94
+ export function archivePathsCommand(paths) {
95
+ const targets = paths.map((value) => {
96
+ const path = String(value ?? '')
97
+ return { path, parent: posix.dirname(path) }
98
+ })
99
+ const writes = []
100
+ const operands = []
101
+ for (const [index, target] of targets.entries()) {
102
+ const list = `"$listdir/${index}"`
103
+ writes.push(` : > ${list}`)
104
+ writes.push(` ( cd ${shellQuote(target.parent)} && find ${shellQuote(findTarget(posix.basename(target.path)))} -xdev \\( -type f -o -type d \\) -print0 > ${list} ) || :`)
105
+ operands.push(`-C ${shellQuote(target.parent)} -T ${list}`)
106
+ }
107
+ const ancestor = commonParent(targets.map((target) => target.parent))
108
+ const relatives = targets.map((target) => shellQuote(findTarget(posix.relative(ancestor, target.path) || '.')))
109
+ const recursive = ` ( cd ${shellQuote(ancestor)} && tar czf - $extra ${relatives.join(' ')} ) || :`
110
+ return [
111
+ 'extra=""',
112
+ 'case "$(tar --version 2>/dev/null | head -1)" in *GNU*) extra="--ignore-failed-read";; esac',
113
+ 'if tar --null --no-recursion -cf /dev/null -T /dev/null 2>/dev/null && listdir=$(mktemp -d 2>/dev/null); then',
114
+ // The lists hold remote paths, so the directory stays private and goes away
115
+ // even when tar fails.
116
+ ` trap 'rm -rf "$listdir"' EXIT HUP INT TERM`,
117
+ ...writes,
118
+ ` tar czf - --null --no-recursion $extra ${operands.join(' ')}`,
119
+ 'else',
120
+ recursive,
121
+ 'fi',
122
+ ].join('\n')
123
+ }
124
+
125
+ /** One entry per kind, so the output stays a handful of lines however large the tree. */
126
+ const CLASSIFY = [
127
+ 'for p; do',
128
+ ' if [ -L "$p" ]; then echo l',
129
+ ' elif [ -d "$p" ]; then if [ -r "$p" ] && [ -x "$p" ]; then echo d; else echo u; fi',
130
+ ' elif [ -f "$p" ]; then if [ -r "$p" ]; then echo f; else echo u; fi',
131
+ ' else echo o; fi',
132
+ 'done',
133
+ ].join('\n')
134
+
135
+ /**
136
+ * The unguarded scan script: one traversal, one line per kind, then the byte
137
+ * total. Entries that cannot be read are counted instead of aborting the walk;
138
+ * the done marker is only echoed when the script reaches its end, so a kill
139
+ * (timeout) is visible to the parser as a missing marker.
140
+ */
141
+ function scanBody(dir) {
142
+ const target = shellQuote(findTarget(dir))
143
+ return [
144
+ // A missing `find` must not be mistaken for an empty folder: no done marker.
145
+ 'command -v find >/dev/null 2>&1 || exit 1',
146
+ `find ${target} -xdev -mindepth 1 -exec sh -c ${shellQuote(CLASSIFY)} _ {} + 2>/dev/null | sort | uniq -c`,
147
+ `bytes=$(du -sb ${target} 2>/dev/null | awk 'NR==1{print $1}')`,
148
+ 'if [ -z "$bytes" ]; then',
149
+ // BSD du has no -b; fall back to 1024-byte blocks.
150
+ ` bytes=$(du -sk ${target} 2>/dev/null | awk 'NR==1{print $1}')`,
151
+ ' if [ -n "$bytes" ]; then bytes=$((bytes * 1024)); fi',
152
+ 'fi',
153
+ '[ -n "$bytes" ] || bytes=0',
154
+ `echo "${BYTES_MARKER} $bytes"`,
155
+ `echo ${DONE_MARKER}`,
156
+ ].join('\n')
157
+ }
158
+
159
+ /**
160
+ * Scan a remote directory, to be run without a working directory (the path is
161
+ * absolute). The work is time-boxed with `timeout` where the remote has it; the
162
+ * API route adds its own abort so a missing `timeout` cannot hang a request.
163
+ */
164
+ export function scanCommand(dir) {
165
+ const body = shellQuote(scanBody(dir))
166
+ return [
167
+ 'if command -v timeout >/dev/null 2>&1; then',
168
+ ` timeout ${SCAN_TIMEOUT_SECONDS} sh -c ${body}`,
169
+ ' rc=$?',
170
+ // timeout(1) exits 124; a signal-killed child lands above that.
171
+ ` if [ "$rc" -ge 124 ]; then echo ${TIMEOUT_MARKER}; fi`,
172
+ 'else',
173
+ ` sh -c ${body}`,
174
+ 'fi',
175
+ ].join('\n')
176
+ }
177
+
178
+ const KINDS = new Map([
179
+ ['f', 'files'],
180
+ ['file', 'files'],
181
+ ['files', 'files'],
182
+ ['d', 'dirs'],
183
+ ['dir', 'dirs'],
184
+ ['dirs', 'dirs'],
185
+ ['directory', 'dirs'],
186
+ ['directories', 'dirs'],
187
+ ['l', 'links'],
188
+ ['link', 'links'],
189
+ ['links', 'links'],
190
+ ['symlink', 'links'],
191
+ ['symlinks', 'links'],
192
+ ['u', 'unreadable'],
193
+ ['unreadable', 'unreadable'],
194
+ ['unread', 'unreadable'],
195
+ ['denied', 'unreadable'],
196
+ ['o', 'others'],
197
+ ['other', 'others'],
198
+ ['others', 'others'],
199
+ ['special', 'others'],
200
+ ])
201
+
202
+ /**
203
+ * Read the output of `scanCommand`. Missing kinds stay at zero and lines may
204
+ * arrive in any order; `complete` is only true when the script reached its end
205
+ * without reporting a timeout — a truncated answer is still worth showing.
206
+ */
207
+ export function parseScanOutput(text) {
208
+ const result = { files: 0, dirs: 0, links: 0, unreadable: 0, others: 0, bytes: 0, complete: false }
209
+ if (typeof text !== 'string' || text.length === 0) return result
210
+ let timedOut = false
211
+ for (const raw of text.split('\n')) {
212
+ const line = raw.trim()
213
+ if (line.length === 0) continue
214
+ if (line === DONE_MARKER) {
215
+ result.complete = true
216
+ continue
217
+ }
218
+ if (line === TIMEOUT_MARKER) {
219
+ timedOut = true
220
+ continue
221
+ }
222
+ const bytes = /^rdscan-bytes\s+(\d+)$/.exec(line)
223
+ if (bytes !== null) {
224
+ result.bytes = Number(bytes[1])
225
+ continue
226
+ }
227
+ const counted = /^(\d+)\s+([A-Za-z]+)$/.exec(line)
228
+ if (counted !== null) {
229
+ const key = KINDS.get(counted[2].toLowerCase())
230
+ if (key !== undefined) result[key] += Number(counted[1])
231
+ }
232
+ }
233
+ if (timedOut) result.complete = false
234
+ return result
235
+ }