39 lines
1.3 KiB
PHP
39 lines
1.3 KiB
PHP
|
|
<?php
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace Phred\Http\Middleware\Security;
|
||
|
|
|
||
|
|
use Phred\Http\Middleware\Middleware;
|
||
|
|
use Phred\Support\Contracts\ConfigInterface;
|
||
|
|
use Psr\Http\Message\ResponseInterface;
|
||
|
|
use Psr\Http\Message\ServerRequestInterface;
|
||
|
|
use Psr\Http\Server\RequestHandlerInterface;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Middleware to add common security headers to the response.
|
||
|
|
*/
|
||
|
|
final class SecureHeadersMiddleware extends Middleware
|
||
|
|
{
|
||
|
|
public function __construct(
|
||
|
|
private readonly ConfigInterface $config
|
||
|
|
) {}
|
||
|
|
|
||
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||
|
|
{
|
||
|
|
$response = $handler->handle($request);
|
||
|
|
|
||
|
|
// Standard security headers
|
||
|
|
$response = $response->withHeader('X-Content-Type-Options', 'nosniff')
|
||
|
|
->withHeader('X-Frame-Options', 'SAMEORIGIN')
|
||
|
|
->withHeader('X-XSS-Protection', '1; mode=block')
|
||
|
|
->withHeader('Referrer-Policy', 'no-referrer-when-downgrade')
|
||
|
|
->withHeader('Content-Security-Policy', $this->config->get('security.csp', "default-src 'self'"));
|
||
|
|
|
||
|
|
if ($this->config->get('security.hsts', true)) {
|
||
|
|
$response = $response->withHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
|
||
|
|
}
|
||
|
|
|
||
|
|
return $response;
|
||
|
|
}
|
||
|
|
}
|