Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions plugins/cors/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Changelog

## [3.0.1](https://github.com/eggjs/egg-cors/compare/v3.0.0...v3.0.1) (2024-04-25)


### Bug Fixes

* let framework known app has custom origin handler or not ([#28](https://github.com/eggjs/egg-cors/issues/28)) ([#29](https://github.com/eggjs/egg-cors/issues/29)) ([b446a98](https://github.com/eggjs/egg-cors/commit/b446a987ee66c38ac07458a5d69992f5a43071a2))

## [3.0.0](https://github.com/eggjs/egg-cors/compare/v2.2.3...v3.0.0) (2023-12-11)


### ⚠ BREAKING CHANGES

* drop Node.js < 14

### Features

* use @koa/cors@5.0.0 ([#27](https://github.com/eggjs/egg-cors/issues/27)) ([599e918](https://github.com/eggjs/egg-cors/commit/599e918f18f65c47e41ebf30d659ae439e10207d))

2.2.3 / 2019-11-14
==================

**fixes**
* [[`7990aa7`](http://github.com/eggjs/egg-cors/commit/7990aa7c92fa2c82bb6e9018b7191852879f1569)] - fix: use new URL instead of url.parse (#22) (Yiyu He <<dead_horse@qq.com>>)

2.2.2 / 2019-10-25
==================

**fixes**
* [[`74e8c26`](http://github.com/eggjs/egg-cors/commit/74e8c264ddbc3aa4b926efa7696a310ef3dabe71)] - fix: should also check origin with port (#21) (Yelmor <<yelmor@outlook.com>>)

**others**
* [[`53ffc7e`](http://github.com/eggjs/egg-cors/commit/53ffc7ec2cb4d119dc2e6b76bbccb0ed7a3712e9)] - chore: update travis (TZ | 天猪 <<atian25@qq.com>>)

2.2.1 / 2019-10-22
==================

**fixes**
* [[`499c2b1`](http://github.com/eggjs/egg-cors/commit/499c2b1cd730b4a9d5d7811946661cc9b475326d)] - fix: second-level domain and port support misjudgement (#20) (Khaidi Chu <<i@2333.moe>>)

2.2.0 / 2019-03-11
==================

**features**
* [[`30a1b8c`](http://github.com/eggjs/egg-cors/commit/30a1b8c8cf58cacd208f86905d334588db523b8e)] - feat: use koa/cors@3, support options.origin to be async function (#19) (Yiyu He <<dead_horse@qq.com>>)

2.1.2 / 2018-11-30
==================

* chore: typings of origin params (#18)

2.1.1 / 2018-10-01
==================

* deps: update (#17)
* chore: add types of cors option. (#15)
* docs: update readme (#16)

2.1.0 / 2018-07-11
==================

**others**
* [[`ff8b7da`](http://github.com/eggjs/egg-cors/commit/ff8b7dab9c9acff5f5319ecca1fe0df5d1ebfaf8)] - chore(typings): add interface Config['cors'] (#12) (waiting <<waiting@xiaozhong.biz>>)

2.0.0 / 2017-11-23
==================

**others**
* [[`120639f`](http://github.com/eggjs/egg-cors/commit/120639fb784ed1ea71eff071124d3f242b52ab72)] - refactor: use async function and support egg@2 (#9) (Yiyu He <<dead_horse@qq.com>>)

1.2.0 / 2017-07-24
==================

* deps: update deps (#8)
* feat: add config for Access-Control-Allow-Origin (#7)

1.1.0 / 2017-03-24
==================

* feat: update to egg@1.0 and docs fix (#6)
* fix: adjust with new test (#4)

1.0.0 / 2016-11-04
==================

* chore: update deps and test on node v7 (#3)
* doc: add configuration information on how to pass in domain whitelist (#2)
* test: add tests (#1)

0.0.2 / 2016-07-15
==================

* init
21 changes: 21 additions & 0 deletions plugins/cors/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) Alibaba Group Holding Limited and other contributors.

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.
86 changes: 86 additions & 0 deletions plugins/cors/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# @eggjs/cors

[![NPM version][npm-image]][npm-url]
[![Known Vulnerabilities][snyk-image]][snyk-url]
[![npm download][download-image]][download-url]
[![Node.js Version](https://img.shields.io/node/v/@eggjs/cors.svg?style=flat)](https://nodejs.org/en/download/)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com)

[npm-image]: https://img.shields.io/npm/v/@eggjs/cors.svg?style=flat-square
[npm-url]: https://npmjs.org/package/@eggjs/cors
[snyk-image]: https://snyk.io/test/npm/@eggjs/cors/badge.svg?style=flat-square
[snyk-url]: https://snyk.io/test/npm/@eggjs/cors
[download-image]: https://img.shields.io/npm/dm/@eggjs/cors.svg?style=flat-square
[download-url]: https://npmjs.org/package/@eggjs/cors

[CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) plugin for egg, based on [@koa/cors](https://github.com/koajs/cors).

## Install

```bash
$ npm i @eggjs/cors --save
```

## Usage

```ts
// {app_root}/config/plugin.ts
import corsPlugin from '@eggjs/cors';

export default {
...corsPlugin(),
};
```

`@eggjs/cors` works internally with [@eggjs/security](https://github.com/eggjs/egg/tree/next/plugins/security). By defining the property of `domainWhiteList` on object `security`, you have successfully informed the framework to whitelist the passed domains.

When you make a request from client side, **egg** should return an `Access-Control-Allow-Origin` response header with the domain that you passed in along with the payload and status code _200_.

```ts
// {app_root}/config/config.default.ts
export default {
security: {
domainWhiteList: ['http://localhost:4200'],
},
};
```

## Configuration

Support all configurations in [@koa/cors](https://github.com/koajs/cors).

```ts
// {app_root}/config/config.default.ts
export default {
cors: {
// {string|Function} origin: '*',
// {string|Array} allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
},
};
```

If the `origin` is set, the plugin will follow it to set the `Access-Control-Allow-Origin` and ignore the `security.domainWhiteList`. Otherwise, the `security.domainWhiteList` which is default will take effect as described above.

## Security

Only in safe domain list support CORS when security plugin enabled.

## Questions & Suggestions

Please open an issue [here](https://github.com/eggjs/egg/issues).

## License

[MIT](LICENSE)

<!-- GITCONTRIBUTOR_START -->

## Contributors

| [<img src="https://avatars.githubusercontent.com/u/227713?v=4" width="100px;"/><br/><sub><b>atian25</b></sub>](https://github.com/atian25)<br/> | [<img src="https://avatars.githubusercontent.com/u/985607?v=4" width="100px;"/><br/><sub><b>dead-horse</b></sub>](https://github.com/dead-horse)<br/> | [<img src="https://avatars.githubusercontent.com/u/156269?v=4" width="100px;"/><br/><sub><b>fengmk2</b></sub>](https://github.com/fengmk2)<br/> | [<img src="https://avatars.githubusercontent.com/u/3139237?v=4" width="100px;"/><br/><sub><b>brickyang</b></sub>](https://github.com/brickyang)<br/> | [<img src="https://avatars.githubusercontent.com/u/3297859?v=4" width="100px;"/><br/><sub><b>sinchang</b></sub>](https://github.com/sinchang)<br/> | [<img src="https://avatars.githubusercontent.com/u/2842176?v=4" width="100px;"/><br/><sub><b>XadillaX</b></sub>](https://github.com/XadillaX)<br/> |
| :---------------------------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------: |
| [<img src="https://avatars.githubusercontent.com/u/1148428?v=4" width="100px;"/><br/><sub><b>mattma</b></sub>](https://github.com/mattma)<br/> | [<img src="https://avatars.githubusercontent.com/u/20397245?v=4" width="100px;"/><br/><sub><b>SoraYama</b></sub>](https://github.com/SoraYama)<br/> | [<img src="https://avatars.githubusercontent.com/u/9161488?v=4" width="100px;"/><br/><sub><b>Yelmor</b></sub>](https://github.com/Yelmor)<br/> | [<img src="https://avatars.githubusercontent.com/u/6895141?v=4" width="100px;"/><br/><sub><b>angela-1</b></sub>](https://github.com/angela-1)<br/> | [<img src="https://avatars.githubusercontent.com/u/1763067?v=4" width="100px;"/><br/><sub><b>waitingsong</b></sub>](https://github.com/waitingsong)<br/> |

This project follows the git-contributor [spec](https://github.com/xudafeng/git-contributor), auto updated at `Mon Dec 11 2023 13:25:00 GMT+0800`.

<!-- GITCONTRIBUTOR_END -->
68 changes: 68 additions & 0 deletions plugins/cors/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
{
"name": "@eggjs/cors",
"version": "4.0.2-beta.26",
"description": "cors support for egg",
"keywords": [
"cors",
"egg",
"egg-plugin",
"eggPlugin"
],
"homepage": "https://github.com/eggjs/egg/tree/next/plugins/cors",
"bugs": {
"url": "https://github.com/eggjs/egg/issues"
},
"license": "MIT",
"author": "dead-horse",
"repository": {
"type": "git",
"url": "git+https://github.com/eggjs/egg.git",
"directory": "plugins/cors"
},
"files": [
"dist"
],
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": "./src/index.ts",
"./app": "./src/app.ts",
"./app/middleware/cors": "./src/app/middleware/cors.ts",
"./config/config.default": "./src/config/config.default.ts",
"./types": "./src/types.ts",
"./package.json": "./package.json"
},
"publishConfig": {
"access": "public",
"exports": {
".": "./dist/index.js",
"./app": "./dist/app.js",
"./app/middleware/cors": "./dist/app/middleware/cors.js",
"./config/config.default": "./dist/config/config.default.js",
"./types": "./dist/types.js",
"./package.json": "./package.json"
}
},
"scripts": {
"typecheck": "tsgo --noEmit"
},
"dependencies": {
"@koa/cors": "catalog:"
},
"devDependencies": {
"@eggjs/mock": "workspace:*",
"@eggjs/security": "workspace:*",
"@types/koa__cors": "catalog:",
"@types/node": "catalog:",
"egg": "workspace:*",
"typescript": "catalog:"
},
"peerDependencies": {
"egg": "workspace:*"
},
"engines": {
"node": ">=22.18.0"
}
}
45 changes: 45 additions & 0 deletions plugins/cors/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type { Application, Context, ILifecycleBoot } from 'egg';

export default class AppBoot implements ILifecycleBoot {
private readonly app;

constructor(app: Application) {
this.app = app;
}

configWillLoad(): void {
const app = this.app;
// put before other core middlewares
app.config.coreMiddleware.unshift('cors');

const corsConfig = app.config.cors;
if (!corsConfig) return;

// if the security plugin is enabled and no `origin` config is provided,
// only safe domains are allowed to support CORS.
corsConfig.hasCustomOriginHandler = !!corsConfig.origin;
if (corsConfig.origin) return;

corsConfig.origin = function corsOrigin(ctx: Context) {
// origin is {protocol}{hostname}{port}...
// `ctx.get()` may return `string[]` for repeated headers
const rawOrigin = ctx.get('origin');
const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin;
if (!origin) return '';

if (typeof ctx.isSafeDomain !== 'function') return origin;

let parsedUrl: URL;
try {
parsedUrl = new URL(origin);
} catch {
return '';
}

if (ctx.isSafeDomain(parsedUrl.hostname) || ctx.isSafeDomain(origin)) {
return origin;
}
return '';
};
}
}
3 changes: 3 additions & 0 deletions plugins/cors/src/app/middleware/cors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import cors from '@koa/cors';

export default cors;
62 changes: 62 additions & 0 deletions plugins/cors/src/config/config.default.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import type { Context, PartialEggConfig } from 'egg';

export interface CorsConfig {
/**
* `Access-Control-Allow-Origin`, default to the request `Origin` header.
*
* When the `security` plugin is enabled and no custom `origin` is provided,
* only safe domains are allowed.
*/
origin?: string | ((ctx: Context) => string | PromiseLike<string>);
/**
* `Access-Control-Allow-Methods`
*/
allowMethods?: string | string[];
/**
* `Access-Control-Expose-Headers`
*/
exposeHeaders?: string | string[];
/**
* `Access-Control-Allow-Headers`
*/
allowHeaders?: string | string[];
/**
* `Access-Control-Max-Age` in seconds
*/
maxAge?: string | number;
/**
* `Access-Control-Allow-Credentials`
*/
credentials?: boolean | ((ctx: Context) => boolean | PromiseLike<boolean>);
/**
* Add CORS headers to error responses as well
*/
keepHeadersOnError?: boolean;
/**
* `Access-Control-Allow-Private-Network`
*/
privateNetworkAccess?: boolean;
/**
* Set to `true` to add `Cross-Origin-Opener-Policy` and
* `Cross-Origin-Embedder-Policy` headers
*/
secureContext?: boolean;
/**
* Set to `true` to skip `Access-Control-Allow-Origin` when the request has
* no `Origin` header
*/
allowAllOrigins?: boolean;
/**
* Whether the user supplied a custom `origin` handler.
*
* Filled in automatically by the plugin, do not set this manually.
* @private
*/
hasCustomOriginHandler?: boolean;
}

const config: PartialEggConfig = {
cors: {},
};

export default config;
Loading