tsndr / cloudflare-worker-jwt

A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
MIT License
649 stars 51 forks source link

verify function fail #70

Closed walatory closed 6 months ago

walatory commented 6 months ago

hello, There may be a problem here, it cause verify fail

https://github.com/tsndr/cloudflare-worker-jwt/blob/0cd10e17f7bffe992da34630012382c45ef199e7/src/index.ts#L224-L228

I think Math.abs should not be used. Math.abs(...) > 0 almost.

tsndr commented 6 months ago

What's the error your're getting?

walatory commented 6 months ago

What's the error your're getting?

I use version 2.5.0 Restrict Timeframe in [README.md](https://github.com/tsndr/cloudflare-worker-jwt/blob/main/README.md)#examples and remove nbf!!


async () => {
    import jwt from '@tsndr/cloudflare-worker-jwt'

    // Creating a token
    const token = await jwt.sign({
        name: 'John Doe',
        email: 'john.doe@gmail.com',
        // nbf: Math.floor(Date.now() / 1000) + (60 * 60),      // Not before: Now + 1h
        exp: Math.floor(Date.now() / 1000) + (2 * (60 * 60)) // Expires: Now + 2h
    }, 'secret')

    // Verifing token
    const isValid = await jwt.verify(token, 'secret') // false

    // Check for validity
    if (!isValid)
        return

    // Decoding token
    const { payload } = jwt.decode(token) // { name: 'John Doe', email: 'john.doe@gmail.com', ... }
}

I run code above, after remove nbf, should isValid = true, but I gotisValid === false always

oof2win2 commented 6 months ago

I am also experiencing this error. I get the EXPIRED error thrown here in this case.

const JWT_SECRET = "bob"
const apikey = await jwt.sign(
    {
        jti: "123541",
        exp: Math.floor(Date.now() / 1000) + 86400,
        sub: "46",
    },
    JWT_SECRET,
);
const isValid = await jwt.verify(apikey, JWT_SECRET, {
    throwError: true,
});

I believe that the issue lies within https://github.com/tsndr/cloudflare-worker-jwt/blob/main/src/index.ts#L227 - when flipping the comparator to < then it works locally. I think the issue arose with the addition of clock tolerance - you flipped the sign in e503b16.

tsndr commented 6 months ago

Sorry about that, fixed with v2.5.1. Thanks for reporting :)

oof2win2 commented 6 months ago

Thanks for the quick reply and fix! Also thank you very much for maintaining such a useful library