-
Notifications
You must be signed in to change notification settings - Fork 42
/
postInstall.js
100 lines (86 loc) · 2.18 KB
/
postInstall.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
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require("fs"));
var crypto = require('crypto');
var reporter = require('./lib/reporter');
var ursa = require('ursa');
var private = './private.pem';
var public = './public.pem';
var jwks = './jwks.json';
//check that the necessary files are in place
//if any one is missing, create a new set
fileExists(private)
.then(function() {
var key = fs.readFileSync('./private.pem');
return saveKey(ursa.coercePrivateKey(key));
}).then(function(){
return fileExists(public);
})
.then(function() {
return fileExists(jwks);
})
.catch(function(e) {
createKeyPair();
});
/**
* fileExists
* fs exists curiously throws
* an error to indicate it exists
* so this function translates it
*/
function fileExists (path) {
return fs.existsAsync(path)
.then(function(e){
reporter.log(path + ' not found');
throw new Error (path + ' not found');
})
.error(function(e) {
reporter.log(path + ' found');
return true;
});
};
/**
* createKeyPair
* generate a new RSA keypair
*/
function createKeyPair() {
reporter.log('...Creating new Key Pair...');
saveKey(ursa.generatePrivateKey());
}
/**
* saveKey
* save the key
*/
function saveKey (key) {
var jwksData = {
keys : [{
kty : 'RSA',
alg : 'RS256',
use : 'sig',
kid : crypto.randomBytes(4).toString('hex'),
n : key.getModulus('base64'),
e : key.getExponent('base64')
}]
};
return Promise.all([
fs.writeFileAsync(private, key.toPrivatePem('utf8'))
.then(function() {
reporter.log('...RSA private key saved');
}).catch(function(e) {
reporter.log('error saving private key');
}),
fs.writeFileAsync(public, key.toPublicPem('utf8'))
.then(function() {
reporter.log('...RSA public key saved');
}).catch(function(e) {
reporter.log('error saving public key');
}),
fs.writeFileAsync(jwks, JSON.stringify(jwksData, null, 2))
.then(function() {
reporter.log('...jwks.json saved');
}).catch(function(e) {
reporter.log('error saving jwks');
}),
]).then(function(){
reporter.log('done saving keys.');
});
}