Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: fastify/fastify-jwt
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v9.0.2
Choose a base ref
...
head repository: fastify/fastify-jwt
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v9.0.3
Choose a head ref
  • 5 commits
  • 6 files changed
  • 1 contributor

Commits on Dec 29, 2024

  1. chore(package): add funding and contribs (#357)

    Signed-off-by: Frazer Smith <frazer.dev@icloud.com>
    Fdawgs authored Dec 29, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    c318c86 View commit details

Commits on Jan 7, 2025

  1. perf: use optional chaining (#359)

    Fdawgs authored Jan 7, 2025

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    0d4821e View commit details
  2. refactor: prefix unused params with underscores (#361)

    Fdawgs authored Jan 7, 2025

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    b8e3031 View commit details

Commits on Jan 11, 2025

  1. docs(readme): spelling and grammar fixes (#362)

    Signed-off-by: Frazer Smith <frazer.dev@icloud.com>
    Fdawgs authored Jan 11, 2025

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    8453f9c View commit details
  2. 9.0.3

    Fdawgs committed Jan 11, 2025

    Verified

    This commit was signed with the committer’s verified signature.
    Fdawgs Frazer Smith
    Copy the full SHA
    e9ee4b9 View commit details
Showing with 73 additions and 48 deletions.
  1. +12 −12 README.md
  2. +4 −8 jwt.js
  3. +30 −1 package.json
  4. +23 −23 test/jwt.test.js
  5. +3 −3 test/options.test.js
  6. +1 −1 types/jwt.test-d.ts
24 changes: 12 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@ npm i @fastify/jwt
```

## Usage
Register as a plugin. This will decorate your `fastify` instance with the following methods: `decode`, `sign`, and `verify`; refer to their documentation to find how to use the utilities. It will also register `request.jwtVerify` and `reply.jwtSign`. You must pass a `secret` when registering the plugin.
Register as a plugin. This will decorate your `fastify` instance with the following methods: `decode`, `sign`, and `verify`; refer to their documentation to find out how to use the utilities. It will also register `request.jwtVerify` and `reply.jwtSign`. You must pass a `secret` when registering the plugin.

```js
const fastify = require('fastify')()
@@ -56,7 +56,7 @@ fastify.addHook("onRequest", async (request, reply) => {
})
```

Afterwards, just use `request.user` in order to retrieve the user information:
Afterwards, just use `request.user` to retrieve the user information:

```js
module.exports = async function(fastify, opts) {
@@ -113,7 +113,7 @@ If you need to verify Auth0 issued HS256 or RS256 JWT tokens, you can use [fasti
### `secret` (required)
You must pass a `secret` to the `options` parameter. The `secret` can be a primitive type String, a function that returns a String or an object `{ private, public }`.

In this object `{ private, public }` the `private` key is a string, buffer or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA. In case of a private key with passphrase an object `{ private: { key, passphrase }, public }` can be used (based on [crypto documentation](https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format)), in this case be sure you pass the `algorithm` inside the signing options prefixed by the `sign` key of the plugin registering options).
In this object `{ private, public }` the `private` key is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA. In case of a private key with passphrase an object `{ private: { key, passphrase }, public }` can be used (based on [crypto documentation](https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format)), in this case be sure you pass the `algorithm` inside the signing options prefixed by the `sign` key of the plugin registering options).

In this object `{ private, public }` the `public` key is a string or buffer containing either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA.

@@ -320,7 +320,7 @@ fastify.listen({ port: 3000 }, err => {

### `onlyCookie`

Setting this options to `true` will decode only the cookie in the request. This is useful for refreshToken implementations where the request typically has two tokens: token and refreshToken. The main authentication token usually has a shorter timeout and the refresh token normally stored in the cookie has a longer timeout. This allows you to check to make sure that the cookie token is still valid, as it could have a different expiring time than the main token. The payloads of the two different tokens could also be different.
Setting this option to `true` will decode only the cookie in the request. This is useful for refreshToken implementations where the request typically has two tokens: token and refreshToken. The main authentication token usually has a shorter timeout and the refresh token normally stored in the cookie has a longer timeout. This allows you to check to make sure that the cookie token is still valid, as it could have a different expiring time than the main token. The payloads of the two different tokens could also be different.

```js
const fastify = require('fastify')()
@@ -606,7 +606,7 @@ fastify.register(require('@fastify/jwt'), {

### `decode`

* `complete`: Return an object with the decoded header, payload, signature and input (the token part before the signature), instead of just the content of the payload. Default is `false`.
* `complete`: Return an object with the decoded header, payload, signature, and input (the token part before the signature), instead of just the content of the payload. Default is `false`.
* `checkTyp`: When validating the decoded header, setting this option forces the check of the typ property against this value. Example: `checkTyp: 'JWT'`. Default is `undefined`.

### `sign`
@@ -624,9 +624,9 @@ fastify.register(require('@fastify/jwt'), {
* `key`: A string or a buffer containing the secret for `HS*` algorithms or the PEM encoded public key for `RS*`, `PS*`, `ES*` and `EdDSA` algorithms. The key can also be a function accepting a Node style callback or a function returning a promise. If provided, it will override the value of [secret](#secret-required) provided in the options.
* `algorithms`: List of strings with the names of the allowed algorithms. By default, all algorithms are accepted.
* `complete`: Return an object with the decoded header, payload, signature and input (the token part before the signature), instead of just the content of the payload. Default is `false`.
* `cache`: A positive number specifying the size of the verified tokens cache (using LRU strategy). Setting this to `true` is equivalent to provide the size 1000. When enabled the performance is dramatically improved. By default the cache is disabled.
* `cacheTTL`: The maximum time to live of a cache entry (in milliseconds). If the token has a earlier expiration or the verifier has a shorter `maxAge`, the earlier takes precedence. The default is `600000`, which is 10 minutes.
* `maxAge`: The maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span (E.g.: `60`, `"2 days"`, `"10h"`, `"7d"`). A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc.), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). By default this is not checked.
* `cache`: A positive number specifying the size of the verified tokens cache (using LRU strategy). Setting this to `true` is equivalent to provide the size 1000. When enabled the performance is dramatically improved. By default the cache is disabled.
* `cacheTTL`: The maximum time to live of a cache entry (in milliseconds). If the token has an earlier expiration or the verifier has a shorter `maxAge`, the earlier takes precedence. The default is `600000`, which is 10 minutes.
* `maxAge`: The maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span (E.g.: `60`, `"2 days"`, `"10h"`, `"7d"`). A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc.), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`). By default, this is not checked.
* ... the rest of the **verify** options can be found [here](https://github.com/nearform/fast-jwt#createverifier).

## API Spec
@@ -645,7 +645,7 @@ This method is used to verify provided token. It accepts a `token` (as `Buffer`
const token = fastify.jwt.sign({ foo: 'bar' })
// synchronously
const decoded = fastify.jwt.verify(token)
// asycnhronously
// asynchronously
fastify.jwt.verify(token, (err, decoded) => {
if (err) fastify.log.error(err)
fastify.log.info(`Token verified. Foo is ${decoded.foo}`)
@@ -665,7 +665,7 @@ fastify.log.info(`Decoded JWT: ${decoded}`)
```

### fastify.jwt.options
For your convenience, the `decode`, `sign`, `verify` and `messages` options you specify during `.register` are made available via `fastify.jwt.options` that will return an object `{ decode, sign, verify, messages }` containing your options.
For your convenience, the `decode`, `sign`, `verify`, and `messages` options you specify during `.register` are made available via `fastify.jwt.options` that will return an object `{ decode, sign, verify, messages }` containing your options.

#### Example
```js
@@ -771,7 +771,7 @@ You can find the list [here](https://github.com/nearform/fast-jwt#algorithms-sup

#### Certificates Generation

[Here](./example/UsingCertificates.md) some example on how to generate certificates and use them, with or without passphrase.
[Here](./example/UsingCertificates.md) are some examples of how to generate certificates and use them, with or without passphrase.

#### Signing and verifying (jwtSign, jwtVerify)
```js
@@ -909,7 +909,7 @@ fastify.get('/', async (request, reply) => {

```

## Acknowledgements
## Acknowledgments

This project is kindly sponsored by:
- [LetzDoIt](https://www.letzdoitapp.com/)
12 changes: 4 additions & 8 deletions jwt.js
Original file line number Diff line number Diff line change
@@ -23,7 +23,7 @@ function isString (x) {
}

function wrapStaticSecretInCallback (secret) {
return function (request, payload, cb) {
return function (_request, _payload, cb) {
return cb(null, secret)
}
}
@@ -67,18 +67,14 @@ function validateOptions (options) {
assert(!options.jwtSign || isString(options.jwtSign), 'Invalid options.jwtSign')

if (
options.sign &&
options.sign.algorithm &&
options.sign.algorithm.includes('RS') &&
options.sign?.algorithm?.includes('RS') &&
(typeof options.secret === 'string' ||
options.secret instanceof Buffer)
) {
throw new Error('RSA Signatures set as Algorithm in the options require a private and public key to be set as the secret')
}
if (
options.sign &&
options.sign.algorithm &&
options.sign.algorithm.includes('ES') &&
options.sign?.algorithm?.includes('ES') &&
(typeof options.secret === 'string' ||
options.secret instanceof Buffer)
) {
@@ -509,7 +505,7 @@ function fastifyJwt (fastify, options, next) {
} else {
const maybePromise = trusted(request, result)

if (maybePromise && maybePromise.then) {
if (maybePromise?.then) {
maybePromise
.then(trusted => trusted ? callback(null, result) : callback(new AuthorizationTokenUntrustedError()))
} else if (maybePromise) {
31 changes: 30 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@fastify/jwt",
"version": "9.0.2",
"version": "9.0.3",
"description": "JWT utils for Fastify",
"main": "jwt.js",
"type": "commonjs",
@@ -26,11 +26,40 @@
"fastify"
],
"author": "Tomas Della Vedova - @delvedor (http://delved.org)",
"contributors": [
{
"name": "Matteo Collina",
"email": "hello@matteocollina.com"
},
{
"name": "Manuel Spigolon",
"email": "behemoth89@gmail.com"
},
{
"name": "Aras Abbasi",
"email": "aras.abbasi@gmail.com"
},
{
"name": "Frazer Smith",
"email": "frazer.dev@icloud.com",
"url": "https://github.com/fdawgs"
}
],
"license": "MIT",
"bugs": {
"url": "https://github.com/fastify/fastify-jwt/issues"
},
"homepage": "https://github.com/fastify/fastify-jwt#readme",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"dependencies": {
"@fastify/error": "^4.0.0",
"@lukeed/ms": "^2.0.2",
46 changes: 23 additions & 23 deletions test/jwt.test.js
Original file line number Diff line number Diff line change
@@ -96,7 +96,7 @@ test('register', function (t) {
t.plan(1)
const fastify = Fastify()
fastify.register(jwt, {
secret: (request, token, callback) => { callback(null, Buffer.from('some secret', 'base64')) }
secret: (_request, _token, callback) => { callback(null, Buffer.from('some secret', 'base64')) }
}).ready(function (error) {
t.error(error)
})
@@ -106,7 +106,7 @@ test('register', function (t) {
t.plan(1)
const fastify = Fastify()
fastify.register(jwt, {
secret: (request, token) => Promise.resolve(Buffer.from('some secret', 'base64'))
secret: () => Promise.resolve(Buffer.from('some secret', 'base64'))
}).ready(function (error) {
t.error(error)
})
@@ -116,7 +116,7 @@ test('register', function (t) {
t.plan(1)
const fastify = Fastify()
fastify.register(jwt, {
secret: async (request, token) => Buffer.from('some secret', 'base64')
secret: async () => Buffer.from('some secret', 'base64')
}).ready(function (error) {
t.error(error)
})
@@ -263,7 +263,7 @@ test('register', function (t) {
return reply.send({ token })
})

fastify.get('/verify', function (request, reply) {
fastify.get('/verify', function (request) {
return request.jwtVerify()
})

@@ -290,37 +290,37 @@ test('register', function (t) {
}

t.test('secret as a function with callback', t => {
return runWithSecret(t, function (request, token, callback) {
return runWithSecret(t, function (_request, _token, callback) {
callback(null, 'some-secret')
})
})

t.test('secret as a function returning a promise', t => {
return runWithSecret(t, function (request, token) {
return runWithSecret(t, function () {
return Promise.resolve('some-secret')
})
})

t.test('secret as an async function', t => {
return runWithSecret(t, async function (request, token) {
return runWithSecret(t, async function () {
return 'some-secret'
})
})

t.test('secret as a function with callback returning a Buffer', t => {
return runWithSecret(t, function (request, token, callback) {
return runWithSecret(t, function (_request, _token, callback) {
callback(null, Buffer.from('some-secret', 'base64'))
})
})

t.test('secret as a function returning a promise with a Buffer', t => {
return runWithSecret(t, function (request, token) {
return runWithSecret(t, function () {
return Promise.resolve(Buffer.from('some secret', 'base64'))
})
})

t.test('secret as an async function returning a Buffer', t => {
return runWithSecret(t, async function (request, token) {
return runWithSecret(t, async function () {
return Buffer.from('some secret', 'base64')
})
})
@@ -386,7 +386,7 @@ test('sign and verify with HS-secret', function (t) {
})
})

fastify.get('/verifySync', function (request, reply) {
fastify.get('/verifySync', function (request) {
return request.jwtVerify()
})

@@ -554,7 +554,7 @@ test('sign and verify with RSA/ECDSA certificates and global options', function
t.plan(4)

try {
fastifyVerifier.jwt.sign({ foo: 'baz' }, function (error, token) {
fastifyVerifier.jwt.sign({ foo: 'baz' }, function (error) {
// as for now, verifier-only error is not propagated here
t.error('SHOULD NOT BE HERE')
t.error(error)
@@ -594,7 +594,7 @@ test('sign and verify with RSA/ECDSA certificates and global options', function
})
})

fastify.get('/verifySync', function (request, reply) {
fastify.get('/verifySync', function (request) {
return request.jwtVerify()
})

@@ -692,7 +692,7 @@ test('sign and verify with RSA/ECDSA certificates and global options', function
})
})

fastifyVerifier.get('/verifySync', function (request, reply) {
fastifyVerifier.get('/verifySync', function (request) {
return request.jwtVerify()
})

@@ -807,7 +807,7 @@ test('sign and verify with RSA/ECDSA certificates and global options', function
})
})

fastify.get('/verifySync', function (request, reply) {
fastify.get('/verifySync', function (request) {
return request.jwtVerify()
})

@@ -962,7 +962,7 @@ test('sign and verify with RSA/ECDSA certificates and global options', function
})
})

fastify.get('/verifySync', function (request, reply) {
fastify.get('/verifySync', function (request) {
return request.jwtVerify()
})

@@ -1117,7 +1117,7 @@ test('sign and verify with RSA/ECDSA certificates and global options', function
})
})

fastify.get('/verifySync', function (request, reply) {
fastify.get('/verifySync', function (request) {
return request.jwtVerify()
})

@@ -1276,7 +1276,7 @@ test('sign and verify with RSA/ECDSA certificates and global options', function
})
})

fastify.get('/verifySync', function (request, reply) {
fastify.get('/verifySync', function (request) {
return request.jwtVerify()
})

@@ -1361,7 +1361,7 @@ test('sign and verify with trusted token', function (t) {
t.plan(2)

const f = Fastify()
f.register(jwt, { secret: 'test', trusted: (request, { jti }) => jti !== 'untrusted' })
f.register(jwt, { secret: 'test', trusted: (_request, { jti }) => jti !== 'untrusted' })
f.get('/', (request, reply) => {
request.jwtVerify()
.then(function (decodedToken) {
@@ -1391,7 +1391,7 @@ test('sign and verify with trusted token', function (t) {
t.plan(2)

const f = Fastify()
f.register(jwt, { secret: 'test', trusted: (request, { jti }) => Promise.resolve(jti !== 'untrusted') })
f.register(jwt, { secret: 'test', trusted: (_request, { jti }) => Promise.resolve(jti !== 'untrusted') })
f.get('/', (request, reply) => {
request.jwtVerify()
.then(function (decodedToken) {
@@ -1503,7 +1503,7 @@ test('errors', function (t) {
const fastify = Fastify()
fastify.register(jwt, {
secret: 'test',
trusted: (request, { jti }) => jti !== 'untrusted',
trusted: (_request, { jti }) => jti !== 'untrusted',
decode: { checkTyp: 'JWT' }
})

@@ -1747,7 +1747,7 @@ test('errors', function (t) {
t.plan(2)

const f = Fastify()
f.register(jwt, { secret: 'test', trusted: (request, { jti }) => Promise.resolve(jti !== 'untrusted') })
f.register(jwt, { secret: 'test', trusted: (_request, { jti }) => Promise.resolve(jti !== 'untrusted') })
f.get('/', (request, reply) => {
request.jwtVerify()
.then(function (decodedToken) {
@@ -2353,7 +2353,7 @@ test('custom response messages', function (t) {
t.plan(6)

const fastify = Fastify()
fastify.register(jwt, { secret: 'test', messages: { noAuthorizationInHeaderMessage: 'auth header missing', authorizationTokenExpiredMessage: 'token expired', authorizationTokenInvalid: 'invalid token', authorizationTokenUntrusted: 'untrusted token', authorizationTokenUnsigned: 'unsigned token' }, trusted: (request, { jti }) => jti !== 'untrusted' })
fastify.register(jwt, { secret: 'test', messages: { noAuthorizationInHeaderMessage: 'auth header missing', authorizationTokenExpiredMessage: 'token expired', authorizationTokenInvalid: 'invalid token', authorizationTokenUntrusted: 'untrusted token', authorizationTokenUnsigned: 'unsigned token' }, trusted: (_request, { jti }) => jti !== 'untrusted' })

fastify.get('/verify', function (request, reply) {
request.jwtVerify()
Loading