dsh-ssh-hub 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +271 -2
- package/cordis.patch.yml +16 -0
- package/icon.svg +3 -0
- package/lib/client.js +13975 -0
- package/lib/index.js +6908 -0
- package/lib/types/activity/history.d.ts +50 -0
- package/lib/types/alerting/notify.d.ts +89 -0
- package/lib/types/alerting/prompt-summary.d.ts +28 -0
- package/lib/types/alerting/rules.d.ts +135 -0
- package/lib/types/alerting/tools.d.ts +30 -0
- package/lib/types/audit/audit-log.d.ts +84 -0
- package/lib/types/audit/recorder.d.ts +50 -0
- package/lib/types/client/api.d.ts +222 -0
- package/lib/types/client/index.d.ts +45 -0
- package/lib/types/client/locales.d.ts +319 -0
- package/lib/types/client/native-panel.d.ts +70 -0
- package/lib/types/client/panel/ClusterTab.d.ts +7 -0
- package/lib/types/client/panel/DeployTab.d.ts +10 -0
- package/lib/types/client/panel/FleetTab.d.ts +10 -0
- package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
- package/lib/types/client/panel/HostsTab.d.ts +25 -0
- package/lib/types/client/panel/LogsTab.d.ts +10 -0
- package/lib/types/client/panel/SshPanel.d.ts +14 -0
- package/lib/types/client/panel/TerminalTab.d.ts +27 -0
- package/lib/types/client/panel/TransferTab.d.ts +7 -0
- package/lib/types/client/panel/TunnelEditDialog.d.ts +15 -0
- package/lib/types/client/panel/TunnelsTab.d.ts +27 -0
- package/lib/types/client/panel/controller.d.ts +253 -0
- package/lib/types/client/panel/helpers.d.ts +45 -0
- package/lib/types/client/panel/tabs.d.ts +62 -0
- package/lib/types/client/panel/xterm.css.d.ts +2 -0
- package/lib/types/client/settings-binding.d.ts +71 -0
- package/lib/types/deploy/orchestrator.d.ts +158 -0
- package/lib/types/deploy/tools.d.ts +14 -0
- package/lib/types/dsh-home.d.ts +16 -0
- package/lib/types/engine/cluster.d.ts +19 -0
- package/lib/types/engine/connection-pool.d.ts +183 -0
- package/lib/types/engine/proxy-command.d.ts +36 -0
- package/lib/types/engine/pty.d.ts +32 -0
- package/lib/types/engine/sftp.d.ts +20 -0
- package/lib/types/engine/terminal-sessions.d.ts +67 -0
- package/lib/types/engine/tunnel-discovery.d.ts +89 -0
- package/lib/types/engine/tunnel-remarks.d.ts +49 -0
- package/lib/types/engine/tunnel.d.ts +76 -0
- package/lib/types/engine.d.ts +103 -0
- package/lib/types/http.d.ts +59 -0
- package/lib/types/index.d.ts +128 -0
- package/lib/types/inspect/checks.d.ts +118 -0
- package/lib/types/inspect/inspection.d.ts +111 -0
- package/lib/types/inspect/tools.d.ts +50 -0
- package/lib/types/logs/search.d.ts +131 -0
- package/lib/types/logs/tools.d.ts +6 -0
- package/lib/types/loopback.d.ts +64 -0
- package/lib/types/monitor/loop.d.ts +133 -0
- package/lib/types/monitor/metrics.d.ts +151 -0
- package/lib/types/mount-once.d.ts +55 -0
- package/lib/types/protocol.d.ts +524 -0
- package/lib/types/routes.d.ts +82 -0
- package/lib/types/security/known-hosts.d.ts +153 -0
- package/lib/types/security/master-secret.d.ts +157 -0
- package/lib/types/security/redact.d.ts +44 -0
- package/lib/types/security/secrets.d.ts +70 -0
- package/lib/types/ssh-config.d.ts +42 -0
- package/lib/types/store.d.ts +183 -0
- package/lib/types/tool-surface.d.ts +72 -0
- package/lib/types/tools.d.ts +56 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +126 -6
- package/src/activity/history.ts +117 -0
- package/src/alerting/notify.ts +212 -0
- package/src/alerting/prompt-summary.ts +71 -0
- package/src/alerting/rules.ts +281 -0
- package/src/alerting/tools.ts +263 -0
- package/src/audit/audit-log.ts +199 -0
- package/src/audit/recorder.ts +73 -0
- package/src/client/api.ts +782 -0
- package/src/client/css-modules.d.ts +5 -0
- package/src/client/index.ts +150 -0
- package/src/client/locales.ts +654 -0
- package/src/client/native-panel.tsx +141 -0
- package/src/client/panel/ClusterTab.tsx +141 -0
- package/src/client/panel/DeployTab.tsx +314 -0
- package/src/client/panel/FleetTab.tsx +494 -0
- package/src/client/panel/HostFormDialog.tsx +289 -0
- package/src/client/panel/HostsTab.tsx +395 -0
- package/src/client/panel/LogsTab.tsx +208 -0
- package/src/client/panel/SshPanel.tsx +105 -0
- package/src/client/panel/TerminalTab.tsx +550 -0
- package/src/client/panel/TransferTab.tsx +238 -0
- package/src/client/panel/TunnelEditDialog.tsx +174 -0
- package/src/client/panel/TunnelsTab.tsx +328 -0
- package/src/client/panel/controller.ts +507 -0
- package/src/client/panel/helpers.ts +84 -0
- package/src/client/panel/panel.module.css +1734 -0
- package/src/client/panel/tabs.ts +52 -0
- package/src/client/panel/xterm.css.ts +2 -0
- package/src/client/settings-binding.ts +184 -0
- package/src/deploy/orchestrator.ts +326 -0
- package/src/deploy/tools.ts +225 -0
- package/src/dsh-home.ts +42 -0
- package/src/engine/cluster.ts +60 -0
- package/src/engine/connection-pool.ts +721 -0
- package/src/engine/proxy-command.ts +248 -0
- package/src/engine/pty.ts +78 -0
- package/src/engine/sftp.ts +229 -0
- package/src/engine/terminal-sessions.ts +280 -0
- package/src/engine/tunnel-discovery.ts +353 -0
- package/src/engine/tunnel-remarks.ts +120 -0
- package/src/engine/tunnel.ts +300 -0
- package/src/engine.ts +195 -0
- package/src/http.ts +127 -0
- package/src/index.ts +690 -0
- package/src/inspect/checks.ts +251 -0
- package/src/inspect/inspection.ts +321 -0
- package/src/inspect/tools.ts +366 -0
- package/src/logs/search.ts +251 -0
- package/src/logs/tools.ts +160 -0
- package/src/loopback.ts +119 -0
- package/src/monitor/loop.ts +265 -0
- package/src/monitor/metrics.ts +333 -0
- package/src/mount-once.ts +142 -0
- package/src/protocol.ts +534 -0
- package/src/routes.ts +998 -0
- package/src/security/known-hosts.ts +342 -0
- package/src/security/master-secret.ts +334 -0
- package/src/security/redact.ts +119 -0
- package/src/security/secrets.ts +152 -0
- package/src/ssh-config.ts +182 -0
- package/src/store.ts +757 -0
- package/src/tool-surface.ts +96 -0
- package/src/tools.ts +550 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Output redaction for remote command results.
|
|
3
|
+
*
|
|
4
|
+
* The base plugin returns exec and cluster output verbatim. That output is
|
|
5
|
+
* the model's context AND, in DSH, part of the session log — so a command
|
|
6
|
+
* like `env` or `cat /etc/redis.conf` writes the remote secrets into a
|
|
7
|
+
* transcript that outlives the session and lands in every backup of it.
|
|
8
|
+
*
|
|
9
|
+
* This module redacts the shapes a secret actually takes in command
|
|
10
|
+
* output. It is a safety net, not a guarantee: the tool cannot know every
|
|
11
|
+
* secret on the remote host. The tool description says so, so the model
|
|
12
|
+
* does not treat the redacted output as safe to reason about freely.
|
|
13
|
+
*
|
|
14
|
+
* Redaction is deliberately conservative about what it hides — a false
|
|
15
|
+
* positive costs a little context, a false negative costs a credential.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** One redaction rule. */
|
|
19
|
+
interface RedactionRule {
|
|
20
|
+
/** The rule name (used in the report). */
|
|
21
|
+
id: string
|
|
22
|
+
/** The pattern to match. */
|
|
23
|
+
pattern: RegExp
|
|
24
|
+
/** The replacement; `$1` style groups are preserved. */
|
|
25
|
+
replacement: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The rules, in order.
|
|
30
|
+
*
|
|
31
|
+
* The `g` flag is required on each: without it only the first match in a
|
|
32
|
+
* line would be redacted, and `env` prints one secret per line.
|
|
33
|
+
*/
|
|
34
|
+
const RULES: readonly RedactionRule[] = [
|
|
35
|
+
{
|
|
36
|
+
id: 'private-key',
|
|
37
|
+
pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g,
|
|
38
|
+
replacement: '[REDACTED PRIVATE KEY]',
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
id: 'authorization-header',
|
|
42
|
+
pattern: /(Authorization\s*[:=]\s*)(?:Bearer|Basic|Token)\s+\S+/gi,
|
|
43
|
+
replacement: '$1[REDACTED]',
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
id: 'aws-key',
|
|
47
|
+
pattern: /\bAKIA[0-9A-Z]{16}\b/g,
|
|
48
|
+
replacement: '[REDACTED AWS KEY ID]',
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
id: 'bearer-token',
|
|
52
|
+
pattern: /\bBearer\s+[A-Za-z0-9._~+/-]{20,}=*/g,
|
|
53
|
+
replacement: 'Bearer [REDACTED]',
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
id: 'password-assignment',
|
|
57
|
+
// `PASSWORD=secret`, `password: secret`, `api_key=secret` ...
|
|
58
|
+
pattern: /\b([A-Za-z0-9_.-]*(?:password|passwd|secret|token|api[_-]?key|access[_-]?key)[A-Za-z0-9_.-]*)(\s*[:=]\s*)("?)([^\s"']+)\3/gi,
|
|
59
|
+
replacement: '$1$2[REDACTED]',
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
id: 'connection-string',
|
|
63
|
+
pattern: /\b([a-z][a-z0-9+.-]*:\/\/)([^\s:@/]+):([^\s@/]+)@/gi,
|
|
64
|
+
replacement: '$1$2:[REDACTED]@',
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
id: 'jwt',
|
|
68
|
+
pattern: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,
|
|
69
|
+
replacement: '[REDACTED JWT]',
|
|
70
|
+
},
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Redact secrets from command output.
|
|
75
|
+
*
|
|
76
|
+
* @param text - the output to redact.
|
|
77
|
+
* @returns the redacted text.
|
|
78
|
+
*/
|
|
79
|
+
export function redactOutput(text: string): string {
|
|
80
|
+
if (text === '') return text
|
|
81
|
+
let result = text
|
|
82
|
+
for (const rule of RULES) {
|
|
83
|
+
result = result.replace(rule.pattern, rule.replacement)
|
|
84
|
+
}
|
|
85
|
+
return result
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Redact a command line before it is logged or displayed.
|
|
90
|
+
*
|
|
91
|
+
* A command may itself carry a secret as an argument (`mysql -p hunter2`,
|
|
92
|
+
* `curl -H 'Authorization: Bearer ...'`), which the output rules would
|
|
93
|
+
* never see.
|
|
94
|
+
*
|
|
95
|
+
* @param command - the command line.
|
|
96
|
+
* @returns the redacted command.
|
|
97
|
+
*/
|
|
98
|
+
export function redactCommand(command: string): string {
|
|
99
|
+
let result = command
|
|
100
|
+
// `mysql -p secret` / `psql --password secret`
|
|
101
|
+
result = result.replace(/(\s-p\s+)(\S+)/g, '$1[REDACTED]')
|
|
102
|
+
result = result.replace(/(--password[= ])(\S+)/g, '$1[REDACTED]')
|
|
103
|
+
// An inline `--header 'Authorization: Bearer ...'`
|
|
104
|
+
result = result.replace(/(Authorization:\s*)(Bearer\s+)?\S+/gi, '$1[REDACTED]')
|
|
105
|
+
return result
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Which rules matched an output.
|
|
110
|
+
*
|
|
111
|
+
* Useful for the audit log: the operator can see that a result was
|
|
112
|
+
* redacted without seeing what was hidden.
|
|
113
|
+
*
|
|
114
|
+
* @param text - the original text.
|
|
115
|
+
* @returns the ids of the rules that matched.
|
|
116
|
+
*/
|
|
117
|
+
export function matchedRules(text: string): string[] {
|
|
118
|
+
return RULES.filter(rule => rule.pattern.test(text)).map(rule => rule.id)
|
|
119
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential encryption: an encrypted envelope for the secrets that live
|
|
3
|
+
* alongside a host entry (passwords, key passphrases).
|
|
4
|
+
*
|
|
5
|
+
* The base plugin stored those in plaintext inside `dsh-ssh.json` — a
|
|
6
|
+
* user-owned file, but plaintext means every backup, every accidental
|
|
7
|
+
* copy and every process running as the same user can read them.
|
|
8
|
+
*
|
|
9
|
+
* The envelope here is deliberately simple and auditable:
|
|
10
|
+
* - a random 32-byte data key encrypts the payload (AES-256-GCM)
|
|
11
|
+
* - the data key is itself wrapped with a key derived from a master secret
|
|
12
|
+
* (scrypt, with a per-file random salt)
|
|
13
|
+
* - authentication is GCM's, so a tampered file fails to decrypt rather
|
|
14
|
+
* than yielding garbage
|
|
15
|
+
*
|
|
16
|
+
* The master secret comes from the environment (`DSH_SSH_HUB_SECRET`), a
|
|
17
|
+
* key file, or the DSH credentials service. There is deliberately NO
|
|
18
|
+
* default: a default master secret would be a backdoor, and silently
|
|
19
|
+
* falling back to plaintext would defeat the point of encrypting at all.
|
|
20
|
+
* When no secret is configured, `secretsEnabled` is false and the store
|
|
21
|
+
* keeps the base plugin's plaintext behaviour.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto'
|
|
25
|
+
|
|
26
|
+
/** The envelope version, so a future format change can be detected. */
|
|
27
|
+
export const ENVELOPE_VERSION = 1
|
|
28
|
+
|
|
29
|
+
/** The encrypted form of one secret. */
|
|
30
|
+
export interface SealedSecret {
|
|
31
|
+
/** Envelope version. */
|
|
32
|
+
v: number
|
|
33
|
+
/** Algorithm tag ('aes-256-gcm'). */
|
|
34
|
+
alg: string
|
|
35
|
+
/** Base64 salt for the key derivation. */
|
|
36
|
+
salt: string
|
|
37
|
+
/** Base64 initialisation vector. */
|
|
38
|
+
iv: string
|
|
39
|
+
/** Base64 authentication tag. */
|
|
40
|
+
tag: string
|
|
41
|
+
/** Base64 ciphertext. */
|
|
42
|
+
data: string
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The scrypt cost parameters. */
|
|
46
|
+
const SCRYPT_KEYLEN = 32
|
|
47
|
+
const SCRYPT_OPTIONS = { N: 16384, r: 8, p: 1 } as const
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Derive the wrapping key from the master secret and the file salt.
|
|
51
|
+
*
|
|
52
|
+
* @param secret - the master secret.
|
|
53
|
+
* @param salt - the per-file random salt.
|
|
54
|
+
* @returns the 32-byte wrapping key.
|
|
55
|
+
*/
|
|
56
|
+
function deriveWrappingKey(secret: string, salt: Buffer): Buffer {
|
|
57
|
+
return scryptSync(secret, salt, SCRYPT_KEYLEN, SCRYPT_OPTIONS)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Encrypt one secret value.
|
|
62
|
+
*
|
|
63
|
+
* Two layers, each with its own IV — GCM requires a unique nonce per key,
|
|
64
|
+
* so the payload cipher and the key-wrap cipher must never share one.
|
|
65
|
+
*
|
|
66
|
+
* @param plaintext - the secret to protect.
|
|
67
|
+
* @param masterSecret - the master secret.
|
|
68
|
+
* @returns the sealed envelope.
|
|
69
|
+
*/
|
|
70
|
+
export function seal(plaintext: string, masterSecret: string): SealedSecret {
|
|
71
|
+
const salt = randomBytes(16)
|
|
72
|
+
// One IV per cipher: reusing a nonce across keys is exactly the mistake
|
|
73
|
+
// GCM punishes.
|
|
74
|
+
const dataIv = randomBytes(12)
|
|
75
|
+
const wrapIv = randomBytes(12)
|
|
76
|
+
const wrappingKey = deriveWrappingKey(masterSecret, salt)
|
|
77
|
+
// The data key is random per secret; only it touches the plaintext.
|
|
78
|
+
const dataKey = randomBytes(32)
|
|
79
|
+
const cipher = createCipheriv('aes-256-gcm', dataKey, dataIv)
|
|
80
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])
|
|
81
|
+
const tag = cipher.getAuthTag()
|
|
82
|
+
const wrapper = createCipheriv('aes-256-gcm', wrappingKey, wrapIv)
|
|
83
|
+
const wrappedKey = Buffer.concat([wrapper.update(dataKey), wrapper.final()])
|
|
84
|
+
const wrapperTag = wrapper.getAuthTag()
|
|
85
|
+
return {
|
|
86
|
+
v: ENVELOPE_VERSION,
|
|
87
|
+
alg: 'aes-256-gcm',
|
|
88
|
+
salt: salt.toString('base64'),
|
|
89
|
+
// Both IVs travel together, each still unique to its cipher.
|
|
90
|
+
iv: Buffer.concat([wrapIv, dataIv]).toString('base64'),
|
|
91
|
+
tag: Buffer.concat([wrapperTag, tag]).toString('base64'),
|
|
92
|
+
data: Buffer.concat([wrappedKey, ciphertext]).toString('base64'),
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Decrypt one sealed secret.
|
|
98
|
+
*
|
|
99
|
+
* @param envelope - the sealed envelope.
|
|
100
|
+
* @param masterSecret - the master secret.
|
|
101
|
+
* @returns the plaintext.
|
|
102
|
+
* @throws when the envelope is malformed, tampered with, or was sealed with
|
|
103
|
+
* a different master secret.
|
|
104
|
+
*/
|
|
105
|
+
export function open(envelope: SealedSecret, masterSecret: string): string {
|
|
106
|
+
if (envelope === null || typeof envelope !== 'object') throw new Error('sealed secret is not an object')
|
|
107
|
+
if (envelope.v !== ENVELOPE_VERSION) throw new Error(`unsupported secret envelope version: ${String(envelope.v)}`)
|
|
108
|
+
if (envelope.alg !== 'aes-256-gcm') throw new Error(`unsupported secret algorithm: ${String(envelope.alg)}`)
|
|
109
|
+
const salt = Buffer.from(envelope.salt, 'base64')
|
|
110
|
+
const ivs = Buffer.from(envelope.iv, 'base64')
|
|
111
|
+
const tagAndAuth = Buffer.from(envelope.tag, 'base64')
|
|
112
|
+
const payload = Buffer.from(envelope.data, 'base64')
|
|
113
|
+
if (salt.length === 0 || ivs.length !== 24 || tagAndAuth.length < 16 || payload.length < 32) {
|
|
114
|
+
throw new Error('sealed secret is malformed')
|
|
115
|
+
}
|
|
116
|
+
const wrapIv = ivs.subarray(0, 12)
|
|
117
|
+
const dataIv = ivs.subarray(12, 24)
|
|
118
|
+
const wrapperTag = tagAndAuth.subarray(0, 16)
|
|
119
|
+
const authTag = tagAndAuth.subarray(16)
|
|
120
|
+
const wrappingKey = deriveWrappingKey(masterSecret, salt)
|
|
121
|
+
const wrapper = createDecipheriv('aes-256-gcm', wrappingKey, wrapIv)
|
|
122
|
+
wrapper.setAuthTag(wrapperTag)
|
|
123
|
+
let dataKey: Buffer
|
|
124
|
+
try {
|
|
125
|
+
dataKey = Buffer.concat([wrapper.update(payload.subarray(0, 32)), wrapper.final()])
|
|
126
|
+
} catch {
|
|
127
|
+
throw new Error('sealed secret cannot be decrypted: wrong master secret or the file was tampered with')
|
|
128
|
+
}
|
|
129
|
+
const decipher = createDecipheriv('aes-256-gcm', dataKey, dataIv)
|
|
130
|
+
decipher.setAuthTag(authTag)
|
|
131
|
+
try {
|
|
132
|
+
return Buffer.concat([decipher.update(payload.subarray(32)), decipher.final()]).toString('utf8')
|
|
133
|
+
} catch {
|
|
134
|
+
throw new Error('sealed secret cannot be decrypted: wrong master secret or the file was tampered with')
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Is a value already a sealed envelope?
|
|
140
|
+
*
|
|
141
|
+
* Used when reading a store that may hold either form (a store written
|
|
142
|
+
* before encryption was enabled still holds plaintext).
|
|
143
|
+
*
|
|
144
|
+
* @param value - the value to inspect.
|
|
145
|
+
* @returns true when the value is an envelope.
|
|
146
|
+
*/
|
|
147
|
+
export function isSealed(value: unknown): value is SealedSecret {
|
|
148
|
+
return typeof value === 'object' && value !== null
|
|
149
|
+
&& typeof (value as SealedSecret).v === 'number'
|
|
150
|
+
&& typeof (value as SealedSecret).alg === 'string'
|
|
151
|
+
&& typeof (value as SealedSecret).data === 'string'
|
|
152
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal `~/.ssh/config` reader for the one-shot host import: Host blocks with
|
|
3
|
+
* `Include` expansion and explicit skip reasons. Values stay raw strings; the
|
|
4
|
+
* store maps them onto a HostPayload.
|
|
5
|
+
*
|
|
6
|
+
* Deliberate simplifications (documented in the package README):
|
|
7
|
+
* - `Match` blocks are skipped — their options are conditional and must never
|
|
8
|
+
* merge into the Host block above them.
|
|
9
|
+
* - A multi-pattern `Host a b` line only exposes its first pattern.
|
|
10
|
+
* - Include pathnames accept `~`, globs, and several whitespace-separated
|
|
11
|
+
* pathnames, but not environment variables, `%` tokens, or quoting.
|
|
12
|
+
* - Relative Include pathnames resolve against the directory of the config
|
|
13
|
+
* file the import started from (OpenSSH: `~/.ssh` for a user config).
|
|
14
|
+
* - A file that already contributed lines is never read twice, which doubles
|
|
15
|
+
* as the Include cycle guard.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'
|
|
19
|
+
import { homedir } from 'node:os'
|
|
20
|
+
import { dirname, isAbsolute, join } from 'node:path'
|
|
21
|
+
import type { ImportSkipBlock } from './protocol.ts'
|
|
22
|
+
|
|
23
|
+
/** One parsed Host block. */
|
|
24
|
+
export interface SshBlock {
|
|
25
|
+
/** Raw Host line value (may hold several whitespace-separated patterns). */
|
|
26
|
+
pattern: string
|
|
27
|
+
/** Lowercased option key/value pairs; the last occurrence of a key wins. */
|
|
28
|
+
props: Record<string, string>
|
|
29
|
+
/**
|
|
30
|
+
* Every value seen for a key that legitimately repeats, in file order.
|
|
31
|
+
* `IdentityFile` may appear several times and OpenSSH tries each one, so
|
|
32
|
+
* keeping only the last occurrence silently breaks a host that relies on a
|
|
33
|
+
* second key — `ssh <alias>` works while this plugin reports "All configured
|
|
34
|
+
* authentication methods failed".
|
|
35
|
+
*/
|
|
36
|
+
repeated: Record<string, string[]>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** One config file read, with every Include expanded in place. */
|
|
40
|
+
export interface SshConfigRead {
|
|
41
|
+
blocks: SshBlock[]
|
|
42
|
+
skipped: ImportSkipBlock[]
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Include recursion guard: a cycle or a runaway chain stops here. */
|
|
46
|
+
const MAX_INCLUDE_DEPTH = 16
|
|
47
|
+
|
|
48
|
+
/** The only line shape ssh_config knows: `Keyword value...` (case-insensitive). */
|
|
49
|
+
const LINE_RE = /^([A-Za-z0-9_-]+)\s+(.+)$/
|
|
50
|
+
|
|
51
|
+
/** Expand a leading `~` the way OpenSSH does for user configuration files. */
|
|
52
|
+
function expandTilde(path: string): string {
|
|
53
|
+
if (path === '~') return homedir()
|
|
54
|
+
if (path.startsWith('~/')) return join(homedir(), path.slice(2))
|
|
55
|
+
return path
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Turn one glob segment into a matcher (`*` and `?` only). */
|
|
59
|
+
function segmentMatcher(segment: string): RegExp {
|
|
60
|
+
const escaped = segment.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
61
|
+
return new RegExp('^' + escaped.replace(/\*/g, '.*').replace(/\?/g, '.') + '$')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Expand a segment list against the filesystem. Wildcards match whole segments
|
|
66
|
+
* only; matches are sorted so a glob import stays deterministic.
|
|
67
|
+
*/
|
|
68
|
+
function globSegments(prefix: string, segments: string[]): string[] {
|
|
69
|
+
const [head, ...rest] = segments
|
|
70
|
+
if (head === undefined) return [prefix]
|
|
71
|
+
if (!/[*?]/.test(head)) return globSegments(join(prefix, head), rest)
|
|
72
|
+
let names: string[]
|
|
73
|
+
try {
|
|
74
|
+
names = readdirSync(prefix)
|
|
75
|
+
} catch {
|
|
76
|
+
return []
|
|
77
|
+
}
|
|
78
|
+
const matcher = segmentMatcher(head)
|
|
79
|
+
return names.filter(name => matcher.test(name)).sort().flatMap(name => globSegments(join(prefix, name), rest))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Resolve one Include pathname into the existing regular files it names. */
|
|
83
|
+
function resolveInclude(spec: string, baseDir: string): string[] {
|
|
84
|
+
const expanded = expandTilde(spec)
|
|
85
|
+
const full = isAbsolute(expanded) ? expanded : join(baseDir, expanded)
|
|
86
|
+
if (!/[*?]/.test(full)) return existsSync(full) ? [full] : []
|
|
87
|
+
const root = /^([A-Za-z]:[\\/]|[\\/])/.exec(full)?.[1] ?? ''
|
|
88
|
+
const segments = full.slice(root.length).split(/[\\/]+/).filter(part => part !== '')
|
|
89
|
+
const files = globSegments(root === '' ? '.' : root, segments)
|
|
90
|
+
return files.filter(path => {
|
|
91
|
+
try {
|
|
92
|
+
return statSync(path).isFile()
|
|
93
|
+
} catch {
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Read one file into lines, splicing every `Include` in place. */
|
|
100
|
+
function readLines(file: string, baseDir: string, visited: Set<string>, depth: number): string[] {
|
|
101
|
+
if (depth > MAX_INCLUDE_DEPTH) return []
|
|
102
|
+
let key: string
|
|
103
|
+
try {
|
|
104
|
+
key = realpathSync(file)
|
|
105
|
+
} catch {
|
|
106
|
+
return []
|
|
107
|
+
}
|
|
108
|
+
if (visited.has(key)) return []
|
|
109
|
+
visited.add(key)
|
|
110
|
+
let text: string
|
|
111
|
+
try {
|
|
112
|
+
text = readFileSync(key, 'utf8')
|
|
113
|
+
} catch {
|
|
114
|
+
return []
|
|
115
|
+
}
|
|
116
|
+
const out: string[] = []
|
|
117
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
118
|
+
const match = LINE_RE.exec(raw.trim())
|
|
119
|
+
if (match === null || match[1].toLowerCase() !== 'include') {
|
|
120
|
+
out.push(raw)
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
for (const spec of match[2].trim().split(/\s+/).filter(part => part !== '')) {
|
|
124
|
+
for (const included of resolveInclude(spec, baseDir)) {
|
|
125
|
+
out.push(...readLines(included, baseDir, visited, depth + 1))
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return out
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Parse one ssh_config file (Include expanded) into Host blocks plus the
|
|
134
|
+
* `Match` blocks that were deliberately skipped.
|
|
135
|
+
*/
|
|
136
|
+
export function readSshConfigBlocks(configPath: string): SshConfigRead {
|
|
137
|
+
const blocks: SshBlock[] = []
|
|
138
|
+
const skipped: ImportSkipBlock[] = []
|
|
139
|
+
const lines = readLines(configPath, dirname(configPath), new Set<string>(), 0)
|
|
140
|
+
let current: SshBlock | undefined
|
|
141
|
+
let pendingComments: string[] = []
|
|
142
|
+
for (const raw of lines) {
|
|
143
|
+
const trimmed = raw.trim()
|
|
144
|
+
if (trimmed.startsWith('#')) {
|
|
145
|
+
const commentText = trimmed.replace(/^#+\s*/, '').trim()
|
|
146
|
+
if (commentText !== '') pendingComments.push(commentText)
|
|
147
|
+
continue
|
|
148
|
+
}
|
|
149
|
+
if (trimmed === '') {
|
|
150
|
+
pendingComments = []
|
|
151
|
+
continue
|
|
152
|
+
}
|
|
153
|
+
const match = LINE_RE.exec(trimmed)
|
|
154
|
+
if (match === null) continue
|
|
155
|
+
const key = match[1].toLowerCase()
|
|
156
|
+
const value = match[2].trim()
|
|
157
|
+
if (key === 'host') {
|
|
158
|
+
current = { pattern: value, props: {}, repeated: {} }
|
|
159
|
+
if (pendingComments.length > 0) {
|
|
160
|
+
current.props.description = pendingComments.join('; ')
|
|
161
|
+
pendingComments = []
|
|
162
|
+
}
|
|
163
|
+
blocks.push(current)
|
|
164
|
+
continue
|
|
165
|
+
}
|
|
166
|
+
if (key === 'match') {
|
|
167
|
+
pendingComments = []
|
|
168
|
+
// Everything below a Match line is conditional; attributing it to the
|
|
169
|
+
// Host block above would import a wrong HostName / ProxyCommand.
|
|
170
|
+
skipped.push({ name: 'Match ' + value, reason: 'match' })
|
|
171
|
+
current = undefined
|
|
172
|
+
continue
|
|
173
|
+
}
|
|
174
|
+
if (current !== undefined) {
|
|
175
|
+
current.props[key] = value
|
|
176
|
+
const seen = current.repeated[key]
|
|
177
|
+
if (seen === undefined) current.repeated[key] = [value]
|
|
178
|
+
else seen.push(value)
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return { blocks, skipped }
|
|
182
|
+
}
|