forked from coralproject/talk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecrets.js
70 lines (60 loc) · 1.76 KB
/
secrets.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
const { JWT_SECRETS, JWT_SECRET, JWT_ALG } = require('./config');
const debug = require('debug')('talk:secrets');
const jwt = require('./services/jwt');
if (JWT_SECRETS) {
if (!Array.isArray(JWT_SECRETS)) {
throw new Error(
'TALK_JWT_SECRETS must be a JSON array in the form [{"kid": kid, ["secret": secret | "private": private, "public": public]}, ...]'
);
}
if (JWT_SECRETS.length === 0) {
throw new Error(
'TALK_JWT_SECRETS must be a JSON array with non zero length'
);
}
// Wrap a multi-secret around the available secrets.
module.exports.jwt = new jwt.MultiSecret(
JWT_SECRETS.map(secret => {
if (!('kid' in secret)) {
throw new Error(
"when multiple keys are specified, kid's must be specified"
);
}
if (typeof secret.kid !== 'string' || secret.kid.length === 0) {
throw new Error('kid must be a unique string');
}
// HMAC secrets do not have public/private keys.
if (JWT_ALG.startsWith('HS')) {
return new jwt.SharedSecret(secret, JWT_ALG);
}
if (!('public' in secret)) {
throw new Error(
'all symetric keys must provide a PEM encoded public key'
);
}
return new jwt.AsymmetricSecret(secret, JWT_ALG);
})
);
debug(
`loaded ${JWT_SECRETS.length} ${
JWT_ALG.startsWith('HS') ? 'shared' : 'asymmetric'
} secrets`
);
} else if (JWT_SECRET) {
if (JWT_ALG.startsWith('HS')) {
module.exports.jwt = new jwt.SharedSecret(
{
secret: JWT_SECRET,
},
JWT_ALG
);
} else {
module.exports.jwt = new jwt.AsymmetricSecret(
JSON.parse(JWT_SECRET),
JWT_ALG
);
}
debug(
`loaded a ${JWT_ALG.startsWith('HS') ? 'shared' : 'asymmetric'} secret`
);
}