dsh-remote-go 0.1.0 → 0.2.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 +56 -95
- package/client.js +3121 -330
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +12 -11
- package/src/admission.js +43 -0
- package/src/api.js +219 -23
- package/src/atomic-json.js +19 -2
- package/src/bootstrap.js +14 -1
- package/src/connect-log.js +145 -8
- package/src/connect-pipeline.js +1545 -108
- package/src/connect-progress.js +28 -8
- package/src/constants.js +65 -3
- package/src/diagnostics.js +3 -0
- package/src/download-jobs.js +17 -0
- package/src/errors.js +98 -2
- package/src/host-lifecycle.js +434 -17
- package/src/host-registry.js +78 -6
- package/src/host-runtime.js +74 -0
- package/src/host-view.js +28 -4
- package/src/index.js +47 -3
- package/src/key-files.js +6 -1
- package/src/known-hosts.js +50 -11
- package/src/layout.js +28 -10
- package/src/local-download.js +232 -13
- package/src/probe.js +13 -1
- package/src/prompts.js +114 -17
- package/src/redact.js +17 -3
- package/src/remote-files.js +2 -2
- package/src/remote-path.js +64 -0
- package/src/remote-proc.js +135 -0
- package/src/remote-proxy.js +815 -0
- package/src/remote-web.js +479 -28
- package/src/request-trust.js +89 -0
- package/src/secrets.js +38 -8
- package/src/service.js +222 -13
- package/src/settings.js +30 -2
- package/src/ssh.js +108 -29
- package/src/store.js +58 -8
- package/src/tools.js +386 -0
- package/src/tunnel.js +60 -1
- package/src/webapp.js +15 -0
- package/vendor/THIRD_PARTY_NOTICES.md +27 -1
- package/vendor/ssh2-entry.mjs +0 -12
|
@@ -0,0 +1,89 @@
|
|
|
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
CHANGED
|
@@ -2,9 +2,30 @@
|
|
|
2
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
3
|
*/
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
import { HOST_ID_RE } from './settings.js'
|
|
6
|
+
|
|
7
|
+
const RECORD_SCOPE = 'dsh-remote-go'
|
|
8
|
+
const RECORD_ID_PREFIX = 'ssh-password-'
|
|
6
9
|
const PAYLOAD_VERSION = 1
|
|
7
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
|
+
|
|
8
29
|
export function createSecretStore(options = {}) {
|
|
9
30
|
const logger = options.logger ?? console
|
|
10
31
|
|
|
@@ -23,8 +44,12 @@ export function createSecretStore(options = {}) {
|
|
|
23
44
|
}
|
|
24
45
|
}
|
|
25
46
|
|
|
47
|
+
/**
|
|
48
|
+
* The address of one host's password, or null when the id is not addressable.
|
|
49
|
+
* @param {string} hostId
|
|
50
|
+
*/
|
|
26
51
|
function keyFor(hostId) {
|
|
27
|
-
return
|
|
52
|
+
return passwordRecordKey(hostId)
|
|
28
53
|
}
|
|
29
54
|
|
|
30
55
|
return {
|
|
@@ -34,9 +59,10 @@ export function createSecretStore(options = {}) {
|
|
|
34
59
|
|
|
35
60
|
async get(hostId) {
|
|
36
61
|
const service = credentials()
|
|
37
|
-
|
|
62
|
+
const key = keyFor(hostId)
|
|
63
|
+
if (!service || key === null) return null
|
|
38
64
|
try {
|
|
39
|
-
const record = await service.readRecord(
|
|
65
|
+
const record = await service.readRecord(key)
|
|
40
66
|
const payload = record && record.kind === 'grant' ? record.payload : null
|
|
41
67
|
if (!payload || typeof payload !== 'object') return null
|
|
42
68
|
if (payload.version !== PAYLOAD_VERSION || typeof payload.password !== 'string') return null
|
|
@@ -53,9 +79,10 @@ export function createSecretStore(options = {}) {
|
|
|
53
79
|
|
|
54
80
|
async set(hostId, password) {
|
|
55
81
|
const service = credentials()
|
|
56
|
-
|
|
82
|
+
const key = keyFor(hostId)
|
|
83
|
+
if (!service || key === null || typeof password !== 'string' || password === '') return false
|
|
57
84
|
try {
|
|
58
|
-
await service.modifyRecord(
|
|
85
|
+
await service.modifyRecord(key, async () => ({
|
|
59
86
|
kind: 'grant',
|
|
60
87
|
payload: { version: PAYLOAD_VERSION, password },
|
|
61
88
|
}))
|
|
@@ -68,11 +95,14 @@ export function createSecretStore(options = {}) {
|
|
|
68
95
|
|
|
69
96
|
async remove(hostId) {
|
|
70
97
|
const service = credentials()
|
|
71
|
-
|
|
98
|
+
const key = keyFor(hostId)
|
|
99
|
+
if (!service || key === null || typeof service.deleteRecord !== 'function') return false
|
|
72
100
|
try {
|
|
73
|
-
await service.deleteRecord(
|
|
101
|
+
await service.deleteRecord(key)
|
|
102
|
+
return true
|
|
74
103
|
} catch (error) {
|
|
75
104
|
logger.warn?.('[dsh-remote-go] could not delete the saved password:', error)
|
|
105
|
+
return false
|
|
76
106
|
}
|
|
77
107
|
},
|
|
78
108
|
}
|
package/src/service.js
CHANGED
|
@@ -3,10 +3,26 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { EventEmitter } from 'node:events'
|
|
5
5
|
import { planNpx, verifyNpxVersion } from './bootstrap.js'
|
|
6
|
-
import {
|
|
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'
|
|
7
16
|
import { createConnectProgress, describePreflightEvent } from './connect-progress.js'
|
|
8
17
|
import { createDownloadJobs } from './download-jobs.js'
|
|
9
|
-
import {
|
|
18
|
+
import {
|
|
19
|
+
reattachHost,
|
|
20
|
+
reconnectHost,
|
|
21
|
+
repairTunnel,
|
|
22
|
+
restartHost,
|
|
23
|
+
startConnect,
|
|
24
|
+
stopRemoteHost,
|
|
25
|
+
} from './connect-pipeline.js'
|
|
10
26
|
import { diagnoseHost } from './diagnostics.js'
|
|
11
27
|
import { errors } from './errors.js'
|
|
12
28
|
import {
|
|
@@ -20,23 +36,30 @@ import {
|
|
|
20
36
|
setActiveHost,
|
|
21
37
|
snapshot,
|
|
22
38
|
} from './host-registry.js'
|
|
23
|
-
import { disconnectHost, shutdownAll } from './host-lifecycle.js'
|
|
39
|
+
import { disconnectHost, noteRemoteUnreachable, shutdownAll } from './host-lifecycle.js'
|
|
40
|
+
import { requireDestination } from './local-download.js'
|
|
24
41
|
import { loadLocalSshMaterial } from './local-ssh.js'
|
|
25
42
|
import { ensureRemoteNode } from './node-runtime.js'
|
|
26
43
|
import { confirmConflict, confirmHostKey } from './prompts.js'
|
|
27
44
|
import { probeRemote } from './probe.js'
|
|
28
45
|
import { SshConnection } from './ssh.js'
|
|
29
|
-
import { createTunnel } from './tunnel.js'
|
|
30
|
-
import { normalizeVersion } from './version.js'
|
|
46
|
+
import { createTunnel, probeLoopback } from './tunnel.js'
|
|
47
|
+
import { compareVersions, normalizeVersion, parseVersion } from './version.js'
|
|
48
|
+
import { nowIso } from './util.js'
|
|
31
49
|
import {
|
|
32
50
|
adoptRemoteWeb,
|
|
51
|
+
clearRunRegistry,
|
|
33
52
|
exchangeTokenOverTunnel,
|
|
34
53
|
findForeignDshProcesses,
|
|
35
54
|
readRunRegistry,
|
|
55
|
+
remoteHttpStatus,
|
|
56
|
+
remoteProcessIdentity,
|
|
57
|
+
resolveRemoteWeb,
|
|
36
58
|
startRemoteWeb,
|
|
37
59
|
stopForeignDshProcesses,
|
|
38
60
|
stopRemoteWeb,
|
|
39
61
|
waitForRemoteUi,
|
|
62
|
+
writeRunRegistry,
|
|
40
63
|
} from './webapp.js'
|
|
41
64
|
|
|
42
65
|
export { describePreflightEvent }
|
|
@@ -44,6 +67,18 @@ export { describePreflightEvent }
|
|
|
44
67
|
/** Milliseconds a paused host-key handshake waits for the user. */
|
|
45
68
|
const HOST_KEY_CONFIRM_TIMEOUT_MS = 120_000
|
|
46
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
|
+
|
|
47
82
|
export class RemoteGoService extends EventEmitter {
|
|
48
83
|
constructor(options) {
|
|
49
84
|
super()
|
|
@@ -58,10 +93,21 @@ export class RemoteGoService extends EventEmitter {
|
|
|
58
93
|
this.hostKeyConfirmTimeoutMs = options.hostKeyConfirmTimeoutMs ?? HOST_KEY_CONFIRM_TIMEOUT_MS
|
|
59
94
|
this.conflictConfirmTimeoutMs = options.conflictConfirmTimeoutMs ?? REMOTE_CONFLICT_TIMEOUT_MS
|
|
60
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()
|
|
61
105
|
|
|
62
106
|
const deps = {
|
|
63
107
|
sshFactory: options.sshFactory ?? ((sshOptions) => new SshConnection(sshOptions)),
|
|
64
108
|
tunnelFactory: options.tunnelFactory ?? createTunnel,
|
|
109
|
+
/** Local listener health: decides whether a transient proxy failure needs a rebuild. */
|
|
110
|
+
tunnelProbe: options.tunnelProbe ?? probeLoopback,
|
|
65
111
|
probe: options.probe ?? probeRemote,
|
|
66
112
|
plan: options.plan ?? planNpx,
|
|
67
113
|
ensureNode: options.ensureNode ?? ensureRemoteNode,
|
|
@@ -71,6 +117,11 @@ export class RemoteGoService extends EventEmitter {
|
|
|
71
117
|
waitUi: options.waitUi ?? waitForRemoteUi,
|
|
72
118
|
exchange: options.exchange ?? exchangeTokenOverTunnel,
|
|
73
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,
|
|
74
125
|
findForeign: options.findForeign ?? findForeignDshProcesses,
|
|
75
126
|
stopForeign: options.stopForeign ?? stopForeignDshProcesses,
|
|
76
127
|
readRegistry: options.readRegistry ?? readRunRegistry,
|
|
@@ -86,6 +137,12 @@ export class RemoteGoService extends EventEmitter {
|
|
|
86
137
|
timers: {
|
|
87
138
|
hostKeyConfirmMs: this.hostKeyConfirmTimeoutMs,
|
|
88
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,
|
|
89
146
|
},
|
|
90
147
|
// Live readers, never cached: a setting or a detected version can change
|
|
91
148
|
// while a connect is already in flight.
|
|
@@ -95,6 +152,26 @@ export class RemoteGoService extends EventEmitter {
|
|
|
95
152
|
userHome: () => process.env.USERPROFILE || process.env.HOME || this.home,
|
|
96
153
|
emitState: () => this.emitState(),
|
|
97
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),
|
|
98
175
|
}
|
|
99
176
|
this.ctx.progress = createConnectProgress({
|
|
100
177
|
logger: this.logger,
|
|
@@ -123,18 +200,53 @@ export class RemoteGoService extends EventEmitter {
|
|
|
123
200
|
|
|
124
201
|
emitState() {
|
|
125
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
|
|
126
207
|
this.emit('state', this.snapshot())
|
|
127
208
|
} catch (error) {
|
|
128
209
|
this.logger.warn?.('[dsh-remote-go] state listener failed:', error)
|
|
129
210
|
}
|
|
130
211
|
}
|
|
131
212
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
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
|
|
137
246
|
}
|
|
247
|
+
this.localVersion = normalized
|
|
248
|
+
this.emitState()
|
|
249
|
+
return true
|
|
138
250
|
}
|
|
139
251
|
|
|
140
252
|
setLocalEnginesNode(range) {
|
|
@@ -144,7 +256,7 @@ export class RemoteGoService extends EventEmitter {
|
|
|
144
256
|
|
|
145
257
|
/** Build the client-facing state snapshot (contract: docs/api.md). */
|
|
146
258
|
snapshot() {
|
|
147
|
-
return snapshot(this.ctx)
|
|
259
|
+
return { ...snapshot(this.ctx), rev: this.stateRev, instance: this.stateInstance }
|
|
148
260
|
}
|
|
149
261
|
|
|
150
262
|
userHome() {
|
|
@@ -179,6 +291,42 @@ export class RemoteGoService extends EventEmitter {
|
|
|
179
291
|
return startConnect(this.ctx, id, options)
|
|
180
292
|
}
|
|
181
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
|
+
|
|
182
330
|
async disconnect(id, options = {}) {
|
|
183
331
|
await this.init()
|
|
184
332
|
return disconnectHost(this.ctx, runtimeOf(this.ctx, id), options)
|
|
@@ -189,6 +337,27 @@ export class RemoteGoService extends EventEmitter {
|
|
|
189
337
|
return reconnectHost(this.ctx, runtimeOf(this.ctx, id))
|
|
190
338
|
}
|
|
191
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
|
+
|
|
192
361
|
async confirmFingerprint(id, decision) {
|
|
193
362
|
return confirmHostKey(this.ctx, runtimeOf(this.ctx, id), decision)
|
|
194
363
|
}
|
|
@@ -205,13 +374,44 @@ export class RemoteGoService extends EventEmitter {
|
|
|
205
374
|
en: 'The host is not connected yet, so the remote UI cannot be opened.',
|
|
206
375
|
})
|
|
207
376
|
}
|
|
377
|
+
const token = encodeURIComponent(runtime.token)
|
|
208
378
|
return {
|
|
209
|
-
url: `http://127.0.0.1:${runtime.tunnel.localPort}/?token=${
|
|
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}`,
|
|
210
382
|
localPort: runtime.tunnel.localPort,
|
|
211
383
|
address: `127.0.0.1:${runtime.tunnel.localPort}`,
|
|
212
384
|
}
|
|
213
385
|
}
|
|
214
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
|
+
|
|
215
415
|
async diagnose(id) {
|
|
216
416
|
await this.init()
|
|
217
417
|
return diagnoseHost(runtimeOf(this.ctx, id), { targetVersion: this.localVersion })
|
|
@@ -226,7 +426,16 @@ export class RemoteGoService extends EventEmitter {
|
|
|
226
426
|
*/
|
|
227
427
|
async startRemoteDownload(id, path, options = {}) {
|
|
228
428
|
await this.init()
|
|
229
|
-
|
|
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 })
|
|
230
439
|
}
|
|
231
440
|
|
|
232
441
|
/** Current view of one download job. */
|
package/src/settings.js
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Plugin settings: defaults, validation and sanitization; unknown or invalid fields fall back to defaults instead of failing activation.
|
|
3
3
|
*/
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
DEFAULT_IDLE_MINUTES,
|
|
6
|
+
DEFAULT_KEY_PATH,
|
|
7
|
+
DEFAULT_REMOTE_PROFILE,
|
|
8
|
+
REMOTE_HEARTBEAT_DEFAULT_SEC,
|
|
9
|
+
REMOTE_HEARTBEAT_MAX_SEC,
|
|
10
|
+
REMOTE_HEARTBEAT_MIN_SEC,
|
|
11
|
+
SSH_READY_TIMEOUT_MS,
|
|
12
|
+
} from './constants.js'
|
|
5
13
|
import { clamp, deepMerge, isPlainObject, parseSshDestination } from './util.js'
|
|
6
14
|
|
|
7
15
|
export function defaultSettings() {
|
|
@@ -13,6 +21,11 @@ export function defaultSettings() {
|
|
|
13
21
|
defaultKeyPath: DEFAULT_KEY_PATH,
|
|
14
22
|
connectTimeoutSec: Math.round(SSH_READY_TIMEOUT_MS / 1000),
|
|
15
23
|
autoReconnect: { enabled: true, maxAttempts: 5, baseDelayMs: 800 },
|
|
24
|
+
/**
|
|
25
|
+
* Light liveness probe of a connected host's remote UI. Two consecutive
|
|
26
|
+
* failures re-read the remote and re-attach; one failed request never does.
|
|
27
|
+
*/
|
|
28
|
+
remoteHeartbeat: { enabled: true, intervalSec: REMOTE_HEARTBEAT_DEFAULT_SEC },
|
|
16
29
|
hostKeyPolicy: 'first-use',
|
|
17
30
|
saveTokens: false,
|
|
18
31
|
language: 'auto',
|
|
@@ -53,6 +66,7 @@ export function sanitizeSettings(raw) {
|
|
|
53
66
|
if (!isPlainObject(raw)) return defaults
|
|
54
67
|
const input = deepMerge(defaults, raw)
|
|
55
68
|
const autoReconnect = isPlainObject(input.autoReconnect) ? input.autoReconnect : defaults.autoReconnect
|
|
69
|
+
const remoteHeartbeat = isPlainObject(input.remoteHeartbeat) ? input.remoteHeartbeat : defaults.remoteHeartbeat
|
|
56
70
|
const bootstrap = isPlainObject(input.bootstrap) ? input.bootstrap : defaults.bootstrap
|
|
57
71
|
const profile = normalizeProfileName(bootstrap.profile) ?? defaults.bootstrap.profile
|
|
58
72
|
return {
|
|
@@ -71,6 +85,15 @@ export function sanitizeSettings(raw) {
|
|
|
71
85
|
maxAttempts: numberIn(autoReconnect.maxAttempts, 0, 20, defaults.autoReconnect.maxAttempts),
|
|
72
86
|
baseDelayMs: numberIn(autoReconnect.baseDelayMs, 100, 30_000, defaults.autoReconnect.baseDelayMs),
|
|
73
87
|
},
|
|
88
|
+
remoteHeartbeat: {
|
|
89
|
+
enabled: boolean(remoteHeartbeat.enabled, defaults.remoteHeartbeat.enabled),
|
|
90
|
+
intervalSec: numberIn(
|
|
91
|
+
remoteHeartbeat.intervalSec,
|
|
92
|
+
REMOTE_HEARTBEAT_MIN_SEC,
|
|
93
|
+
REMOTE_HEARTBEAT_MAX_SEC,
|
|
94
|
+
defaults.remoteHeartbeat.intervalSec,
|
|
95
|
+
),
|
|
96
|
+
},
|
|
74
97
|
hostKeyPolicy: oneOf(input.hostKeyPolicy, ['first-use', 'strict'], defaults.hostKeyPolicy),
|
|
75
98
|
saveTokens: boolean(input.saveTokens, defaults.saveTokens),
|
|
76
99
|
language: oneOf(input.language, ['auto', 'zh', 'en'], defaults.language),
|
|
@@ -81,6 +104,9 @@ export function sanitizeSettings(raw) {
|
|
|
81
104
|
}
|
|
82
105
|
}
|
|
83
106
|
|
|
107
|
+
/** The only id shape this plugin issues: `randomId('h')` (docs/api.md `HostView.id`). */
|
|
108
|
+
export const HOST_ID_RE = /^h_[a-z0-9]{1,32}$/
|
|
109
|
+
|
|
84
110
|
export function sanitizeHostEntry(raw, options = {}) {
|
|
85
111
|
const settings = options.settings ?? defaultSettings()
|
|
86
112
|
const existing = options.existing ?? null
|
|
@@ -108,7 +134,9 @@ export function sanitizeHostEntry(raw, options = {}) {
|
|
|
108
134
|
existing?.hostKeyPolicy ?? settings.hostKeyPolicy,
|
|
109
135
|
)
|
|
110
136
|
return {
|
|
111
|
-
|
|
137
|
+
// A malformed or over-long id is never echoed: an id names the secrets entry, the proxy
|
|
138
|
+
// route and the client's host link, so only the shape this plugin issues is accepted.
|
|
139
|
+
id: typeof raw.id === 'string' && HOST_ID_RE.test(raw.id) ? raw.id : (existing?.id ?? undefined),
|
|
112
140
|
name: name || destination.host || destination.alias || 'remote',
|
|
113
141
|
address,
|
|
114
142
|
port: numberIn(raw.port ?? destination.port ?? existing?.port, 1, 65535, settings.defaultPort),
|