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,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-host SSH password storage in DSH's own credential store (`ctx.credentials`), never in
|
|
3
|
+
* `hosts.json`; with no credential service nothing is persisted.
|
|
4
|
+
*
|
|
5
|
+
* Both kernel shapes this store touches live in `kernel-adapter.ts`: the record API and the
|
|
6
|
+
* `<scope>/<id>` key grammar, which is replicated there and confirmed against the kernel's own
|
|
7
|
+
* parser when one is exposed. A kernel whose grammar moved (`changed`) does not change the keys
|
|
8
|
+
* this plugin generates — the stored form is the one already on users' machines — but it is
|
|
9
|
+
* reported once, because a save the moved grammar later refuses must not look like a silent no-op.
|
|
10
|
+
*
|
|
11
|
+
* The same applies to a credential service that is present but whose members changed shape: the
|
|
12
|
+
* store answers "not stored" exactly as it does without a service, so that `changed` would make a
|
|
13
|
+
* remembered password look forgotten. It is warned about once per store, at the same level as the
|
|
14
|
+
* grammar warning.
|
|
15
|
+
*/
|
|
16
|
+
import { credentialRecordKey, createKernelAdapter } from './kernel-adapter.js';
|
|
17
|
+
import { HOST_ID_RE } from './settings.js';
|
|
18
|
+
import { isPlainObject } from './util.js';
|
|
19
|
+
const RECORD_SCOPE = 'dsh-remote-go';
|
|
20
|
+
const RECORD_ID_PREFIX = 'ssh-password-';
|
|
21
|
+
const PAYLOAD_VERSION = 1;
|
|
22
|
+
/**
|
|
23
|
+
* DSH addresses a stored record as `<scope>/<id>`, and both segments must match
|
|
24
|
+
* `/^[a-z][a-z0-9-]*$/` (`parseCredentialKey` in `@deepseek-ai/dsh-credentials`). A colon-separated
|
|
25
|
+
* key such as `dsh-remote-go:ssh-password:h_1` is stored as given but rejected the next time the
|
|
26
|
+
* credential document is read — the whole file then fails to load, taking every other credential
|
|
27
|
+
* with it. A host id is `h_<base36>`: its only character outside the grammar is the underscore,
|
|
28
|
+
* which maps onto `-` without collisions because the issued suffix never contains one. Only an id
|
|
29
|
+
* this plugin issued is addressable, so an unexpected value never reaches the document.
|
|
30
|
+
* @param hostId - the host id as it appears in `hosts.json`.
|
|
31
|
+
* @returns the record key, or `null` when the id is not addressable.
|
|
32
|
+
*/
|
|
33
|
+
export function passwordRecordKey(hostId) {
|
|
34
|
+
if (typeof hostId !== 'string' || !HOST_ID_RE.test(hostId))
|
|
35
|
+
return null;
|
|
36
|
+
return credentialRecordKey(RECORD_SCOPE, RECORD_ID_PREFIX + hostId.replace(/_/g, '-'));
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Build the store for one plugin activation.
|
|
40
|
+
* @param options - the kernel context (a fake in tests) and the warning sink.
|
|
41
|
+
* @returns the store; every method answers "not stored"/"not saved" instead of throwing.
|
|
42
|
+
*/
|
|
43
|
+
export function createSecretStore(options = {}) {
|
|
44
|
+
const logger = options.logger ?? console;
|
|
45
|
+
const kernel = createKernelAdapter(options.ctx);
|
|
46
|
+
let grammarChecked = false;
|
|
47
|
+
let serviceChangedNoted = false;
|
|
48
|
+
/**
|
|
49
|
+
* Report a moved key grammar once per store. The keys stay in their stored form on purpose: a
|
|
50
|
+
* changed grammar is a kernel we do not recognize, not a reason to orphan every saved password.
|
|
51
|
+
*/
|
|
52
|
+
function noteGrammar() {
|
|
53
|
+
if (grammarChecked)
|
|
54
|
+
return;
|
|
55
|
+
grammarChecked = true;
|
|
56
|
+
const probe = kernel.credentialKeyGrammar();
|
|
57
|
+
if (probe.state !== 'changed')
|
|
58
|
+
return;
|
|
59
|
+
logger.warn?.('[dsh-remote-go] the kernel credential key grammar changed; keys keep their stored form and saves may stop working:', probe.detail);
|
|
60
|
+
}
|
|
61
|
+
/** The record API, or `null` when this composition has no credential service. */
|
|
62
|
+
function credentials() {
|
|
63
|
+
const probe = kernel.credentialService();
|
|
64
|
+
if (probe.state === 'ok' && probe.value !== null) {
|
|
65
|
+
noteGrammar();
|
|
66
|
+
return probe.value;
|
|
67
|
+
}
|
|
68
|
+
// A service that exists but no longer has the record members is not "no credential service":
|
|
69
|
+
// answering null silently would present every remembered password as forgotten. Report it
|
|
70
|
+
// once per store, like the grammar warning; repeated lookups stay quiet.
|
|
71
|
+
if (probe.state === 'changed') {
|
|
72
|
+
if (!serviceChangedNoted) {
|
|
73
|
+
serviceChangedNoted = true;
|
|
74
|
+
logger.warn?.('[dsh-remote-go] the kernel credential service changed shape; saved passwords cannot be read or written:', probe.detail);
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
if (probe.reason === 'lookup-failed') {
|
|
79
|
+
logger.warn?.('[dsh-remote-go] credential service lookup failed:', probe.detail);
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
return {
|
|
84
|
+
available() {
|
|
85
|
+
return credentials() !== null;
|
|
86
|
+
},
|
|
87
|
+
async get(hostId) {
|
|
88
|
+
const service = credentials();
|
|
89
|
+
const key = passwordRecordKey(hostId);
|
|
90
|
+
if (!service || key === null)
|
|
91
|
+
return null;
|
|
92
|
+
try {
|
|
93
|
+
const record = await service.readRecord(key);
|
|
94
|
+
const payload = record && record.kind === 'grant' ? record.payload : null;
|
|
95
|
+
// A stored payload is untrusted JSON from the credential document: narrow it, never cast it.
|
|
96
|
+
if (!isPlainObject(payload))
|
|
97
|
+
return null;
|
|
98
|
+
if (payload.version !== PAYLOAD_VERSION || typeof payload.password !== 'string')
|
|
99
|
+
return null;
|
|
100
|
+
return payload.password === '' ? null : payload.password;
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
logger.warn?.('[dsh-remote-go] could not read the saved password:', error);
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
async has(hostId) {
|
|
108
|
+
return (await this.get(hostId)) !== null;
|
|
109
|
+
},
|
|
110
|
+
async set(hostId, password) {
|
|
111
|
+
const service = credentials();
|
|
112
|
+
const key = passwordRecordKey(hostId);
|
|
113
|
+
if (!service || key === null || typeof password !== 'string' || password === '')
|
|
114
|
+
return false;
|
|
115
|
+
try {
|
|
116
|
+
await service.modifyRecord(key, async () => ({
|
|
117
|
+
kind: 'grant',
|
|
118
|
+
payload: { version: PAYLOAD_VERSION, password },
|
|
119
|
+
}));
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
logger.warn?.('[dsh-remote-go] could not save the password:', error);
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
async remove(hostId) {
|
|
128
|
+
const service = credentials();
|
|
129
|
+
const key = passwordRecordKey(hostId);
|
|
130
|
+
if (!service || key === null || typeof service.deleteRecord !== 'function')
|
|
131
|
+
return false;
|
|
132
|
+
try {
|
|
133
|
+
await service.deleteRecord(key);
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
logger.warn?.('[dsh-remote-go] could not delete the saved password:', error);
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Orchestration service — the facade over host-registry, the connect workflow (`connect/`), host-lifecycle, prompts and connect-progress; every external step is injected.
|
|
3
|
+
*/
|
|
4
|
+
import { EventEmitter } from 'node:events';
|
|
5
|
+
import { MIN_DSH_VERSION, REMOTE_VIEW_PREFIX } from './constants.js';
|
|
6
|
+
import { connectLogTail, connectLogVisible } from './connect-log.js';
|
|
7
|
+
import { describePreflightEvent } from './connect-progress.js';
|
|
8
|
+
import { createCtx } from './context.js';
|
|
9
|
+
import { createDownloadJobs } from './download-jobs.js';
|
|
10
|
+
import { reconnectHost, startConnect } from './connect/links.js';
|
|
11
|
+
import { reattachHost } from './connect/reattach.js';
|
|
12
|
+
import { repairTunnel } from './connect/repair.js';
|
|
13
|
+
import { restartHost } from './connect/restart.js';
|
|
14
|
+
import { stopRemoteHost } from './connect/stop.js';
|
|
15
|
+
import { installWatchdog } from './connect/watchdog.js';
|
|
16
|
+
import { diagnoseHost } from './diagnostics.js';
|
|
17
|
+
import { errors } from './errors.js';
|
|
18
|
+
import { discoverSshAliases, initRegistry, listKeyFiles, removeHost, runtimeOf, saveHost, saveSettings, setActiveHost, snapshot, } from './host-registry.js';
|
|
19
|
+
import { disconnectHost, shutdownAll } from './host-lifecycle.js';
|
|
20
|
+
import { requireDestination } from './local-download.js';
|
|
21
|
+
import { confirmConflict, confirmHostKey } from './prompts.js';
|
|
22
|
+
import { compareVersions, normalizeVersion, parseVersion } from './version.js';
|
|
23
|
+
import { nowIso } from './util.js';
|
|
24
|
+
import { noteRemoteUnreachable } from './watchdog.js';
|
|
25
|
+
export { describePreflightEvent };
|
|
26
|
+
/**
|
|
27
|
+
* One Host process can create several services (tests, a plugin reload in-process). The
|
|
28
|
+
* instance id must differ for each so the Client can tell a new publish generation from a stale
|
|
29
|
+
* frame without trusting wall-clock ordering.
|
|
30
|
+
*/
|
|
31
|
+
let stateInstanceSequence = 0;
|
|
32
|
+
function stateInstanceId() {
|
|
33
|
+
stateInstanceSequence += 1;
|
|
34
|
+
const pid = typeof process !== 'undefined' && Number.isInteger(process.pid) ? process.pid.toString(36) : '0';
|
|
35
|
+
return `${pid}-${Date.now().toString(36)}-${stateInstanceSequence.toString(36)}`;
|
|
36
|
+
}
|
|
37
|
+
export class RemoteGoService extends EventEmitter {
|
|
38
|
+
constructor(options) {
|
|
39
|
+
super();
|
|
40
|
+
this.store = options.store;
|
|
41
|
+
this.home = options.home;
|
|
42
|
+
this.logger = options.logger ?? console;
|
|
43
|
+
this.localVersion = options.localVersion ?? null;
|
|
44
|
+
// `engines.node` of the local DSH package; the managed Node version is its
|
|
45
|
+
// lower bound (see `managedNodeVersionFromEngine`). Null until detected.
|
|
46
|
+
this.engineNodeRange = options.engineNodeRange ?? null;
|
|
47
|
+
this.secrets = options.secrets ?? null;
|
|
48
|
+
this.stateRev = 0;
|
|
49
|
+
this.stateInstance = stateInstanceId();
|
|
50
|
+
/**
|
|
51
|
+
* What only the facade can supply: the publish revision, the lazy load, the two adopted
|
|
52
|
+
* values (it owns them: `api.ts` and `index.ts` read the fields) and the episode event.
|
|
53
|
+
*/
|
|
54
|
+
const hooks = {
|
|
55
|
+
publish: () => this.emitState(),
|
|
56
|
+
publishLogs: (hostId) => this.emitLogs(hostId),
|
|
57
|
+
load: () => this.init(),
|
|
58
|
+
localVersion: () => this.localVersion,
|
|
59
|
+
engineNodeRange: () => this.engineNodeRange,
|
|
60
|
+
/**
|
|
61
|
+
* The watchdog reports an episode (suspected -> confirmed -> recovered); the Client
|
|
62
|
+
* contract gets the same transitions as one SSE event, and the state frames carry the
|
|
63
|
+
* `restarting-remote` progress. Never let a listener failure break the probe.
|
|
64
|
+
*/
|
|
65
|
+
onEpisode: (runtime, info) => {
|
|
66
|
+
try {
|
|
67
|
+
this.emit('remote-unreachable', { hostId: runtime.id, at: nowIso(), ...info });
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
this.logger.warn?.('[dsh-remote-go] remote-unreachable listener failed:', error);
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
// The assembly root is `context.ts` (P2/1): this class only owns the facade state above.
|
|
75
|
+
this.ctx = createCtx({ ...options, logger: this.logger }, hooks);
|
|
76
|
+
/**
|
|
77
|
+
* The watchdog: one bus (assembled in `context.ts`), one subscriber (`connect/watchdog.ts`),
|
|
78
|
+
* installed here because the facade owns the lifecycle — it subscribes now and unsubscribes on
|
|
79
|
+
* shutdown, exactly where the three reverse callbacks of design-arch §1.7 used to be wired.
|
|
80
|
+
* The two orchestration entries are bound here: the actor is not an entry point, so it takes
|
|
81
|
+
* the three slices it reads plus these two callbacks instead of the whole context.
|
|
82
|
+
*/
|
|
83
|
+
this.uninstallWatchdog = installWatchdog(this.ctx, {
|
|
84
|
+
reattach: (runtime, info) => reattachHost(this.ctx, runtime, info),
|
|
85
|
+
repair: (runtime) => repairTunnel(this.ctx, runtime),
|
|
86
|
+
});
|
|
87
|
+
/**
|
|
88
|
+
* `noteRemoteUnreachable` is not a capability: `watchdog.ts` is imported forward by every
|
|
89
|
+
* production caller. The alias exists because 13 test call sites drive a proxy/tunnel failure
|
|
90
|
+
* through `service.ctx` (design-arch §1.7, §1.6).
|
|
91
|
+
*/
|
|
92
|
+
this.ctx.noteRemoteUnreachable = (runtime, source) => noteRemoteUnreachable(this.ctx, runtime, source);
|
|
93
|
+
this.downloads = createDownloadJobs({
|
|
94
|
+
logger: this.logger,
|
|
95
|
+
emit: (job) => this.emit('download', job),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
get runtimes() {
|
|
99
|
+
return this.ctx.state.runtimes;
|
|
100
|
+
}
|
|
101
|
+
get activeHostId() {
|
|
102
|
+
return this.ctx.state.activeHostId;
|
|
103
|
+
}
|
|
104
|
+
async init() {
|
|
105
|
+
await initRegistry(this.ctx);
|
|
106
|
+
return this;
|
|
107
|
+
}
|
|
108
|
+
emitState() {
|
|
109
|
+
try {
|
|
110
|
+
// Every emitted frame gets its own monotonic revision. The Client drops a frame whose
|
|
111
|
+
// `rev` is not newer than the one on screen, so an out-of-order SSE delivery or a slow
|
|
112
|
+
// `GET /state` can no longer repaint the panel backwards (docs/api.md StateView.rev).
|
|
113
|
+
//
|
|
114
|
+
// Only a change to the *state model* publishes here. A connect log line is not one: it is
|
|
115
|
+
// published on the log channel (`emitLogs`) and must not move `rev`, or the Client would
|
|
116
|
+
// discard in-flight `/state` reads every 150 ms (docs/api.md v2.12).
|
|
117
|
+
this.stateRev += 1;
|
|
118
|
+
this.emit('state', this.snapshot());
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
this.logger.warn?.('[dsh-remote-go] state listener failed:', error);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* One host's log ring grew: publish it on the log channel only (docs/api.md `GET /events/logs`).
|
|
126
|
+
*
|
|
127
|
+
* The payload is just the host id; a subscriber reads the cursor view itself, so the event
|
|
128
|
+
* carries no snapshot and cannot be confused with a state change. Coalescing (150 ms) belongs
|
|
129
|
+
* to the event hub, not here.
|
|
130
|
+
* @param hostId - the host whose rows changed.
|
|
131
|
+
*/
|
|
132
|
+
emitLogs(hostId) {
|
|
133
|
+
try {
|
|
134
|
+
this.emit('logs', { hostId });
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
this.logger.warn?.('[dsh-remote-go] log listener failed:', error);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Adopt a DSH version for this machine.
|
|
142
|
+
*
|
|
143
|
+
* `source === 'client'` is the browser's `POST /local-version` backfill: it exists for the
|
|
144
|
+
* case where the Host could not detect the version by itself, so it must never overwrite a
|
|
145
|
+
* detected one, and it must stay inside the range this plugin supports. Without both guards
|
|
146
|
+
* any local page could pin the remote npx runtime (and the version-parity check) to a value
|
|
147
|
+
* of its choosing.
|
|
148
|
+
* @param version - a DSH semver string.
|
|
149
|
+
* @param source - where the value came from; only `client` is distrusted.
|
|
150
|
+
* @returns whether the value was adopted.
|
|
151
|
+
*/
|
|
152
|
+
setLocalVersion(version, source = 'detected') {
|
|
153
|
+
const normalized = version ? normalizeVersion(String(version)) : null;
|
|
154
|
+
const valid = normalized !== null && parseVersion(normalized) !== null;
|
|
155
|
+
if (source === 'client') {
|
|
156
|
+
if (this.localVersion !== null)
|
|
157
|
+
return false;
|
|
158
|
+
// A page may only name a real DSH version: a typo or a crafted value is a client mistake
|
|
159
|
+
// (400), not a silent no-op the page could mistake for success.
|
|
160
|
+
if (!valid) {
|
|
161
|
+
throw errors.invalidInput('version', {
|
|
162
|
+
zh: '本机 DSH 版本格式不合法。',
|
|
163
|
+
en: 'The local DSH version is not a valid version.',
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
if (compareVersions(normalized, MIN_DSH_VERSION) < 0) {
|
|
167
|
+
throw errors.invalidInput('version', {
|
|
168
|
+
zh: `本机 DSH 版本 ${normalized} 低于插件要求的最低版本 ${MIN_DSH_VERSION}。`,
|
|
169
|
+
en: `Local DSH ${normalized} is below the minimum this plugin supports (${MIN_DSH_VERSION}).`,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
else if (!valid) {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
this.localVersion = normalized;
|
|
177
|
+
this.emitState();
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
setLocalEnginesNode(range) {
|
|
181
|
+
const text = typeof range === 'string' ? range.trim() : '';
|
|
182
|
+
this.engineNodeRange = text === '' ? null : text;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Build the client-facing state snapshot (contract: docs/api.md).
|
|
186
|
+
*
|
|
187
|
+
* `options.logs === false` is the state-frame shape: every `hosts[].logs` is `[]` (the log
|
|
188
|
+
* channel owns the rows). The default keeps the `GET /state` / diagnostics shape, whose tail is
|
|
189
|
+
* the authoritative snapshot and the Client's only fallback when the log channel is missing.
|
|
190
|
+
* @param options - `logs: false` strips the per-host tails.
|
|
191
|
+
*/
|
|
192
|
+
snapshot(options = {}) {
|
|
193
|
+
return { ...snapshot(this.ctx, options), rev: this.stateRev, instance: this.stateInstance };
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* One host's cursor view for the log channel, or null for an unknown host.
|
|
197
|
+
* Reads the live runtime, so a published row is already in the ring by the time it is asked for.
|
|
198
|
+
* @param hostId - the host to read.
|
|
199
|
+
*/
|
|
200
|
+
logView(hostId) {
|
|
201
|
+
const runtime = this.ctx.state.runtimes.get(hostId);
|
|
202
|
+
if (!runtime)
|
|
203
|
+
return null;
|
|
204
|
+
const logs = Array.isArray(runtime.logs) ? runtime.logs : [];
|
|
205
|
+
const seq = typeof runtime.logSeq === 'number' ? runtime.logSeq : 0;
|
|
206
|
+
const oldest = logs[0];
|
|
207
|
+
const firstSeq = oldest !== undefined && typeof oldest.seq === 'number' ? oldest.seq : seq + 1;
|
|
208
|
+
return {
|
|
209
|
+
hostId,
|
|
210
|
+
// `connectCount` is what the boundary line numbers ("第 N 次连接"); it only moves forward.
|
|
211
|
+
attempt: typeof runtime.connectCount === 'number' ? runtime.connectCount : 0,
|
|
212
|
+
visible: connectLogVisible(runtime.status),
|
|
213
|
+
firstSeq,
|
|
214
|
+
seq,
|
|
215
|
+
// `connectLogTail` is the one exit for the entry shape (redaction happened at write time).
|
|
216
|
+
entries: connectLogTail(runtime),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
/** The hosts whose connect window is on screen, i.e. every host the log channel publishes. */
|
|
220
|
+
logHostIds() {
|
|
221
|
+
const ids = [];
|
|
222
|
+
for (const [id, runtime] of this.ctx.state.runtimes) {
|
|
223
|
+
if (connectLogVisible(runtime.status))
|
|
224
|
+
ids.push(id);
|
|
225
|
+
}
|
|
226
|
+
return ids;
|
|
227
|
+
}
|
|
228
|
+
userHome() {
|
|
229
|
+
return this.ctx.userHome();
|
|
230
|
+
}
|
|
231
|
+
async saveHost(rawHost) {
|
|
232
|
+
return saveHost(this.ctx, rawHost);
|
|
233
|
+
}
|
|
234
|
+
async removeHost(id) {
|
|
235
|
+
return removeHost(this.ctx, id);
|
|
236
|
+
}
|
|
237
|
+
setActiveHost(id) {
|
|
238
|
+
return setActiveHost(this.ctx, id);
|
|
239
|
+
}
|
|
240
|
+
async saveSettings(patch) {
|
|
241
|
+
return saveSettings(this.ctx, patch);
|
|
242
|
+
}
|
|
243
|
+
async listKeyFiles(dir) {
|
|
244
|
+
return listKeyFiles(this.ctx, dir);
|
|
245
|
+
}
|
|
246
|
+
async discoverSshAliases() {
|
|
247
|
+
return discoverSshAliases(this.ctx);
|
|
248
|
+
}
|
|
249
|
+
async connect(id, options = {}) {
|
|
250
|
+
return startConnect(this.ctx, id, options);
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Remember (or forget) the SSH password without opening a connection. The wizard's plain
|
|
254
|
+
* "save" action uses this, and it is the only way to refresh a saved password that does not
|
|
255
|
+
* require a successful connect first. The value never enters `hosts.json`; `available:false`
|
|
256
|
+
* means no credential store can persist it here.
|
|
257
|
+
* @param id - host id.
|
|
258
|
+
*/
|
|
259
|
+
async saveHostPassword(id, options = {}) {
|
|
260
|
+
await this.init();
|
|
261
|
+
const runtime = runtimeOf(this.ctx, id);
|
|
262
|
+
const available = this.secrets ? this.secrets.available() === true : false;
|
|
263
|
+
if (!available)
|
|
264
|
+
return { available: false, saved: false };
|
|
265
|
+
if (options.clear === true) {
|
|
266
|
+
const removed = await this.secrets.remove(id);
|
|
267
|
+
// The password in memory belonged to the record just removed: a later connect must ask
|
|
268
|
+
// instead of silently reusing a credential the user asked to forget.
|
|
269
|
+
runtime.password = null;
|
|
270
|
+
runtime.passwordSaved = !removed;
|
|
271
|
+
this.emitState();
|
|
272
|
+
return { available, saved: false };
|
|
273
|
+
}
|
|
274
|
+
const password = typeof options.password === 'string' ? options.password : '';
|
|
275
|
+
if (password === '') {
|
|
276
|
+
throw errors.invalidInput('password', { zh: '密码不能为空。', en: 'The password must not be empty.' });
|
|
277
|
+
}
|
|
278
|
+
const saved = await this.secrets.set(id, password);
|
|
279
|
+
// An explicit save also arms the in-memory copy, so clicking "connect" next does not ask
|
|
280
|
+
// again for a password this process just proved and stored.
|
|
281
|
+
runtime.password = password;
|
|
282
|
+
runtime.passwordSaved = saved;
|
|
283
|
+
this.emitState();
|
|
284
|
+
return { available, saved };
|
|
285
|
+
}
|
|
286
|
+
async disconnect(id, options = {}) {
|
|
287
|
+
await this.init();
|
|
288
|
+
return disconnectHost(this.ctx, runtimeOf(this.ctx, id), options);
|
|
289
|
+
}
|
|
290
|
+
async reconnect(id) {
|
|
291
|
+
await this.init();
|
|
292
|
+
return reconnectHost(this.ctx, runtimeOf(this.ctx, id));
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Restart the managed remote web on the same SSH session (the "Restart remote DSH"
|
|
296
|
+
* card action). Only a connected host can be restarted; the work runs in the
|
|
297
|
+
* background and reports through `/state` like a connect does.
|
|
298
|
+
*/
|
|
299
|
+
async restart(id) {
|
|
300
|
+
await this.init();
|
|
301
|
+
return restartHost(this.ctx, runtimeOf(this.ctx, id));
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Stop the managed remote web this connection is bound to, then release the link and
|
|
305
|
+
* leave the host `disconnected` (the "Stop remote DSH" card action). Runs synchronously
|
|
306
|
+
* on the same SSH session: `/state` carries `stopping-remote` while it works, and a
|
|
307
|
+
* refusal (wrong state, busy, or an unprovable pid) is thrown as a coded error (HTTP 409).
|
|
308
|
+
*/
|
|
309
|
+
async stopRemote(id) {
|
|
310
|
+
await this.init();
|
|
311
|
+
return stopRemoteHost(this.ctx, runtimeOf(this.ctx, id));
|
|
312
|
+
}
|
|
313
|
+
async confirmFingerprint(id, decision) {
|
|
314
|
+
return confirmHostKey(this.ctx, runtimeOf(this.ctx, id), decision);
|
|
315
|
+
}
|
|
316
|
+
async confirmConflict(id, decision) {
|
|
317
|
+
return confirmConflict(runtimeOf(this.ctx, id), decision);
|
|
318
|
+
}
|
|
319
|
+
openInfo(id) {
|
|
320
|
+
const runtime = runtimeOf(this.ctx, id);
|
|
321
|
+
if (runtime.status !== 'connected' || !runtime.tunnel || !runtime.token) {
|
|
322
|
+
throw errors.remoteUiUnreachable({
|
|
323
|
+
zh: '主机尚未连接,无法打开远端界面。',
|
|
324
|
+
en: 'The host is not connected yet, so the remote UI cannot be opened.',
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
const token = encodeURIComponent(runtime.token);
|
|
328
|
+
return {
|
|
329
|
+
url: `http://127.0.0.1:${runtime.tunnel.localPort}/?token=${token}`,
|
|
330
|
+
// The browser half's carrier: same-origin seat of the same UI, proxied to this tunnel.
|
|
331
|
+
webUrl: `${REMOTE_VIEW_PREFIX}${encodeURIComponent(id)}/?token=${token}`,
|
|
332
|
+
localPort: runtime.tunnel.localPort,
|
|
333
|
+
address: `127.0.0.1:${runtime.tunnel.localPort}`,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
/** Configured host ids (the proxy keeps one stream upgrade route per id). */
|
|
337
|
+
hostIds() {
|
|
338
|
+
return [...this.ctx.state.runtimes.keys()];
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Loopback target of one host's remote web UI, for the same-origin proxy.
|
|
342
|
+
* Reads the live runtime, so a reconnect hands the proxy the new tunnel on the next request.
|
|
343
|
+
* @param id - host id.
|
|
344
|
+
*/
|
|
345
|
+
webViewTarget(id) {
|
|
346
|
+
const runtime = this.ctx.state.runtimes.get(id);
|
|
347
|
+
if (!runtime || runtime.status !== 'connected' || !runtime.tunnel)
|
|
348
|
+
return null;
|
|
349
|
+
return { localPort: runtime.tunnel.localPort, remotePort: runtime.remote.port };
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* The same-origin proxy could not reach a host's tunnel. One failed request is not a
|
|
353
|
+
* restart: it starts the same probe confirmation the heartbeat uses.
|
|
354
|
+
* @param id - host id the proxy serves.
|
|
355
|
+
*/
|
|
356
|
+
noteUpstreamFailure(id) {
|
|
357
|
+
const runtime = this.ctx.state.runtimes.get(id);
|
|
358
|
+
if (!runtime)
|
|
359
|
+
return;
|
|
360
|
+
noteRemoteUnreachable(this.ctx, runtime, 'proxy');
|
|
361
|
+
}
|
|
362
|
+
async diagnose(id) {
|
|
363
|
+
await this.init();
|
|
364
|
+
return diagnoseHost(runtimeOf(this.ctx, id), { targetVersion: this.localVersion });
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Start preparing one remote file or folder for the client's download.
|
|
368
|
+
* @param id - host id.
|
|
369
|
+
* @param path - absolute remote path.
|
|
370
|
+
* @param options - local destination directory.
|
|
371
|
+
* @returns the initial download job view.
|
|
372
|
+
*/
|
|
373
|
+
async startRemoteDownload(id, path, options = {}) {
|
|
374
|
+
await this.init();
|
|
375
|
+
const runtime = runtimeOf(this.ctx, id);
|
|
376
|
+
// One home root for both checks: the pre-flight below and the write itself. Falling back to
|
|
377
|
+
// `os.homedir()` later could disagree with `userHome()` when HOME/USERPROFILE is unset, and
|
|
378
|
+
// then a destination accepted here would be refused by the job.
|
|
379
|
+
const home = this.userHome();
|
|
380
|
+
// The local folder is checked before a job exists: a refused destination is the caller's
|
|
381
|
+
// mistake (HTTP 400 `invalid-input`), not a job that first answers `preparing` and then
|
|
382
|
+
// reports the refusal asynchronously (which also wasted a job slot and an SFTP stat).
|
|
383
|
+
await requireDestination(options.destination, { home });
|
|
384
|
+
return this.downloads.start(runtime, path, { ...options, home });
|
|
385
|
+
}
|
|
386
|
+
/** Current view of one download job. */
|
|
387
|
+
async remoteDownloadStatus(jobId) {
|
|
388
|
+
await this.init();
|
|
389
|
+
return this.downloads.status(jobId);
|
|
390
|
+
}
|
|
391
|
+
/** Cancel one download job. */
|
|
392
|
+
async cancelRemoteDownload(jobId) {
|
|
393
|
+
await this.init();
|
|
394
|
+
return this.downloads.cancel(jobId);
|
|
395
|
+
}
|
|
396
|
+
async shutdown() {
|
|
397
|
+
// Stop reacting to watchdog events before the hosts are torn down: a re-attach or a listener
|
|
398
|
+
// rebuild started by a closing episode has nowhere to land. Idempotent.
|
|
399
|
+
this.uninstallWatchdog?.();
|
|
400
|
+
this.uninstallWatchdog = null;
|
|
401
|
+
this.ctx.state.disposed = true;
|
|
402
|
+
this.ctx.progress.dispose();
|
|
403
|
+
this.downloads.dispose();
|
|
404
|
+
await shutdownAll(this.ctx);
|
|
405
|
+
}
|
|
406
|
+
}
|