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

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

## Install

```bash
npm install @eggjs/cors
```

## Usage

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

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

When no custom `origin` is configured, the plugin uses the Security plugin's
`domainWhiteList`. Without the Security plugin, the request origin is allowed.

## Configuration

All [@koa/cors options](https://github.com/koajs/cors#corsoptions) are supported.

```ts
// config/config.default.ts
export default {
cors: {
origin: 'https://example.com',
credentials: true,
},
};
```

A custom `origin` takes precedence over `security.domainWhiteList`.

## License

[MIT](LICENSE)
67 changes: 67 additions & 0 deletions plugins/cors/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
{
"name": "@eggjs/cors",
"version": "4.0.0-beta.26",
"description": "CORS plugin for Egg",
"keywords": [
"cors",
"egg",
"egg-plugin"
],
"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:",
"@types/koa__cors": "catalog:"
},
"devDependencies": {
"@eggjs/mock": "workspace:*",
"@eggjs/tsconfig": "workspace:*",
"@types/node": "catalog:",
"egg": "workspace:*",
"typescript": "catalog:"
},
"peerDependencies": {
"egg": "workspace:*"
},
"engines": {
"node": ">=22.18.0"
}
}
40 changes: 40 additions & 0 deletions plugins/cors/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { Application, Context, ILifecycleBoot } from 'egg';
import type { Context as KoaContext } from 'koa';

export default class AppBoot implements ILifecycleBoot {
#app: Application;

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

configWillLoad(): void {
const { config } = this.#app;
const coreMiddleware = config.coreMiddleware;
for (let index = coreMiddleware.lastIndexOf('cors'); index >= 0; index = coreMiddleware.lastIndexOf('cors')) {
coreMiddleware.splice(index, 1);
}
coreMiddleware.unshift('cors');

config.cors.hasCustomOriginHandler = Boolean(config.cors.origin);
config.cors.origin ??= function corsOrigin(ctx: KoaContext): string {
const origin = ctx.get('origin');
if (!origin) return '';

const eggContext = ctx as unknown as Context;
if (typeof eggContext.isSafeDomain !== 'function') return origin;

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

if (eggContext.isSafeDomain(parsedUrl.hostname) || eggContext.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;
10 changes: 10 additions & 0 deletions plugins/cors/src/config/config.default.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { Options as KoaCorsOptions } from '@koa/cors';

export interface CorsConfig extends KoaCorsOptions {
/** Whether the application supplied its own origin handler. */
hasCustomOriginHandler?: boolean;
}

export default {
cors: {} as CorsConfig,
};
14 changes: 14 additions & 0 deletions plugins/cors/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import './types.ts';
import { definePluginFactory, type EggPluginFactory } from 'egg';

/**
* CORS plugin.
*
* @since 4.1.0
*/
export default definePluginFactory({
name: 'cors',
enable: true,
path: import.meta.dirname,
optionalDependencies: ['security'],
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}) as EggPluginFactory;
7 changes: 7 additions & 0 deletions plugins/cors/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { CorsConfig } from './config/config.default.ts';

declare module 'egg' {
interface EggAppConfig {
cors: CorsConfig;
}
}
144 changes: 144 additions & 0 deletions plugins/cors/test/cors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { strict as assert } from 'node:assert';
import path from 'node:path';

import { mm, type MockApplication } from '@eggjs/mock';
import type { Application } from 'egg';
import { afterAll, afterEach, beforeAll, describe, it } from 'vitest';

import AppBoot from '../src/app.ts';

function createApp(name: string): MockApplication {
return mm.app({
baseDir: path.join(import.meta.dirname, 'fixtures', 'apps', name),
});
}

describe('@eggjs/cors', () => {
let app: MockApplication;

beforeAll(async () => {
app = createApp('cors');
await app.ready();
});
afterAll(() => app.close());
afterEach(() => mm.restore());

it('does not set an origin header when the request has no origin', async () => {
await app
.httpRequest()
.get('/')
.expect({ foo: 'bar' })
.expect((res) => assert.equal(res.headers['access-control-allow-origin'], undefined))
.expect(200);
});

it('allows origins in the security domain whitelist', async () => {
await app
.httpRequest()
.get('/')
.set('Origin', 'http://test.eggjs.org')
.expect('Access-Control-Allow-Origin', 'http://test.eggjs.org')
.expect('Access-Control-Allow-Credentials', 'true')
.expect(200);

await app
.httpRequest()
.get('/')
.set('Origin', 'https://b.com:1234')
.expect('Access-Control-Allow-Origin', 'https://b.com:1234')
.expect(200);
});

it('rejects origins outside the security domain whitelist', async () => {
await app
.httpRequest()
.get('/')
.set('Origin', 'http://eggjs.org!.evil.com')
.expect((res) => {
assert.equal(res.headers['access-control-allow-origin'], undefined);
assert.equal(res.headers['access-control-allow-credentials'], undefined);
})
.expect(200);
});
});

describe('@eggjs/cors middleware registration', () => {
it('moves an existing cors middleware to the front without duplicating it', () => {
const coreMiddleware = ['bodyParser', 'cors', 'overrideMethod', 'cors'];
const app = {
config: {
coreMiddleware,
cors: {},
},
} as unknown as Application;

new AppBoot(app).configWillLoad();

assert.deepEqual(coreMiddleware, ['cors', 'bodyParser', 'overrideMethod']);
});
});

describe('@eggjs/cors with a string origin', () => {
let app: MockApplication;

beforeAll(async () => {
app = createApp('cors-origin');
await app.ready();
});
afterAll(() => app.close());
afterEach(() => mm.restore());

it('uses the configured origin instead of the whitelist', async () => {
await app
.httpRequest()
.get('/')
.set('Origin', 'http://not-in-the-whitelist.example')
.expect('Access-Control-Allow-Origin', 'eggjs.org')
.expect('Access-Control-Allow-Credentials', 'true')
.expect(200);
});
});

describe('@eggjs/cors with an origin function', () => {
let app: MockApplication;

beforeAll(async () => {
app = createApp('cors-origin-function');
await app.ready();
});
afterAll(() => app.close());
afterEach(() => mm.restore());

it('marks and invokes the custom origin handler', async () => {
await app.httpRequest().get('/config').expect({ hasCustomOriginHandler: true }).expect(200);
await app
.httpRequest()
.get('/')
.set('Origin', 'http://example.com')
.expect('Access-Control-Allow-Origin', 'eggjs.org')
.expect(200);
});
});

describe('@eggjs/cors private network access', () => {
let app: MockApplication;

beforeAll(async () => {
app = createApp('cors-private-network');
await app.ready();
});
afterAll(() => app.close());
afterEach(() => mm.restore());

it('sets the private network header on a preflight request', async () => {
await app
.httpRequest()
.options('/')
.set('Origin', 'https://eggjs.org')
.set('Access-Control-Request-Method', 'POST')
.set('Access-Control-Request-Private-Network', 'true')
.expect('Access-Control-Allow-Origin', 'https://eggjs.org')
.expect('Access-Control-Allow-Private-Network', 'true')
.expect(204);
});
});
10 changes: 10 additions & 0 deletions plugins/cors/test/fixtures/apps/cors-origin-function/app/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = (app) => {
app.get('/', async (ctx) => {
ctx.body = { foo: 'bar' };
});
app.get('/config', async (ctx) => {
ctx.body = {
hasCustomOriginHandler: ctx.app.config.cors.hasCustomOriginHandler,
};
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
exports.keys = 'cors-origin-function-test';
exports.cors = {
async origin(ctx) {
if (!ctx.get('origin')) return '';
return 'eggjs.org';
},
credentials: true,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import corsPlugin from '../../../../../src/index.ts';

module.exports = {
...corsPlugin(),
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "cors-origin-function-test"
}
5 changes: 5 additions & 0 deletions plugins/cors/test/fixtures/apps/cors-origin/app/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = (app) => {
app.get('/', async (ctx) => {
ctx.body = { foo: 'bar' };
});
};
Loading