dsh-remote-go 0.2.0 → 0.3.1
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 +11 -3
- package/{client.js → dist/client.js} +7144 -8367
- package/dist/index.js +4 -0
- package/dist/src/admission.js +21 -0
- package/dist/src/api.js +380 -0
- package/dist/src/atomic-json.js +201 -0
- package/dist/src/bootstrap.js +96 -0
- package/dist/src/connect/attach.js +21 -0
- package/dist/src/connect/bootstrap.js +8 -0
- package/dist/src/connect/failures.js +29 -0
- package/dist/src/connect/guards.js +36 -0
- package/dist/src/connect/launch.js +70 -0
- package/dist/src/connect/links.js +54 -0
- package/dist/src/connect/ownership.js +139 -0
- package/dist/src/connect/pipeline.js +376 -0
- package/dist/src/connect/reattach.js +191 -0
- package/dist/src/connect/registry.js +10 -0
- package/dist/src/connect/repair.js +97 -0
- package/dist/src/connect/restart.js +255 -0
- package/dist/src/connect/stop.js +164 -0
- package/dist/src/connect/transport.js +101 -0
- package/dist/src/connect/verify.js +30 -0
- package/dist/src/connect/watchdog.js +44 -0
- package/dist/src/connect-log.js +137 -0
- package/dist/src/connect-progress.js +110 -0
- package/dist/src/constants.js +29 -0
- package/dist/src/context.js +96 -0
- package/dist/src/diagnostics.js +133 -0
- package/dist/src/download-jobs.js +221 -0
- package/dist/src/errors.js +228 -0
- package/dist/src/events.js +326 -0
- package/dist/src/host-lifecycle.js +368 -0
- package/dist/src/host-registry.js +181 -0
- package/dist/src/host-runtime.js +77 -0
- package/dist/src/host-view.js +52 -0
- package/dist/src/index.js +196 -0
- package/dist/src/kernel-adapter.js +388 -0
- package/dist/src/key-files.js +39 -0
- package/dist/src/known-hosts.js +104 -0
- package/dist/src/layout.js +26 -0
- package/dist/src/local-download.js +311 -0
- package/dist/src/local-ssh.js +23 -0
- package/dist/src/local-version.js +87 -0
- package/dist/src/node/download.js +157 -0
- package/dist/src/node-runtime.js +327 -0
- package/dist/src/probe.js +95 -0
- package/dist/src/prompts.js +198 -0
- package/dist/src/proxy/cookies.js +102 -0
- package/dist/src/proxy/headers.js +167 -0
- package/dist/src/proxy/http.js +134 -0
- package/dist/src/proxy/index.js +121 -0
- package/dist/src/proxy/limits.js +6 -0
- package/dist/src/proxy/routes.js +32 -0
- package/dist/src/proxy/upgrade.js +160 -0
- package/dist/src/redact.js +85 -0
- package/dist/src/remote-files.js +60 -0
- package/dist/src/remote-path.js +82 -0
- package/dist/src/remote-proc.js +271 -0
- package/dist/src/remote-web/registry.js +107 -0
- package/dist/src/remote-web/resolve.js +229 -0
- package/dist/src/remote-web/start.js +190 -0
- package/dist/src/remote-web/stop.js +74 -0
- package/dist/src/request-trust.js +70 -0
- package/dist/src/runtime/dispatch.js +200 -0
- package/dist/src/runtime/effects.js +81 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +70 -0
- package/dist/src/runtime/rules.js +480 -0
- package/dist/src/secrets.js +119 -0
- package/dist/src/service.js +300 -0
- package/dist/src/settings.js +143 -0
- package/dist/src/ssh-config.js +257 -0
- package/dist/src/ssh-failures.js +71 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +258 -0
- package/dist/src/ssh.js +395 -0
- package/dist/src/store.js +174 -0
- package/dist/src/tool-shared.js +146 -0
- package/dist/src/tools-exec-policy.js +121 -0
- package/dist/src/tools-exec.js +307 -0
- package/dist/src/tools-report.js +357 -0
- package/dist/src/tools.js +337 -0
- package/dist/src/tunnel.js +111 -0
- package/dist/src/util.js +112 -0
- package/dist/src/version.js +108 -0
- package/dist/src/watchdog-bus.js +21 -0
- package/dist/src/watchdog.js +116 -0
- package/index.js +5 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +37 -19
- package/src/admission.js +0 -43
- package/src/api.js +0 -536
- package/src/atomic-json.js +0 -225
- package/src/bootstrap.js +0 -113
- package/src/connect-log.js +0 -176
- package/src/connect-pipeline.js +0 -1900
- package/src/connect-progress.js +0 -155
- package/src/constants.js +0 -93
- package/src/diagnostics.js +0 -160
- package/src/download-jobs.js +0 -234
- package/src/errors.js +0 -412
- package/src/host-lifecycle.js +0 -604
- package/src/host-registry.js +0 -217
- package/src/host-runtime.js +0 -127
- package/src/host-view.js +0 -75
- package/src/index.js +0 -206
- package/src/key-files.js +0 -54
- package/src/known-hosts.js +0 -133
- package/src/layout.js +0 -53
- package/src/local-download.js +0 -381
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -101
- package/src/prompts.js +0 -229
- package/src/redact.js +0 -68
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -137
- package/src/remote-proc.js +0 -343
- package/src/remote-proxy.js +0 -815
- package/src/remote-web.js +0 -751
- package/src/request-trust.js +0 -89
- package/src/secrets.js +0 -109
- package/src/service.js +0 -459
- package/src/settings.js +0 -163
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -731
- package/src/store.js +0 -193
- package/src/tools.js +0 -386
- package/src/tunnel.js +0 -132
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -43
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
package/src/request-trust.js
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The browser-trust fence shared by the local HTTP API and the same-origin remote proxy.
|
|
3
|
-
*
|
|
4
|
-
* Both surfaces answer on the local DSH origin, so both must give the same answer to one question:
|
|
5
|
-
* did this request arrive from the origin it names? Two confused-deputy paths reach a loopback web
|
|
6
|
-
* server — DNS rebinding and a cross-site page — and a browser labels neither reliably: a rebound
|
|
7
|
-
* page sends its own hostname as `Host` while the socket lands on this server, and a plain
|
|
8
|
-
* navigation or image read carries no `Origin` and no Fetch-Metadata. `Host` is the one header
|
|
9
|
-
* rebinding cannot forge, so it is checked for every request; when a browser does attach `Origin`
|
|
10
|
-
* or `sec-fetch-site`, they must agree too.
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '[::1]', '::1'])
|
|
14
|
-
|
|
15
|
-
/** The port a URL actually names, counting an omitted default port. */
|
|
16
|
-
function effectivePort(url) {
|
|
17
|
-
if (url.port !== '') return url.port
|
|
18
|
-
return url.protocol === 'https:' ? '443' : '80'
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Hostname/port match for a `Host` header (which carries no scheme). The suffix is the local
|
|
23
|
-
* listener's origin; loopback spellings are interchangeable because a browser may dial either one.
|
|
24
|
-
* @param {string | undefined} value - verbatim `Host` header.
|
|
25
|
-
* @param {URL} origin - this listener's own origin.
|
|
26
|
-
* @returns {boolean}
|
|
27
|
-
*/
|
|
28
|
-
export function sameServerHost(value, origin) {
|
|
29
|
-
if (typeof value !== 'string' || value === '') return false
|
|
30
|
-
let candidate
|
|
31
|
-
try {
|
|
32
|
-
candidate = new URL(`${origin.protocol}//${value}`)
|
|
33
|
-
} catch {
|
|
34
|
-
return false
|
|
35
|
-
}
|
|
36
|
-
// WHATWG parsing rewrites anything that is not a bare authority: `user@host` drops its userinfo,
|
|
37
|
-
// a backslash becomes a path separator, `#`/`?` start the fragment/query, and a trailing dot or a
|
|
38
|
-
// zero-padded port is normalized away. A browser fills `Host` from the serialized URL, so a value
|
|
39
|
-
// the parser had to rewrite is not an authority this server answers to; comparing the rewritten
|
|
40
|
-
// hostname would let `attacker.example@127.0.0.1:port` pass as loopback.
|
|
41
|
-
if (candidate.host !== value.toLowerCase()) return false
|
|
42
|
-
if (effectivePort(candidate) !== effectivePort(origin)) return false
|
|
43
|
-
if (candidate.hostname === origin.hostname) return true
|
|
44
|
-
return LOOPBACK_HOSTNAMES.has(origin.hostname) && LOOPBACK_HOSTNAMES.has(candidate.hostname)
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Full same-origin match for an `Origin` header (scheme included).
|
|
49
|
-
*
|
|
50
|
-
* The authority is compared verbatim (case-insensitively) as well as through `sameServerHost`.
|
|
51
|
-
* A browser fills `Origin` from the serialized URL, so anything the URL parser had to rewrite —
|
|
52
|
-
* `user@host`, a trailing dot, a zero-padded port — cannot have come from one, and letting the
|
|
53
|
-
* rewritten form through would accept `http://attacker.example@127.0.0.1:port` as loopback.
|
|
54
|
-
* @param {string | undefined} value - verbatim `Origin` header.
|
|
55
|
-
* @param {URL} origin - this listener's own origin.
|
|
56
|
-
* @returns {boolean}
|
|
57
|
-
*/
|
|
58
|
-
export function sameServerOrigin(value, origin) {
|
|
59
|
-
if (typeof value !== 'string' || value === '') return false
|
|
60
|
-
// One trailing slash is tolerated (`Origin: http://host/` is not what a browser sends, but a
|
|
61
|
-
// hand-written caller may); no regex on this string, it is attacker-controlled.
|
|
62
|
-
const text = value.endsWith('/') ? value.slice(0, -1) : value
|
|
63
|
-
let candidate
|
|
64
|
-
try {
|
|
65
|
-
candidate = new URL(text)
|
|
66
|
-
} catch {
|
|
67
|
-
return false
|
|
68
|
-
}
|
|
69
|
-
// Drop the scheme without a regex: `scheme://rest` is the only shape left after URL parsing.
|
|
70
|
-
const schemeEnd = text.indexOf('://')
|
|
71
|
-
const authority = schemeEnd === -1 ? '' : text.slice(schemeEnd + 3)
|
|
72
|
-
if (authority.toLowerCase() !== candidate.host) return false
|
|
73
|
-
return candidate.protocol === origin.protocol && sameServerHost(candidate.host, origin)
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* The fence applied to a browser navigation and its subresources: the request must name this
|
|
78
|
-
* server, and any browser-announced relationship must be same-origin.
|
|
79
|
-
* @param {{ headers: Record<string, string | string[] | undefined> }} req
|
|
80
|
-
* @param {URL} origin - this listener's own origin.
|
|
81
|
-
* @returns {boolean}
|
|
82
|
-
*/
|
|
83
|
-
export function trustedRequest(req, origin) {
|
|
84
|
-
if (!sameServerHost(req.headers.host, origin)) return false
|
|
85
|
-
const originHeader = req.headers.origin
|
|
86
|
-
if (typeof originHeader === 'string' && originHeader !== '' && !sameServerOrigin(originHeader, origin)) return false
|
|
87
|
-
if (req.headers['sec-fetch-site'] === 'cross-site') return false
|
|
88
|
-
return true
|
|
89
|
-
}
|
package/src/secrets.js
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Per-host SSH password storage in DSH's own credential store (`ctx.credentials`), never in `hosts.json`; with no credential service nothing is persisted.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { HOST_ID_RE } from './settings.js'
|
|
6
|
-
|
|
7
|
-
const RECORD_SCOPE = 'dsh-remote-go'
|
|
8
|
-
const RECORD_ID_PREFIX = 'ssh-password-'
|
|
9
|
-
const PAYLOAD_VERSION = 1
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* DSH addresses a stored record as `<scope>/<id>`, and both segments must match
|
|
13
|
-
* `/^[a-z][a-z0-9-]*$/` (`parseCredentialKey` in `@deepseek-ai/dsh-credentials`). A colon-separated
|
|
14
|
-
* key such as `dsh-remote-go:ssh-password:h_1` is stored as given but rejected the next time the
|
|
15
|
-
* credential document is read — the whole file then fails to load, taking every other credential
|
|
16
|
-
* with it. A host id is `h_<base36>`: its only character outside the grammar is the underscore,
|
|
17
|
-
* which maps onto `-` without collisions because the issued suffix never contains one. Only an id
|
|
18
|
-
* this plugin issued is addressable, so an unexpected value never reaches the document.
|
|
19
|
-
* @param {string} hostId - the host whose password is addressed.
|
|
20
|
-
* @returns {string|null} the DSH credential key, or null when the id cannot be addressed.
|
|
21
|
-
*/
|
|
22
|
-
export function passwordRecordKey(hostId) {
|
|
23
|
-
if (typeof hostId !== 'string' || !HOST_ID_RE.test(hostId)) return null
|
|
24
|
-
const id = RECORD_ID_PREFIX + hostId.replace(/_/g, '-')
|
|
25
|
-
if (!/^[a-z][a-z0-9-]*$/.test(id)) return null
|
|
26
|
-
return `${RECORD_SCOPE}/${id}`
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export function createSecretStore(options = {}) {
|
|
30
|
-
const logger = options.logger ?? console
|
|
31
|
-
|
|
32
|
-
function credentials() {
|
|
33
|
-
try {
|
|
34
|
-
const ctx = options.ctx
|
|
35
|
-
if (!ctx || typeof ctx.get !== 'function') return null
|
|
36
|
-
const service = ctx.get('credentials')
|
|
37
|
-
if (!service || typeof service.modifyRecord !== 'function' || typeof service.readRecord !== 'function') {
|
|
38
|
-
return null
|
|
39
|
-
}
|
|
40
|
-
return service
|
|
41
|
-
} catch (error) {
|
|
42
|
-
logger.warn?.('[dsh-remote-go] credential service lookup failed:', error)
|
|
43
|
-
return null
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* The address of one host's password, or null when the id is not addressable.
|
|
49
|
-
* @param {string} hostId
|
|
50
|
-
*/
|
|
51
|
-
function keyFor(hostId) {
|
|
52
|
-
return passwordRecordKey(hostId)
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
return {
|
|
56
|
-
available() {
|
|
57
|
-
return credentials() !== null
|
|
58
|
-
},
|
|
59
|
-
|
|
60
|
-
async get(hostId) {
|
|
61
|
-
const service = credentials()
|
|
62
|
-
const key = keyFor(hostId)
|
|
63
|
-
if (!service || key === null) return null
|
|
64
|
-
try {
|
|
65
|
-
const record = await service.readRecord(key)
|
|
66
|
-
const payload = record && record.kind === 'grant' ? record.payload : null
|
|
67
|
-
if (!payload || typeof payload !== 'object') return null
|
|
68
|
-
if (payload.version !== PAYLOAD_VERSION || typeof payload.password !== 'string') return null
|
|
69
|
-
return payload.password === '' ? null : payload.password
|
|
70
|
-
} catch (error) {
|
|
71
|
-
logger.warn?.('[dsh-remote-go] could not read the saved password:', error)
|
|
72
|
-
return null
|
|
73
|
-
}
|
|
74
|
-
},
|
|
75
|
-
|
|
76
|
-
async has(hostId) {
|
|
77
|
-
return (await this.get(hostId)) !== null
|
|
78
|
-
},
|
|
79
|
-
|
|
80
|
-
async set(hostId, password) {
|
|
81
|
-
const service = credentials()
|
|
82
|
-
const key = keyFor(hostId)
|
|
83
|
-
if (!service || key === null || typeof password !== 'string' || password === '') return false
|
|
84
|
-
try {
|
|
85
|
-
await service.modifyRecord(key, async () => ({
|
|
86
|
-
kind: 'grant',
|
|
87
|
-
payload: { version: PAYLOAD_VERSION, password },
|
|
88
|
-
}))
|
|
89
|
-
return true
|
|
90
|
-
} catch (error) {
|
|
91
|
-
logger.warn?.('[dsh-remote-go] could not save the password:', error)
|
|
92
|
-
return false
|
|
93
|
-
}
|
|
94
|
-
},
|
|
95
|
-
|
|
96
|
-
async remove(hostId) {
|
|
97
|
-
const service = credentials()
|
|
98
|
-
const key = keyFor(hostId)
|
|
99
|
-
if (!service || key === null || typeof service.deleteRecord !== 'function') return false
|
|
100
|
-
try {
|
|
101
|
-
await service.deleteRecord(key)
|
|
102
|
-
return true
|
|
103
|
-
} catch (error) {
|
|
104
|
-
logger.warn?.('[dsh-remote-go] could not delete the saved password:', error)
|
|
105
|
-
return false
|
|
106
|
-
}
|
|
107
|
-
},
|
|
108
|
-
}
|
|
109
|
-
}
|
package/src/service.js
DELETED
|
@@ -1,459 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Orchestration service — the facade over host-registry, connect-pipeline, host-lifecycle, prompts and connect-progress; every external step is injected.
|
|
3
|
-
*/
|
|
4
|
-
import { EventEmitter } from 'node:events'
|
|
5
|
-
import { planNpx, verifyNpxVersion } from './bootstrap.js'
|
|
6
|
-
import {
|
|
7
|
-
MIN_DSH_VERSION,
|
|
8
|
-
REMOTE_CONFLICT_TIMEOUT_MS,
|
|
9
|
-
REMOTE_REATTACH_ATTEMPTS,
|
|
10
|
-
REMOTE_REATTACH_INTERVAL_MS,
|
|
11
|
-
REMOTE_TUNNEL_REPAIR_SETTLE_MS,
|
|
12
|
-
REMOTE_UNREACHABLE_CONFIRM_DELAY_MS,
|
|
13
|
-
REMOTE_UNREACHABLE_RECHECK_DELAY_MS,
|
|
14
|
-
REMOTE_VIEW_PREFIX,
|
|
15
|
-
} from './constants.js'
|
|
16
|
-
import { createConnectProgress, describePreflightEvent } from './connect-progress.js'
|
|
17
|
-
import { createDownloadJobs } from './download-jobs.js'
|
|
18
|
-
import {
|
|
19
|
-
reattachHost,
|
|
20
|
-
reconnectHost,
|
|
21
|
-
repairTunnel,
|
|
22
|
-
restartHost,
|
|
23
|
-
startConnect,
|
|
24
|
-
stopRemoteHost,
|
|
25
|
-
} from './connect-pipeline.js'
|
|
26
|
-
import { diagnoseHost } from './diagnostics.js'
|
|
27
|
-
import { errors } from './errors.js'
|
|
28
|
-
import {
|
|
29
|
-
discoverSshAliases,
|
|
30
|
-
initRegistry,
|
|
31
|
-
listKeyFiles,
|
|
32
|
-
removeHost,
|
|
33
|
-
runtimeOf,
|
|
34
|
-
saveHost,
|
|
35
|
-
saveSettings,
|
|
36
|
-
setActiveHost,
|
|
37
|
-
snapshot,
|
|
38
|
-
} from './host-registry.js'
|
|
39
|
-
import { disconnectHost, noteRemoteUnreachable, shutdownAll } from './host-lifecycle.js'
|
|
40
|
-
import { requireDestination } from './local-download.js'
|
|
41
|
-
import { loadLocalSshMaterial } from './local-ssh.js'
|
|
42
|
-
import { ensureRemoteNode } from './node-runtime.js'
|
|
43
|
-
import { confirmConflict, confirmHostKey } from './prompts.js'
|
|
44
|
-
import { probeRemote } from './probe.js'
|
|
45
|
-
import { SshConnection } from './ssh.js'
|
|
46
|
-
import { createTunnel, probeLoopback } from './tunnel.js'
|
|
47
|
-
import { compareVersions, normalizeVersion, parseVersion } from './version.js'
|
|
48
|
-
import { nowIso } from './util.js'
|
|
49
|
-
import {
|
|
50
|
-
adoptRemoteWeb,
|
|
51
|
-
clearRunRegistry,
|
|
52
|
-
exchangeTokenOverTunnel,
|
|
53
|
-
findForeignDshProcesses,
|
|
54
|
-
readRunRegistry,
|
|
55
|
-
remoteHttpStatus,
|
|
56
|
-
remoteProcessIdentity,
|
|
57
|
-
resolveRemoteWeb,
|
|
58
|
-
startRemoteWeb,
|
|
59
|
-
stopForeignDshProcesses,
|
|
60
|
-
stopRemoteWeb,
|
|
61
|
-
waitForRemoteUi,
|
|
62
|
-
writeRunRegistry,
|
|
63
|
-
} from './webapp.js'
|
|
64
|
-
|
|
65
|
-
export { describePreflightEvent }
|
|
66
|
-
|
|
67
|
-
/** Milliseconds a paused host-key handshake waits for the user. */
|
|
68
|
-
const HOST_KEY_CONFIRM_TIMEOUT_MS = 120_000
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* One Host process can create several services (tests, a plugin reload in-process). The
|
|
72
|
-
* instance id must differ for each so the Client can tell a new publish generation from a stale
|
|
73
|
-
* frame without trusting wall-clock ordering.
|
|
74
|
-
*/
|
|
75
|
-
let stateInstanceSequence = 0
|
|
76
|
-
function stateInstanceId() {
|
|
77
|
-
stateInstanceSequence += 1
|
|
78
|
-
const pid = typeof process !== 'undefined' && Number.isInteger(process.pid) ? process.pid.toString(36) : '0'
|
|
79
|
-
return `${pid}-${Date.now().toString(36)}-${stateInstanceSequence.toString(36)}`
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export class RemoteGoService extends EventEmitter {
|
|
83
|
-
constructor(options) {
|
|
84
|
-
super()
|
|
85
|
-
this.store = options.store
|
|
86
|
-
this.home = options.home
|
|
87
|
-
this.logger = options.logger ?? console
|
|
88
|
-
this.localVersion = options.localVersion ?? null
|
|
89
|
-
// `engines.node` of the local DSH package; the managed Node version is its
|
|
90
|
-
// lower bound (see `managedNodeVersionFromEngine`). Null until detected.
|
|
91
|
-
this.engineNodeRange = options.engineNodeRange ?? null
|
|
92
|
-
this.secrets = options.secrets ?? null
|
|
93
|
-
this.hostKeyConfirmTimeoutMs = options.hostKeyConfirmTimeoutMs ?? HOST_KEY_CONFIRM_TIMEOUT_MS
|
|
94
|
-
this.conflictConfirmTimeoutMs = options.conflictConfirmTimeoutMs ?? REMOTE_CONFLICT_TIMEOUT_MS
|
|
95
|
-
this.logLevel = typeof options.logLevel === 'string' ? options.logLevel : null
|
|
96
|
-
/** Monotonic revision of the published `/state` snapshot (StateView.rev). */
|
|
97
|
-
this.stateRev = 0
|
|
98
|
-
/**
|
|
99
|
-
* Identifies this plugin instance. `rev` is only monotonic inside one process; after a Host
|
|
100
|
-
* restart or a plugin reload a fresh counter would look older to a Client that is still
|
|
101
|
-
* holding the previous high-water mark, and every new frame would be dropped. The Client
|
|
102
|
-
* accepts a frame from a different instance regardless of its `rev` (StateView.instance).
|
|
103
|
-
*/
|
|
104
|
-
this.stateInstance = stateInstanceId()
|
|
105
|
-
|
|
106
|
-
const deps = {
|
|
107
|
-
sshFactory: options.sshFactory ?? ((sshOptions) => new SshConnection(sshOptions)),
|
|
108
|
-
tunnelFactory: options.tunnelFactory ?? createTunnel,
|
|
109
|
-
/** Local listener health: decides whether a transient proxy failure needs a rebuild. */
|
|
110
|
-
tunnelProbe: options.tunnelProbe ?? probeLoopback,
|
|
111
|
-
probe: options.probe ?? probeRemote,
|
|
112
|
-
plan: options.plan ?? planNpx,
|
|
113
|
-
ensureNode: options.ensureNode ?? ensureRemoteNode,
|
|
114
|
-
preflight: options.preflight ?? verifyNpxVersion,
|
|
115
|
-
startWeb: options.startWeb ?? startRemoteWeb,
|
|
116
|
-
stopWeb: options.stopWeb ?? stopRemoteWeb,
|
|
117
|
-
waitUi: options.waitUi ?? waitForRemoteUi,
|
|
118
|
-
exchange: options.exchange ?? exchangeTokenOverTunnel,
|
|
119
|
-
adopt: options.adopt ?? adoptRemoteWeb,
|
|
120
|
-
resolveRemote: options.resolveRemote ?? resolveRemoteWeb,
|
|
121
|
-
writeRegistry: options.writeRegistry ?? writeRunRegistry,
|
|
122
|
-
clearRegistry: options.clearRegistry ?? clearRunRegistry,
|
|
123
|
-
remoteStatus: options.remoteStatus ?? remoteHttpStatus,
|
|
124
|
-
processIdentity: options.processIdentity ?? remoteProcessIdentity,
|
|
125
|
-
findForeign: options.findForeign ?? findForeignDshProcesses,
|
|
126
|
-
stopForeign: options.stopForeign ?? stopForeignDshProcesses,
|
|
127
|
-
readRegistry: options.readRegistry ?? readRunRegistry,
|
|
128
|
-
loadSshMaterial: options.loadSshMaterial ?? loadLocalSshMaterial,
|
|
129
|
-
}
|
|
130
|
-
this.ctx = {
|
|
131
|
-
deps,
|
|
132
|
-
store: this.store,
|
|
133
|
-
home: this.home,
|
|
134
|
-
logger: this.logger,
|
|
135
|
-
secrets: this.secrets,
|
|
136
|
-
state: { runtimes: new Map(), activeHostId: null, initialized: false, disposed: false },
|
|
137
|
-
timers: {
|
|
138
|
-
hostKeyConfirmMs: this.hostKeyConfirmTimeoutMs,
|
|
139
|
-
conflictConfirmMs: this.conflictConfirmTimeoutMs,
|
|
140
|
-
// Liveness confirmation and the re-attach retry loop; tests shorten these.
|
|
141
|
-
remoteConfirmDelayMs: options.remoteConfirmDelayMs ?? REMOTE_UNREACHABLE_CONFIRM_DELAY_MS,
|
|
142
|
-
remoteRecheckMs: options.remoteRecheckMs ?? REMOTE_UNREACHABLE_RECHECK_DELAY_MS,
|
|
143
|
-
reattachAttempts: options.reattachAttempts ?? REMOTE_REATTACH_ATTEMPTS,
|
|
144
|
-
reattachIntervalMs: options.reattachIntervalMs ?? REMOTE_REATTACH_INTERVAL_MS,
|
|
145
|
-
tunnelRepairSettleMs: options.tunnelRepairSettleMs ?? REMOTE_TUNNEL_REPAIR_SETTLE_MS,
|
|
146
|
-
},
|
|
147
|
-
// Live readers, never cached: a setting or a detected version can change
|
|
148
|
-
// while a connect is already in flight.
|
|
149
|
-
settings: () => this.store.getSettings(),
|
|
150
|
-
localVersion: () => this.localVersion,
|
|
151
|
-
engineNodeRange: () => this.engineNodeRange,
|
|
152
|
-
userHome: () => process.env.USERPROFILE || process.env.HOME || this.home,
|
|
153
|
-
emitState: () => this.emitState(),
|
|
154
|
-
init: () => this.init(),
|
|
155
|
-
/**
|
|
156
|
-
* The watchdog reports an episode (suspected -> confirmed -> recovered); the Client
|
|
157
|
-
* contract gets the same transitions as one SSE event, and the state frames carry the
|
|
158
|
-
* `restarting-remote` progress. Never let a listener failure break the probe.
|
|
159
|
-
*/
|
|
160
|
-
onRemoteUnreachable: (runtime, info) => {
|
|
161
|
-
try {
|
|
162
|
-
this.emit('remote-unreachable', { hostId: runtime.id, at: nowIso(), ...info })
|
|
163
|
-
} catch (error) {
|
|
164
|
-
this.logger.warn?.('[dsh-remote-go] remote-unreachable listener failed:', error)
|
|
165
|
-
}
|
|
166
|
-
},
|
|
167
|
-
/** A proxy or tunnel failure arrived: confirm it with probes instead of trusting one request. */
|
|
168
|
-
noteRemoteUnreachable: (runtime, source) => noteRemoteUnreachable(this.ctx, runtime, source),
|
|
169
|
-
/** Confirmed by probes: re-read the remote, rewrite the registry, rebuild the tunnel. */
|
|
170
|
-
requestReattach: (runtime, info) => {
|
|
171
|
-
void reattachHost(this.ctx, runtime, info)
|
|
172
|
-
},
|
|
173
|
-
/** The remote answers but proxied requests fail: rebuild the local listener (B8). */
|
|
174
|
-
repairTunnel: (runtime) => repairTunnel(this.ctx, runtime),
|
|
175
|
-
}
|
|
176
|
-
this.ctx.progress = createConnectProgress({
|
|
177
|
-
logger: this.logger,
|
|
178
|
-
logLevel: this.logLevel,
|
|
179
|
-
getSettings: () => this.store.getSettings(),
|
|
180
|
-
emitState: () => this.emitState(),
|
|
181
|
-
})
|
|
182
|
-
this.downloads = createDownloadJobs({
|
|
183
|
-
logger: this.logger,
|
|
184
|
-
emit: (job) => this.emit('download', job),
|
|
185
|
-
})
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
get runtimes() {
|
|
189
|
-
return this.ctx.state.runtimes
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
get activeHostId() {
|
|
193
|
-
return this.ctx.state.activeHostId
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
async init() {
|
|
197
|
-
await initRegistry(this.ctx)
|
|
198
|
-
return this
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
emitState() {
|
|
202
|
-
try {
|
|
203
|
-
// Every emitted frame gets its own monotonic revision. The Client drops a frame whose
|
|
204
|
-
// `rev` is not newer than the one on screen, so an out-of-order SSE delivery or a slow
|
|
205
|
-
// `GET /state` can no longer repaint the panel backwards (docs/api.md StateView.rev).
|
|
206
|
-
this.stateRev += 1
|
|
207
|
-
this.emit('state', this.snapshot())
|
|
208
|
-
} catch (error) {
|
|
209
|
-
this.logger.warn?.('[dsh-remote-go] state listener failed:', error)
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* Adopt a DSH version for this machine.
|
|
215
|
-
*
|
|
216
|
-
* `source === 'client'` is the browser's `POST /local-version` backfill: it exists for the
|
|
217
|
-
* case where the Host could not detect the version by itself, so it must never overwrite a
|
|
218
|
-
* detected one, and it must stay inside the range this plugin supports. Without both guards
|
|
219
|
-
* any local page could pin the remote npx runtime (and the version-parity check) to a value
|
|
220
|
-
* of its choosing.
|
|
221
|
-
* @param {unknown} version - a DSH semver string.
|
|
222
|
-
* @param {string} [source] - where the value came from; only `client` is distrusted.
|
|
223
|
-
* @returns {boolean} whether the value was adopted.
|
|
224
|
-
*/
|
|
225
|
-
setLocalVersion(version, source = 'detected') {
|
|
226
|
-
const normalized = version ? normalizeVersion(String(version)) : null
|
|
227
|
-
const valid = normalized !== null && parseVersion(normalized) !== null
|
|
228
|
-
if (source === 'client') {
|
|
229
|
-
if (this.localVersion !== null) return false
|
|
230
|
-
// A page may only name a real DSH version: a typo or a crafted value is a client mistake
|
|
231
|
-
// (400), not a silent no-op the page could mistake for success.
|
|
232
|
-
if (!valid) {
|
|
233
|
-
throw errors.invalidInput('version', {
|
|
234
|
-
zh: '本机 DSH 版本格式不合法。',
|
|
235
|
-
en: 'The local DSH version is not a valid version.',
|
|
236
|
-
})
|
|
237
|
-
}
|
|
238
|
-
if (compareVersions(normalized, MIN_DSH_VERSION) < 0) {
|
|
239
|
-
throw errors.invalidInput('version', {
|
|
240
|
-
zh: `本机 DSH 版本 ${normalized} 低于插件要求的最低版本 ${MIN_DSH_VERSION}。`,
|
|
241
|
-
en: `Local DSH ${normalized} is below the minimum this plugin supports (${MIN_DSH_VERSION}).`,
|
|
242
|
-
})
|
|
243
|
-
}
|
|
244
|
-
} else if (!valid) {
|
|
245
|
-
return false
|
|
246
|
-
}
|
|
247
|
-
this.localVersion = normalized
|
|
248
|
-
this.emitState()
|
|
249
|
-
return true
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
setLocalEnginesNode(range) {
|
|
253
|
-
const text = typeof range === 'string' ? range.trim() : ''
|
|
254
|
-
this.engineNodeRange = text === '' ? null : text
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/** Build the client-facing state snapshot (contract: docs/api.md). */
|
|
258
|
-
snapshot() {
|
|
259
|
-
return { ...snapshot(this.ctx), rev: this.stateRev, instance: this.stateInstance }
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
userHome() {
|
|
263
|
-
return this.ctx.userHome()
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
async saveHost(rawHost) {
|
|
267
|
-
return saveHost(this.ctx, rawHost)
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
async removeHost(id) {
|
|
271
|
-
return removeHost(this.ctx, id)
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
setActiveHost(id) {
|
|
275
|
-
return setActiveHost(this.ctx, id)
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
async saveSettings(patch) {
|
|
279
|
-
return saveSettings(this.ctx, patch)
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
async listKeyFiles(dir) {
|
|
283
|
-
return listKeyFiles(this.ctx, dir)
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
async discoverSshAliases() {
|
|
287
|
-
return discoverSshAliases(this.ctx)
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
async connect(id, options = {}) {
|
|
291
|
-
return startConnect(this.ctx, id, options)
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
/**
|
|
295
|
-
* Remember (or forget) the SSH password without opening a connection. The wizard's plain
|
|
296
|
-
* "save" action uses this, and it is the only way to refresh a saved password that does not
|
|
297
|
-
* require a successful connect first. The value never enters `hosts.json`; `available:false`
|
|
298
|
-
* means no credential store can persist it here.
|
|
299
|
-
* @param {string} id - host id.
|
|
300
|
-
* @param {{ password?: string, clear?: boolean }} [options]
|
|
301
|
-
* @returns {Promise<{ available: boolean, saved: boolean }>}
|
|
302
|
-
*/
|
|
303
|
-
async saveHostPassword(id, options = {}) {
|
|
304
|
-
await this.init()
|
|
305
|
-
const runtime = runtimeOf(this.ctx, id)
|
|
306
|
-
const available = this.secrets ? this.secrets.available() === true : false
|
|
307
|
-
if (!available) return { available: false, saved: false }
|
|
308
|
-
if (options.clear === true) {
|
|
309
|
-
const removed = await this.secrets.remove(id)
|
|
310
|
-
// The password in memory belonged to the record just removed: a later connect must ask
|
|
311
|
-
// instead of silently reusing a credential the user asked to forget.
|
|
312
|
-
runtime.password = null
|
|
313
|
-
runtime.passwordSaved = !removed
|
|
314
|
-
this.emitState()
|
|
315
|
-
return { available, saved: false }
|
|
316
|
-
}
|
|
317
|
-
const password = typeof options.password === 'string' ? options.password : ''
|
|
318
|
-
if (password === '') {
|
|
319
|
-
throw errors.invalidInput('password', { zh: '密码不能为空。', en: 'The password must not be empty.' })
|
|
320
|
-
}
|
|
321
|
-
const saved = await this.secrets.set(id, password)
|
|
322
|
-
// An explicit save also arms the in-memory copy, so clicking "connect" next does not ask
|
|
323
|
-
// again for a password this process just proved and stored.
|
|
324
|
-
runtime.password = password
|
|
325
|
-
runtime.passwordSaved = saved
|
|
326
|
-
this.emitState()
|
|
327
|
-
return { available, saved }
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
async disconnect(id, options = {}) {
|
|
331
|
-
await this.init()
|
|
332
|
-
return disconnectHost(this.ctx, runtimeOf(this.ctx, id), options)
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
async reconnect(id) {
|
|
336
|
-
await this.init()
|
|
337
|
-
return reconnectHost(this.ctx, runtimeOf(this.ctx, id))
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
/**
|
|
341
|
-
* Restart the managed remote web on the same SSH session (the "Restart remote DSH"
|
|
342
|
-
* card action). Only a connected host can be restarted; the work runs in the
|
|
343
|
-
* background and reports through `/state` like a connect does.
|
|
344
|
-
*/
|
|
345
|
-
async restart(id) {
|
|
346
|
-
await this.init()
|
|
347
|
-
return restartHost(this.ctx, runtimeOf(this.ctx, id))
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
/**
|
|
351
|
-
* Stop the managed remote web this connection is bound to, then release the link and
|
|
352
|
-
* leave the host `disconnected` (the "Stop remote DSH" card action). Runs synchronously
|
|
353
|
-
* on the same SSH session: `/state` carries `stopping-remote` while it works, and a
|
|
354
|
-
* refusal (wrong state, busy, or an unprovable pid) is thrown as a coded error (HTTP 409).
|
|
355
|
-
*/
|
|
356
|
-
async stopRemote(id) {
|
|
357
|
-
await this.init()
|
|
358
|
-
return stopRemoteHost(this.ctx, runtimeOf(this.ctx, id))
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
async confirmFingerprint(id, decision) {
|
|
362
|
-
return confirmHostKey(this.ctx, runtimeOf(this.ctx, id), decision)
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
async confirmConflict(id, decision) {
|
|
366
|
-
return confirmConflict(runtimeOf(this.ctx, id), decision)
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
openInfo(id) {
|
|
370
|
-
const runtime = runtimeOf(this.ctx, id)
|
|
371
|
-
if (runtime.status !== 'connected' || !runtime.tunnel || !runtime.token) {
|
|
372
|
-
throw errors.remoteUiUnreachable({
|
|
373
|
-
zh: '主机尚未连接,无法打开远端界面。',
|
|
374
|
-
en: 'The host is not connected yet, so the remote UI cannot be opened.',
|
|
375
|
-
})
|
|
376
|
-
}
|
|
377
|
-
const token = encodeURIComponent(runtime.token)
|
|
378
|
-
return {
|
|
379
|
-
url: `http://127.0.0.1:${runtime.tunnel.localPort}/?token=${token}`,
|
|
380
|
-
// The browser half's carrier: same-origin seat of the same UI, proxied to this tunnel.
|
|
381
|
-
webUrl: `${REMOTE_VIEW_PREFIX}${encodeURIComponent(id)}/?token=${token}`,
|
|
382
|
-
localPort: runtime.tunnel.localPort,
|
|
383
|
-
address: `127.0.0.1:${runtime.tunnel.localPort}`,
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
/** Configured host ids (the proxy keeps one stream upgrade route per id). */
|
|
388
|
-
hostIds() {
|
|
389
|
-
return [...this.ctx.state.runtimes.keys()]
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
/**
|
|
393
|
-
* Loopback target of one host's remote web UI, for the same-origin proxy.
|
|
394
|
-
* Reads the live runtime, so a reconnect hands the proxy the new tunnel on the next request.
|
|
395
|
-
* @param {string} id - host id.
|
|
396
|
-
* @returns {{ localPort: number, remotePort: number | null } | null}
|
|
397
|
-
*/
|
|
398
|
-
webViewTarget(id) {
|
|
399
|
-
const runtime = this.ctx.state.runtimes.get(id)
|
|
400
|
-
if (!runtime || runtime.status !== 'connected' || !runtime.tunnel) return null
|
|
401
|
-
return { localPort: runtime.tunnel.localPort, remotePort: runtime.remote.port }
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
/**
|
|
405
|
-
* The same-origin proxy could not reach a host's tunnel. One failed request is not a
|
|
406
|
-
* restart: it starts the same probe confirmation the heartbeat uses.
|
|
407
|
-
* @param {string} id - host id the proxy serves.
|
|
408
|
-
*/
|
|
409
|
-
noteUpstreamFailure(id) {
|
|
410
|
-
const runtime = this.ctx.state.runtimes.get(id)
|
|
411
|
-
if (!runtime) return
|
|
412
|
-
noteRemoteUnreachable(this.ctx, runtime, 'proxy')
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
async diagnose(id) {
|
|
416
|
-
await this.init()
|
|
417
|
-
return diagnoseHost(runtimeOf(this.ctx, id), { targetVersion: this.localVersion })
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
/**
|
|
421
|
-
* Start preparing one remote file or folder for the client's download.
|
|
422
|
-
* @param {string} id - host id.
|
|
423
|
-
* @param {unknown} path - absolute remote path.
|
|
424
|
-
* @param {{ destination?: string }} [options] - local destination directory.
|
|
425
|
-
* @returns {object} the initial download job view.
|
|
426
|
-
*/
|
|
427
|
-
async startRemoteDownload(id, path, options = {}) {
|
|
428
|
-
await this.init()
|
|
429
|
-
const runtime = runtimeOf(this.ctx, id)
|
|
430
|
-
// One home root for both checks: the pre-flight below and the write itself. Falling back to
|
|
431
|
-
// `os.homedir()` later could disagree with `userHome()` when HOME/USERPROFILE is unset, and
|
|
432
|
-
// then a destination accepted here would be refused by the job.
|
|
433
|
-
const home = this.userHome()
|
|
434
|
-
// The local folder is checked before a job exists: a refused destination is the caller's
|
|
435
|
-
// mistake (HTTP 400 `invalid-input`), not a job that first answers `preparing` and then
|
|
436
|
-
// reports the refusal asynchronously (which also wasted a job slot and an SFTP stat).
|
|
437
|
-
await requireDestination(options.destination, { home })
|
|
438
|
-
return this.downloads.start(runtime, path, { ...options, home })
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
/** Current view of one download job. */
|
|
442
|
-
async remoteDownloadStatus(jobId) {
|
|
443
|
-
await this.init()
|
|
444
|
-
return this.downloads.status(jobId)
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
/** Cancel one download job. */
|
|
448
|
-
async cancelRemoteDownload(jobId) {
|
|
449
|
-
await this.init()
|
|
450
|
-
return this.downloads.cancel(jobId)
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
async shutdown() {
|
|
454
|
-
this.ctx.state.disposed = true
|
|
455
|
-
this.ctx.progress.dispose()
|
|
456
|
-
this.downloads.dispose()
|
|
457
|
-
await shutdownAll(this.ctx)
|
|
458
|
-
}
|
|
459
|
-
}
|