/
ssh.js
389 lines (377 loc) · 13.6 KB
/
ssh.js
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
import nodeSsh from 'node-ssh'
import resolveUsername from 'username'
import path from 'path'
import { executeCommands, cmdPromise, isEmpty, isFunction } from './utils'
import { getParsedEnv } from './env'
import { getDbDumpZipCommands } from './database'
import { pathBackups, pathApp } from './paths'
import { colourAttention, colourNotice } from './palette'
import chalk from 'chalk'
const getSshInit = async ({ host, user, port, sshKeyPath }) => {
// Connect to the remote server via SSH
// Get the remote env file
const config = {
host: host,
username: user,
port: port,
}
// Get the custom privateKey if it's set
sshKeyPath = !isEmpty(sshKeyPath) ? { sshKeyPath: sshKeyPath } : null
const connection = await sshConnect({ ...config, ...sshKeyPath })
return connection
}
const getSshFile = async ({ connection, from, to }) => {
let errorMessage
// Download the composer file from the remote server
await connection
.getFile(
to, // To local
from // From remote
)
.catch(e => (errorMessage = `${e}\n${from}`))
// If there’s download issues then return the messages
if (errorMessage) return new Error(errorMessage)
return
}
// Connect to the remote server via SSH
const sshConnect = async ({ host, username, port, sshKeyPath }) => {
let errorMessage
// Get the local username so we can get the default key below (macOS path)
const user = await resolveUsername()
const sshKeyResolvedPath = !isEmpty(sshKeyPath)
? sshKeyPath
: `/Users/${user}/.ssh/id_rsa`
// Create a SSH connection
const ssh = new nodeSsh()
await ssh
.connect({
host: host,
username: username,
port: port,
privateKey: sshKeyResolvedPath,
})
.catch(error => (errorMessage = error))
if (errorMessage)
return new Error(
String(errorMessage).includes(
'Error: Cannot parse privateKey: Unsupported key format'
)
? `Your SSH key isn't in a format Swiff can work with\n (${sshKeyResolvedPath})\n\n1. Generate a new one with:\n ${colourNotice(
`ssh-keygen -m PEM -b 4096 -f /Users/${user}/.ssh/swiff`
)}\n\n2. Then add the key to the server:\n ${colourNotice(
`ssh-copy-id -i /Users/${user}/.ssh/swiff ${
port !== 22 ? `-p ${port} ` : ''
}${username}@${host}`
)}`
: String(errorMessage).includes(
'config.privateKey does not exist at'
)
? `Your SSH key isn’t found at ${colourAttention(
sshKeyResolvedPath
)}\n\nCheck the ${colourAttention(
`SWIFF_CUSTOM_KEY`
)} value is correct in your local .env\n\nmacOS path example:\n${colourAttention(
`SWIFF_CUSTOM_KEY="/Users/${user}/.ssh/[key-filename]"`
)}`
: errorMessage
)
return ssh
}
const getSshEnv = async ({ host, username, port, appPath, sshKeyPath }) => {
let errorMessage
// Create a SSH connection
const ssh = await sshConnect({ host, username, port, sshKeyPath })
// If there’s any connection issues then return the messages
if (ssh instanceof Error) return ssh
// Set where we’ll be downloading the temporary remote .env file
const tempBackupPath = path.join(pathBackups, '.env')
// Download the remote .env file
// We can’t read the env contents with this package so we have to download
// then read it
await ssh
.getFile(tempBackupPath, path.join(appPath, '.env'))
.catch(error => (errorMessage = error))
// If there’s any .env download issues then return the messages
if (errorMessage) {
// If dispose is a function call it
if (
ssh.dispose() &&
{}.toString.call(ssh.dispose()) === '[object Function]'
)
ssh.dispose()
return new Error(errorMessage)
}
// Return the contents of the .env file
const remoteEnv = getParsedEnv(tempBackupPath)
if (remoteEnv) {
// Remove the temporary remote .env file
await cmdPromise(`rm ${tempBackupPath}`).catch(
error => (errorMessage = error)
)
// If there’s any .env removal issues then return the messages
if (errorMessage) {
if (
ssh.dispose() &&
{}.toString.call(ssh.dispose()) === '[object Function]'
)
ssh.dispose()
return new Error(errorMessage)
}
}
// Close the SSH connection
ssh.dispose()
// Return the contents of the env
return remoteEnv
}
const getSshCopyInstructions = ({ server }, sshKeyPath) =>
`${chalk.bold(
`Haven’t added your key to the server?`
)}\nYou can quickly add it with ssh-copy-id:\n${colourNotice(
`ssh-copy-id ${!isEmpty(sshKeyPath) ? `-i ${sshKeyPath} ` : ''}${
server.port !== 22 ? `-p ${server.port} ` : ''
}${server.user}@${server.host}`
)}`
const getSshPushCommands = ({
pushFolders,
user,
host,
port,
workingDirectory,
sshKeyPath,
}) => {
// https://download.samba.org/pub/rsync/rsync.html
const flags = [
// '--dry-run',
// Preserve permissions
'--archive',
// Compress file data during the transfer
'--compress',
// Output a change-summary for all updates
'--itemize-changes',
// Delete extraneous files from dest dirs
'--delete',
// Ignore misc files
'--exclude ".git"',
'--exclude ".env"',
'--exclude ".DS_Store"',
// Connect via a port number
// Set the custom identity if provided
`-e "ssh -p ${port}${
!isEmpty(sshKeyPath) ? ` -i '${sshKeyPath}'` : ''
}"`,
].join(' ')
// Build the final command string from an array of folders
const rsyncCommands = pushFolders
.map(item => {
const rSyncFrom = `${path.join(pathApp, item)}/`
const rSyncTo = `${path.join(workingDirectory, item)}/`
// Folders aren't created by rsync natively
// https://stackoverflow.com/questions/1636889/rsync-how-can-i-configure-it-to-create-target-directory-on-server
const createFolderCmd = `--rsync-path="mkdir -p ${rSyncTo} && rsync"`
return [
`echo '!${item}'`,
`(rsync ${createFolderCmd} ${flags} ${rSyncFrom} ${user}@${host}:${rSyncTo})`,
].join(' && ')
})
.join(' && ')
// Use grep to filter the rsync output
const greppage = `grep -E '^(!|>|<|\\*)'`
return `(${rsyncCommands}) | ${greppage}`
}
const getPushDatabaseCommands = ({
host,
user,
port,
fromPath,
toPath,
sshKeyPath,
}) => {
// https://download.samba.org/pub/rsync/rsync.html
const flags = [
// '--dry-run',
// Preserve permissions
'--archive',
// Compress file data during the transfer
'--compress',
// Connect via a port number
// Set the custom identity if provided
`-e "ssh -p ${port}${
!isEmpty(sshKeyPath) ? ` -i '${sshKeyPath}'` : ''
}"`,
].join(' ')
// Build the command string
return `rsync ${flags} ${fromPath} ${user}@${host}:${toPath}`
}
const getSshPullCommands = ({
pullFolders,
user,
host,
port,
appPath,
sshKeyPath,
}) => {
// https://download.samba.org/pub/rsync/rsync.html
const flags = [
// '--dry-run',
// Preserve permissions
'--archive',
// Compress file data during the transfer
'--compress',
// Output a change-summary for all updates
'--itemize-changes',
// Ignore misc files
'--exclude ".git"',
'--exclude ".env"',
'--exclude ".DS_Store"',
// Connect via a port number
// Set the custom identity if provided
`-e "ssh -p ${port}${
!isEmpty(sshKeyPath) ? ` -i '${sshKeyPath}'` : ''
}"`,
].join(' ')
// Build the final command string from an array of folders
const rsyncCommands = pullFolders
.map(item => {
const rSyncFrom = `${path.join(appPath, item)}/`
const rSyncTo = `./${item}/`
// Folders aren't created by rsync natively
const createFolderCmd = `mkdir -p ${rSyncTo}`
return [
`echo '!${item}'`,
createFolderCmd,
`rsync ${flags} ${user}@${host}:${rSyncFrom} ${rSyncTo}`,
].join(' && ')
})
.join(';')
// Use grep to filter the rsync output
const greppage = `grep -E '^(!|>|<|\\*)'`
return `(${rsyncCommands}) | ${greppage}`
}
// Build command to test the SSH connection is setup
const getSshTestCommand = (user, host, port, sshKeyPath) => {
// Set the custom identity if provided
const sshKeyString = !isEmpty(sshKeyPath) ? `-i "${sshKeyPath}"` : ''
return `ssh -p ${port} ${sshKeyString} -o BatchMode=yes -o ConnectTimeout=5 ${user}@${host} echo 'SSH access is setup' 2>&1`
}
// Upload a database over SSH to a remote folder
const pushSshDatabase = async config => {
const pushDatabaseStatus = await executeCommands(
getPushDatabaseCommands(config)
)
if (pushDatabaseStatus instanceof Error)
return new Error(
`There was an issue uploading your local ${colourAttention(
config.dbName
)} database\n\n${pushDatabaseStatus}`
)
return
}
// Download a database over SSH to a local folder
const getSshDatabase = async ({
remoteEnv,
host,
user,
port,
sshAppPath,
gzipFileName,
sshKeyPath,
unzip = false,
}) => {
const ssh = await getSshInit({
host: host,
user: user,
port: port,
sshKeyPath: sshKeyPath,
})
// If there’s connection issues then return the messages
if (ssh instanceof Error) return ssh
// Dump the database and gzip on the remote server
const zipCommandConfig = {
host: remoteEnv.DB_SERVER,
port: remoteEnv.DB_PORT,
user: remoteEnv.DB_USER,
password: remoteEnv.DB_PASSWORD,
database: remoteEnv.DB_DATABASE,
gzipFilePath: gzipFileName,
}
let errorMessage
await ssh
.execCommand(getDbDumpZipCommands(zipCommandConfig), {
cwd: sshAppPath,
})
.then(result => {
const errorOutput = String(result.stderr)
// There's an error found (mysql makes this check tedious)
if (errorOutput.toLowerCase().includes('error')) {
// Close the connection
ssh.dispose()
// Format the remote env settings for display
const remoteSettings = `${colourAttention(
`DB_SERVER="${remoteEnv.DB_SERVER}"\nDB_PORT="${
remoteEnv.DB_PORT
}"\nDB_USER="${zipCommandConfig.user}"\nDB_PASSWORD="${
zipCommandConfig.password
}"\nDB_DATABASE="${zipCommandConfig.database}"`
)}\n\n${path.join(sshAppPath, '.env')}`
// Set the error message
errorMessage = errorOutput.includes('Unknown MySQL server host')
? `There were issues connecting to the remote database server ${colourAttention(
remoteEnv.DB_SERVER
)}\nVerify the settings in the remote env are correct:\n\n${remoteSettings}`
: errorOutput.includes('Access denied')
? `Couldn’t connect with the remote .env database settings:\n\n${remoteSettings}`
: errorOutput
}
})
.catch(e => (errorMessage = e))
// If there’s db dump/gzip issues then return the messages
if (errorMessage) return new Error(errorMessage)
// Download the file from the remote server
const downloadTo = `${pathBackups}/${gzipFileName}`
const sshFile = await getSshFile({
connection: ssh,
from: `${sshAppPath}/${gzipFileName}`,
to: downloadTo,
})
if (sshFile instanceof Error)
return (
ssh.dispose() &&
new Error(
`${
String(errorMessage).includes('No such file')
? `There was an issue downloading the remote ${colourAttention(
remoteEnv.DB_DATABASE
)} database\n\nMaybe there’s incorrect database settings in the ${colourAttention(
'remote .env'
)}? \n\n${colourAttention(
JSON.stringify(remoteEnv, null, 2)
)}`
: errorMessage
}`
)
)
// Cleanup the database dump on the server
await ssh
.execCommand(`rm ${gzipFileName}`, { cwd: sshAppPath })
.catch(e => (errorMessage = e))
// If there’s removal issues then close the connection and return the messages
if (errorMessage) return ssh.dispose() && new Error(errorMessage)
// Close the connection
ssh.dispose()
// Unzip the database
// -d : decompress / -f : force overwrite any existing file
unzip && (await executeCommands(`gzip -df '${downloadTo}'`))
return
}
export {
getSshInit,
getSshFile,
getSshEnv,
getSshDatabase,
getSshTestCommand,
getSshCopyInstructions,
getSshPushCommands,
getSshPullCommands,
pushSshDatabase,
sshConnect,
}