dsh-remote-go 0.0.1 → 0.1.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 (49) hide show
  1. package/README.md +126 -7
  2. package/client.js +5972 -0
  3. package/cordis.patch.yml +3 -0
  4. package/index.js +4 -0
  5. package/locale/en.json +6 -0
  6. package/locale/zh.json +6 -0
  7. package/package.json +76 -3
  8. package/src/api.js +340 -0
  9. package/src/atomic-json.js +208 -0
  10. package/src/bootstrap.js +100 -0
  11. package/src/connect-log.js +39 -0
  12. package/src/connect-pipeline.js +463 -0
  13. package/src/connect-progress.js +135 -0
  14. package/src/constants.js +31 -0
  15. package/src/diagnostics.js +157 -0
  16. package/src/download-jobs.js +217 -0
  17. package/src/errors.js +316 -0
  18. package/src/host-lifecycle.js +187 -0
  19. package/src/host-registry.js +145 -0
  20. package/src/host-runtime.js +53 -0
  21. package/src/host-view.js +51 -0
  22. package/src/index.js +162 -0
  23. package/src/key-files.js +49 -0
  24. package/src/known-hosts.js +94 -0
  25. package/src/layout.js +35 -0
  26. package/src/local-download.js +162 -0
  27. package/src/local-ssh.js +27 -0
  28. package/src/local-version.js +88 -0
  29. package/src/node-runtime.js +521 -0
  30. package/src/probe.js +89 -0
  31. package/src/prompts.js +132 -0
  32. package/src/redact.js +54 -0
  33. package/src/remote-files.js +71 -0
  34. package/src/remote-path.js +73 -0
  35. package/src/remote-proc.js +208 -0
  36. package/src/remote-web.js +300 -0
  37. package/src/secrets.js +79 -0
  38. package/src/service.js +250 -0
  39. package/src/settings.js +135 -0
  40. package/src/ssh-config.js +271 -0
  41. package/src/ssh.js +652 -0
  42. package/src/store.js +143 -0
  43. package/src/tunnel.js +73 -0
  44. package/src/util.js +153 -0
  45. package/src/version.js +103 -0
  46. package/src/webapp.js +28 -0
  47. package/vendor/THIRD_PARTY_NOTICES.md +10 -0
  48. package/vendor/ssh2-entry.mjs +12 -0
  49. package/vendor/ssh2.bundle.cjs +25 -0
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The client-facing view of one host (docs/api.md HostView).
3
+ */
4
+ import { versionParity } from './version.js'
5
+ import { connectLogTail, connectLogVisible } from './connect-log.js'
6
+
7
+ export function hostView(runtime, ctx) {
8
+ const entry = runtime.entry
9
+ return {
10
+ id: runtime.id,
11
+ name: entry.name,
12
+ address: entry.address,
13
+ addressMasked: maskAddress(entry),
14
+ /** Never the secret itself; lets the Client ask for a one-time password. */
15
+ authType: entry.auth?.type ?? 'key',
16
+ /** The configured key file path (not a secret); lets the edit form prefill it. */
17
+ authKeyPath: entry.auth?.type === 'key' && typeof entry.auth.keyPath === 'string' ? entry.auth.keyPath : null,
18
+ /** Whether a remembered password exists in the credential store (never the value). */
19
+ passwordSaved: entry.auth?.type === 'password' ? runtime.passwordSaved === true || runtime.password != null : false,
20
+ passwordStorageAvailable: ctx.passwordStorageAvailable,
21
+ jumpHost: entry.jumpHost ?? null,
22
+ status: runtime.status,
23
+ phase: runtime.phase,
24
+ progress: runtime.progress,
25
+ error: runtime.error,
26
+ warning: runtime.warning,
27
+ conflict: runtime.conflict,
28
+ fingerprint: runtime.fingerprint,
29
+ logs: connectLogVisible(runtime.status) ? connectLogTail(runtime) : [],
30
+ remote: {
31
+ ...runtime.remote,
32
+ version: runtime.remote.version ?? null,
33
+ },
34
+ keepAlive: entry.keepAlive,
35
+ idleMinutes: entry.idleMinutes,
36
+ autoReconnect: entry.autoReconnect,
37
+ hostKeyPolicy: entry.hostKeyPolicy,
38
+ lastOpenedAt: entry.lastOpenedAt,
39
+ createdAt: entry.createdAt,
40
+ updatedAt: entry.updatedAt,
41
+ targetVersion: ctx.targetVersion,
42
+ versionParity: versionParity(ctx.targetVersion, runtime.remote.version ?? null),
43
+ }
44
+ }
45
+
46
+ function maskAddress(entry) {
47
+ const port = entry.port && entry.port !== 22 ? `:${entry.port}` : ''
48
+ const user = entry.username ? `${entry.username}@` : ''
49
+ const host = entry.address || '?'
50
+ return `${user}${host}${port}`
51
+ }
package/src/index.js ADDED
@@ -0,0 +1,162 @@
1
+ /**
2
+ * dsh-remote-go — Host half: registers the local HTTP API the browser panel uses and owns the SSH / bootstrap / tunnel lifecycle; it never proxies UI bytes.
3
+ */
4
+ import { API_PREFIX, PLUGIN_ID } from './constants.js'
5
+ import { statSync } from 'node:fs'
6
+ import path from 'node:path'
7
+ import { createApi } from './api.js'
8
+ import { detectLocalEnginesNode, detectLocalVersion } from './local-version.js'
9
+ import { RemoteGoService } from './service.js'
10
+ import { createSecretStore } from './secrets.js'
11
+ import { HostStore, resolveDshHome, resolveStateDir } from './store.js'
12
+ import { messageOf } from './util.js'
13
+
14
+ export const name = PLUGIN_ID
15
+ export const inject = ['webServer']
16
+
17
+ export const optional = ['connection', 'credentials']
18
+
19
+ export function apply(ctx, config = {}) {
20
+ const logger = createLogger()
21
+ const home = config.home ? String(config.home) : resolveDshHome(process.env)
22
+ const stateDir = resolveStateDir(home)
23
+ const store = new HostStore({ dir: stateDir, logger })
24
+ // Saved SSH passwords live in DSH's credential store, never in hosts.json.
25
+ const secrets = createSecretStore({ ctx, logger })
26
+ const service = new RemoteGoService({
27
+ store,
28
+ home,
29
+ logger,
30
+ secrets,
31
+ localVersion: config.localVersion ? String(config.localVersion) : null,
32
+ hostKeyConfirmTimeoutMs: config.hostKeyConfirmTimeoutMs,
33
+ })
34
+ const getOrigin = () => {
35
+ try {
36
+ return ctx.webServer?.getOrigin?.() ?? null
37
+ } catch {
38
+ return null
39
+ }
40
+ }
41
+ const api = createApi({
42
+ service,
43
+ getOrigin,
44
+ logger,
45
+ diagnostics: () =>
46
+ describeSelf(ctx, {
47
+ home,
48
+ stateDir,
49
+ localVersion: service.localVersion,
50
+ engineNodeRange: service.engineNodeRange,
51
+ }),
52
+ })
53
+
54
+ ctx.effect(() => {
55
+ const disposeRoute = ctx.webServer.register({
56
+ kind: 'prefix',
57
+ path: API_PREFIX,
58
+ handler: (/** @type {any} */ req, /** @type {any} */ res) => {
59
+ void api.handler(req, res)
60
+ },
61
+ })
62
+ logger.info(`API mounted at ${API_PREFIX} (state dir ${stateDir})`)
63
+
64
+ void (async () => {
65
+ try {
66
+ await service.init()
67
+ const detected = await detectLocalVersion({ ctx })
68
+ if (detected.version) service.setLocalVersion(detected.version, detected.source)
69
+ // The managed Node version is the lower bound of DSH's own `engines.node`;
70
+ // reading it here keeps the plugin in step with the running DSH build.
71
+ const engine = await detectLocalEnginesNode({ ctx })
72
+ if (engine.range) service.setLocalEnginesNode(engine.range, engine.source)
73
+ if (!detected.version)
74
+ logger.warn(
75
+ 'could not detect the local DSH version; the remote npx runtime cannot be pinned to this machine, so connections will fail until the version is readable',
76
+ )
77
+ } catch (error) {
78
+ logger.error('initialization failed:', error)
79
+ }
80
+ })()
81
+
82
+ return () => {
83
+ api.dispose()
84
+ void service.shutdown()
85
+ disposeRoute()
86
+ logger.info('unloaded')
87
+ }
88
+ }, 'dsh-remote-go: http api + service')
89
+
90
+ return service
91
+ }
92
+
93
+ function describeSelf(ctx, info) {
94
+ const out = {
95
+ home: info.home,
96
+ stateDir: info.stateDir,
97
+ hostVersion: info.localVersion,
98
+ engineNodeRange: info.engineNodeRange ?? null,
99
+ entry: null,
100
+ client: null,
101
+ }
102
+ try {
103
+ const entry = ctx?.fiber?.entry
104
+ out.entry = {
105
+ id: entry?.options?.id ?? null,
106
+ name: entry?.options?.name ?? null,
107
+ }
108
+ } catch {
109
+ /* fiber shape is loader-internal; diagnostics must never throw */
110
+ }
111
+ try {
112
+ const clientModules = ctx?.get?.('clientModules') ?? ctx?.clientModules
113
+ const graph = clientModules?.graph?.()
114
+ const clientPath = clientModules?.clientPath?.(PLUGIN_ID) ?? null
115
+ const row = Array.isArray(graph?.entries) ? (graph.entries.find((item) => item.id === PLUGIN_ID) ?? null) : null
116
+ let bundle = null
117
+ if (clientPath) {
118
+ try {
119
+ const stat = statSync(clientPath)
120
+ bundle = { path: clientPath, size: stat.size, mtimeMs: stat.mtimeMs }
121
+ } catch (error) {
122
+ bundle = { path: clientPath, error: messageOf(error) }
123
+ }
124
+ }
125
+ out.client = {
126
+ graph: graph ? { rev: graph.rev ?? null, release: graph.release ?? null, entries: graph.entries.length } : null,
127
+ row: row
128
+ ? { id: row.id, rev: row.rev, url: row.url, inject: row.inject ?? [], immediately: row.immediately === true }
129
+ : null,
130
+ clientPath,
131
+ bundle,
132
+ }
133
+ } catch (error) {
134
+ out.client = { error: messageOf(error) }
135
+ }
136
+ return out
137
+ }
138
+
139
+ function createLogger() {
140
+ const tag = '[dsh-remote-go]'
141
+ const write = (/** @type {'info'|'warn'|'error'|'debug'} */ level, /** @type {any[]} */ args) => {
142
+ const sink =
143
+ level === 'debug'
144
+ ? console.debug
145
+ : level === 'error'
146
+ ? console.error
147
+ : level === 'warn'
148
+ ? console.warn
149
+ : console.info
150
+ try {
151
+ sink?.call(console, tag, ...args)
152
+ } catch {
153
+ /* logging must never throw */
154
+ }
155
+ }
156
+ return {
157
+ info: (...args) => write('info', args),
158
+ warn: (...args) => write('warn', args),
159
+ error: (...args) => write('error', args),
160
+ debug: (...args) => write('debug', args),
161
+ }
162
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Read-only directory browsing for the key-file picker; a path that resolves outside the user home directory (through `..` or a symlink) is refused.
3
+ */
4
+ import { promises as fs } from 'node:fs'
5
+ import path from 'node:path'
6
+ import { expandHome } from './util.js'
7
+
8
+ const MAX_ENTRIES = 500
9
+
10
+ export async function listKeyFiles(options) {
11
+ const home = path.resolve(options.home)
12
+ const impl = options.fsImpl ?? fs
13
+ // Canonical base: the home directory spelled the way the filesystem reports it.
14
+ // Every path below derives from this one spelling, so the returned `path` and
15
+ // `parent` can never disagree — Windows hands out an 8.3 short path
16
+ // (`C:\Users\RUNNER~1\…`) for a directory that realpath reports in long form.
17
+ const realHome = await impl.realpath(home).catch(() => home)
18
+ const requested = expandHome(options.dir, realHome)
19
+ const target = path.resolve(requested || path.join(realHome, '.ssh'))
20
+ // Resolve first, then judge: a symlinked directory may lead outside home. A path
21
+ // that does not exist keeps its requested spelling, which the check still judges.
22
+ const realTarget = await impl.realpath(target).catch(() => target)
23
+ if (realTarget !== realHome && !realTarget.startsWith(realHome + path.sep)) {
24
+ throw new Error('key-file path must stay inside the home directory')
25
+ }
26
+
27
+ const dirents = await impl.readdir(realTarget, { withFileTypes: true })
28
+ const entries = []
29
+ for (const dirent of dirents) {
30
+ const full = path.join(realTarget, dirent.name)
31
+ const isDirectory = dirent.isDirectory()
32
+ // Only regular files and directories are selectable; a socket or device node
33
+ // in a home directory is never a private key.
34
+ if (!isDirectory && !dirent.isFile()) continue
35
+ entries.push({ name: dirent.name, path: full, isDirectory })
36
+ }
37
+ entries.sort((left, right) => {
38
+ if (left.isDirectory !== right.isDirectory) return left.isDirectory ? -1 : 1
39
+ return left.name.localeCompare(right.name)
40
+ })
41
+ const shown = entries.slice(0, MAX_ENTRIES)
42
+ const parent = realTarget === realHome ? null : path.dirname(realTarget)
43
+ return {
44
+ path: realTarget,
45
+ parent: parent ?? realHome,
46
+ entries: shown,
47
+ truncated: entries.length > shown.length,
48
+ }
49
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Read-only `~/.ssh/known_hosts` parsing and OpenSSH SHA256 fingerprints; hashed entries are counted, never guessed at.
3
+ */
4
+ import { createHash } from 'node:crypto'
5
+
6
+ export function fingerprintFromBase64(keyBase64) {
7
+ const digest = createHash('sha256').update(Buffer.from(keyBase64, 'base64')).digest('base64')
8
+ return `SHA256:${digest.replace(/=+$/g, '')}`
9
+ }
10
+
11
+ export function fingerprintFromBlob(keyBlob) {
12
+ const digest = createHash('sha256').update(keyBlob).digest('base64')
13
+ return `SHA256:${digest.replace(/=+$/g, '')}`
14
+ }
15
+
16
+ export function parseKnownHosts(text) {
17
+ const entries = []
18
+ const malformed = []
19
+ let hashedCount = 0
20
+ let revoked = 0
21
+ let certAuthority = 0
22
+
23
+ const lines = String(text ?? '').split(/\r?\n/)
24
+ for (let index = 0; index < lines.length; index += 1) {
25
+ const lineNo = index + 1
26
+ const raw = lines[index].trim()
27
+ if (raw === '' || raw.startsWith('#')) continue
28
+ const parts = raw.split(/\s+/)
29
+ let marker = null
30
+ if (parts[0].startsWith('@')) marker = parts.shift() ?? null
31
+ if (parts.length < 3) {
32
+ malformed.push({ line: lineNo, text: raw })
33
+ continue
34
+ }
35
+ const [hostField, keyType, keyBase64] = parts
36
+ if (marker === '@revoked') {
37
+ revoked += 1
38
+ continue
39
+ }
40
+ if (marker === '@cert-authority') {
41
+ certAuthority += 1
42
+ continue
43
+ }
44
+ if (hostField.startsWith('|1|')) {
45
+ hashedCount += 1
46
+ continue
47
+ }
48
+ if (!/^[A-Za-z0-9+/=]+$/.test(keyBase64 ?? '')) {
49
+ malformed.push({ line: lineNo, text: raw })
50
+ continue
51
+ }
52
+ entries.push({
53
+ hosts: hostField.split(',').filter(Boolean),
54
+ keyType,
55
+ keyBase64,
56
+ fingerprint: fingerprintFromBase64(keyBase64),
57
+ marker,
58
+ line: lineNo,
59
+ })
60
+ }
61
+ return { entries, hashedCount, malformed, revoked, certAuthority }
62
+ }
63
+
64
+ export function knownHostFieldMatches(pattern, host, port) {
65
+ const portSuffix = port && port !== 22 ? `:${port}` : null
66
+ const candidates = portSuffix ? [`[${host}]${portSuffix}`] : []
67
+ // A plain `host` line also matches a non-default port only for SSH's default
68
+ // behavior; be conservative and require the bracketed form for non-22.
69
+ candidates.push(host, `[${host}]`)
70
+ const escaped = String(pattern)
71
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
72
+ .replace(/\*/g, '.*')
73
+ .replace(/\?/g, '.')
74
+ const matcher = new RegExp(`^${escaped}$`, 'i')
75
+ return candidates.some((candidate) => matcher.test(candidate))
76
+ }
77
+
78
+ export function findKnownHostEntries(parsed, host, port) {
79
+ return parsed.entries.filter((entry) => entry.hosts.some((pattern) => knownHostFieldMatches(pattern, host, port)))
80
+ }
81
+
82
+ export function summarizeKnownHosts(parsed) {
83
+ const hosts = new Set()
84
+ for (const entry of parsed.entries) {
85
+ for (const host of entry.hosts) {
86
+ if (!host.startsWith('|1|')) hosts.add(host)
87
+ }
88
+ }
89
+ return {
90
+ entries: parsed.entries.length,
91
+ hashed: parsed.hashedCount,
92
+ hosts: [...hosts].sort().slice(0, 200),
93
+ }
94
+ }
package/src/layout.js ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Remote directory layout: everything the plugin writes lives under `$DSH_HOME/remote-go`, so a host only gets `~/.dsh` plus that one subdirectory.
3
+ */
4
+ import { REMOTE_DSH_DIR, REMOTE_STATE_DIR } from './constants.js'
5
+
6
+ export function remoteLayout(home = null) {
7
+ const dshHome = expandRemoteTilde(`~/${REMOTE_DSH_DIR}`, home).replace(/\/+$/, '')
8
+ const root = `${dshHome}/${REMOTE_STATE_DIR}`
9
+ return {
10
+ root,
11
+ // Kept for callers that resolve the remote DSH home separately from the
12
+ // plugin's own state directory.
13
+ stateHome: dshHome,
14
+ // The remote DSH runs with its real home, so its data is the user's own.
15
+ dshHome,
16
+ nodeDir: `${root}/node`,
17
+ downloadDir: `${root}/downloads`,
18
+ logsDir: `${root}/logs`,
19
+ logFile: `${root}/logs/web.log`,
20
+ runDir: `${root}/run`,
21
+ runFile: `${root}/run/web.json`,
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Expand a leading `~` (or `~/`) with a known remote home. When `home` is not
27
+ * known yet the tilde is preserved; callers must expand before shell use.
28
+ */
29
+ function expandRemoteTilde(value, home) {
30
+ const text = String(value ?? '')
31
+ if (!home) return text
32
+ if (text === '~') return home
33
+ if (text.startsWith('~/')) return `${home.replace(/\/+$/, '')}/${text.slice(2)}`
34
+ return text
35
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Local download writer. Every download (single file or folder) is streamed from
3
+ * SFTP directly to a user-selected local directory. Nothing is archived or held in
4
+ * memory, and there is no byte or entry cap. Existing target names are renamed with
5
+ * a ` (2)`, ` (3)` suffix so a download never overwrites local data.
6
+ */
7
+ import path from 'node:path'
8
+ import { mkdir, open, rm, stat } from 'node:fs/promises'
9
+ import { errors, isRemoteGoError } from './errors.js'
10
+ import { remoteFileName, safeLocalSegment } from './remote-path.js'
11
+
12
+ async function requireDestination(destination) {
13
+ if (typeof destination !== 'string' || destination.trim() === '' || destination.includes('\0')) {
14
+ throw errors.invalidInput('destination', {
15
+ zh: '请选择本机的保存文件夹。',
16
+ en: 'Choose a destination folder on this machine.',
17
+ })
18
+ }
19
+ const base = path.resolve(destination)
20
+ try {
21
+ const info = await stat(base)
22
+ if (!info.isDirectory()) {
23
+ throw errors.invalidInput('destination', {
24
+ zh: '选择的保存位置不是文件夹。',
25
+ en: 'The selected destination is not a folder.',
26
+ })
27
+ }
28
+ } catch (error) {
29
+ if (isRemoteGoError(error)) throw error
30
+ throw errors.invalidInput('destination', {
31
+ zh: '选择的保存文件夹不存在或不可写。',
32
+ en: 'The selected destination folder does not exist or cannot be written.',
33
+ })
34
+ }
35
+ return base
36
+ }
37
+
38
+ async function createUniqueFolder(base, name) {
39
+ const safeName = safeLocalSegment(name) || 'download'
40
+ for (let index = 1; index <= 999; index += 1) {
41
+ const candidate = path.join(base, index === 1 ? safeName : `${safeName} (${index})`)
42
+ try {
43
+ await mkdir(candidate)
44
+ return candidate
45
+ } catch (error) {
46
+ if (/** @type {any} */ (error)?.code !== 'EEXIST') throw error
47
+ }
48
+ }
49
+ throw errors.invalidInput('destination', {
50
+ zh: '目标目录里已经有太多同名文件夹,请换一个目录。',
51
+ en: 'The destination already contains too many folders with this name; choose another directory.',
52
+ })
53
+ }
54
+
55
+ async function createUniqueFile(base, name) {
56
+ const safeName = safeLocalSegment(name) || 'download'
57
+ const extension = path.extname(safeName)
58
+ const stem = path.basename(safeName, extension) || 'download'
59
+ for (let index = 1; index <= 999; index += 1) {
60
+ const fileName = index === 1 ? safeName : `${stem} (${index})${extension}`
61
+ const candidate = path.join(base, fileName)
62
+ try {
63
+ const handle = await open(candidate, 'wx', 0o600)
64
+ await handle.close()
65
+ return candidate
66
+ } catch (error) {
67
+ if (/** @type {any} */ (error)?.code !== 'EEXIST') throw error
68
+ }
69
+ }
70
+ throw errors.invalidInput('destination', {
71
+ zh: '目标目录里已经有太多同名文件,请换一个目录。',
72
+ en: 'The destination already contains too many files with this name; choose another directory.',
73
+ })
74
+ }
75
+
76
+ function toDownloadError(error) {
77
+ if (isRemoteGoError(error)) return error
78
+ return errors.remoteFileUnavailable(undefined, {
79
+ technical: String(/** @type {any} */ (error?.message ?? error ?? '')).slice(0, 300),
80
+ })
81
+ }
82
+
83
+ /**
84
+ * Stream one remote file into `destination`, creating an auto-renamed local file.
85
+ * @param {object} runtime - connected host runtime.
86
+ * @param {string} remotePath - normalized absolute remote path.
87
+ * @param {unknown} destination - absolute local directory.
88
+ * @param {{ onProgress?: Function, isCancelled?: () => boolean }} [options]
89
+ * @returns {Promise<{ path: string, kind: 'file', name: string, destination: string,
90
+ * totalBytes: number, files: number }>}
91
+ */
92
+ export async function saveHostFile(runtime, remotePath, destination, options = {}) {
93
+ if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
94
+ throw errors.remoteFileUnavailable({
95
+ zh: '这台主机还没有连接,无法读取远端文件。',
96
+ en: 'This host is not connected, so the remote file cannot be read.',
97
+ })
98
+ }
99
+ if (typeof runtime.ssh.saveRemoteFile !== 'function') {
100
+ throw errors.internal('the SSH transport does not support file saves')
101
+ }
102
+ const base = await requireDestination(destination)
103
+ const name = remoteFileName(remotePath)
104
+ let localPath = null
105
+ try {
106
+ localPath = await createUniqueFile(base, name)
107
+ const result = await runtime.ssh.saveRemoteFile(remotePath, localPath, options)
108
+ return {
109
+ path: remotePath,
110
+ kind: 'file',
111
+ name: path.basename(localPath),
112
+ destination: localPath,
113
+ totalBytes: Number(result?.size ?? 0),
114
+ files: 1,
115
+ }
116
+ } catch (error) {
117
+ if (localPath) await rm(localPath, { force: true }).catch(() => {})
118
+ throw toDownloadError(error)
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Copy one remote folder into `destination` as individual local files.
124
+ * @param {object} runtime - connected host runtime.
125
+ * @param {string} remotePath - normalized absolute remote folder path.
126
+ * @param {unknown} destination - absolute local directory.
127
+ * @param {{ onInventory?: Function, onProgress?: Function, isCancelled?: () => boolean }} [options]
128
+ * @returns {Promise<{ path: string, kind: 'folder', name: string, destination: string,
129
+ * totalBytes: number, files: number, cancelled?: boolean }>}
130
+ */
131
+ export async function saveHostFolder(runtime, remotePath, destination, options = {}) {
132
+ if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
133
+ throw errors.remoteFileUnavailable({
134
+ zh: '这台主机还没有连接,无法读取远端文件夹。',
135
+ en: 'This host is not connected, so the remote folder cannot be read.',
136
+ })
137
+ }
138
+ if (typeof runtime.ssh.saveRemoteTree !== 'function') {
139
+ throw errors.internal('the SSH transport does not support folder saves')
140
+ }
141
+ const base = await requireDestination(destination)
142
+ const name = remoteFileName(remotePath)
143
+ let root = null
144
+ try {
145
+ root = await createUniqueFolder(base, name)
146
+ const result = await runtime.ssh.saveRemoteTree(remotePath, root, options)
147
+ return {
148
+ path: remotePath,
149
+ kind: 'folder',
150
+ name,
151
+ destination: result?.destination ?? root,
152
+ totalBytes: Number(result?.totalBytes ?? 0),
153
+ files: Number(result?.totalFiles ?? 0),
154
+ ...(result?.cancelled === true ? { cancelled: true } : {}),
155
+ }
156
+ } catch (error) {
157
+ if (root) await rm(root, { recursive: true, force: true }).catch(() => {})
158
+ throw toDownloadError(error)
159
+ }
160
+ }
161
+
162
+ export { requireDestination }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Local SSH material (read-only): `~/.ssh/config` and `~/.ssh/known_hosts`; never writes, never prompts.
3
+ */
4
+ import { existsSync } from 'node:fs'
5
+ import { readFile } from 'node:fs/promises'
6
+ import path from 'node:path'
7
+
8
+ export async function loadLocalSshMaterial(input) {
9
+ const sshDir = path.join(input.home, '.ssh')
10
+ const configPath = path.join(sshDir, 'config')
11
+ const knownHostsPath = path.join(sshDir, 'known_hosts')
12
+ const exists = input.exists ?? existsSync
13
+ const read = input.readFileImpl ?? readFile
14
+ let configText = ''
15
+ let knownHostsText = ''
16
+ try {
17
+ if (exists(configPath)) configText = await read(configPath, 'utf8')
18
+ } catch {
19
+ configText = ''
20
+ }
21
+ try {
22
+ if (exists(knownHostsPath)) knownHostsText = await read(knownHostsPath, 'utf8')
23
+ } catch {
24
+ knownHostsText = ''
25
+ }
26
+ return { sshDir, configText, knownHostsText, configPath, knownHostsPath }
27
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Detect the DSH version of the local installation; the remote runtime is pinned to this exact version, never to npm `latest`.
3
+ */
4
+ import { existsSync } from 'node:fs'
5
+ import { readFile } from 'node:fs/promises'
6
+ import path from 'node:path'
7
+ import { normalizeVersion, parseVersion } from './version.js'
8
+
9
+ export async function detectLocalVersion(input = {}) {
10
+ const env = input.env ?? process.env
11
+ const explicit = env.DSH_VERSION || env.DSH_RUNTIME_VERSION
12
+ if (explicit && parseVersion(normalizeVersion(explicit))) {
13
+ return { version: normalizeVersion(explicit), source: 'env' }
14
+ }
15
+
16
+ // The web client-module registry publishes the Host release identity, which
17
+ // releases share with the CLI package version.
18
+ try {
19
+ const clientModules = input.ctx?.get?.('clientModules')
20
+ const release = clientModules?.graph?.()?.release
21
+ if (release?.version && parseVersion(normalizeVersion(release.version))) {
22
+ return { version: normalizeVersion(release.version), source: 'client-modules' }
23
+ }
24
+ } catch {
25
+ /* service not present in this composition */
26
+ }
27
+
28
+ for (const candidate of candidatePackageJsons(input)) {
29
+ try {
30
+ if (!existsSync(candidate)) continue
31
+ const text = await readFile(candidate, 'utf8')
32
+ const parsed = JSON.parse(text)
33
+ if (parsed?.name === '@deepseek-ai/dsh' && parsed?.version && parseVersion(normalizeVersion(parsed.version))) {
34
+ return { version: normalizeVersion(parsed.version), source: `package.json:${candidate}` }
35
+ }
36
+ } catch {}
37
+ }
38
+ return { version: null, source: 'unknown' }
39
+ }
40
+
41
+ /**
42
+ * The local DSH build's Node engine range (`engines.node`). It is the source of
43
+ * truth for the managed Node version the plugin installs on the remote: the
44
+ * remote runs this exact DSH version, so it must satisfy this declaration.
45
+ *
46
+ * Best-effort like the version probe: an unreadable or missing package yields
47
+ * `range: null` and the caller falls back to the plugin's own floor.
48
+ */
49
+ export async function detectLocalEnginesNode(input = {}) {
50
+ for (const candidate of candidatePackageJsons(input)) {
51
+ try {
52
+ if (!existsSync(candidate)) continue
53
+ const parsed = JSON.parse(await readFile(candidate, 'utf8'))
54
+ const range = parsed?.engines?.node
55
+ if (typeof range === 'string' && range.trim() !== '') {
56
+ return { range: range.trim(), source: `package.json:${candidate}` }
57
+ }
58
+ } catch {}
59
+ }
60
+ return { range: null, source: 'unknown' }
61
+ }
62
+
63
+ export function candidatePackageJsons(input = {}) {
64
+ const out = []
65
+ const argv1 = input.argv1 ?? process.argv[1] ?? ''
66
+ const marker = `${path.sep}@deepseek-ai${path.sep}dsh${path.sep}`
67
+ const markerIndex = argv1.indexOf(marker)
68
+ if (markerIndex >= 0) {
69
+ out.push(path.join(argv1.slice(0, markerIndex + marker.length), 'package.json'))
70
+ }
71
+ const resourcesPath = input.resourcesPath ?? /** @type {any} */ (process).resourcesPath
72
+ if (typeof resourcesPath === 'string' && resourcesPath !== '') {
73
+ out.push(path.join(resourcesPath, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
74
+ out.push(
75
+ path.join(resourcesPath, 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'package.json'),
76
+ )
77
+ out.push(path.join(resourcesPath, 'app', 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
78
+ }
79
+ // Walk up from the CLI entry looking for a nested package.
80
+ let dir = argv1 ? path.dirname(argv1) : (input.cwd ?? process.cwd())
81
+ for (let i = 0; i < 8; i += 1) {
82
+ out.push(path.join(dir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
83
+ const parent = path.dirname(dir)
84
+ if (parent === dir) break
85
+ dir = parent
86
+ }
87
+ return [...new Set(out)]
88
+ }