Remove jsonwebtoken dependency

This commit is contained in:
advplyr 2022-07-06 18:45:43 -05:00
parent b61ecefce4
commit 954cf3e14e
29 changed files with 2130 additions and 93 deletions

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Auth0, Inc. <support@auth0.com> (http://auth0.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,30 @@
var jws = require('../jws');
module.exports = function (jwt, options) {
options = options || {};
var decoded = jws.decode(jwt, options);
if (!decoded) { return null; }
var payload = decoded.payload;
//try parse the payload
if (typeof payload === 'string') {
try {
var obj = JSON.parse(payload);
if (obj !== null && typeof obj === 'object') {
payload = obj;
}
} catch (e) { }
}
//return header if `complete` option is enabled. header includes claims
//such as `kid` and `alg` used to select the key within a JWKS needed to
//verify the signature
if (options.complete === true) {
return {
header: decoded.header,
payload: payload,
signature: decoded.signature
};
}
return payload;
};

View file

@ -0,0 +1,17 @@
//
// modified for use in audiobookshelf
// Source: https://github.com/auth0/node-jsonwebtoken
//
module.exports = {
verify: require('./verify'),
sign: require('./sign'),
JsonWebTokenError: require('./lib/JsonWebTokenError'),
NotBeforeError: require('./lib/NotBeforeError'),
TokenExpiredError: require('./lib/TokenExpiredError'),
};
Object.defineProperty(module.exports, 'decode', {
enumerable: false,
value: require('./decode'),
});

View file

@ -0,0 +1,14 @@
var JsonWebTokenError = function (message, error) {
Error.call(this, message);
if(Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = 'JsonWebTokenError';
this.message = message;
if (error) this.inner = error;
};
JsonWebTokenError.prototype = Object.create(Error.prototype);
JsonWebTokenError.prototype.constructor = JsonWebTokenError;
module.exports = JsonWebTokenError;

View file

@ -0,0 +1,13 @@
var JsonWebTokenError = require('./JsonWebTokenError');
var NotBeforeError = function (message, date) {
JsonWebTokenError.call(this, message);
this.name = 'NotBeforeError';
this.date = date;
};
NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype);
NotBeforeError.prototype.constructor = NotBeforeError;
module.exports = NotBeforeError;

View file

@ -0,0 +1,13 @@
var JsonWebTokenError = require('./JsonWebTokenError');
var TokenExpiredError = function (message, expiredAt) {
JsonWebTokenError.call(this, message);
this.name = 'TokenExpiredError';
this.expiredAt = expiredAt;
};
TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype);
TokenExpiredError.prototype.constructor = TokenExpiredError;
module.exports = TokenExpiredError;

View file

@ -0,0 +1,18 @@
var ms = require('../../ms');
module.exports = function (time, iat) {
var timestamp = iat || Math.floor(Date.now() / 1000);
if (typeof time === 'string') {
var milliseconds = ms(time);
if (typeof milliseconds === 'undefined') {
return;
}
return Math.floor(timestamp + milliseconds / 1000);
} else if (typeof time === 'number') {
return timestamp + time;
} else {
return;
}
};

View file

@ -0,0 +1,214 @@
var timespan = require('./lib/timespan');
var PS_SUPPORTED = true
var jws = require('../jws');
var once = require('../lodash.once');
var SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'];
if (PS_SUPPORTED) {
SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512');
}
function isPlainObject(value) {
var type = typeof value;
return !!value && type == 'object' && !Array.isArray(value);
}
function isInteger(val) {
return !isNaN(val) && val !== null && !String(val).includes('.')
}
function isNumber(val) {
return !isNaN(val) && val !== null
}
function isString(val) {
return typeof val == 'string'
}
var sign_options_schema = {
expiresIn: { isValid: function (value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' },
notBefore: { isValid: function (value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' },
audience: { isValid: function (value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' },
algorithm: { isValid: function (value) { return SUPPORTED_ALGS.includes(value); }, message: '"algorithm" must be a valid string enum value' },
header: { isValid: isPlainObject, message: '"header" must be an object' },
encoding: { isValid: isString, message: '"encoding" must be a string' },
issuer: { isValid: isString, message: '"issuer" must be a string' },
subject: { isValid: isString, message: '"subject" must be a string' },
jwtid: { isValid: isString, message: '"jwtid" must be a string' },
noTimestamp: { isValid: function (value) { return value === true || value === false; }, message: '"noTimestamp" must be a boolean' },
keyid: { isValid: isString, message: '"keyid" must be a string' },
mutatePayload: { isValid: function (value) { return value === true || value === false; }, message: '"mutatePayload" must be a boolean' }
};
var registered_claims_schema = {
iat: { isValid: isNumber, message: '"iat" should be a number of seconds' },
exp: { isValid: isNumber, message: '"exp" should be a number of seconds' },
nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' }
};
function validate(schema, allowUnknown, object, parameterName) {
if (!isPlainObject(object)) {
throw new Error('Expected "' + parameterName + '" to be a plain object.');
}
Object.keys(object)
.forEach(function (key) {
var validator = schema[key];
if (!validator) {
if (!allowUnknown) {
throw new Error('"' + key + '" is not allowed in "' + parameterName + '"');
}
return;
}
if (!validator.isValid(object[key])) {
throw new Error(validator.message);
}
});
}
function validateOptions(options) {
return validate(sign_options_schema, false, options, 'options');
}
function validatePayload(payload) {
return validate(registered_claims_schema, true, payload, 'payload');
}
var options_to_payload = {
'audience': 'aud',
'issuer': 'iss',
'subject': 'sub',
'jwtid': 'jti'
};
var options_for_objects = [
'expiresIn',
'notBefore',
'noTimestamp',
'audience',
'issuer',
'subject',
'jwtid',
];
module.exports = function (payload, secretOrPrivateKey, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
} else {
options = options || {};
}
var isObjectPayload = typeof payload === 'object' &&
!Buffer.isBuffer(payload);
var header = Object.assign({
alg: options.algorithm || 'HS256',
typ: isObjectPayload ? 'JWT' : undefined,
kid: options.keyid
}, options.header);
function failure(err) {
if (callback) {
return callback(err);
}
throw err;
}
if (!secretOrPrivateKey && options.algorithm !== 'none') {
return failure(new Error('secretOrPrivateKey must have a value'));
}
if (typeof payload === 'undefined') {
return failure(new Error('payload is required'));
} else if (isObjectPayload) {
try {
validatePayload(payload);
}
catch (error) {
return failure(error);
}
if (!options.mutatePayload) {
payload = Object.assign({}, payload);
}
} else {
var invalid_options = options_for_objects.filter(function (opt) {
return typeof options[opt] !== 'undefined';
});
if (invalid_options.length > 0) {
return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload) + ' payload'));
}
}
if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') {
return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));
}
if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') {
return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));
}
try {
validateOptions(options);
}
catch (error) {
return failure(error);
}
var timestamp = payload.iat || Math.floor(Date.now() / 1000);
if (options.noTimestamp) {
delete payload.iat;
} else if (isObjectPayload) {
payload.iat = timestamp;
}
if (typeof options.notBefore !== 'undefined') {
try {
payload.nbf = timespan(options.notBefore, timestamp);
}
catch (err) {
return failure(err);
}
if (typeof payload.nbf === 'undefined') {
return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
}
}
if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') {
try {
payload.exp = timespan(options.expiresIn, timestamp);
}
catch (err) {
return failure(err);
}
if (typeof payload.exp === 'undefined') {
return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
}
}
Object.keys(options_to_payload).forEach(function (key) {
var claim = options_to_payload[key];
if (typeof options[key] !== 'undefined') {
if (typeof payload[claim] !== 'undefined') {
return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.'));
}
payload[claim] = options[key];
}
});
var encoding = options.encoding || 'utf8';
if (typeof callback === 'function') {
callback = callback && once(callback);
jws.createSign({
header: header,
privateKey: secretOrPrivateKey,
payload: payload,
encoding: encoding
}).once('error', callback)
.once('done', function (signature) {
callback(null, signature);
});
} else {
return jws.sign({ header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding });
}
};

View file

@ -0,0 +1,225 @@
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 PS_SUPPORTED = true
var jws = require('../jws');
var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512'];
var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512'];
var HS_ALGS = ['HS256', 'HS384', 'HS512'];
if (PS_SUPPORTED) {
PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512');
RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512');
}
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;
};
}
if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') {
return done(new JsonWebTokenError('clockTimestamp must be a number'));
}
if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) {
return done(new JsonWebTokenError('nonce must be a non-empty string'));
}
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 decodedToken;
try {
decodedToken = decode(jwtString, { complete: true });
} catch (err) {
return done(err);
}
if (!decodedToken) {
return done(new JsonWebTokenError('invalid token'));
}
var header = decodedToken.header;
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 (!hasSignature && !options.algorithms) {
options.algorithms = ['none'];
}
if (!options.algorithms) {
options.algorithms = secretOrPublicKey.toString().includes('BEGIN CERTIFICATE') ||
secretOrPublicKey.toString().includes('BEGIN PUBLIC KEY') ? PUB_KEY_ALGS :
secretOrPublicKey.toString().includes('BEGIN RSA PUBLIC KEY') ? RSA_KEY_ALGS : HS_ALGS;
}
if (!~options.algorithms.indexOf(decodedToken.header.alg)) {
return done(new JsonWebTokenError('invalid algorithm'));
}
var valid;
try {
valid = jws.verify(jwtString, decodedToken.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.nonce) {
if (payload.nonce !== options.nonce) {
return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce));
}
}
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)));
}
}
if (options.complete === true) {
var signature = decodedToken.signature;
return done(null, {
header: header,
payload: payload,
signature: signature
});
}
return done(null, payload);
});
};