-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
359 lines (297 loc) · 9.11 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
'use strict'
/*!
* @fastify/csrf
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* Copyright(c) 2021-2022 Fastify Collaborators
* MIT Licensed
*/
const crypto = require('node:crypto')
/**
* Token generation/verification class.
*
* @param {object} [options]
* @param {number} [options.saltLength=8] The string length of the salt
* @param {number} [options.secretLength=18] The byte length of the secret key
* @param {number} [options.validity=0] The maximum milliseconds of validity of this token. 0 disables the check.
* @param {boolean} [options.userInfo=false] Require userInfo on create() and verify()
* @public
*/
function Tokens (options) {
if (!(this instanceof Tokens)) {
return new Tokens(options)
}
const opts = options || {}
const algorithm = opts.algorithm !== undefined
? opts.algorithm
: 'sha256'
try {
crypto
.createHash(algorithm)
} catch (err) {
throw new TypeError('option algorithm must be a supported hash-algorithm')
}
const saltLength = opts.saltLength !== undefined
? opts.saltLength
: 8
if (typeof saltLength !== 'number' || !isFinite(saltLength) || saltLength < 1) {
throw new TypeError('option saltLength must be finite number > 1')
}
const secretLength = opts.secretLength !== undefined
? opts.secretLength
: 18
if (typeof secretLength !== 'number' || !isFinite(secretLength) || secretLength < 1) {
throw new TypeError('option secretLength must be finite number > 1')
}
const validity = opts.validity !== undefined
? opts.validity
: 0
if (typeof validity !== 'number' || !isFinite(validity) || validity < 0) {
throw new TypeError('option validity must be finite number > 0')
}
const userInfo = opts.userInfo !== undefined
? opts.userInfo
: false
if (typeof userInfo !== 'boolean') {
throw new TypeError('option userInfo must be a boolean')
}
const hmacKey = opts.hmacKey
if (hmacKey) {
try {
// validate if the hmacKey is a valid format
hashingStrategy(algorithm, hmacKey)
} catch (err) {
throw new TypeError('option hmacKey must be a supported hmac key')
}
}
this.algorithm = algorithm
this.saltLength = saltLength
this.saltGenerator = saltGenerator(saltLength)
this.secretLength = secretLength
this.validity = validity
this.userInfo = userInfo
this.hmacKey = hmacKey
}
/**
* Create a new CSRF token.
*
* @param {string} secret The secret for the token.
* @param {?string} userInfo The userInfo for the token.
* @returns {string}
* @public
*/
Tokens.prototype.create = function create (secret, userInfo) {
if (!secret || typeof secret !== 'string') {
throw new TypeError('argument secret is required')
}
const date = this.validity > 0 ? Date.now() : null
if (this.userInfo) {
if (typeof userInfo !== 'string') {
throw new TypeError('argument userInfo is required to be a string')
}
}
return this._tokenize(secret, this.saltGenerator(), date, userInfo, this.algorithm)
}
/**
* Create a new secret key.
*
* @param {function} [callback]
* @returns {string}
* @public
*/
Tokens.prototype.secret = Buffer.isEncoding('base64url')
? function secret (callback) {
if (callback !== undefined && typeof callback !== 'function') {
throw new TypeError('argument callback must be a function')
}
if (!callback && !global.Promise) {
throw new TypeError('argument callback is required')
}
if (callback) {
crypto.randomBytes(this.secretLength, (err, buf) => {
err
? callback(err)
: callback(null, buf.toString('base64url'))
})
return
}
return new Promise((resolve, reject) => {
crypto.randomBytes(this.secretLength, (err, buf) => {
err
? reject(err)
: resolve(buf.toString('base64url'))
})
})
}
: function secret (callback) {
if (callback !== undefined && typeof callback !== 'function') {
throw new TypeError('argument callback must be a function')
}
if (!callback && !global.Promise) {
throw new TypeError('argument callback is required')
}
if (callback) {
return crypto.randomBytes(this.secretLength, function (err, buf) {
err
? callback(err)
: callback(null, buf
.toString('base64')
.replace(PLUS_GLOBAL_REGEXP, '-')
.replace(SLASH_GLOBAL_REGEXP, '_')
.replace(EQUAL_GLOBAL_REGEXP, ''))
})
}
return new Promise((resolve, reject) => {
crypto.randomBytes(this.secretLength, (err, buf) => {
err
? reject(err)
: resolve(buf
.toString('base64')
.replace(PLUS_GLOBAL_REGEXP, '-')
.replace(SLASH_GLOBAL_REGEXP, '_')
.replace(EQUAL_GLOBAL_REGEXP, ''))
})
})
}
/**
* Create a new secret key synchronously.
* @returns {string}
* @public
*/
Tokens.prototype.secretSync = Buffer.isEncoding('base64url')
? function secretSync () {
return crypto.randomBytes(this.secretLength)
.toString('base64url')
}
: function secretSync () {
return crypto.randomBytes(this.secretLength)
.toString('base64')
.replace(PLUS_GLOBAL_REGEXP, '-')
.replace(SLASH_GLOBAL_REGEXP, '_')
.replace(EQUAL_GLOBAL_REGEXP, '')
}
/**
* Tokenize a secret, salt, date and userInfo.
* @returns {string}
* @private
*/
Tokens.prototype._tokenize = Buffer.isEncoding('base64url')
? function _tokenize (secret, salt, date, userInfo, algorithm) {
let toHash = ''
if (date !== null) {
toHash += date.toString(36) + '-'
}
if (typeof userInfo === 'string') {
toHash +=
hashingStrategy(algorithm, this.hmacKey)
.update(userInfo)
.digest('base64url')
.replace(MINUS_GLOBAL_REGEXP, '_') + '-'
}
toHash += salt
return toHash + '-' +
hashingStrategy(algorithm, this.hmacKey)
.update(toHash + '-' + secret, 'ascii')
.digest('base64url')
}
: function _tokenize (secret, salt, date, userInfo, algorithm) {
let toHash = ''
if (date !== null) {
toHash += date.toString(36) + '-'
}
if (typeof userInfo === 'string') {
toHash += hashingStrategy(algorithm, this.hmacKey)
.update(userInfo)
.digest('base64')
.replace(PLUS_SLASH_GLOBAL_REGEXP, '_')
.replace(EQUAL_GLOBAL_REGEXP, '') + '-'
}
toHash += salt
return toHash + '-' + hashingStrategy(algorithm, this.hmacKey)
.update(toHash + '-' + secret, 'ascii')
.digest('base64')
.replace(PLUS_GLOBAL_REGEXP, '-')
.replace(SLASH_GLOBAL_REGEXP, '_')
.replace(EQUAL_GLOBAL_REGEXP, '')
}
/**
* Verify if a given token is valid for a given secret.
*
* @param {string} secret The secret for the token.
* @param {string} token The token itself.s
* @param {?string} userInfo The userInfo for the token.
* @returns {string}
* @public
*/
Tokens.prototype.verify = function verify (secret, token, userInfo) {
if (!secret || typeof secret !== 'string') {
return false
}
if (!token || typeof token !== 'string') {
return false
}
if (this.userInfo && (!userInfo || typeof userInfo !== 'string')) {
return false
}
let curIdx = 0
let nextIdx = token.indexOf('-')
if (nextIdx === -1) {
return false
}
let date = null
if (this.validity > 0) {
date = parseInt(token.slice(curIdx, nextIdx), 36)
if (Date.now() - date > this.validity) {
return false
}
curIdx = nextIdx + 1
nextIdx = token.indexOf('-', curIdx)
if (nextIdx === -1) {
return false
}
}
if (this.userInfo) {
// we skip the userInfo part, this will be verified with the hashing
curIdx = nextIdx + 1
nextIdx = token.indexOf('-', curIdx)
if (nextIdx === -1) {
return false
}
}
const salt = token.slice(curIdx, nextIdx)
const actual = Buffer.from(token)
const expected = Buffer.from(this._tokenize(secret, salt, date, userInfo, this.algorithm))
// to avoid the exposure if the provided value has the correct length, we call
// timingSafeEqual with the actual value. The additional length check itself is
// timing safe.
return crypto.timingSafeEqual(
actual.length === expected.length
? expected
: actual,
actual
) && actual.length === expected.length
}
const EQUAL_GLOBAL_REGEXP = /=/g
const PLUS_GLOBAL_REGEXP = /\+/g
const SLASH_GLOBAL_REGEXP = /\//g
const MINUS_GLOBAL_REGEXP = /-/g
const PLUS_SLASH_GLOBAL_REGEXP = /[+/]/g
function saltGenerator (saltLength) {
const fnBody = []
fnBody.push('const base62 = \'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\'.split(\'\');')
fnBody.push('return function () {')
const salt = []
for (let i = 0; i < saltLength; ++i) salt.push('base62[(62 * Math.random()) | 0]')
fnBody.push('return ' + salt.join('+'))
fnBody.push('}')
return new Function(fnBody.join(''))() // eslint-disable-line no-new-func
}
function hashingStrategy (algorithm, key) {
if (key) {
return crypto.createHmac(algorithm, key)
}
return crypto.createHash(algorithm)
}
module.exports = Tokens
module.exports.default = Tokens
module.exports.Tokens = Tokens