Add explicit MIME types and caching for static assets

Improve asset handling with:
- Path traversal protection
- Explicit MIME type mapping
- Configurable caching headers
- Case-insensitive extension matching
This commit is contained in:
Ruben 2026-02-25 23:09:43 +01:00
parent 74672b2d04
commit a1344ca407

View file

@ -17,10 +17,30 @@ $ctx = createContext();
$GLOBALS['ctx'] = $ctx; $GLOBALS['ctx'] = $ctx;
// Check for assets in /custom/assets/ served at root level // Check for assets in /custom/assets/ served at root level
$assetPath = dirname(__DIR__) . '/custom/assets/' . $ctx->requestPath; $assetsDir = realpath(dirname(__DIR__) . '/custom/assets');
if (file_exists($assetPath) && is_file($assetPath)) { $realAsset = realpath($assetsDir . '/' . $ctx->requestPath);
header('Content-Type: ' . (mime_content_type($assetPath) ?: 'application/octet-stream')); if ($realAsset && strncmp($realAsset, $assetsDir . '/', strlen($assetsDir) + 1) === 0 && is_file($realAsset)) {
readfile($assetPath); $assetMimeTypes = [
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'geojson' => 'application/json',
'svg' => 'image/svg+xml',
'woff' => 'font/woff',
'woff2' => 'font/woff2',
'ttf' => 'font/ttf',
'otf' => 'font/otf',
'png' => 'image/png',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'webp' => 'image/webp',
];
$assetExt = strtolower(pathinfo($realAsset, PATHINFO_EXTENSION));
$mime = $assetMimeTypes[$assetExt] ?? 'application/octet-stream';
$cacheSeconds = in_array($assetExt, ['json', 'geojson']) ? 60 : 31536000;
header('Content-Type: ' . $mime);
header('Cache-Control: public, max-age=' . $cacheSeconds);
readfile($realAsset);
exit; exit;
} }