forked from webpod/webpod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssh.ts
253 lines (236 loc) · 6.35 KB
/
ssh.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import {spawn, spawnSync} from 'node:child_process'
import process from 'node:process'
import {controlPath, escapeshellarg} from './utils.js'
export type RemoteShell = {
(pieces: TemplateStringsArray, ...values: (string | Promise<string>)[]): Promise<Response>
with(config: Config): RemoteShell
exit(): void
check(): boolean
test(pieces: TemplateStringsArray, ...values: (string | Promise<string>)[]): Promise<boolean>;
cd(path: string): void
}
export type Config = {
port?: number | string
forwardAgent?: boolean
shell?: string
prefix?: string
cwd?: string
nothrow?: boolean
multiplexing?: boolean
options?: SshOptions
}
export function ssh(host: string, config: Config = {}): RemoteShell {
const $ = async function (pieces, ...values) {
const source = new Error().stack!.split(/^\s*at\s/m)[2].trim()
const debug = process.env['WEBPOD_DEBUG'] ?? ''
if (pieces.some(p => p == undefined)) {
throw new Error(`Malformed command at ${source}`)
}
let resolve: (out: Response) => void, reject: (out: Response) => void
const promise = new Promise<Response>((...args) => ([resolve, reject] = args))
const stringValues: string[] = []
for (const value of values) {
stringValues.push(await value)
}
const cmd = composeCmd(pieces, stringValues)
let options: SshOptions = {
ControlMaster: 'auto',
ControlPath: controlPath(host),
ControlPersist: '5m',
ConnectTimeout: '5s',
ForwardAgent: 'yes',
StrictHostKeyChecking: 'accept-new',
}
if (config.port != undefined) {
options.Port = config.port.toString()
}
if (config.forwardAgent != undefined) {
options.ForwardAgent = config.forwardAgent ? 'yes' : 'no'
}
if (config.multiplexing === false) {
options.ControlMaster = 'no'
options.ControlPath = 'none'
options.ControlPersist = 'no'
}
options = {...options, ...config.options}
const id = 'id$' + Math.random().toString(36).slice(2)
const args: string[] = [
host,
...Object.entries(options).flatMap(
([key, value]) => ['-o', `${key}=${value}`]
),
`: ${id}; ${config.shell ?? 'bash -ls'}`
]
let input = config.prefix ?? 'set -euo pipefail; '
if (config.cwd != undefined) {
input += `cd ${escapeshellarg(config.cwd)}; `
}
input += cmd
if (debug !== '') {
if (debug.includes('ssh')) args.unshift('-vvv')
console.error('ssh', args.map(escapeshellarg).join(' '), '<<<', escapeshellarg(input))
}
const child = spawn('ssh', args, {
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
})
let stdout = '', stderr = '', combined = ''
child.stdout.on('data', data => {
stdout += data
combined += data
})
child.stderr.on('data', data => {
if (debug.includes('ssh') && /^debug\d:/.test(data)) {
process.stderr.write(data)
return
}
stderr += data
combined += data
})
child.on('close', (code) => {
if (code === 0 || config.nothrow)
resolve(new Response(source, code, stdout, stderr))
else
reject(new Response(source, code, stdout, stderr))
})
child.on('error', err => {
reject(new Response(source, null, stdout, stderr, err))
})
child.stdin.write(input)
child.stdin.end()
return promise
} as RemoteShell
$.with = (override) => ssh(host, {
...config, ...override,
options: {...config.options, ...override.options}
})
$.exit = () => spawnSync('ssh', [host,
'-o', `ControlPath=${controlPath(host)}`,
'-O', 'exit',
])
$.check = () => spawnSync('ssh', [host,
'-o', `ControlPath=${controlPath(host)}`,
'-O', 'check',
]).status == 0
$.test = async (pieces, ...values) => {
try {
await $(pieces, ...values)
return true
} catch {
return false
}
}
$.cd = (path) => {
config.cwd = path
}
return $
}
export class Response extends String {
constructor(
public readonly source: string,
public readonly exitCode: number | null,
public readonly stdout: string,
public readonly stderr: string,
public readonly error?: Error
) {
super(stdout.trim())
}
}
export function composeCmd(pieces: TemplateStringsArray, values: string[]) {
let cmd = pieces[0], i = 0
while (i < values.length) {
let v = values[i]
let s = escapeshellarg(v.toString())
cmd += s + pieces[++i]
}
return cmd
}
type SshOptions = { [key in AvailableOptions]?: string }
type AvailableOptions =
'AddKeysToAgent' |
'AddressFamily' |
'BatchMode' |
'BindAddress' |
'CanonicalDomains' |
'CanonicalizeFallbackLocal' |
'CanonicalizeHostname' |
'CanonicalizeMaxDots' |
'CanonicalizePermittedCNAMEs' |
'CASignatureAlgorithms' |
'CertificateFile' |
'ChallengeResponseAuthentication' |
'CheckHostIP' |
'Ciphers' |
'ClearAllForwardings' |
'Compression' |
'ConnectionAttempts' |
'ConnectTimeout' |
'ControlMaster' |
'ControlPath' |
'ControlPersist' |
'DynamicForward' |
'EscapeChar' |
'ExitOnForwardFailure' |
'FingerprintHash' |
'ForwardAgent' |
'ForwardX11' |
'ForwardX11Timeout' |
'ForwardX11Trusted' |
'GatewayPorts' |
'GlobalKnownHostsFile' |
'GSSAPIAuthentication' |
'GSSAPIDelegateCredentials' |
'HashKnownHosts' |
'Host' |
'HostbasedAcceptedAlgorithms' |
'HostbasedAuthentication' |
'HostKeyAlgorithms' |
'HostKeyAlias' |
'Hostname' |
'IdentitiesOnly' |
'IdentityAgent' |
'IdentityFile' |
'IPQoS' |
'KbdInteractiveAuthentication' |
'KbdInteractiveDevices' |
'KexAlgorithms' |
'KnownHostsCommand' |
'LocalCommand' |
'LocalForward' |
'LogLevel' |
'MACs' |
'Match' |
'NoHostAuthenticationForLocalhost' |
'NumberOfPasswordPrompts' |
'PasswordAuthentication' |
'PermitLocalCommand' |
'PermitRemoteOpen' |
'PKCS11Provider' |
'Port' |
'PreferredAuthentications' |
'ProxyCommand' |
'ProxyJump' |
'ProxyUseFdpass' |
'PubkeyAcceptedAlgorithms' |
'PubkeyAuthentication' |
'RekeyLimit' |
'RemoteCommand' |
'RemoteForward' |
'RequestTTY' |
'SendEnv' |
'ServerAliveInterval' |
'ServerAliveCountMax' |
'SetEnv' |
'StreamLocalBindMask' |
'StreamLocalBindUnlink' |
'StrictHostKeyChecking' |
'TCPKeepAlive' |
'Tunnel' |
'TunnelDevice' |
'UpdateHostKeys' |
'UseKeychain' |
'User' |
'UserKnownHostsFile' |
'VerifyHostKeyDNS' |
'VisualHostKey' |
'XAuthLocation'