Giter Site home page Giter Site logo

fastify-cors's Introduction

@fastify/cors

CI NPM version js-standard-style

@fastify/cors enables the use of CORS in a Fastify application.

Install

npm i @fastify/cors

Compatibility

Plugin version Fastify version
^8.0.0 ^4.0.0
^7.0.0 ^3.0.0
^3.0.0 ^2.0.0
^1.0.0 ^1.0.0

Please note that if a Fastify version is out of support, then so are the corresponding version(s) of this plugin in the table above. See Fastify's LTS policy for more details.

Usage

Require @fastify/cors and register it as any other plugin, it will add an onRequest hook and a wildcard options route.

import Fastify from 'fastify'
import cors from '@fastify/cors'

const fastify = Fastify()
await fastify.register(cors, { 
  // put your options here
})

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

await fastify.listen({ port: 3000 })

You can use it as is without passing any option or you can configure it as explained below.

Options

  • origin: Configures the Access-Control-Allow-Origin CORS header. The value of origin could be of different types:
    • Boolean - set origin to true to reflect the request origin, or set it to false to disable CORS.
    • String - set origin to a specific origin. For example if you set it to "http://example.com" only requests from "http://example.com" will be allowed. The special * value (default) allows any origin.
    • RegExp - set origin to a regular expression pattern that will be used to test the request origin. If it is a match, the request origin will be reflected. For example, the pattern /example\.com$/ will reflect any request that is coming from an origin ending with "example.com".
    • Array - set origin to an array of valid origins. Each origin can be a String or a RegExp. For example ["http://example1.com", /\.example2\.com$/] will accept any request from "http://example1.com" or from a subdomain of "example2.com".
    • Function - set origin to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback as a second (which expects the signature err [Error | null], origin), where origin is a non-function value of the origin option. Async-await and promises are supported as well. The Fastify instance is bound to function call and you may access via this. For example:
    origin: (origin, cb) => {
      const hostname = new URL(origin).hostname
      if(hostname === "localhost"){
        //  Request from localhost will pass
        cb(null, true)
        return
      }
      // Generate an error on other origins, disabling access
      cb(new Error("Not allowed"), false)
    }
  • methods: Configures the Access-Control-Allow-Methods CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: ['GET', 'PUT', 'POST']).
  • hook: See the section Custom Fastify hook name (default: onRequest)
  • allowedHeaders: Configures the Access-Control-Allow-Headers CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: ['Content-Type', 'Authorization']). If not specified, defaults to reflecting the headers specified in the request's Access-Control-Request-Headers header.
  • exposedHeaders: Configures the Access-Control-Expose-Headers CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: ['Content-Range', 'X-Content-Range']). If not specified, no custom headers are exposed.
  • credentials: Configures the Access-Control-Allow-Credentials CORS header. Set to true to pass the header, otherwise it is omitted.
  • maxAge: Configures the Access-Control-Max-Age CORS header. In seconds. Set to an integer to pass the header, otherwise it is omitted.
  • cacheControl: Configures the Cache-Control header for CORS preflight responses. Set to an integer to pass the header as Cache-Control: max-age=${cacheControl}, or set to a string to pass the header as Cache-Control: ${cacheControl} (fully define the header value), otherwise the header is omitted.
  • preflightContinue: Pass the CORS preflight response to the route handler (default: false).
  • optionsSuccessStatus: Provides a status code to use for successful OPTIONS requests, since some legacy browsers (IE11, various SmartTVs) choke on 204.
  • preflight: if needed you can entirely disable preflight by passing false here (default: true).
  • strictPreflight: Enforces strict requirement of the CORS preflight request headers (Access-Control-Request-Method and Origin) as defined by the W3C CORS specification (the current fetch living specification does not define server behavior for missing headers). Preflight requests without the required headers will result in 400 errors when set to true (default: true).
  • hideOptionsRoute: hide options route from the documentation built using @fastify/swagger (default: true).

⚠️ DoS attacks

The use of RegExp or a function for the origin parameter might allow an attacker to perform a Denial of Service attack. Craft those with extreme care.

Configuring CORS Asynchronously

const fastify = require('fastify')()

fastify.register(require('@fastify/cors'), (instance) => {
  return (req, callback) => {
    const corsOptions = {
      // This is NOT recommended for production as it enables reflection exploits
      origin: true
    };

    // do not include CORS headers for requests from localhost
    if (/^localhost$/m.test(req.headers.origin)) {
      corsOptions.origin = false
    }

    // callback expects two parameters: error and options
    callback(null, corsOptions)
  }
})

fastify.register(async function (fastify) {
  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })
})

fastify.listen({ port: 3000 })

Custom Fastify hook name

By default, @fastify/cors adds a onRequest hook where the validation and header injection are executed. This can be customized by passing hook in the options. Valid values are onRequest, preParsing, preValidation, preHandler, preSerialization, and onSend.

import Fastify from 'fastify'
import cors from '@fastify/cors'

const fastify = Fastify()
await fastify.register(cors, { 
  hook: 'preHandler',
})

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

await fastify.listen({ port: 3000 })

When configuring CORS asynchronously, an object with delegator key is expected:

const fastify = require('fastify')()

fastify.register(require('@fastify/cors'), {
  hook: 'preHandler',
  delegator: (req, callback) => {
    const corsOptions = {
      // This is NOT recommended for production as it enables reflection exploits
      origin: true
    };

    // do not include CORS headers for requests from localhost
    if (/^localhost$/m.test(req.headers.origin)) {
      corsOptions.origin = false
    }

    // callback expects two parameters: error and options
    callback(null, corsOptions)
  },
})

fastify.register(async function (fastify) {
  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })
})

fastify.listen({ port: 3000 })

Acknowledgements

The code is a port for Fastify of expressjs/cors.

License

Licensed under MIT.
expressjs/cors license

fastify-cors's People

Contributors

alemagio avatar boenrobot avatar cemremengu avatar climba03003 avatar codyzu avatar delvedor avatar dependabot-preview[bot] avatar dependabot[bot] avatar eomm avatar ethan-arrowood avatar fdawgs avatar frikille avatar gcangussu avatar ghostd avatar github-actions[bot] avatar greenkeeper[bot] avatar is2ei avatar jsumners avatar laat avatar mcollina avatar mohammedslimani avatar naumf avatar salmanm avatar skellla avatar superchupudev avatar timedtext avatar tom-brouwer avatar uzlopak avatar vmarceau avatar zekth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify-cors's Issues

Pass fastify instance to origin function

Hi. In order to allow usage of previously registered modules and plugins (e.g. like fastify-mongo or others) in origin function it will be good if fastify instance will be passed there as parameter.

Now it's only an option to use closure for that, but that limits a bit where that function could be declared.

Confusing description of origin function

According to docs:

Function - set origin to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (which expects the signature err [object], allow [bool]) as the second, async-await and promises are supported as well.

Here we can see callback param allow which in this context has meaning to allow such request or not.

However according to the code this parameter called origin and control enabling or disabling cors. So if allow is set to false then cors headers will not be added at all.

So I wonder what behaviour is right?

IMO allow param looks quiet logical in that case and it should control access-control-allow-origin header value. If true it's set to origin, if false it's set header to false, so cross origin requests will be blocked by browser (but they will not fail with 500 error, which is not quiet correct code for that case).
But it looks like in express cors that param controls adding header and if it's set to false it just doesn't send it.

An in-range update of @typescript-eslint/eslint-plugin is breaking the build 🚨

The devDependency @typescript-eslint/eslint-plugin was updated from 2.19.0 to 2.19.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@typescript-eslint/eslint-plugin is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v2.19.1

2.19.1 (2020-02-10)

Bug Fixes

  • eslint-plugin: [unbound-method] blacklist a few unbound natives (#1562) (4670aab)
  • typescript-estree: ts returning wrong file with project references (#1575) (4c12dac)
Commits

The new version differs by 5 commits.

  • 1c8f0df chore: publish v2.19.1
  • 4c12dac fix(typescript-estree): ts returning wrong file with project references (#1575)
  • e9cf734 docs(eslint-plugin): fix typo in readme
  • 10d86b1 docs(eslint-plugin): [no-dupe-class-members] fix typo (#1566)
  • 4670aab fix(eslint-plugin): [unbound-method] blacklist a few unbound natives (#1562)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Typescript definition misleading

Hey guys, I start using this plugin with TS support in my codebase, and I use a custom function for origin field for cors options. Which I found the sample for it in your test file here

https://github.com/fastify/fastify-cors/blob/master/test/cors.test.js#L240.

But I got an error when using this kind of function signature, that TS told me about incompatible types for my function. When I look out on the d.ts file is supposed to be originCallback type

https://github.com/fastify/fastify-cors/blob/master/index.d.ts#L7

I think that type is for the second parameter in the function right? And the definition should be

type originCustom = (header: string, cb: originCallback) => void;
....
origin?: string | boolean | RegExp | string[] | RegExp[] | originCustom; // not originCallback

am I correct here, or the test is misguided me?

Access-Control-Allow-Origin wrong value in case of not authorized Origin

🐛 Bug Report

In the case of a non validated request the Access-Control-Allow-Origin is set to false as mentionned in #124 . Which is not RFC compliant, also the use of null is not the best as said in https://w3c.github.io/webappsec-cors-for-developers/#avoid-returning-access-control-allow-origin-null . Would be better to not return the CORS header in the case a non validation. What do you think @mcollina ?

RFC: https://tools.ietf.org/html/rfc6454#section-7.1

ChainAlert: npm package release (6.1.0) has no matching tag in this repo

Dear fastify-cors maintainers,
Thank you for your contribution to the open-source community.

This issue was automatically created to inform you a new version (6.1.0) of fastify-cors was published without a matching tag in this repo.

As part of our efforts to fight software supply chain attacks, we would like to verify this release is known and intended, and not a result of an unauthorized activity.

If you find this behavior legitimate, kindly close and ignore this issue. Read more

badge

The plugin treats every OPTIONS request as a preflight request

#13 🐛 Bug Report

For an OPTIONS request to be a valid preflight request, it should have following Headers present in the request:

  • Origin
  • Access-Control-Request-Method
  • Access-Control-Request-Headers
    Otherwise the request should be treated as a normal OPTIONS request and forwarded to route

To Reproduce

// package.json

{
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "fastify": "^3.4.1",
    "fastify-cors": "4.1.0"
  }
}

// index.js

const fastify = require('fastify')()

fastify.register(require('fastify-cors'), { 
    origin: "*",
    optionsSuccessStatus: 200,
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
})

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

fastify.listen(3000)

// requests
1- With CORS headers

curl --location --request OPTIONS 'http://localhost:3000/' \
--header 'Origin: abc.com' \
--header 'Access-Control-Request-Method: POST'

Response: 200

2- Without CORS headers

curl --location --request OPTIONS 'http://localhost:3001/'

Resposne: 200

Expected behavior

If the request is not a valid preflight request (does not contain CORS preflight request mandatory headers), it should be forwarded to route

Your Environment

  • node version: 10
  • fastify version: >=2.0.0
  • os: Windows

An in-range update of @typescript-eslint/parser is breaking the build 🚨

The devDependency @typescript-eslint/parser was updated from 2.19.0 to 2.19.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@typescript-eslint/parser is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v2.19.1

2.19.1 (2020-02-10)

Bug Fixes

  • eslint-plugin: [unbound-method] blacklist a few unbound natives (#1562) (4670aab)
  • typescript-estree: ts returning wrong file with project references (#1575) (4c12dac)
Commits

The new version differs by 5 commits.

  • 1c8f0df chore: publish v2.19.1
  • 4c12dac fix(typescript-estree): ts returning wrong file with project references (#1575)
  • e9cf734 docs(eslint-plugin): fix typo in readme
  • 10d86b1 docs(eslint-plugin): [no-dupe-class-members] fix typo (#1566)
  • 4670aab fix(eslint-plugin): [unbound-method] blacklist a few unbound natives (#1562)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Weird issue with async registering the plugin breaking the route table

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.27.2

Plugin version

6.0.3

Node.js version

16.14.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

21.10

Description

Note: happens on MacOS as well

When registering the plugin in an async fashion, the fastify server's configuration is altered somehow in that routePrefixes remain set on the instance even without nested routes. Weirdly enough, this doesn't happen when calling then after registering the plugin.

See this repo

The ONLY difference between the working and broken code:

$ diff broken.js working.js
11c11
<   })
---
>   }).then(() => console.log('cors registered'))

For reference, both tables:

// working.js
└── /
    ├── /
    ├── * (OPTIONS)
    └── v
        ├── 1/user (GET)
        └── 2/user (GET)

// broken.js
└── /
    ├── /
    ├── * (OPTIONS)
    └── v1/
        ├── user (GET)
        └── v2/user (GET)

Steps to Reproduce

See this repo

NOTE: code taken from the fastify route example with prefixing

  • npm install
  • node working.js
  • node broken.js
  • compare route table logs

Expected Behavior

Expected both route tables to look like this:

└── /
    ├── /
    ├── * (OPTIONS)
    └── v
        ├── 1/user (GET)
        └── 2/user (GET)

post will CORS

fastify.register(require('fastify-cors'), {
'origin': true,
'methods': "GET,HEAD,PUT,PATCH,POST,DELETE"
})
2018-12-17 11 56 08

��I set Schema
2018-12-17 11 48 32

if post don't follow Schema, it will console

Access to XMLHttpRequest at 'http://localhost:4000/api/users' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
commons.app.js:697 Uncaught (in promise) Error: Network Error
2018-12-17 11 50 29
2018-12-17 11 50 39

but if follow Schema, it will be fine.
2018-12-17 11 50 46

so, how can I let error show up ?

asynchronous dynamic cors not even worked!

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure it has not already been reported

Fastify version

latest

Plugin version

latest

Node.js version

14

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

win10

Description

yo your origin is pointing to nothing. How to fix this? I know it suppose to be an object?

Steps to Reproduce

fastify.register(require('fastify-cors'), (instance) => (req, callback) => {
  let corsOptions;
  // do not include CORS headers for requests from localhost
  if (/localhost/.test(origin)) {
    corsOptions = { origin: false }
  } else {
    corsOptions = { origin: true }
  }
  callback(null, corsOptions) // callback expects two parameters: error and options
})

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

.test(origin) points to undefined man

Expected Behavior

origin should not be undefined

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 11.9.4 to 11.9.5.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Update `latest` tags on the NPM registry

I was a bit confused by the deprecation of @types/fastify-cors. The deprecation message is telling that the latest fastify-cors has its own type definition. But latest is still pointing to 1.0.0 which hasnt any type definition.

> npm info fastify-cors versions
[ '0.0.1',
  '0.1.0',
  '0.2.0',
  '1.0.0',
  '2.0.0',
  '2.0.1',
  '2.1.0',
  '2.1.1' ]

> npm info fastify-cors dist-tags
{ latest: '1.0.0', next: '2.0.1' }

An in-range update of @typescript-eslint/eslint-plugin is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye 👋 and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


The devDependency @typescript-eslint/eslint-plugin was updated from 2.23.0 to 2.24.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@typescript-eslint/eslint-plugin is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v2.24.0

2.24.0 (2020-03-16)

Bug Fixes

  • typescript-estree: unnecessary program updates by removing timeout methods (#1693) (2ccd66b)

Features

  • typescript-estree: support 3.8 export * as ns (#1698) (133f622)
Commits

The new version differs by 9 commits.

  • 56e1e16 chore: publish v2.24.0
  • 71ef267 docs: code of conduct spelling
  • 970cfbd docs: prettier the code of conduct
  • 4a0e886 docs: add netlify to the readme
  • cb33eba chore: add code of conduct
  • 0b65f5e chore: bump acorn from 6.4.0 to 6.4.1 (#1730)
  • 2ccd66b fix(typescript-estree): unnecessary program updates by removing timeout methods (#1693)
  • 4ab3bf0 docs(eslint-plugin): typo in no-unsafe-member-access (#1720)
  • 133f622 feat(typescript-estree): support 3.8 export * as ns (#1698)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Request is processed even if origin not whitelisted

Maybe I didn't get the concept of CORS right, but I'm facing the following issue:

I whitelist a domain http://example.com using
server.register(fastifyCors, { origin: ["http://example.com"]});

Then I define the following endpoint:

server.post("/mypost", async(request, response) => {
    foo();
    response.send("OK");
});

Now, if I receive a request from a domain other than http://example.com, I'd expect foo() not to be executed. However, it seems foo() is run always, no matter from which origin the request comes.

What am I missing here?

Thanks in advance!

CORS fails on multipart/form-data

Everything works fine on localhost but when on the server getting CORS error

origin xxxxx has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Simple axios post with multipart/form-data
let dataURIString =fileBlob let data = new FormData() data.append('file', dataURIString) this.$axios.post(${process.env.API}/post, data) .then(function (response) { console.log(response) }).catch(function (error) { console.log(error) })

Fastify Server side server.js:

fastify.register(require('fastify-cors'), { origin: true, optionsSuccessStatus: 200 })

Route:
app.post('/post', aesCalculator, async (req, reply) => { reply.send(req.body) }

Simply changing the Axios post to JSON and CORS issue goes away. Anyone successfully used multipart with CORS? I am using fastify-multipart plugin but as mentioned, when on the same domain like localhost it works correctly with no issue.

Value of CORS header is false

🐛 Bug Report

Value of access-control-allow-origin is false when using RegExps and arrays. Works fine when using string though.

To Reproduce

Steps to reproduce the behavior:

await app.server.register(cors, {
    origin: ["http://localhost:3000"],
});

image
image

Expected behavior

The header being set to the origin if allowed and not present if denied.

Your Environment

  • node version: 14.16.0
  • fastify version: 3.12.0
  • os: Windows

Cannot find version 7.0.0

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

7.0.0

Plugin version

No response

Node.js version

any

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

20.04.4 LTS (Focal Fossa)

Description

I'm trying to install fastify-cors. The npm package manager automatically found version 6.2.0 which downloaded fastify-cors.depricated and fastify-cors but the latter doesn't export types (only index.js).

I've tried downloading fastify-cors 7.0.0 since I found this is the latest release on GitHub but npm can't find that version. Since the latest release was yestery I'm guessing something went wrong.

For now the solution I'm using is: continue using the fastify-cors.depricated.

Steps to Reproduce

npm install [email protected]

Expected Behavior

I'm expecting fastify-cors at version 7.0.0 to be installed.

Fastify-cors with middleware

Q: If i use this plugin with session (express-session) middleware. I get session-cookie on prefligth response. I think it because used 'preHandler' hook that higher in lifecycle. It is true and i must use another express-like middleware cors or i have solution to use fastify-cors and express-session middleware together? Sorry if is it inappropriate question i am new in programming, i am just curios.

异步配置cors的 README 示例代码错误,容易误导使用者。

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure it has not already been reported

Fastify version

6.0.0

Node.js version

14.16.1

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

11.2.3

Description

问题一 : README 示例代码有错误, { } 不能作为return 的功能使用,应该使用( )

image

一些小建议:

源码中异步配置CORS是这样写的。
image

  • 其中分一个参数的情况和两个参数的情况,但是两种情况的入参一种是req,一种是reply,虽然没有错误,但是对于使用者来说不看源码的话,还是会有一些疑问
  • 当我们使用一个参数的时候需要这样写,返回一个promise,这样是否有些多余,我们可以直接返回一个options,这样应该更加简洁和方便。
fastify.register(require('fastify-cors'), (instance) => { (req) => {
  let corsOptions;
  if (/localhost/.test(origin)) {
    corsOptions = { origin: false }
  } else {
    corsOptions = { origin: true }
  }
  return new Promise((resolve,reject)=>{
     resolve(corsOptions)
  })
 }
})
  • 综上所述,我们像这样写,考虑放弃第二个参数 callback,可能会更加友好。
function handleCorsOptionsDelegator (optionsResolver, fastify) {
  fastify.addHook('onRequest', (req, reply, next) => {
    const options = optionsResolver(req,reply) 
    if(typeof options === 'object'){
      const corsOptions = Object.assign({}, defaultOptions, options)
      onRequest(fastify, corsOptions, req, reply, next)
    }else{
      next(new Error('Invalid CORS origin option'))
    }
    next()
  })
}
  • 我们使用的时候只用返回一个options就好
fastify.register(require('fastify-cors'), (req, reply) => {
    //Other operations
    return { origin: '*', methods: 'POST' }
  })

上述如果有错误,我们可以一起讨论。

Steps to Reproduce

Expected Behavior

No response

404 Not Found on OPTIONS request

Completely stumped. I have the cors plugin installed, and two routes as follows:

module.exports = async (app, opts) => {
  app.get('/bar', async (request, reply) => {
    return { hello: 'bar called' }
  })

  app.get('/foo', async (request, reply) => {
    return { hello: 'foo called' }
  })
}

OPTIONS requests seem to be working, and are handled by the onRequest hook in the fastify-cors plugin, but when I change the path of the bar route, to anything else that doesn't start with bar... I get a 404 not found response.

e.g.:

module.exports = async (app, opts) => {
  app.get('/fuzzy', async (request, reply) => {
    return { hello: 'bar called' }
  })
}

curl -X OPTIONS http://127.0.0.1:3000/fuzzy

returns

{"statusCode":404,"error":"Not Found","message":"Not Found"}

Any ideas?

Getting a OPTIONS under default tag in swagger doc

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure it has not already been reported

Fastify version

3.19.0

Plugin version

6.0,1

Node.js version

14.17.0

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

I am facing an weird issue. In my swagger doc, I am always seeing default OPTIONS API is getting listed without any specification from my routes.

I am registering fastify-cors which seems the issue.

fastify.register(require('fastify-cors'), {});
fastify.register(require('./routes/routes'));

This is the screen shot:

enter image description here

My versions are:

    "fastify": "^3.19.0",
    "fastify-auth0-verify": "^0.5.2",
    "fastify-cors": "^6.0.1",
    "fastify-swagger": "^4.8.2",
    "fastify-mongodb": "^2.0.1",
	"mongo-sanitize": "^1.1.0"

What's the way out? It looks really odd as my swagger is going to be out for our customers/integrators.

Thanks,
Pradip

Steps to Reproduce

Use the versions and register it like

fastify.register(require('fastify-cors'), {});

Expected Behavior

The default route specification should not come in the swagger.

add CORS headers to non-preflight

🐛 Bug Report

The plugin does not add CORS headers to non-preflight requests, and Chrome does not accept this. In cors package, they do this.

To Reproduce

In the source, I see that the headers are added only when request method is OPTIONS.

Expected behavior

Add CORS headers to requests whose method is not OPTIONS.

Your Environment

  • node version: 12
  • fastify version: >=1.0.0
  • os: Linux

An in-range update of fastify is breaking the build 🚨

The devDependency fastify was updated from 2.7.1 to 2.8.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v2.8.0

📚 PR:

  • docs(Serverless): add missing punctuation marks (#1783)
  • Add toStrinTag to errors (#1785)
  • [ts] Add handler to RouteShorthandOptions (#1788)
  • typo: typescript-server.ts (#1791)
  • Add request property to reply documentation (#1792)
  • Use .isFluentSchema instead of symbol to check for fluent-schema (#1794)
  • fix inverted if in serverless example (#1797)
  • Ensure that header properties are not duplicated in schema (#1806)
  • docs(Hooks): Add each Hook to a title (#1801)
  • Docs(typescript) and other typos (#1811)
  • docs(Hooks): (#1810)
  • Update standard (#1816)
  • add plugin for autogenerate crud route in Ecosystem (#1813)
  • chore(package): update @typescript-eslint/parser to version 2.0.0 (#1799)
  • Improve default 404 route (#1826)
  • Schema build error (#1808)
  • Update Ecosystem.md (#1827)
  • fix: premature close test (#1833)
  • Added Zeit Now docs (#1824)
  • greenkeeper ignore @typescript-eslint/eslint-plugin (#1835)
Commits

The new version differs by 21 commits.

  • 00d72e5 Bumped v2.8.0
  • c56a9c1 greenkeeper ignore @typescript-eslint/eslint-plugin (#1835)
  • db66ea3 Added Zeit Now docs (#1824)
  • 804256e fix: premature close test (#1833)
  • 936b509 Update Ecosystem.md (#1827)
  • 5f3ae97 Schema build error (#1808)
  • 76c8879 Improve default 404 route (#1826)
  • 05c0329 chore(package): update @typescript-eslint/parser to version 2.0.0 (#1799)
  • d48c6a2 add plugin for autogenerate crud route in Ecosystem (#1813)
  • 0d6055d Update standard (#1816)
  • 639298b docs(Hooks): (#1810)
  • 0d2fdd7 Docs(typescript) and other typos (#1811)
  • 1568dff docs(Hooks): Add each Hook to a title (#1801)
  • 9c940b7 Ensure that header properties are not duplicated in schema (#1806)
  • fb68541 fix inverted if in serverless example (#1797)

There are 21 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

More types should be exported

Hi,

🐛 Bug Report

I try fastify (and this plugin) within an existing typescript (3.8) project. Here is my sample code:

import type { originCallback, originFunction } from 'fastify-cors';

const corsDelegate: originFunction = (origin: string, callback: originCallback) => {
  if (isOriginAllowed(origin, getAllowedOrigins(), areAllPortsAllowed())) {
    callback(null, true);
    return
  }
  callback(new Error("Not allowed"), false);
};

tsc throws this error:

TS2459: Module '"../node_modules/fastify-cors"' declares 'originFunction' locally, but it is not exported.

Expected behavior

no TS error ;-)

Your Environment

  • node version: 12
  • fastify version: 2.14.0
  • os: Linux
  • fastify-cors: 3.0.3

100% code coverage

As titled!

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |    88.41 |    80.65 |      100 |    88.89 |                   |
 index.js |    88.41 |    80.65 |      100 |    88.89 |... 43,146,148,150 |
----------|----------|----------|----------|----------|-------------------|

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.7.0 to 12.7.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Fastify cors > v2.1.3 causes fastify schema compiler build error

💥 Regression Report

Upgrading from [email protected] to [email protected] and beyond causes some shared schema failures.

Last working version

Worked up to version: 2.1.3

Stopped working in version: 2.2.0, 3.0.0

To Reproduce

Steps to reproduce the behavior:

  1. Install fastify, fastify-cors, fastify-plugin
  2. Run the following code node index.js
const fastify = require('fastify')({ logger: true });
const cors = require('fastify-cors');
const fp = require('fastify-plugin');

const sharedSchemas = fp(
    async f => {
        f.addSchema({
            $id: 'https://example.com/bson',
            type: 'object',
            types: {
                objectId: {
                    type: 'string',
                    pattern: '\\b[0-9A-Fa-f]{24}\\b',
                },
            }
        });
    }
);

async function main() {
    await fastify.register(cors);
    await fastify.register(sharedSchemas);

    console.dir(fastify.getSchemas());

    fastify.route({
        method: 'GET',
        url: '/:id',
        schema: {
            params: {
                type: 'object',
                properties: {
                    id: { $ref: 'https://example.com/bson#/types/objectId' },
                },
            },
        },
        handler: async (req) => ({ hello: req.params.id }),
    });

    await fastify.listen('1337', '127.0.0.1');
}

main().catch(console.error);

This spits out the error

FastifyError [FST_ERR_SCH_BUILD]: FST_ERR_SCH_BUILD: Failed building the schema for GET: /:id, due error can't resolve reference https://example.com/bson#/types/objectId from id #
    at Object.afterRouteAdded (/contrib/fastify-cors-schema/node_modules/fastify/lib/route.js:232:37)
    at /contrib/fastify-cors-schema/node_modules/fastify/lib/route.js:168:25
    at Object._encapsulateThreeParam (/contrib/fastify-cors-schema/node_modules/avvio/boot.js:417:7)
    at Boot.callWithCbOrNextTick (/contrib/fastify-cors-schema/node_modules/avvio/boot.js:339:5)
    at Boot._after (/contrib/fastify-cors-schema/node_modules/avvio/boot.js:230:26)
    at Plugin.exec (/contrib/fastify-cors-schema/node_modules/avvio/plugin.js:89:17)
    at Boot.loadPlugin (/contrib/fastify-cors-schema/node_modules/avvio/plugin.js:175:10)
    at Task.release (/contrib/fastify-cors-schema/node_modules/fastq/queue.js:127:16)
    at worked (/contrib/fastify-cors-schema/node_modules/fastq/queue.js:169:10)
    at /contrib/fastify-cors-schema/node_modules/avvio/plugin.js:178:7 {
  name: 'FastifyError [FST_ERR_SCH_BUILD]',
  code: 'FST_ERR_SCH_BUILD',
  message: "FST_ERR_SCH_BUILD: Failed building the schema for GET: /:id, due error can't resolve reference https://example.com/bson#/types/objectId from id #",
  statusCode: 500
}

Expected behavior

Schemas shouldn't be affected by a cors plugin.
If you run npm install [email protected], then run node index.js again, everything is fine.

Your Environment

  • node version: 12
  • fastify version: >=2.0.0
  • os: Mac
  • any other relevant information

Allow all headers with wildcard

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Is is possible to allow all headers? I've tried it by passing a wildcard * to the allowedHeaders config option, and it didn't work.
I think it would be a great addition to allow it, there are other libraries which allow it, for example, fastapi

Domain is blocked by CORS even though it is in the origin string?

Hopefully a quick question from incorrect syntax. I am trying to only allow requests that are from my domain to succeed with fastify-cors. Requests are succeeding if I use an asterisk in the config but if I try and get specific on the domain it is failing.

This is the origin config I am trying to use:

  fastify.register(require('fastify-cors'), {
    origin: 'http://modfi-dev.nonset.com' // fails
  })

However when I use Firefox to initiate a request to my App I am getting this CORS error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://modfi-dev.nonset.com:4000/batch_stock_prices/?stocks=AAPL,MSFT,NFLX,TSLA,SBUX. 

(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://modfi-dev.nonset.com’).

I've tried adding the port as well as trying a regex expression for the origin config but it doesn't seem to make a difference.

This is how I am attempting to make the request to the fastify server from my app

axios.get('http://' + appDomain +':4000/batch_stock_prices/?stocks=' + _stock, { timeout: 2000 })
...

appDomain is modfi-dev.nonset.com

Requests go through fine if I use an asterisk but that defeats the purpose of CORS:

  fastify.register(require('fastify-cors'), {
    origin: '*' // works fine
  })

Am I missing something obvious?

Origin function does not receive `origin` attribute

Hi,

First of all, good job guys!
I am looking at the possibilities of Fastify and the plugins and noticed that when using a function to validate the origin, it is not passed (always undefined).

fastify.register(require('fastify-cors'), {
origin: (origin, callback) => {
console.log('ORG: ', origin)

  const whitelist = [undefined]
  if (whitelist.indexOf(origin) !== -1) {
    callback(null, true)
  } else {
    callback(new Error('Not allowed by CORS'))
  }
}

})

Wrong type for `originFunction`

🐛 Bug Report

originFunction is defined as follow:

type originFunction = (origin: string, callback: originCallback) => void;

To Reproduce

When the server receives a request without Origin header, the origin parameter is undefined (which is expectable).

Expected behavior

The correct type of the function should be:

type originFunction = (origin: string | undefined, callback: originCallback) => void;

Your Environment

  • node version: 12
  • fastify version: 2.14.0
  • os: Linux
  • fastify-cors: 3.0.3

How to use origin callback and pass null in TypeScript?

In the exported types, the callback definition for the origin function is:

type originCallback = (err: Error, allow: boolean) => void;

type originFunction = (origin: string, callback: originCallback) => void;

This does not allow us to call as follows (per examples?)

callback(null, true);

Note: cannot pass null for the first parameter as it is not of type Error

How should we call the callback in case where there is no error?

fastify.Plugin Namespace has no exported member 'Plugin'.

🐛 Bug Report

A clear and concise description of what the bug is.

Trying to compile my code with Typescript however I keep receiving the following issue:

node_modules/fastify-cors/index.d.ts:18:36 - error TS2694: Namespace '"/Users/harvey/devproject/node_modules/fastify/fastify"' has no exported member 'Plugin'.

The error is on line 18

18 declare const fastifyCors: fastify.Plugin<

To Reproduce

Steps to reproduce the behavior:

tsc

Expected behavior

I expect it to not throw the error and grab the Plugin type correctly.

Your Environment

  • node version: 12
  • fastify version: >=3.0.0
  • os: Mac
  • any other relevant information

Typescript Support: Origin is undefined

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.0.0

Plugin version

3.0.0

Node.js version

v14.15.4

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

11.5.2

Description

Following the async example in a typescript environment with fastify plugin results in origin is undefined

Steps to Reproduce

Trying to set up CORS for fastify vai the fastify-plugin in a fairly strict typescript environment. The docs showing the async configuration https://github.com/fastify/fastify-cors#configuring-cors-asynchronously

import fp from 'fastify-plugin';
import cors from 'fastify-cors';

export default fp(async (fastify) => {
  fastify.register(cors, () => (callback: any): void => {
    let corsOptions;
    if (/localhost/.test(origin)) {
      corsOptions = { origin: false };
    } else {
      corsOptions = { origin: 'www.mywebsite.com' };
    }
    callback(null, corsOptions);
  });
});

The error I get is

'origin' is not defined.eslintno-undef
Cannot find name 'origin'.ts(2304)

How do I define origin?

If I try the non-async example from the docs origin is still undefined

import fp from 'fastify-plugin';
import cors from 'fastify-cors';

export default fp(async (fastify) => {
  fastify.register(cors, {
    origin: (origin, callback) => {
      // eslint-disable-next-line no-console
      console.log(origin); //<======== undefined
      if (/localhost/.test(origin)) {
        callback(null, true);
      } else {
        callback(new Error('Not allowed by CORS'), false);
      }
    },
  });
});

Expected Behavior

I expect typescript to not complain about origin being undefined

Demo code can be found here https://github.com/bkawk/fastify-swagger/blob/cors/src/plugins/cors.ts

Your .dependabot/config.yml contained invalid details

Dependabot encountered the following error when parsing your .dependabot/config.yml:

The property '#/' did not contain a required property of 'update_configs'
The property '#/' contains additional properties ["update_conigs"] outside of the schema when none are allowed

Please update the config file to conform with Dependabot's specification using our docs and online validator.

CORS policy: No 'Access-Control-Allow-Origin'

Hello, i added fastify-cors in project

    fastify.register(require('fastify-cors'), { 
        origin: true,
        methods: ['GET', 'PUT', 'POST']
    })

use localhost:3010 server

in browser push button load data from other server.

Error:

Access to XMLHttpRequest at 'https://site.com/rawaddr/1EFyFPMeaV4ZEy7zdFT4k3EvDud5ixaSGa' from origin 'http://localhost:3010' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

axios request

        const response = await axios.get( url, {} );
        console.log(response)

problem in server localhost or browser axios settings?

Different allowed origins for different routes

It would be nice to have a way to specify different allowed origins for different routes. For example, if I have a public api endpoint available to third parties it would be nice to specify in the plugin options origin: "*" for that and origin: false for other routes. I tried passing a function to the origin option but it looks like only req.headers.origin is passed into that instead of the entire request object. Is there a good pattern to satisfy this use case?

Preflight 404

💥 Regression Report

Apologies, I'm unsure if this is a true regression because I haven't kept good track of version timeline, however the implementation I had was working (as recent as a day or two ago) and now it is not. The application now 404s on preflight and disabling preflight via options seems to have no effect. There are a few old issues that seem pertinent to the problem I'm experiencing i.e. #20. I'm new to Fastify, this could very well be my implementation, but I'm not trying to do anything fancy.

Last working version

Worked up to version: 5.1.0

Stopped working in version: 5.1.0

To Reproduce

  void fastify.register(import("fastify-cors"), { preflight: false })
  void fastify.register(AutoLoad, {
    dir: join(__dirname, "plugins"),
    options: opts,
  })
  void fastify.register(AutoLoad, {
    dir: join(__dirname, "modules"),
    indexPattern: /.*routes(\.ts|\.js|\.cjs|\.mjs)$/,
    options: opts,
  })

Expected behavior

To not fail on preflight.

Screen Shot 2020-12-18 at 4 59 07 PM

Your Environment

  • node version: 12
  • fastify version: >=3.0.0
  • os: Mac

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.12.9 to 12.12.10.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Cors header is missing if fastify schema validation fails

If fastify route has schema validation and the request will be invalid it will return fast 400 error without calling cors plugin and adding appropriate headers.

I don't know if it's even possible to fix current fastify request lifecycle, but probably you'll have an idea.

Here's test case.

test('Dynamic origin resolution (validation error)', t => {
  t.plan(4)

  const fastify = Fastify()
  const origin = (header, cb) => {
    return new Promise((resolve, reject) => {
      t.strictEqual(header, 'example.com')
      resolve(true)
    })
  }
  fastify.register(cors, { origin })

  fastify.get('/:id', {schema: {
    params: {
      id: {
        type: 'number',
        description: 'number'
      }
    }
  }}, (req, reply) => {
    reply.send('ok')
  })

  fastify.inject({
    method: 'GET',
    url: '/abc',
    headers: { origin: 'example.com' }
  }, (err, res) => {
    t.error(err)
    delete res.headers.date
    console.log(res.payload)
    t.strictEqual(res.statusCode, 400)
    t.deepEqual(JSON.parse(res.payload), {'statusCode': 400, 'error': 'Bad Request', 'message': 'params.id should be number'})
    t.deepEqual(res.headers, {
      'access-control-allow-origin': 'example.com',
      vary: 'Origin',
      'content-length': '79',
      'content-type': 'application/json; charset=utf-8',
      connection: 'keep-alive'
    })
  })
})

[5.0.0] new version giving preflight errors

🐛 Bug Report

I upgraded from 4.1.0 to 5.0.0 and now I'm getting errors in development (localhost). I can't really figure out what changed based on the release notes

To Reproduce

Steps to reproduce the behavior:

fastify.register(require('fastify-cors'), {
   origin: new RegExp('http://localhost'),
   credentials: true,
   optionsSuccessStatus: 200
})

Chrome throws the following error and returns a 401 status:

Access to XMLHttpRequest at 'http://localhost:3000/api/login' from origin 'http://localhost:8080' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I tried turning off preflight/strictPreFlight but no luck there.

Expected behavior

Local development still works just like in 4.1.0

Your Environment

  • node version: 14
  • fastify version: >= 3.8.0
  • os: Docker (linux)
  • any other relevant information

Configuring CORS Asynchronously

What are you trying to achieve or the steps to reproduce?

The "cors" library allows us to set the configuration asynchronously. I don't see any option to achieve it with fastify-cors.

Use case

I need cors headers in responses from my application, but in some cases, I don't want them, f. ex. when the request comes from the internal network.

TypeScript error

🐛 Bug Report

The type definition has some problem

To Reproduce

The following does not give ant type problem, but does not work

import fastifyCors from 'fastify-cors';
console.log(fastifyCors); // shows undefined
fastifyServer.register(fastifyCors);

the following works but I had to get rid of type by using as any

import * as fastifyCors from 'fastify-cors';
fastifyServer.register(fastifyCors as any);
  • *node version: 12
  • *fastify version: >=3.0.0
  • os: Linux

access-control-allow-origin always false

🐛 Bug Report

access-control-allow-origin always false and access-control-allow-methods not found on response headers

My configuration

app.register(require('fastify-cors'), {
    origin: ['https://juabali.com'],
    methods: ['GET', 'POST, 'PUT', 'PATCH', 'DELETE'],
    allowedHeaders: [
      'Authorization',
      'Content-Type',
      'User-Agent',
      // user device headers
      'X-Device-Brand',
      'X-Device-Model',
      'X-Device-Platform',
      'X-Device-OS',
      'X-Device-Token',
      // client info headers
      'X-Client-AppVersion',
      'X-Client-AppId',
      'X-Client-Id',
    ],
    credentials: true,
  });

Expected behavior

access-control-allow-originto be same at configuration

Result

➜ http localhost:3000

HTTP/1.1 200 OK
Connection: keep-alive
Date: Sat, 07 Dec 2019 19:03:48 GMT
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
access-control-allow-credentials: true
access-control-allow-origin: false
content-length: 43
content-type: application/json; charset=utf-8
etag: "1i9popv"
vary: Origin

{
    "name": "Juabali Turtle",
    "version": "0.0.1"
}

Your Environment

  • node version: 10.15.2
  • fastify version: 2.10.0
  • os: Linux

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.7.10 to 12.7.11.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

isRequestOriginAllowed function returning random (invalid) results when Regex is used

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.20.2

Plugin version

6.0.2

Node.js version

16.6.2

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

PopOS 20.04

Description

Every other request, the isRequestOriginAllowed function, will return an invalid result, in case a Regex is used.

The behaviour can be tracked back to this line in the code

The .test function is called, although this function retains state in the regex object. E.g. on first invocation, it will go through the regex until it is matched, and return the result. On second invocation, it will go through the remainder of the regex and reset, returning a wrong result. Then on the third invocation it produces the right result again. This behaviour is also described on the MDN page of the function:

As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.

Steps to Reproduce

Initialize the plugin with a Regex or list of regexes:

fastify.register(require('fastify-cors'), {
    origin: new RegExp('floodtags.com', 'gi'),
    methods: ['OPTIONS', 'GET', 'POST'],
    credentials: true,
    allowedHeaders: ['Authorization'],
  });

Now every other request from e.g. https://www.floodtags.com/ will not get the correct Access-Control-Allow-Origin header

Expected Behavior

The 'isRequestOriginAllowed' should return the same result on every invocation.

This can be achieved by e.g. using the String.match function instead of Regex.test. I can submit a pull-request for this if needed, please let me know!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.