chore: Normalize Origin header in CORS middleware dan update test_cors

This commit is contained in:
mwpn
2025-12-17 14:25:29 +07:00
parent a8bd195743
commit a87d29c228
2 changed files with 25 additions and 12 deletions

View File

@@ -22,8 +22,8 @@ class CorsMiddleware implements MiddlewareInterface
{
// Load allowed origins from ENV or use defaults
$originsEnv = AppConfig::get('CORS_ALLOWED_ORIGINS', '*');
$this->allowedOrigins = $originsEnv === '*'
? ['*']
$this->allowedOrigins = $originsEnv === '*'
? ['*']
: array_map('trim', explode(',', $originsEnv));
// Allowed HTTP methods
@@ -47,6 +47,15 @@ class CorsMiddleware implements MiddlewareInterface
): ResponseInterface {
$origin = $request->getHeaderLine('Origin');
// Normalize origin (strip path if someone sends invalid Origin)
if ($origin && str_contains($origin, '/')) {
$parsed = parse_url($origin);
if (isset($parsed['scheme'], $parsed['host'])) {
$origin = $parsed['scheme'] . '://' . $parsed['host']
. (isset($parsed['port']) ? ':' . $parsed['port'] : '');
}
}
// Handle preflight OPTIONS request
if ($request->getMethod() === 'OPTIONS') {
$responseFactory = new ResponseFactory();
@@ -132,4 +141,3 @@ class CorsMiddleware implements MiddlewareInterface
return $this->allowedOrigins[0] ?? null;
}
}