-
Notifications
You must be signed in to change notification settings - Fork 30
/
signer.js
319 lines (268 loc) · 9.12 KB
/
signer.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
'use strict'
const {
base64UrlMatcher,
base64UrlReplacer,
useNewCrypto,
hsAlgorithms,
esAlgorithms,
rsaAlgorithms,
edAlgorithms,
detectPrivateKeyAlgorithm,
createSignature
} = require('./crypto')
const { TokenError } = require('./error')
const { getAsyncKey, ensurePromiseCallback } = require('./utils')
const { createPrivateKey, createSecretKey } = require('node:crypto')
const { parse: parseMs } = require('@lukeed/ms')
const supportedAlgorithms = new Set([...hsAlgorithms, ...esAlgorithms, ...rsaAlgorithms, ...edAlgorithms, 'none'])
const supportedAlgorithmsList = Array.from(supportedAlgorithms).join(', ')
function checkIsCompatibleAlgorithm(expected, actual) {
const expectedType = expected.slice(0, 2)
const actualType = actual.slice(0, 2)
let valid = true // We accept everything for HS
// If the key is passphrase encrypted (actual === "ENCRYPTED") only RS and ES algos are supported
if (expectedType === 'RS' || expectedType === 'PS') {
// RS and PS use same keys
valid = actualType === 'RS' || (expectedType === 'RS' && actual === 'ENCRYPTED')
} else if (expectedType === 'ES' || expectedType === 'Ed') {
// ES and Ed must match
valid = expectedType === actualType || (expectedType === 'ES' && actual === 'ENCRYPTED')
}
if (!valid) {
throw new TokenError(TokenError.codes.invalidKey, `Invalid private key provided for algorithm ${expected}.`)
}
}
function prepareKeyOrSecret(key, algorithm) {
if (typeof key === 'string') {
key = Buffer.from(key, 'utf-8')
}
// Only on Node 12 - Create a key object
/* istanbul ignore next */
if (useNewCrypto) {
key = algorithm[0] === 'H' ? createSecretKey(key) : createPrivateKey(key)
}
return key
}
function sign(
{
key,
algorithm,
noTimestamp,
mutatePayload,
clockTimestamp,
expiresIn,
notBefore,
kid,
typ,
isAsync,
additionalHeader,
fixedPayload
},
payload,
cb
) {
const [callback, promise] = isAsync ? ensurePromiseCallback(cb) : []
// Validate payload
if (typeof payload !== 'object') {
throw new TokenError(TokenError.codes.invalidType, 'The payload must be an object.')
}
if (payload.exp && (!Number.isInteger(payload.exp) || payload.exp < 0)) {
throw new TokenError(TokenError.codes.invalidClaimValue, 'The exp claim must be a positive integer.')
}
// Prepare the header
const header = {
alg: algorithm,
typ: typ || 'JWT',
kid,
...additionalHeader
}
// Prepare the payload
let encodedPayload = ''
// Add claims
const iat = payload.iat * 1000 || clockTimestamp || Date.now()
const finalPayload = {
...payload,
...fixedPayload,
iat: noTimestamp ? undefined : Math.floor(iat / 1000),
exp: payload.exp ? payload.exp : expiresIn ? Math.floor((iat + expiresIn) / 1000) : undefined,
nbf: payload.nbf ? payload.nbf : notBefore ? Math.floor((iat + notBefore) / 1000) : undefined
}
if (mutatePayload) {
Object.assign(payload, finalPayload)
}
encodedPayload = Buffer.from(JSON.stringify(finalPayload), 'utf-8')
.toString('base64')
.replace(base64UrlMatcher, base64UrlReplacer)
// We have the key
if (!callback) {
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8')
.toString('base64')
.replace(base64UrlMatcher, base64UrlReplacer)
const input = encodedHeader + '.' + encodedPayload
const signature = algorithm === 'none' ? '' : createSignature(algorithm, key, input)
return input + '.' + signature
}
// Get the key asynchronously
getAsyncKey(key, { header, payload }, (err, currentKey) => {
if (err) {
const error = TokenError.wrap(err, TokenError.codes.keyFetchingError, 'Cannot fetch key.')
return callback(error)
}
if (typeof currentKey === 'string') {
currentKey = Buffer.from(currentKey, 'utf-8')
} else if (!(currentKey instanceof Buffer)) {
return callback(
new TokenError(
TokenError.codes.keyFetchingError,
'The key returned from the callback must be a string or a buffer containing a secret or a private key.'
)
)
}
let token
try {
// Detect the private key - If the algorithm was known, just verify they match, otherwise assign it
const availableAlgorithm = detectPrivateKeyAlgorithm(currentKey, algorithm)
if (algorithm) {
checkIsCompatibleAlgorithm(algorithm, availableAlgorithm)
} else {
header.alg = algorithm = availableAlgorithm
}
currentKey = prepareKeyOrSecret(currentKey, algorithm)
const encodedHeader = Buffer.from(JSON.stringify(header), 'utf-8')
.toString('base64')
.replace(base64UrlMatcher, base64UrlReplacer)
const input = encodedHeader + '.' + encodedPayload
token = input + '.' + createSignature(algorithm, currentKey, input)
} catch (e) {
return callback(e)
}
callback(null, token)
})
return promise
}
module.exports = function createSigner(options) {
let {
key,
algorithm,
noTimestamp,
mutatePayload,
clockTimestamp,
expiresIn,
notBefore,
jti,
aud,
iss,
sub,
nonce,
kid,
typ,
header: additionalHeader
} = { clockTimestamp: 0, ...options }
// Validate options
if (
algorithm &&
!supportedAlgorithms.has(algorithm)
) {
throw new TokenError(
TokenError.codes.invalidOption,
`The algorithm option must be one of the following values: ${supportedAlgorithmsList}.`
)
}
const keyType = typeof key
const isKeyPasswordProtected = keyType === 'object' && key && key.key && key.passphrase
if (algorithm === 'none') {
if (key) {
throw new TokenError(
TokenError.codes.invalidOption,
'The key option must not be provided when the algorithm option is "none".'
)
}
} else if (
!key ||
(keyType !== 'string' && !(key instanceof Buffer) && keyType !== 'function' && !isKeyPasswordProtected)
) {
throw new TokenError(
TokenError.codes.invalidOption,
'The key option must be a string, a buffer, an object containing key/passphrase properties or a function returning the algorithm secret or private key.'
)
} else if (isKeyPasswordProtected && !algorithm) {
throw new TokenError(
TokenError.codes.invalidAlgorithm,
'When using password protected key you must provide the algorithm option.'
)
}
// Convert the key to a string when not a function, in order to be able to detect
if (key && keyType !== 'function') {
// Detect the private key - If the algorithm was known, just verify they match, otherwise assign it
const availableAlgorithm = detectPrivateKeyAlgorithm(isKeyPasswordProtected ? key.key : key, algorithm)
if (algorithm) {
checkIsCompatibleAlgorithm(algorithm, availableAlgorithm)
} else {
algorithm = availableAlgorithm
}
key = prepareKeyOrSecret(key, algorithm)
}
if (expiresIn) {
if (typeof expiresIn === 'string') {
expiresIn = parseMs(expiresIn)
}
if (typeof expiresIn !== 'number' || expiresIn < 0) {
throw new TokenError(TokenError.codes.invalidOption, 'The expiresIn option must be a positive number or a valid string.')
}
}
if (notBefore) {
if (typeof notBefore === 'string') {
notBefore = parseMs(notBefore)
}
if (typeof notBefore !== 'number' || notBefore < 0) {
throw new TokenError(TokenError.codes.invalidOption, 'The notBefore option must be a positive number or a valid string.')
}
}
if (clockTimestamp && (typeof clockTimestamp !== 'number' || clockTimestamp < 0)) {
throw new TokenError(TokenError.codes.invalidOption, 'The clockTimestamp option must be a positive number.')
}
if (jti && typeof jti !== 'string') {
throw new TokenError(TokenError.codes.invalidOption, 'The jti option must be a string.')
}
if (aud && typeof aud !== 'string' && !Array.isArray(aud)) {
throw new TokenError(TokenError.codes.invalidOption, 'The aud option must be a string or an array of strings.')
}
if (iss && typeof iss !== 'string') {
throw new TokenError(TokenError.codes.invalidOption, 'The iss option must be a string.')
}
if (sub && typeof sub !== 'string') {
throw new TokenError(TokenError.codes.invalidOption, 'The sub option must be a string.')
}
if (nonce && typeof nonce !== 'string') {
throw new TokenError(TokenError.codes.invalidOption, 'The nonce option must be a string.')
}
if (kid && typeof kid !== 'string') {
throw new TokenError(TokenError.codes.invalidOption, 'The kid option must be a string.')
}
if (additionalHeader && typeof additionalHeader !== 'object') {
throw new TokenError(TokenError.codes.invalidOption, 'The header option must be a object.')
}
const fpo = { jti, aud, iss, sub, nonce }
const fixedPayload = Object.entries(fpo).reduce((obj, [key, value]) => {
if (value !== undefined) {
obj[key] = value
}
return obj
}, {})
// Return the signer
const context = {
key,
algorithm,
noTimestamp,
mutatePayload,
clockTimestamp,
expiresIn,
notBefore,
kid,
typ,
isAsync: keyType === 'function',
additionalHeader,
fixedPayload
}
return sign.bind(null, context)
}