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.
- package/README.md +126 -7
- package/client.js +5972 -0
- package/cordis.patch.yml +3 -0
- package/index.js +4 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +76 -3
- package/src/api.js +340 -0
- package/src/atomic-json.js +208 -0
- package/src/bootstrap.js +100 -0
- package/src/connect-log.js +39 -0
- package/src/connect-pipeline.js +463 -0
- package/src/connect-progress.js +135 -0
- package/src/constants.js +31 -0
- package/src/diagnostics.js +157 -0
- package/src/download-jobs.js +217 -0
- package/src/errors.js +316 -0
- package/src/host-lifecycle.js +187 -0
- package/src/host-registry.js +145 -0
- package/src/host-runtime.js +53 -0
- package/src/host-view.js +51 -0
- package/src/index.js +162 -0
- package/src/key-files.js +49 -0
- package/src/known-hosts.js +94 -0
- package/src/layout.js +35 -0
- package/src/local-download.js +162 -0
- package/src/local-ssh.js +27 -0
- package/src/local-version.js +88 -0
- package/src/node-runtime.js +521 -0
- package/src/probe.js +89 -0
- package/src/prompts.js +132 -0
- package/src/redact.js +54 -0
- package/src/remote-files.js +71 -0
- package/src/remote-path.js +73 -0
- package/src/remote-proc.js +208 -0
- package/src/remote-web.js +300 -0
- package/src/secrets.js +79 -0
- package/src/service.js +250 -0
- package/src/settings.js +135 -0
- package/src/ssh-config.js +271 -0
- package/src/ssh.js +652 -0
- package/src/store.js +143 -0
- package/src/tunnel.js +73 -0
- package/src/util.js +153 -0
- package/src/version.js +103 -0
- package/src/webapp.js +28 -0
- package/vendor/THIRD_PARTY_NOTICES.md +10 -0
- package/vendor/ssh2-entry.mjs +12 -0
- package/vendor/ssh2.bundle.cjs +25 -0
package/src/prompts.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two prompts a connection can pause on (unknown host key, foreign DSH already running) and the answers the Client sends back; each settles exactly once.
|
|
3
|
+
*/
|
|
4
|
+
import { errors, toErrorView } from './errors.js'
|
|
5
|
+
import { createDecision, nowIso } from './util.js'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Park the SSH handshake until the user answers the fingerprint prompt.
|
|
9
|
+
*/
|
|
10
|
+
export function requestHostKey(ctx, runtime, info) {
|
|
11
|
+
const policy = runtime.entry.hostKeyPolicy ?? ctx.settings().hostKeyPolicy
|
|
12
|
+
if (policy === 'strict') throw errors.hostKeyUnknown(info.sha256)
|
|
13
|
+
ctx.progress.log(
|
|
14
|
+
runtime,
|
|
15
|
+
'info',
|
|
16
|
+
`waiting for the host key to be confirmed (${info.keyType} ${info.sha256}); the SSH handshake is paused`,
|
|
17
|
+
)
|
|
18
|
+
const decision = createDecision(ctx.timers.hostKeyConfirmMs, () => {
|
|
19
|
+
ctx.progress.set(runtime, {
|
|
20
|
+
status: 'error',
|
|
21
|
+
phase: null,
|
|
22
|
+
progress: null,
|
|
23
|
+
error: toErrorView(errors.hostKeyUnknown(info.sha256)),
|
|
24
|
+
})
|
|
25
|
+
return false
|
|
26
|
+
})
|
|
27
|
+
runtime.pendingHostKey = { sha256: info.sha256, keyType: info.keyType, resolve: decision.settle }
|
|
28
|
+
runtime.fingerprint = { sha256: info.sha256, keyType: info.keyType, status: 'pending', pinned: null }
|
|
29
|
+
runtime.status = 'fingerprint-pending'
|
|
30
|
+
runtime.phase = 'ssh'
|
|
31
|
+
runtime.progress = { code: 'host-key-confirm', params: { sha256: info.sha256, keyType: info.keyType } }
|
|
32
|
+
ctx.emitState()
|
|
33
|
+
return decision.promise
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Answer the host-key prompt. Pinning is written straight through to the store so
|
|
38
|
+
* a failed first attempt still remembers the key the user accepted.
|
|
39
|
+
*/
|
|
40
|
+
export async function confirmHostKey(ctx, runtime, decision) {
|
|
41
|
+
const pending = runtime.pendingHostKey
|
|
42
|
+
if (!pending) {
|
|
43
|
+
throw errors.invalidInput('fingerprint', {
|
|
44
|
+
zh: '没有待确认的主机指纹。',
|
|
45
|
+
en: 'No host key is pending confirmation.',
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
if (decision.sha256 && pending.sha256 && decision.sha256 !== pending.sha256) {
|
|
49
|
+
throw errors.invalidInput('fingerprint', {
|
|
50
|
+
zh: '确认的指纹与待确认的不一致。',
|
|
51
|
+
en: 'The confirmed fingerprint does not match the pending one.',
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
if (decision.accept && decision.remember) {
|
|
55
|
+
await ctx.store.patchHost(runtime.id, { pinnedFingerprint: pending.sha256 })
|
|
56
|
+
runtime.entry = { ...runtime.entry, pinnedFingerprint: pending.sha256 }
|
|
57
|
+
}
|
|
58
|
+
runtime.fingerprint = {
|
|
59
|
+
sha256: pending.sha256,
|
|
60
|
+
keyType: pending.keyType,
|
|
61
|
+
status: 'pinned',
|
|
62
|
+
pinned: decision.remember ? pending.sha256 : null,
|
|
63
|
+
}
|
|
64
|
+
runtime.pendingHostKey = null
|
|
65
|
+
runtime.status = 'connecting'
|
|
66
|
+
runtime.progress = { code: 'auth-checking' }
|
|
67
|
+
pending.resolve(decision.accept === true)
|
|
68
|
+
ctx.emitState()
|
|
69
|
+
return { ok: true }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Pause the pipeline for a decision about foreign remote processes.
|
|
74
|
+
* Mirrors the host-key prompt: a status, a promise, and a bounded timeout.
|
|
75
|
+
*/
|
|
76
|
+
export function askConflict(ctx, runtime, processes) {
|
|
77
|
+
runtime.status = 'conflict-pending'
|
|
78
|
+
runtime.progress = { code: 'remote-dsh-running', params: { count: processes.length } }
|
|
79
|
+
runtime.conflict = {
|
|
80
|
+
detectedAt: nowIso(),
|
|
81
|
+
processes: processes.slice(0, 20).map((process) => ({
|
|
82
|
+
pid: process.pid,
|
|
83
|
+
command: String(process.command ?? '').slice(0, 400),
|
|
84
|
+
})),
|
|
85
|
+
}
|
|
86
|
+
ctx.emitState()
|
|
87
|
+
const decision = createDecision(
|
|
88
|
+
ctx.timers.conflictConfirmMs,
|
|
89
|
+
() => ({ action: 'cancel', timedOut: true }),
|
|
90
|
+
() => {
|
|
91
|
+
if (runtime.pendingConflict?.resolve === decision.settle) runtime.pendingConflict = null
|
|
92
|
+
runtime.conflict = null
|
|
93
|
+
if (runtime.desired === 'connected') {
|
|
94
|
+
runtime.status = 'connecting'
|
|
95
|
+
runtime.progress = { code: 'probing' }
|
|
96
|
+
}
|
|
97
|
+
ctx.emitState()
|
|
98
|
+
},
|
|
99
|
+
)
|
|
100
|
+
runtime.pendingConflict = { processes, resolve: decision.settle }
|
|
101
|
+
return decision.promise
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function confirmConflict(runtime, decision) {
|
|
105
|
+
const pending = runtime.pendingConflict
|
|
106
|
+
if (!pending) {
|
|
107
|
+
throw errors.invalidInput('conflict', {
|
|
108
|
+
zh: '没有待确认的远端 DSH 冲突。',
|
|
109
|
+
en: 'No remote DSH conflict is pending confirmation.',
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
const action = decision?.action
|
|
113
|
+
if (action !== 'stop' && action !== 'alongside' && action !== 'cancel') {
|
|
114
|
+
throw errors.invalidInput('conflict', {
|
|
115
|
+
zh: '请选择停止手工实例、与它并存,或取消连接。',
|
|
116
|
+
en: 'Choose whether to stop the manual instance, keep it alongside, or cancel.',
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
pending.resolve({ action })
|
|
120
|
+
return { ok: true }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Abandon a pending conflict prompt (teardown). Resolving it with `cancel` makes
|
|
125
|
+
* the stalled `askConflict` call return instead of holding the pipeline open.
|
|
126
|
+
*/
|
|
127
|
+
export function cancelConflict(runtime) {
|
|
128
|
+
const pending = runtime.pendingConflict
|
|
129
|
+
runtime.pendingConflict = null
|
|
130
|
+
runtime.conflict = null
|
|
131
|
+
if (pending) pending.resolve({ action: 'cancel' })
|
|
132
|
+
}
|
package/src/redact.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diagnostics redaction: tokens, passwords and private keys never leave the machine in a diagnostic package.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
const SECRET_QUERY_KEYS = ['token', 'access_token', 'api_key', 'apikey', 'key', 'secret', 'password', 'passwd', 'auth']
|
|
6
|
+
const SECRET_HEADER_RE = /\b(authorization|cookie|set-cookie|x-api-key|proxy-authorization)\s*:\s*[^\r\n]+/gi
|
|
7
|
+
const BEARER_RE = /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/g
|
|
8
|
+
const TOKEN_QUERY_RE = new RegExp(`([?&](?:${SECRET_QUERY_KEYS.join('|')})=)[^&#\\s"']+`, 'gi')
|
|
9
|
+
const PRIVATE_KEY_RE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g
|
|
10
|
+
const PASSWORD_FLAG_RE = /(--password[=\s]+|-p\s+|password[=:]\s*)(\S+)/gi
|
|
11
|
+
const DSH_TOKEN_LINE_RE = /(dsh web:\s*\S*?\?token=)[A-Za-z0-9._~+/=-]+/g
|
|
12
|
+
const LONG_HEX_RE = /\b[a-f0-9]{40,}\b/gi
|
|
13
|
+
const LONG_BASE64_RE = /\b[A-Za-z0-9+/]{48,}={0,2}\b/g
|
|
14
|
+
|
|
15
|
+
export function redactText(text, options = {}) {
|
|
16
|
+
if (typeof text !== 'string' || text === '') return text
|
|
17
|
+
let out = text
|
|
18
|
+
out = out.replace(PRIVATE_KEY_RE, '-----BEGIN PRIVATE KEY-----<redacted>-----END PRIVATE KEY-----')
|
|
19
|
+
out = out.replace(SECRET_HEADER_RE, (match) => `${match.split(':')[0]}: <redacted>`)
|
|
20
|
+
out = out.replace(BEARER_RE, (_match, scheme) => `${scheme} <redacted>`)
|
|
21
|
+
out = out.replace(TOKEN_QUERY_RE, '$1<redacted>')
|
|
22
|
+
out = out.replace(DSH_TOKEN_LINE_RE, '$1<redacted>')
|
|
23
|
+
out = out.replace(PASSWORD_FLAG_RE, '$1<redacted>')
|
|
24
|
+
if (!options.keepPaths) {
|
|
25
|
+
// Home directories of the remote account are not secrets, but avoid leaking
|
|
26
|
+
// arbitrary local user names into exported diagnostics.
|
|
27
|
+
out = out.replace(/(\/home\/)[^/\s]+/g, '$1<user>')
|
|
28
|
+
out = out.replace(/\b(C:\\Users\\)[^\\\s]+/gi, '$1<user>')
|
|
29
|
+
}
|
|
30
|
+
return out
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function redactValue(key, value) {
|
|
34
|
+
const lowered = String(key).toLowerCase()
|
|
35
|
+
if (typeof value === 'string') {
|
|
36
|
+
if (/(password|token|secret|passphrase|authorization|apikey|api_key|privatekey|cookie)/.test(lowered))
|
|
37
|
+
return '<redacted>'
|
|
38
|
+
return redactText(value)
|
|
39
|
+
}
|
|
40
|
+
if (Array.isArray(value)) return value.map((item) => redactValue(key, item))
|
|
41
|
+
if (value && typeof value === 'object') return redactObject(value)
|
|
42
|
+
return value
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Deep-redact a JSON-compatible value.
|
|
47
|
+
*/
|
|
48
|
+
export function redactObject(value) {
|
|
49
|
+
if (Array.isArray(value)) return /** @type {T} */ (value.map((item) => redactValue('', item)))
|
|
50
|
+
if (!value || typeof value !== 'object') return value
|
|
51
|
+
const out = {}
|
|
52
|
+
for (const [key, item] of Object.entries(value)) out[key] = redactValue(key, item)
|
|
53
|
+
return /** @type {T} */ (out)
|
|
54
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote download entry: validate an absolute Linux path, inspect it, then hand it
|
|
3
|
+
* to the local writer. Both files and folders stream directly to disk; no bytes are
|
|
4
|
+
* buffered in the Host and no ZIP is created.
|
|
5
|
+
*/
|
|
6
|
+
import { errors, isRemoteGoError } from './errors.js'
|
|
7
|
+
import { requireDestination, saveHostFile, saveHostFolder } from './local-download.js'
|
|
8
|
+
import { normalizeRemoteFilePath } from './remote-path.js'
|
|
9
|
+
|
|
10
|
+
export { normalizeRemoteFilePath, remoteFileName } from './remote-path.js'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Save one file or one folder for a download job.
|
|
14
|
+
* @param {object} runtime - the connected host runtime.
|
|
15
|
+
* @param {unknown} rawPath - the requested absolute remote path.
|
|
16
|
+
* @param {{ destination?: string, onProgress?: Function, onInventory?: Function,
|
|
17
|
+
* isCancelled?: () => boolean }} [options]
|
|
18
|
+
* @returns {Promise<{ path: string, kind: 'file'|'folder', name: string,
|
|
19
|
+
* destination: string, totalBytes: number, files: number, cancelled?: boolean }>}
|
|
20
|
+
*/
|
|
21
|
+
export async function readHostDownload(runtime, rawPath, options = {}) {
|
|
22
|
+
if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
|
|
23
|
+
throw errors.remoteFileUnavailable({
|
|
24
|
+
zh: '这台主机还没有连接,无法读取远端内容。',
|
|
25
|
+
en: 'This host is not connected, so the remote content cannot be read.',
|
|
26
|
+
})
|
|
27
|
+
}
|
|
28
|
+
const remotePath = normalizeRemoteFilePath(rawPath)
|
|
29
|
+
const ssh = runtime.ssh
|
|
30
|
+
if (typeof ssh.inspectRemotePath !== 'function') {
|
|
31
|
+
throw errors.internal('the SSH transport does not support path inspection')
|
|
32
|
+
}
|
|
33
|
+
let destination
|
|
34
|
+
try {
|
|
35
|
+
const info = await ssh.inspectRemotePath(remotePath)
|
|
36
|
+
destination = await requireDestination(options.destination)
|
|
37
|
+
if (info.isFile) return await saveHostFile(runtime, remotePath, destination, options)
|
|
38
|
+
if (info.isDirectory) return await saveHostFolder(runtime, remotePath, destination, options)
|
|
39
|
+
throw errors.remoteFileUnavailable({
|
|
40
|
+
zh: '这个远端路径既不是普通文件,也不是文件夹。',
|
|
41
|
+
en: 'This remote path is neither a regular file nor a folder.',
|
|
42
|
+
})
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (isRemoteGoError(error)) throw error
|
|
45
|
+
throw toRemoteFileError(error)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Classify an SFTP failure without leaking transport internals to the client.
|
|
51
|
+
* @param {unknown} error - the transport error.
|
|
52
|
+
* @returns {import('./errors.js').RemoteGoError} a client-safe error.
|
|
53
|
+
*/
|
|
54
|
+
export function toRemoteFileError(error) {
|
|
55
|
+
if (isRemoteGoError(error)) return error
|
|
56
|
+
const code = Number(/** @type {any} */ (error)?.code)
|
|
57
|
+
const message = String(/** @type {any} */ (error?.message ?? error ?? ''))
|
|
58
|
+
if (code === 2 || /no such file|not found/i.test(message)) {
|
|
59
|
+
return errors.remoteFileUnavailable({
|
|
60
|
+
zh: '远端文件不存在或已经被移动。',
|
|
61
|
+
en: 'The remote file no longer exists or was moved.',
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
if (code === 3 || /permission denied|access denied/i.test(message)) {
|
|
65
|
+
return errors.remoteFileUnavailable({
|
|
66
|
+
zh: '当前 SSH 用户没有读取这个远端路径的权限。',
|
|
67
|
+
en: 'The SSH user is not allowed to read this remote path.',
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
return errors.remoteFileUnavailable(undefined, { technical: message.slice(0, 300) })
|
|
71
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/** Validation and naming for absolute remote POSIX paths. */
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { errors } from './errors.js'
|
|
4
|
+
|
|
5
|
+
/** Longest accepted path, matching the remote contract of ordinary POSIX tools. */
|
|
6
|
+
const MAX_PATH_CHARS = 4096
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Validate and normalize a remote file path.
|
|
10
|
+
* @param {unknown} value - path from the client request.
|
|
11
|
+
* @returns {string} a normalized absolute POSIX path.
|
|
12
|
+
*/
|
|
13
|
+
export function normalizeRemoteFilePath(value) {
|
|
14
|
+
if (typeof value !== 'string') {
|
|
15
|
+
throw errors.invalidInput('path', {
|
|
16
|
+
zh: '远端文件路径必须是字符串。',
|
|
17
|
+
en: 'The remote file path must be a string.',
|
|
18
|
+
})
|
|
19
|
+
}
|
|
20
|
+
const text = value
|
|
21
|
+
if (text === '') {
|
|
22
|
+
throw errors.invalidInput('path', {
|
|
23
|
+
zh: '远端文件路径不能为空。',
|
|
24
|
+
en: 'The remote file path must not be empty.',
|
|
25
|
+
})
|
|
26
|
+
}
|
|
27
|
+
if (text.length > MAX_PATH_CHARS) {
|
|
28
|
+
throw errors.invalidInput('path', {
|
|
29
|
+
zh: '远端文件路径过长。',
|
|
30
|
+
en: 'The remote file path is too long.',
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
if (text.includes('\0') || text.includes('\r') || text.includes('\n')) {
|
|
34
|
+
throw errors.invalidInput('path', {
|
|
35
|
+
zh: '远端文件路径包含不可用的控制字符。',
|
|
36
|
+
en: 'The remote file path contains unsupported control characters.',
|
|
37
|
+
})
|
|
38
|
+
}
|
|
39
|
+
if (!text.startsWith('/')) {
|
|
40
|
+
throw errors.invalidInput('path', {
|
|
41
|
+
zh: '远端文件路径必须是绝对路径。',
|
|
42
|
+
en: 'The remote file path must be absolute.',
|
|
43
|
+
})
|
|
44
|
+
}
|
|
45
|
+
const normalized = path.posix.normalize(text)
|
|
46
|
+
if (!normalized.startsWith('/')) {
|
|
47
|
+
throw errors.invalidInput('path', {
|
|
48
|
+
zh: '远端文件路径必须是绝对路径。',
|
|
49
|
+
en: 'The remote file path must be absolute.',
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
return normalized
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The suggested download name for a remote path.
|
|
57
|
+
* @param {string} remotePath - a normalized absolute path.
|
|
58
|
+
* @returns {string} the last path segment, or a safe generic name.
|
|
59
|
+
*/
|
|
60
|
+
export function remoteFileName(remotePath) {
|
|
61
|
+
const name = path.posix.basename(remotePath)
|
|
62
|
+
return name === '' || name === '/' || name === '.' || name === '..' ? 'download' : name
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** One local filename segment; Windows-safe so the same code works on every Desktop. */
|
|
66
|
+
export function safeLocalSegment(value) {
|
|
67
|
+
let text = String(value ?? '')
|
|
68
|
+
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_')
|
|
69
|
+
.replace(/[. ]+$/, '')
|
|
70
|
+
if (text === '' || text === '.' || text === '..') text = '_'
|
|
71
|
+
if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(text)) text = '_' + text
|
|
72
|
+
return text
|
|
73
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote process and reachability primitives: find, stop and probe DSH processes on the remote, plus the one HTTP round-trip that proves the remote UI answers.
|
|
3
|
+
*/
|
|
4
|
+
import http from 'node:http'
|
|
5
|
+
import { TUNNEL_PROBE_TIMEOUT_MS } from './constants.js'
|
|
6
|
+
import { isPid, messageOf } from './util.js'
|
|
7
|
+
|
|
8
|
+
/** A listener answering 200, 302 or 401 is up: 401 without the launch cookie still proves it serves. */
|
|
9
|
+
export function isUiUp(status) {
|
|
10
|
+
return status === 200 || status === 302 || status === 401
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function buildForeignDshCommand(ignorePids = []) {
|
|
14
|
+
const ignore = (Array.isArray(ignorePids) ? ignorePids : [])
|
|
15
|
+
.map((pid) => Number(pid))
|
|
16
|
+
.filter((pid) => isPid(pid))
|
|
17
|
+
.join(' ')
|
|
18
|
+
return `set -u
|
|
19
|
+
IGNORE=" ${ignore} "
|
|
20
|
+
PS_OUT=$(ps -eww -o pid=,comm=,args= 2>/dev/null || ps -eo pid=,comm=,args= 2>/dev/null || true)
|
|
21
|
+
printf '%s\\n' "$PS_OUT" | while IFS= read -r LINE; do
|
|
22
|
+
[ -z "$LINE" ] && continue
|
|
23
|
+
set -- $LINE
|
|
24
|
+
PID=$1
|
|
25
|
+
COMM=$2
|
|
26
|
+
shift 2
|
|
27
|
+
ARGS="$*"
|
|
28
|
+
[ -z "$PID" ] && continue
|
|
29
|
+
case "$IGNORE" in *" $PID "*) continue ;; esac
|
|
30
|
+
case "$COMM" in node|dsh|npm|npx) ;; *) continue ;; esac
|
|
31
|
+
case "$ARGS" in
|
|
32
|
+
*"@deepseek-ai/dsh"*|*"/bin/dsh "*|*" dsh "*) ;;
|
|
33
|
+
*) continue ;;
|
|
34
|
+
esac
|
|
35
|
+
case "$ARGS" in
|
|
36
|
+
*"ps -eww"*|*"PS_OUT"*|*"IGNORE"*) continue ;;
|
|
37
|
+
esac
|
|
38
|
+
ENV_HOME=$(tr '\\0' '\\n' < "/proc/$PID/environ" 2>/dev/null | sed -n 's/^DSH_HOME=//p' | tail -n 1)
|
|
39
|
+
if [ -n "\${ENV_HOME:-}" ] && [ "$ENV_HOME" != "$HOME/.dsh" ]; then continue; fi
|
|
40
|
+
printf '%s\\t%s\\n' "$PID" "$ARGS"
|
|
41
|
+
done`
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function parseForeignDshOutput(stdout) {
|
|
45
|
+
const processes = []
|
|
46
|
+
for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
|
|
47
|
+
const tab = rawLine.indexOf('\t')
|
|
48
|
+
if (tab <= 0) continue
|
|
49
|
+
const pid = Number(rawLine.slice(0, tab).trim())
|
|
50
|
+
const command = rawLine.slice(tab + 1).trim()
|
|
51
|
+
if (!isPid(pid) || command === '') continue
|
|
52
|
+
processes.push({ pid, command })
|
|
53
|
+
}
|
|
54
|
+
return processes
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Find DSH processes on the remote that this plugin did not start.
|
|
59
|
+
*
|
|
60
|
+
* Never throws: a failed scan is reported as `{ ok: false }`, and the caller
|
|
61
|
+
* proceeds without a conflict prompt (a broken scan must not block connecting).
|
|
62
|
+
*/
|
|
63
|
+
export async function findForeignDshProcesses(ssh, options = {}) {
|
|
64
|
+
try {
|
|
65
|
+
const result = await ssh.exec(buildForeignDshCommand(options.ignorePids ?? []), {
|
|
66
|
+
timeoutMs: options.timeoutMs ?? 20_000,
|
|
67
|
+
maxBytes: 200_000,
|
|
68
|
+
})
|
|
69
|
+
if (result.code !== 0) {
|
|
70
|
+
return { ok: false, processes: [], reason: 'exec-failed', technical: String(result.stderr ?? '').slice(0, 500) }
|
|
71
|
+
}
|
|
72
|
+
return { ok: true, processes: parseForeignDshOutput(result.stdout) }
|
|
73
|
+
} catch (error) {
|
|
74
|
+
// swallow-ok: a scan failure is surfaced as ok:false and the caller proceeds without a prompt
|
|
75
|
+
return {
|
|
76
|
+
ok: false,
|
|
77
|
+
processes: [],
|
|
78
|
+
reason: 'exec-failed',
|
|
79
|
+
technical: messageOf(error),
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export async function stopForeignDshProcesses(ssh, processes, options = {}) {
|
|
85
|
+
const pids = [
|
|
86
|
+
...new Set(
|
|
87
|
+
(Array.isArray(processes) ? processes : []).map((process) => Number(process?.pid)).filter((pid) => isPid(pid)),
|
|
88
|
+
),
|
|
89
|
+
]
|
|
90
|
+
if (pids.length === 0) return { ok: true, alive: [], output: '' }
|
|
91
|
+
const script = `set -u
|
|
92
|
+
PIDS="${pids.join(' ')}"
|
|
93
|
+
for PID in $PIDS; do kill -TERM "$PID" 2>/dev/null || true; done
|
|
94
|
+
i=0
|
|
95
|
+
while [ "$i" -lt 20 ]; do
|
|
96
|
+
ALIVE=0
|
|
97
|
+
for PID in $PIDS; do
|
|
98
|
+
if kill -0 "$PID" 2>/dev/null; then ALIVE=1; fi
|
|
99
|
+
done
|
|
100
|
+
if [ "$ALIVE" -eq 0 ]; then break; fi
|
|
101
|
+
i=$((i+1))
|
|
102
|
+
sleep 0.5
|
|
103
|
+
done
|
|
104
|
+
for PID in $PIDS; do
|
|
105
|
+
if kill -0 "$PID" 2>/dev/null; then kill -KILL "$PID" 2>/dev/null || true; fi
|
|
106
|
+
done
|
|
107
|
+
sleep 0.2
|
|
108
|
+
for PID in $PIDS; do
|
|
109
|
+
if kill -0 "$PID" 2>/dev/null; then echo "ALIVE:$PID"; fi
|
|
110
|
+
done
|
|
111
|
+
echo "STOPPED"
|
|
112
|
+
`
|
|
113
|
+
try {
|
|
114
|
+
const result = await ssh.exec(script, { timeoutMs: options.timeoutMs ?? 30_000 })
|
|
115
|
+
const output = String(result.stdout ?? '')
|
|
116
|
+
const alive = [...output.matchAll(/ALIVE:(\d+)/g)].map((match) => Number(match[1]))
|
|
117
|
+
return { ok: result.code === 0 && alive.length === 0, alive, output }
|
|
118
|
+
} catch (error) {
|
|
119
|
+
// swallow-ok: a stop failure is returned to the caller with the original message
|
|
120
|
+
return { ok: false, alive: pids, output: messageOf(error) }
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export async function remoteHttpStatus(ssh, port) {
|
|
125
|
+
if (!isPid(port)) return null
|
|
126
|
+
const script = `URL="http://127.0.0.1:${port}/"
|
|
127
|
+
if command -v curl >/dev/null 2>&1; then
|
|
128
|
+
curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$URL" 2>/dev/null || true
|
|
129
|
+
elif command -v wget >/dev/null 2>&1; then
|
|
130
|
+
wget -S -O /dev/null --max-time 5 "$URL" 2>&1 | sed -n 's/.*HTTP\\/[0-9.]* \\([0-9][0-9][0-9]\\).*/\\1/p' | head -n 1
|
|
131
|
+
fi
|
|
132
|
+
`
|
|
133
|
+
try {
|
|
134
|
+
const result = await ssh.exec(script, { timeoutMs: 15_000 })
|
|
135
|
+
const code = Number(String(result.stdout ?? '').trim())
|
|
136
|
+
return Number.isInteger(code) && code > 0 ? code : null
|
|
137
|
+
} catch {
|
|
138
|
+
return null
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function waitForRemoteUi(ssh, port, options = {}) {
|
|
143
|
+
const attempts = options.attempts ?? 20
|
|
144
|
+
const intervalMs = options.intervalMs ?? 500
|
|
145
|
+
let last = null
|
|
146
|
+
for (let i = 0; i < attempts; i += 1) {
|
|
147
|
+
last = await remoteHttpStatus(ssh, port)
|
|
148
|
+
if (isUiUp(last)) return { ok: true, status: last }
|
|
149
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs))
|
|
150
|
+
}
|
|
151
|
+
return { ok: false, status: last }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function exchangeTokenOverTunnel(localPort, token, options = {}) {
|
|
155
|
+
const timeoutMs = options.timeoutMs ?? TUNNEL_PROBE_TIMEOUT_MS
|
|
156
|
+
const basePath = options.path ?? '/'
|
|
157
|
+
const tokenPath = `/?token=${encodeURIComponent(token)}`
|
|
158
|
+
const first = await httpRequest({
|
|
159
|
+
port: localPort,
|
|
160
|
+
path: basePath === '/' ? tokenPath : `${basePath}?token=${encodeURIComponent(token)}`,
|
|
161
|
+
timeoutMs,
|
|
162
|
+
})
|
|
163
|
+
const setCookies = first.headers['set-cookie'] ?? []
|
|
164
|
+
const cookieHeader = setCookies.map((cookie) => String(cookie).split(';')[0]).join('; ')
|
|
165
|
+
const location = first.headers.location ?? null
|
|
166
|
+
const second = await httpRequest({
|
|
167
|
+
port: localPort,
|
|
168
|
+
path: location && location.startsWith('/') ? location : '/',
|
|
169
|
+
timeoutMs,
|
|
170
|
+
headers: cookieHeader ? { cookie: cookieHeader } : {},
|
|
171
|
+
})
|
|
172
|
+
const titleMatch = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(second.body)
|
|
173
|
+
return {
|
|
174
|
+
ok: second.status === 200 && second.body.length > 0,
|
|
175
|
+
firstStatus: first.status,
|
|
176
|
+
status: second.status,
|
|
177
|
+
title: titleMatch ? titleMatch[1].trim().slice(0, 200) : null,
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function httpRequest(options) {
|
|
182
|
+
return new Promise((resolve, reject) => {
|
|
183
|
+
const request = http.request(
|
|
184
|
+
{
|
|
185
|
+
host: '127.0.0.1',
|
|
186
|
+
port: options.port,
|
|
187
|
+
path: options.path,
|
|
188
|
+
method: 'GET',
|
|
189
|
+
headers: { 'user-agent': 'dsh-remote-go', ...options.headers },
|
|
190
|
+
timeout: options.timeoutMs,
|
|
191
|
+
},
|
|
192
|
+
(response) => {
|
|
193
|
+
const chunks = []
|
|
194
|
+
response.on('data', (chunk) => chunks.push(Buffer.from(chunk)))
|
|
195
|
+
response.on('end', () => {
|
|
196
|
+
resolve({
|
|
197
|
+
status: response.statusCode ?? 0,
|
|
198
|
+
headers: response.headers,
|
|
199
|
+
body: Buffer.concat(chunks).toString('utf8'),
|
|
200
|
+
})
|
|
201
|
+
})
|
|
202
|
+
},
|
|
203
|
+
)
|
|
204
|
+
request.on('timeout', () => request.destroy(new Error('local tunnel probe timed out')))
|
|
205
|
+
request.on('error', reject)
|
|
206
|
+
request.end()
|
|
207
|
+
})
|
|
208
|
+
}
|