0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-27 21:39:16 -05:00
logto/packages/core/src/middleware/koa-cors.ts
2023-03-03 14:11:19 +08:00

40 lines
1.1 KiB
TypeScript

import cors from '@koa/cors';
import type { UrlSet } from '@logto/shared';
import type { MiddlewareType } from 'koa';
import { EnvSet } from '#src/env-set/index.js';
export default function koaCors<StateT, ContextT, ResponseBodyT>(
...urlSets: UrlSet[]
): MiddlewareType<StateT, ContextT, ResponseBodyT> {
return cors({
origin: (ctx) => {
const { origin } = ctx.request.headers;
if (
origin &&
urlSets.some((set) => {
const deduplicated = set.deduplicated();
// The URL Set has only one endpoint available, just use that endpoint.
if (deduplicated.length <= 1) {
return deduplicated.some((url) => url.origin === origin);
}
// For multiple endpoints, should filter out localhost in production.
return deduplicated.some(
(url) =>
url.origin === origin &&
// Disable localhost CORS in production since it's unsafe
!(EnvSet.values.isProduction && url.hostname === 'localhost')
);
})
) {
return origin;
}
return '';
},
exposeHeaders: '*',
});
}