-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
102 lines (90 loc) · 2.21 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
#!/usr/bin/env node
const fs = require('fs');
const inquirer = require('inquirer');
const { pem2jwk } = require('pem-jwk');
const shortid = require('shortid');
const shorthash = require('shorthash');
const jwt = require('jsonwebtoken');
const sshpk = require('sshpk');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const main = async () => {
const homeDirectory = process.env.HOME;
const configPath = `${homeDirectory}/.jwtgen`;
const privateKey = await readFile(`${homeDirectory}/.ssh/id_rsa`, 'utf-8');
const publicKey = sshpk
.parseKey(await readFile(`${homeDirectory}/.ssh/id_rsa.pub`), 'ssh')
.toBuffer('pem')
.toString();
const algorithm = 'RS256';
const keyId = shorthash.unique(privateKey.trim());
const publicJwk = {
...pem2jwk(publicKey),
alg: algorithm,
use: 'sig',
kid: keyId
};
const config = JSON.parse(await tryReadFile(configPath)) || {};
const { audience, expiresIn, passphrase, username } = await inquirer.prompt([
{
name: 'username',
message: 'User name',
type: 'string',
default: config.username || process.env.USER
},
{
name: 'audience',
message: 'Audience',
type: 'string',
default: config.audience
},
{
name: 'expiresIn',
message: 'Token lifetime (e.g.: "1h", "7d")',
type: 'string',
default: config.expiresIn
},
{
name: 'passphrase',
message: 'Passphrase',
type: 'password'
}
]);
await writeFile(
configPath,
JSON.stringify({
username,
audience,
expiresIn
})
);
const token = jwt.sign(
{ sub: username },
{ key: privateKey, passphrase },
{
algorithm,
audience,
expiresIn,
jwtid: shortid.generate(),
issuer: username,
keyid: keyId
}
);
console.log('Public Key PEM:');
console.log(publicKey);
console.log('\n');
console.log('Public Key JWK:');
console.log(publicJwk);
console.log('\n');
console.log('JWT:');
console.log(token);
};
const tryReadFile = async filePath => {
try {
return await readFile(filePath, 'utf-8');
} catch {
return null;
}
};
main();