Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.25% covered (success)
91.25%
73 / 80
50.00% covered (danger)
50.00%
3 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
JavascriptCdnProxy
91.25% covered (success)
91.25%
73 / 80
50.00% covered (danger)
50.00%
3 / 6
37.92
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getResponse
97.92% covered (success)
97.92%
47 / 48
0.00% covered (danger)
0.00%
0 / 1
14
 readFakePackage
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 rewriteRedirectLocation
70.00% covered (warning)
70.00%
7 / 10
0.00% covered (danger)
0.00%
0 / 1
5.68
 isCachedResponse
76.92% covered (warning)
76.92%
10 / 13
0.00% covered (danger)
0.00%
0 / 1
15.08
 createResponse
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2namespace Apie\JavascriptCdn;
3
4use Apie\Core\FileStorage\StoredFile;
5use Apie\Core\ValueObjects\Exceptions\InvalidStringForValueObjectException;
6use Apie\JavascriptCdn\ValueObjects\JavascriptCdnPath;
7use Nyholm\Psr7\Response;
8use Psr\Cache\CacheItemPoolInterface;
9use Psr\Http\Message\ResponseInterface;
10use Symfony\Component\HttpClient\HttpClient;
11use Symfony\Contracts\HttpClient\HttpClientInterface;
12
13class JavascriptCdnProxy
14{
15    private const CDN_BASE_URL = 'https://cdn.jsdelivr.net/npm/';
16
17    private const LATEST_TTL = 600;
18    private const VERSIONED_TTL = 63072000;
19
20    private const FORWARDED_HEADERS = [
21        'cache-control',
22        'content-type',
23        'etag',
24        'expires',
25        'last-modified',
26    ];
27
28    private readonly HttpClientInterface $httpClient;
29    private readonly string $fakePackagesDirectory;
30
31    public function __construct(
32        private readonly CacheItemPoolInterface $cache,
33        ?HttpClientInterface $httpClient = null,
34        ?string $fakePackagesDirectory = null
35    ) {
36        $this->httpClient = $httpClient ?? HttpClient::create();
37        $fakePackagesDirectory ??= __DIR__ . '/../apie-cdn';
38        $this->fakePackagesDirectory = $fakePackagesDirectory;
39    }
40
41    public function getResponse(JavascriptCdnPath $packagePath): ResponseInterface
42    {
43        $fakePackage = $this->readFakePackage($packagePath);
44        if ($fakePackage instanceof StoredFile) {
45            return new Response(200, [
46                'Content-Type' => $fakePackage->getServerMimeType(),
47                'Cache-Control' => 'no-cache',
48                'X-Content-Type-Options' => 'nosniff',
49            ], $fakePackage->getStream());
50        }
51
52        $cacheItem = $this->cache->getItem('apie_javascript_cdn.' . hash('sha256', $packagePath->toNative()));
53        if ($cacheItem->isHit()) {
54            $cachedResponse = $cacheItem->get();
55            if ($this->isCachedResponse($cachedResponse)) {
56                return $this->createResponse(
57                    $cachedResponse['status'],
58                    $cachedResponse['headers'],
59                    $cachedResponse['body']
60                );
61            }
62        }
63
64        $cdnResponse = $this->httpClient->request('GET', self::CDN_BASE_URL . $packagePath, [
65            'max_redirects' => 0,
66            'timeout' => 30,
67        ]);
68        $headers = [];
69        foreach (self::FORWARDED_HEADERS as $header) {
70            $values = $cdnResponse->getHeaders(false)[$header] ?? [];
71            if ($values !== []) {
72                $headers[$header] = $values;
73            }
74        }
75        $headers['X-Content-Type-Options'] = 'nosniff';
76        $status = $cdnResponse->getStatusCode();
77        $body = $cdnResponse->getContent(false);
78
79        $isRedirect = in_array($status, [301, 302, 307, 308], true);
80        if ($isRedirect) {
81            $location = $this->rewriteRedirectLocation($cdnResponse->getHeaders(false)['location'][0] ?? null);
82            if ($location === null) {
83                return new Response(502, ['Content-Type' => 'text/plain'], 'Invalid redirect from the CDN.');
84            }
85            $headers = ['Location' => $location, 'X-Content-Type-Options' => 'nosniff'];
86            $body = '';
87        }
88
89        if ($isRedirect || ($status >= 200 && $status < 300)) {
90            if (!$packagePath->isLatestVersion()) {
91                // versioned assets never change: let the browser use its own cache without revalidating
92                unset($headers['expires'], $headers['Expires']);
93                $headers['Cache-Control'] = 'public, max-age=' . self::VERSIONED_TTL . ', immutable';
94            }
95            $cacheItem->expiresAfter($packagePath->isLatestVersion() ? self::LATEST_TTL : self::VERSIONED_TTL);
96            $cacheItem->set([
97                'status' => $status,
98                'headers' => $headers,
99                'body' => $body,
100            ]);
101            if (!$this->cache->save($cacheItem)) {
102                throw new \RuntimeException('Unable to cache the JavaScript CDN response.');
103            }
104        }
105
106        return $this->createResponse($status, $headers, $body);
107    }
108
109    private function readFakePackage(JavascriptCdnPath $packagePath): ?StoredFile
110    {
111        $filePath = realpath($this->fakePackagesDirectory . DIRECTORY_SEPARATOR . $packagePath->getRelativePath());
112        if (
113            $filePath === false
114            || !is_file($filePath)
115        ) {
116            return null;
117        }
118
119        return StoredFile::createFromLocalFile($filePath);
120    }
121
122    /**
123     * Rewrites a CDN redirect to the same-origin proxy route, so the browser never leaves this host.
124     */
125    private function rewriteRedirectLocation(?string $location): ?string
126    {
127        if ($location === null) {
128            return null;
129        }
130        foreach ([self::CDN_BASE_URL, '/npm/'] as $prefix) {
131            if (str_starts_with($location, $prefix)) {
132                $target = substr($location, strlen($prefix));
133                try {
134                    new JavascriptCdnPath($target);
135                } catch (InvalidStringForValueObjectException) {
136                    return null;
137                }
138
139                return '/npm/' . $target;
140            }
141        }
142
143        return null;
144    }
145
146    /**
147     * @phpstan-assert-if-true array{status: int, headers: array<string, list<string>|string>, body: string} $response
148     */
149    private function isCachedResponse(mixed $response): bool
150    {
151        if (
152            !is_array($response)
153            || !isset($response['status'], $response['headers'], $response['body'])
154            || !is_int($response['status'])
155            || !is_array($response['headers'])
156            || !is_string($response['body'])
157        ) {
158            return false;
159        }
160        foreach ($response['headers'] as $name => $values) {
161            if (
162                !is_string($name)
163                || !(is_string($values) || (is_array($values) && array_is_list($values)))
164            ) {
165                return false;
166            }
167            if (is_array($values) && array_filter($values, static fn ($value) => !is_string($value)) !== []) {
168                return false;
169            }
170        }
171
172        return true;
173    }
174
175    /**
176     * @param array<string, list<string>|string> $headers
177     */
178    private function createResponse(int $status, array $headers, string $body): ResponseInterface
179    {
180        return new Response($status, $headers, $body);
181    }
182}