feat: n8n can replace the JSON-LD of content elements via PUT /api/json-ld/{uid}
n8n is the source of truth for the SEO markup: the element's bodytext is overwritten with the posted object, wrapped in a ld+json script element. Values are escaped with JSON_HEX_TAG so they cannot close the element. The endpoint has its own key (jsonLdApiKey, header only) and writes through DataHandler as the non-admin backend user _n8n, so every change is in the record history and can be undone there, and the page cache is cleared. Until the key and the user exist on prod, every request answers 403/503. Prod setup (group n8n, user _n8n) is in docs/cms-api.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
81a8013e8a
commit
7ae9aa266e
6 files changed
+185
-11
No files matched your search
@@ -8,9 +8,10 @@ use Psr\Http\Message\ServerRequestInterface;
|
||||
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
|
||||
|
||||
/**
|
||||
* Checks the shared key of the CMS backchannel endpoints (content feed, CMS index).
|
||||
* Checks the api keys: the shared `cmsApiKey` of the CMS backchannel endpoints (content feed, CMS
|
||||
* index) and the keys of single write endpoints (`jsonLdApiKey` for n8n).
|
||||
*
|
||||
* An empty or missing `cmsApiKey` denies every request. ExtensionConfiguration::get() returns the
|
||||
* An empty or missing key denies every request. ExtensionConfiguration::get() returns the
|
||||
* stored configuration verbatim, so a newly added key is absent until someone saves the extension
|
||||
* configuration in the backend - defaulting to "allow" there would publish the whole catalogue.
|
||||
*/
|
||||
@@ -22,12 +23,6 @@ class ApiKeyAuthenticator
|
||||
|
||||
public function isAuthorized(ServerRequestInterface $request): bool
|
||||
{
|
||||
$configured = (string) ($this->extensionConfiguration->get('ep_products')['cmsApiKey'] ?? '');
|
||||
|
||||
if ('' === $configured) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Header first: query-string keys end up in access logs. `key` stays accepted for parity
|
||||
// with the existing /api/hotel and /api/product calls.
|
||||
$provided = $request->getHeaderLine('X-Api-Key');
|
||||
@@ -36,6 +31,25 @@ class ApiKeyAuthenticator
|
||||
$provided = (string) ($request->getQueryParams()['key'] ?? '');
|
||||
}
|
||||
|
||||
return $this->matches('cmsApiKey', $provided);
|
||||
}
|
||||
|
||||
/**
|
||||
* For write endpoints: the key is only accepted as header, it never shows up in access logs.
|
||||
*/
|
||||
public function isAuthorizedByHeader(ServerRequestInterface $request, string $configKey): bool
|
||||
{
|
||||
return $this->matches($configKey, $request->getHeaderLine('X-Api-Key'));
|
||||
}
|
||||
|
||||
private function matches(string $configKey, string $provided): bool
|
||||
{
|
||||
$configured = (string) ($this->extensionConfiguration->get('ep_products')[$configKey] ?? '');
|
||||
|
||||
if ('' === $configured) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return hash_equals($configured, $provided);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace EP\EpProducts\JsonLd;
|
||||
|
||||
use EP\EpProducts\Http\ApiKeyAuthenticator;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use TYPO3\CMS\Backend\Utility\BackendUtility;
|
||||
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
|
||||
use TYPO3\CMS\Core\DataHandling\DataHandler;
|
||||
use TYPO3\CMS\Core\Http\JsonResponse;
|
||||
use TYPO3\CMS\Core\Utility\GeneralUtility;
|
||||
|
||||
/**
|
||||
* PUT /api/json-ld/{uid}: n8n replaces the JSON-LD of an html content element (SEO markup).
|
||||
*
|
||||
* n8n is the source of truth: the element's bodytext is overwritten with the posted object,
|
||||
* whatever it held before. The write goes through DataHandler as the backend user `_n8n`, so every
|
||||
* change is in the record history (and can be undone there) and the page cache is cleared.
|
||||
*/
|
||||
class JsonLdApi
|
||||
{
|
||||
public const PATH_PREFIX = '/api/json-ld/';
|
||||
|
||||
private const string BACKEND_USER = '_n8n';
|
||||
|
||||
// JSON_HEX_TAG: a "</script>" inside a value must not end the script element
|
||||
private const int JSON_FLAGS = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_THROW_ON_ERROR;
|
||||
|
||||
public function __construct(private readonly ApiKeyAuthenticator $authenticator)
|
||||
{
|
||||
}
|
||||
|
||||
public function handle(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
// POST is n8n's default method; both replace the whole object
|
||||
if (!in_array($request->getMethod(), ['PUT', 'POST'], true)) {
|
||||
return new JsonResponse(['message' => 'Method not allowed'], 405, ['Allow' => 'PUT, POST']);
|
||||
}
|
||||
|
||||
if (!$this->authenticator->isAuthorizedByHeader($request, 'jsonLdApiKey')) {
|
||||
return new JsonResponse(['message' => 'Invalid or missing api key'], 403);
|
||||
}
|
||||
|
||||
$uid = substr($request->getUri()->getPath(), strlen(self::PATH_PREFIX));
|
||||
$record = 1 === preg_match('/^[1-9]\d*$/', $uid)
|
||||
? BackendUtility::getRecord('tt_content', (int) $uid, 'uid,pid,bodytext')
|
||||
: null;
|
||||
|
||||
if (null === $record) {
|
||||
return new JsonResponse(['message' => 'Content element not found'], 404);
|
||||
}
|
||||
|
||||
try {
|
||||
// Decoded as objects, not arrays, so an empty {} stays an object
|
||||
$jsonLd = json_decode((string) $request->getBody(), false, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
return new JsonResponse(['message' => 'Invalid JSON: ' . $e->getMessage()], 400);
|
||||
}
|
||||
|
||||
if (!is_object($jsonLd) && !is_array($jsonLd)) {
|
||||
return new JsonResponse(['message' => 'Expected a JSON-LD object or array'], 400);
|
||||
}
|
||||
|
||||
$bodytext = '<script type="application/ld+json">' . "\n" . json_encode($jsonLd, self::JSON_FLAGS) . "\n" . '</script>';
|
||||
$result = ['uid' => (int) $record['uid'], 'pid' => (int) $record['pid']];
|
||||
|
||||
if ($bodytext === $record['bodytext']) {
|
||||
return new JsonResponse($result + ['changed' => false]);
|
||||
}
|
||||
|
||||
$backendUser = $this->getBackendUser();
|
||||
|
||||
if (null === $backendUser) {
|
||||
return new JsonResponse(['message' => 'Backend user ' . self::BACKEND_USER . ' is missing'], 503);
|
||||
}
|
||||
|
||||
$errors = $this->write((int) $record['uid'], $bodytext, $backendUser);
|
||||
|
||||
if ([] !== $errors) {
|
||||
return new JsonResponse(['message' => 'Content element not saved', 'errors' => $errors], 500);
|
||||
}
|
||||
|
||||
return new JsonResponse($result + ['changed' => true]);
|
||||
}
|
||||
|
||||
private function getBackendUser(): ?BackendUserAuthentication
|
||||
{
|
||||
$backendUser = GeneralUtility::makeInstance(BackendUserAuthentication::class);
|
||||
$backendUser->setBeUserByName(self::BACKEND_USER);
|
||||
|
||||
if (empty($backendUser->user['uid'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$backendUser->fetchGroupData();
|
||||
|
||||
return $backendUser;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string> DataHandler's error log, empty on success
|
||||
*/
|
||||
private function write(int $uid, string $bodytext, BackendUserAuthentication $backendUser): array
|
||||
{
|
||||
// Hooks and helpers called by DataHandler read the global user, not the one passed in
|
||||
$previousBackendUser = $GLOBALS['BE_USER'] ?? null;
|
||||
$GLOBALS['BE_USER'] = $backendUser;
|
||||
|
||||
try {
|
||||
$dataHandler = GeneralUtility::makeInstance(DataHandler::class);
|
||||
// The user only has modify access to tt_content, no page permissions: n8n may update
|
||||
// any content element, whichever page it is on
|
||||
$dataHandler->bypassAccessCheckForRecords = true;
|
||||
$dataHandler->start(['tt_content' => [$uid => ['bodytext' => $bodytext]]], [], $backendUser);
|
||||
$dataHandler->process_datamap();
|
||||
|
||||
return array_values($dataHandler->errorLog);
|
||||
} finally {
|
||||
$GLOBALS['BE_USER'] = $previousBackendUser;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use TYPO3\CMS\Core\Resource\FileInterface;
|
||||
use TYPO3\CMS\Core\Database\Connection;
|
||||
use EP\EpProducts\ContentFeed\ContentFeedApi;
|
||||
use EP\EpProducts\Http\ApiKeyAuthenticator;
|
||||
use EP\EpProducts\JsonLd\JsonLdApi;
|
||||
use EP\EpProducts\Service\MyEpImageService;
|
||||
use EP\EpProducts\Utility\HotelIconUtility;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
@@ -28,6 +29,7 @@ class ApiMiddleware implements MiddlewareInterface
|
||||
private readonly ImageService $imageService,
|
||||
private readonly ContentFeedApi $contentFeedApi,
|
||||
private readonly ApiKeyAuthenticator $authenticator,
|
||||
private readonly JsonLdApi $jsonLdApi,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -51,6 +53,10 @@ class ApiMiddleware implements MiddlewareInterface
|
||||
return $this->contentFeedApi->handle($request);
|
||||
}
|
||||
|
||||
if (str_starts_with($path, JsonLdApi::PATH_PREFIX)) {
|
||||
return $this->jsonLdApi->handle($request);
|
||||
}
|
||||
|
||||
return $handler->handle($request);
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,9 @@ bpnConnectApiMaxDuration = 15
|
||||
# cat=ContentFeed; type=string; label=API key for the CMS backchannel endpoints (/api/hotel, /api/product, /api/calendar-hotels for MyE&P; /api/content/* for the chatbot; see docs/cms-api.md); sent as X-Api-Key or ?key=. Empty denies every request.
|
||||
cmsApiKey =
|
||||
|
||||
# cat=JsonLd; type=string; label=API key for n8n's PUT /api/json-ld/{uid} (see docs/cms-api.md); sent as X-Api-Key header only. Empty denies every request.
|
||||
jsonLdApiKey =
|
||||
|
||||
# cat=ContentFeed; type=boolean; label=Serve the chatbot content feed (off: all feed endpoints answer 503)
|
||||
contentFeedEnabled = 1
|
||||
|
||||
|
||||
Reference in new issue
Block a user