-
Notifications
You must be signed in to change notification settings - Fork 3
/
server-system.js
74 lines (60 loc) · 2.17 KB
/
server-system.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
const fs = require('fs');
const fetch = require('node-fetch');
const jwt = require('jsonwebtoken');
const program = require('commander');
const colors = require('colors');
const crypto = require('crypto');
const path = require('path');
const { Spinner } = require('cli-spinner');
const generateKey = (bits) => crypto.randomBytes(Math.ceil(bits / 8)).toString('base64');
const keySize = 512;
function environmentFile(environment) {
return `./config/${environment}.json`;
}
program
.command('call <api>')
.alias('c')
.option('--env [environment]', 'The environment to run, defaults to development', 'development')
.option('-V --verbose', 'Run in verbose mode')
.action(async (api, {env, verbose}) => {
const {
host,
systemSecret
} = JSON.parse(fs.readFileSync(environmentFile(env)).toString());
console.log(`Triggering api ${colors.cyan(host)}${colors.cyan(api)} in environment ${colors.green(env)}`);
const key = Buffer.from(systemSecret, 'base64');
try {
const spinner = new Spinner('processing.. %s');
spinner.setSpinnerString(18);
spinner.start();
const result = await fetch(`${host}${api}`, {
method: 'POST',
headers: {
authorization: `jwt ${jwt.sign({}, key, { algorithm: 'HS256', expiresIn: '5 min' })}`
}
});
spinner.stop(true);
if (!result.ok) {
console.error(colors.red(`[${result.status}]`), await result.text());
} else {
console.log(colors.green(`[${result.status}]`), await result.text());
}
} catch (ex) {
if (verbose) {
console.error(colors.red(ex.message), ex);
} else {
console.error(colors.red(ex.message));
}
}
});
program
.command('generate')
.alias('g')
.option('--env [environment]', 'The environment to run, defaults to development', 'development')
.action(({ env }) => {
console.log(`Generating new secret for environment ${colors.green(env)}`)
const config = JSON.parse(fs.readFileSync(environmentFile(env)).toString());
config.systemSecret = generateKey(keySize);
fs.writeFileSync(environmentFile(env), JSON.stringify(config, null, 4));
});
program.parse(process.argv);