New JsonCacheHeaders middleware (outer, frontend stack): GET/HEAD 200 responses under /_json get a single Cache-Control: no-cache, Expires: 0 and a content md5 ETag; If-None-Match answers as empty 304. Logged-in visitors (fe_typo_user) keep TYPO3 headers. Expires: 0 is deliberate so mod_expires leaves the response alone. .htaccess: the global Header unset ETag now skips /_json (KEEP_ETAG env, carried across the mod_rewrite internal redirect as REDIRECT_KEEP_ETAG). Fulfils tickets 0011-FE point 3 and 0055-BE question 6; asset immutable headers were already live. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
61 lines
2.1 KiB
PHP
61 lines
2.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Evomedien\Vitec\Middleware;
|
|
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
use Psr\Http\Server\MiddlewareInterface;
|
|
use Psr\Http\Server\RequestHandlerInterface;
|
|
use TYPO3\CMS\Core\Http\Response;
|
|
|
|
/**
|
|
* Normalizes client caching for the headless JSON API (/_json):
|
|
* a single "Cache-Control: no-cache" plus a content ETag, answering
|
|
* If-None-Match with an empty 304 so browsers revalidate instead of
|
|
* re-downloading (tickets 0011-FE / 0055-BE).
|
|
*
|
|
* "Expires: 0" is set on purpose: mod_expires leaves responses alone
|
|
* that already carry an Expires header, otherwise it would re-add
|
|
* max-age/Expires on top of ours (public/.htaccess ExpiresByType).
|
|
*
|
|
* Logged-in visitors (fe_typo_user cookie) keep TYPO3's own headers:
|
|
* their responses may be personalized and must not be eligible for
|
|
* shared revalidation.
|
|
*/
|
|
final class JsonCacheHeaders implements MiddlewareInterface
|
|
{
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
|
{
|
|
$response = $handler->handle($request);
|
|
|
|
$path = $request->getUri()->getPath();
|
|
if (
|
|
!\in_array($request->getMethod(), ['GET', 'HEAD'], true)
|
|
|| $response->getStatusCode() !== 200
|
|
|| ($path !== '/_json' && !str_starts_with($path, '/_json/'))
|
|
|| isset($request->getCookieParams()['fe_typo_user'])
|
|
) {
|
|
return $response;
|
|
}
|
|
|
|
$etag = '"' . md5((string)$response->getBody()) . '"';
|
|
|
|
$ifNoneMatch = trim($request->getHeaderLine('If-None-Match'));
|
|
if ($ifNoneMatch !== '' && str_contains($ifNoneMatch, $etag)) {
|
|
return (new Response())
|
|
->withStatus(304)
|
|
->withHeader('ETag', $etag)
|
|
->withHeader('Cache-Control', 'no-cache')
|
|
->withHeader('Expires', '0');
|
|
}
|
|
|
|
return $response
|
|
->withHeader('Cache-Control', 'no-cache')
|
|
->withoutHeader('Pragma')
|
|
->withHeader('Expires', '0')
|
|
->withHeader('ETag', $etag);
|
|
}
|
|
}
|