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,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin settings: defaults, validation and sanitization; unknown or invalid fields fall back to defaults instead of failing activation.
|
|
3
|
+
*/
|
|
4
|
+
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';
|
|
5
|
+
import { clamp, deepMerge, isPlainObject, parseSshDestination } from './util.js';
|
|
6
|
+
export function defaultSettings() {
|
|
7
|
+
return {
|
|
8
|
+
defaultPort: 22,
|
|
9
|
+
// Only a key file (or a one-time password) is supported: there is no SSH
|
|
10
|
+
// agent path any more, so the default is the key file the wizard pre-fills.
|
|
11
|
+
defaultAuth: 'key',
|
|
12
|
+
defaultKeyPath: DEFAULT_KEY_PATH,
|
|
13
|
+
connectTimeoutSec: Math.round(SSH_READY_TIMEOUT_MS / 1000),
|
|
14
|
+
autoReconnect: { enabled: true, maxAttempts: 5, baseDelayMs: 800 },
|
|
15
|
+
/**
|
|
16
|
+
* Light liveness probe of a connected host's remote UI. Two consecutive
|
|
17
|
+
* failures re-read the remote and re-attach; one failed request never does.
|
|
18
|
+
*/
|
|
19
|
+
remoteHeartbeat: { enabled: true, intervalSec: REMOTE_HEARTBEAT_DEFAULT_SEC },
|
|
20
|
+
hostKeyPolicy: 'first-use',
|
|
21
|
+
saveTokens: false,
|
|
22
|
+
language: 'auto',
|
|
23
|
+
logLevel: 'info',
|
|
24
|
+
bootstrap: {
|
|
25
|
+
profile: DEFAULT_REMOTE_PROFILE,
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A profile name DSH can boot: one safe path segment, and never `desktop`
|
|
31
|
+
* (the Electron app reserves that profile and the CLI refuses it).
|
|
32
|
+
*/
|
|
33
|
+
function normalizeProfileName(value) {
|
|
34
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
35
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(text))
|
|
36
|
+
return null;
|
|
37
|
+
if (text.toLowerCase() === 'desktop')
|
|
38
|
+
return null;
|
|
39
|
+
return text;
|
|
40
|
+
}
|
|
41
|
+
function oneOf(value, allowed, fallback) {
|
|
42
|
+
return allowed.includes(value) ? value : fallback;
|
|
43
|
+
}
|
|
44
|
+
function numberIn(value, min, max, fallback) {
|
|
45
|
+
const num = typeof value === 'number' ? value : Number(value);
|
|
46
|
+
if (!Number.isFinite(num))
|
|
47
|
+
return fallback;
|
|
48
|
+
return clamp(Math.round(num), min, max);
|
|
49
|
+
}
|
|
50
|
+
function boolean(value, fallback) {
|
|
51
|
+
return typeof value === 'boolean' ? value : fallback;
|
|
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
|
|
58
|
+
// read through a loose view: the type says what a *sanitized* settings object holds, not
|
|
59
|
+
// what the file 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
|
|
68
|
+
// resetting, because key files are the only non-interactive option left.
|
|
69
|
+
defaultAuth: input.defaultAuth === 'agent' ? 'key' : oneOf(input.defaultAuth, ['key', 'password'], defaults.defaultAuth),
|
|
70
|
+
defaultKeyPath: typeof input.defaultKeyPath === 'string' && input.defaultKeyPath.trim() !== ''
|
|
71
|
+
? input.defaultKeyPath.trim()
|
|
72
|
+
: defaults.defaultKeyPath,
|
|
73
|
+
connectTimeoutSec: numberIn(input.connectTimeoutSec, 5, 300, defaults.connectTimeoutSec),
|
|
74
|
+
autoReconnect: {
|
|
75
|
+
enabled: boolean(autoReconnect.enabled, defaults.autoReconnect.enabled),
|
|
76
|
+
maxAttempts: numberIn(autoReconnect.maxAttempts, 0, 20, defaults.autoReconnect.maxAttempts),
|
|
77
|
+
baseDelayMs: numberIn(autoReconnect.baseDelayMs, 100, 30_000, defaults.autoReconnect.baseDelayMs),
|
|
78
|
+
},
|
|
79
|
+
remoteHeartbeat: {
|
|
80
|
+
enabled: boolean(remoteHeartbeat.enabled, defaults.remoteHeartbeat.enabled),
|
|
81
|
+
intervalSec: numberIn(remoteHeartbeat.intervalSec, REMOTE_HEARTBEAT_MIN_SEC, REMOTE_HEARTBEAT_MAX_SEC, defaults.remoteHeartbeat.intervalSec),
|
|
82
|
+
},
|
|
83
|
+
hostKeyPolicy: oneOf(input.hostKeyPolicy, ['first-use', 'strict'], defaults.hostKeyPolicy),
|
|
84
|
+
saveTokens: boolean(input.saveTokens, defaults.saveTokens),
|
|
85
|
+
language: oneOf(input.language, ['auto', 'zh', 'en'], defaults.language),
|
|
86
|
+
logLevel: oneOf(input.logLevel, ['error', 'warn', 'info', 'debug'], defaults.logLevel),
|
|
87
|
+
bootstrap: {
|
|
88
|
+
profile,
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/** The only id shape this plugin issues: `randomId('h')` (docs/api.md `HostView.id`). */
|
|
93
|
+
export const HOST_ID_RE = /^h_[a-z0-9]{1,32}$/;
|
|
94
|
+
export function sanitizeHostEntry(raw, options = {}) {
|
|
95
|
+
const settings = options.settings ?? defaultSettings();
|
|
96
|
+
const existing = options.existing ?? null;
|
|
97
|
+
if (!isPlainObject(raw))
|
|
98
|
+
throw new Error('host entry must be an object');
|
|
99
|
+
const name = typeof raw.name === 'string' && raw.name.trim() !== '' ? raw.name.trim().slice(0, 120) : '';
|
|
100
|
+
const address = typeof raw.address === 'string' ? raw.address.trim() : '';
|
|
101
|
+
if (address === '')
|
|
102
|
+
throw new Error('address is required');
|
|
103
|
+
// `parseSshDestination` never returns an `alias`; the fallback below is dead but the order
|
|
104
|
+
// of fallbacks is part of the accepted host-name shape, so it stays.
|
|
105
|
+
const destination = parseSshDestination(address);
|
|
106
|
+
if (!destination.host)
|
|
107
|
+
throw new Error('address is invalid');
|
|
108
|
+
const userInput = typeof raw.username === 'string' ? raw.username.trim() : '';
|
|
109
|
+
const username = userInput || existing?.username || destination.user || '';
|
|
110
|
+
const authType = raw.auth && isPlainObject(raw.auth)
|
|
111
|
+
? raw.auth.type === 'agent'
|
|
112
|
+
? 'key'
|
|
113
|
+
: oneOf(raw.auth.type, ['key', 'password'], settings.defaultAuth)
|
|
114
|
+
: (existing?.auth?.type ?? settings.defaultAuth);
|
|
115
|
+
const keyPathInput = raw.auth && isPlainObject(raw.auth) && typeof raw.auth.keyPath === 'string' ? raw.auth.keyPath.trim() : '';
|
|
116
|
+
const keyPath = keyPathInput || existing?.auth?.keyPath || (authType === 'key' ? settings.defaultKeyPath : '');
|
|
117
|
+
const keepAlive = oneOf(raw.keepAlive, ['keep', 'stop', 'idle'], existing?.keepAlive ?? 'keep');
|
|
118
|
+
const hostKeyPolicy = oneOf(raw.hostKeyPolicy, ['first-use', 'strict'], existing?.hostKeyPolicy ?? settings.hostKeyPolicy);
|
|
119
|
+
return {
|
|
120
|
+
// A malformed or over-long id is never echoed: an id names the secrets entry, the proxy
|
|
121
|
+
// route and the client's host link, so only the shape this plugin issues is accepted.
|
|
122
|
+
id: typeof raw.id === 'string' && HOST_ID_RE.test(raw.id) ? raw.id : (existing?.id ?? undefined),
|
|
123
|
+
name: name || destination.host || destination.alias || 'remote',
|
|
124
|
+
address,
|
|
125
|
+
port: numberIn(raw.port ?? destination.port ?? existing?.port, 1, 65535, settings.defaultPort),
|
|
126
|
+
username: username || null,
|
|
127
|
+
auth: { type: authType, ...(keyPath ? { keyPath } : {}) },
|
|
128
|
+
jumpHost: typeof raw.jumpHost === 'string'
|
|
129
|
+
? raw.jumpHost.trim() !== ''
|
|
130
|
+
? raw.jumpHost.trim()
|
|
131
|
+
: null
|
|
132
|
+
: (existing?.jumpHost ?? null),
|
|
133
|
+
keepAlive,
|
|
134
|
+
idleMinutes: numberIn(raw.idleMinutes ?? existing?.idleMinutes, 1, 24 * 60, DEFAULT_IDLE_MINUTES),
|
|
135
|
+
autoReconnect: boolean(raw.autoReconnect, existing?.autoReconnect ?? settings.autoReconnect.enabled),
|
|
136
|
+
hostKeyPolicy,
|
|
137
|
+
pinnedFingerprint: typeof raw.pinnedFingerprint === 'string' && raw.pinnedFingerprint.startsWith('SHA256:')
|
|
138
|
+
? raw.pinnedFingerprint
|
|
139
|
+
: (existing?.pinnedFingerprint ?? null),
|
|
140
|
+
createdAt: existing?.createdAt ?? new Date().toISOString(),
|
|
141
|
+
updatedAt: new Date().toISOString(),
|
|
142
|
+
lastOpenedAt: existing?.lastOpenedAt ?? null,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only `~/.ssh/config` parsing and alias discovery for the subset `ssh_config(5)` defines; `Include`, `Match` and `ProxyCommand` are reported, not guessed.
|
|
3
|
+
*/
|
|
4
|
+
const KNOWN_OPTIONS = new Set([
|
|
5
|
+
'hostname',
|
|
6
|
+
'user',
|
|
7
|
+
'port',
|
|
8
|
+
'identityfile',
|
|
9
|
+
'certificatefile',
|
|
10
|
+
'proxyjump',
|
|
11
|
+
'proxycommand',
|
|
12
|
+
'serveraliveinterval',
|
|
13
|
+
'serveralivecountmax',
|
|
14
|
+
'connecttimeout',
|
|
15
|
+
'identitiesonly',
|
|
16
|
+
'preferredauthentications',
|
|
17
|
+
]);
|
|
18
|
+
function parseLine(line) {
|
|
19
|
+
const trimmed = line.trim();
|
|
20
|
+
if (trimmed === '' || trimmed.startsWith('#'))
|
|
21
|
+
return null;
|
|
22
|
+
const eq = trimmed.indexOf('=');
|
|
23
|
+
const space = trimmed.search(/\s/);
|
|
24
|
+
let keyword;
|
|
25
|
+
let value;
|
|
26
|
+
if (eq >= 0 && (space < 0 || eq < space)) {
|
|
27
|
+
keyword = trimmed.slice(0, eq);
|
|
28
|
+
value = trimmed.slice(eq + 1);
|
|
29
|
+
}
|
|
30
|
+
else if (space >= 0) {
|
|
31
|
+
keyword = trimmed.slice(0, space);
|
|
32
|
+
value = trimmed.slice(space + 1);
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
keyword = trimmed;
|
|
36
|
+
value = '';
|
|
37
|
+
}
|
|
38
|
+
value = value.trim();
|
|
39
|
+
if ((value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
|
|
40
|
+
(value.startsWith("'") && value.endsWith("'") && value.length >= 2)) {
|
|
41
|
+
value = value.slice(1, -1);
|
|
42
|
+
}
|
|
43
|
+
return { keyword: keyword.trim(), value };
|
|
44
|
+
}
|
|
45
|
+
function splitPatterns(value) {
|
|
46
|
+
const patterns = [];
|
|
47
|
+
const negated = [];
|
|
48
|
+
for (const token of value.split(/\s+/)) {
|
|
49
|
+
if (token === '')
|
|
50
|
+
continue;
|
|
51
|
+
if (token.startsWith('!'))
|
|
52
|
+
negated.push(token.slice(1));
|
|
53
|
+
else
|
|
54
|
+
patterns.push(token);
|
|
55
|
+
}
|
|
56
|
+
return { patterns, negated };
|
|
57
|
+
}
|
|
58
|
+
export function parseSshConfig(text) {
|
|
59
|
+
const entries = [];
|
|
60
|
+
const globals = {};
|
|
61
|
+
const unsupported = [];
|
|
62
|
+
const malformed = [];
|
|
63
|
+
let current = null;
|
|
64
|
+
const lines = String(text ?? '').split(/\r?\n/);
|
|
65
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
66
|
+
const lineNo = index + 1;
|
|
67
|
+
const parsed = parseLine(lines[index]);
|
|
68
|
+
if (!parsed)
|
|
69
|
+
continue;
|
|
70
|
+
const keyword = parsed.keyword.toLowerCase();
|
|
71
|
+
if (keyword === 'host') {
|
|
72
|
+
const { patterns, negated } = splitPatterns(parsed.value);
|
|
73
|
+
current = { patterns, negated, options: {}, line: lineNo };
|
|
74
|
+
if (patterns.length === 0)
|
|
75
|
+
malformed.push({ line: lineNo, text: lines[index] });
|
|
76
|
+
else
|
|
77
|
+
entries.push(current);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (keyword === 'match') {
|
|
81
|
+
unsupported.push({ line: lineNo, keyword: 'Match' });
|
|
82
|
+
// Options inside a Match block only apply under conditions we cannot
|
|
83
|
+
// evaluate; skip them until the next Host block.
|
|
84
|
+
current = { patterns: ['__dsh_remote_go_match_block__'], negated: [], options: {}, line: lineNo };
|
|
85
|
+
entries.push(current);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (keyword === 'include') {
|
|
89
|
+
unsupported.push({ line: lineNo, keyword: 'Include' });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (!KNOWN_OPTIONS.has(keyword)) {
|
|
93
|
+
// Unknown-but-harmless options are ignored; only flag keywords that would
|
|
94
|
+
// change meaning if misread.
|
|
95
|
+
if (keyword === 'proxycommand' || keyword === 'certificatefile')
|
|
96
|
+
unsupported.push({ line: lineNo, keyword: parsed.keyword });
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (parsed.value === '') {
|
|
100
|
+
malformed.push({ line: lineNo, text: lines[index] });
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (current) {
|
|
104
|
+
current.options[keyword] = current.options[keyword] ?? [];
|
|
105
|
+
current.options[keyword].push(parsed.value);
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
globals[keyword] = globals[keyword] ?? [];
|
|
109
|
+
globals[keyword].push(parsed.value);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return { entries, globals, unsupported, malformed };
|
|
113
|
+
}
|
|
114
|
+
export function matchHostPattern(pattern, value) {
|
|
115
|
+
if (pattern === '*')
|
|
116
|
+
return true;
|
|
117
|
+
const escaped = pattern
|
|
118
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
119
|
+
.replace(/\*/g, '.*')
|
|
120
|
+
.replace(/\?/g, '.');
|
|
121
|
+
return new RegExp(`^${escaped}$`, 'i').test(value);
|
|
122
|
+
}
|
|
123
|
+
export function entryMatches(entry, alias) {
|
|
124
|
+
if (entry.patterns.includes('__dsh_remote_go_match_block__'))
|
|
125
|
+
return false;
|
|
126
|
+
const positive = entry.patterns.some((pattern) => matchHostPattern(pattern, alias));
|
|
127
|
+
if (!positive)
|
|
128
|
+
return false;
|
|
129
|
+
return !entry.negated.some((pattern) => matchHostPattern(pattern, alias));
|
|
130
|
+
}
|
|
131
|
+
const ADDITIVE_OPTIONS = new Set(['identityfile', 'certificatefile']);
|
|
132
|
+
function effectiveOptions(globals, entries, alias, tokens) {
|
|
133
|
+
const out = {};
|
|
134
|
+
const apply = (options) => {
|
|
135
|
+
for (const [key, values] of Object.entries(options)) {
|
|
136
|
+
const expanded = values.map((value) => expandTokens(value, tokens));
|
|
137
|
+
if (ADDITIVE_OPTIONS.has(key)) {
|
|
138
|
+
out[key] = [...(out[key] ?? []), ...expanded];
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (out[key] !== undefined)
|
|
142
|
+
continue;
|
|
143
|
+
out[key] = expanded;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
apply(globals);
|
|
147
|
+
for (const entry of entries) {
|
|
148
|
+
if (entryMatches(entry, alias))
|
|
149
|
+
apply(entry.options);
|
|
150
|
+
}
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
export function expandTokens(value, tokens) {
|
|
154
|
+
return String(value).replace(/%([hprd%])/g, (match, token) => {
|
|
155
|
+
if (token === '%')
|
|
156
|
+
return '%';
|
|
157
|
+
return tokens[token] ?? match;
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
function expandTilde(value, home) {
|
|
161
|
+
if (value === '~')
|
|
162
|
+
return home;
|
|
163
|
+
if (value.startsWith('~/'))
|
|
164
|
+
return `${home.replace(/[\\/]+$/, '')}/${value.slice(2)}`;
|
|
165
|
+
return value;
|
|
166
|
+
}
|
|
167
|
+
export function resolveSshAlias(parsed, alias, options = {}) {
|
|
168
|
+
const home = options.home ?? '~';
|
|
169
|
+
const baseTokens = { h: alias, r: '~', p: '22', d: home };
|
|
170
|
+
const firstPass = effectiveOptions(parsed.globals, parsed.entries, alias, baseTokens);
|
|
171
|
+
const host = firstPass.hostname?.[0] ?? alias;
|
|
172
|
+
const user = firstPass.user?.[0] ?? null;
|
|
173
|
+
const rawPort = firstPass.port?.[0] ?? '22';
|
|
174
|
+
const port = /^\d+$/.test(rawPort) ? Number(rawPort) : 22;
|
|
175
|
+
const tokens = { h: host, r: user ?? '~', p: String(port), d: home };
|
|
176
|
+
const resolved = effectiveOptions(parsed.globals, parsed.entries, alias, tokens);
|
|
177
|
+
const identityFiles = (resolved.identityfile ?? []).map((value) => expandTilde(value, home));
|
|
178
|
+
const proxyJump = resolved.proxyjump?.[0] ?? null;
|
|
179
|
+
return {
|
|
180
|
+
alias,
|
|
181
|
+
host,
|
|
182
|
+
user,
|
|
183
|
+
port,
|
|
184
|
+
identityFiles,
|
|
185
|
+
proxyJump,
|
|
186
|
+
source: 'config',
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* List concrete, manually-dialable aliases from the config. Wildcard patterns
|
|
191
|
+
* (`*`, `?`) and negations are skipped because they cannot be resolved without
|
|
192
|
+
* a concrete target.
|
|
193
|
+
*/
|
|
194
|
+
export function discoverSshAliases(parsed, options = {}) {
|
|
195
|
+
const out = [];
|
|
196
|
+
const seen = new Set();
|
|
197
|
+
for (const entry of parsed.entries) {
|
|
198
|
+
for (const pattern of entry.patterns) {
|
|
199
|
+
if (pattern.includes('*') || pattern.includes('?') || pattern.startsWith('__dsh_remote_go_'))
|
|
200
|
+
continue;
|
|
201
|
+
if (seen.has(pattern))
|
|
202
|
+
continue;
|
|
203
|
+
seen.add(pattern);
|
|
204
|
+
const resolved = resolveSshAlias(parsed, pattern, options);
|
|
205
|
+
out.push({ alias: pattern, host: resolved.host, user: resolved.user, port: resolved.port, source: 'config' });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
export function resolveDestination(destination, options = {}) {
|
|
211
|
+
const text = String(destination ?? '').trim();
|
|
212
|
+
const literal = parseDestinationLiteral(text);
|
|
213
|
+
const parsed = parseSshConfig(options.configText ?? '');
|
|
214
|
+
const home = options.home ?? '~';
|
|
215
|
+
const aliases = discoverSshAliases(parsed, { home });
|
|
216
|
+
const alias = aliases.find((item) => item.alias === text);
|
|
217
|
+
if (alias) {
|
|
218
|
+
const resolved = resolveSshAlias(parsed, text, { home });
|
|
219
|
+
return {
|
|
220
|
+
input: text,
|
|
221
|
+
alias: text,
|
|
222
|
+
host: resolved.host,
|
|
223
|
+
user: literal.user ?? resolved.user,
|
|
224
|
+
port: literal.port ?? resolved.port,
|
|
225
|
+
identityFiles: resolved.identityFiles,
|
|
226
|
+
proxyJump: resolved.proxyJump,
|
|
227
|
+
source: 'config',
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
// Literal destination: inherit globals (e.g. a global IdentityFile) but not
|
|
231
|
+
// Host blocks that do not match the literal text.
|
|
232
|
+
const tokens = { h: literal.host, r: literal.user ?? '~', p: String(literal.port ?? 22), d: home };
|
|
233
|
+
const globals = effectiveOptions(parsed.globals, [], text, tokens);
|
|
234
|
+
const identityFiles = (globals.identityfile ?? []).map((value) => expandTilde(value, home));
|
|
235
|
+
return {
|
|
236
|
+
input: text,
|
|
237
|
+
alias: null,
|
|
238
|
+
host: literal.host,
|
|
239
|
+
user: literal.user,
|
|
240
|
+
port: literal.port ?? 22,
|
|
241
|
+
identityFiles,
|
|
242
|
+
proxyJump: globals.proxyjump?.[0] ?? null,
|
|
243
|
+
source: 'manual',
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
function parseDestinationLiteral(text) {
|
|
247
|
+
let user = null;
|
|
248
|
+
let rest = text;
|
|
249
|
+
const at = rest.lastIndexOf('@');
|
|
250
|
+
if (at >= 0) {
|
|
251
|
+
user = rest.slice(0, at);
|
|
252
|
+
rest = rest.slice(at + 1);
|
|
253
|
+
}
|
|
254
|
+
let host = rest;
|
|
255
|
+
let port = null;
|
|
256
|
+
if (rest.startsWith('[')) {
|
|
257
|
+
const close = rest.indexOf(']');
|
|
258
|
+
if (close > 0) {
|
|
259
|
+
host = rest.slice(1, close);
|
|
260
|
+
const tail = rest.slice(close + 1);
|
|
261
|
+
if (/^:\d+$/.test(tail))
|
|
262
|
+
port = Number(tail.slice(1));
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
const colon = rest.lastIndexOf(':');
|
|
267
|
+
if (colon > 0 && rest.indexOf(':') === colon) {
|
|
268
|
+
const maybePort = rest.slice(colon + 1);
|
|
269
|
+
if (/^\d{1,5}$/.test(maybePort)) {
|
|
270
|
+
host = rest.slice(0, colon);
|
|
271
|
+
port = Number(maybePort);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return { user: user || null, host, port };
|
|
276
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSH failure classification: the one place that turns a transport failure into the coded,
|
|
3
|
+
* bilingual error the Client renders (decision D2).
|
|
4
|
+
*
|
|
5
|
+
* Both adapters share it — the ssh2 one and the test double — so "which code and which sentence
|
|
6
|
+
* does this failure produce" has exactly one answer. The client-visible wording comes from
|
|
7
|
+
* `errors.ts`; this module only decides *which* factory applies, which is why extracting it keeps
|
|
8
|
+
* the text byte-for-byte identical to the pre-P5 `toSshError`.
|
|
9
|
+
*
|
|
10
|
+
* The three details the table pins and that must not be "simplified" away:
|
|
11
|
+
* - `errors.network` is retryable for connection failures, `errors.auth` too, and
|
|
12
|
+
* `host-key-changed` is not — that row decides whether the Client offers "Retry";
|
|
13
|
+
* - `exec` timeouts are **results** (`SshExecResult.timedOut`), never exceptions, so no timeout
|
|
14
|
+
* factory is called from the exec path;
|
|
15
|
+
* - a `RemoteGoError` that already reached us is the contract's own failure and is passed
|
|
16
|
+
* through untouched (the host-key factories build theirs directly).
|
|
17
|
+
*/
|
|
18
|
+
import { errors, RemoteGoError } from './errors.js';
|
|
19
|
+
import { headTail } from './util.js';
|
|
20
|
+
/**
|
|
21
|
+
* The typed "the transport is gone" failure: retryable network, never a bare internal error.
|
|
22
|
+
*
|
|
23
|
+
* The wording and the `reason=ssh-closed` technical string are frozen: `exec`, `forwardOut` and
|
|
24
|
+
* the SFTP entry points have raised exactly this sentence since the first release, and callers
|
|
25
|
+
* (plus tests) match on it.
|
|
26
|
+
*/
|
|
27
|
+
export function closedError() {
|
|
28
|
+
return errors.network({
|
|
29
|
+
zh: 'SSH 连接已断开,本次操作没有完成;如果主机仍在线,重连即可继续。',
|
|
30
|
+
en: 'SSH connection is not open; the transport closed before this step finished.',
|
|
31
|
+
}, { technical: 'reason=ssh-closed' });
|
|
32
|
+
}
|
|
33
|
+
/** The endpoint a host-key failure names in its sentence. */
|
|
34
|
+
function endpointOf(context) {
|
|
35
|
+
const host = context.host ?? 'the host';
|
|
36
|
+
const port = context.port ?? 22;
|
|
37
|
+
return `${host}:${port}`;
|
|
38
|
+
}
|
|
39
|
+
/** The host-key failure an adapter reports when it has no more specific factory to call. */
|
|
40
|
+
function hostKeyFailure(context) {
|
|
41
|
+
const endpoint = endpointOf(context);
|
|
42
|
+
return errors.network({
|
|
43
|
+
zh: `主机密钥校验未通过(${endpoint})。`,
|
|
44
|
+
en: `Host key verification failed for ${endpoint}.`,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
/** The factory one explicit kind maps to; see the table in design-ssh §5. */
|
|
48
|
+
function failureOfKind(kind, context) {
|
|
49
|
+
if (kind === 'closed')
|
|
50
|
+
return closedError();
|
|
51
|
+
if (kind === 'auth')
|
|
52
|
+
return errors.auth();
|
|
53
|
+
if (kind === 'hostkey')
|
|
54
|
+
return hostKeyFailure(context);
|
|
55
|
+
// `transport` and `timeout` are the same client-visible failure: a retryable network error.
|
|
56
|
+
// The timeout row exists so an adapter can label a handshake deadline without inventing a
|
|
57
|
+
// second sentence for it (an `exec` deadline never reaches this function at all).
|
|
58
|
+
return errors.network();
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Turn any thrown value into the error the contract may expose.
|
|
62
|
+
*
|
|
63
|
+
* Rules, in order (each one is the pre-P5 `toSshError` rule, unchanged):
|
|
64
|
+
* 1. an already-coded `RemoteGoError` passes through;
|
|
65
|
+
* 2. an explicit `kind` chooses the factory without inspecting the message;
|
|
66
|
+
* 3. a host-key-looking message → network with the host-key sentence;
|
|
67
|
+
* 4. an authentication-looking message → `auth`;
|
|
68
|
+
* 5. a connection/timeout code or message → default `network`;
|
|
69
|
+
* 6. anything else → `network` with `SSH 连接失败:<headTail(message, 300)>`.
|
|
70
|
+
*
|
|
71
|
+
* @param error - the thrown value; `unknown` because every caller catches one.
|
|
72
|
+
* @param context - the endpoint (for the sentence) and the adapter's optional kind label.
|
|
73
|
+
* @returns the coded error; never throws.
|
|
74
|
+
*/
|
|
75
|
+
export function classifySshFailure(error, context = {}) {
|
|
76
|
+
if (error instanceof RemoteGoError)
|
|
77
|
+
return error;
|
|
78
|
+
if (context.kind !== undefined)
|
|
79
|
+
return failureOfKind(context.kind, context);
|
|
80
|
+
if (!error)
|
|
81
|
+
return errors.internal('unknown ssh error');
|
|
82
|
+
// A thrown value is `unknown`: the `as` restates the two fields a node/ssh2 transport error
|
|
83
|
+
// carries, and the `??` fallbacks keep a thrown string working.
|
|
84
|
+
const message = String(error.message ?? error);
|
|
85
|
+
const code = String(error.code ?? '');
|
|
86
|
+
if (/host key|hostkey|verification/i.test(message))
|
|
87
|
+
return hostKeyFailure(context);
|
|
88
|
+
if (/authentication|All configured authentication methods failed|Permission denied/i.test(message)) {
|
|
89
|
+
return errors.auth();
|
|
90
|
+
}
|
|
91
|
+
if (/ECONNREFUSED|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|timed out|timeout|Cannot connect|connect failed/i.test(`${code} ${message}`)) {
|
|
92
|
+
return errors.network();
|
|
93
|
+
}
|
|
94
|
+
return errors.network({
|
|
95
|
+
zh: `SSH 连接失败:${headTail(message, 300)}`,
|
|
96
|
+
en: `SSH connection failed: ${headTail(message, 300)}`,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The historical name for {@link classifySshFailure}.
|
|
101
|
+
*
|
|
102
|
+
* It stays an alias (not a copy) so the two can never drift: callers/tests that have always
|
|
103
|
+
* imported `toSshError(error, host, port)` keep working, and there is exactly one rule table.
|
|
104
|
+
* @param error - the thrown value.
|
|
105
|
+
* @param host - the endpoint the failure is about.
|
|
106
|
+
* @param port - the endpoint's port.
|
|
107
|
+
*/
|
|
108
|
+
export function toSshError(error, host, port) {
|
|
109
|
+
return classifySshFailure(error, { host, port });
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Whether one thrown value is one of the two host-key refusals.
|
|
113
|
+
*
|
|
114
|
+
* `connect()`'s auth-candidate loop must rethrow these instead of trying the next credential: a
|
|
115
|
+
* rejected key is a policy decision, not an authentication failure.
|
|
116
|
+
* @param error - the thrown value.
|
|
117
|
+
*/
|
|
118
|
+
export function isHostKeyError(error) {
|
|
119
|
+
// Same narrowing as the classifier: a thrown value is `unknown`, and only its `code` is read.
|
|
120
|
+
const code = error?.code;
|
|
121
|
+
return code === 'host-key-changed' || code === 'host-key-unknown';
|
|
122
|
+
}
|