-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
393 lines (346 loc) · 11.9 KB
/
index.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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
'use strict';
const crypto = require('crypto');
const util = require('util');
const jsonwebtoken = require('jsonwebtoken');
const t = require('tcomb');
const StandardError = require('standard-error');
const arrayOfStrings = t.refinement(t.Array, n => n.every(t.String), 'Array<String>');
const Store = t.interface({
// Signature: (userId, refreshToken)
remove: t.Function,
// Signature: (userId)
removeAll: t.Function,
// Signature: (userId, refreshToken)
add: t.Function
}, 'Stores');
const JWT = t.interface({
// Signature: (payload, secret, {algorithm: String})
sign: t.Function,
// Signature: (payload, secret, {algorithm: String, otherVerifyOptions})
verify: t.Function,
// Signature: (payload)
decode: t.Function,
}, 'JWT');
/**
* @type {String}
* @typedef Secret
* @description a string greater than 20 characters
*/
const Secret = secret => {
t.String(secret);
t.assert(secret.length >= 20, 'The secret must be greater than or equal 20 characters');
return secret;
};
const ExpiresAt = t.Integer;
const Algorithm = t.enums.of(['HS256', 'HS384', 'HS512', 'RS256'], 'Algorithm');
const UserId = t.String;
const Prolong = t.Boolean;
const accessTokenType = 'Authomatic-AT';
const refreshTokenType = 'Authomatic-RT';
// Does not add extra functionality to the token, merely makes it look complete and professional
const refreshTokenSignOptions = {
aud: ['Authomatic'],
iss: 'Authomatic'
};
const refreshTokenVerifyOptions = {
audience: ['Authomatic'],
issuer: 'Authomatic'
};
/**
* Access token
* @typedef AccessToken
* @type {String}
* @description Regular JWT token.
* Its payload looks like this:
```js
{
"t": "Authomatic-AT",
"uid": "userId",
"exp": "someNumber",
"jti": "randomBytes",
...otherClaims,
"pld": {
...otherUserContent
}
}
```
*/
/**
* Refresh token
* @typedef RefreshToken
* @type {String}
* @description regular JWT token.
* Its payload looks like this:
```js
{
"t": "Authomatic-RT",
"iss": "Authomatic",
"aud": ["Authomatic"]
"uid": "userId",
"exp": "someNumber",
"jti": "randomBytes",
"accessTokenJTI": "randomBytes"
}
```
*/
/**
* Token pairs
* @typedef Tokens
* @type {Object}
* @property {AccessToken} accessToken
* @property {Number} accessTokenExpiresAt epoch
* @property {RefreshToken} refreshToken
* @property {Number} refreshTokenExpiresAt epoch
*/
/**
* Verify options to be used when verifying tokens
* @typedef VerifyOptions
* @type {Object}
* @property {Array|String} [audience] checks the aud field
* @property {String|Array} [issuer] checks the iss field
* @property {Boolean} [ignoreExpiration] if true, ignores the expiration check of access tokens
* @property {Boolean} [ignoreNotBefore] if true, ignores the not before check of access tokens
* @property {String} [subject] checks the sub field
* @property {Number|String} [clockTolerance]
* @property {String|Number} [maxAge]
* @property {Number} [clockTimestamp] overrides the clock for the verification process
*/
const VerifyOptions = t.interface({
audience: t.maybe(t.union([arrayOfStrings, t.String])),
issuer: t.maybe(t.union([t.String, arrayOfStrings])),
ignoreExpiration: t.maybe(t.Boolean),
ignoreNotBefore: t.maybe(t.Boolean),
subject: t.maybe(t.String),
clockTolerance: t.maybe(t.union([t.Number, t.String])),
maxAge: t.maybe(t.union([t.String, t.Number])),
clockTimestamp: t.maybe(t.Number)
}, {name: 'VerifyOptions', strict: true});
/**
* The allowed user options to for signing tokens
* @typedef SignOptions
* @type {Object}
* @property {Number} [nbf]
* @property {Array|String} [aud]
* @property {String} [iss]
* @property {String} [sub]
*/
const SignOptions = t.interface({
nbf: t.maybe(t.Number),
aud: t.maybe(t.union([arrayOfStrings, t.String])),
iss: t.maybe(t.String),
sub: t.maybe(t.String),
}, {name: 'SignOptions', strict: true});
const getTypeRefinement = tokenType =>
t.refinement(
t.String,
n => n === tokenType,
`Token type: ${tokenType}`
);
const internalSignOptions = SignOptions.extend(t.interface({
uid: UserId,
jti: t.String,
exp: ExpiresAt
}, {name: 'InternalSignOptions', strict: true}));
const Payload = internalSignOptions.extend(t.interface({
pld: t.Any,
rme: t.Boolean,
t: getTypeRefinement(accessTokenType)
}, {name: 'Payload', strict: true}));
const RefreshPayload = internalSignOptions.extend(t.interface({
accessTokenJTI: t.String,
t: getTypeRefinement(refreshTokenType)
}, {name: 'RefreshPayload', strict: true}));
/**
* The refresh token was not found.
* @type {StandardError}
* @typedef RefreshTokenNotFound
* @property {String} [name='RefreshTokenNotFound']
*/
const refreshTokenNotFound = new StandardError(
'The refresh token was not found',
{name: 'RefreshTokenNotFound'}
);
/**
* The tokens provided do not match
* @type {StandardError}
* @typedef TokensMismatch
* @property {String} [name='TokensMismatch']
*/
const tokensMismatch = new StandardError(
'The tokens provided do not match',
{name: 'TokensMismatch'}
);
/**
* The provided input is not a valid token.
* @type {StandardError}
* @typedef InvalidToken
* @property {String} [name='InvalidToken']
*/
const invalidToken = new StandardError(
'The provided input is not a valid token',
{name: 'InvalidToken'}
);
// 15 minutes
const regularAccessTTL = 60 * 15;
// 1 hour
const prolongedAccessTTL = 60 * 60;
// 25 minutes
const regularRefreshTTL = 60 * 25;
// 7 days
const prolongedRefreshTTL = 60 * 60 * 24 * 7;
// Seconds -> Seconds Since the Epoch
const computeExpiryDate = seconds => Math.floor(Date.now() / 1000) + seconds;
const randomBytes = util.promisify(crypto.randomBytes);
const generateTokenId = () => randomBytes(32).then(x => x.toString('base64'));
/**
* Authomatic
* @param {Object} store one of authomatic stores
* @param {String} [algorithm=HS256] Can be one of these ['HS256', 'HS384', 'HS512', 'RS256']
* @param {SignOptions} [defaultSignOptions]
* @param {VerifyOptions} [defaultVerifyOptions]
*/
module.exports = function Authomatic({
store, algorithm = 'HS256',
jwt = jsonwebtoken, defaultSignOptions = {}, defaultVerifyOptions = {}
}) {
Store(store);
Algorithm(algorithm);
JWT(jwt);
SignOptions(defaultSignOptions);
VerifyOptions(defaultVerifyOptions);
const checkToken = type => token => {
const decodedATContent = jwt.decode(token);
if(decodedATContent && decodedATContent.t === type) {
return token;
}
throw invalidToken;
};
const AccessToken = checkToken(accessTokenType);
const RefreshToken = checkToken(refreshTokenType);
const sign = async (userId, secret, content = {}, prolong = false, signOptions = {}) => {
UserId(userId);
Prolong(prolong);
Secret(secret);
const accessExp = computeExpiryDate(prolong ? prolongedAccessTTL : regularAccessTTL);
const refreshTTL = prolong ? prolongedRefreshTTL : regularRefreshTTL;
const refreshExp = computeExpiryDate(refreshTTL);
// Order of spreading is important!
const accessPayload = Payload({
...defaultSignOptions,
...SignOptions(signOptions),
pld: content, uid: userId, exp: accessExp, rme: prolong,
jti: await generateTokenId(), t: accessTokenType
});
const refreshPayload = RefreshPayload({
...refreshTokenSignOptions, uid: userId,
accessTokenJTI: accessPayload.jti, exp: refreshExp,
jti: await generateTokenId(), t: refreshTokenType
});
const accessToken = jwt.sign(accessPayload, secret, {algorithm});
const refreshToken = jwt.sign(refreshPayload, secret, {algorithm});
await store.add(userId, refreshPayload.jti, accessPayload.jti, refreshTTL * 1000);
return {
accessToken, accessTokenExpiresAt: accessExp, refreshToken, refreshTokenExpiresAt: refreshExp
};
};
const verifyRefreshToken = (refreshToken, secret) =>
jwt.verify(RefreshToken(refreshToken), Secret(secret), {
...refreshTokenVerifyOptions,
algorithm
});
const verifyAccessToken = (token, secret, verifyOptions = {}) =>
jwt.verify(AccessToken(token), Secret(secret), {
...defaultVerifyOptions,
...VerifyOptions(verifyOptions),
algorithm
});
const refresh = async (refreshToken, accessToken, secret, verifyOptions) => {
RefreshToken(refreshToken);
// It is required to pass verifyOptions during refresh because the old function didn't have it
VerifyOptions(verifyOptions);
Secret(secret);
const verifiedRTContent = verifyRefreshToken(refreshToken, secret);
const {uid: userId, jti: refreshTokenJTI} = verifiedRTContent;
// Eagerly invalidates refresh token
if(!await store.remove(userId, refreshTokenJTI)) {
throw refreshTokenNotFound;
}
AccessToken(accessToken);
const verifiedATContent =
verifyAccessToken(accessToken, secret, {...verifyOptions, ignoreExpiration: true});
// RefreshTokens works with only one AccessToken
if (verifiedATContent.jti !== verifiedRTContent.accessTokenJTI) {
throw tokensMismatch;
}
// eslint-disable-next-line no-unused-vars
const {exp, iat, jti, uid, t, pld: payload, rme, ...jwtOptions} = verifiedATContent;
// Finally, sign new tokens for the user
return sign(userId, secret, payload, rme, jwtOptions);
};
const invalidateRefreshToken = (refreshToken, secret) => {
const {uid, jti} = verifyRefreshToken(refreshToken, secret);
return store.remove(uid, jti);
};
const invalidateAllRefreshTokens = userId => store.removeAll(UserId(userId));
return {
/**
* Returns access and refresh tokens
* @param {String} userId
* @param {Secret} secret
* @param {Object} [content] user defined properties
* @param {Boolean} [prolong] if true, the refreshToken will last 4 days and accessToken 1 hour,
* otherwise the refresh token will last 25 minutes and the accessToken 15 minutes.
* @param {SignOptions} [signOptions] Options to be passed to jwt.sign
* @returns {Promise<Tokens>}
* @throws {TypeError} typeError if any param was not sent exactly as specified
*/
sign,
/**
* Verifies token, might throw jwt.verify errors
* @param {String} token
* @param {Secret} secret
* @param {VerifyOptions} [verifyOptions] Options to pass to jwt.verify.
* @returns {String} decoded token
* @throws {InvalidToken} invalidToken
* @throws {TypeError} typeError if any param was not sent exactly as specified
* @throws JsonWebTokenError
* @throws TokenExpiredError
* Error info at {@link https://www.npmjs.com/package/jsonwebtoken#errors--codes}
*/
verify: verifyAccessToken,
/**
* Issues a new access token using a refresh token and an old token (can be expired).
* @param {String} refreshToken
* @param {String} accessToken
* @param {Secret} secret
* @param {SignOptions} signOptions Options passed to jwt.sign,
* ignoreExpiration will be set to true
* @returns {Promise<Tokens>}
* @throws {RefreshTokenNotFound} refreshTokenNotFound
* @throws {TokensMismatch} tokensMismatch
* @throws {TypeError} typeError if any param was not sent exactly as specified
* @throws JsonWebTokenError
* @throws TokenExpiredError
* Error info at {@link https://www.npmjs.com/package/jsonwebtoken#errors--codes}
*/
refresh,
/**
* Invalidates refresh token
* @param {String} refreshToken
* @returns {Promise<Boolean>} true if successful, false otherwise.
* @throws {TypeError} typeError if any param was not sent exactly as specified
* @throws {InvalidToken} invalidToken
* @throws JsonWebTokenError
* @throws TokenExpiredError
* Error info at {@link https://www.npmjs.com/package/jsonwebtoken#errors--codes}
*/
invalidateRefreshToken,
/**
* Invalidates all refresh tokens
* @param {String} userId
* @returns {Promise<Boolean>} true if successful, false otherwise.
* @throws {TypeError} typeError if any param was not sent exactly as specified
*/
invalidateAllRefreshTokens
};
};