forked from webpod/webpod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssh.ts
303 lines (283 loc) · 7.87 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import {spawn, spawnSync} from 'node:child_process'
import process from 'node:process'
import {createGzip} from 'node:zlib'
import fs from 'node:fs'
import {addr, controlPath, escapeshellarg} from './utils.js'
import chalk from 'chalk'
import {progressMessage} from './spinner.js'
type Values = (string | string[] | Promise<string> | Promise<string[]>)[]
export type RemoteShell = {
(pieces: TemplateStringsArray, ...values: Values): Promise<Response>
with(config: Partial<SshConfig>): RemoteShell
exit(): void
check(): boolean
test(pieces: TemplateStringsArray, ...values: Values): Promise<boolean>;
cd(path: string): void
}
export type SshConfig = {
remoteUser: string
hostname: string
port?: number | string
shell: string
prefix: string
cwd?: string
nothrow: boolean
multiplexing: boolean
verbose: boolean
become?: string
env: Record<string, string>
ssh: SshOptions
}
export function ssh(partial: Partial<SshConfig>): RemoteShell {
const config: SshConfig = {
remoteUser: partial.remoteUser ?? 'root',
hostname: partial.hostname ?? 'localhost',
port: partial.port,
shell: partial.shell ?? 'bash -s',
prefix: partial.prefix ?? 'set -euo pipefail; ',
cwd: partial.cwd,
nothrow: partial.nothrow ?? false,
multiplexing: partial.multiplexing ?? true,
verbose: partial.verbose ?? false,
become: partial.become,
env: partial.env ?? {},
ssh: partial.ssh ?? {},
}
const $ = async function (pieces, ...values) {
const location = 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 ${location}`)
}
let resolve: (out: Response) => void, reject: (out: Response) => void
const promise = new Promise<Response>((...args) => ([resolve, reject] = args))
const args = sshArgs(config)
const id = 'id$' + Math.random().toString(36).slice(2)
args.push(
`: ${id}; ` +
(config.become ? `sudo -H -u ${escapeshellarg(config.become)} ` : '') +
env(config.env) +
config.shell
)
const cmd = await composeCmd(pieces, values)
const cmdFull = config.prefix + workingDir(config.cwd) + cmd
if (debug !== '') {
if (debug.includes('ssh')) args.unshift('-vvv')
console.error(chalk.grey(`ssh ${args.map(escapeshellarg).join(' ')} <<< ${escapeshellarg(cmdFull)}`))
}
if (config.verbose) {
console.error(`${chalk.green.bold(`${config.become ?? config.remoteUser}@${config.hostname}`)}${chalk.magenta.bold(`:${config.cwd ?? ''}`)}${chalk.bold.blue(`$`)} ${chalk.bold(cmd)}`)
}
const child = spawn('ssh', args, {
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
})
let stdout = '', stderr = ''
child.stdout.on('data', data => {
if (config.verbose) process.stdout.write(data)
stdout += data
progressMessage(data.toString())
})
child.stderr.on('data', data => {
if (debug.includes('ssh') && /^debug\d:/.test(data)) {
process.stderr.write(data)
return
}
if (config.verbose) process.stderr.write(data)
stderr += data
progressMessage(data.toString())
})
child.on('close', (code) => {
if (code === 0 || config.nothrow)
resolve(new Response(cmd, location, code, stdout, stderr))
else
reject(new Response(cmd, location, code, stdout, stderr))
})
child.on('error', err => {
reject(new Response(cmd, location, null, stdout, stderr, err))
})
child.stdin.write(cmdFull)
child.stdin.end()
return promise
} as RemoteShell
$.with = (override) => ssh({
...config, ...override,
ssh: {...config.ssh, ...override.ssh ?? {}}
})
$.exit = () => spawnSync('ssh', [addr(config),
'-o', `ControlPath=${controlPath(addr(config))}`,
'-O', 'exit',
])
$.check = () => spawnSync('ssh', [addr(config),
'-o', `ControlPath=${controlPath(addr(config))}`,
'-O', 'check',
]).status == 0
$.test = async (pieces, ...values) => {
try {
await $(pieces, ...values)
return true
} catch {
return false
}
}
$.cd = (path) => {
config.cwd = path
}
return $
}
export function sshArgs(config: Partial<SshConfig>): string[] {
let options: SshOptions = {
ControlMaster: 'auto',
ControlPath: controlPath(addr(config)),
ControlPersist: '5m',
ConnectTimeout: '5s',
StrictHostKeyChecking: 'accept-new',
}
if (config.port != undefined) {
options.Port = config.port.toString()
}
if (config.multiplexing === false) {
delete options.ControlMaster
delete options.ControlPath
delete options.ControlPersist
}
options = {...options, ...config.ssh}
return [
addr(config),
...Object.entries(options).flatMap(
([key, value]) => ['-o', `${key}=${value}`]
),
]
}
function workingDir(cwd: string | undefined): string {
if (cwd == undefined || cwd == '') {
return ``
}
return `cd ${escapeshellarg(cwd)}; `
}
function env(env: Record<string, string>): string {
return Object.entries(env)
.map(([key, value]) => {
if (key.endsWith('++')) {
return `${key.replace(/\++$/, '')}=$PATH:${escapeshellarg(value)} `
} else {
return `${key}=${escapeshellarg(value)} `
}
})
.join('')
}
export class Response extends String {
constructor(
public readonly command: string,
public readonly location: string,
public readonly exitCode: number | null,
public readonly stdout: string,
public readonly stderr: string,
public readonly error?: Error
) {
super(stdout.trim())
}
}
export async function composeCmd(pieces: TemplateStringsArray, values: Values) {
let cmd = pieces[0], i = 0
while (i < values.length) {
const v = await values[i]
let s = ''
if (Array.isArray(v)) {
s = v.map(escapeshellarg).join(' ')
} else {
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'