dsh-remote-go 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/{client.js → dist/client.js} +7144 -8367
- package/dist/index.js +4 -0
- package/dist/src/admission.js +21 -0
- package/dist/src/api.js +380 -0
- package/dist/src/atomic-json.js +201 -0
- package/dist/src/bootstrap.js +96 -0
- package/dist/src/connect/attach.js +21 -0
- package/dist/src/connect/bootstrap.js +8 -0
- package/dist/src/connect/failures.js +29 -0
- package/dist/src/connect/guards.js +36 -0
- package/dist/src/connect/launch.js +70 -0
- package/dist/src/connect/links.js +54 -0
- package/dist/src/connect/ownership.js +139 -0
- package/dist/src/connect/pipeline.js +376 -0
- package/dist/src/connect/reattach.js +191 -0
- package/dist/src/connect/registry.js +10 -0
- package/dist/src/connect/repair.js +97 -0
- package/dist/src/connect/restart.js +255 -0
- package/dist/src/connect/stop.js +164 -0
- package/dist/src/connect/transport.js +101 -0
- package/dist/src/connect/verify.js +30 -0
- package/dist/src/connect/watchdog.js +44 -0
- package/dist/src/connect-log.js +137 -0
- package/dist/src/connect-progress.js +110 -0
- package/dist/src/constants.js +29 -0
- package/dist/src/context.js +96 -0
- package/dist/src/diagnostics.js +133 -0
- package/dist/src/download-jobs.js +221 -0
- package/dist/src/errors.js +228 -0
- package/dist/src/events.js +326 -0
- package/dist/src/host-lifecycle.js +368 -0
- package/dist/src/host-registry.js +181 -0
- package/dist/src/host-runtime.js +77 -0
- package/dist/src/host-view.js +52 -0
- package/dist/src/index.js +196 -0
- package/dist/src/kernel-adapter.js +388 -0
- package/dist/src/key-files.js +39 -0
- package/dist/src/known-hosts.js +104 -0
- package/dist/src/layout.js +26 -0
- package/dist/src/local-download.js +311 -0
- package/dist/src/local-ssh.js +23 -0
- package/dist/src/local-version.js +87 -0
- package/dist/src/node/download.js +157 -0
- package/dist/src/node-runtime.js +327 -0
- package/dist/src/probe.js +95 -0
- package/dist/src/prompts.js +198 -0
- package/dist/src/proxy/cookies.js +102 -0
- package/dist/src/proxy/headers.js +167 -0
- package/dist/src/proxy/http.js +134 -0
- package/dist/src/proxy/index.js +121 -0
- package/dist/src/proxy/limits.js +6 -0
- package/dist/src/proxy/routes.js +32 -0
- package/dist/src/proxy/upgrade.js +160 -0
- package/dist/src/redact.js +85 -0
- package/dist/src/remote-files.js +60 -0
- package/dist/src/remote-path.js +82 -0
- package/dist/src/remote-proc.js +271 -0
- package/dist/src/remote-web/registry.js +107 -0
- package/dist/src/remote-web/resolve.js +229 -0
- package/dist/src/remote-web/start.js +190 -0
- package/dist/src/remote-web/stop.js +74 -0
- package/dist/src/request-trust.js +70 -0
- package/dist/src/runtime/dispatch.js +200 -0
- package/dist/src/runtime/effects.js +81 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +70 -0
- package/dist/src/runtime/rules.js +480 -0
- package/dist/src/secrets.js +119 -0
- package/dist/src/service.js +300 -0
- package/dist/src/settings.js +143 -0
- package/dist/src/ssh-config.js +257 -0
- package/dist/src/ssh-failures.js +71 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +258 -0
- package/dist/src/ssh.js +395 -0
- package/dist/src/store.js +174 -0
- package/dist/src/tool-shared.js +146 -0
- package/dist/src/tools-exec-policy.js +121 -0
- package/dist/src/tools-exec.js +307 -0
- package/dist/src/tools-report.js +357 -0
- package/dist/src/tools.js +337 -0
- package/dist/src/tunnel.js +111 -0
- package/dist/src/util.js +112 -0
- package/dist/src/version.js +108 -0
- package/dist/src/watchdog-bus.js +21 -0
- package/dist/src/watchdog.js +116 -0
- package/index.js +5 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +37 -19
- package/src/admission.js +0 -43
- package/src/api.js +0 -536
- package/src/atomic-json.js +0 -225
- package/src/bootstrap.js +0 -113
- package/src/connect-log.js +0 -176
- package/src/connect-pipeline.js +0 -1900
- package/src/connect-progress.js +0 -155
- package/src/constants.js +0 -93
- package/src/diagnostics.js +0 -160
- package/src/download-jobs.js +0 -234
- package/src/errors.js +0 -412
- package/src/host-lifecycle.js +0 -604
- package/src/host-registry.js +0 -217
- package/src/host-runtime.js +0 -127
- package/src/host-view.js +0 -75
- package/src/index.js +0 -206
- package/src/key-files.js +0 -54
- package/src/known-hosts.js +0 -133
- package/src/layout.js +0 -53
- package/src/local-download.js +0 -381
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -101
- package/src/prompts.js +0 -229
- package/src/redact.js +0 -68
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -137
- package/src/remote-proc.js +0 -343
- package/src/remote-proxy.js +0 -815
- package/src/remote-web.js +0 -751
- package/src/request-trust.js +0 -89
- package/src/secrets.js +0 -109
- package/src/service.js +0 -459
- package/src/settings.js +0 -163
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -731
- package/src/store.js +0 -193
- package/src/tools.js +0 -386
- package/src/tunnel.js +0 -132
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -43
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/** Orchestration facade over host-registry, the connect workflow, host-lifecycle, prompts and connect-progress; every
|
|
2
|
+
* external step is injected. */
|
|
3
|
+
import { EventEmitter } from 'node:events';
|
|
4
|
+
import { MIN_DSH_VERSION, REMOTE_VIEW_PREFIX } from './constants.js';
|
|
5
|
+
import { connectLogTail, connectLogVisible } from './connect-log.js';
|
|
6
|
+
import { describePreflightEvent } from './connect-progress.js';
|
|
7
|
+
import { createCtx } from './context.js';
|
|
8
|
+
import { createDownloadJobs } from './download-jobs.js';
|
|
9
|
+
import { reconnectHost, startConnect } from './connect/links.js';
|
|
10
|
+
import { reattachHost } from './connect/reattach.js';
|
|
11
|
+
import { repairTunnel } from './connect/repair.js';
|
|
12
|
+
import { restartHost } from './connect/restart.js';
|
|
13
|
+
import { stopRemoteHost } from './connect/stop.js';
|
|
14
|
+
import { installWatchdog } from './connect/watchdog.js';
|
|
15
|
+
import { diagnoseHost } from './diagnostics.js';
|
|
16
|
+
import { errors } from './errors.js';
|
|
17
|
+
import { discoverSshAliases, initRegistry, listKeyFiles, removeHost, runtimeOf, saveHost, saveSettings, setActiveHost, snapshot, } from './host-registry.js';
|
|
18
|
+
import { disconnectHost, shutdownAll } from './host-lifecycle.js';
|
|
19
|
+
import { requireDestination } from './local-download.js';
|
|
20
|
+
import { confirmConflict, confirmHostKey } from './prompts.js';
|
|
21
|
+
import { compareVersions, normalizeVersion, parseVersion } from './version.js';
|
|
22
|
+
import { nowIso } from './util.js';
|
|
23
|
+
import { noteRemoteUnreachable } from './watchdog.js';
|
|
24
|
+
export { describePreflightEvent };
|
|
25
|
+
let stateInstanceSequence = 0;
|
|
26
|
+
/** A fresh instance id per service, so a restarted Host's low `rev` is still accepted as newer. */
|
|
27
|
+
function stateInstanceId() {
|
|
28
|
+
stateInstanceSequence += 1;
|
|
29
|
+
const pid = typeof process !== 'undefined' && Number.isInteger(process.pid) ? process.pid.toString(36) : '0';
|
|
30
|
+
return `${pid}-${Date.now().toString(36)}-${stateInstanceSequence.toString(36)}`;
|
|
31
|
+
}
|
|
32
|
+
export class RemoteGoService extends EventEmitter {
|
|
33
|
+
constructor(options) {
|
|
34
|
+
super();
|
|
35
|
+
this.store = options.store;
|
|
36
|
+
this.home = options.home;
|
|
37
|
+
this.logger = options.logger ?? console;
|
|
38
|
+
this.localVersion = options.localVersion ?? null;
|
|
39
|
+
this.engineNodeRange = options.engineNodeRange ?? null;
|
|
40
|
+
this.secrets = options.secrets ?? null;
|
|
41
|
+
this.stateRev = 0;
|
|
42
|
+
this.stateInstance = stateInstanceId();
|
|
43
|
+
// Only the facade can supply these: the publish revision, the lazy load, the two adopted values
|
|
44
|
+
// (`api.ts` and `index.ts` read the fields) and the episode event.
|
|
45
|
+
const hooks = {
|
|
46
|
+
publish: () => this.emitState(),
|
|
47
|
+
publishLogs: (hostId) => this.emitLogs(hostId),
|
|
48
|
+
load: () => this.init(),
|
|
49
|
+
localVersion: () => this.localVersion,
|
|
50
|
+
engineNodeRange: () => this.engineNodeRange,
|
|
51
|
+
onEpisode: (runtime, info) => {
|
|
52
|
+
try {
|
|
53
|
+
this.emit('remote-unreachable', { hostId: runtime.id, at: nowIso(), ...info });
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
this.logger.warn?.('[dsh-remote-go] remote-unreachable listener failed:', error);
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
this.ctx = createCtx({ ...options, logger: this.logger }, hooks);
|
|
61
|
+
this.uninstallWatchdog = installWatchdog(this.ctx, {
|
|
62
|
+
reattach: (runtime, info) => reattachHost(this.ctx, runtime, info),
|
|
63
|
+
repair: (runtime) => repairTunnel(this.ctx, runtime),
|
|
64
|
+
});
|
|
65
|
+
this.ctx.noteRemoteUnreachable = (runtime, source) => noteRemoteUnreachable(this.ctx, runtime, source);
|
|
66
|
+
this.downloads = createDownloadJobs({
|
|
67
|
+
logger: this.logger,
|
|
68
|
+
emit: (job) => this.emit('download', job),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
get runtimes() {
|
|
72
|
+
return this.ctx.state.runtimes;
|
|
73
|
+
}
|
|
74
|
+
get activeHostId() {
|
|
75
|
+
return this.ctx.state.activeHostId;
|
|
76
|
+
}
|
|
77
|
+
async init() {
|
|
78
|
+
await initRegistry(this.ctx);
|
|
79
|
+
return this;
|
|
80
|
+
}
|
|
81
|
+
emitState() {
|
|
82
|
+
try {
|
|
83
|
+
// Every frame gets its own monotonic revision, so an out-of-order SSE delivery or a slow
|
|
84
|
+
// `GET /state` cannot repaint the panel backwards; a connect log row must not move it.
|
|
85
|
+
this.stateRev += 1;
|
|
86
|
+
this.emit('state', this.snapshot());
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
this.logger.warn?.('[dsh-remote-go] state listener failed:', error);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
emitLogs(hostId) {
|
|
93
|
+
try {
|
|
94
|
+
this.emit('logs', { hostId });
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
this.logger.warn?.('[dsh-remote-go] log listener failed:', error);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** Adopt a DSH version for this machine. A `client` backfill exists for the case where the Host could not detect the
|
|
101
|
+
* version itself, so it must never overwrite a detected one and must stay inside the supported range — without both
|
|
102
|
+
* guards any local page could pin the remote runtime. */
|
|
103
|
+
setLocalVersion(version, source = 'detected') {
|
|
104
|
+
const normalized = version ? normalizeVersion(String(version)) : null;
|
|
105
|
+
const valid = normalized !== null && parseVersion(normalized) !== null;
|
|
106
|
+
// A client backfill must never overwrite a detected version nor name one below the floor,
|
|
107
|
+
// otherwise any local page could pin the remote npx runtime to a value of its choosing.
|
|
108
|
+
if (source === 'client') {
|
|
109
|
+
if (this.localVersion !== null)
|
|
110
|
+
return false;
|
|
111
|
+
if (!valid) {
|
|
112
|
+
throw errors.invalidInput('version', {
|
|
113
|
+
zh: '本机 DSH 版本格式不合法。',
|
|
114
|
+
en: 'The local DSH version is not a valid version.',
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
if (compareVersions(normalized, MIN_DSH_VERSION) < 0) {
|
|
118
|
+
throw errors.invalidInput('version', {
|
|
119
|
+
zh: `本机 DSH 版本 ${normalized} 低于插件要求的最低版本 ${MIN_DSH_VERSION}。`,
|
|
120
|
+
en: `Local DSH ${normalized} is below the minimum this plugin supports (${MIN_DSH_VERSION}).`,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
else if (!valid) {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
this.localVersion = normalized;
|
|
128
|
+
this.emitState();
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
setLocalEnginesNode(range) {
|
|
132
|
+
const text = typeof range === 'string' ? range.trim() : '';
|
|
133
|
+
this.engineNodeRange = text === '' ? null : text;
|
|
134
|
+
}
|
|
135
|
+
/** Build the client-facing state snapshot; `logs: false` is the state-frame shape that strips every tail. */
|
|
136
|
+
snapshot(options = {}) {
|
|
137
|
+
return { ...snapshot(this.ctx, options), rev: this.stateRev, instance: this.stateInstance };
|
|
138
|
+
}
|
|
139
|
+
logView(hostId) {
|
|
140
|
+
const runtime = this.ctx.state.runtimes.get(hostId);
|
|
141
|
+
if (!runtime)
|
|
142
|
+
return null;
|
|
143
|
+
const logs = Array.isArray(runtime.logs) ? runtime.logs : [];
|
|
144
|
+
const seq = typeof runtime.logSeq === 'number' ? runtime.logSeq : 0;
|
|
145
|
+
const oldest = logs[0];
|
|
146
|
+
// An empty ring reports "one past the current cursor", so a cursor from the last row still replays.
|
|
147
|
+
const firstSeq = oldest !== undefined && typeof oldest.seq === 'number' ? oldest.seq : seq + 1;
|
|
148
|
+
return {
|
|
149
|
+
hostId,
|
|
150
|
+
attempt: typeof runtime.connectCount === 'number' ? runtime.connectCount : 0,
|
|
151
|
+
visible: connectLogVisible(runtime.status),
|
|
152
|
+
firstSeq,
|
|
153
|
+
seq,
|
|
154
|
+
entries: connectLogTail(runtime),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
logHostIds() {
|
|
158
|
+
const ids = [];
|
|
159
|
+
for (const [id, runtime] of this.ctx.state.runtimes) {
|
|
160
|
+
if (connectLogVisible(runtime.status))
|
|
161
|
+
ids.push(id);
|
|
162
|
+
}
|
|
163
|
+
return ids;
|
|
164
|
+
}
|
|
165
|
+
userHome() {
|
|
166
|
+
return this.ctx.userHome();
|
|
167
|
+
}
|
|
168
|
+
async saveHost(rawHost) {
|
|
169
|
+
return saveHost(this.ctx, rawHost);
|
|
170
|
+
}
|
|
171
|
+
async removeHost(id) {
|
|
172
|
+
return removeHost(this.ctx, id);
|
|
173
|
+
}
|
|
174
|
+
setActiveHost(id) {
|
|
175
|
+
return setActiveHost(this.ctx, id);
|
|
176
|
+
}
|
|
177
|
+
async saveSettings(patch) {
|
|
178
|
+
return saveSettings(this.ctx, patch);
|
|
179
|
+
}
|
|
180
|
+
async listKeyFiles(dir) {
|
|
181
|
+
return listKeyFiles(this.ctx, dir);
|
|
182
|
+
}
|
|
183
|
+
async discoverSshAliases() {
|
|
184
|
+
return discoverSshAliases(this.ctx);
|
|
185
|
+
}
|
|
186
|
+
async connect(id, options = {}) {
|
|
187
|
+
return startConnect(this.ctx, id, options);
|
|
188
|
+
}
|
|
189
|
+
/** Remember or forget the SSH password without connecting; the value never enters `hosts.json`. */
|
|
190
|
+
async saveHostPassword(id, options = {}) {
|
|
191
|
+
await this.init();
|
|
192
|
+
const runtime = runtimeOf(this.ctx, id);
|
|
193
|
+
const available = this.secrets ? this.secrets.available() === true : false;
|
|
194
|
+
if (!available)
|
|
195
|
+
return { available: false, saved: false };
|
|
196
|
+
if (options.clear === true) {
|
|
197
|
+
const removed = await this.secrets.remove(id);
|
|
198
|
+
// The in-memory password belonged to the record just removed: a later connect must ask again.
|
|
199
|
+
runtime.password = null;
|
|
200
|
+
runtime.passwordSaved = !removed;
|
|
201
|
+
this.emitState();
|
|
202
|
+
return { available, saved: false };
|
|
203
|
+
}
|
|
204
|
+
const password = typeof options.password === 'string' ? options.password : '';
|
|
205
|
+
if (password === '') {
|
|
206
|
+
throw errors.invalidInput('password', { zh: '密码不能为空。', en: 'The password must not be empty.' });
|
|
207
|
+
}
|
|
208
|
+
const saved = await this.secrets.set(id, password);
|
|
209
|
+
// An explicit save also arms the in-memory copy, so clicking "connect" next does not ask again
|
|
210
|
+
// for a password this process just proved and stored.
|
|
211
|
+
runtime.password = password;
|
|
212
|
+
runtime.passwordSaved = saved;
|
|
213
|
+
this.emitState();
|
|
214
|
+
return { available, saved };
|
|
215
|
+
}
|
|
216
|
+
async disconnect(id, options = {}) {
|
|
217
|
+
await this.init();
|
|
218
|
+
return disconnectHost(this.ctx, runtimeOf(this.ctx, id), options);
|
|
219
|
+
}
|
|
220
|
+
async reconnect(id) {
|
|
221
|
+
await this.init();
|
|
222
|
+
return reconnectHost(this.ctx, runtimeOf(this.ctx, id));
|
|
223
|
+
}
|
|
224
|
+
/** Restart the managed remote web on the same SSH session (the "Restart remote DSH" card action). */
|
|
225
|
+
async restart(id) {
|
|
226
|
+
await this.init();
|
|
227
|
+
return restartHost(this.ctx, runtimeOf(this.ctx, id));
|
|
228
|
+
}
|
|
229
|
+
/** Stop the managed remote web this connection is bound to, then release the link and leave the host `disconnected`;
|
|
230
|
+
* a refusal (wrong state, busy, unprovable pid) is a coded error (HTTP 409). */
|
|
231
|
+
async stopRemote(id) {
|
|
232
|
+
await this.init();
|
|
233
|
+
return stopRemoteHost(this.ctx, runtimeOf(this.ctx, id));
|
|
234
|
+
}
|
|
235
|
+
async confirmFingerprint(id, decision) {
|
|
236
|
+
return confirmHostKey(this.ctx, runtimeOf(this.ctx, id), decision);
|
|
237
|
+
}
|
|
238
|
+
async confirmConflict(id, decision) {
|
|
239
|
+
return confirmConflict(runtimeOf(this.ctx, id), decision);
|
|
240
|
+
}
|
|
241
|
+
openInfo(id) {
|
|
242
|
+
const runtime = runtimeOf(this.ctx, id);
|
|
243
|
+
if (runtime.status !== 'connected' || !runtime.tunnel || !runtime.token) {
|
|
244
|
+
throw errors.remoteUiUnreachable({
|
|
245
|
+
zh: '主机尚未连接,无法打开远端界面。',
|
|
246
|
+
en: 'The host is not connected yet, so the remote UI cannot be opened.',
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
const token = encodeURIComponent(runtime.token);
|
|
250
|
+
return {
|
|
251
|
+
url: `http://127.0.0.1:${runtime.tunnel.localPort}/?token=${token}`,
|
|
252
|
+
webUrl: `${REMOTE_VIEW_PREFIX}${encodeURIComponent(id)}/?token=${token}`,
|
|
253
|
+
localPort: runtime.tunnel.localPort,
|
|
254
|
+
address: `127.0.0.1:${runtime.tunnel.localPort}`,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
hostIds() {
|
|
258
|
+
return [...this.ctx.state.runtimes.keys()];
|
|
259
|
+
}
|
|
260
|
+
webViewTarget(id) {
|
|
261
|
+
const runtime = this.ctx.state.runtimes.get(id);
|
|
262
|
+
if (!runtime || runtime.status !== 'connected' || !runtime.tunnel)
|
|
263
|
+
return null;
|
|
264
|
+
return { localPort: runtime.tunnel.localPort, remotePort: runtime.remote.port };
|
|
265
|
+
}
|
|
266
|
+
/** One failed proxy request is not a restart: it starts the same probe confirmation the heartbeat uses. */
|
|
267
|
+
noteUpstreamFailure(id) {
|
|
268
|
+
const runtime = this.ctx.state.runtimes.get(id);
|
|
269
|
+
if (!runtime)
|
|
270
|
+
return;
|
|
271
|
+
noteRemoteUnreachable(this.ctx, runtime, 'proxy');
|
|
272
|
+
}
|
|
273
|
+
async diagnose(id) {
|
|
274
|
+
await this.init();
|
|
275
|
+
return diagnoseHost(runtimeOf(this.ctx, id), { targetVersion: this.localVersion });
|
|
276
|
+
}
|
|
277
|
+
async startRemoteDownload(id, path, options = {}) {
|
|
278
|
+
await this.init();
|
|
279
|
+
const runtime = runtimeOf(this.ctx, id);
|
|
280
|
+
const home = this.userHome();
|
|
281
|
+
await requireDestination(options.destination, { home });
|
|
282
|
+
return this.downloads.start(runtime, path, { ...options, home });
|
|
283
|
+
}
|
|
284
|
+
async remoteDownloadStatus(jobId) {
|
|
285
|
+
await this.init();
|
|
286
|
+
return this.downloads.status(jobId);
|
|
287
|
+
}
|
|
288
|
+
async cancelRemoteDownload(jobId) {
|
|
289
|
+
await this.init();
|
|
290
|
+
return this.downloads.cancel(jobId);
|
|
291
|
+
}
|
|
292
|
+
async shutdown() {
|
|
293
|
+
this.uninstallWatchdog?.();
|
|
294
|
+
this.uninstallWatchdog = null;
|
|
295
|
+
this.ctx.state.disposed = true;
|
|
296
|
+
this.ctx.progress.dispose();
|
|
297
|
+
this.downloads.dispose();
|
|
298
|
+
await shutdownAll(this.ctx);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/** Plugin settings: defaults, validation and sanitization; unknown or invalid fields fall back to defaults instead of failing activation. */
|
|
2
|
+
import { DEFAULT_IDLE_MINUTES, DEFAULT_KEY_PATH, DEFAULT_REMOTE_PROFILE, REMOTE_HEARTBEAT_DEFAULT_SEC, REMOTE_HEARTBEAT_MAX_SEC, REMOTE_HEARTBEAT_MIN_SEC, SSH_READY_TIMEOUT_MS, } from './constants.js';
|
|
3
|
+
import { clamp, deepMerge, isPlainObject, parseSshDestination } from './util.js';
|
|
4
|
+
export function defaultSettings() {
|
|
5
|
+
return {
|
|
6
|
+
defaultPort: 22,
|
|
7
|
+
// Only a key file (or a one-time password) is supported: there is no SSH agent path any more,
|
|
8
|
+
// so the default is the key file the wizard pre-fills.
|
|
9
|
+
defaultAuth: 'key',
|
|
10
|
+
defaultKeyPath: DEFAULT_KEY_PATH,
|
|
11
|
+
connectTimeoutSec: Math.round(SSH_READY_TIMEOUT_MS / 1000),
|
|
12
|
+
autoReconnect: { enabled: true, maxAttempts: 5, baseDelayMs: 800 },
|
|
13
|
+
// Light liveness probe: two consecutive failures re-read the remote and re-attach; one never does.
|
|
14
|
+
remoteHeartbeat: { enabled: true, intervalSec: REMOTE_HEARTBEAT_DEFAULT_SEC },
|
|
15
|
+
hostKeyPolicy: 'first-use',
|
|
16
|
+
saveTokens: false,
|
|
17
|
+
language: 'auto',
|
|
18
|
+
logLevel: 'info',
|
|
19
|
+
bootstrap: { profile: DEFAULT_REMOTE_PROFILE },
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/** A profile name DSH can boot: one safe path segment, and never `desktop` (the Electron app reserves that profile and the CLI refuses it). */
|
|
23
|
+
function normalizeProfileName(value) {
|
|
24
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
25
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(text))
|
|
26
|
+
return null;
|
|
27
|
+
if (text.toLowerCase() === 'desktop')
|
|
28
|
+
return null;
|
|
29
|
+
return text;
|
|
30
|
+
}
|
|
31
|
+
function oneOf(value, allowed, fallback) {
|
|
32
|
+
return allowed.includes(value) ? value : fallback;
|
|
33
|
+
}
|
|
34
|
+
function numberIn(value, min, max, fallback) {
|
|
35
|
+
const num = typeof value === 'number' ? value : Number(value);
|
|
36
|
+
if (!Number.isFinite(num))
|
|
37
|
+
return fallback;
|
|
38
|
+
return clamp(Math.round(num), min, max);
|
|
39
|
+
}
|
|
40
|
+
function boolean(value, fallback) {
|
|
41
|
+
return typeof value === 'boolean' ? value : fallback;
|
|
42
|
+
}
|
|
43
|
+
/** A trimmed non-empty string, or `fallback` when the patch names nothing usable. */
|
|
44
|
+
function textOr(value, fallback) {
|
|
45
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback;
|
|
46
|
+
}
|
|
47
|
+
/** A trimmed non-empty string, or `fallback` (null included) when the patch names nothing usable. */
|
|
48
|
+
function optionalText(value, fallback) {
|
|
49
|
+
if (typeof value !== 'string')
|
|
50
|
+
return fallback;
|
|
51
|
+
return value.trim() !== '' ? value.trim() : null;
|
|
52
|
+
}
|
|
53
|
+
export function sanitizeSettings(raw) {
|
|
54
|
+
const defaults = defaultSettings();
|
|
55
|
+
if (!isPlainObject(raw))
|
|
56
|
+
return defaults;
|
|
57
|
+
// A stored file may still carry a retired value (`defaultAuth: "agent"`), so every field is read
|
|
58
|
+
// through a loose view: the type says what a *sanitized* settings object holds, not what the file
|
|
59
|
+
// on disk holds.
|
|
60
|
+
const input = deepMerge(defaults, raw);
|
|
61
|
+
const autoReconnect = isPlainObject(input.autoReconnect) ? input.autoReconnect : defaults.autoReconnect;
|
|
62
|
+
const remoteHeartbeat = isPlainObject(input.remoteHeartbeat) ? input.remoteHeartbeat : defaults.remoteHeartbeat;
|
|
63
|
+
const bootstrap = isPlainObject(input.bootstrap) ? input.bootstrap : defaults.bootstrap;
|
|
64
|
+
const profile = normalizeProfileName(bootstrap.profile) ?? defaults.bootstrap.profile;
|
|
65
|
+
return {
|
|
66
|
+
defaultPort: numberIn(input.defaultPort, 1, 65535, defaults.defaultPort),
|
|
67
|
+
// The retired "agent" choice migrates to key-file auth instead of silently resetting, because
|
|
68
|
+
// key files are the only non-interactive option left.
|
|
69
|
+
defaultAuth: input.defaultAuth === 'agent' ? 'key' : oneOf(input.defaultAuth, ['key', 'password'], defaults.defaultAuth),
|
|
70
|
+
defaultKeyPath: textOr(input.defaultKeyPath, defaults.defaultKeyPath),
|
|
71
|
+
connectTimeoutSec: numberIn(input.connectTimeoutSec, 5, 300, defaults.connectTimeoutSec),
|
|
72
|
+
autoReconnect: {
|
|
73
|
+
enabled: boolean(autoReconnect.enabled, defaults.autoReconnect.enabled),
|
|
74
|
+
maxAttempts: numberIn(autoReconnect.maxAttempts, 0, 20, defaults.autoReconnect.maxAttempts),
|
|
75
|
+
baseDelayMs: numberIn(autoReconnect.baseDelayMs, 100, 30_000, defaults.autoReconnect.baseDelayMs),
|
|
76
|
+
},
|
|
77
|
+
remoteHeartbeat: {
|
|
78
|
+
enabled: boolean(remoteHeartbeat.enabled, defaults.remoteHeartbeat.enabled),
|
|
79
|
+
intervalSec: numberIn(remoteHeartbeat.intervalSec, REMOTE_HEARTBEAT_MIN_SEC, REMOTE_HEARTBEAT_MAX_SEC, defaults.remoteHeartbeat.intervalSec),
|
|
80
|
+
},
|
|
81
|
+
hostKeyPolicy: oneOf(input.hostKeyPolicy, ['first-use', 'strict'], defaults.hostKeyPolicy),
|
|
82
|
+
saveTokens: boolean(input.saveTokens, defaults.saveTokens),
|
|
83
|
+
language: oneOf(input.language, ['auto', 'zh', 'en'], defaults.language),
|
|
84
|
+
logLevel: oneOf(input.logLevel, ['error', 'warn', 'info', 'debug'], defaults.logLevel),
|
|
85
|
+
bootstrap: { profile },
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** The only id shape this plugin issues: `randomId('h')` (docs/api.md `HostView.id`). */
|
|
89
|
+
export const HOST_ID_RE = /^h_[a-z0-9]{1,32}$/;
|
|
90
|
+
/** The persisted auth choice; a payload that names no usable type falls back to the settings default. */
|
|
91
|
+
function readAuthType(auth, existing, settings) {
|
|
92
|
+
if (auth === null)
|
|
93
|
+
return existing?.auth?.type ?? settings.defaultAuth;
|
|
94
|
+
// The retired "agent" choice migrates instead of resetting: key files are the only non-interactive
|
|
95
|
+
// option left, and a silent reset would drop a configured key path from the form.
|
|
96
|
+
if (auth.type === 'agent')
|
|
97
|
+
return 'key';
|
|
98
|
+
return oneOf(auth.type, ['key', 'password'], settings.defaultAuth);
|
|
99
|
+
}
|
|
100
|
+
export function sanitizeHostEntry(raw, options = {}) {
|
|
101
|
+
const settings = options.settings ?? defaultSettings();
|
|
102
|
+
const existing = options.existing ?? null;
|
|
103
|
+
if (!isPlainObject(raw))
|
|
104
|
+
throw new Error('host entry must be an object');
|
|
105
|
+
const name = typeof raw.name === 'string' && raw.name.trim() !== '' ? raw.name.trim().slice(0, 120) : '';
|
|
106
|
+
const address = typeof raw.address === 'string' ? raw.address.trim() : '';
|
|
107
|
+
if (address === '')
|
|
108
|
+
throw new Error('address is required');
|
|
109
|
+
// `parseSshDestination` never returns an `alias`; the fallback below is dead but the order of
|
|
110
|
+
// fallbacks is part of the accepted host-name shape, so it stays.
|
|
111
|
+
const destination = parseSshDestination(address);
|
|
112
|
+
if (!destination.host)
|
|
113
|
+
throw new Error('address is invalid');
|
|
114
|
+
const userInput = typeof raw.username === 'string' ? raw.username.trim() : '';
|
|
115
|
+
const username = userInput || existing?.username || destination.user || '';
|
|
116
|
+
const authPatch = isPlainObject(raw.auth) ? raw.auth : null;
|
|
117
|
+
const authType = readAuthType(authPatch, existing, settings);
|
|
118
|
+
const keyPathInput = authPatch !== null && typeof authPatch.keyPath === 'string' ? authPatch.keyPath.trim() : '';
|
|
119
|
+
const keyPath = keyPathInput || existing?.auth?.keyPath || (authType === 'key' ? settings.defaultKeyPath : '');
|
|
120
|
+
const keepAlive = oneOf(raw.keepAlive, ['keep', 'stop', 'idle'], existing?.keepAlive ?? 'keep');
|
|
121
|
+
const hostKeyPolicy = oneOf(raw.hostKeyPolicy, ['first-use', 'strict'], existing?.hostKeyPolicy ?? settings.hostKeyPolicy);
|
|
122
|
+
return {
|
|
123
|
+
// A malformed or over-long id is never echoed: an id names the secrets entry, the proxy route
|
|
124
|
+
// and the client's host link, so only the shape this plugin issues is accepted.
|
|
125
|
+
id: typeof raw.id === 'string' && HOST_ID_RE.test(raw.id) ? raw.id : (existing?.id ?? undefined),
|
|
126
|
+
name: name || destination.host || destination.alias || 'remote',
|
|
127
|
+
address,
|
|
128
|
+
port: numberIn(raw.port ?? destination.port ?? existing?.port, 1, 65535, settings.defaultPort),
|
|
129
|
+
username: username || null,
|
|
130
|
+
auth: { type: authType, ...(keyPath ? { keyPath } : {}) },
|
|
131
|
+
jumpHost: optionalText(raw.jumpHost, existing?.jumpHost ?? null),
|
|
132
|
+
keepAlive,
|
|
133
|
+
idleMinutes: numberIn(raw.idleMinutes ?? existing?.idleMinutes, 1, 24 * 60, DEFAULT_IDLE_MINUTES),
|
|
134
|
+
autoReconnect: boolean(raw.autoReconnect, existing?.autoReconnect ?? settings.autoReconnect.enabled),
|
|
135
|
+
hostKeyPolicy,
|
|
136
|
+
pinnedFingerprint: typeof raw.pinnedFingerprint === 'string' && raw.pinnedFingerprint.startsWith('SHA256:')
|
|
137
|
+
? raw.pinnedFingerprint
|
|
138
|
+
: (existing?.pinnedFingerprint ?? null),
|
|
139
|
+
createdAt: existing?.createdAt ?? new Date().toISOString(),
|
|
140
|
+
updatedAt: new Date().toISOString(),
|
|
141
|
+
lastOpenedAt: existing?.lastOpenedAt ?? null,
|
|
142
|
+
};
|
|
143
|
+
}
|