{"id":13539343,"url":"https://github.com/cyu/rack-cors","last_synced_at":"2025-05-12T05:28:30.342Z","repository":{"id":929434,"uuid":"698944","full_name":"cyu/rack-cors","owner":"cyu","description":"Rack Middleware for handling Cross-Origin Resource Sharing (CORS), which makes cross-origin AJAX possible.","archived":false,"fork":false,"pushed_at":"2025-01-13T20:17:49.000Z","size":673,"stargazers_count":3288,"open_issues_count":38,"forks_count":261,"subscribers_count":40,"default_branch":"master","last_synced_at":"2025-05-12T04:06:56.206Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cyu.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2010-06-02T10:14:29.000Z","updated_at":"2025-05-11T15:30:25.000Z","dependencies_parsed_at":"2023-07-05T15:17:07.390Z","dependency_job_id":"60b4784b-4791-424a-85f9-b38a1b0e0bd0","html_url":"https://github.com/cyu/rack-cors","commit_stats":{"total_commits":256,"total_committers":76,"mean_commits":"3.3684210526315788","dds":0.73828125,"last_synced_commit":"0e68b881ef6c428bbf928b2c4a92ab49a34823e3"},"previous_names":[],"tags_count":29,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cyu%2Frack-cors","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cyu%2Frack-cors/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cyu%2Frack-cors/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cyu%2Frack-cors/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cyu","download_url":"https://codeload.github.com/cyu/rack-cors/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253680863,"owners_count":21946662,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T09:01:23.745Z","updated_at":"2025-05-12T05:28:30.315Z","avatar_url":"https://github.com/cyu.png","language":"JavaScript","readme":"# Rack CORS Middleware [![Build Status](https://github.com/cyu/rack-cors/actions/workflows/ci.yaml/badge.svg)](https://github.com/cyu/rack-cors/actions)\n\n`Rack::Cors` provides support for Cross-Origin Resource Sharing (CORS) for Rack compatible web applications.\n\nThe [CORS spec](http://www.w3.org/TR/cors/) allows web applications to make cross domain AJAX calls without using workarounds such as JSONP. See [further explanations on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)\n\n## Installation\n\nInstall the gem:\n\n`gem install rack-cors`\n\nOr in your Gemfile:\n\n```ruby\ngem 'rack-cors'\n```\n\n\n## Configuration\n\n### Rails Configuration\nFor Rails, you'll need to add this middleware on application startup. A practical way to do this is with an initializer file. For example, the following will allow GET, POST, PATCH, or PUT requests from any origin on any resource:\n\n```ruby\n# config/initializers/cors.rb\n\nRails.application.config.middleware.insert_before 0, Rack::Cors do\n  allow do\n    origins '*'\n    resource '*', headers: :any, methods: [:get, :post, :patch, :put]\n  end\nend\n```\n\nNOTE: If you create application with `--api` option, configuration is automatically generated in `config/initializers/cors.rb`.\n\nWe use `insert_before` to make sure `Rack::Cors` runs at the beginning of the stack to make sure it isn't interfered with by other middleware (see `Rack::Cache` note in **Common Gotchas** section). Basic setup examples for Rails 5 \u0026 Rails 6 can be found in the examples/ directory.\n\nSee The [Rails Guide to Rack](http://guides.rubyonrails.org/rails_on_rack.html) for more details on rack middlewares or watch the [railscast](http://railscasts.com/episodes/151-rack-middleware).\n\nRead more about it here in the [Rails Guides](https://guides.rubyonrails.org/configuring.html#configuring-middleware)\n\n### Rack Configuration\n\nNOTE: If you're running Rails, adding `config/initializers/cors.rb` should be enough.  There is no need to update `config.ru` as well.\n\nIn `config.ru`, configure `Rack::Cors` by passing a block to the `use` command:\n\n```ruby\nuse Rack::Cors do\n  allow do\n    origins 'localhost:3000', '127.0.0.1:3000',\n            /\\Ahttp:\\/\\/192\\.168\\.0\\.\\d{1,3}(:\\d+)?\\z/\n            # regular expressions can be used here\n\n    resource '/file/list_all/', :headers =\u003e 'x-domain-token'\n    resource '/file/at/*',\n        methods: [:get, :post, :delete, :put, :patch, :options, :head],\n        headers: 'x-domain-token',\n        expose: ['Some-Custom-Response-Header'],\n        max_age: 600\n        # headers to expose\n  end\n\n  allow do\n    origins '*'\n    resource '/public/*', headers: :any, methods: :get\n\n    # Only allow a request for a specific host\n    resource '/api/v1/*',\n        headers: :any,\n        methods: :get,\n        if: proc { |env| env['HTTP_HOST'] == 'api.example.com' }\n  end\nend\n```\n\n### Configuration Reference\n\n#### Middleware Options\n* **debug** (boolean):  Enables debug logging and `X-Rack-CORS` HTTP headers for debugging.\n* **logger** (Object or Proc): Specify the logger to log to.  If a proc is provided, it will be called when a logger is needed.  This is helpful in cases where the logger is initialized after `Rack::Cors` is initially configured, like `Rails.logger`.\n\n#### Origin\nOrigins can be specified as a string, a regular expression, or as '\\*' to allow all origins.\n\n**\\*SECURITY NOTE:** Be careful when using regular expressions to not accidentally be too inclusive.  For example, the expression `/https:\\/\\/example\\.com/` will match the domain *example.com.randomdomainname.co.uk*.  It is recommended that any regular expression be enclosed with start \u0026 end string anchors, like `\\Ahttps:\\/\\/example\\.com\\z`.\n\nAdditionally, origins can be specified dynamically via a block of the following form:\n```ruby\n  origins { |source, env| true || false }\n```\n\nA Resource path can be specified as exact string match (`/path/to/file.txt`) or with a '\\*' wildcard (`/all/files/in/*`).  A resource can take the following options:\n\n* **methods** (string or array or `:any`): The HTTP methods allowed for the resource.\n* **headers** (string or array or `:any`): The HTTP headers that will be allowed in the CORS resource request.  Use `:any` to allow for any headers in the actual request.\n* **expose** (string or array): The HTTP headers in the resource response can be exposed to the client.\n* **credentials** (boolean, default: `false`): Sets the `Access-Control-Allow-Credentials` response header. **Note:** If a wildcard (`*`) origin is specified, this option cannot be set to `true`.  Read this [security article](http://web-in-security.blogspot.de/2017/07/cors-misconfigurations-on-large-scale.html) for more information.\n* **max_age** (number): Sets the `Access-Control-Max-Age` response header.\n* **if** (Proc): If the result of the proc is true, will process the request as a valid CORS request.\n* **vary** (string or array): A list of HTTP headers to add to the 'Vary' header.\n\n\n## Common Gotchas\n\n### Origin Matching\n\n* When specifying an origin, make sure that it does not have a trailing slash.\n\n* When specifying an HTTP origin that uses the scheme's default port (e.g. `http://example.test:80`), some clients may not strip the port which could result in unexpected blocked requests (additional context [here](https://github.com/request/request/pull/2904)).\n\n### Testing Postman and/or cURL\n\n* Make sure you're passing in an `Origin:` header.  That header is required to trigger a CORS response.  Here's [a good SO post](https://stackoverflow.com/questions/12173990/how-can-you-debug-a-cors-request-with-curl) about using cURL for testing CORS.\n* Make sure your origin does not have a trailing slash.\n\n### Positioning in the Middleware Stack\n\nPositioning of `Rack::Cors` in the middleware stack is very important. In the Rails example above we put it above all other middleware which, in our experience, provides the most consistent results.\n\nHere are some scenarios where incorrect positioning have created issues:\n\n* **Serving static files.**  Insert before `ActionDispatch::Static` so that static files are served with the proper CORS headers.  **NOTE:** this might not work in production as static files are usually served from the web server (Nginx, Apache) and not the Rails container.\n\n* **Caching in the middleware.**  Insert before `Rack::Cache` so that the proper CORS headers are written and not cached ones.\n\n* **Authentication via Warden**  Warden will return immediately if a resource that requires authentication is accessed without authentication.  If `Warden::Manager`is in the stack before `Rack::Cors`, it will return without the correct CORS headers being applied, resulting in a failed CORS request.\n\nYou can run the following command to see what the middleware stack looks like:\n\n```bash\nbundle exec rails middleware\n```\n\nNote that the middleware stack is different in production.  For example, the `ActionDispatch::Static` middleware will not be part of the stack if `config.serve_static_assets = false`.  You can run this to see what your middleware stack looks like in production:\n\n```bash\nRAILS_ENV=production bundle exec rails middleware\n```\n\n### Serving static files\n\nIf you trying to serve CORS headers on static assets (like CSS, JS, Font files), keep in mind that static files are usually served directly from web servers and never runs through the Rails container (including the middleware stack where `Rack::Cors` resides).\n\nIn Heroku, you can serve static assets through the Rails container by setting `config.serve_static_assets = true` in `production.rb`.\n\n### Custom Protocols (chrome-extension://, ionic://, etc.)\n\nPrior to 2.0.0, `http://`, `https://`, and `file://` are the only protocols supported in the `origins` list. If you wish to specify an origin that\nhas a custom protocol (`chrome-extension://`, `ionic://`, etc.) simply exclude the protocol. [See issue.](https://github.com/cyu/rack-cors/issues/100)\n\nFor example, instead of specifying `chrome-extension://aomjjhallfgjeglblehebfpbcfeobpga` specify `aomjjhallfgjeglblehebfpbcfeobpga` in `origins`.\n\nAs of 2.0.0 (currently in RC1), you can specify origins with a custom protocol.\n\n### Rails 6 Host Matching\n\nRails 6 will block requests from unauthorized hosts, and this issue can be confused as a CORS related error. So in development, if you're making requests using something other than localhost or 127.0.0.1, make sure the server host has been authorized. [More info here](https://guides.rubyonrails.org/configuring.html#actiondispatch-hostauthorization)\n","funding_links":[],"categories":["\u003ca id=\"683b645c2162a1fce5f24ac2abfa1973\"\u003e\u003c/a\u003e漏洞\u0026\u0026漏洞管理\u0026\u0026漏洞发现/挖掘\u0026\u0026漏洞开发\u0026\u0026漏洞利用\u0026\u0026Fuzzing","JavaScript","Uncategorized","HTTP Clients and tools","Middleware"],"sub_categories":["\u003ca id=\"13fb2b7d1617dd6e0f503f52b95ba86b\"\u003e\u003c/a\u003eCORS","Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcyu%2Frack-cors","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcyu%2Frack-cors","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcyu%2Frack-cors/lists"}