dsh-remote-go 0.2.0 → 0.3.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 +11 -3
- package/{client.js → dist/client.js} +7710 -8182
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/{src → dist/src}/constants.js +30 -56
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -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/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
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host registry: the configured hosts, their runtime objects and the client-facing snapshot; reads are pure, writes re-emit the snapshot after `store`.
|
|
3
|
+
*/
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { errors } from './errors.js';
|
|
7
|
+
import { createHostRuntime } from './host-runtime.js';
|
|
8
|
+
import { hostView } from './host-view.js';
|
|
9
|
+
import { listKeyFiles as listKeyFilesInHome, OUTSIDE_HOME } from './key-files.js';
|
|
10
|
+
import { parseKnownHosts, summarizeKnownHosts } from './known-hosts.js';
|
|
11
|
+
import { stopRemoteHeartbeat } from './host-lifecycle.js';
|
|
12
|
+
import { dispatch, scopeFactsFor } from './runtime/dispatch.js';
|
|
13
|
+
import { createRuntimeEffects } from './runtime/effects.js';
|
|
14
|
+
import { discoverSshAliases as discoverAliasesFromConfig, parseSshConfig } from './ssh-config.js';
|
|
15
|
+
import { startRemoteHeartbeat } from './watchdog.js';
|
|
16
|
+
function ensureRuntime(ctx, host) {
|
|
17
|
+
const existing = ctx.state.runtimes.get(host.id);
|
|
18
|
+
if (existing) {
|
|
19
|
+
existing.entry = host;
|
|
20
|
+
return existing;
|
|
21
|
+
}
|
|
22
|
+
// The store issues the id (`sanitizeHostEntry`) and the runtime map is keyed by it; an entry
|
|
23
|
+
// without one can only come from a caller that never saved it, never from `listHosts`.
|
|
24
|
+
const runtime = createHostRuntime(host);
|
|
25
|
+
ctx.state.runtimes.set(host.id, runtime);
|
|
26
|
+
return runtime;
|
|
27
|
+
}
|
|
28
|
+
export function runtimeOf(ctx, id) {
|
|
29
|
+
const runtime = ctx.state.runtimes.get(id);
|
|
30
|
+
if (!runtime)
|
|
31
|
+
throw errors.invalidInput('id', { zh: `未知主机 ${id}`, en: `Unknown host ${id}` });
|
|
32
|
+
return runtime;
|
|
33
|
+
}
|
|
34
|
+
export async function initRegistry(ctx) {
|
|
35
|
+
if (ctx.state.initialized)
|
|
36
|
+
return;
|
|
37
|
+
await ctx.store.load();
|
|
38
|
+
for (const host of ctx.store.listHosts())
|
|
39
|
+
ensureRuntime(ctx, host);
|
|
40
|
+
// `passwordSaved` is a fact about the credential store, not about this process: without this
|
|
41
|
+
// read the Client would ask again after every DSH restart even though the password is saved,
|
|
42
|
+
// and the saved value would never be tried.
|
|
43
|
+
await restoreSavedPasswords(ctx);
|
|
44
|
+
ctx.state.initialized = true;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Re-read which password-auth hosts have a saved password. Only presence is loaded; the secret
|
|
48
|
+
* itself stays in the credential store until a connection actually needs it.
|
|
49
|
+
* @param ctx - service context.
|
|
50
|
+
*/
|
|
51
|
+
async function restoreSavedPasswords(ctx) {
|
|
52
|
+
if (!ctx.secrets)
|
|
53
|
+
return;
|
|
54
|
+
await Promise.all([...ctx.state.runtimes.values()].map(async (runtime) => {
|
|
55
|
+
if (runtime.entry.auth?.type !== 'password') {
|
|
56
|
+
runtime.passwordSaved = false;
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
runtime.passwordSaved = await ctx.secrets.has(runtime.id);
|
|
60
|
+
}));
|
|
61
|
+
}
|
|
62
|
+
function hostViewFor(ctx, runtime, options = {}) {
|
|
63
|
+
return hostView(runtime, {
|
|
64
|
+
targetVersion: ctx.localVersion(),
|
|
65
|
+
passwordStorageAvailable: ctx.secrets ? ctx.secrets.available() === true : false,
|
|
66
|
+
// A quarantined hosts.json means the list beside it is the empty recovery fallback.
|
|
67
|
+
storeCorrupt: ctx.store?.hostsCorrupt === true,
|
|
68
|
+
}, options);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Build the client-facing state snapshot (contract: docs/api.md).
|
|
72
|
+
* @param ctx - the service context.
|
|
73
|
+
* @param options - `logs: false` strips every tail (the SSE state frame's shape).
|
|
74
|
+
*/
|
|
75
|
+
export function snapshot(ctx, options = {}) {
|
|
76
|
+
const localVersion = ctx.localVersion();
|
|
77
|
+
const hosts = [...ctx.state.runtimes.values()].map((runtime) => hostViewFor(ctx, runtime, options));
|
|
78
|
+
return {
|
|
79
|
+
hostVersion: localVersion,
|
|
80
|
+
targetVersion: localVersion,
|
|
81
|
+
hosts,
|
|
82
|
+
settings: ctx.store.getSettings(),
|
|
83
|
+
activeHostId: ctx.state.activeHostId,
|
|
84
|
+
firstRun: hosts.length === 0,
|
|
85
|
+
/** Whether a password typed for any host can be persisted at all (the Client hides the choice). */
|
|
86
|
+
passwordStorageAvailable: ctx.secrets ? ctx.secrets.available() === true : false,
|
|
87
|
+
// Store-wide, and deliberately not per host: a quarantined hosts.json leaves this list
|
|
88
|
+
// empty, which is exactly the case the user has to be told about.
|
|
89
|
+
storeCorrupt: ctx.store?.hostsCorrupt === true,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export async function saveHost(ctx, rawHost) {
|
|
93
|
+
await ctx.init();
|
|
94
|
+
// The auth mode as it is stored now: a switch away from password must not leave its secret
|
|
95
|
+
// behind as an orphaned credential record.
|
|
96
|
+
const previousAuth = rawHost && typeof rawHost === 'object' && typeof rawHost.id === 'string'
|
|
97
|
+
? (ctx.store.getHost(rawHost.id)?.auth?.type ?? null)
|
|
98
|
+
: null;
|
|
99
|
+
let entry;
|
|
100
|
+
try {
|
|
101
|
+
entry = await ctx.store.upsertHost(rawHost, { settings: ctx.store.getSettings() });
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
// The store's validators throw bare messages; map them to the client's field
|
|
105
|
+
// errors here so the contract stays typed.
|
|
106
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
107
|
+
if (message === 'address is required') {
|
|
108
|
+
throw errors.invalidInput('address', {
|
|
109
|
+
zh: '请填写服务器地址或 ~/.ssh/config 别名。',
|
|
110
|
+
en: 'Enter a server address or an ~/.ssh/config alias.',
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
if (message === 'address is invalid') {
|
|
114
|
+
throw errors.invalidInput('address', { zh: '服务器地址格式不正确。', en: 'The server address is not valid.' });
|
|
115
|
+
}
|
|
116
|
+
throw errors.invalidInput('host', {
|
|
117
|
+
zh: `主机配置不合法:${message}`,
|
|
118
|
+
en: `Invalid host entry: ${message}`,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
const runtime = ensureRuntime(ctx, entry);
|
|
122
|
+
if (previousAuth === 'password' && entry.auth?.type !== 'password') {
|
|
123
|
+
await ctx.secrets?.remove(entry.id);
|
|
124
|
+
runtime.passwordSaved = false;
|
|
125
|
+
runtime.password = null;
|
|
126
|
+
}
|
|
127
|
+
ctx.emitState();
|
|
128
|
+
return hostViewFor(ctx, runtime);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Delete one host. It is the whole context, not a slice: the teardown it runs needs the watchdog's
|
|
132
|
+
* five slices (`createRuntimeEffects`/`scopeFactsFor`) and the deletion itself needs `Store`, so
|
|
133
|
+
* `Store & TeardownCtx` was the full six written the long way. The gate registers this function
|
|
134
|
+
* (`godCtxParams` in the architecture budget) rather than pretending it is narrow.
|
|
135
|
+
*/
|
|
136
|
+
export async function removeHost(ctx, id) {
|
|
137
|
+
await ctx.init();
|
|
138
|
+
const runtime = ctx.state.runtimes.get(id);
|
|
139
|
+
if (runtime) {
|
|
140
|
+
// A deleted host must not be resurrected by a timer scheduled before deletion, and a
|
|
141
|
+
// connect pipeline still in flight must see that the user no longer wants it: it may
|
|
142
|
+
// never publish a connected state or a fresh `activeHostId` afterwards (H4).
|
|
143
|
+
if (ctx.state.activeHostId === id)
|
|
144
|
+
ctx.state.activeHostId = null;
|
|
145
|
+
// `host.removed` owns the desired flag, the token bump, the timer disarms, the prompt
|
|
146
|
+
// settlement and the teardown; the frame is published below with the host already gone, so
|
|
147
|
+
// this call must not emit on its own.
|
|
148
|
+
const event = { type: 'host.removed', keepAlive: runtime.entry.keepAlive };
|
|
149
|
+
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
150
|
+
caller: 'silent',
|
|
151
|
+
emit: false,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
ctx.state.runtimes.delete(id);
|
|
155
|
+
await ctx.store.removeHost(id);
|
|
156
|
+
// The host is gone: its saved password must not outlive it in the credential store.
|
|
157
|
+
await ctx.secrets?.remove(id);
|
|
158
|
+
if (ctx.state.activeHostId === id)
|
|
159
|
+
ctx.state.activeHostId = null;
|
|
160
|
+
ctx.emitState();
|
|
161
|
+
return { ok: true };
|
|
162
|
+
}
|
|
163
|
+
export function setActiveHost(ctx, id) {
|
|
164
|
+
if (id !== null && !ctx.state.runtimes.has(id))
|
|
165
|
+
throw errors.invalidInput('id');
|
|
166
|
+
ctx.state.activeHostId = id;
|
|
167
|
+
ctx.emitState();
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Persist settings and restart the heartbeat of every connected host. Saving needs `Store`; the
|
|
171
|
+
* heartbeat policy needs the watchdog's slice set, so the two together are the whole context (the
|
|
172
|
+
* gate's `godCtxParams` entry names it).
|
|
173
|
+
*/
|
|
174
|
+
export async function saveSettings(ctx, patch) {
|
|
175
|
+
await ctx.init();
|
|
176
|
+
const settings = await ctx.store.saveSettings(patch);
|
|
177
|
+
// The liveness switch applies to hosts that are already connected, not just the next one.
|
|
178
|
+
for (const runtime of ctx.state.runtimes.values()) {
|
|
179
|
+
if (runtime.status !== 'connected')
|
|
180
|
+
continue;
|
|
181
|
+
if (settings.remoteHeartbeat.enabled)
|
|
182
|
+
startRemoteHeartbeat(ctx, runtime);
|
|
183
|
+
else
|
|
184
|
+
stopRemoteHeartbeat(runtime);
|
|
185
|
+
}
|
|
186
|
+
ctx.emitState();
|
|
187
|
+
return settings;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Browse directories inside the user's home so the client can pick a private-key
|
|
191
|
+
* file instead of typing an absolute path. Read-only and home-confined.
|
|
192
|
+
*/
|
|
193
|
+
export async function listKeyFiles(ctx, dir) {
|
|
194
|
+
// The picker is rooted at the OS user home, not DSH_HOME: private keys live in
|
|
195
|
+
// `~/.ssh` of the account, while the service's `home` is the DSH state root.
|
|
196
|
+
const userHome = homedir();
|
|
197
|
+
let listing;
|
|
198
|
+
try {
|
|
199
|
+
listing = await listKeyFilesInHome({ home: userHome, dir: typeof dir === 'string' ? dir : '' });
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
// A path outside the home directory (`C:\Windows`, `..`, a symlink escape) or an
|
|
203
|
+
// unreadable one is the caller's mistake: answer 400 instead of turning a bare `Error`
|
|
204
|
+
// into a 500, and never echo the requested path back in `technical`.
|
|
205
|
+
if (error?.code === OUTSIDE_HOME || ['ENOENT', 'EACCES', 'EPERM', 'ENOTDIR'].includes(error?.code)) {
|
|
206
|
+
throw errors.invalidInput('path', {
|
|
207
|
+
zh: '这个目录不在用户主目录内,或无法读取。',
|
|
208
|
+
en: 'This folder is outside the home directory, or cannot be read.',
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
const settings = ctx.store.getSettings();
|
|
214
|
+
return { ...listing, defaultKeyPath: settings.defaultKeyPath, defaultDir: path.join(userHome, '.ssh') };
|
|
215
|
+
}
|
|
216
|
+
/** Read-only SSH discovery for the wizard (design §15.1). */
|
|
217
|
+
export async function discoverSshAliases(ctx) {
|
|
218
|
+
const material = await ctx.deps.loadSshMaterial({ home: ctx.userHome() });
|
|
219
|
+
const parsed = parseSshConfig(material.configText);
|
|
220
|
+
const aliases = discoverAliasesFromConfig(parsed, { home: ctx.userHome() });
|
|
221
|
+
const knownHosts = parseKnownHosts(material.knownHostsText);
|
|
222
|
+
return {
|
|
223
|
+
aliases: aliases.map((alias) => ({
|
|
224
|
+
alias: alias.alias,
|
|
225
|
+
host: alias.host,
|
|
226
|
+
user: alias.user,
|
|
227
|
+
port: alias.port,
|
|
228
|
+
source: 'config',
|
|
229
|
+
})),
|
|
230
|
+
knownHosts: summarizeKnownHosts(knownHosts),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** An empty `RemoteRuntime`; the teardown path resets to it while keeping the version. */
|
|
2
|
+
export function emptyRemote() {
|
|
3
|
+
return {
|
|
4
|
+
version: null,
|
|
5
|
+
uiReady: false,
|
|
6
|
+
localPort: null,
|
|
7
|
+
port: null,
|
|
8
|
+
pid: null,
|
|
9
|
+
dshHome: null,
|
|
10
|
+
profile: null,
|
|
11
|
+
bootstrapLevel: null,
|
|
12
|
+
nodeVersion: null,
|
|
13
|
+
nodeSource: null,
|
|
14
|
+
startedAt: null,
|
|
15
|
+
viewRev: 0,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Build the mutable state for one host. The entry always carries the id the store issued.
|
|
20
|
+
*
|
|
21
|
+
* The return annotation types the literal field by field, so an empty container needs no `as`
|
|
22
|
+
* (contextual typing supplies its element type) and a missing or extra field is a compile error.
|
|
23
|
+
* @param host - the stored host, already carrying its id.
|
|
24
|
+
* @returns a fresh runtime in the `unconfigured` state.
|
|
25
|
+
*/
|
|
26
|
+
export function createHostRuntime(host) {
|
|
27
|
+
return {
|
|
28
|
+
id: host.id,
|
|
29
|
+
entry: host,
|
|
30
|
+
status: 'unconfigured',
|
|
31
|
+
phase: null,
|
|
32
|
+
progress: null,
|
|
33
|
+
error: null,
|
|
34
|
+
warning: null,
|
|
35
|
+
warningSource: null,
|
|
36
|
+
fingerprint: host.pinnedFingerprint
|
|
37
|
+
? { sha256: host.pinnedFingerprint, keyType: 'pinned', status: 'pinned', pinned: host.pinnedFingerprint }
|
|
38
|
+
: null,
|
|
39
|
+
jumpFingerprint: null,
|
|
40
|
+
remote: emptyRemote(),
|
|
41
|
+
ssh: null,
|
|
42
|
+
jumpSsh: null,
|
|
43
|
+
tunnel: null,
|
|
44
|
+
token: null,
|
|
45
|
+
password: null,
|
|
46
|
+
savePassword: false,
|
|
47
|
+
forgetPassword: false,
|
|
48
|
+
passwordSaved: false,
|
|
49
|
+
facts: null,
|
|
50
|
+
remoteHome: null,
|
|
51
|
+
remotePid: null,
|
|
52
|
+
remoteProfile: null,
|
|
53
|
+
exchange: null,
|
|
54
|
+
pendingHostKey: null,
|
|
55
|
+
pendingConflict: null,
|
|
56
|
+
conflict: null,
|
|
57
|
+
desired: 'idle',
|
|
58
|
+
connectCancelled: false,
|
|
59
|
+
transportLost: false,
|
|
60
|
+
reconnectAttempts: 0,
|
|
61
|
+
reconnectTimer: null,
|
|
62
|
+
idleTimer: null,
|
|
63
|
+
connectPromise: null,
|
|
64
|
+
linkBusy: null,
|
|
65
|
+
linkToken: 0,
|
|
66
|
+
restartPromise: null,
|
|
67
|
+
reattachPromise: null,
|
|
68
|
+
launched: new Map(),
|
|
69
|
+
bound: null,
|
|
70
|
+
tunnelRepair: null,
|
|
71
|
+
tunnelRepairFailures: 0,
|
|
72
|
+
nextTunnelRepairAt: 0,
|
|
73
|
+
heartbeatTimer: null,
|
|
74
|
+
remoteCheckTimer: null,
|
|
75
|
+
remoteFailures: 0,
|
|
76
|
+
remoteEpisode: false,
|
|
77
|
+
episodeSource: null,
|
|
78
|
+
episodeCooldownUntil: 0,
|
|
79
|
+
alongsidePids: [],
|
|
80
|
+
restarts: [],
|
|
81
|
+
closing: false,
|
|
82
|
+
logs: [],
|
|
83
|
+
logSeq: 0,
|
|
84
|
+
connectCount: 0,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client-facing view of one host (docs/api.md HostView).
|
|
3
|
+
*/
|
|
4
|
+
import { versionParity } from './version.js';
|
|
5
|
+
import { connectLogTail, connectLogVisible } from './connect-log.js';
|
|
6
|
+
export function hostView(runtime, ctx, options = {}) {
|
|
7
|
+
const entry = runtime.entry;
|
|
8
|
+
return {
|
|
9
|
+
id: runtime.id,
|
|
10
|
+
name: entry.name,
|
|
11
|
+
address: entry.address,
|
|
12
|
+
addressMasked: maskAddress(entry),
|
|
13
|
+
/**
|
|
14
|
+
* The plain connection fields. The masked address is presentation only: the editor must not
|
|
15
|
+
* parse it back (a bare IPv6 like `fe80::1` used to yield port 1, and the default port was
|
|
16
|
+
* silently replaced by 22). Never a secret.
|
|
17
|
+
*/
|
|
18
|
+
username: entry.username ?? null,
|
|
19
|
+
port: entry.port ?? 22,
|
|
20
|
+
/** Never the secret itself; lets the Client ask for a one-time password. */
|
|
21
|
+
authType: entry.auth?.type ?? 'key',
|
|
22
|
+
/** The configured key file path (not a secret); lets the edit form prefill it. */
|
|
23
|
+
authKeyPath: entry.auth?.type === 'key' && typeof entry.auth.keyPath === 'string' ? entry.auth.keyPath : null,
|
|
24
|
+
/**
|
|
25
|
+
* Whether a remembered password exists in the credential store (never the value). The
|
|
26
|
+
* runtime mirror is restored from the store on load, so this stays true across a DSH
|
|
27
|
+
* restart while a one-time password used for this connection alone stays false.
|
|
28
|
+
*/
|
|
29
|
+
passwordSaved: entry.auth?.type === 'password' ? runtime.passwordSaved === true : false,
|
|
30
|
+
passwordStorageAvailable: ctx.passwordStorageAvailable,
|
|
31
|
+
jumpHost: entry.jumpHost ?? null,
|
|
32
|
+
status: runtime.status,
|
|
33
|
+
phase: runtime.phase,
|
|
34
|
+
progress: runtime.progress,
|
|
35
|
+
error: runtime.error,
|
|
36
|
+
warning: runtime.warning,
|
|
37
|
+
conflict: runtime.conflict,
|
|
38
|
+
fingerprint: runtime.fingerprint,
|
|
39
|
+
logs: options.logs === false ? [] : connectLogVisible(runtime.status) ? connectLogTail(runtime) : [],
|
|
40
|
+
logAttempt: typeof runtime.connectCount === 'number' ? runtime.connectCount : 0,
|
|
41
|
+
logSeq: typeof runtime.logSeq === 'number' ? runtime.logSeq : 0,
|
|
42
|
+
remote: {
|
|
43
|
+
...runtime.remote,
|
|
44
|
+
version: runtime.remote.version ?? null,
|
|
45
|
+
},
|
|
46
|
+
keepAlive: entry.keepAlive,
|
|
47
|
+
idleMinutes: entry.idleMinutes,
|
|
48
|
+
autoReconnect: entry.autoReconnect,
|
|
49
|
+
hostKeyPolicy: entry.hostKeyPolicy,
|
|
50
|
+
lastOpenedAt: entry.lastOpenedAt,
|
|
51
|
+
createdAt: entry.createdAt,
|
|
52
|
+
updatedAt: entry.updatedAt,
|
|
53
|
+
targetVersion: ctx.targetVersion,
|
|
54
|
+
versionParity: versionParity(ctx.targetVersion, runtime.remote.version ?? null),
|
|
55
|
+
/**
|
|
56
|
+
* True when `hosts.json` was unreadable on load: this list is the recovered fallback, and a
|
|
57
|
+
* copy of the damaged file is kept next to it (`hosts.json.corrupt-<timestamp>`). Contract
|
|
58
|
+
* field only — the Client renders it as a warning (docs/api.md HostView).
|
|
59
|
+
*/
|
|
60
|
+
storeCorrupt: ctx.storeCorrupt === true,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
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) {
|
|
69
|
+
const port = entry.port && entry.port !== 22 ? `:${entry.port}` : '';
|
|
70
|
+
const user = entry.username ? `${entry.username}@` : '';
|
|
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;
|
|
74
|
+
return `${user}${host}${port}`;
|
|
75
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
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.
|
|
4
|
+
*/
|
|
5
|
+
import { API_PREFIX, PLUGIN_ID, REMOTE_VIEW_PREFIX } from './constants.js';
|
|
6
|
+
import { statSync } from 'node:fs';
|
|
7
|
+
import { createAdmission } from './admission.js';
|
|
8
|
+
import { createApi } from './api.js';
|
|
9
|
+
import { KERNEL_PROBE_VERSION, createKernelAdapter } from './kernel-adapter.js';
|
|
10
|
+
import { detectLocalEnginesNode, detectLocalVersion } from './local-version.js';
|
|
11
|
+
import { createRemoteProxy } from './proxy/index.js';
|
|
12
|
+
import { RemoteGoService } from './service.js';
|
|
13
|
+
import { createSecretStore } from './secrets.js';
|
|
14
|
+
import { HostStore, resolveDshHome, resolveStateDir } from './store.js';
|
|
15
|
+
import { registerHostTools } from './tools.js';
|
|
16
|
+
import { messageOf } from './util.js';
|
|
17
|
+
export const name = PLUGIN_ID;
|
|
18
|
+
export const inject = ['webServer'];
|
|
19
|
+
export const optional = ['connection', 'credentials'];
|
|
20
|
+
export function apply(ctx, config = {}) {
|
|
21
|
+
const logger = createLogger();
|
|
22
|
+
// The kernel's own metadata (loader fiber, client-module registry) is read through one adapter,
|
|
23
|
+
// so `/diagnostics/self` and every future kernel probe share the same three-state answers.
|
|
24
|
+
const kernel = createKernelAdapter(ctx);
|
|
25
|
+
const home = config.home ? String(config.home) : resolveDshHome(process.env);
|
|
26
|
+
const stateDir = resolveStateDir(home);
|
|
27
|
+
const store = new HostStore({ dir: stateDir, logger });
|
|
28
|
+
// Saved SSH passwords live in DSH's credential store, never in hosts.json.
|
|
29
|
+
const secrets = createSecretStore({ ctx, logger });
|
|
30
|
+
const service = new RemoteGoService({
|
|
31
|
+
store,
|
|
32
|
+
home,
|
|
33
|
+
logger,
|
|
34
|
+
secrets,
|
|
35
|
+
localVersion: config.localVersion ? String(config.localVersion) : null,
|
|
36
|
+
hostKeyConfirmTimeoutMs: config.hostKeyConfirmTimeoutMs,
|
|
37
|
+
});
|
|
38
|
+
const getOrigin = () => {
|
|
39
|
+
try {
|
|
40
|
+
return ctx.webServer?.getOrigin?.() ?? null;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
// DSH's own admission for every route this plugin serves: the kernel's Host/Origin fence plus
|
|
47
|
+
// browser-session authentication. `connection` is optional, so the gate hands the request to the
|
|
48
|
+
// plugin's own fence when the service is absent (see admission.js).
|
|
49
|
+
const admit = createAdmission(ctx, logger);
|
|
50
|
+
const api = createApi({
|
|
51
|
+
service,
|
|
52
|
+
getOrigin,
|
|
53
|
+
admit,
|
|
54
|
+
logger,
|
|
55
|
+
diagnostics: () => describeSelf(kernel, {
|
|
56
|
+
home,
|
|
57
|
+
stateDir,
|
|
58
|
+
localVersion: service.localVersion,
|
|
59
|
+
engineNodeRange: service.engineNodeRange,
|
|
60
|
+
storeCorrupt: store.hostsCorrupt,
|
|
61
|
+
}),
|
|
62
|
+
});
|
|
63
|
+
// The browser half's remote window lives on the local origin (the desktop half uses a guest
|
|
64
|
+
// instead), so the same-origin proxy is the only thing that needs to know how to reach a tunnel.
|
|
65
|
+
const proxy = createRemoteProxy({
|
|
66
|
+
webServer: ctx.webServer,
|
|
67
|
+
getOrigin,
|
|
68
|
+
admit,
|
|
69
|
+
resolveHost: (id) => service.webViewTarget(id),
|
|
70
|
+
// A failed upstream is a suspicion, not a restart: the service confirms it with probes.
|
|
71
|
+
onUpstreamError: (id) => service.noteUpstreamFailure(id),
|
|
72
|
+
logger,
|
|
73
|
+
});
|
|
74
|
+
ctx.effect(() => {
|
|
75
|
+
const disposeRoute = ctx.webServer.register({
|
|
76
|
+
kind: 'prefix',
|
|
77
|
+
path: API_PREFIX,
|
|
78
|
+
handler: (req, res) => {
|
|
79
|
+
void api.handler(req, res);
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
const disposeView = ctx.webServer.register({
|
|
83
|
+
kind: 'prefix',
|
|
84
|
+
path: proxy.routePath,
|
|
85
|
+
handler: (req, 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, {
|
|
90
|
+
service,
|
|
91
|
+
logger,
|
|
92
|
+
exec: { allowWrite: config.exec?.allowWrite === true },
|
|
93
|
+
});
|
|
94
|
+
const syncViewRoutes = () => proxy.sync(service.hostIds());
|
|
95
|
+
service.on('state', syncViewRoutes);
|
|
96
|
+
logger.info(`API mounted at ${API_PREFIX} (state dir ${stateDir})`);
|
|
97
|
+
logger.info(`remote view mounted at ${REMOTE_VIEW_PREFIX}<host> (browser carrier)`);
|
|
98
|
+
void (async () => {
|
|
99
|
+
try {
|
|
100
|
+
await service.init();
|
|
101
|
+
syncViewRoutes();
|
|
102
|
+
const detected = await detectLocalVersion({ ctx, logger });
|
|
103
|
+
if (detected.version)
|
|
104
|
+
service.setLocalVersion(detected.version, detected.source);
|
|
105
|
+
// The managed Node version is the lower bound of DSH's own `engines.node`;
|
|
106
|
+
// reading it here keeps the plugin in step with the running DSH build.
|
|
107
|
+
const engine = await detectLocalEnginesNode({ ctx });
|
|
108
|
+
// `setLocalEnginesNode` has always taken one parameter; the source is not persisted there
|
|
109
|
+
// (only `setLocalVersion` reports where its value came from).
|
|
110
|
+
if (engine.range)
|
|
111
|
+
service.setLocalEnginesNode(engine.range);
|
|
112
|
+
if (!detected.version)
|
|
113
|
+
logger.warn('could not detect the local DSH version; the remote npx runtime cannot be pinned to this machine, so connections will fail until the version is readable');
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
logger.error('initialization failed:', error);
|
|
117
|
+
}
|
|
118
|
+
})();
|
|
119
|
+
return () => {
|
|
120
|
+
service.removeListener('state', syncViewRoutes);
|
|
121
|
+
// A failing disposer must not skip the rest of the unload: the proxy, the API and the SSH
|
|
122
|
+
// transports below still have to be released.
|
|
123
|
+
try {
|
|
124
|
+
disposeTools();
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
logger.error('unload: could not dispose the model tools:', error);
|
|
128
|
+
}
|
|
129
|
+
proxy.dispose();
|
|
130
|
+
api.dispose();
|
|
131
|
+
void service.shutdown();
|
|
132
|
+
disposeRoute();
|
|
133
|
+
disposeView();
|
|
134
|
+
logger.info('unloaded');
|
|
135
|
+
};
|
|
136
|
+
}, 'dsh-remote-go: http api + service');
|
|
137
|
+
return service;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* The `/diagnostics/self` body: the installation facts plus the kernel probe table.
|
|
141
|
+
*
|
|
142
|
+
* Every kernel read goes through `kernel-adapter.ts`, whose three states map onto this document the
|
|
143
|
+
* same way everywhere: `ok` fills the historical field, `absent`/`changed` leave it `null` (exactly
|
|
144
|
+
* what a missing service used to do) and `kernel.probes` says which of the two it was.
|
|
145
|
+
*/
|
|
146
|
+
function describeSelf(kernel, info) {
|
|
147
|
+
const out = {
|
|
148
|
+
home: info.home,
|
|
149
|
+
stateDir: info.stateDir,
|
|
150
|
+
hostVersion: info.localVersion,
|
|
151
|
+
engineNodeRange: info.engineNodeRange ?? null,
|
|
152
|
+
// True when hosts.json was unreadable and the list beside it is the recovered fallback.
|
|
153
|
+
storeCorrupt: info.storeCorrupt === true,
|
|
154
|
+
entry: null,
|
|
155
|
+
client: null,
|
|
156
|
+
kernel: { version: KERNEL_PROBE_VERSION, probes: kernel.probeReport() },
|
|
157
|
+
};
|
|
158
|
+
const entry = kernel.fiberEntry();
|
|
159
|
+
if (entry.state === 'ok' && entry.value !== null)
|
|
160
|
+
out.entry = { id: entry.value.id, name: entry.value.name };
|
|
161
|
+
const graph = kernel.clientModuleGraph();
|
|
162
|
+
const row = kernel.clientModuleRow(PLUGIN_ID);
|
|
163
|
+
const clientPathProbe = kernel.clientPath(PLUGIN_ID);
|
|
164
|
+
const clientPath = clientPathProbe.state === 'ok' ? clientPathProbe.value : null;
|
|
165
|
+
let bundle = null;
|
|
166
|
+
if (clientPath) {
|
|
167
|
+
try {
|
|
168
|
+
const stat = statSync(clientPath);
|
|
169
|
+
bundle = { path: clientPath, size: stat.size, mtimeMs: stat.mtimeMs };
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
bundle = { path: clientPath, error: messageOf(error) };
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
out.client = {
|
|
176
|
+
graph: graph.state === 'ok' && graph.value !== null
|
|
177
|
+
? { rev: graph.value.rev, release: graph.value.release, entries: graph.value.entries }
|
|
178
|
+
: null,
|
|
179
|
+
row: row.state === 'ok' && row.value !== null
|
|
180
|
+
? {
|
|
181
|
+
id: row.value.id,
|
|
182
|
+
rev: row.value.rev,
|
|
183
|
+
url: row.value.url,
|
|
184
|
+
inject: row.value.inject,
|
|
185
|
+
immediately: row.value.immediately,
|
|
186
|
+
}
|
|
187
|
+
: null,
|
|
188
|
+
clientPath,
|
|
189
|
+
bundle,
|
|
190
|
+
};
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
193
|
+
function createLogger() {
|
|
194
|
+
const tag = '[dsh-remote-go]';
|
|
195
|
+
const write = (level, args) => {
|
|
196
|
+
const sink = level === 'debug'
|
|
197
|
+
? console.debug
|
|
198
|
+
: level === 'error'
|
|
199
|
+
? console.error
|
|
200
|
+
: level === 'warn'
|
|
201
|
+
? console.warn
|
|
202
|
+
: console.info;
|
|
203
|
+
try {
|
|
204
|
+
sink?.call(console, tag, ...args);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
// swallow-ok: logging must never throw into the host
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
return {
|
|
211
|
+
info: (...args) => write('info', args),
|
|
212
|
+
warn: (...args) => write('warn', args),
|
|
213
|
+
error: (...args) => write('error', args),
|
|
214
|
+
debug: (...args) => write('debug', args),
|
|
215
|
+
};
|
|
216
|
+
}
|