forked from ozomer/node-jsonwebtoken
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathverify.js
236 lines (192 loc) · 7.84 KB
/
verify.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
var JsonWebTokenError = require('./lib/JsonWebTokenError');
var NotBeforeError = require('./lib/NotBeforeError');
var TokenExpiredError = require('./lib/TokenExpiredError');
var decode = require('./decode');
var timespan = require('./lib/timespan');
var ed25519Utils = require('./lib/ed25519Utils');
var jws = require('jws');
var ed25519 = require('./lib/ed25519');
var util = require('util');
module.exports = function (jwtString, secretOrPublicKey, options, callback) {
if ((typeof options === 'function') && !callback) {
callback = options;
options = {};
}
if (!options) {
options = {};
}
//clone this object since we are going to mutate it.
options = Object.assign({}, options);
var done;
if (callback) {
done = callback;
} else {
done = function(err, data) {
if (err) throw err;
return data;
};
}
// secretOrPublicKey may be an object of the format: { "algorithm": ..., "key": ... }
if (secretOrPublicKey && secretOrPublicKey.algorithm) {
if (options.algorithm) {
if (options.algorithm !== secretOrPublicKey.algorithm) {
return done(new JsonWebTokenError('The algorithm specified in the key is different from the algorithm specified in the options'));
}
} else {
options.algorithm = secretOrPublicKey.algorithm;
}
secretOrPublicKey = secretOrPublicKey.key;
}
if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') {
return done(new JsonWebTokenError('clockTimestamp must be a number'));
}
var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000);
if (!jwtString){
return done(new JsonWebTokenError('jwt must be provided'));
}
if (typeof jwtString !== 'string') {
return done(new JsonWebTokenError('jwt must be a string'));
}
var parts = jwtString.split('.');
if (parts.length !== 3){
return done(new JsonWebTokenError('jwt malformed'));
}
var hasSignature = parts[2].trim() !== '';
if (!hasSignature && secretOrPublicKey){
return done(new JsonWebTokenError('jwt signature is required'));
}
if (hasSignature && !secretOrPublicKey) {
return done(new JsonWebTokenError('secret or public key must be provided'));
}
if (!options.algorithm) {
var assumedAlgorithms = ~(secretOrPublicKey || '').toString().indexOf('BEGIN CERTIFICATE') ||
~(secretOrPublicKey || '').toString().indexOf('BEGIN PUBLIC KEY') ?
[ 'RS256','RS384','RS512','ES256','ES384','ES512' ] :
~(secretOrPublicKey || '').toString().indexOf('BEGIN RSA PUBLIC KEY') ?
[ 'RS256','RS384','RS512' ] :
[ 'HS256','HS384','HS512' ];
// We intentionally don't tell the user that his algorithm might be "none".
return done(new JsonWebTokenError('algorithm must be specified in the options or in the key. Looking at the key, it is probably one of: ' + assumedAlgorithms.join(', ')))
}
var decodedToken;
try {
decodedToken = decode(jwtString, { complete: true });
} catch(err) {
return done(err);
}
if (!decodedToken) {
return done(new JsonWebTokenError('invalid token'));
}
var header = decodedToken.header;
if (!(options.algorithm === 'Ed25519' && header.alg === 'EdDSA' ||
options.algorithm === header.alg)) {
return done(new JsonWebTokenError('invalid algorithm'));
}
var getSecret;
if (typeof secretOrPublicKey === 'function') {
if (!callback) {
return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback'));
}
getSecret = secretOrPublicKey;
}
else {
getSecret = function(header, secretCallback) {
return secretCallback(null, secretOrPublicKey);
};
}
return getSecret(header, function(err, secretOrPublicKey) {
if(err) {
return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message));
}
var hasSignature = parts[2].trim() !== '';
if (!hasSignature && secretOrPublicKey){
return done(new JsonWebTokenError('jwt signature is required'));
}
if (hasSignature && !secretOrPublicKey) {
return done(new JsonWebTokenError('secret or public key must be provided'));
}
if (header.alg === 'EdDSA') {
try {
secretOrPublicKey = ed25519Utils.toPublicKey(secretOrPublicKey);
} catch (err) {
return done(new JsonWebTokenError('Invalid Ed25519 public key'));
}
}
var valid;
try {
if (header.alg === 'EdDSA') {
// Token must have good format because jws.decode validated it.
var securedInput = ed25519Utils.bufferFromString(util.format('%s.%s', parts[0], parts[1]));
var signature = ed25519Utils.bufferFromString(parts[2], 'base64');
valid = (signature.length === ed25519Utils.SIGNATURE_SIZE) && ed25519.Verify(securedInput, signature, secretOrPublicKey);
} else {
valid = jws.verify(jwtString, header.alg, secretOrPublicKey);
}
} catch (e) {
return done(e);
}
if (!valid) {
return done(new JsonWebTokenError('invalid signature'));
}
var payload = decodedToken.payload;
if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) {
if (typeof payload.nbf !== 'number') {
return done(new JsonWebTokenError('invalid nbf value'));
}
if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) {
return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000)));
}
}
if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) {
if (typeof payload.exp !== 'number') {
return done(new JsonWebTokenError('invalid exp value'));
}
if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) {
return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000)));
}
}
if (options.audience) {
var audiences = Array.isArray(options.audience) ? options.audience : [options.audience];
var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
var match = target.some(function (targetAudience) {
return audiences.some(function (audience) {
return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience;
});
});
if (!match) {
return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or ')));
}
}
if (options.issuer) {
var invalid_issuer =
(typeof options.issuer === 'string' && payload.iss !== options.issuer) ||
(Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1);
if (invalid_issuer) {
return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer));
}
}
if (options.subject) {
if (payload.sub !== options.subject) {
return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject));
}
}
if (options.jwtid) {
if (payload.jti !== options.jwtid) {
return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid));
}
}
if (options.maxAge) {
if (typeof payload.iat !== 'number') {
return done(new JsonWebTokenError('iat required when maxAge is specified'));
}
var maxAgeTimestamp = timespan(options.maxAge, payload.iat);
if (typeof maxAgeTimestamp === 'undefined') {
return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
}
if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) {
return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000)));
}
}
return done(null, payload);
});
};