forked from webpod/webpod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssh.ts
212 lines (206 loc) · 5.47 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
import { spawn, spawnSync } from 'node:child_process'
import process from 'node:process'
import { composeCmd, controlPath, escapeshellarg } from './utils.js'
export type RemoteShell = {
(config: Config): RemoteShell
(pieces: TemplateStringsArray, ...values: any[]): Promise<Result>
exit: () => void
check: () => boolean
}
export type Config = {
port?: number | string
forwardAgent?: boolean
shell?: string
prefix?: string
nothrow?: boolean
options?: SshOptions
}
export function ssh(host: string, config: Config = {}): RemoteShell {
const $ = function (piecesOrConfig, ...values) {
if (!Array.isArray(piecesOrConfig)) {
const override: Config = piecesOrConfig as Config
return ssh(host, {
...config, ...override,
options: {...config.options, ...override.options},
})
}
const pieces = piecesOrConfig as TemplateStringsArray
const source = new Error().stack!.split(/^\s*at\s/m)[2].trim()
if (pieces.some(p => p == undefined)) {
throw new Error(`Malformed command at ${source}`)
}
let resolve: (out: Result) => void, reject: (out: Result) => void
const promise = new Promise<Result>((...args) => ([resolve, reject] = args))
const cmd = composeCmd(pieces, values)
const shellId = 'id$' + Math.random().toString(36).slice(2)
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'
}
options = {...options, ...config.options}
const args: string[] = [
host,
...Object.entries(options).flatMap(
([key, value]) => ['-o', `${key}=${value}`]
),
`: ${shellId}; ${config.shell ?? 'bash -ls'}`
]
let input = config.prefix ?? 'set -euo pipefail; '
input += cmd
if (process.env.WEBPOD_DEBUG) {
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 => {
stderr += data
combined += data
})
child.on('close', (code) => {
(code === 0 || config.nothrow ? resolve : reject)(
new Result(source, shellId, code, stdout, stderr, combined)
)
})
child.on('error', err => {
reject(
new Result(source, shellId, null, stdout, stderr, combined, err)
)
})
child.stdin.write(input)
child.stdin.end()
return promise
} as RemoteShell
$.exit = () => spawnSync('ssh', [host,
'-o', `ControlPath=${controlPath(host)}`,
'-O', 'exit',
])
$.check = () => spawnSync('ssh', [host,
'-o', `ControlPath=${controlPath(host)}`,
'-O', 'check',
]).status == 0
return $
}
export class Result extends Error {
constructor(
public readonly source: string,
public readonly shellId: string,
public readonly exitCode: number | null,
public readonly stdout: string,
public readonly stderr: string,
public readonly combined: string,
public readonly error?: Error
) {
super(combined + (error?.message || ''))
}
}
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'