feat(server): make CORS middleware configurable (#5123)
* feat(server): make CORS middleware configurable Add detailed configuration options for CORS in config.yaml, including origin, methods, headers, credentials, and max age. Update server initialization to apply these settings dynamically instead of using hardcoded values. * fix(server): Fix default value and conditional logic issues in CORS configuration - Changed the default value of `cors.maxAge` from `null` to `0`. - Simplified the conditional check logic for `allowedHeaders`, removing duplicate checks for `corsAllowedHeaders` being `null`. * fix(server): Fix CORS exposed headers configuration logic - Removed redundant conditional checks. now directly validates array length when `corsExposedHeaders` has a truthy value * Improve types + simplify checks * fix(cors): align maxAge default with original behavior * Adjust default array values * Remove debug log --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
This commit is contained in:
+25
-5
@@ -103,12 +103,32 @@ app.use(bodyParser.json({ limit: '500mb' }));
|
||||
app.use(bodyParser.urlencoded({ extended: true, limit: '500mb' }));
|
||||
|
||||
// CORS Settings //
|
||||
const CORS = cors({
|
||||
origin: 'null',
|
||||
methods: ['OPTIONS'],
|
||||
});
|
||||
const corsEnabled = getConfigValue('cors.enabled', true, 'boolean');
|
||||
if (corsEnabled) {
|
||||
const corsOrigin = getConfigValue('cors.origin', 'null');
|
||||
const corsMethods = getConfigValue('cors.methods', ['OPTIONS']);
|
||||
const corsAllowedHeaders = getConfigValue('cors.allowedHeaders', []);
|
||||
const corsExposedHeaders = getConfigValue('cors.exposedHeaders', []);
|
||||
const corsCredentials = getConfigValue('cors.credentials', false, 'boolean');
|
||||
const corsMaxAge = getConfigValue('cors.maxAge', null, 'number');
|
||||
|
||||
app.use(CORS);
|
||||
/** @type {cors.CorsOptions} */
|
||||
const corsOptions = {
|
||||
origin: corsOrigin,
|
||||
methods: corsMethods,
|
||||
credentials: corsCredentials,
|
||||
};
|
||||
if (Array.isArray(corsAllowedHeaders) && corsAllowedHeaders.length > 0) {
|
||||
corsOptions.allowedHeaders = corsAllowedHeaders;
|
||||
}
|
||||
if (Array.isArray(corsExposedHeaders) && corsExposedHeaders.length > 0) {
|
||||
corsOptions.exposedHeaders = corsExposedHeaders;
|
||||
}
|
||||
if (corsMaxAge !== null && Number.isInteger(corsMaxAge)) {
|
||||
corsOptions.maxAge = corsMaxAge;
|
||||
}
|
||||
app.use(cors(corsOptions));
|
||||
}
|
||||
|
||||
if (cliArgs.listen && cliArgs.basicAuthMode) {
|
||||
app.use(basicAuthMiddleware);
|
||||
|
||||
Reference in New Issue
Block a user