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
package/src/host-registry.js
CHANGED
|
@@ -6,9 +6,15 @@ import path from 'node:path'
|
|
|
6
6
|
import { errors } from './errors.js'
|
|
7
7
|
import { createHostRuntime } from './host-runtime.js'
|
|
8
8
|
import { hostView } from './host-view.js'
|
|
9
|
-
import { listKeyFiles as listKeyFilesInHome } from './key-files.js'
|
|
9
|
+
import { listKeyFiles as listKeyFilesInHome, OUTSIDE_HOME } from './key-files.js'
|
|
10
10
|
import { parseKnownHosts, summarizeKnownHosts } from './known-hosts.js'
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
cancelIdleStop,
|
|
13
|
+
cancelReconnect,
|
|
14
|
+
startRemoteHeartbeat,
|
|
15
|
+
stopRemoteHeartbeat,
|
|
16
|
+
teardownRuntime,
|
|
17
|
+
} from './host-lifecycle.js'
|
|
12
18
|
import { discoverSshAliases as discoverAliasesFromConfig, parseSshConfig } from './ssh-config.js'
|
|
13
19
|
|
|
14
20
|
function ensureRuntime(ctx, host) {
|
|
@@ -32,13 +38,37 @@ export async function initRegistry(ctx) {
|
|
|
32
38
|
if (ctx.state.initialized) return
|
|
33
39
|
await ctx.store.load()
|
|
34
40
|
for (const host of ctx.store.listHosts()) ensureRuntime(ctx, host)
|
|
41
|
+
// `passwordSaved` is a fact about the credential store, not about this process: without this
|
|
42
|
+
// read the Client would ask again after every DSH restart even though the password is saved,
|
|
43
|
+
// and the saved value would never be tried.
|
|
44
|
+
await restoreSavedPasswords(ctx)
|
|
35
45
|
ctx.state.initialized = true
|
|
36
46
|
}
|
|
37
47
|
|
|
48
|
+
/**
|
|
49
|
+
* Re-read which password-auth hosts have a saved password. Only presence is loaded; the secret
|
|
50
|
+
* itself stays in the credential store until a connection actually needs it.
|
|
51
|
+
* @param {object} ctx - service context.
|
|
52
|
+
*/
|
|
53
|
+
async function restoreSavedPasswords(ctx) {
|
|
54
|
+
if (!ctx.secrets) return
|
|
55
|
+
await Promise.all(
|
|
56
|
+
[...ctx.state.runtimes.values()].map(async (runtime) => {
|
|
57
|
+
if (runtime.entry.auth?.type !== 'password') {
|
|
58
|
+
runtime.passwordSaved = false
|
|
59
|
+
return
|
|
60
|
+
}
|
|
61
|
+
runtime.passwordSaved = await ctx.secrets.has(runtime.id)
|
|
62
|
+
}),
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
|
|
38
66
|
function hostViewFor(ctx, runtime) {
|
|
39
67
|
return hostView(runtime, {
|
|
40
68
|
targetVersion: ctx.localVersion(),
|
|
41
69
|
passwordStorageAvailable: ctx.secrets ? ctx.secrets.available() === true : false,
|
|
70
|
+
// A quarantined hosts.json means the list beside it is the empty recovery fallback.
|
|
71
|
+
storeCorrupt: ctx.store?.hostsCorrupt === true,
|
|
42
72
|
})
|
|
43
73
|
}
|
|
44
74
|
|
|
@@ -53,11 +83,22 @@ export function snapshot(ctx) {
|
|
|
53
83
|
settings: ctx.store.getSettings(),
|
|
54
84
|
activeHostId: ctx.state.activeHostId,
|
|
55
85
|
firstRun: hosts.length === 0,
|
|
86
|
+
/** Whether a password typed for any host can be persisted at all (the Client hides the choice). */
|
|
87
|
+
passwordStorageAvailable: ctx.secrets ? ctx.secrets.available() === true : false,
|
|
88
|
+
// Store-wide, and deliberately not per host: a quarantined hosts.json leaves this list
|
|
89
|
+
// empty, which is exactly the case the user has to be told about.
|
|
90
|
+
storeCorrupt: ctx.store?.hostsCorrupt === true,
|
|
56
91
|
}
|
|
57
92
|
}
|
|
58
93
|
|
|
59
94
|
export async function saveHost(ctx, rawHost) {
|
|
60
95
|
await ctx.init()
|
|
96
|
+
// The auth mode as it is stored now: a switch away from password must not leave its secret
|
|
97
|
+
// behind as an orphaned credential record.
|
|
98
|
+
const previousAuth =
|
|
99
|
+
rawHost && typeof rawHost === 'object' && typeof rawHost.id === 'string'
|
|
100
|
+
? (ctx.store.getHost(rawHost.id)?.auth?.type ?? null)
|
|
101
|
+
: null
|
|
61
102
|
let entry
|
|
62
103
|
try {
|
|
63
104
|
entry = await ctx.store.upsertHost(rawHost, { settings: ctx.store.getSettings() })
|
|
@@ -79,22 +120,33 @@ export async function saveHost(ctx, rawHost) {
|
|
|
79
120
|
en: `Invalid host entry: ${message}`,
|
|
80
121
|
})
|
|
81
122
|
}
|
|
82
|
-
ensureRuntime(ctx, entry)
|
|
123
|
+
const runtime = ensureRuntime(ctx, entry)
|
|
124
|
+
if (previousAuth === 'password' && entry.auth?.type !== 'password') {
|
|
125
|
+
await ctx.secrets?.remove(entry.id)
|
|
126
|
+
runtime.passwordSaved = false
|
|
127
|
+
runtime.password = null
|
|
128
|
+
}
|
|
83
129
|
ctx.emitState()
|
|
84
|
-
return hostViewFor(ctx,
|
|
130
|
+
return hostViewFor(ctx, runtime)
|
|
85
131
|
}
|
|
86
132
|
|
|
87
133
|
export async function removeHost(ctx, id) {
|
|
88
134
|
await ctx.init()
|
|
89
135
|
const runtime = ctx.state.runtimes.get(id)
|
|
90
136
|
if (runtime) {
|
|
91
|
-
// A deleted host must not be resurrected by a timer scheduled before deletion
|
|
137
|
+
// A deleted host must not be resurrected by a timer scheduled before deletion, and a
|
|
138
|
+
// connect pipeline still in flight must see that the user no longer wants it: it may
|
|
139
|
+
// never publish a connected state or a fresh `activeHostId` afterwards (H4).
|
|
140
|
+
runtime.desired = 'idle'
|
|
92
141
|
cancelReconnect(runtime)
|
|
93
142
|
cancelIdleStop(runtime)
|
|
143
|
+
if (ctx.state.activeHostId === id) ctx.state.activeHostId = null
|
|
94
144
|
await teardownRuntime(ctx, runtime, { stopRemote: runtime.entry.keepAlive === 'stop' })
|
|
95
145
|
}
|
|
96
146
|
ctx.state.runtimes.delete(id)
|
|
97
147
|
await ctx.store.removeHost(id)
|
|
148
|
+
// The host is gone: its saved password must not outlive it in the credential store.
|
|
149
|
+
await ctx.secrets?.remove(id)
|
|
98
150
|
if (ctx.state.activeHostId === id) ctx.state.activeHostId = null
|
|
99
151
|
ctx.emitState()
|
|
100
152
|
return { ok: true }
|
|
@@ -109,6 +161,12 @@ export function setActiveHost(ctx, id) {
|
|
|
109
161
|
export async function saveSettings(ctx, patch) {
|
|
110
162
|
await ctx.init()
|
|
111
163
|
const settings = await ctx.store.saveSettings(patch)
|
|
164
|
+
// The liveness switch applies to hosts that are already connected, not just the next one.
|
|
165
|
+
for (const runtime of ctx.state.runtimes.values()) {
|
|
166
|
+
if (runtime.status !== 'connected') continue
|
|
167
|
+
if (settings.remoteHeartbeat.enabled) startRemoteHeartbeat(ctx, runtime)
|
|
168
|
+
else stopRemoteHeartbeat(runtime)
|
|
169
|
+
}
|
|
112
170
|
ctx.emitState()
|
|
113
171
|
return settings
|
|
114
172
|
}
|
|
@@ -121,7 +179,21 @@ export async function listKeyFiles(ctx, dir) {
|
|
|
121
179
|
// The picker is rooted at the OS user home, not DSH_HOME: private keys live in
|
|
122
180
|
// `~/.ssh` of the account, while the service's `home` is the DSH state root.
|
|
123
181
|
const userHome = homedir()
|
|
124
|
-
|
|
182
|
+
let listing
|
|
183
|
+
try {
|
|
184
|
+
listing = await listKeyFilesInHome({ home: userHome, dir: typeof dir === 'string' ? dir : '' })
|
|
185
|
+
} catch (error) {
|
|
186
|
+
// A path outside the home directory (`C:\Windows`, `..`, a symlink escape) or an
|
|
187
|
+
// unreadable one is the caller's mistake: answer 400 instead of turning a bare `Error`
|
|
188
|
+
// into a 500, and never echo the requested path back in `technical`.
|
|
189
|
+
if (error?.code === OUTSIDE_HOME || ['ENOENT', 'EACCES', 'EPERM', 'ENOTDIR'].includes(error?.code)) {
|
|
190
|
+
throw errors.invalidInput('path', {
|
|
191
|
+
zh: '这个目录不在用户主目录内,或无法读取。',
|
|
192
|
+
en: 'This folder is outside the home directory, or cannot be read.',
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
throw error
|
|
196
|
+
}
|
|
125
197
|
const settings = ctx.store.getSettings()
|
|
126
198
|
return { ...listing, defaultKeyPath: settings.defaultKeyPath, defaultDir: path.join(userHome, '.ssh') }
|
|
127
199
|
}
|
package/src/host-runtime.js
CHANGED
|
@@ -15,6 +15,12 @@ export function emptyRemote() {
|
|
|
15
15
|
nodeVersion: null,
|
|
16
16
|
nodeSource: null,
|
|
17
17
|
startedAt: null,
|
|
18
|
+
/**
|
|
19
|
+
* Bumped on every successful attach (connect, local restart, remote re-attach).
|
|
20
|
+
* The Client uses it to know that its warm carrier holds a launch URL and a
|
|
21
|
+
* session cookie from the previous tunnel, so it must navigate again.
|
|
22
|
+
*/
|
|
23
|
+
viewRev: 0,
|
|
18
24
|
}
|
|
19
25
|
}
|
|
20
26
|
|
|
@@ -30,24 +36,92 @@ export function createHostRuntime(host) {
|
|
|
30
36
|
fingerprint: host.pinnedFingerprint
|
|
31
37
|
? { sha256: host.pinnedFingerprint, keyType: 'pinned', status: 'pinned', pinned: host.pinnedFingerprint }
|
|
32
38
|
: null,
|
|
39
|
+
/**
|
|
40
|
+
* The jump host's own host key context: `{ sha256, keyType, status, pinned }`. Kept apart
|
|
41
|
+
* from `fingerprint` (the target) so a jump-host confirmation can never pin the target
|
|
42
|
+
* and a target pin can never be checked against the jump host (B1).
|
|
43
|
+
*/
|
|
44
|
+
jumpFingerprint: null,
|
|
33
45
|
remote: emptyRemote(),
|
|
34
46
|
ssh: null,
|
|
35
47
|
jumpSsh: null,
|
|
36
48
|
tunnel: null,
|
|
37
49
|
token: null,
|
|
38
50
|
password: null,
|
|
51
|
+
/**
|
|
52
|
+
* What to do with `password` once SSH accepts it: write it to the credential store, or
|
|
53
|
+
* remove the stored record (an explicit "this connection only"). Both reset per attempt.
|
|
54
|
+
*/
|
|
55
|
+
savePassword: false,
|
|
56
|
+
forgetPassword: false,
|
|
57
|
+
/** Mirrors the credential store for `HostView.passwordSaved` (restored on load). */
|
|
58
|
+
passwordSaved: false,
|
|
39
59
|
facts: null,
|
|
60
|
+
/**
|
|
61
|
+
* The last known remote home, managed web pid and profile. `facts`/`remote` are cleared by
|
|
62
|
+
* every teardown, but the idle policy still has to prove and stop the right process on the
|
|
63
|
+
* right host path afterwards (H1).
|
|
64
|
+
*/
|
|
65
|
+
remoteHome: null,
|
|
66
|
+
remotePid: null,
|
|
67
|
+
remoteProfile: null,
|
|
40
68
|
exchange: null,
|
|
41
69
|
pendingHostKey: null,
|
|
42
70
|
pendingConflict: null,
|
|
43
71
|
conflict: null,
|
|
44
72
|
desired: 'idle',
|
|
73
|
+
/**
|
|
74
|
+
* The user answered a prompt with "no" (or let it time out): the connection attempt must
|
|
75
|
+
* not be retried automatically, because a retry would ask the same question again (H2).
|
|
76
|
+
*/
|
|
77
|
+
connectCancelled: false,
|
|
78
|
+
/**
|
|
79
|
+
* The transport this attempt was dialling closed under the pipeline (including while the
|
|
80
|
+
* handshake was still waiting for a host-key answer). Such a failure is a dropped link,
|
|
81
|
+
* not an auth/key decision (H3).
|
|
82
|
+
*/
|
|
83
|
+
transportLost: false,
|
|
45
84
|
reconnectAttempts: 0,
|
|
46
85
|
reconnectTimer: null,
|
|
47
86
|
idleTimer: null,
|
|
48
87
|
connectPromise: null,
|
|
88
|
+
/** One-shot link actions (local restart / remote re-attach / listener repair / stop) and their token. */
|
|
89
|
+
linkBusy: null,
|
|
90
|
+
linkToken: 0,
|
|
91
|
+
restartPromise: null,
|
|
92
|
+
reattachPromise: null,
|
|
93
|
+
/**
|
|
94
|
+
* Processes this connection actually launched (pid -> start time), plus pids adopted from a
|
|
95
|
+
* registry record written by a launch. Only these may ever be stopped; a pid a re-attach
|
|
96
|
+
* discovered gets display rights, never kill rights.
|
|
97
|
+
*/
|
|
98
|
+
launched: new Map(),
|
|
99
|
+
/**
|
|
100
|
+
* The remote web this connection is bound to, with the `/proc` identity proved when it bound:
|
|
101
|
+
* `{ pid, startTime, origin: 'launch' | 'reattach' }`. A re-attached pid lives here (never in
|
|
102
|
+
* `launched`), so the explicit "Stop remote DSH" action can stop exactly that one process
|
|
103
|
+
* without granting the kill right to a restart.
|
|
104
|
+
*/
|
|
105
|
+
bound: null,
|
|
106
|
+
/** Current tunnel repair (a broken local listener under a healthy remote). */
|
|
107
|
+
tunnelRepair: null,
|
|
108
|
+
tunnelRepairFailures: 0,
|
|
109
|
+
nextTunnelRepairAt: 0,
|
|
110
|
+
/** Liveness probes: a confirmed episode is two consecutive failed probes. */
|
|
111
|
+
heartbeatTimer: null,
|
|
112
|
+
remoteCheckTimer: null,
|
|
113
|
+
remoteFailures: 0,
|
|
114
|
+
remoteEpisode: false,
|
|
115
|
+
episodeSource: null,
|
|
116
|
+
episodeCooldownUntil: 0,
|
|
117
|
+
/** Processes kept alongside this connection (chosen in the conflict prompt). */
|
|
118
|
+
alongsidePids: [],
|
|
119
|
+
/** Bounded, client-independent record of restarts / re-attaches for diagnostics. */
|
|
120
|
+
restarts: [],
|
|
49
121
|
closing: false,
|
|
50
122
|
logs: [],
|
|
51
123
|
logSeq: 0,
|
|
124
|
+
// Which connection this runtime is on; the connect log starts at 1 and resets its ring.
|
|
125
|
+
connectCount: 0,
|
|
52
126
|
}
|
|
53
127
|
}
|
package/src/host-view.js
CHANGED
|
@@ -11,12 +11,23 @@ export function hostView(runtime, ctx) {
|
|
|
11
11
|
name: entry.name,
|
|
12
12
|
address: entry.address,
|
|
13
13
|
addressMasked: maskAddress(entry),
|
|
14
|
+
/**
|
|
15
|
+
* The plain connection fields. The masked address is presentation only: the editor must not
|
|
16
|
+
* parse it back (a bare IPv6 like `fe80::1` used to yield port 1, and the default port was
|
|
17
|
+
* silently replaced by 22). Never a secret.
|
|
18
|
+
*/
|
|
19
|
+
username: entry.username ?? null,
|
|
20
|
+
port: entry.port ?? 22,
|
|
14
21
|
/** Never the secret itself; lets the Client ask for a one-time password. */
|
|
15
22
|
authType: entry.auth?.type ?? 'key',
|
|
16
23
|
/** The configured key file path (not a secret); lets the edit form prefill it. */
|
|
17
24
|
authKeyPath: entry.auth?.type === 'key' && typeof entry.auth.keyPath === 'string' ? entry.auth.keyPath : null,
|
|
18
|
-
/**
|
|
19
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Whether a remembered password exists in the credential store (never the value). The
|
|
27
|
+
* runtime mirror is restored from the store on load, so this stays true across a DSH
|
|
28
|
+
* restart while a one-time password used for this connection alone stays false.
|
|
29
|
+
*/
|
|
30
|
+
passwordSaved: entry.auth?.type === 'password' ? runtime.passwordSaved === true : false,
|
|
20
31
|
passwordStorageAvailable: ctx.passwordStorageAvailable,
|
|
21
32
|
jumpHost: entry.jumpHost ?? null,
|
|
22
33
|
status: runtime.status,
|
|
@@ -40,12 +51,25 @@ export function hostView(runtime, ctx) {
|
|
|
40
51
|
updatedAt: entry.updatedAt,
|
|
41
52
|
targetVersion: ctx.targetVersion,
|
|
42
53
|
versionParity: versionParity(ctx.targetVersion, runtime.remote.version ?? null),
|
|
54
|
+
/**
|
|
55
|
+
* True when `hosts.json` was unreadable on load: this list is the recovered fallback, and a
|
|
56
|
+
* copy of the damaged file is kept next to it (`hosts.json.corrupt-<timestamp>`). Contract
|
|
57
|
+
* field only — the Client renders it as a warning (docs/api.md HostView).
|
|
58
|
+
*/
|
|
59
|
+
storeCorrupt: ctx.storeCorrupt === true,
|
|
43
60
|
}
|
|
44
61
|
}
|
|
45
62
|
|
|
46
|
-
|
|
63
|
+
/**
|
|
64
|
+
* The display form of the endpoint: `user@host`, `user@host:2222`, and bracketed IPv6
|
|
65
|
+
* (`user@[fe80::1]`, `user@[fe80::1]:2222`). The port is omitted only for SSH's default 22, which
|
|
66
|
+
* is why the Client reads `port`/`username` instead of parsing this string.
|
|
67
|
+
*/
|
|
68
|
+
export function maskAddress(entry) {
|
|
47
69
|
const port = entry.port && entry.port !== 22 ? `:${entry.port}` : ''
|
|
48
70
|
const user = entry.username ? `${entry.username}@` : ''
|
|
49
|
-
const
|
|
71
|
+
const raw = entry.address || '?'
|
|
72
|
+
// An unbracketed address containing a colon is IPv6 in URL/SSH notation.
|
|
73
|
+
const host = raw.includes(':') && !(raw.startsWith('[') && raw.endsWith(']')) ? `[${raw}]` : raw
|
|
50
74
|
return `${user}${host}${port}`
|
|
51
75
|
}
|
package/src/index.js
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* dsh-remote-go — Host half: registers the local HTTP API
|
|
2
|
+
* dsh-remote-go — Host half: registers the local HTTP API and the browser half's same-origin remote proxy,
|
|
3
|
+
* and owns the SSH / bootstrap / tunnel lifecycle; it never copies remote data.
|
|
3
4
|
*/
|
|
4
|
-
import { API_PREFIX, PLUGIN_ID } from './constants.js'
|
|
5
|
+
import { API_PREFIX, PLUGIN_ID, REMOTE_VIEW_PREFIX } from './constants.js'
|
|
5
6
|
import { statSync } from 'node:fs'
|
|
6
|
-
import
|
|
7
|
+
import { createAdmission } from './admission.js'
|
|
7
8
|
import { createApi } from './api.js'
|
|
8
9
|
import { detectLocalEnginesNode, detectLocalVersion } from './local-version.js'
|
|
10
|
+
import { createRemoteProxy } from './remote-proxy.js'
|
|
9
11
|
import { RemoteGoService } from './service.js'
|
|
10
12
|
import { createSecretStore } from './secrets.js'
|
|
11
13
|
import { HostStore, resolveDshHome, resolveStateDir } from './store.js'
|
|
14
|
+
import { registerHostTools } from './tools.js'
|
|
12
15
|
import { messageOf } from './util.js'
|
|
13
16
|
|
|
14
17
|
export const name = PLUGIN_ID
|
|
@@ -38,9 +41,14 @@ export function apply(ctx, config = {}) {
|
|
|
38
41
|
return null
|
|
39
42
|
}
|
|
40
43
|
}
|
|
44
|
+
// DSH's own admission for every route this plugin serves: the kernel's Host/Origin fence plus
|
|
45
|
+
// browser-session authentication. `connection` is optional, so the gate hands the request to the
|
|
46
|
+
// plugin's own fence when the service is absent (see admission.js).
|
|
47
|
+
const admit = createAdmission(ctx, logger)
|
|
41
48
|
const api = createApi({
|
|
42
49
|
service,
|
|
43
50
|
getOrigin,
|
|
51
|
+
admit,
|
|
44
52
|
logger,
|
|
45
53
|
diagnostics: () =>
|
|
46
54
|
describeSelf(ctx, {
|
|
@@ -48,8 +56,20 @@ export function apply(ctx, config = {}) {
|
|
|
48
56
|
stateDir,
|
|
49
57
|
localVersion: service.localVersion,
|
|
50
58
|
engineNodeRange: service.engineNodeRange,
|
|
59
|
+
storeCorrupt: store.hostsCorrupt,
|
|
51
60
|
}),
|
|
52
61
|
})
|
|
62
|
+
// The browser half's remote window lives on the local origin (the desktop half uses a guest
|
|
63
|
+
// instead), so the same-origin proxy is the only thing that needs to know how to reach a tunnel.
|
|
64
|
+
const proxy = createRemoteProxy({
|
|
65
|
+
webServer: ctx.webServer,
|
|
66
|
+
getOrigin,
|
|
67
|
+
admit,
|
|
68
|
+
resolveHost: (id) => service.webViewTarget(id),
|
|
69
|
+
// A failed upstream is a suspicion, not a restart: the service confirms it with probes.
|
|
70
|
+
onUpstreamError: (id) => service.noteUpstreamFailure(id),
|
|
71
|
+
logger,
|
|
72
|
+
})
|
|
53
73
|
|
|
54
74
|
ctx.effect(() => {
|
|
55
75
|
const disposeRoute = ctx.webServer.register({
|
|
@@ -59,11 +79,23 @@ export function apply(ctx, config = {}) {
|
|
|
59
79
|
void api.handler(req, res)
|
|
60
80
|
},
|
|
61
81
|
})
|
|
82
|
+
const disposeView = ctx.webServer.register({
|
|
83
|
+
kind: 'prefix',
|
|
84
|
+
path: proxy.routePath,
|
|
85
|
+
handler: (/** @type {any} */ req, /** @type {any} */ res) => proxy.handle(req, res),
|
|
86
|
+
})
|
|
87
|
+
// The model-facing host list lives on the Host half only: a local LLM session reads the same
|
|
88
|
+
// snapshot the switcher renders, and the remote DSH never loads this package.
|
|
89
|
+
const disposeTools = registerHostTools(ctx, { service, logger })
|
|
90
|
+
const syncViewRoutes = () => proxy.sync(service.hostIds())
|
|
91
|
+
service.on('state', syncViewRoutes)
|
|
62
92
|
logger.info(`API mounted at ${API_PREFIX} (state dir ${stateDir})`)
|
|
93
|
+
logger.info(`remote view mounted at ${REMOTE_VIEW_PREFIX}<host> (browser carrier)`)
|
|
63
94
|
|
|
64
95
|
void (async () => {
|
|
65
96
|
try {
|
|
66
97
|
await service.init()
|
|
98
|
+
syncViewRoutes()
|
|
67
99
|
const detected = await detectLocalVersion({ ctx })
|
|
68
100
|
if (detected.version) service.setLocalVersion(detected.version, detected.source)
|
|
69
101
|
// The managed Node version is the lower bound of DSH's own `engines.node`;
|
|
@@ -80,9 +112,19 @@ export function apply(ctx, config = {}) {
|
|
|
80
112
|
})()
|
|
81
113
|
|
|
82
114
|
return () => {
|
|
115
|
+
service.removeListener('state', syncViewRoutes)
|
|
116
|
+
// A failing disposer must not skip the rest of the unload: the proxy, the API and the SSH
|
|
117
|
+
// transports below still have to be released.
|
|
118
|
+
try {
|
|
119
|
+
disposeTools()
|
|
120
|
+
} catch (error) {
|
|
121
|
+
logger.error('unload: could not dispose the model tools:', error)
|
|
122
|
+
}
|
|
123
|
+
proxy.dispose()
|
|
83
124
|
api.dispose()
|
|
84
125
|
void service.shutdown()
|
|
85
126
|
disposeRoute()
|
|
127
|
+
disposeView()
|
|
86
128
|
logger.info('unloaded')
|
|
87
129
|
}
|
|
88
130
|
}, 'dsh-remote-go: http api + service')
|
|
@@ -96,6 +138,8 @@ function describeSelf(ctx, info) {
|
|
|
96
138
|
stateDir: info.stateDir,
|
|
97
139
|
hostVersion: info.localVersion,
|
|
98
140
|
engineNodeRange: info.engineNodeRange ?? null,
|
|
141
|
+
// True when hosts.json was unreadable and the list beside it is the recovered fallback.
|
|
142
|
+
storeCorrupt: info.storeCorrupt === true,
|
|
99
143
|
entry: null,
|
|
100
144
|
client: null,
|
|
101
145
|
}
|
package/src/key-files.js
CHANGED
|
@@ -7,6 +7,9 @@ import { expandHome } from './util.js'
|
|
|
7
7
|
|
|
8
8
|
const MAX_ENTRIES = 500
|
|
9
9
|
|
|
10
|
+
/** Code of the "not inside the home directory" refusal, so callers can map it to an HTTP 400. */
|
|
11
|
+
export const OUTSIDE_HOME = 'EOUTSIDEHOME'
|
|
12
|
+
|
|
10
13
|
export async function listKeyFiles(options) {
|
|
11
14
|
const home = path.resolve(options.home)
|
|
12
15
|
const impl = options.fsImpl ?? fs
|
|
@@ -21,7 +24,9 @@ export async function listKeyFiles(options) {
|
|
|
21
24
|
// that does not exist keeps its requested spelling, which the check still judges.
|
|
22
25
|
const realTarget = await impl.realpath(target).catch(() => target)
|
|
23
26
|
if (realTarget !== realHome && !realTarget.startsWith(realHome + path.sep)) {
|
|
24
|
-
|
|
27
|
+
const error = new Error('key-file path must stay inside the home directory')
|
|
28
|
+
error.code = OUTSIDE_HOME
|
|
29
|
+
throw error
|
|
25
30
|
}
|
|
26
31
|
|
|
27
32
|
const dirents = await impl.readdir(realTarget, { withFileTypes: true })
|
package/src/known-hosts.js
CHANGED
|
@@ -61,18 +61,57 @@ export function parseKnownHosts(text) {
|
|
|
61
61
|
return { entries, hashedCount, malformed, revoked, certAuthority }
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
/**
|
|
65
|
+
* OpenSSH `known_hosts` host-field matching: `*` matches any run of characters, `?` exactly
|
|
66
|
+
* one, everything else is literal and the comparison ignores case.
|
|
67
|
+
*
|
|
68
|
+
* Implemented without a regular expression on purpose: a host field is data, and building a
|
|
69
|
+
* `RegExp` from it invites injection and backtracking on remote-controlled text.
|
|
70
|
+
* @param {string} pattern - one host field.
|
|
71
|
+
* @param {string} value - the host field form being matched (plain or `[host]:port`).
|
|
72
|
+
* @returns {boolean} whether the pattern covers the value.
|
|
73
|
+
*/
|
|
74
|
+
function wildcardMatch(pattern, value) {
|
|
75
|
+
const wanted = String(pattern).toLowerCase()
|
|
76
|
+
const text = String(value).toLowerCase()
|
|
77
|
+
let patternAt = 0
|
|
78
|
+
let textAt = 0
|
|
79
|
+
let starAt = -1
|
|
80
|
+
let markAt = 0
|
|
81
|
+
while (textAt < text.length) {
|
|
82
|
+
if (patternAt < wanted.length && (wanted[patternAt] === '?' || wanted[patternAt] === text[textAt])) {
|
|
83
|
+
patternAt += 1
|
|
84
|
+
textAt += 1
|
|
85
|
+
} else if (patternAt < wanted.length && wanted[patternAt] === '*') {
|
|
86
|
+
starAt = patternAt
|
|
87
|
+
patternAt += 1
|
|
88
|
+
markAt = textAt
|
|
89
|
+
} else if (starAt >= 0) {
|
|
90
|
+
patternAt = starAt + 1
|
|
91
|
+
textAt = markAt + 1
|
|
92
|
+
markAt = textAt
|
|
93
|
+
} else {
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
while (patternAt < wanted.length && wanted[patternAt] === '*') patternAt += 1
|
|
98
|
+
return patternAt === wanted.length
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Whether one `known_hosts` host field covers `host` on `port`.
|
|
103
|
+
*
|
|
104
|
+
* OpenSSH writes a plain `host` field only for port 22 and `[host]:port` for every other
|
|
105
|
+
* port, and it matches the same way: a plain entry never vouches for a service on 2222.
|
|
106
|
+
* @param {string} pattern - one (possibly wildcarded) host field.
|
|
107
|
+
* @param {string} host - the host being dialled.
|
|
108
|
+
* @param {number | string | null | undefined} port - the port being dialled.
|
|
109
|
+
* @returns {boolean} whether the field covers that destination.
|
|
110
|
+
*/
|
|
64
111
|
export function knownHostFieldMatches(pattern, host, port) {
|
|
65
|
-
const
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
// behavior; be conservative and require the bracketed form for non-22.
|
|
69
|
-
candidates.push(host, `[${host}]`)
|
|
70
|
-
const escaped = String(pattern)
|
|
71
|
-
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
72
|
-
.replace(/\*/g, '.*')
|
|
73
|
-
.replace(/\?/g, '.')
|
|
74
|
-
const matcher = new RegExp(`^${escaped}$`, 'i')
|
|
75
|
-
return candidates.some((candidate) => matcher.test(candidate))
|
|
112
|
+
const targetPort = Number(port) || 22
|
|
113
|
+
const target = targetPort === 22 ? String(host) : `[${host}]:${targetPort}`
|
|
114
|
+
return wildcardMatch(pattern, target)
|
|
76
115
|
}
|
|
77
116
|
|
|
78
117
|
export function findKnownHostEntries(parsed, host, port) {
|
package/src/layout.js
CHANGED
|
@@ -2,9 +2,28 @@
|
|
|
2
2
|
* Remote directory layout: everything the plugin writes lives under `$DSH_HOME/remote-go`, so a host only gets `~/.dsh` plus that one subdirectory.
|
|
3
3
|
*/
|
|
4
4
|
import { REMOTE_DSH_DIR, REMOTE_STATE_DIR } from './constants.js'
|
|
5
|
+
import { errors } from './errors.js'
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Build the remote layout for a known home directory.
|
|
9
|
+
*
|
|
10
|
+
* The home has to be a real absolute path: an unexpanded `~` is not expanded by a
|
|
11
|
+
* non-interactive shell, so a layout built without it would silently address a literal
|
|
12
|
+
* `~` directory (`kill -0` a `~`-path pid is a no-op that still exits 0). Refusing here
|
|
13
|
+
* keeps every caller honest instead of pretending such a command worked.
|
|
14
|
+
*
|
|
15
|
+
* @param {string} home - the remote user's absolute home directory.
|
|
16
|
+
* @returns {{ root: string, stateHome: string, dshHome: string, nodeDir: string,
|
|
17
|
+
* downloadDir: string, logsDir: string, logFile: string, runDir: string, runFile: string }}
|
|
18
|
+
*/
|
|
19
|
+
export function remoteLayout(home) {
|
|
20
|
+
const base = typeof home === 'string' ? home.trim().replace(/\/+$/, '') : ''
|
|
21
|
+
if (!base.startsWith('/')) {
|
|
22
|
+
throw errors.internal(
|
|
23
|
+
new Error(`the remote home directory is unknown (${JSON.stringify(home)}); refusing to build a "~" layout`),
|
|
24
|
+
)
|
|
25
|
+
}
|
|
26
|
+
const dshHome = `${base}/${REMOTE_DSH_DIR}`
|
|
8
27
|
const root = `${dshHome}/${REMOTE_STATE_DIR}`
|
|
9
28
|
return {
|
|
10
29
|
root,
|
|
@@ -23,13 +42,12 @@ export function remoteLayout(home = null) {
|
|
|
23
42
|
}
|
|
24
43
|
|
|
25
44
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
45
|
+
* The layout a host runtime describes: the facts its live connection probed, or the home
|
|
46
|
+
* it remembered before those facts were cleared (keep-alive / idle policy).
|
|
47
|
+
* @param {{ facts?: { home?: string } | null, remoteHome?: string | null }} runtime
|
|
48
|
+
* @returns {ReturnType<typeof remoteLayout>}
|
|
28
49
|
*/
|
|
29
|
-
function
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
if (text === '~') return home
|
|
33
|
-
if (text.startsWith('~/')) return `${home.replace(/\/+$/, '')}/${text.slice(2)}`
|
|
34
|
-
return text
|
|
50
|
+
export function layoutForRuntime(runtime) {
|
|
51
|
+
const home = runtime?.facts?.home ?? runtime?.remoteHome ?? null
|
|
52
|
+
return remoteLayout(home)
|
|
35
53
|
}
|