-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcore.js
More file actions
141 lines (128 loc) · 4.83 KB
/
core.js
File metadata and controls
141 lines (128 loc) · 4.83 KB
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
const path = require('path');
const _ = require('lodash');
const jwt = require('jsonwebtoken');
const generateRandomString = require('randomstring').generate;
const { RateLimiterMemory } = require('rate-limiter-flexible');
const getCoreConfigFromConfig = require('./utils/getCoreConfigFromConfig');
const {encrypt, decrypt} = require('./utils/aes');
const getToken = (data, key, options) => jwt.sign(_.omit(data, ['iat', 'exp']), key, options);
const getRefreshToken = (token, key, options) => jwt.sign({signature: jwt.decode(token, {complete: true}).signature}, key, options);
const checkRefreshToken = (token, refreshToken, key) => {
try {
if(jwt.verify(refreshToken, key)) {
return jwt.decode(token, {complete: true}).signature === jwt.decode(refreshToken).signature;
}
} catch(e) {
return false;
}
return false;
};
const wrapKey = (securityKey, key) => securityKey + key.substr(0, key.length - securityKey.toString().length);
const getHandleRateLimiters = (options) => {
const rateLimiters = _.map(
_.filter(options, { isRateLimiterEnabled: true }),
({ key, limiterOptions, getErrorDescription }) => {
const rateLimiter = new RateLimiterMemory(limiterOptions);
return async (ctx, next) => {
try {
const limiterKey = _.get(ctx, key);
await rateLimiter.consume(limiterKey);
await next();
} catch (rejRes) {
ctx.status = 429;
ctx.body = getErrorDescription(ctx);
}
};
});
return rateLimiters.length ? rateLimiters : [async (ctx, next) => await next()];
};
// TODO add validation for every route
// TODO add brute checker https://github.com/llambda/koa-brute
// TODO add rate-limit
// TODO add eslint-plugin-security
// TODO add helmet
// TODO add tests
// TODO add scan with npm audit, nsp and snyk
// TODO blacklist tokens
module.exports = function(router, config) {
const {
key,
expiresIn,
refreshExpiresIn,
securityKeyRule,
fixedSecurityCodes,
rateLimiterConfig,
sendKeyPlugin: sendKeyPluginName
} = getCoreConfigFromConfig(config);
if(!sendKeyPluginName) {
console.log('sendKeyPlugin plugin is undefined');
process.exit(-1);
}
const sendKeyPlugin = require(path.resolve(`./node_modules/${sendKeyPluginName}/plugin`));
router.post('/key', ...getHandleRateLimiters(rateLimiterConfig['/key']), async function handleKeyGeneration(ctx) {
const {user, redirectUrl, params} = ctx.request.body;
const token = getToken({u: user, p: params}, key, {expiresIn});
const ekey = encrypt(token, key);
const securityKey = fixedSecurityCodes[user] ? fixedSecurityCodes[user]
: generateRandomString(securityKeyRule);
const eproof = encrypt(ekey, wrapKey(securityKey, key));
ctx.ok({eproof});
sendKeyPlugin({user, redirectUrl, params, ekey, securityKey, config});
});
router.post('/token/status', ...getHandleRateLimiters(rateLimiterConfig['/token/status']), async function handleTokenVerification(ctx) {
const {token} = ctx.request.body;
jwt.verify(token, key, function(err) {
if (err) {
const {name, message} = err;
ctx.forbidden({name, message});
} else {
ctx.ok();
}
});
});
router.post('/token', ...getHandleRateLimiters(rateLimiterConfig['/token']), async function handleTokenGeneration(ctx) {
async function generateTokenFromEkey(ctx) {
const {ekey} = ctx.request.body;
const token = decrypt(ekey, key);
if(token) {
const refreshToken = getRefreshToken(token, key, {expiresIn: refreshExpiresIn});
ctx.ok({token, refreshToken});
} else {
ctx.forbidden();
}
}
async function generateTokenFromRefreshToken(ctx) {
const {token, refreshToken} = ctx.request.body;
if(checkRefreshToken(token, refreshToken, key)) {
const decoded = jwt.decode(token);
const newToken = getToken(decoded, key, {expiresIn})
const refreshToken = getRefreshToken(newToken, key, {expiresIn: refreshExpiresIn});
ctx.ok({token: newToken, refreshToken});
} else {
ctx.forbidden();
}
}
async function generateTokenFromProof(ctx) {
const {eproof, securityKey} = ctx.request.body;
const ekey = decrypt(eproof, wrapKey(securityKey, key));
if(ekey) {
const token = decrypt(ekey, key);
const refreshToken = getRefreshToken(token, key, {expiresIn: refreshExpiresIn});
ctx.ok({token, refreshToken});
} else {
ctx.forbidden();
}
}
const {ekey, token, refreshToken, eproof, securityKey} = ctx.request.body;
if(ekey) {
await generateTokenFromEkey(ctx);
} else if(token && refreshToken) {
await generateTokenFromRefreshToken(ctx);
} else if(eproof && securityKey) {
await generateTokenFromProof(ctx);
} else {
ctx.forbidden();
}
});
return router.routes();
};