CORS: merge requested headers into allow-headers for preflight and responses
Some checks failed
armco-org/node-starter-kit/pipeline/head There was a failure building this commit

This commit is contained in:
2026-02-03 20:20:03 +05:30
parent 9635e4630a
commit c918e8a291

View File

@@ -444,8 +444,21 @@ export async function initCors(app: Application, config: CorsConfig, logger?: Lo
const { allowed, isPublic, credentials } = await isOriginAllowedAsync(origin, requestPath, req)
if (allowed) {
setCorsHeaders(res, origin, isPublic, credentials, override)
res.status(204).end()
setCorsHeaders(res, origin, isPublic, credentials, override)
// Merge any Access-Control-Request-Headers into the response's Access-Control-Allow-Headers
try {
const acrh = req.headers['access-control-request-headers']
if (acrh) {
const existing = (res.getHeader && res.getHeader('Access-Control-Allow-Headers')) || ''
const existingArr = (existing && String(existing).split(',').map(h => h.trim()).filter(Boolean)) || []
const requestedArr = String(acrh).split(',').map(h => h.trim()).filter(Boolean)
const combined = Array.from(new Set(existingArr.concat(requestedArr)))
res.setHeader('Access-Control-Allow-Headers', combined.join(','))
}
} catch (e) {
// swallow errors — header merging is best-effort for preflight
}
res.status(204).end()
return
} else {
// Still return 204 but without CORS headers (browser will block)
@@ -458,7 +471,20 @@ export async function initCors(app: Application, config: CorsConfig, logger?: Lo
const { allowed, isPublic, credentials } = await isOriginAllowedAsync(origin, requestPath, req)
if (allowed) {
setCorsHeaders(res, origin, isPublic, credentials, override)
setCorsHeaders(res, origin, isPublic, credentials, override)
// Ensure any runtime-requested headers are present on actual responses as well
try {
const acrh = req.headers['access-control-request-headers']
if (acrh) {
const existing = (res.getHeader && res.getHeader('Access-Control-Allow-Headers')) || ''
const existingArr = (existing && String(existing).split(',').map(h => h.trim()).filter(Boolean)) || []
const requestedArr = String(acrh).split(',').map(h => h.trim()).filter(Boolean)
const combined = Array.from(new Set(existingArr.concat(requestedArr)))
res.setHeader('Access-Control-Allow-Headers', combined.join(','))
}
} catch (e) {
// best-effort
}
}
next()