-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
536 lines (480 loc) · 13.1 KB
/
index.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
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
import { execFileSync } from 'child_process'
import {
copyFileSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
renameSync,
writeFileSync,
} from 'fs'
import { basename } from 'path'
import { createInterface } from 'readline'
export type Config = {
filename: string
server_name: string
port: number
}
export function parse_default_filename(server_name: string) {
return server_name.split(' ')[0].split(',')[0] + '.conf'
}
export function format_config_list(config_list: Config[]): string {
let lines: string[] = []
lines.push(`| port | server_name | filename |`)
lines.push(`|-------|-------------|----------|`)
config_list.sort((a, b) => a.port - b.port)
for (let config of config_list) {
let port = config.port.toString().padStart(5, ' ')
let line = `| ${port} | ${config.server_name} |`
let default_filename = parse_default_filename(config.server_name)
if (config.filename == default_filename) {
line += ` - |`
} else {
line += ` ${config.filename} |`
}
lines.push(line)
}
return lines.join('\n')
}
export function parse_config_list(text: string): Config[] {
let lines = text
.split('\n')
.map(line =>
line
.split('|')
.map(col => col.trim())
.filter(col => col.length > 0),
)
.filter(line => line.length > 0)
let headers = lines.shift()
if (!headers) {
throw new Error('missing header line')
}
if (
headers[0]?.toLowerCase() != 'port' ||
headers[1]?.toLowerCase() != 'server_name' ||
headers[2]?.toLowerCase() != 'filename'
) {
throw new Error(
'invalid header, expect: "| port | server_name | filename |"',
)
}
if (lines.length == 0) return []
// remove separator line
if (
lines[0][0]?.startsWith('-') &&
lines[0][1]?.startsWith('-') &&
lines[0][2]?.startsWith('-')
) {
lines.shift()
}
let config_list: Config[] = []
for (let cols of lines) {
let port = +cols[0]
if (!port) {
throw new Error('invalid port, got: ' + JSON.stringify(cols[0]))
}
let server_name = cols[1]
if (!server_name) {
throw new Error('missing server_name, port: ' + port)
}
let filename = cols[2]
if (filename == '-') {
filename = parse_default_filename(server_name)
}
let config: Config = {
port,
server_name,
filename,
}
config_list.push(config)
}
return config_list
}
export function scan_conf_dir(dir: string): Config[] {
if (!existsSync(dir)) {
console.log('Warning: nginx config directory not found: ' + config_dir)
return []
}
let filenames = readdirSync(dir)
let config_list: Config[] = []
for (let filename of filenames) {
let file = join(dir, filename)
try {
let config = parse_conf_file(file)
config_list.push(config)
} catch (error) {
let message = String(error)
if (message.includes('not found')) {
continue
}
showError(error)
}
}
return config_list
}
export function parse_conf_lines(text: string): string[] {
let lines = text
.split('\n')
.map(line => line.split('#')[0].trim())
.filter(line => line.length > 0)
return lines
}
export function parse_conf_file(file: string): Config {
let text = load_file(file).trim()
let lines = parse_conf_lines(text)
let server_name = lines
.find(line => line.startsWith('server_name '))
?.replace('server_name ', '')
.split(';')[0]
.trim()
if (!server_name) {
throw new Error('server_name not found, file: ' + JSON.stringify(file))
}
let port = +lines
.find(line => line.startsWith('proxy_pass '))
?.replace('proxy_pass ', '')
.split(';')[0]
.split(':')
.pop()!
if (!port) {
throw new Error('port not found, file: ' + JSON.stringify(file))
}
let filename = basename(file)
return { filename, server_name, port }
}
export function save_conf_file(args: { dir: string; config: Config }) {
let { dir, config } = args
let text = `
server {
listen 80;
listen [::]:80;
server_name ${config.server_name};
# client_max_body_size 1M;
location / {
proxy_pass http://localhost:${config.port};
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
`
let file = join(dir, config.filename)
save_file(file, text)
}
export function update_conf_file(file: string) {
const text = load_file(file)
let new_text = text.replaceAll('\r', '')
for (;;) {
let t = new_text.replaceAll('\n\n\n\n', '\n\n\n')
if (t == new_text) {
break
}
new_text = t
}
let lines = parse_conf_lines(new_text)
// look for line: "listen 443 ssl http2; # managed by Certbot"
// or line: "listen 443 http2 ssl; # managed by Certbot"
let has_http2 = lines.some(line => {
if (!line.startsWith('listen 443 ')) {
return false
}
let parts = line.split(';')[0].split(' ')
return parts.includes('ssl') && parts.includes('http2')
})
// look for lines: "listen 443 ssl; # managed by Certbot"
let has_ssl = lines.some(line => line.startsWith('listen 443 ssl'))
if (!has_http2 && has_ssl) {
let lines = new_text.split('\n')
for (let i = 0; i < lines.length; i++) {
let line = lines[i]
if (line.trimStart()[0] == '#') {
continue
}
lines[i] = line.replace('listen 443 ssl;', 'listen 443 ssl http2;')
}
new_text = lines.join('\n')
}
if (new_text != text) {
save_file(file, new_text)
}
if (!has_http2 && !has_ssl) {
// not obtained ssl cert by certbot yet
return 'no ssl' as const
}
}
function join(...parts: string[]) {
// use linux convention even when the script is generated on windows (to be run on linux server)
return parts.join('/')
}
function save_file(file: string, text: string) {
text = text.trim() + '\n'
if (existsSync(file)) {
let old_text = readFileSync(file).toString()
if (text == old_text) {
console.log('unchanged file:', file)
return
}
let date = new Date()
let y = date.getFullYear()
let m = date.getMonth().toString().padStart(2, '0')
let d = date.getDate().toString().padStart(2, '0')
let H = date.getHours().toString().padStart(2, '0')
let M = date.getMinutes().toString().padStart(2, '0')
let S = date.getSeconds().toString().padStart(2, '0')
let new_file = `${file}.bk_${y}-${m}-${d}_${H}${M}${S}`
console.log('backup file:', file, '->', new_file)
renameSync(file, new_file)
}
console.log('save file:', file)
writeFileSync(file, text)
}
function load_file(file: string) {
console.log('load file:', file)
return readFileSync(file).toString()
}
function showError(error: unknown) {
if (__filename.endsWith('.js')) {
console.error(String(error))
} else {
console.error(error)
}
}
let config_list_file = 'nginx.md'
export let config_dir = '/etc/nginx/conf.d'
let draft_dir = 'draft/conf.d'
let bash_file = 'draft/update.sh'
export function set_config_dir(dir: string) {
config_dir = dir
}
export let modes = {
scan_config() {
console.log('scanning config dir:', config_dir)
let config_list = scan_conf_dir(config_dir)
let text = format_config_list(config_list)
save_file(config_list_file, text)
console.log()
console.log(
'[message] please update file:',
config_list_file,
'to continue',
)
},
apply_config(options: { apply_formatting: boolean }) {
let text = load_file(config_list_file)
let config_list = parse_config_list(text)
let no_ssl = false
let lines: string[] = []
mkdirSync(draft_dir, { recursive: true })
for (let config of config_list) {
let src = join(config_dir, config.filename)
let dest = join(draft_dir, config.filename)
if (!existsSync(src)) {
save_conf_file({ dir: draft_dir, config })
no_ssl = true
lines.push(`sudo cp ${JSON.stringify(dest)} ${JSON.stringify(src)}`)
continue
}
copyFileSync(src, dest)
let update_result = update_conf_file(dest)
if (update_result == 'no ssl') {
no_ssl = true
continue
}
if (is_file_same(src, dest)) {
// already updated
continue
}
lines.push(`sudo cp ${JSON.stringify(dest)} ${JSON.stringify(src)}`)
}
if (no_ssl || lines.length > 0) {
lines.push(`sudo nginx -t`)
lines.push(`sudo service nginx restart`)
}
if (no_ssl) {
lines.push(`sudo certbot --nginx`)
lines.push(
`echo "Hint: run nginx-portal again to enable http2 in nginx configs"`,
)
}
save_file(bash_file, lines.join('\n'))
console.log()
console.log('[message] please run file:', bash_file, 'to continue')
},
show_bash() {
let text = load_file(bash_file)
console.log()
console.log(`content of ${bash_file}:`)
console.log('```')
console.log(text.trim())
console.log('```')
},
run_bash() {
let out = execFileSync('bash', [bash_file], {
stdio: 'inherit',
}).toString()
console.log(out.trimEnd())
},
async interactive() {
for (;;) {
console.log(
`
Select an action:
0. exit
1. scan nginx configs into nginx.md
2. apply nginx configs from nginx.md and generate ${bash_file}
3. show ${bash_file}
4. run ${bash_file}
`.trim(),
)
let ans = await ask('action: ')
ans = ans.toLowerCase()
switch (ans) {
case '0':
case 'exit':
case '.exit':
return
case '1':
case 'scan':
modes.scan_config()
break
case '2':
case 'apply': {
let ans = await ask('apply formatting to nginx configs? (y/N): ')
let apply_formatting = ans.trim()[0]?.toLowerCase() == 'y'
modes.apply_config({ apply_formatting })
break
}
case '3':
case 'show':
modes.show_bash()
break
case '4':
case 'run':
modes.run_bash()
break
default:
console.error('Error: unknown action')
break
}
console.log()
}
},
}
function read_file_for_compare(file: string): string {
return readFileSync(file)
.toString()
.trim()
.split('\n')
.map(line => line.trim())
.join('')
}
function is_file_same(a_file: string, b_file: string) {
let a_text = read_file_for_compare(a_file)
let b_text = read_file_for_compare(b_file)
return a_text == b_text
}
function showHelp() {
let { version } = require('./package.json')
console.log(
`
nginx-portal v${version}
Usage: nginx-portal [options]
Options:
-s | --scan scan nginx configs and save to nginx.md file
-a | --apply apply nginx configs from nginx.md file
-f | --format apply formatting to nginx configs (default skip formatting if no other effective changes)
-i | --interactive run multiple modes with interactive menu
-d | --config_dir DIR set the directory of nginx configs to be scanned from (default: /etc/nginx/conf.d)
-h | --help show this help message
-v | --version show version information
Example:
nginx-portal -h
`.trim(),
)
}
function showVersion() {
let { version } = require('./package.json')
console.log(version)
}
async function cli() {
let interactive_flag = false
let scan_config_flag = false
let apply_config_flag = false
let apply_formatting = false
for (let i = 2; i < process.argv.length; i++) {
let arg = process.argv[i]
switch (arg) {
case '-h':
case '--help':
showHelp()
process.exit(0)
case '-v':
case '--version':
showVersion()
process.exit(0)
case '-i':
case '--interactive':
interactive_flag = true
break
case '-s':
case '--scan':
scan_config_flag = true
break
case '-a':
case '--apply':
apply_config_flag = true
break
case '-f':
case '--format':
apply_formatting = true
break
case '-d':
case '--config_dir':
i++
config_dir = process.argv[i]
if (!config_dir || config_dir == '-') {
console.error('Error: --config_dir requires a directory argument')
process.exit(1)
}
break
default:
console.error('Error: unknown argument:', JSON.stringify(arg))
process.exit(1)
}
}
if (!interactive_flag && !scan_config_flag && !apply_config_flag) {
console.error('Error: run mode not specified.')
console.error('Hint: run "nginx-portal --help" to see available options.')
process.exit(1)
}
if (interactive_flag) {
await modes.interactive()
return
}
if (scan_config_flag) {
modes.scan_config()
}
if (apply_config_flag) {
modes.apply_config({ apply_formatting })
}
}
function ask(prompt: string) {
return new Promise<string>(resolve => {
let io = createInterface({ input: process.stdin, output: process.stdout })
io.question(prompt, answer => {
io.close()
resolve(answer)
})
})
}
export async function main() {
try {
await cli()
} catch (error) {
showError(error)
process.exit(1)
}
}