Repository navigation
Expand file tree
/
Copy pathinit.ts
More file actions
822 lines (744 loc) · 23.7 KB
/
Copy pathinit.ts
File metadata and controls
822 lines (744 loc) · 23.7 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
import {Args, Command, Flags} from '@oclif/core'
import * as dns from 'node:dns'
import fs from 'node:fs/promises'
import * as os from 'node:os'
import * as path from 'node:path'
import * as child from 'node:child_process'
import * as net from 'node:net'
import {NodeSSH} from 'node-ssh'
import {select, input, password as inquirerPassword} from '@inquirer/prompts'
import {addDisco, isDiscoAlreadyInConfig} from '../config.js'
import {SingleBar} from 'cli-progress'
import {Readable} from 'node:stream'
const PROVISION_DOMAIN_URL = 'https://backend.disco.cloud/api/installer/provision-domain'
export default class Init extends Command {
static args = {
sshString: Args.string({required: true}),
}
static description = 'initializes a new server'
static examples = [
'<%= config.bin %> <%= command.id %> root@disco.example.com',
'<%= config.bin %> <%= command.id %> root@disco.example.com --version 0.4.0',
'<%= config.bin %> <%= command.id %> root@203.0.113.7 # automatically gets a domain',
]
static flags = {
version: Flags.string({default: 'latest', description: 'version of disco daemon to install'}),
verbose: Flags.boolean({default: false, description: 'show extra output'}),
host: Flags.string({
description:
'hostname to use, when installing using an internal IP for the SSH connection, e.g. disco init root@10.1.2.3 --host disco.example.com',
}),
'local-image': Flags.string({description: 'local Docker image to upload and use (mostly for Disco development)'}),
'advertise-addr': Flags.string({
description: 'fixed IP address used to add nodes. defaults to resolving domain name of ssh connection',
}),
'cloudflare-tunnel': Flags.string({
description: 'Cloudflare Tunnel token, if you want to run disco behind a Cloudflare tunnel',
}),
'identity-file': Flags.string({
char: 'i',
description: 'SSH key to use for authentication',
}),
option: Flags.string({
char: 'o',
multiple: true,
description: 'install option, as key=value (repeatable)',
}),
}
// one long method: the whole init flow, step by step. splitting it would not make it clearer.
// eslint-disable-next-line complexity
public async run(): Promise<void> {
const {args, flags} = await this.parse(Init)
const {
version,
verbose,
'local-image': imageFlag,
'advertise-addr': advertiseAddrFlag,
'identity-file': identityFile,
option: optionFlags,
} = flags
const options = parseOptions(optionFlags ?? [], (message) => this.error(message))
const image = imageFlag === undefined ? `letsdiscodev/daemon:${version}` : imageFlag
const [argUsername, sshHost] = args.sshString.split('@')
// an ip without --host: once connected, ask disco.cloud for a domain from the server itself
const provisionDomain = flags.host === undefined && net.isIP(sshHost) !== 0
let host = flags.host === undefined ? sshHost : flags.host
let username = argUsername
if (!provisionDomain && isDiscoAlreadyInConfig(host)) {
this.error('host already present in .disco config')
}
let advertiseAddr = advertiseAddrFlag
if (advertiseAddr === undefined) {
advertiseAddr = await new Promise<string>((resolve, reject) => {
dns.lookup(sshHost, (err, address, _) => {
if (err) {
reject(err)
} else {
resolve(address)
}
})
})
}
const passphrase = identityFile ? await maybeGetKeyPassphrase({identityFile}) : undefined
let ssh
let password
try {
;({ssh, password} = await connectSsh({
host: sshHost,
username,
identityFile,
passphrase: passphrase ?? undefined,
}))
} catch {
this.error('could not connect to SSH')
}
if (username !== 'root') {
const canSudoWithoutPassword = await userCanSudoWitoutPassword({ssh, verbose})
// use password if provided, or ask for one if needed
const passwordToUse =
password === undefined
? canSudoWithoutPassword
? undefined
: await inquirerPassword({message: `${username}@${host}'s password:`})
: password
if (verbose) {
if (passwordToUse === undefined) {
process.stdout.write('Will not use password\n')
} else {
process.stdout.write('Will use password\n')
}
}
await setupRootSshAccess({ssh, password: passwordToUse, verbose})
username = 'root'
try {
;({ssh, password} = await connectSsh({host: sshHost, username, identityFile}))
} catch {
this.error('could not connect to SSH as root')
}
}
if (provisionDomain) {
let output
try {
output = await runSshCommand({
ssh,
command: `curl -sS -m 30 -X POST ${PROVISION_DOMAIN_URL}`,
verbose,
progressBar: undefined,
})
} catch (error) {
this.error(`could not get a domain from disco.cloud (pass --host <your domain>, or try again later)\n${error}`)
}
try {
host = parseProvisionedDomain(output, sshHost)
} catch (error) {
this.error(`${(error as Error).message} (pass --host <your domain>, or try again later)`)
}
if (isDiscoAlreadyInConfig(host)) {
this.error(`host ${host} already present in .disco config`)
}
this.log(`Domain: ${host}`)
}
const dockerAlreadyInstalled = await checkDockerInstalled(ssh)
let progressBar
if (!verbose) {
const dockerInstallOutputCount = 309
const discoInitOutputCount = 261
const count = dockerAlreadyInstalled ? discoInitOutputCount : dockerInstallOutputCount + discoInitOutputCount
progressBar = new SingleBar({format: '[{bar}] {percentage}%', clearOnComplete: true})
progressBar.start(count, 0)
}
await installDockerIfNeeded({dockerAlreadyInstalled, verbose, ssh, progressBar})
if (imageFlag !== undefined) {
await uploadLocalImage({
image: imageFlag,
ssh,
verbose,
})
}
if (verbose) {
this.log('Initializing Disco')
}
const apiKey = await initDisco({
ssh,
host,
advertiseAddr,
cloudflareTunnel: flags['cloudflare-tunnel'],
image,
options,
verbose,
progressBar,
})
if (verbose) {
this.log('Adding Disco to local config')
}
addDisco({name: host, host, apiKey})
ssh.dispose()
if (progressBar !== undefined) {
progressBar.stop()
}
// a new domain: dns and the certificate can take a moment, so the next command would fail without this
if (provisionDomain && !(await waitForHttps(host, 5 * 60 * 1000))) {
this.error(`Disco is installed, but https://${host} did not answer within 5 minutes (port 443 blocked?)`)
}
this.log('Done')
}
}
async function maybeGetKeyPassphrase({identityFile}: {identityFile: string}): Promise<null | string> {
// identify file might have a passphrase.
// hack-ish way to check if a passphrase is required below.
// from https://stackoverflow.com/a/70160696
// ssh-keygen -y -P "" -f ~/.ssh/id_rsa
// if getting an exit error code (ie not 0), then the key has a passphrase. prompt for it and then pass it.
return new Promise<null | string>((resolve) => {
child.exec(`ssh-keygen -y -P "" -f ${identityFile}`, (error, _stdout, _stderr) => {
if (error) {
// the key has a passphrase, prompt for it
inquirerPassword({message: 'Enter passphrase for key: '}).then((passphrase) => {
resolve(passphrase)
})
} else {
resolve(null)
}
})
})
}
async function uploadLocalImage({image, ssh, verbose}: {image: string; ssh: NodeSSH; verbose: boolean}): Promise<void> {
if (verbose) {
process.stdout.write(`Uploading image ${image}\n`)
}
const dockerSaveProcess = child.spawn('docker', ['save', image])
const processCompleted = new Promise<void>((resolve, reject) => {
dockerSaveProcess.on('close', (code) => {
if (code === 0) {
resolve()
} else {
reject(new Error(`docker save ${image} returned code ${code}`))
}
})
})
await runSshCommand({
ssh,
command: 'docker load',
stdin: dockerSaveProcess.stdout,
progressBar: undefined,
verbose,
})
await processCompleted
if (verbose) {
process.stdout.write('Upload complete\n')
}
}
export async function installDockerIfNeeded({
dockerAlreadyInstalled,
dockerVersion,
verbose,
ssh,
progressBar,
}: {
dockerAlreadyInstalled: boolean
dockerVersion?: string
verbose: boolean
ssh: NodeSSH
progressBar: SingleBar | undefined
}): Promise<void> {
if (!dockerAlreadyInstalled) {
if (verbose) {
if (dockerVersion === undefined) {
process.stdout.write('Installing Docker\n')
} else {
process.stdout.write(`Installing Docker ${dockerVersion}\n`)
}
}
try {
await installDocker({ssh, dockerVersion, verbose, progressBar})
} catch (error) {
if ((error as Error).toString().includes('Could not get lock')) {
throw new Error(`Package manager already busy. Try again in a few minutes.`)
}
throw new Error(`Failed to install Docker\n${error}`)
}
} else if (verbose) {
process.stdout.write('Docker already installed\n')
}
}
async function getSshPrivateKeyPaths(): Promise<string[]> {
const sshDir = path.join(os.homedir(), '.ssh')
const filenames = await fs.readdir(sshDir)
const publicKeys = filenames.filter((filename) => filename.endsWith('.pub'))
const possiblePrivKeyPaths = publicKeys
.map((pubKeyFilename) => pubKeyFilename.slice(0, -4))
.map((privKeyFilename) => path.join(sshDir, privKeyFilename))
const privKeyPathsWithIsFile = await Promise.all(
possiblePrivKeyPaths.map(
(privKeyPath) =>
new Promise<{privKeyPath: string; isFile: boolean}>((resolve) => {
fs.stat(privKeyPath).then((stat) =>
resolve({
privKeyPath,
isFile: stat.isFile(),
}),
)
}),
),
)
const privKeyPaths = privKeyPathsWithIsFile
.filter((keyWithIsFile) => keyWithIsFile.isFile)
.map((keyWithIsFile) => keyWithIsFile.privKeyPath)
return privKeyPaths
}
export async function connectSsh({
host,
username,
password,
identityFile,
passphrase,
}: {
host: string
username: string
password?: boolean | string | undefined // false means don't try password
identityFile?: string
passphrase?: string
}): Promise<{ssh: NodeSSH; password: string | undefined}> {
// use the ssh-agent, because it makes it so much easier.
// i.e. it will (usually? always?) find the right key to use, it will
// deal with keys that have passphrases, etc.
const sshAuthSocket = process.platform === 'win32' ? 'pageant' : process.env.SSH_AUTH_SOCK
const ssh = new NodeSSH()
try {
await ssh.connect({
host,
username,
privateKeyPath: identityFile,
agent: sshAuthSocket,
timeout: 5,
passphrase,
})
return {ssh, password: undefined}
} catch {}
if (password === undefined) {
password = await inquirerPassword({message: `${username}@${host}'s password:`})
}
if (typeof password === 'string') {
await ssh.connect({
host,
username,
password,
timeout: 5,
})
return {ssh, password}
}
throw new Error('Failed to connect with SSH')
}
export async function checkDockerInstalled(ssh: NodeSSH): Promise<boolean> {
const {code} = await ssh.execCommand('command -v docker >/dev/null 2>&1')
return code === 0
}
async function installDocker({
ssh,
dockerVersion,
verbose,
progressBar,
}: {
ssh: NodeSSH
dockerVersion?: string
verbose: boolean
progressBar: SingleBar | undefined
}): Promise<void> {
const commands = [
'sudo apt-get update',
'DEBIAN_FRONTEND=noninteractive sudo apt-get install -y ca-certificates curl gnupg',
'sudo install -m 0755 -d /etc/apt/keyrings',
'curl -fsSL https://download.docker.com/linux/$(. /etc/os-release && echo "$ID")/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg',
'sudo chmod a+r /etc/apt/keyrings/docker.gpg',
'echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] ' +
'https://download.docker.com/linux/$(. /etc/os-release && echo "$ID") ' +
'$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | ' +
'sudo tee /etc/apt/sources.list.d/docker.list > /dev/null',
'sudo apt-get update',
]
if (dockerVersion === undefined) {
commands.push(
'DEBIAN_FRONTEND=noninteractive sudo apt-get install -y docker-ce docker-ce-cli ' +
'containerd.io docker-buildx-plugin docker-compose-plugin',
)
} else {
commands.push(
`DEBIAN_FRONTEND=noninteractive sudo apt-get install -y \
docker-ce=$(apt-cache madison docker-ce | grep --fixed-strings ${dockerVersion} | head -1 | awk '{print $3}') \
docker-ce-cli=$(apt-cache madison docker-ce-cli | grep --fixed-strings ${dockerVersion} | head -1 | awk '{print $3}') \
containerd.io docker-buildx-plugin docker-compose-plugin`,
)
}
for await (const command of commands) {
await runSshCommand({ssh, command, verbose, progressBar})
}
}
function parseOptions(values: string[], fail: (message: string) => never): Record<string, string> {
const options: Record<string, string> = {}
for (const value of values) {
const index = value.indexOf('=')
if (index < 1) {
fail(`invalid option "${value}", expected key=value`)
}
const key = value.slice(0, index)
if (key in options) {
fail(`option "${key}" given more than once`)
}
options[key] = value.slice(index + 1)
}
return options
}
function shellQuote(value: string): string {
return `'${value.replaceAll("'", String.raw`'\''`)}'`
}
async function initDisco({
ssh,
host,
advertiseAddr,
cloudflareTunnel,
image,
options,
verbose,
progressBar,
}: {
ssh: NodeSSH
host: string
advertiseAddr: string
cloudflareTunnel: string | undefined
image: string
options: Record<string, string>
verbose: boolean
progressBar: SingleBar | undefined
}): Promise<string> {
const command =
'docker run ' +
'--rm ' +
'--mount source=disco-data,target=/disco/data ' +
'--mount type=bind,source=/var/run,target=/host/var/run ' +
'--mount type=bind,source=/etc,target=/host/etc ' +
'--mount type=bind,source=$HOME,target=/host/$HOME ' +
'--mount source=disco-caddy-init-config,target=/initconfig ' +
'--mount type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock ' +
`--env DISCO_HOST="${host}" ` +
`--env DISCO_ADVERTISE_ADDR="${advertiseAddr}" ` +
'--env HOST_HOME=$HOME ' +
`--env DISCO_IMAGE=${image} ` +
(cloudflareTunnel === undefined ? '' : `--env CLOUDFLARE_TUNNEL_TOKEN=${cloudflareTunnel} `) +
(Object.keys(options).length === 0
? ''
: `--env DISCO_INIT_OPTIONS=${shellQuote(JSON.stringify(options))} `) +
`${image} ` +
'disco_init'
const output = await runSshCommand({ssh, command, verbose, progressBar})
const apiKey = extractApiKey(output)
return apiKey
}
// the provision-domain answer, checked: a plain hostname, pointed at the ip we are connected to
export function parseProvisionedDomain(output: string, sshHost: string): string {
let body
try {
body = JSON.parse(output)
} catch {
throw new Error(`unexpected answer from disco.cloud: ${output.slice(0, 200)}`)
}
const {domain, public_ip: publicIp} = body ?? {}
if (typeof domain !== 'string' || !/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(domain)) {
throw new Error(`unexpected domain from disco.cloud: ${JSON.stringify(domain)}`)
}
if (publicIp !== sshHost) {
throw new Error(
`the server reaches the internet as ${JSON.stringify(publicIp)}, not ${sshHost}: the domain would point there`,
)
}
return domain
}
async function waitForHttps(host: string, timeoutMs: number): Promise<boolean> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
try {
// eslint-disable-next-line no-await-in-loop
await fetch(`https://${host}/`, {signal: AbortSignal.timeout(10_000)})
return true
} catch {
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => {
setTimeout(resolve, 5000)
})
}
}
return false
}
export function extractApiKey(output: string): string {
const match = output.match(/Created API key: ([a-z0-9]{32})/)
if (!match) {
throw new Error('could not extract API key')
}
return match[1]
}
export async function runSshCommand({
ssh,
command,
stdin,
verbose,
progressBar,
}: {
ssh: NodeSSH
command: string
stdin?: Readable | string
verbose: boolean
progressBar: SingleBar | undefined
}): Promise<string> {
let stdout = ''
let stderr = ''
if (verbose) {
process.stdout.write(`$ ${command}\n`)
}
const {code} = await ssh.execCommand(command, {
stdin,
onStdout(chunk) {
const str = chunk.toString('utf8')
stdout += str
if (verbose) {
process.stdout.write(str)
}
if (progressBar !== undefined) {
progressBar.increment()
}
},
onStderr(chunk) {
const str = chunk.toString('utf8')
stderr += str
if (verbose) {
process.stderr.write(str)
}
if (progressBar !== undefined) {
progressBar.increment()
}
},
})
if (code !== 0) {
throw new Error(`Failed to run command over SSH\n${command}\n${stderr}`)
}
return stdout
}
export async function userCanSudoWitoutPassword({ssh, verbose}: {ssh: NodeSSH; verbose: boolean}): Promise<boolean> {
try {
await runSshCommand({ssh, command: 'sudo -n true', verbose, progressBar: undefined})
if (verbose) {
process.stdout.write('Can run sudo commands without password\n')
}
return true
} catch {
if (verbose) {
process.stdout.write('Sudo commands require password\n')
}
return false
}
}
export async function setupRootSshAccess({
ssh,
verbose,
password,
}: {
ssh: NodeSSH
verbose: boolean
password: string | undefined
}) {
const permitRootLogin = await readPermitRootLogin({ssh, verbose})
if (permitRootLogin === null) {
// no statement set, add one
await addPermitRootLoginProhibitPassword({ssh, password, verbose})
} else if (!['nopwd', 'prohibit-password', 'without-password', 'yes'].includes(permitRootLogin)) {
// currently explicitly not permissive enough
// allow SSH root login with private key
await updatePermitRootLoginToProhibitPassword({ssh, password, verbose})
}
await uploadRootSshPublicKey({ssh, verbose, password})
await restartSshD({ssh, verbose, password})
ssh.dispose()
}
async function readPermitRootLogin({ssh, verbose}: {ssh: NodeSSH; verbose: boolean}): Promise<null | string> {
try {
const statement = await runSshCommand({
ssh,
command: 'cat /etc/ssh/sshd_config | grep PermitRootLogin',
verbose,
progressBar: undefined,
})
if (statement.startsWith('PermitRootLogin')) {
return statement.split(' ')[1]
}
} catch {
// the grep did not return any results, so it won't exit with a code 0
// assume that it didn't work, return null
return null
}
return null
}
async function updatePermitRootLoginToProhibitPassword({
ssh,
password,
verbose,
}: {
ssh: NodeSSH
password: string | undefined
verbose: boolean
}): Promise<void> {
await runSshCommand({
ssh,
command: `sudo ${
password === undefined ? ' ' : '-S '
}sed -i '0,/^PermitRootLogin/c\\PermitRootLogin prohibit-password' /etc/ssh/sshd_config`,
verbose,
stdin: password,
progressBar: undefined,
})
}
async function addPermitRootLoginProhibitPassword({
ssh,
password,
verbose,
}: {
ssh: NodeSSH
password: string | undefined
verbose: boolean
}): Promise<void> {
await runSshCommand({
ssh,
command: `sudo ${
password === undefined ? ' ' : '-S '
} sh -c "echo 'PermitRootLogin prohibit-password' >> /etc/ssh/sshd_config"`,
verbose,
stdin: password,
progressBar: undefined,
})
}
async function uploadRootSshPublicKey({
ssh,
verbose,
password,
}: {
ssh: NodeSSH
verbose: boolean
password: string | undefined
}): Promise<void> {
const privKeyPaths = await getSshPrivateKeyPaths()
const selectedPrivKeyName = await select({
message: 'Select SSH key to setup for root access',
choices: [
...privKeyPaths.map((keyPath) => ({
name: keyPath,
value: keyPath,
})),
{
name: 'Create a new one',
value: '__NEW__',
},
],
})
let localPublicKeyPath: string
if (selectedPrivKeyName === '__NEW__') {
const idRsaExists = privKeyPaths.filter((keyPath) => keyPath.endsWith(`${path.sep}id_rsa`))
const defaultKeyName = idRsaExists ? `id_rsa_disco_${Math.floor(Math.random() * 9_999_999)}` : 'id_rsa'
const privKeyName = await input({message: 'Enter the name of the new key to create', default: defaultKeyName})
const localPrivKeyPath = path.join(os.homedir(), '.ssh', privKeyName)
localPublicKeyPath = `${localPrivKeyPath}.pub`
await new Promise<void>((resolve, reject) => {
child.exec(`ssh-keygen -f ${localPrivKeyPath} -N ""`, (error, stdout, stderr) => {
if (error) {
reject(new Error('Error running ssh-keygen'))
}
if (verbose) {
process.stdout.write(stdout)
process.stderr.write(stderr)
}
resolve()
})
})
// ssh-add the new key
await new Promise<void>((resolve, reject) => {
child.exec(`ssh-add ${localPrivKeyPath}`, (error, stdout, stderr) => {
if (error) {
reject(new Error('Error running ssh-add'))
}
if (verbose) {
process.stdout.write(stdout)
process.stderr.write(stderr)
}
resolve()
})
})
} else {
localPublicKeyPath = `${selectedPrivKeyName}.pub`
}
const publicKeyContent = await fs.readFile(localPublicKeyPath)
await runSshCommand({
ssh,
command: `sudo ${password === undefined ? ' ' : '-S '}mkdir -p /root/.ssh`,
verbose,
stdin: password,
progressBar: undefined,
})
await runSshCommand({
ssh,
command: `sudo ${password === undefined ? ' ' : '-S '}touch /root/.ssh/authorized_keys`,
verbose,
stdin: password,
progressBar: undefined,
})
// on AWS EC2 Ubuntu, they have this preventing you from logging in as root, remove it.
await runSshCommand({
ssh,
command: `sudo ${
password === undefined ? ' ' : '-S '
}sed -i '/Please login as the user/d' /root/.ssh/authorized_keys`,
verbose,
stdin: password,
progressBar: undefined,
})
let keyAlreadyAuthorized
try {
await runSshCommand({
ssh,
// grep the trimmed version of the public key content, otherwise
// there's a carriage return at the end of the line
command: `sudo ${password === undefined ? ' ' : '-S '}sh -c "grep '${publicKeyContent
.toString('utf8')
.trim()}' /root/.ssh/authorized_keys"`,
verbose,
stdin: password,
progressBar: undefined,
})
keyAlreadyAuthorized = true
} catch {
keyAlreadyAuthorized = false
}
if (!keyAlreadyAuthorized) {
await runSshCommand({
ssh,
command: `sudo ${
password === undefined ? ' ' : '-S '
}sh -c "echo '${publicKeyContent}' >> /root/.ssh/authorized_keys"`,
verbose,
stdin: password,
progressBar: undefined,
})
}
}
async function restartSshD({
ssh,
verbose,
password,
}: {
ssh: NodeSSH
verbose: boolean
password: string | undefined
}): Promise<void> {
await runSshCommand({
ssh,
command: `sudo ${password === undefined ? ' ' : '-S '}/etc/init.d/ssh restart`,
stdin: password,
verbose,
progressBar: undefined,
})
}