auth0 / node-jsonwebtoken

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html
MIT License
17.68k stars 1.23k forks source link

v9: `decode` does not work with `import *` in TypeScript #875

Open bluepichu opened 1 year ago

bluepichu commented 1 year ago

Description

If you import * as jwt from "jsonwebtoken", then you can't call jwt.decode. It works fine if you use a default import though (import jwt from "jsonwebtoken").

Related to #866, and probably also #870.

The root cause of this is that import * in TS gets translated in such a way that only enumerable properties are copied from the module. Since decode is non-enumerable it is not properly copied.

Reproduction

import * as jwt from "jsonwebtoken";

jwt.decode("abc"); // TypeError: jwt.decode is not a function

Environment

Version 9.0.0 on Node 16.19.0 with TS 4.6.2

swapnil-sudhir commented 1 year ago

Any solution for this so far ? @bluepichu

lloydjatkinson commented 1 year ago
import { decode } from 'jsonwebtoken';

console.log(
    decode(
        'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE2NzMyNzcwNTMsImV4cCI6MTcwNDgxMzA1MywiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.cN6HdDt31tosRDffE6UIgDGy3lgjFW9j9uO-VCd8S7U'
    )
);
rpuls commented 1 year ago

I am having an issue that I think is related. Long story short, I am getting: TypeError: Cannot redefine property: decode when trying to stub decode with sinon.stub - but no issue stubbing the verify function.

I require jwt like this: const jwt = require('jsonwebtoken'); and my stack does not allow me to use import

I posted the issue on OS with some more detail: https://stackoverflow.com/questions/75071217/jsonwebtoken-9-0-0-getting-error-typeerror-cannot-redefine-property-decode

bluepichu commented 1 year ago

@rpuls I think your issue is the same as #870 (which has a temporary workaround and an open fix)

rocket2023 commented 1 year ago

Version 9.0.0 on Node 16.19.0 and node 18.x with TS 4.x jwt.sign(...); // TypeError: jwt.sign is not a function

lloydjatkinson commented 1 year ago

@rocket2023 https://github.com/auth0/node-jsonwebtoken/issues/875#issuecomment-1375779641