Projektstart

This commit is contained in:
2026-01-22 15:49:12 +01:00
parent 7212eb6f7a
commit 57e5f652f8
10637 changed files with 2598792 additions and 64 deletions

2
backend/node_modules/@fastify/jwt/.gitattributes generated vendored Normal file
View File

@@ -0,0 +1,2 @@
# Set default behavior to automatically convert line endings
* text=auto eol=lf

View File

@@ -0,0 +1,13 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"
open-pull-requests-limit: 10
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "monthly"
open-pull-requests-limit: 10

21
backend/node_modules/@fastify/jwt/.github/stale.yml generated vendored Normal file
View File

@@ -0,0 +1,21 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 15
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- "discussion"
- "feature request"
- "bug"
- "help wanted"
- "plugin suggestion"
- "good first issue"
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

View File

@@ -0,0 +1,25 @@
name: CI
on:
push:
branches:
- main
- next
- 'v*'
paths-ignore:
- 'docs/**'
- '*.md'
pull_request:
paths-ignore:
- 'docs/**'
- '*.md'
jobs:
test:
permissions:
contents: write
pull-requests: write
uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5
with:
license-check: true
lint: true

21
backend/node_modules/@fastify/jwt/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Fastify
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

919
backend/node_modules/@fastify/jwt/README.md generated vendored Normal file
View File

@@ -0,0 +1,919 @@
# @fastify/jwt
[![CI](https://github.com/fastify/fastify-jwt/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-jwt/actions/workflows/ci.yml)
[![NPM version](https://img.shields.io/npm/v/@fastify/jwt.svg?style=flat)](https://www.npmjs.com/package/@fastify/jwt)
[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)
JWT utils for Fastify, internally it uses [fast-jwt](https://github.com/nearform/fast-jwt).
**NOTE:** The plugin has been migrated from using `jsonwebtoken` to `fast-jwt`. Even though `fast-jwt` has 1:1 feature implementation with `jsonwebtoken`, some _exotic_ implementations might break. In that case please open an issue with details of your implementation. See [Upgrading notes](UPGRADING.md) for more details about what changes this migration introduced.
- `@fastify/jwt` >= v9 supports Fastify@5.
- `@fastify/jwt` < v9 supports Fastify@4.
- `@fastify/jwt` < v6 supports Fastify@3.
- `@fastify/jwt` [v1.x](https://github.com/fastify/fastify-jwt/tree/1.x)
supports both Fastify@2.
## Install
```
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 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')()
fastify.register(require('@fastify/jwt'), {
secret: 'supersecret'
})
fastify.post('/signup', (req, reply) => {
// some code
const token = fastify.jwt.sign({ payload })
reply.send({ token })
})
fastify.listen({ port: 3000 }, err => {
if (err) throw err
})
```
For verifying & accessing the decoded token inside your services, you can use a global `onRequest` hook to define the verification process like so:
```js
const fastify = require('fastify')()
fastify.register(require('@fastify/jwt'), {
secret: 'supersecret'
})
fastify.addHook("onRequest", async (request, reply) => {
try {
await request.jwtVerify()
} catch (err) {
reply.send(err)
}
})
```
Afterwards, just use `request.user` to retrieve the user information:
```js
module.exports = async function(fastify, opts) {
fastify.get("/", async function(request, reply) {
return request.user
})
}
```
However, most of the time we want to protect only some of the routes in our application. To achieve this you can wrap your authentication logic into a plugin like
```js
const fp = require("fastify-plugin")
module.exports = fp(async function(fastify, opts) {
fastify.register(require("@fastify/jwt"), {
secret: "supersecret"
})
fastify.decorate("authenticate", async function(request, reply) {
try {
await request.jwtVerify()
} catch (err) {
reply.send(err)
}
})
})
```
Then use the `onRequest` of a route to protect it & access the user information inside:
```js
module.exports = async function(fastify, opts) {
fastify.get(
"/",
{
onRequest: [fastify.authenticate]
},
async function(request, reply) {
return request.user
}
)
}
```
Make sure that you also check [@fastify/auth](https://github.com/fastify/fastify-auth) plugin for composing more complex strategies.
### Auth0 tokens verification
If you need to verify Auth0 issued HS256 or RS256 JWT tokens, you can use [fastify-auth0-verify](https://github.com/nearform/fastify-auth0-verify), which is based on top of this module.
## Options
### `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 `public` key is a string or buffer containing either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA.
Function based `secret` is supported by the `request.jwtVerify()` and `reply.jwtSign()` methods and is called with `request`, `token`, and `callback` parameters.
#### Verify-only mode
In cases where your incoming JWT tokens are issued by a trusted external
service, and you need only to verify their signature without issuing, there is
an option to configure `fastify-jwt` in *verify-only* mode by passing the
`secret` object containing only a public key: `{ public }`.
When only a public key is provided, decode and verification functions will work as
described below, but an exception will be thrown at an attempt to use any form
of `sign` functionality.
#### Example
```js
const { readFileSync } = require('node:fs')
const path = require('node:path')
const fastify = require('fastify')()
const jwt = require('@fastify/jwt')
// secret as a string
fastify.register(jwt, { secret: 'supersecret' })
// secret as a function with callback
fastify.register(jwt, {
secret: function (request, token, callback) {
// do something
callback(null, 'supersecret')
}
})
// secret as a function returning a promise
fastify.register(jwt, {
secret: function (request, token) {
return Promise.resolve('supersecret')
}
})
// secret as an async function
fastify.register(jwt, {
secret: async function (request, token) {
return 'supersecret'
}
})
// secret as an object of RSA keys (without passphrase)
// the files are loaded as strings
fastify.register(jwt, {
secret: {
private: readFileSync(`${path.join(__dirname, 'certs')}/private.key`, 'utf8'),
public: readFileSync(`${path.join(__dirname, 'certs')}/public.key`, 'utf8')
},
sign: { algorithm: 'RS256' }
})
// secret as an object of P-256 ECDSA keys (with a passphrase)
// the files are loaded as buffers
fastify.register(jwt, {
secret: {
private: {
key: readFileSync(`${path.join(__dirname, 'certs')}/private.pem`),
passphrase: 'super secret passphrase'
},
public: readFileSync(`${path.join(__dirname, 'certs')}/public.pem`)
},
sign: { algorithm: 'ES256' }
})
// secret as an object with RSA public key
// fastify-jwt is configured in VERIFY-ONLY mode
fastify.register(jwt, {
secret: {
public: process.env.JWT_ISSUER_PUBKEY
}
})
```
### Default options
Optionally you can define global default options that will be used by `@fastify/jwt` API if you do not override them.
#### Example
```js
const { readFileSync } = require('node:fs')
const path = require('node:path')
const fastify = require('fastify')()
const jwt = require('@fastify/jwt')
fastify.register(jwt, {
secret: {
private: readFileSync(`${path.join(__dirname, 'certs')}/private.pem`, 'utf8')
public: readFileSync(`${path.join(__dirname, 'certs')}/public.pem`, 'utf8')
},
// Global default decoding method options
decode: { complete: true },
// Global default signing method options
sign: {
algorithm: 'ES256',
iss: 'api.example.tld'
},
// Global default verifying method options
verify: { allowedIss: 'api.example.tld' }
})
fastify.get('/decode', async (request, reply) => {
// We clone the global signing options before modifying them
let altSignOptions = Object.assign({}, fastify.jwt.options.sign)
altSignOptions.iss = 'another.example.tld'
// We generate a token using the default sign options
const token = await reply.jwtSign({ foo: 'bar' })
// We generate a token using overrided options
const tokenAlt = await reply.jwtSign({ foo: 'bar' }, altSignOptions)
// We decode the token using the default options
const decodedToken = fastify.jwt.decode(token)
// We decode the token using completely overided the default options
const decodedTokenAlt = fastify.jwt.decode(tokenAlt, { complete: false })
return { decodedToken, decodedTokenAlt }
/**
* Will return:
*
* {
* "decodedToken": {
* "header": {
* "alg": "ES256",
* "typ": "JWT"
* },
* "payload": {
* "foo": "bar",
* "iat": 1540305336
* "iss": "api.example.tld"
* },
* "signature": "gVf5bzROYB4nPgQC0nbJTWCiJ3Ya51cyuP-N50cidYo"
* },
* decodedTokenAlt: {
* "foo": "bar",
* "iat": 1540305337
* "iss": "another.example.tld"
* },
* }
*/
})
fastify.listen({ port: 3000 }, err => {
if (err) throw err
})
```
### `cookie`
#### Example using cookie
In some situations you may want to store a token in a cookie. This allows you to drastically reduce the attack surface of XSS on your web app with the [`httpOnly`](https://owasp.org/www-community/HttpOnly) and `secure` flags. Cookies can be susceptible to CSRF. You can mitigate this by either setting the [`sameSite`](https://owasp.org/www-community/SameSite) flag to `strict`, or by using a CSRF library such as [`@fastify/csrf`](https://www.npmjs.com/package/@fastify/csrf).
**Note:** This plugin will look for a decorated request with the `cookies` property. [`@fastify/cookie`](https://www.npmjs.com/package/@fastify/cookie) supports this feature, and therefore you should use it when using the cookie feature. The plugin will fallback to looking for the token in the authorization header if either of the following happens (even if the cookie option is enabled):
- The request has both the authorization and cookie header
- Cookie is empty, authorization header is present
If you are signing your cookie, you can set the `signed` boolean to `true` which will make sure the JWT is verified using the unsigned value.
```js
const fastify = require('fastify')()
const jwt = require('@fastify/jwt')
fastify.register(jwt, {
secret: 'foobar',
cookie: {
cookieName: 'token',
signed: false
}
})
fastify
.register(require('@fastify/cookie'))
fastify.get('/cookies', async (request, reply) => {
const token = await reply.jwtSign({
name: 'foo',
role: ['admin', 'spy']
})
reply
.setCookie('token', token, {
domain: 'your.domain',
path: '/',
secure: true, // send cookie over HTTPS only
httpOnly: true,
sameSite: true // alternative CSRF protection
})
.code(200)
.send('Cookie sent')
})
fastify.addHook('onRequest', (request) => request.jwtVerify())
fastify.get('/verifycookie', (request, reply) => {
reply.send({ code: 'OK', message: 'it works!' })
})
fastify.listen({ port: 3000 }, err => {
if (err) throw err
})
```
### `onlyCookie`
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')()
const jwt = require('@fastify/jwt')
fastify.register(jwt, {
secret: 'foobar',
cookie: {
cookieName: 'refreshToken',
},
sign: {
expiresIn: '10m'
}
})
fastify
.register(require('@fastify/cookie'))
fastify.get('/cookies', async (request, reply) => {
const token = await reply.jwtSign({
name: 'foo'
})
const refreshToken = await reply.jwtSign({
name: 'bar'
}, {expiresIn: '1d'})
reply
.setCookie('refreshToken', refreshToken, {
domain: 'your.domain',
path: '/',
secure: true, // send cookie over HTTPS only
httpOnly: true,
sameSite: true // alternative CSRF protection
})
.code(200)
.send({token})
})
fastify.addHook('onRequest', (request) => request.jwtVerify({onlyCookie: true}))
fastify.get('/verifycookie', (request, reply) => {
reply.send({ code: 'OK', message: 'it works!' })
})
fastify.listen({ port: 3000 }, err => {
if (err) throw err
})
```
### `trusted`
Additionally, it is also possible to reject tokens selectively (i.e. blacklisting) by providing the option `trusted` with the following signature: `(request, decodedToken) => boolean|Promise<boolean>|SignPayloadType|Promise<SignPayloadType>` where `request` is a `FastifyRequest` and `decodedToken` is the parsed (and verified) token information. Its result should be `false` or `Promise<false>` if the token should be rejected or, otherwise, be `true` or `Promise<true>` if the token should be accepted and, considering that `request.user` will be used after that, the return should be `decodedToken` itself.
#### Example trusted tokens
```js
const fastify = require('fastify')()
fastify.register(require('@fastify/jwt'), {
secret: 'foobar',
trusted: validateToken
})
fastify.addHook('onRequest', (request) => request.jwtVerify())
fastify.get('/', (request, reply) => {
reply.send({ code: 'OK', message: 'it works!' })
})
fastify.listen({ port: 3000 }, (err) => {
if (err) {
throw err
}
})
// ideally this function would do a query against some sort of storage to determine its outcome
async function validateToken(request, decodedToken) {
const denylist = ['token1', 'token2']
return !denylist.includes(decodedToken.jti)
}
```
### `formatUser`
#### Example with formatted user
You may customize the `request.user` object setting a custom sync function as parameter:
```js
const fastify = require('fastify')();
fastify.register(require('@fastify/jwt'), {
formatUser: function (user) {
return {
departmentName: user.department_name,
name: user.name
}
},
secret: 'supersecret'
});
fastify.addHook('onRequest', (request, reply) => request.jwtVerify());
fastify.get("/", async (request, reply) => {
return `Hello, ${request.user.name} from ${request.user.departmentName}.`;
});
```
### `namespace`
To define multiple JWT validators on the same routes, you may use the
`namespace` option. You can combine this with custom names for `jwtVerify`,
`jwtDecode`, and `jwtSign`.
When you omit the `jwtVerify`, `jwtDecode`, or `jwtSign` options, the default
function name will be `<namespace>JwtVerify`, `<namespace>JwtDecode` and
`<namespace>JwtSign` correspondingly.
#### Example with namespace
```js
const fastify = require('fastify')
fastify.register(jwt, {
secret: 'test',
namespace: 'security',
// will decorate request with `securityVerify`, `securitySign`,
// and default `securityJwtDecode` since no custom alias provided
jwtVerify: 'securityVerify',
jwtSign: 'securitySign'
})
fastify.register(jwt, {
secret: 'fastify',
// will decorate request with default `airDropJwtVerify`, `airDropJwtSign`,
// and `airDropJwtDecode` since no custom aliases provided
namespace: 'airDrop'
})
// use them like this:
fastify.post('/sign/:namespace', async function (request, reply) {
switch (request.params.namespace) {
case 'security':
return reply.securitySign(request.body)
default:
return reply.airDropJwtSign(request.body)
}
})
```
### `extractToken`
Setting this option will allow you to extract a token using function passed in for `extractToken` option. The function definition should be `(request: FastifyRequest) => token`. Fastify JWT will check if this option is set, if this option is set it will use the function defined in the option. When this option is not set then it will follow the normal flow.
```js
const fastify = require('fastify')
const jwt = require('@fastify/jwt')
fastify.register(jwt, { secret: 'test', verify: { extractToken: (request) => request.headers.customauthheader } })
fastify.post('/sign', function (request, reply) {
return reply.jwtSign(request.body)
.then(function (token) {
return { token }
})
})
fastify.get('/verify', function (request, reply) {
// token avaiable via `request.headers.customauthheader` as defined in fastify.register above
return request.jwtVerify()
.then(function (decodedToken) {
return reply.send(decodedToken)
})
})
fastify.listen(3000, function (err) {
if (err) throw err
})
```
#### Typescript
To simplify the use of namespaces in TypeScript you can use the `FastifyJwtNamespace` helper type:
```typescript
declare module 'fastify' {
interface FastifyInstance extends
FastifyJwtNamespace<{namespace: 'security'}> {
}
}
```
Alternatively you can type each key explicitly:
```typescript
declare module 'fastify' {
interface FastifyInstance extends
FastifyJwtNamespace<{
jwtDecode: 'securityJwtDecode',
jwtSign: 'securityJwtSign',
jwtVerify: 'securityJwtVerify',
}> { }
}
```
### `messages`
For your convenience, you can override the default HTTP response messages sent when an unauthorized or bad request error occurs. You can choose the specific messages to override and the rest will fallback to the default messages. The object must be in the format specified in the example below.
#### Example
```js
const fastify = require('fastify')
const myCustomMessages = {
badRequestErrorMessage: 'Format is Authorization: Bearer [token]',
badCookieRequestErrorMessage: 'Cookie could not be parsed in request',
noAuthorizationInHeaderMessage: 'No Authorization was found in request.headers',
noAuthorizationInCookieMessage: 'No Authorization was found in request.cookies',
authorizationTokenExpiredMessage: 'Authorization token expired',
authorizationTokenUntrusted: 'Untrusted authorization token',
authorizationTokenUnsigned: 'Unsigned authorization token'
// for the below message you can pass a sync function that must return a string as shown or a string
authorizationTokenInvalid: (err) => {
return `Authorization token is invalid: ${err.message}`
}
}
fastify.register(require('@fastify/jwt'), {
secret: 'supersecret',
messages: myCustomMessages
})
```
##### Error Code
`ERR_ASSERTION` - Missing required parameter or option
* Error Status Code: `500`
* Error Message: `Missing ${required}`
`FST_JWT_BAD_REQUEST` - Bad format in request authorization header. Example of correct format `Authorization: Bearer [token]`
* Error Status Code: `400`
* Error Message: `Format is Authorization: Bearer [token]`
`FST_JWT_BAD_COOKIE_REQUEST` - Cookie could not be parsed in request object
* Error Status Code: `400`
* Error Message: `Cookie could not be parsed in request`
`FST_JWT_NO_AUTHORIZATION_IN_HEADER` - No Authorization header was found in request.headers
* Error Status Code: `401`
* Error Message: `No Authorization was found in request.headers
`FST_JWT_NO_AUTHORIZATION_IN_COOKIE` - No Authorization header was found in request.cookies
* Error Status Code: `401`
* Error Message: `No Authorization was found in request.cookies`
`FST_JWT_AUTHORIZATION_TOKEN_EXPIRED` - Authorization token has expired
* Error Status Code: `401`
* Error Message: `Authorization token expired`
`FST_JWT_AUTHORIZATION_TOKEN_INVALID` - Authorization token provided is invalid.
* Error Status Code: `401`
* Error Message: `Authorization token is invalid: ${err.message}`
`FST_JWT_AUTHORIZATION_TOKEN_UNTRUSTED` - Untrusted authorization token was provided
* Error Status Code: `401`
* Error Message: `Untrusted authorization token`
`FAST_JWT_MISSING_SIGNATURE` - Unsigned or missing authorization token
* Error Status Code: `401`
* Error Message: `Unsigned authorization token`
### `decoratorName`
If this plugin is used together with fastify/passport, we might get an error as both plugins use the same name for a decorator. We can change the name of the decorator, or `user` will default
#### Example
```js
const fastify = require('fastify')
fastify.register(require('@fastify/jwt'), {
secret: 'supersecret',
decoratorName: 'customName'
})
```
### `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`.
* `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`
* `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.
* `algorithm`: The algorithm to use to sign the token. The default is autodetected from the key, using RS256 for RSA private keys, HS256 for plain secrets and the correspondent ES or EdDSA algorithms for EC or Ed* private keys.
* `mutatePayload`: If set to `true`, the original payload will be modified in place (via `Object.assign`) by the signing function. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.
* `expiresIn`: Time span after which the token expires, added as the `exp` claim in the payload. 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"`). This will override any existing value in the claim.
* `notBefore`: Time span before the token is active, added as the `nbf` claim in the payload. 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"`). This will override any existing value in the claim.
* ... the rest of the **sign** options can be found [here](https://github.com/nearform/fast-jwt#createsigner).
### `verify`
* `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 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
### fastify.jwt.sign(payload [,options] [,callback])
This method is used to sign the provided `payload`. It returns the token.
The `payload` must be an `Object`. Can be used asynchronously by passing a callback function; synchronously without a callback.
`options` must be an `Object` and can contain [sign](#sign) options.
### fastify.jwt.verify(token, [,options] [,callback])
This method is used to verify provided token. It accepts a `token` (as `Buffer` or a `string`) and returns the payload or the sections of the token. Can be used asynchronously by passing a callback function; synchronously without a callback.
`options` must be an `Object` and can contain [verify](#verify) options.
#### Example
```js
const token = fastify.jwt.sign({ foo: 'bar' })
// synchronously
const decoded = fastify.jwt.verify(token)
// asynchronously
fastify.jwt.verify(token, (err, decoded) => {
if (err) fastify.log.error(err)
fastify.log.info(`Token verified. Foo is ${decoded.foo}`)
})
```
### fastify.jwt.decode(token [,options])
This method is used to decode the provided token. It accepts a token (as a `Buffer` or a `string`) and returns the payload or the sections of the token.
`options` must be an `Object` and can contain [decode](#decode) options.
Can only be used synchronously.
#### Example
```js
const token = fastify.jwt.sign({ foo: 'bar' })
const decoded = fastify.jwt.decode(token)
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.
#### Example
```js
const { readFileSync } = require('node:fs')
const path = require('node:path')
const fastify = require('fastify')()
const jwt = require('@fastify/jwt')
fastify.register(jwt, {
secret: {
private: readFileSync(`${path.join(__dirname, 'certs')}/private.key`),
public: readFileSync(`${path.join(__dirname, 'certs')}/public.key`)
},
sign: {
algorithm: 'RS256',
aud: 'foo',
iss: 'example.tld'
},
verify: {
allowedAud: 'foo',
allowedIss: 'example.tld',
}
})
fastify.get('/', (request, reply) => {
const globalOptions = fastify.jwt.options
// We recommend that you clone the options like this when you need to mutate them
// modifiedVerifyOptions = { audience: 'foo', issuer: 'example.tld' }
let modifiedVerifyOptions = Object.assign({}, fastify.jwt.options.verify)
modifiedVerifyOptions.allowedAud = 'bar'
modifiedVerifyOptions.allowedSub = 'test'
return { globalOptions, modifiedVerifyOptions }
/**
* Will return :
* {
* globalOptions: {
* decode: {},
* sign: {
* algorithm: 'RS256',
* aud: 'foo',
* iss: 'example.tld'
* },
* verify: {
* allowedAud: 'foo',
* allowedIss: 'example.tld'
* }
* },
* modifiedVerifyOptions: {
* allowedAud: 'bar',
* allowedIss: 'example.tld',
* allowedSub: 'test'
* }
* }
*/
})
fastify.listen({ port: 3000 }, err => {
if (err) throw err
})
```
### fastify.jwt.cookie
For your convenience, `request.jwtVerify()` will look for the token in the cookies property of the decorated request. You must specify `cookieName`. Refer to the [cookie example](https://github.com/fastify/fastify-jwt#example-using-cookie) to see sample usage and important caveats.
### reply.jwtSign(payload, [options,] callback)
`options` must be an `Object` and can contain `sign` options.
### request.jwtVerify([options,] callback)
`options` must be an `Object` and can contain `verify` and `decode` options.
### request.jwtDecode([options,] callback)
Decode a JWT without verifying.
`options` must be an `Object` and can contain `verify` and `decode` options.
### Algorithms supported
The following algorithms are currently supported by [fast-jwt](https://github.com/nearform/fast-jwt) that is internally used by `@fastify/jwt`.
**Name** | **Description**
----------------|----------------------------
none | Empty algorithm - The token signature section will be empty
HS256 | HMAC using SHA-256 hash algorithm
HS384 | HMAC using SHA-384 hash algorithm
HS512 | HMAC using SHA-512 hash algorithm
ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm
ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm
ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm
RS256 | RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm
RS384 | RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm
RS512 | RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm
PS256 | RSASSA-PSS using SHA-256 hash algorithm
PS384 | RSASSA-PSS using SHA-384 hash algorithm
PS512 | RSASSA-PSS using SHA-512 hash algorithm
EdDSA | EdDSA tokens using Ed25519 or Ed448 keys, only supported on Node.js 12+
You can find the list [here](https://github.com/nearform/fast-jwt#algorithms-supported).
### Examples
#### Certificates Generation
[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
const fastify = require('fastify')()
const jwt = require('@fastify/jwt')
const request = require('request')
fastify.register(jwt, {
secret: function (request, reply, callback) {
// do something
callback(null, 'supersecret')
}
})
fastify.post('/sign', function (request, reply) {
reply.jwtSign(request.body.payload, function (err, token) {
return reply.send(err || { 'token': token })
})
})
fastify.get('/verify', function (request, reply) {
request.jwtVerify(function (err, decoded) {
return reply.send(err || decoded)
})
})
fastify.listen({ port: 3000 }, function (err) {
if (err) fastify.log.error(err)
fastify.log.info(`Server live on port: ${fastify.server.address().port}`)
// sign payload and get JWT
request({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
payload: {
foo: 'bar'
}
},
uri: `http://localhost:${fastify.server.address().port}/sign`,
json: true
}, function (err, response, body) {
if (err) fastify.log.error(err)
fastify.log.info(`JWT token is ${body.token}`)
// verify JWT
request({
method: 'GET',
headers: {
'Content-Type': 'application/json',
authorization: 'Bearer ' + body.token
},
uri: 'http://localhost:' + fastify.server.address().port + '/verify',
json: true
}, function (err, response, body) {
if (err) fastify.log.error(err)
fastify.log.info(`JWT verified. Foo is ${body.foo}`)
})
})
})
```
#### Verifying with JWKS
The following example integrates the [get-jwks](https://github.com/nearform/get-jwks) package to fetch a JWKS and verify a JWT against a valid public JWK.
##### Example
```js
const Fastify = require('fastify')
const fjwt = require('@fastify/jwt')
const buildGetJwks = require('get-jwks')
const fastify = Fastify()
const getJwks = buildGetJwks()
fastify.register(fjwt, {
decode: { complete: true },
secret: (request, token) => {
const { header: { kid, alg }, payload: { iss } } = token
return getJwks.getPublicKey({ kid, domain: iss, alg })
}
})
fastify.addHook('onRequest', async (request, reply) => {
try {
await request.jwtVerify()
} catch (err) {
reply.send(err)
}
})
fastify.listen({ port: 3000 })
```
## TypeScript
This plugin has two available exports, the default plugin function `fastifyJwt` and the plugin options object `FastifyJWTOptions`.
Import them like so:
```ts
import fastifyJwt, { FastifyJWTOptions } from '@fastify/jwt'
```
Define custom Payload Type and Attached User Type to request object
> [typescript declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html)
```ts
// fastify-jwt.d.ts
import "@fastify/jwt"
declare module "@fastify/jwt" {
interface FastifyJWT {
payload: { id: number } // payload type is used for signing and verifying
user: {
id: number,
name: string,
age: number
} // user type is return type of `request.user` object
}
}
// index.ts
fastify.get('/', async (request, reply) => {
request.user.name // string
const token = await reply.jwtSign({
id: '123'
// ^ Type 'string' is not assignable to type 'number'.
});
})
```
## Acknowledgments
This project is kindly sponsored by:
- [LetzDoIt](https://www.letzdoitapp.com/)
## License
Licensed under [MIT](./LICENSE).

23
backend/node_modules/@fastify/jwt/UPGRADING.md generated vendored Normal file
View File

@@ -0,0 +1,23 @@
## Upgrading Notes
This document captures breaking changes between versions of `@fastify/jwt`.
### Upgrading from 3.x to 4.0
In `v4` we migrated away from using `jsonwebtoken` to `fast-jwt`. This introduced the following breaking changes:
- **sign** options:
- `audience` should be changed to `aud`
- `issuer` should be changed to `iss`
- `jwtid` should be changed to `jti`
- `subject` should be changed to `sub`
- `keyId` should be changed to `kid`
- **verify** options:
- `audience` should be changed to `allowedAud`
- `issuer` should be changed to `allowedIss`
- `subject` should be changed to `allowedSub`
- `jwtid` should be changed to `allowedJti`
- `nonce` should be changed to `allowedNonce`
- **decode** options:
- `json` option has been removed
- `checkTyp` option has been introduced. If set to a string value, a check of the `typ` header claim is forced. Example: `checkTyp: 'JWT'`. By default `checkTyp` is `undefined`.

6
backend/node_modules/@fastify/jwt/eslint.config.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
'use strict'
module.exports = require('neostandard')({
ignores: require('neostandard').resolveIgnoresFromGitignore(),
ts: true
})

View File

@@ -0,0 +1,118 @@
# Certificates generation
## RSA Signatures - Certificates (without passphrase)
Certificates `private.key` and `public.key` are generated with http://travistidwell.com/jsencrypt/demo/ or with the following command
```sh
openssl genrsa -out private.key 2048
openssl rsa -in private.key -out public.key -outform PEM -pubout
```
Code example
```js
const { readFileSync } = require('node:fs')
const fastify = require('fastify')()
const jwt = require('@fastify/jwt')
fastify.register(jwt, {
secret: {
private: readFileSync('path/to/private.key', 'utf8'),
public: readFileSync('path/to/public.key', 'utf8')
},
sign: { algorithm: 'RS256' }
})
```
## RSA Signatures - Certificates (with passphrase)
Certificates `private.pem` and `public.pem` are generated with the following command lines
```sh
# generate a 2048-bit RSA key pair, and encrypts them with a passphrase
# the passphrase I choose for the demo files is: super secret passphrase
openssl genrsa -des3 -out private.pem 2048
# export the RSA public key to a file
openssl rsa -in private.pem -outform PEM -pubout -out public.pem
```
Code example
```js
const { readFileSync } = require('node:fs')
const fastify = require('fastify')()
const jwt = require('@fastify/jwt')
fastify.register(jwt, {
secret: {
private: {
key: readFileSync('path/to/private.pem', 'utf8'),
passphrase: 'super secret passphrase'
},
public: readFileSync('path/to/public.pem', 'utf8')
},
sign: { algorithm: 'RS256' }
})
```
## ECDSA Signatures - Certificates (without passphrase)
Certificates `privateECDSA.key` and `publicECDSA.key` are generated with the following command lines
```sh
# generate a P-256 curve ECDSA key pair
openssl ecparam -genkey -name prime256v1 -out privateECDSA.key
# export the ECDSA public key to a file
openssl ec -in privateECDSA.key -pubout -out publicECDSA.key
```
Code example
```js
const { readFileSync } = require('node:fs')
const fastify = require('fastify')()
const jwt = require('@fastify/jwt')
fastify.register(jwt, {
secret: {
private: readFileSync('path/to/privateECDSA.key', 'utf8'),
public: readFileSync('path/to/publicECDSA.key', 'utf8')
},
sign: { algorithm: 'ES256' }
})
```
## ECDSA Signatures - Certificates (with passphrase)
Certificates `privateECDSA.pem` and `publicECDSA.pem` are generated with the following command lines
```sh
# generate a P-256 curve ECDSA key pair, and encrypts them with a passphrase
# the passphrase I choose for the demo files is: super secret passphrase
openssl ecparam -genkey -name prime256v1 | openssl ec -aes256 -out privateECDSA.pem
# export the ECDSA public key to a file
openssl ec -in privateECDSA.pem -pubout -out publicECDSA.pem
```
Code example
```js
const { readFileSync } = require('node:fs')
const fastify = require('fastify')()
const jwt = require('@fastify/jwt')
fastify.register(jwt, {
secret: {
private: {
key: readFileSync('path/to/publicECDSA.pem', 'utf8'),
passphrase: 'super secret passphrase'
},
public: readFileSync('path/to/publicECDSA.pem', 'utf8')
},
sign: { algorithm: 'ES256' }
})
```

570
backend/node_modules/@fastify/jwt/jwt.js generated vendored Normal file
View File

@@ -0,0 +1,570 @@
'use strict'
const fp = require('fastify-plugin')
const { createSigner, createDecoder, createVerifier, TokenError } = require('fast-jwt')
const assert = require('node:assert')
const steed = require('steed')
const { parse } = require('@lukeed/ms')
const createError = require('@fastify/error')
const messages = {
badRequestErrorMessage: 'Format is Authorization: Bearer [token]',
badCookieRequestErrorMessage: 'Cookie could not be parsed in request',
noAuthorizationInHeaderMessage: 'No Authorization was found in request.headers',
noAuthorizationInCookieMessage: 'No Authorization was found in request.cookies',
authorizationTokenExpiredMessage: 'Authorization token expired',
authorizationTokenInvalid: (err) => `Authorization token is invalid: ${err.message}`,
authorizationTokenUntrusted: 'Untrusted authorization token',
authorizationTokenUnsigned: 'Unsigned authorization token'
}
function isString (x) {
return Object.prototype.toString.call(x) === '[object String]'
}
function wrapStaticSecretInCallback (secret) {
return function (_request, _payload, cb) {
return cb(null, secret)
}
}
function convertToMs (time) {
// by default if time is number we assume that they are seconds - see README.md
if (typeof time === 'number') {
return time * 1000
}
return parse(time)
}
function convertTemporalProps (options, isVerifyOptions) {
if (!options || typeof options === 'function') {
return options
}
const formatedOptions = Object.assign({}, options)
if (isVerifyOptions && formatedOptions.maxAge) {
formatedOptions.maxAge = convertToMs(formatedOptions.maxAge)
} else if (formatedOptions.expiresIn || formatedOptions.notBefore) {
if (formatedOptions.expiresIn) {
formatedOptions.expiresIn = convertToMs(formatedOptions.expiresIn)
}
if (formatedOptions.notBefore) {
formatedOptions.notBefore = convertToMs(formatedOptions.notBefore)
}
}
return formatedOptions
}
function validateOptions (options) {
assert(options.secret, 'missing secret')
assert(!options.options, 'options prefix is deprecated')
assert(!options.jwtVerify || isString(options.jwtVerify), 'Invalid options.jwtVerify')
assert(!options.jwtDecode || isString(options.jwtDecode), 'Invalid options.jwtDecode')
assert(!options.jwtSign || isString(options.jwtSign), 'Invalid options.jwtSign')
if (
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?.algorithm?.includes('ES') &&
(typeof options.secret === 'string' ||
options.secret instanceof Buffer)
) {
throw new Error('ECDSA Signatures set as Algorithm in the options require a private and public key to be set as the secret')
}
}
function fastifyJwt (fastify, options, next) {
try {
validateOptions(options)
} catch (e) {
return next(e)
}
const {
cookie,
decode: decodeOptions = {},
formatUser,
jwtDecode,
jwtSign,
jwtVerify,
secret,
sign: initialSignOptions = {},
trusted,
decoratorName = 'user',
// TODO: disable on next major
// enable errorCacheTTL to prevent breaking change
verify: initialVerifyOptions = { errorCacheTTL: 600000 },
...pluginOptions
} = options
const validatorCache = new Map()
let secretOrPrivateKey
let secretOrPublicKey
if (typeof secret === 'object' && !Buffer.isBuffer(secret)) {
if (!secret.public) {
return next(new Error('missing public key'))
}
secretOrPrivateKey = secret.private
secretOrPublicKey = secret.public
} else {
secretOrPrivateKey = secretOrPublicKey = secret
}
let hasStaticPublicKey = false
let secretCallbackSign = secretOrPrivateKey
let secretCallbackVerify = secretOrPublicKey
if (typeof secretCallbackSign !== 'function') {
secretCallbackSign = wrapStaticSecretInCallback(secretCallbackSign)
}
if (typeof secretCallbackVerify !== 'function') {
secretCallbackVerify = wrapStaticSecretInCallback(secretCallbackVerify)
hasStaticPublicKey = true
}
const signOptions = convertTemporalProps(initialSignOptions)
const verifyOptions = convertTemporalProps(initialVerifyOptions, true)
const messagesOptions = Object.assign({}, messages, pluginOptions.messages)
const namespace = typeof pluginOptions.namespace === 'string' ? pluginOptions.namespace : undefined
const NoAuthorizationInCookieError = createError('FST_JWT_NO_AUTHORIZATION_IN_COOKIE', messagesOptions.noAuthorizationInCookieMessage, 401)
const AuthorizationTokenExpiredError = createError('FST_JWT_AUTHORIZATION_TOKEN_EXPIRED', messagesOptions.authorizationTokenExpiredMessage, 401)
const AuthorizationTokenUntrustedError = createError('FST_JWT_AUTHORIZATION_TOKEN_UNTRUSTED', messagesOptions.authorizationTokenUntrusted, 401)
const AuthorizationTokenUnsignedError = createError('FAST_JWT_MISSING_SIGNATURE', messagesOptions.authorizationTokenUnsigned, 401)
const NoAuthorizationInHeaderError = createError('FST_JWT_NO_AUTHORIZATION_IN_HEADER', messagesOptions.noAuthorizationInHeaderMessage, 401)
const AuthorizationTokenInvalidError = createError('FST_JWT_AUTHORIZATION_TOKEN_INVALID', typeof messagesOptions.authorizationTokenInvalid === 'function'
? messagesOptions.authorizationTokenInvalid({ message: '%s' })
: messagesOptions.authorizationTokenInvalid
, 401)
const BadRequestError = createError('FST_JWT_BAD_REQUEST', messagesOptions.badRequestErrorMessage, 400)
const BadCookieRequestError = createError('FST_JWT_BAD_COOKIE_REQUEST', messagesOptions.badCookieRequestErrorMessage, 400)
const jwtDecorator = {
decode,
options: {
decode: decodeOptions,
sign: initialSignOptions,
verify: initialVerifyOptions,
messages: messagesOptions,
decoratorName
},
cookie,
sign,
verify,
lookupToken
}
let jwtDecodeName = 'jwtDecode'
let jwtVerifyName = 'jwtVerify'
let jwtSignName = 'jwtSign'
if (namespace) {
if (!fastify.jwt) {
fastify.decorateRequest(decoratorName, null)
fastify.decorate('jwt', Object.create(null))
}
if (fastify.jwt[namespace]) {
return next(new Error(`JWT namespace already used "${namespace}"`))
}
fastify.jwt[namespace] = jwtDecorator
jwtDecodeName = jwtDecode || `${namespace}JwtDecode`
jwtVerifyName = jwtVerify || `${namespace}JwtVerify`
jwtSignName = jwtSign || `${namespace}JwtSign`
} else {
fastify.decorateRequest(decoratorName, null)
fastify.decorate('jwt', jwtDecorator)
}
fastify.decorateRequest(jwtDecodeName, requestDecode)
fastify.decorateRequest(jwtVerifyName, requestVerify)
fastify.decorateReply(jwtSignName, replySign)
const signerConfig = checkAndMergeSignOptions()
// no signer when configured in verify-mode
const signer = signerConfig.options.key
? createSigner(signerConfig.options)
: null
const decoder = createDecoder(decodeOptions)
const verifierConfig = checkAndMergeVerifyOptions()
const verifier = createVerifier(verifierConfig.options)
next()
function getVerifier (options, globalOptions) {
const useGlobalOptions = globalOptions ?? options === verifierConfig.options
// Use global verifier if using global options with static key
if (useGlobalOptions && hasStaticPublicKey) return verifier
// Only cache verifier when using default options (except for key)
if (useGlobalOptions && options.key && typeof options.key === 'string') {
let verifier = validatorCache.get(options.key)
if (!verifier) {
verifier = createVerifier(options)
validatorCache.set(options.key, verifier)
}
return verifier
}
return createVerifier(options)
}
function decode (token, options) {
assert(token, 'missing token')
let selectedDecoder = decoder
if (options && options !== decodeOptions && typeof options !== 'function') {
selectedDecoder = createDecoder(options)
}
try {
return selectedDecoder(token)
} catch (error) {
// Ignoring the else branch because it's not possible to test it,
// it's just a safeguard for future changes in the fast-jwt library
if (error.code === TokenError.codes.malformed) {
throw new AuthorizationTokenInvalidError(error.message)
} else if (error.code === TokenError.codes.invalidType) {
throw new AuthorizationTokenInvalidError(error.message)
} /* c8 ignore start */ else {
throw error
} /* c8 ignore stop */
}
}
function lookupToken (request, options) {
assert(request, 'missing request')
options = Object.assign({}, verifyOptions, options)
let token
const extractToken = options.extractToken
const onlyCookie = options.onlyCookie
if (extractToken) {
token = extractToken(request)
if (!token) {
throw new BadRequestError()
}
} else if (request.headers.authorization && !onlyCookie && /^Bearer\s/i.test(request.headers.authorization)) {
const parts = request.headers.authorization.split(' ')
if (parts.length === 2) {
token = parts[1]
} else {
throw new BadRequestError()
}
} else if (cookie) {
if (request.cookies) {
if (request.cookies[cookie.cookieName]) {
const tokenValue = request.cookies[cookie.cookieName]
token = cookie.signed ? request.unsignCookie(tokenValue).value : tokenValue
} else {
throw new NoAuthorizationInCookieError()
}
} else {
throw new BadCookieRequestError()
}
} else {
throw new NoAuthorizationInHeaderError()
}
return token
}
function mergeOptionsWithKey (options, useProvidedPrivateKey) {
if (useProvidedPrivateKey && (typeof useProvidedPrivateKey !== 'boolean')) {
return Object.assign({}, options, { key: useProvidedPrivateKey })
} else {
const key = useProvidedPrivateKey ? secretOrPrivateKey : secretOrPublicKey
return Object.assign(!options.key ? { key } : {}, options)
}
}
function checkAndMergeOptions (options, defaultOptions, usePrivateKey, callback) {
if (typeof options === 'function') {
return { options: mergeOptionsWithKey(defaultOptions, usePrivateKey), callback: options }
}
return { options: mergeOptionsWithKey(options || defaultOptions, usePrivateKey), callback }
}
function checkAndMergeSignOptions (options, callback) {
return checkAndMergeOptions(options, signOptions, true, callback)
}
function checkAndMergeVerifyOptions (options, callback) {
return checkAndMergeOptions(options, verifyOptions, false, callback)
}
function sign (payload, options, callback) {
assert(payload, 'missing payload')
// if a global signer was not created, sign mode is not supported
assert(signer, 'unable to sign: secret is configured in verify mode')
let localSigner = signer
const localOptions = convertTemporalProps(options)
const signerConfig = checkAndMergeSignOptions(localOptions, callback)
if (options && typeof options !== 'function') {
localSigner = createSigner(signerConfig.options)
}
if (typeof signerConfig.callback === 'function') {
const token = localSigner(payload)
signerConfig.callback(null, token)
} else {
return localSigner(payload)
}
}
function verify (token, options, callback) {
assert(token, 'missing token')
assert(secretOrPublicKey, 'missing secret')
let localVerifier = verifier
const localOptions = convertTemporalProps(options, true)
const verifierConfig = checkAndMergeVerifyOptions(localOptions, callback)
if (options && typeof options !== 'function') {
localVerifier = getVerifier(verifierConfig.options)
}
if (typeof verifierConfig.callback === 'function') {
const result = localVerifier(token)
verifierConfig.callback(null, result)
} else {
return localVerifier(token)
}
}
function replySign (payload, options, next) {
// if a global signer was not created, sign mode is not supported
assert(signer, 'unable to sign: secret is configured in verify mode')
let useLocalSigner = true
if (typeof options === 'function') {
next = options
options = {}
useLocalSigner = false
} // support no options
if (!options) {
options = {}
useLocalSigner = false
}
const reply = this
if (next === undefined) {
return new Promise(function (resolve, reject) {
reply[jwtSignName](payload, options, function (err, val) {
err ? reject(err) : resolve(val)
})
})
}
if (options.sign) {
const localSignOptions = convertTemporalProps(options.sign)
// New supported contract, options supports sign and can expand
options = {
sign: mergeOptionsWithKey(Object.assign({}, signOptions, localSignOptions), true)
}
} else {
const localOptions = convertTemporalProps(options)
// Original contract, options supports only sign
options = mergeOptionsWithKey(Object.assign({}, signOptions, localOptions), true)
}
if (!payload) {
return next(new Error('jwtSign requires a payload'))
}
steed.waterfall([
function getSecret (callback) {
const signResult = secretCallbackSign(reply.request, payload, callback)
if (signResult && typeof signResult.then === 'function') {
signResult.then(result => callback(null, result), callback)
}
},
function sign (secretOrPrivateKey, callback) {
if (useLocalSigner) {
const signerOptions = mergeOptionsWithKey(options.sign || options, secretOrPrivateKey)
const localSigner = createSigner(signerOptions)
const token = localSigner(payload)
callback(null, token)
} else {
const token = signer(payload)
callback(null, token)
}
}
], next)
}
function requestDecode (options, next) {
if (typeof options === 'function' && !next) {
next = options
options = {}
} // support no options
if (!options) {
options = {}
}
options = {
decode: Object.assign({}, decodeOptions, options.decode),
verify: Object.assign({}, verifyOptions, options.verify)
}
const request = this
if (next === undefined) {
return new Promise(function (resolve, reject) {
request[jwtDecodeName](options, function (err, val) {
err ? reject(err) : resolve(val)
})
})
}
try {
const token = lookupToken(request, options.verify)
const decodedToken = decode(token, options.decode)
return next(null, decodedToken)
} catch (err) {
return next(err)
}
}
function requestVerify (options, next) {
const request = this
if (next === undefined) {
return new Promise(function (resolve, reject) {
request[jwtVerifyName](options, function (err, val) {
err ? reject(err) : resolve(val)
})
})
}
const useGlobalOptions = !options
if (typeof options === 'function') {
next = options
options = {}
} // support no options
if (!options) {
options = {}
}
if (options.decode || options.verify) {
const localVerifyOptions = convertTemporalProps(options.verify, true)
// New supported contract, options supports both decode and verify
options = {
decode: Object.assign({}, decodeOptions, options.decode),
verify: Object.assign({}, verifyOptions, localVerifyOptions)
}
} else {
const localOptions = convertTemporalProps(options, true)
// Original contract, options supports only verify
options = Object.assign({}, verifyOptions, localOptions)
}
let token
try {
token = lookupToken(request, options.verify || options)
} catch (err) {
return next(err)
}
const decodedToken = decode(token, options.decode || decodeOptions)
steed.waterfall([
function getSecret (callback) {
const verifyResult = secretCallbackVerify(request, decodedToken, callback)
if (verifyResult && typeof verifyResult.then === 'function') {
verifyResult.then(result => callback(null, result), callback)
}
},
function verify (secretOrPublicKey, callback) {
try {
const verifierOptions = mergeOptionsWithKey(options.verify || options, secretOrPublicKey)
const localVerifier = getVerifier(verifierOptions, useGlobalOptions)
const verifyResult = localVerifier(token)
if (verifyResult && typeof verifyResult.then === 'function') {
verifyResult.then(result => callback(null, result), error => wrapError(error, callback))
} else {
callback(null, verifyResult)
}
} catch (error) {
return wrapError(error, callback)
}
},
function checkIfIsTrusted (result, callback) {
if (!trusted) {
callback(null, result)
} else {
const maybePromise = trusted(request, result)
if (maybePromise?.then) {
maybePromise
.then(trusted => trusted ? callback(null, result) : callback(new AuthorizationTokenUntrustedError()))
} else if (maybePromise) {
callback(null, result)
} else {
callback(new AuthorizationTokenUntrustedError())
}
}
}
], function (err, result) {
if (err) {
next(err)
} else {
const user = formatUser ? formatUser(result) : result
request[decoratorName] = user
next(null, user)
}
})
}
function wrapError (error, callback) {
if (error.code === TokenError.codes.expired) {
return callback(new AuthorizationTokenExpiredError())
}
if (error.code === TokenError.codes.invalidKey ||
error.code === TokenError.codes.invalidSignature ||
error.code === TokenError.codes.invalidClaimValue ||
error.code === TokenError.codes.missingRequiredClaim
) {
return callback(typeof messagesOptions.authorizationTokenInvalid === 'function'
? new AuthorizationTokenInvalidError(error.message)
: new AuthorizationTokenInvalidError())
}
if (error.code === TokenError.codes.missingSignature) {
return callback(new AuthorizationTokenUnsignedError())
}
return callback(error)
}
}
module.exports = fp(fastifyJwt, {
fastify: '5.x',
name: '@fastify/jwt'
})
module.exports.default = fastifyJwt
module.exports.fastifyJwt = fastifyJwt

View File

@@ -0,0 +1,2 @@
# Set default behavior to automatically convert line endings
* text=auto eol=lf

View File

@@ -0,0 +1,13 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"
open-pull-requests-limit: 10
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "monthly"
open-pull-requests-limit: 10

View File

@@ -0,0 +1,21 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 15
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- "discussion"
- "feature request"
- "bug"
- "help wanted"
- "plugin suggestion"
- "good first issue"
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

View File

@@ -0,0 +1,28 @@
name: CI
on:
push:
branches:
- main
- next
- 'v*'
paths-ignore:
- 'docs/**'
- '*.md'
pull_request:
paths-ignore:
- 'docs/**'
- '*.md'
permissions:
contents: read
jobs:
test:
permissions:
contents: write
pull-requests: write
uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5
with:
license-check: true
lint: true

View File

@@ -0,0 +1,23 @@
MIT License
Copyright (c) 2017-present The Fastify team
The Fastify team members are listed at https://github.com/fastify/fastify#team.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,188 @@
# fastify-plugin
[![CI](https://github.com/fastify/fastify-plugin/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-plugin/actions/workflows/ci.yml)
[![NPM version](https://img.shields.io/npm/v/fastify-plugin.svg?style=flat)](https://www.npmjs.com/package/fastify-plugin)
[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)
`fastify-plugin` is a plugin helper for [Fastify](https://github.com/fastify/fastify).
When you build plugins for Fastify and you want them to be accessible in the same context where you require them, you have two ways:
1. Use the `skip-override` hidden property
2. Use this module
__Note: the v4.x series of this module covers Fastify v4__
__Note: the v2.x & v3.x series of this module covers Fastify v3. For Fastify v2 support, refer to the v1.x series.__
## Install
```sh
npm i fastify-plugin
```
## Usage
`fastify-plugin` can do three things for you:
- Add the `skip-override` hidden property
- Check the bare-minimum version of Fastify
- Pass some custom metadata of the plugin to Fastify
Example using a callback:
```js
const fp = require('fastify-plugin')
module.exports = fp(function (fastify, opts, done) {
// your plugin code
done()
})
```
Example using an [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) function:
```js
const fp = require('fastify-plugin')
// A callback function param is not required for async functions
module.exports = fp(async function (fastify, opts) {
// Wait for an async function to fulfill promise before proceeding
await exampleAsyncFunction()
})
```
## Metadata
In addition, if you use this module when creating new plugins, you can declare the dependencies, the name, and the expected Fastify version that your plugin needs.
#### Fastify version
If you need to set a bare-minimum version of Fastify for your plugin, just add the [semver](https://semver.org/) range that you need:
```js
const fp = require('fastify-plugin')
module.exports = fp(function (fastify, opts, done) {
// your plugin code
done()
}, { fastify: '5.x' })
```
If you need to check the Fastify version only, you can pass just the version string.
You can check [here](https://github.com/npm/node-semver#ranges) how to define a `semver` range.
#### Name
Fastify uses this option to validate the dependency graph, allowing it to ensure that no name collisions occur and making it possible to perform [dependency checks](https://github.com/fastify/fastify-plugin#dependencies).
```js
const fp = require('fastify-plugin')
function plugin (fastify, opts, done) {
// your plugin code
done()
}
module.exports = fp(plugin, {
fastify: '5.x',
name: 'your-plugin-name'
})
```
#### Dependencies
You can also check if the `plugins` and `decorators` that your plugin intend to use are present in the dependency graph.
> *Note:* This is the point where registering `name` of the plugins become important, because you can reference `plugin` dependencies by their [name](https://github.com/fastify/fastify-plugin#name).
```js
const fp = require('fastify-plugin')
function plugin (fastify, opts, done) {
// your plugin code
done()
}
module.exports = fp(plugin, {
fastify: '5.x',
decorators: {
fastify: ['plugin1', 'plugin2'],
reply: ['compress']
},
dependencies: ['plugin1-name', 'plugin2-name']
})
```
#### Encapsulate
By default, `fastify-plugin` breaks the [encapsulation](https://github.com/fastify/fastify/blob/HEAD/docs/Reference/Encapsulation.md) but you can optionally keep the plugin encapsulated.
This allows you to set the plugin's name and validate its dependencies without making the plugin accessible.
```js
const fp = require('fastify-plugin')
function plugin (fastify, opts, done) {
// the decorator is not accessible outside this plugin
fastify.decorate('util', function() {})
done()
}
module.exports = fp(plugin, {
name: 'my-encapsulated-plugin',
fastify: '5.x',
decorators: {
fastify: ['plugin1', 'plugin2'],
reply: ['compress']
},
dependencies: ['plugin1-name', 'plugin2-name'],
encapsulate: true
})
```
#### Bundlers and Typescript
`fastify-plugin` adds a `.default` and `[name]` property to the passed in function.
The type definition would have to be updated to leverage this.
## Known Issue: TypeScript Contextual Inference
[Documentation Reference](https://www.typescriptlang.org/docs/handbook/functions.html#inferring-the-types)
It is common for developers to inline their plugin with fastify-plugin such as:
```js
fp((fastify, opts, done) => { done() })
fp(async (fastify, opts) => { return })
```
TypeScript can sometimes infer the types of the arguments for these functions. Plugins in Fastify are recommended to be typed using either `FastifyPluginCallback` or `FastifyPluginAsync`. These two definitions only differ in two ways:
1. The third argument `done` (the callback part)
2. The return type `FastifyPluginCallback` or `FastifyPluginAsync`
At this time, TypeScript inference is not smart enough to differentiate by definition argument length alone.
Thus, if you are a TypeScript developer please use on the following patterns instead:
```ts
// Callback
// Assign type directly
const pluginCallback: FastifyPluginCallback = (fastify, options, done) => { }
fp(pluginCallback)
// or define your own function declaration that satisfies the existing definitions
const pluginCallbackWithTypes = (fastify: FastifyInstance, options: FastifyPluginOptions, done: (error?: FastifyError) => void): void => { }
fp(pluginCallbackWithTypes)
// or inline
fp((fastify: FastifyInstance, options: FastifyPluginOptions, done: (error?: FastifyError) => void): void => { })
// Async
// Assign type directly
const pluginAsync: FastifyPluginAsync = async (fastify, options) => { }
fp(pluginAsync)
// or define your own function declaration that satisfies the existing definitions
const pluginAsyncWithTypes = async (fastify: FastifyInstance, options: FastifyPluginOptions): Promise<void> => { }
fp(pluginAsyncWithTypes)
// or inline
fp(async (fastify: FastifyInstance, options: FastifyPluginOptions): Promise<void> => { })
```
## Acknowledgments
This project is kindly sponsored by:
- [nearForm](https://nearform.com)
- [LetzDoIt](https://www.letzdoitapp.com/)
## License
Licensed under [MIT](./LICENSE).

View File

@@ -0,0 +1,6 @@
'use strict'
module.exports = require('neostandard')({
ignores: require('neostandard').resolveIgnoresFromGitignore(),
ts: true
})

View File

@@ -0,0 +1,25 @@
'use strict'
const fpStackTracePattern = /at\s(?:.*\.)?plugin\s.*\n\s*(.*)/
const fileNamePattern = /(\w*(\.\w*)*)\..*/
module.exports = function getPluginName (fn) {
if (fn.name.length > 0) return fn.name
const stackTraceLimit = Error.stackTraceLimit
Error.stackTraceLimit = 10
try {
throw new Error('anonymous function')
} catch (e) {
Error.stackTraceLimit = stackTraceLimit
return extractPluginName(e.stack)
}
}
function extractPluginName (stack) {
const m = stack.match(fpStackTracePattern)
// get last section of path and match for filename
return m ? m[1].split(/[/\\]/).slice(-1)[0].match(fileNamePattern)[1] : 'anonymous'
}
module.exports.extractPluginName = extractPluginName

View File

@@ -0,0 +1,10 @@
'use strict'
module.exports = function toCamelCase (name) {
if (name[0] === '@') {
name = name.slice(1).replace('/', '-')
}
return name.replace(/-(.)/g, function (match, g1) {
return g1.toUpperCase()
})
}

View File

@@ -0,0 +1,70 @@
{
"name": "fastify-plugin",
"version": "5.1.0",
"description": "Plugin helper for Fastify",
"main": "plugin.js",
"type": "commonjs",
"types": "types/plugin.d.ts",
"scripts": {
"lint": "eslint",
"lint:fix": "eslint --fix",
"test": "npm run test:unit && npm run test:typescript",
"test:unit": "c8 --100 node --test",
"test:coverage": "c8 node --test && c8 report --reporter=html",
"test:typescript": "tsd"
},
"repository": {
"type": "git",
"url": "git+https://github.com/fastify/fastify-plugin.git"
},
"keywords": [
"plugin",
"helper",
"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-plugin/issues"
},
"homepage": "https://github.com/fastify/fastify-plugin#readme",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"devDependencies": {
"@fastify/type-provider-typebox": "^5.1.0",
"@types/node": "^24.0.8",
"c8": "^10.1.2",
"eslint": "^9.17.0",
"fastify": "^5.0.0",
"neostandard": "^0.12.0",
"proxyquire": "^2.1.3",
"tsd": "^0.33.0"
}
}

View File

@@ -0,0 +1,67 @@
'use strict'
const getPluginName = require('./lib/getPluginName')
const toCamelCase = require('./lib/toCamelCase')
let count = 0
function plugin (fn, options = {}) {
let autoName = false
if (fn.default !== undefined) {
// Support for 'export default' behaviour in transpiled ECMAScript module
fn = fn.default
}
if (typeof fn !== 'function') {
throw new TypeError(
`fastify-plugin expects a function, instead got a '${typeof fn}'`
)
}
if (typeof options === 'string') {
options = {
fastify: options
}
}
if (
typeof options !== 'object' ||
Array.isArray(options) ||
options === null
) {
throw new TypeError('The options object should be an object')
}
if (options.fastify !== undefined && typeof options.fastify !== 'string') {
throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof options.fastify}'`)
}
if (!options.name) {
autoName = true
options.name = getPluginName(fn) + '-auto-' + count++
}
fn[Symbol.for('skip-override')] = options.encapsulate !== true
fn[Symbol.for('fastify.display-name')] = options.name
fn[Symbol.for('plugin-meta')] = options
// Faux modules support
if (!fn.default) {
fn.default = fn
}
// TypeScript support for named imports
// See https://github.com/fastify/fastify/issues/2404 for more details
// The type definitions would have to be update to match this.
const camelCase = toCamelCase(options.name)
if (!autoName && !fn[camelCase]) {
fn[camelCase] = fn
}
return fn
}
module.exports = plugin
module.exports.default = plugin
module.exports.fastifyPlugin = plugin

View File

@@ -0,0 +1,110 @@
'use strict'
const { test } = require('node:test')
const fp = require('../plugin')
test('webpack removes require.main.filename', t => {
const filename = require.main.filename
const info = console.info
t.after(() => {
require.main.filename = filename
console.info = info
})
require.main.filename = null
console.info = function (msg) {
t.assert.fail('logged: ' + msg)
}
fp((_fastify, _opts, next) => {
next()
}, {
fastify: '^5.0.0'
})
})
test('support faux modules', (t) => {
const plugin = fp((_fastify, _opts, next) => {
next()
})
t.assert.strictEqual(plugin.default, plugin)
})
test('support faux modules does not override existing default field in babel module', (t) => {
const module = {
default: (_fastify, _opts, next) => next()
}
module.default.default = 'Existing default field'
const plugin = fp(module)
t.assert.strictEqual(plugin.default, 'Existing default field')
})
test('support ts named imports', (t) => {
const plugin = fp((_fastify, _opts, next) => {
next()
}, {
name: 'hello'
})
t.assert.strictEqual(plugin.hello, plugin)
})
test('from kebab-case to camelCase', (t) => {
const plugin = fp((_fastify, _opts, next) => {
next()
}, {
name: 'hello-world'
})
t.assert.strictEqual(plugin.helloWorld, plugin)
})
test('from @-prefixed named imports', (t) => {
const plugin = fp((_fastify, _opts, next) => {
next()
}, {
name: '@hello/world'
})
t.assert.strictEqual(plugin.helloWorld, plugin)
})
test('from @-prefixed named kebab-case to camelCase', (t) => {
const plugin = fp((_fastify, _opts, next) => {
next()
}, {
name: '@hello/my-world'
})
t.assert.strictEqual(plugin.helloMyWorld, plugin)
})
test('from kebab-case to camelCase multiple words', (t) => {
const plugin = fp((_fastify, _opts, next) => {
next()
}, {
name: 'hello-long-world'
})
t.assert.strictEqual(plugin.helloLongWorld, plugin)
})
test('from kebab-case to camelCase multiple words does not override', (t) => {
const fn = (_fastify, _opts, next) => {
next()
}
const foobar = {}
fn.helloLongWorld = foobar
const plugin = fp(fn, {
name: 'hello-long-world'
})
t.assert.strictEqual(plugin.helloLongWorld, foobar)
})

View File

@@ -0,0 +1,67 @@
'use strict'
const { test } = require('node:test')
const fp = require('../plugin')
test('checkVersion having require.main.filename', (t) => {
const info = console.info
t.assert.ok(require.main.filename)
t.after(() => {
console.info = info
})
console.info = function (msg) {
t.assert.fail('logged: ' + msg)
}
fp((_fastify, _opts, next) => {
next()
}, {
fastify: '^5.0.0'
})
})
test('checkVersion having no require.main.filename but process.argv[1]', (t) => {
const filename = require.main.filename
const info = console.info
t.after(() => {
require.main.filename = filename
console.info = info
})
require.main.filename = null
console.info = function (msg) {
t.assert.fail('logged: ' + msg)
}
fp((_fastify, _opts, next) => {
next()
}, {
fastify: '^5.0.0'
})
})
test('checkVersion having no require.main.filename and no process.argv[1]', (t) => {
const filename = require.main.filename
const argv = process.argv
const info = console.info
t.after(() => {
require.main.filename = filename
process.argv = argv
console.info = info
})
require.main.filename = null
process.argv[1] = null
console.info = function (msg) {
t.assert.fail('logged: ' + msg)
}
fp((_fastify, _opts, next) => {
next()
}, {
fastify: '^5.0.0'
})
})

View File

@@ -0,0 +1,14 @@
'use strict'
const { test } = require('node:test')
const fp = require('../plugin')
test('anonymous function should be named composite.test0', (t) => {
t.plan(2)
const fn = fp((_fastify, _opts, next) => {
next()
})
t.assert.strictEqual(fn[Symbol.for('plugin-meta')].name, 'composite.test-auto-0')
t.assert.strictEqual(fn[Symbol.for('fastify.display-name')], 'composite.test-auto-0')
})

View File

@@ -0,0 +1,11 @@
import { test } from 'node:test'
import fp from '../../plugin.js'
test('esm base support', (t) => {
fp((_fastify, _opts, next) => {
next()
}, {
fastify: '^5.0.0'
})
t.assert.ok(true, 'fp function called without throwing an error')
})

View File

@@ -0,0 +1,11 @@
'use strict'
// Node v8 throw a `SyntaxError: Unexpected token import`
// even if this branch is never touch in the code,
// by using `eval` we can avoid this issue.
// eslint-disable-next-line
new Function('module', 'return import(module)')('./esm.mjs').catch((err) => {
process.nextTick(() => {
throw err
})
})

View File

@@ -0,0 +1,49 @@
'use strict'
const { test } = require('node:test')
const extractPluginName = require('../lib/getPluginName').extractPluginName
const winStack = `Error: anonymous function
at checkName (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\index.js:43:11)
at plugin (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\index.js:24:20)
at Test.test (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\test\\hello.test.js:9:14)
at bound (domain.js:396:14)
at Test.runBound (domain.js:409:12)
at ret (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\tap\\lib\\test.js:278:21)
at Test.main (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\tap\\lib\\test.js:282:7)
at writeSubComment (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\tap\\lib\\test.js:371:13)
at TAP.writeSubComment (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\tap\\lib\\test.js:403:5)
at Test.runBeforeEach (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\tap\\lib\\test.js:370:14)
at loop (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\function-loop\\index.js:35:15)
at TAP.runBeforeEach (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\tap\\lib\\test.js:683:7)
at TAP.processSubtest (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\tap\\lib\\test.js:369:12)
at TAP.process (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\tap\\lib\\test.js:306:14)
at TAP.sub (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\tap\\lib\\test.js:185:10)
at TAP.test (C:\\Users\\leonardo.davinci\\Desktop\\fastify-plugin\\node_modules\\tap\\lib\\test.js:209:17)`
const nixStack = `Error: anonymous function
at checkName (/home/leonardo/desktop/fastify-plugin/index.js:43:11)
at plugin (/home/leonardo/desktop/fastify-plugin/index.js:24:20)
at Test.test (/home/leonardo/desktop/fastify-plugin/test/this.is.a.test.js:9:14)
at bound (domain.js:396:14)
at Test.runBound (domain.js:409:12)
at ret (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:278:21)
at Test.main (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:282:7)
at writeSubComment (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:371:13)
at TAP.writeSubComment (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:403:5)
at Test.runBeforeEach (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:370:14)
at loop (/home/leonardo/desktop/fastify-plugin/node_modules/function-loop/index.js:35:15)
at TAP.runBeforeEach (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:683:7)
at TAP.processSubtest (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:369:12)
at TAP.process (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:306:14)
at TAP.sub (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:185:10)
at TAP.test (/home/leonardo/desktop/fastify-plugin/node_modules/tap/lib/test.js:209:17)`
const anonymousStack = 'Unable to parse this'
test('extractPluginName tests', (t) => {
t.plan(3)
t.assert.strictEqual(extractPluginName(winStack), 'hello.test')
t.assert.strictEqual(extractPluginName(nixStack), 'this.is.a.test')
t.assert.strictEqual(extractPluginName(anonymousStack), 'anonymous')
})

View File

@@ -0,0 +1,15 @@
'use strict'
const { test } = require('node:test')
const fp = require('../plugin')
test('anonymous function should be named mu1tip1e.composite.test', (t) => {
t.plan(2)
const fn = fp((_fastify, _opts, next) => {
next()
})
t.assert.strictEqual(fn[Symbol.for('plugin-meta')].name, 'mu1tip1e.composite.test-auto-0')
t.assert.strictEqual(fn[Symbol.for('fastify.display-name')], 'mu1tip1e.composite.test-auto-0')
})

View File

@@ -0,0 +1,396 @@
'use strict'
const { test } = require('node:test')
const proxyquire = require('proxyquire')
const fp = require('../plugin')
const Fastify = require('fastify')
const pkg = require('../package.json')
test('fastify-plugin is a function', (t) => {
t.plan(1)
t.assert.ok(typeof fp === 'function')
})
test('should return the function with the skip-override Symbol', (t) => {
t.plan(1)
function plugin (_fastify, _opts, next) {
next()
}
fp(plugin)
t.assert.ok(plugin[Symbol.for('skip-override')])
})
test('should support "default" function from babel module', (t) => {
t.plan(1)
const plugin = {
default: () => { }
}
try {
fp(plugin)
t.assert.ok(true)
} catch (e) {
t.assert.strictEqual(e.message, 'fastify-plugin expects a function, instead got a \'object\'')
}
})
test('should throw if the plugin is not a function', (t) => {
t.plan(1)
try {
fp('plugin')
t.assert.fail()
} catch (e) {
t.assert.strictEqual(e.message, 'fastify-plugin expects a function, instead got a \'string\'')
}
})
test('should check the fastify version', (t) => {
t.plan(1)
function plugin (_fastify, _opts, next) {
next()
}
try {
fp(plugin, { fastify: '>=0.10.0' })
t.assert.ok(true)
} catch {
t.assert.fail()
}
})
test('should check the fastify version', (t) => {
t.plan(1)
function plugin (_fastify, _opts, next) {
next()
}
try {
fp(plugin, '>=0.10.0')
t.assert.ok(true)
} catch {
t.assert.fail()
}
})
test('the options object should be an object', (t) => {
t.plan(2)
try {
fp(() => { }, null)
t.assert.fail()
} catch (e) {
t.assert.strictEqual(e.message, 'The options object should be an object')
}
try {
fp(() => { }, [])
t.assert.fail()
} catch (e) {
t.assert.strictEqual(e.message, 'The options object should be an object')
}
})
test('should throw if the version number is not a string', (t) => {
t.plan(1)
try {
fp(() => { }, { fastify: 12 })
t.assert.fail()
} catch (e) {
t.assert.strictEqual(e.message, 'fastify-plugin expects a version string, instead got \'number\'')
}
})
test('Should accept an option object', (t) => {
t.plan(2)
const opts = { hello: 'world' }
function plugin (_fastify, _opts, next) {
next()
}
fp(plugin, opts)
t.assert.ok(plugin[Symbol.for('skip-override')], 'skip-override symbol should be present')
t.assert.deepStrictEqual(plugin[Symbol.for('plugin-meta')], opts, 'plugin-meta should match opts')
})
test('Should accept an option object and checks the version', (t) => {
t.plan(2)
const opts = { hello: 'world', fastify: '>=0.10.0' }
function plugin (_fastify, _opts, next) {
next()
}
fp(plugin, opts)
t.assert.ok(plugin[Symbol.for('skip-override')])
t.assert.deepStrictEqual(plugin[Symbol.for('plugin-meta')], opts)
})
test('should set anonymous function name to file it was called from with a counter', (t) => {
const fp = proxyquire('../plugin.js', { stubs: {} })
const fn = fp((_fastify, _opts, next) => {
next()
})
t.assert.strictEqual(fn[Symbol.for('plugin-meta')].name, 'test-auto-0')
t.assert.strictEqual(fn[Symbol.for('fastify.display-name')], 'test-auto-0')
const fn2 = fp((_fastify, _opts, next) => {
next()
})
t.assert.strictEqual(fn2[Symbol.for('plugin-meta')].name, 'test-auto-1')
t.assert.strictEqual(fn2[Symbol.for('fastify.display-name')], 'test-auto-1')
})
test('should set function name if Error.stackTraceLimit is set to 0', (t) => {
const stackTraceLimit = Error.stackTraceLimit = 0
const fp = proxyquire('../plugin.js', { stubs: {} })
const fn = fp((_fastify, _opts, next) => {
next()
})
t.assert.strictEqual(fn[Symbol.for('plugin-meta')].name, 'test-auto-0')
t.assert.strictEqual(fn[Symbol.for('fastify.display-name')], 'test-auto-0')
const fn2 = fp((_fastify, _opts, next) => {
next()
})
t.assert.strictEqual(fn2[Symbol.for('plugin-meta')].name, 'test-auto-1')
t.assert.strictEqual(fn2[Symbol.for('fastify.display-name')], 'test-auto-1')
Error.stackTraceLimit = stackTraceLimit
})
test('should set display-name to meta name', (t) => {
t.plan(2)
const functionName = 'superDuperSpecialFunction'
const fn = fp((_fastify, _opts, next) => next(), {
name: functionName
})
t.assert.strictEqual(fn[Symbol.for('plugin-meta')].name, functionName)
t.assert.strictEqual(fn[Symbol.for('fastify.display-name')], functionName)
})
test('should preserve fastify version in meta', (t) => {
t.plan(1)
const opts = { hello: 'world', fastify: '>=0.10.0' }
const fn = fp((_fastify, _opts, next) => next(), opts)
t.assert.strictEqual(fn[Symbol.for('plugin-meta')].fastify, '>=0.10.0')
})
test('should check fastify dependency graph - plugin', async (t) => {
t.plan(1)
const fastify = Fastify()
fastify.register(fp((_fastify, _opts, next) => next(), {
fastify: '5.x',
name: 'plugin1-name'
}))
fastify.register(fp((_fastify, _opts, next) => next(), {
fastify: '5.x',
name: 'test',
dependencies: ['plugin1-name', 'plugin2-name']
}))
await t.assert.rejects(fastify.ready(), { message: "The dependency 'plugin2-name' of plugin 'test' is not registered" })
})
test('should check fastify dependency graph - decorate', async (t) => {
t.plan(1)
const fastify = Fastify()
fastify.decorate('plugin1', fp((_fastify, _opts, next) => next(), {
fastify: '5.x',
name: 'plugin1-name'
}))
fastify.register(fp((_fastify, _opts, next) => next(), {
fastify: '5.x',
name: 'test',
decorators: { fastify: ['plugin1', 'plugin2'] }
}))
await t.assert.rejects(fastify.ready(), { message: "The decorator 'plugin2' required by 'test' is not present in Fastify" })
})
test('should check fastify dependency graph - decorateReply', async (t) => {
t.plan(1)
const fastify = Fastify()
fastify.decorateReply('plugin1', fp((_fastify, _opts, next) => next(), {
fastify: '5.x',
name: 'plugin1-name'
}))
fastify.register(fp((_fastify, _opts, next) => next(), {
fastify: '5.x',
name: 'test',
decorators: { reply: ['plugin1', 'plugin2'] }
}))
await t.assert.rejects(fastify.ready(), { message: "The decorator 'plugin2' required by 'test' is not present in Reply" })
})
test('should accept an option to encapsulate', async (t) => {
t.plan(3)
const fastify = Fastify()
fastify.register(fp((fastify, _opts, next) => {
fastify.decorate('accessible', true)
next()
}, {
name: 'accessible-plugin'
}))
fastify.register(fp((fastify, _opts, next) => {
fastify.decorate('alsoAccessible', true)
next()
}, {
name: 'accessible-plugin2',
encapsulate: false
}))
fastify.register(fp((fastify, _opts, next) => {
fastify.decorate('encapsulated', true)
next()
}, {
name: 'encapsulated-plugin',
encapsulate: true
}))
await fastify.ready()
t.assert.ok(fastify.hasDecorator('accessible'))
t.assert.ok(fastify.hasDecorator('alsoAccessible'))
t.assert.ok(!fastify.hasDecorator('encapsulated'))
})
test('should check dependencies when encapsulated', async (t) => {
t.plan(1)
const fastify = Fastify()
fastify.register(fp((_fastify, _opts, next) => next(), {
name: 'test',
dependencies: ['missing-dependency-name'],
encapsulate: true
}))
await t.assert.rejects(fastify.ready(), { message: "The dependency 'missing-dependency-name' of plugin 'test' is not registered" })
})
test(
'should check version when encapsulated',
{ skip: /\d-.+/.test(pkg.devDependencies.fastify) },
async (t) => {
t.plan(1)
const fastify = Fastify()
fastify.register(fp((_fastify, _opts, next) => next(), {
name: 'test',
fastify: '<=2.10.0',
encapsulate: true
}))
await t.assert.rejects(fastify.ready(), { message: /fastify-plugin: test - expected '<=2.10.0' fastify version, '\d.\d+.\d+' is installed/ })
}
)
test('should check decorators when encapsulated', async (t) => {
t.plan(1)
const fastify = Fastify()
fastify.decorate('plugin1', 'foo')
fastify.register(fp((_fastify, _opts, next) => next(), {
fastify: '5.x',
name: 'test',
encapsulate: true,
decorators: { fastify: ['plugin1', 'plugin2'] }
}))
await t.assert.rejects(fastify.ready(), { message: "The decorator 'plugin2' required by 'test' is not present in Fastify" })
})
test('plugin name when encapsulated', async (t) => {
t.plan(6)
const fastify = Fastify()
fastify.register(function plugin (_instance, _opts, next) {
next()
})
fastify.register(fp(getFn('hello'), {
fastify: '5.x',
name: 'hello',
encapsulate: true
}))
fastify.register(function plugin (fastify, _opts, next) {
fastify.register(fp(getFn('deep'), {
fastify: '5.x',
name: 'deep',
encapsulate: true
}))
fastify.register(fp(function genericPlugin (fastify, _opts, next) {
t.assert.strictEqual(fastify.pluginName, 'deep-deep', 'should be deep-deep')
fastify.register(fp(getFn('deep-deep-deep'), {
fastify: '5.x',
name: 'deep-deep-deep',
encapsulate: true
}))
fastify.register(fp(getFn('deep-deep -> not-encapsulated-2'), {
fastify: '5.x',
name: 'not-encapsulated-2'
}))
next()
}, {
fastify: '5.x',
name: 'deep-deep',
encapsulate: true
}))
fastify.register(fp(getFn('plugin -> not-encapsulated'), {
fastify: '5.x',
name: 'not-encapsulated'
}))
next()
})
await fastify.ready()
function getFn (expectedName) {
return function genericPlugin (fastify, _opts, next) {
t.assert.strictEqual(fastify.pluginName, expectedName, `should be ${expectedName}`)
next()
}
}
})

View File

@@ -0,0 +1,24 @@
'use strict'
const { test } = require('node:test')
const toCamelCase = require('../lib/toCamelCase')
test('from kebab-case to camelCase', (t) => {
t.plan(1)
t.assert.strictEqual(toCamelCase('hello-world'), 'helloWorld')
})
test('from @-prefixed named imports', (t) => {
t.plan(1)
t.assert.strictEqual(toCamelCase('@hello/world'), 'helloWorld')
})
test('from @-prefixed named kebab-case to camelCase', (t) => {
t.plan(1)
t.assert.strictEqual(toCamelCase('@hello/my-world'), 'helloMyWorld')
})
test('from kebab-case to camelCase multiple words', (t) => {
t.plan(1)
t.assert.strictEqual(toCamelCase('hello-long-world'), 'helloLongWorld')
})

View File

@@ -0,0 +1,19 @@
import { FastifyPluginAsync } from 'fastify'
type FastifyExampleAsync = FastifyPluginAsync<fastifyExampleAsync.FastifyExampleAsyncOptions>
declare namespace fastifyExampleAsync {
export interface FastifyExampleAsyncOptions {
foo?: 'bar'
}
export interface FastifyExampleAsyncPluginOptions extends FastifyExampleAsyncOptions {
}
export const fastifyExampleAsync: FastifyExampleAsync
export { fastifyExampleAsync as default }
}
declare function fastifyExampleAsync (...params: Parameters<FastifyExampleAsync>): ReturnType<FastifyExampleAsync>
export default fastifyExampleAsync

View File

@@ -0,0 +1,19 @@
import { FastifyPluginCallback } from 'fastify'
type FastifyExampleCallback = FastifyPluginCallback<fastifyExampleCallback.FastifyExampleCallbackOptions>
declare namespace fastifyExampleCallback {
export interface FastifyExampleCallbackOptions {
foo?: 'bar'
}
export interface FastifyExampleCallbackPluginOptions extends FastifyExampleCallbackOptions {
}
export const fastifyExampleCallback: FastifyExampleCallback
export { fastifyExampleCallback as default }
}
declare function fastifyExampleCallback (...params: Parameters<FastifyExampleCallback>): ReturnType<FastifyExampleCallback>
export default fastifyExampleCallback

View File

@@ -0,0 +1,61 @@
/// <reference types="fastify" />
import {
FastifyPluginCallback,
FastifyPluginAsync,
FastifyPluginOptions,
RawServerBase,
RawServerDefault,
FastifyTypeProvider,
FastifyTypeProviderDefault,
FastifyBaseLogger,
} from 'fastify'
type FastifyPlugin = typeof fastifyPlugin
declare namespace fastifyPlugin {
export interface PluginMetadata {
/** Bare-minimum version of Fastify for your plugin, just add the semver range that you need. */
fastify?: string,
name?: string,
/** Decorator dependencies for this plugin */
decorators?: {
fastify?: (string | symbol)[],
reply?: (string | symbol)[],
request?: (string | symbol)[]
},
/** The plugin dependencies */
dependencies?: string[],
encapsulate?: boolean
}
// Exporting PluginOptions for backward compatibility after renaming it to PluginMetadata
/**
* @deprecated Use PluginMetadata instead
*/
export interface PluginOptions extends PluginMetadata {}
export const fastifyPlugin: FastifyPlugin
export { fastifyPlugin as default }
}
/**
* This function does three things for you:
* 1. Add the `skip-override` hidden property
* 2. Check bare-minimum version of Fastify
* 3. Pass some custom metadata of the plugin to Fastify
* @param fn Fastify plugin function
* @param options Optional plugin options
*/
declare function fastifyPlugin<
Options extends FastifyPluginOptions = Record<never, never>,
RawServer extends RawServerBase = RawServerDefault,
TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
Logger extends FastifyBaseLogger = FastifyBaseLogger,
Fn extends FastifyPluginCallback<Options, RawServer, TypeProvider, Logger> | FastifyPluginAsync<Options, RawServer, TypeProvider, Logger> = FastifyPluginCallback<Options, RawServer, TypeProvider, Logger>
> (
fn: Fn extends unknown ? Fn extends (...args: any) => Promise<any> ? FastifyPluginAsync<Options, RawServer, TypeProvider, Logger> : FastifyPluginCallback<Options, RawServer, TypeProvider, Logger> : Fn,
options?: fastifyPlugin.PluginMetadata | string
): Fn
export = fastifyPlugin

View File

@@ -0,0 +1,166 @@
import fastifyPlugin from '..'
import fastify, { FastifyPluginCallback, FastifyPluginAsync, FastifyError, FastifyInstance, FastifyPluginOptions, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger } from 'fastify'
import { expectAssignable, expectError, expectNotType, expectType } from 'tsd'
import { Server } from 'node:https'
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
import fastifyExampleCallback from './example-callback.test-d'
import fastifyExampleAsync from './example-async.test-d'
interface Options {
foo: string
}
const testSymbol = Symbol('foobar')
// Callback
const pluginCallback: FastifyPluginCallback = (_fastify, _options, _next) => { }
expectType<FastifyPluginCallback>(fastifyPlugin(pluginCallback))
const pluginCallbackWithTypes = (_fastify: FastifyInstance, _options: FastifyPluginOptions, _next: (error?: FastifyError) => void): void => { }
expectAssignable<FastifyPluginCallback>(fastifyPlugin(pluginCallbackWithTypes))
expectNotType<any>(fastifyPlugin(pluginCallbackWithTypes))
expectAssignable<FastifyPluginCallback>(fastifyPlugin((_fastify: FastifyInstance, _options: FastifyPluginOptions, _next: (error?: FastifyError) => void): void => { }))
expectNotType<any>(fastifyPlugin((_fastify: FastifyInstance, _options: FastifyPluginOptions, _next: (error?: FastifyError) => void): void => { }))
expectType<FastifyPluginCallback>(fastifyPlugin(pluginCallback, ''))
expectType<FastifyPluginCallback>(fastifyPlugin(pluginCallback, {
fastify: '',
name: '',
decorators: {
fastify: ['', testSymbol],
reply: ['', testSymbol],
request: ['', testSymbol]
},
dependencies: [''],
encapsulate: true
}))
const pluginCallbackWithOptions: FastifyPluginCallback<Options> = (_fastify, options, _next) => {
expectType<string>(options.foo)
}
expectType<FastifyPluginCallback<Options>>(fastifyPlugin(pluginCallbackWithOptions))
const pluginCallbackWithServer: FastifyPluginCallback<Options, Server> = (fastify, _options, _next) => {
expectType<Server>(fastify.server)
}
expectType<FastifyPluginCallback<Options, Server>>(fastifyPlugin(pluginCallbackWithServer))
const pluginCallbackWithTypeProvider: FastifyPluginCallback<Options, Server, TypeBoxTypeProvider> = (_fastify, _options, _next) => { }
expectType<FastifyPluginCallback<Options, Server, TypeBoxTypeProvider>>(fastifyPlugin(pluginCallbackWithTypeProvider))
// Async
const pluginAsync: FastifyPluginAsync = async (_fastify, _options) => { }
expectType<FastifyPluginAsync>(fastifyPlugin(pluginAsync))
const pluginAsyncWithTypes = async (_fastify: FastifyInstance, _options: FastifyPluginOptions): Promise<void> => { }
expectType<FastifyPluginAsync<FastifyPluginOptions, RawServerDefault, FastifyTypeProviderDefault>>(fastifyPlugin(pluginAsyncWithTypes))
expectType<FastifyPluginAsync<FastifyPluginOptions, RawServerDefault, FastifyTypeProviderDefault>>(fastifyPlugin(async (_fastify: FastifyInstance, _options: FastifyPluginOptions): Promise<void> => { }))
expectType<FastifyPluginAsync>(fastifyPlugin(pluginAsync, ''))
expectType<FastifyPluginAsync>(fastifyPlugin(pluginAsync, {
fastify: '',
name: '',
decorators: {
fastify: ['', testSymbol],
reply: ['', testSymbol],
request: ['', testSymbol]
},
dependencies: [''],
encapsulate: true
}))
const pluginAsyncWithOptions: FastifyPluginAsync<Options> = async (_fastify, options) => {
expectType<string>(options.foo)
}
expectType<FastifyPluginAsync<Options>>(fastifyPlugin(pluginAsyncWithOptions))
const pluginAsyncWithServer: FastifyPluginAsync<Options, Server> = async (fastify, _options) => {
expectType<Server>(fastify.server)
}
expectType<FastifyPluginAsync<Options, Server>>(fastifyPlugin(pluginAsyncWithServer))
const pluginAsyncWithTypeProvider: FastifyPluginAsync<Options, Server, TypeBoxTypeProvider> = async (_fastify, _options) => { }
expectType<FastifyPluginAsync<Options, Server, TypeBoxTypeProvider>>(fastifyPlugin(pluginAsyncWithTypeProvider))
// Fastify register
const server = fastify()
server.register(fastifyPlugin(pluginCallback))
server.register(fastifyPlugin(pluginCallbackWithTypes), { foo: 'bar' })
server.register(fastifyPlugin(pluginCallbackWithOptions), { foo: 'bar' })
server.register(fastifyPlugin(pluginCallbackWithServer), { foo: 'bar' })
server.register(fastifyPlugin(pluginCallbackWithTypeProvider), { foo: 'bar' })
server.register(fastifyPlugin(pluginAsync))
server.register(fastifyPlugin(pluginAsyncWithTypes), { foo: 'bar' })
server.register(fastifyPlugin(pluginAsyncWithOptions), { foo: 'bar' })
server.register(fastifyPlugin(pluginAsyncWithServer), { foo: 'bar' })
server.register(fastifyPlugin(pluginAsyncWithTypeProvider), { foo: 'bar' })
// properly handling callback and async
fastifyPlugin(function (fastify, options, next) {
expectType<FastifyInstance>(fastify)
expectType<Record<never, never>>(options)
expectType<(err?: Error) => void>(next)
})
fastifyPlugin<Options>(function (fastify, options, next) {
expectType<FastifyInstance>(fastify)
expectType<Options>(options)
expectType<(err?: Error) => void>(next)
})
fastifyPlugin<Options>(async function (fastify, options) {
expectType<FastifyInstance>(fastify)
expectType<Options>(options)
})
expectAssignable<FastifyPluginAsync<Options, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger>>(fastifyPlugin(async function (_fastify: FastifyInstance, _options: Options) { }))
expectNotType<any>(fastifyPlugin(async function (_fastify: FastifyInstance, _options: Options) { }))
fastifyPlugin(async function (fastify, options: Options) {
expectType<FastifyInstance>(fastify)
expectType<Options>(options)
})
fastifyPlugin(async function (fastify, options) {
expectType<FastifyInstance>(fastify)
expectType<Record<never, never>>(options)
})
expectError(
fastifyPlugin(async function (fastify, options: Options, _next) {
expectType<FastifyInstance>(fastify)
expectType<Options>(options)
})
)
expectAssignable<FastifyPluginCallback<Options>>(fastifyPlugin(function (_fastify, _options, _next) { }))
expectNotType<any>(fastifyPlugin(function (_fastify, _options, _next) { }))
fastifyPlugin(function (fastify, options: Options, next) {
expectType<FastifyInstance>(fastify)
expectType<Options>(options)
expectType<(err?: Error) => void>(next)
})
expectError(
fastifyPlugin(function (fastify, options: Options, _next) {
expectType<FastifyInstance>(fastify)
expectType<Options>(options)
return Promise.resolve()
})
)
server.register(fastifyExampleCallback, { foo: 'bar' })
expectError(server.register(fastifyExampleCallback, { foo: 'baz' }))
server.register(fastifyExampleAsync, { foo: 'bar' })
expectError(server.register(fastifyExampleAsync, { foo: 'baz' }))

86
backend/node_modules/@fastify/jwt/package.json generated vendored Normal file
View File

@@ -0,0 +1,86 @@
{
"name": "@fastify/jwt",
"version": "9.1.0",
"description": "JWT utils for Fastify",
"main": "jwt.js",
"type": "commonjs",
"types": "types/jwt.d.ts",
"scripts": {
"lint": "eslint",
"lint:fix": "eslint --fix",
"test": "npm run lint && npm run test:unit && npm run test:typescript",
"test:typescript": "tsd",
"test:unit": "c8 --100 node --test",
"test:unit:report": "c8 -r html --100 node --test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/fastify/fastify-jwt.git"
},
"keywords": [
"jwt",
"json",
"token",
"jsonwebtoken",
"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",
"fast-jwt": "^5.0.0",
"fastify-plugin": "^5.0.0",
"steed": "^1.1.3"
},
"devDependencies": {
"@fastify/cookie": "^11.0.1",
"@fastify/pre-commit": "^2.1.0",
"@types/node": "^22.0.0",
"c8": "^10.1.3",
"eslint": "^9.17.0",
"fastify": "^5.0.0",
"neostandard": "^0.12.0",
"tsd": "^0.31.0"
},
"publishConfig": {
"access": "public"
},
"pre-commit": [
"lint",
"test"
]
}

88
backend/node_modules/@fastify/jwt/test/helper.js generated vendored Normal file
View File

@@ -0,0 +1,88 @@
'use strict'
const crypto = require('node:crypto')
function generateKeyPair () {
const options = {
modulusLength: 2048,
publicExponent: 0x10001,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
}
return crypto.generateKeyPairSync('rsa', options)
}
function generateKeyPairProtected (passphrase) {
const options = {
modulusLength: 2048,
publicExponent: 0x10001,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase
}
}
return crypto.generateKeyPairSync('rsa', options)
}
function withResolvers () {
let promiseResolve, promiseReject
const promise = new Promise((resolve, reject) => {
promiseResolve = resolve
promiseReject = reject
})
return { promise, resolve: promiseResolve, reject: promiseReject }
}
function generateKeyPairECDSA () {
const options = {
modulusLength: 2048,
namedCurve: 'prime256v1',
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
}
return crypto.generateKeyPairSync('ec', options)
}
function generateKeyPairECDSAProtected (passphrase) {
const options = {
modulusLength: 2048,
namedCurve: 'prime256v1',
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase
}
}
return crypto.generateKeyPairSync('ec', options)
}
module.exports = {
generateKeyPair,
generateKeyPairProtected,
generateKeyPairECDSA,
generateKeyPairECDSAProtected,
withResolvers
}

View File

@@ -0,0 +1,134 @@
'use strict'
const { test } = require('node:test')
const Fastify = require('fastify')
const jwt = require('../jwt')
const { createSigner } = require('fast-jwt')
test('Async key provider should be resolved internally', async function (t) {
const fastify = Fastify()
fastify.register(jwt, {
secret: {
private: 'supersecret',
public: async () => Promise.resolve('supersecret')
},
verify: {
extractToken: (request) => request.headers.jwt,
key: () => Promise.resolve('supersecret')
}
})
fastify.get('/', async function (request, reply) {
const token = await reply.jwtSign({ user: 'test' })
request.headers.jwt = token
await request.jwtVerify()
return reply.send(request.user)
})
const response = await fastify.inject({
method: 'get',
url: '/',
headers: {
jwt: 'supersecret'
}
})
t.assert.ok(response)
t.assert.strictEqual(response.json().user, 'test')
})
test('Async key provider errors should be resolved internally', async function (t) {
const fastify = Fastify()
fastify.register(jwt, {
secret: {
public: async () => Promise.resolve('key used per request, false not allowed')
},
verify: {
extractToken: (request) => request.headers.jwt,
key: () => Promise.resolve('key not used')
}
})
fastify.get('/', async function (request, reply) {
const signSync = createSigner({ key: 'invalid signature error' })
request.headers.jwt = signSync({ sub: '1234567890', name: 'John Doe', iat: 1516239022 })
// call to local verifier without cache
await request.jwtVerify()
return reply.send(typeof request.user.then)
})
const response = await fastify.inject({
method: 'get',
url: '/'
})
t.assert.strictEqual(response.statusCode, 401)
})
test('Async key provider should be resolved internally with cache', async function (t) {
const fastify = Fastify()
fastify.register(jwt, {
secret: {
private: 'this secret reused from cache',
public: async () => false
},
verify: {
extractToken: (request) => request.headers.jwt,
key: () => Promise.resolve('this secret reused from cache')
}
})
fastify.get('/', async function (request, reply) {
const signSync = createSigner({ key: 'this secret reused from cache' })
request.headers.jwt = signSync({ sub: '1234567890', name: 'John Doe', iat: 1516239022 })
await new Promise((resolve, reject) => request.jwtVerify((err, payload) => {
if (err) {
reject(err)
return
}
resolve(payload)
}))
await new Promise((resolve, reject) => request.jwtVerify((err, payload) => {
if (err) {
reject(err)
return
}
resolve(payload)
}))
return reply.send(request.user)
})
const response = await fastify.inject({
method: 'get',
url: '/'
})
t.assert.strictEqual(response.statusCode, 200)
t.assert.strictEqual(response.json().name, 'John Doe')
})
test('Async key provider errors should be resolved internally with cache', async function (t) {
const fastify = Fastify()
fastify.register(jwt, {
secret: {
public: async () => false
},
verify: {
extractToken: (request) => request.headers.jwt,
key: () => Promise.resolve('this secret reused from cache')
}
})
fastify.get('/', async function (request, reply) {
const signSync = createSigner({ key: 'invalid signature error' })
request.headers.jwt = signSync({ sub: '1234567890', name: 'John Doe', iat: 1516239022 })
// request.headers.jwt =
// 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
// call to plugin root level verifier
await new Promise((resolve, reject) => request.jwtVerify((err, payload) => {
if (err) {
reject(err)
return
}
resolve(payload)
}))
return reply.send(typeof request.user.then)
})
const response = await fastify.inject({
method: 'get',
url: '/'
})
t.assert.strictEqual(response.statusCode, 401)
})

3004
backend/node_modules/@fastify/jwt/test/jwt.test.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,132 @@
'use strict'
const { test } = require('node:test')
const Fastify = require('fastify')
const jwt = require('../jwt')
test('Unable to add the namespace twice', async function (t) {
t.plan(1)
const fastify = Fastify()
fastify.register(jwt, { secret: 'test', namespace: 'security', jwtVerify: 'securityVerify', jwtSign: 'securitySign' })
await t.assert.rejects(() => fastify.register(jwt, { secret: 'hello', namespace: 'security', jwtVerify: 'secureVerify', jwtSign: 'secureSign' })
.ready(), new Error('JWT namespace already used "security"'))
})
test('multiple namespace', async function (t) {
const fastify = Fastify()
fastify.register(jwt, { namespace: 'aaa', secret: 'test', verify: { extractToken: (request) => request.headers.customauthheader } })
fastify.register(jwt, { namespace: 'bbb', secret: 'sea', verify: { extractToken: (request) => request.headers.customauthheader }, jwtVerify: 'verifyCustom', jwtSign: 'signCustom', jwtDecode: 'decodeCustom' })
fastify.post('/sign/:namespace', async function (request, reply) {
switch (request.params.namespace) {
case 'aaa':
return reply.aaaJwtSign(request.body)
case 'bbb':
return reply.signCustom(request.body)
default:
reply.code(501).send({ message: `Namespace ${request.params.namespace} is not implemented correctly` })
}
})
fastify.get('/verify/:namespace', async function (request, reply) {
switch (request.params.namespace) {
case 'aaa':
return request.aaaJwtVerify()
case 'bbb':
return request.verifyCustom()
default:
reply.code(501).send({ message: `Namespace ${request.params.namespace} is not implemented correctly` })
}
})
fastify.get('/decode/:namespace', async function (request, reply) {
switch (request.params.namespace) {
case 'aaa':
return request.aaaJwtDecode()
case 'bbb':
return request.decodeCustom()
default:
reply.code(501).send({ message: `Namespace ${request.params.namespace} is not implemented correctly` })
}
})
await fastify.ready()
let signResponse
let verifyResponse
signResponse = await fastify.inject({
method: 'post',
url: '/sign/aaa',
payload: { foo: 'bar' }
})
const tokenA = signResponse.payload
t.assert.ok(tokenA)
verifyResponse = await fastify.inject({
method: 'get',
url: '/verify/aaa',
headers: {
customauthheader: tokenA
}
})
t.assert.strictEqual(verifyResponse.statusCode, 200)
t.assert.strictEqual(verifyResponse.json().foo, 'bar')
verifyResponse = await fastify.inject({
method: 'get',
url: '/verify/bbb',
headers: {
customauthheader: tokenA
}
})
t.assert.strictEqual(verifyResponse.statusCode, 401)
signResponse = await fastify.inject({
method: 'post',
url: '/sign/bbb',
payload: { foo: 'sky' }
})
const tokenB = signResponse.payload
t.assert.ok(tokenB)
verifyResponse = await fastify.inject({
method: 'get',
url: '/verify/bbb',
headers: {
customauthheader: tokenB
}
})
t.assert.strictEqual(verifyResponse.statusCode, 200)
t.assert.strictEqual(verifyResponse.json().foo, 'sky')
verifyResponse = await fastify.inject({
method: 'get',
url: '/verify/aaa',
headers: {
customauthheader: tokenB
}
})
t.assert.strictEqual(verifyResponse.statusCode, 401)
const decodeResponseAAA = await fastify.inject({
method: 'get',
url: '/decode/aaa',
headers: {
customauthheader: tokenA
}
})
t.assert.strictEqual(decodeResponseAAA.statusCode, 200)
t.assert.strictEqual(decodeResponseAAA.json().foo, 'bar')
const verifyResponseBBB = await fastify.inject({
method: 'get',
url: '/decode/bbb',
headers: {
customauthheader: tokenB
}
})
t.assert.strictEqual(verifyResponseBBB.statusCode, 200)
t.assert.strictEqual(verifyResponseBBB.json().foo, 'sky')
})

147
backend/node_modules/@fastify/jwt/test/options.test.js generated vendored Normal file
View File

@@ -0,0 +1,147 @@
'use strict'
const { test } = require('node:test')
const Fastify = require('fastify')
const jwt = require('../jwt')
const { AssertionError } = require('node:assert')
test('Options validation', async function (t) {
t.plan(3)
await t.test('Options are required', async function (t) {
t.plan(1)
const fastify = Fastify()
await t.assert.rejects(() => fastify.register(jwt).ready(), new AssertionError({ expected: true, operator: '==', message: 'missing secret' }))
})
await t.test('Request method aliases', async function (t) {
t.plan(6)
await t.test('jwtDecode fail', async function (t) {
t.plan(1)
const fastify = Fastify()
await t.assert.rejects(() => fastify.register(jwt, {
secret: 'sec',
jwtDecode: true
}).ready(), new AssertionError({ expected: true, operator: '==', message: 'Invalid options.jwtDecode', actual: false }))
})
await t.test('jwtDecode success', async function (t) {
const fastify = Fastify()
await fastify.register(jwt, {
secret: 'sec',
jwtDecode: 'hello'
})
})
await t.test('jwtVerify fail', async function (t) {
t.plan(1)
const fastify = Fastify()
await t.assert.rejects(() => fastify.register(jwt, {
secret: 'sec',
jwtVerify: 123
}).ready(), new AssertionError({ expected: true, operator: '==', message: 'Invalid options.jwtVerify', actual: false }))
})
await t.test('jwtVerify success', async function (t) {
const fastify = Fastify()
await fastify.register(jwt, {
secret: 'sec',
jwtVerify: String('hello')
}).ready()
})
await t.test('jwtSign fail', async function (t) {
t.plan(1)
const fastify = Fastify()
await t.assert.rejects(() => fastify.register(jwt, {
secret: 'sec',
jwtSign: {}
}).ready(), new AssertionError({ expected: true, operator: '==', message: 'Invalid options.jwtSign', actual: false }))
})
await t.test('jwtSign success', async function (t) {
const fastify = Fastify()
await fastify.register(jwt, {
secret: 'sec',
jwtSign: ''
}).ready()
})
})
await t.test('Secret formats', async function (t) {
t.plan(2)
await t.test('RS/ES algorithm in sign options and secret as string', async function (t) {
t.plan(2)
await t.test('RS algorithm (Must return an error)', async function (t) {
t.plan(1)
const fastify = Fastify()
await t.assert.rejects(() => fastify.register(jwt, {
secret: 'test',
sign: {
algorithm: 'RS256',
aud: 'Some audience',
iss: 'Some issuer',
sub: 'Some subject'
}
}).ready(), new Error('RSA Signatures set as Algorithm in the options require a private and public key to be set as the secret'))
})
await t.test('ES algorithm (Must return an error)', async function (t) {
t.plan(1)
const fastify = Fastify()
await t.assert.rejects(() => fastify.register(jwt, {
secret: 'test',
sign: {
algorithm: 'ES256',
aud: 'Some audience',
iss: 'Some issuer',
sub: 'Some subject'
}
}).ready(), new Error('ECDSA Signatures set as Algorithm in the options require a private and public key to be set as the secret'))
})
})
await t.test('RS/ES algorithm in sign options and secret as a Buffer', async function (t) {
t.plan(2)
await t.test('RS algorithm (Must return an error)', async function (t) {
t.plan(1)
const fastify = Fastify()
await t.assert.rejects(() => fastify.register(jwt, {
secret: Buffer.from('some secret', 'base64'),
sign: {
algorithm: 'RS256',
aud: 'Some audience',
iss: 'Some issuer',
sub: 'Some subject'
}
}).ready(), new Error('RSA Signatures set as Algorithm in the options require a private and public key to be set as the secret'))
})
await t.test('ES algorithm (Must return an error)', async function (t) {
t.plan(1)
const fastify = Fastify()
await t.assert.rejects(() => fastify.register(jwt, {
secret: Buffer.from('some secret', 'base64'),
sign: {
algorithm: 'ES256',
aud: 'Some audience',
iss: 'Some issuer',
sub: 'Some subject'
}
}).ready(), new Error('ECDSA Signatures set as Algorithm in the options require a private and public key to be set as the secret'))
})
})
})
})

216
backend/node_modules/@fastify/jwt/types/jwt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,216 @@
import {
DecoderOptions,
JwtHeader,
KeyFetcher,
SignerCallback,
SignerOptions,
VerifierCallback,
VerifierOptions
} from 'fast-jwt'
import {
FastifyPluginCallback,
FastifyRequest
} from 'fastify'
declare module 'fastify' {
interface FastifyInstance {
jwt: fastifyJwt.JWT
}
interface FastifyReply {
jwtSign(payload: fastifyJwt.SignPayloadType, options?: fastifyJwt.FastifyJwtSignOptions): Promise<string>
jwtSign(payload: fastifyJwt.SignPayloadType, callback: SignerCallback): void
jwtSign(payload: fastifyJwt.SignPayloadType, options: fastifyJwt.FastifyJwtSignOptions, callback: SignerCallback): void
jwtSign(payload: fastifyJwt.SignPayloadType, options?: Partial<fastifyJwt.SignOptions>): Promise<string>
jwtSign(payload: fastifyJwt.SignPayloadType, options: Partial<fastifyJwt.SignOptions>, callback: SignerCallback): void
}
interface FastifyRequest {
jwtVerify<Decoded extends fastifyJwt.VerifyPayloadType>(options?: fastifyJwt.FastifyJwtVerifyOptions): Promise<Decoded>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
jwtVerify<Decoded extends fastifyJwt.VerifyPayloadType>(callback: VerifierCallback): void
// eslint-disable-next-line @typescript-eslint/no-unused-vars
jwtVerify<Decoded extends fastifyJwt.VerifyPayloadType>(options: fastifyJwt.FastifyJwtVerifyOptions, callback: VerifierCallback): void
jwtVerify<Decoded extends fastifyJwt.VerifyPayloadType>(options?: Partial<fastifyJwt.VerifyOptions>): Promise<Decoded>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
jwtVerify<Decoded extends fastifyJwt.VerifyPayloadType>(options: Partial<fastifyJwt.VerifyOptions>, callback: VerifierCallback): void
jwtDecode<Decoded extends fastifyJwt.DecodePayloadType>(options?: fastifyJwt.FastifyJwtDecodeOptions): Promise<Decoded>
jwtDecode<Decoded extends fastifyJwt.DecodePayloadType>(callback: fastifyJwt.DecodeCallback<Decoded>): void
jwtDecode<Decoded extends fastifyJwt.DecodePayloadType>(options: fastifyJwt.FastifyJwtDecodeOptions, callback: fastifyJwt.DecodeCallback<Decoded>): void
user: fastifyJwt.UserType
}
}
type FastifyJwt = FastifyPluginCallback<fastifyJwt.FastifyJWTOptions>
declare namespace fastifyJwt {
export type FastifyJwtNamespace<C extends {
namespace?: string;
jwtDecode?: string;
jwtVerify?: string;
jwtSign?: string;
}> =
Record<C extends { jwtDecode: string }
? C['jwtDecode']
: C extends { namespace: string }
? `${C['namespace']}JwtDecode`
: never,
JWT['decode']>
&
Record<C extends { jwtSign: string }
? C['jwtSign']
: C extends { namespace: string }
? `${C['namespace']}JwtSign`
: never,
JWT['sign']>
&
Record<C extends { jwtVerify: string }
? C['jwtVerify']
: C extends { namespace: string }
? `${C['namespace']}JwtVerify`
: never,
JWT['verify']>
/**
* for declaration merging
* @example
* ```
* declare module '@fastify/jwt' {
* interface FastifyJWT {
* payload: { name: string; email: string }
* }
* }
* ```
* @example
* ```
* // With `formatUser`.
* declare module '@fastify/jwt' {
* interface FastifyJWT {
* payload: { Name: string; e_mail: string }
* user: { name: string; email: string }
* }
* }
* ```
*/
export interface FastifyJWT {
// payload: ...
// user: ...
}
export type SignPayloadType = FastifyJWT extends { payload: infer T }
? T extends string | object | Buffer
? T
: string | object | Buffer
: string | object | Buffer
export type UserType = FastifyJWT extends { user: infer T }
? T
: SignPayloadType
export type TokenOrHeader = JwtHeader | { header: JwtHeader; payload: any }
export type Secret = string | Buffer | KeyFetcher | { key: Secret; passphrase: string }
| ((request: FastifyRequest, tokenOrHeader: TokenOrHeader, cb: (e: Error | null, secret: string | Buffer | undefined) => void) => void)
| ((request: FastifyRequest, tokenOrHeader: TokenOrHeader) => Promise<string | Buffer>)
export type VerifyPayloadType = object | string
export type DecodePayloadType = object | string
export interface DecodeCallback<Decoded extends DecodePayloadType> {
(err: Error, decoded: Decoded): void
}
export interface SignOptions extends Omit<SignerOptions, 'expiresIn' | 'notBefore'> {
expiresIn: number | string;
notBefore: number | string;
key?: string | Buffer
}
export interface VerifyOptions extends Omit<VerifierOptions, 'maxAge'> {
maxAge: number | string;
onlyCookie: boolean;
key?: string | Buffer
}
export interface FastifyJWTOptions {
secret: Secret | { public: Secret; private?: Secret }
decode?: Partial<DecoderOptions>
sign?: Partial<SignOptions>
verify?: Partial<VerifyOptions> & {
extractToken?: (request: FastifyRequest) => string | void
}
cookie?: {
cookieName: string
signed: boolean
}
messages?: {
badRequestErrorMessage?: string
badCookieRequestErrorMessage?: string
noAuthorizationInHeaderMessage?: string
noAuthorizationInCookieMessage?: string
authorizationTokenExpiredMessage?: string
authorizationTokenInvalid?: ((err: Error) => string) | string
authorizationTokenUntrusted?: string
authorizationTokenUnsigned?: string
}
trusted?: (
request: FastifyRequest,
decodedToken: { [k: string]: any }
) => boolean | Promise<boolean> | SignPayloadType | Promise<SignPayloadType>
formatUser?: (payload: SignPayloadType) => UserType
jwtDecode?: string
namespace?: string
jwtVerify?: string
jwtSign?: string
decoratorName?: string
}
export interface JWT {
options: {
decode: Partial<DecoderOptions>
sign: Partial<SignOptions>
verify: Partial<VerifyOptions>
}
cookie?: {
cookieName: string,
signed: boolean
}
sign(payload: SignPayloadType, options?: Partial<SignOptions>): string
sign(payload: SignPayloadType, callback: SignerCallback): void
sign(payload: SignPayloadType, options: Partial<SignOptions>, callback: SignerCallback): void
verify<Decoded extends VerifyPayloadType>(token: string, options?: Partial<VerifyOptions>): Decoded
// eslint-disable-next-line @typescript-eslint/no-unused-vars
verify<Decoded extends VerifyPayloadType>(token: string, callback: VerifierCallback): void
// eslint-disable-next-line @typescript-eslint/no-unused-vars
verify<Decoded extends VerifyPayloadType>(token: string, options: Partial<VerifyOptions>, callback: VerifierCallback): void
decode<Decoded extends DecodePayloadType>(token: string, options?: Partial<DecoderOptions>): null | Decoded
lookupToken(request: FastifyRequest, options?: FastifyJWTOptions['verify']): string
}
export type { JwtHeader }
export interface FastifyJwtSignOptions {
sign?: Partial<SignOptions>
}
export interface FastifyJwtVerifyOptions {
decode: Partial<DecoderOptions>
verify: Partial<VerifyOptions>
}
export interface FastifyJwtDecodeOptions {
decode: Partial<DecoderOptions>
verify: Partial<VerifyOptions>
}
export const fastifyJwt: FastifyJwt
export { fastifyJwt as default }
}
declare function fastifyJwt (...params: Parameters<FastifyJwt>): ReturnType<FastifyJwt>
export = fastifyJwt

203
backend/node_modules/@fastify/jwt/types/jwt.test-d.ts generated vendored Normal file
View File

@@ -0,0 +1,203 @@
import fastify from 'fastify'
import fastifyJwt, { FastifyJWTOptions, FastifyJwtNamespace, JWT, SignOptions, VerifyOptions } from '..'
import { expectAssignable, expectType } from 'tsd'
const app = fastify()
const secretOptions = {
secret: 'supersecret',
publicPrivateKey: {
public: 'publicKey',
private: 'privateKey'
},
secretFnCallback: (_req: any, _token: any, cb: any) => { cb(null, 'supersecret') },
secretFnPromise: (_req: any, _token: any) => Promise.resolve('supersecret'),
secretFnAsync: async (_req: any, _token: any) => 'supersecret',
secretFnBufferCallback: (_req: any, _token: any, cb: any) => { cb(null, Buffer.from('some secret', 'base64')) },
secretFnBufferPromise: (_req: any, _token: any) => Promise.resolve(Buffer.from('some secret', 'base64')),
secretFnBufferAsync: async (_req: any, _token: any) => Buffer.from('some secret', 'base64'),
publicPrivateKeyFn: {
public: (_req: any, _rep: any, cb: any) => { cb(null, 'publicKey') },
private: 'privateKey'
},
publicPrivateKeyFn2: {
public: 'publicKey',
private: (_req: any, _rep: any, cb: any) => { cb(null, 'privateKey') },
}
}
const jwtOptions: FastifyJWTOptions = {
secret: 'supersecret',
sign: {
expiresIn: 3600
},
cookie: {
cookieName: 'jwt',
signed: false
},
verify: {
maxAge: '1 hour',
extractToken: () => 'token',
onlyCookie: false
},
decode: {
complete: true
},
messages: {
badRequestErrorMessage: 'Bad Request',
badCookieRequestErrorMessage: 'Bad Cookie Request',
noAuthorizationInHeaderMessage: 'No Header',
noAuthorizationInCookieMessage: 'No Cookie',
authorizationTokenExpiredMessage: 'Token Expired',
authorizationTokenInvalid: (err) => `${err.message}`,
authorizationTokenUntrusted: 'Token untrusted'
},
trusted: () => false || '' || Buffer.from('foo'),
formatUser: payload => {
const objectPayload = typeof payload === 'string'
? JSON.parse(payload)
: Buffer.isBuffer(payload)
? JSON.parse(payload.toString())
: payload
return { name: objectPayload.userName }
},
namespace: 'security',
jwtVerify: 'securityVerify',
jwtSign: 'securitySign'
}
app.register(fastifyJwt, jwtOptions)
Object.values(secretOptions).forEach((value) => {
app.register(fastifyJwt, { ...jwtOptions, secret: value })
})
app.register(fastifyJwt, { ...jwtOptions, trusted: () => Promise.resolve(false || '' || Buffer.from('foo')) })
app.register(fastifyJwt, {
secret: {
private: {
key: 'privateKey',
passphrase: 'super secret passphrase',
},
public: 'publicKey',
},
sign: { algorithm: 'ES256' },
})
app.register(fastifyJwt, { ...jwtOptions, decoratorName: 'token' })
// expect jwt and its subsequent methods have merged with the fastify instance
expectAssignable<object>(app.jwt)
expectAssignable<Function>(app.jwt.sign)
expectAssignable<Function>(app.jwt.verify)
expectAssignable<Function>(app.jwt.decode)
expectAssignable<Function>(app.jwt.lookupToken)
expectAssignable<FastifyJWTOptions['cookie']>(app.jwt.cookie)
app.addHook('preHandler', async (request, reply) => {
// assert request and reply specific interface merges
expectAssignable<Function>(request.jwtVerify)
expectAssignable<Function>(request.jwtDecode)
expectAssignable<object | string | Buffer>(request.user)
expectAssignable<Function>(reply.jwtSign)
try {
await request.jwtVerify()
} catch (err) {
reply.send(err)
}
})
app.post('/signup', async (req, reply) => {
const token = app.jwt.sign({ user: 'userName' })
reply.send({ token })
})
// define custom payload
// declare module './jwt' {
// interface FastifyJWT {
// payload: {
// user: string
// }
// }
// }
// Custom payload with formatUser
// declare module './jwt' {
// interface FastifyJWT {
// payload: {
// user: string
// }
// user: {
// name: string
// }
// }
// }
expectType<JWT['decode']>(({} as FastifyJwtNamespace<{ namespace: 'security' }>).securityJwtDecode)
expectType<JWT['sign']>(({} as FastifyJwtNamespace<{ namespace: 'security' }>).securityJwtSign)
expectType<JWT['verify']>(({} as FastifyJwtNamespace<{ namespace: 'security' }>).securityJwtVerify)
declare module 'fastify' {
interface FastifyInstance extends FastifyJwtNamespace<{ namespace: 'tsdTest' }> {
}
}
expectType<JWT['decode']>(app.tsdTestJwtDecode)
expectType<JWT['sign']>(app.tsdTestJwtSign)
expectType<JWT['verify']>(app.tsdTestJwtVerify)
expectType<JWT['decode']>(({} as FastifyJwtNamespace<{ namespace: 'security', jwtDecode: 'decode' }>).decode)
expectType<JWT['sign']>(({} as FastifyJwtNamespace<{ namespace: 'security', jwtDecode: 'decode' }>).securityJwtSign)
expectType<JWT['verify']>(({} as FastifyJwtNamespace<{ namespace: 'security', jwtDecode: 'decode' }>).securityJwtVerify)
expectType<JWT['decode']>(({} as FastifyJwtNamespace<{ namespace: 'security', jwtSign: 'decode' }>).securityJwtDecode)
expectType<JWT['sign']>(({} as FastifyJwtNamespace<{ namespace: 'security', jwtSign: 'sign' }>).sign)
expectType<JWT['verify']>(({} as FastifyJwtNamespace<{ namespace: 'security', jwtSign: 'decode' }>).securityJwtVerify)
expectType<JWT['decode']>(({} as FastifyJwtNamespace<{ namespace: 'security', jwtVerify: 'verify' }>).securityJwtDecode)
expectType<JWT['sign']>(({} as FastifyJwtNamespace<{ namespace: 'security', jwtVerify: 'verify' }>).securityJwtSign)
expectType<JWT['verify']>(({} as FastifyJwtNamespace<{ namespace: 'security', jwtVerify: 'verify' }>).verify)
expectType<JWT['decode']>(({} as FastifyJwtNamespace<{ jwtDecode: 'decode' }>).decode)
expectType<JWT['sign']>(({} as FastifyJwtNamespace<{ jwtSign: 'sign' }>).sign)
expectType<JWT['verify']>(({} as FastifyJwtNamespace<{ jwtVerify: 'verify' }>).verify)
let signOptions: SignOptions = {
key: 'supersecret',
algorithm: 'HS256',
mutatePayload: true,
expiresIn: 3600,
notBefore: 0,
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
signOptions = {
key: Buffer.from('supersecret', 'utf-8'),
algorithm: 'HS256',
mutatePayload: true,
expiresIn: 3600,
notBefore: 0,
}
let verifyOptions: VerifyOptions = {
key: 'supersecret',
algorithms: ['HS256'],
complete: true,
cache: true,
cacheTTL: 3600,
maxAge: '1 hour',
onlyCookie: false,
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
verifyOptions = {
key: Buffer.from('supersecret', 'utf-8'),
algorithms: ['HS256'],
complete: true,
cache: 3600,
cacheTTL: 3600,
maxAge: 3600,
onlyCookie: true,
}