cloudflare-worker-jwt icon indicating copy to clipboard operation
cloudflare-worker-jwt copied to clipboard

`throwError` does not throw on invalid signature

Open stephent opened this issue 1 year ago • 1 comments

The readme states:

throws

If options.throwError is true and the token is invalid, an error will be thrown.

But the verify method does not throw if the following line returns false, even if throwError is true:

https://github.com/tsndr/cloudflare-worker-jwt/blob/8a75c24253af770fc27b8cb9ff25adf2eaa3291c/src/index.ts#L232

This could result in invalid JWTs being mistakenly accepted, if the caller assumes they can simply try/catch with throwError passed as true and don't also check the return value.

stephent avatar Jun 09 '24 18:06 stephent

See also #76 - the code shown there appears to make exactly this incorrect assumption.

stephent avatar Jun 09 '24 20:06 stephent

what about https://github.com/tsndr/cloudflare-worker-jwt/blob/8a75c24253af770fc27b8cb9ff25adf2eaa3291c/src/index.ts#L234-L236

chamini2 avatar Sep 27 '24 07:09 chamini2

@chamini2 what about it? That doesn't change anything about the reported issue...

stephent avatar Sep 27 '24 10:09 stephent

Can you share an example of this that should have failed

chamini2 avatar Sep 27 '24 17:09 chamini2

A JWT with an invalid signature will simply return false and won't throw even if throwError is set to true. crypto.subtle.verify doesn't always throw, per the docs (https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/verify#return_value).

I think it would be fine either throw an error if throwError is true and verify returns false`, or alternatively to update the documentation along the lines of

If options.throwError is true, any errors encountered while validating the token will be rethrown, however callers must always check the method return value to confirm token validity, as an invalid token does not necessarily result in a thrown error.

stephent avatar Sep 27 '24 17:09 stephent

As of v3.0.0 verify() will now throw INVALID_SIGNATURE and also return the decoded payload instead of a boolean.

tsndr avatar Oct 03 '24 17:10 tsndr