SecurityHeadersMiddleware::process()   A
last analyzed

Complexity

Conditions 5
Paths 12

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 33
rs 9.2568
c 0
b 0
f 0
cc 5
nc 12
nop 2
1
<?php
2
3
namespace Jidaikobo\Kontiki\Middleware;
4
5
use Psr\Http\Message\ResponseInterface as Response;
6
use Psr\Http\Message\ServerRequestInterface as Request;
7
use Psr\Http\Server\MiddlewareInterface;
8
use Psr\Http\Server\RequestHandlerInterface;
9
10
class SecurityHeadersMiddleware implements MiddlewareInterface
11
{
12
    /**
13
     * Process an incoming server request and apply security headers.
14
     *
15
     * @param  Request                 $request
16
     * @param  RequestHandlerInterface $handler
17
     * @return Response
18
     */
19
    public function process(Request $request, RequestHandlerInterface $handler): Response
20
    {
21
        // Delegate the request to the next middleware or controller
22
        $response = $handler->handle($request);
23
24
        // ホスト名を取得
25
        $host = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443)
26
            ? 'https://' . ($_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? 'localhost'))
27
            : 'http://' . ($_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? 'localhost'));
28
29
        // Add security headers
30
        $headers = [
31
            "Content-Security-Policy" => "default-src 'self'; " .
32
                "script-src 'self' https://cdn.jsdelivr.net https://code.jquery.com; " .
33
                "style-src 'self' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; " .
34
                "font-src 'self' https://cdnjs.cloudflare.com; " .
35
                "img-src 'self' data:; " .
36
                "connect-src 'self'; " .
37
                "frame-src 'self';",
38
            "Strict-Transport-Security" => "max-age=31536000; includeSubDomains",
39
            "X-Content-Type-Options" => "nosniff",
40
            "Referrer-Policy" => "no-referrer-when-downgrade",
41
            "X-XSS-Protection" => "1; mode=block",
42
            "Permissions-Policy" => "geolocation=(), microphone=(), camera=()",
43
            "X-Frame-Options" => "SAMEORIGIN",
44
            "Access-Control-Allow-Origin" => $host,
45
        ];
46
47
        foreach ($headers as $key => $value) {
48
            $response = $response->withHeader($key, $value);
49
        }
50
51
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response could return the type Psr\Http\Message\MessageInterface which includes types incompatible with the type-hinted return Psr\Http\Message\ResponseInterface. Consider adding an additional type-check to rule them out.
Loading history...
52
    }
53
}
54