so npm audit just found jsonwebtoken to have a security vulnerbility. The solution is to update to version 9.0.0 - which I did.
However, my mocha tests are not passing now. During a beforeEach, I am trying to stub the decode function using sinon.stub, which now throws this TypeError:
TypeError: Cannot redefine property: decode
The beforeEach:
const jwt = require('jsonwebtoken');
beforeEach(function () {
this.sinon.stub(jwt, 'verify').returns({ email: '[email protected]' });
this.sinon.stub(jwt, 'decode').returns({ header: { alg: 'RS256', typ: 'JWT', kid: 'MOCKKID' } });
this.sinon.stub(jwks, 'getKey').returns('some mock certificate');
this.sinon.stub(T, 'expired');
});
I assume that stubbing verify still works, since the error only throws on the next line when I try to stub decode
Yes, there is a post with similar question, but it's two years old, and the accepted answer is that "this is soon to be fixed in a future version". So not really relevant anymore.
Because jsonwebtoken v9.0.0 makes the decode function non-enumerable and non-configurable, see v9.0.0/index.js#L9
index.js:
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'),
});
From the documentation Non-configurable properties created by Object.defineProperty
The
Object.defineProperty()creates non-configurable properties if you haven't specified them as configurable.
Which means the configurable: false is the default. That's why sinon.stub(jwt, 'decode') doesn't work anymore.
And there is PR trying to fix it to allow the decode function to be stubbed. This PR makes the decode configurable:
Object.defineProperty(module.exports, 'decode', {
enumerable: false,
configurable: true,
value: require('./decode'),
});
There is a temporary solution, you can create your own jwt utils module and stub your own jwt utils.
E.g.
jwt-repack.js:
const jwt = require('jsonwebtoken');
const decode = require('jsonwebtoken').decode;
module.exports = {
...jwt,
decode
};
index.test.js:
const sinon = require('sinon');
const jwt = require('./jwt-repack');
it('should pass', () => {
sinon.stub(jwt, 'decode').returns({ header: { alg: 'RS256', typ: 'JWT', kid: 'MOCKKID' } });
const actual = jwt.decode();
sinon.assert.match(actual, { header: { alg: 'RS256', typ: 'JWT', kid: 'MOCKKID' } });
});
package versions:
"jsonwebtoken9": "npm:jsonwebtoken@^9.0.0",
"sinon": "^8.1.1",
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With