From 7ae9aa266e1f0b199a3d9ed6476868c3136238c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Fromme?= Date: Mon, 2 Nov 2026 17:40:23 +0100 Subject: [PATCH] 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 --- config/system/secrets.example.php | 2 + docs/cms-api.md | 30 ++++- .../Classes/Http/ApiKeyAuthenticator.php | 30 +++-- .../ep_products/Classes/JsonLd/JsonLdApi.php | 125 ++++++++++++++++++ .../Classes/Middleware/ApiMiddleware.php | 6 + packages/ep_products/ext_conf_template.txt | 3 + 6 files changed, 185 insertions(+), 11 deletions(-) create mode 100644 packages/ep_products/Classes/JsonLd/JsonLdApi.php diff --git a/config/system/secrets.example.php b/config/system/secrets.example.php index e20bb6c..be59129 100644 --- a/config/system/secrets.example.php +++ b/config/system/secrets.example.php @@ -22,6 +22,8 @@ return [ 'ep_products' => [ // /api/hotel, /api/product, /api/content/* (X-Api-Key or ?key=) 'cmsApiKey' => '', + // n8n: PUT /api/json-ld/{uid} (X-Api-Key only), writes as backend user _n8n + 'jsonLdApiKey' => '', // MyE&P OAuth2 client credentials (import, price calendar); locally e.g. https://myep.ddev.site/api/ 'myEpApiBaseUrl' => '', 'myEpApiClientId' => '', diff --git a/docs/cms-api.md b/docs/cms-api.md index 8426cf4..c28122c 100644 --- a/docs/cms-api.md +++ b/docs/cms-api.md @@ -1,7 +1,7 @@ # CMS API -Endpoints TYPO3 serves to other systems: **MyE&P** (hotel and product content, calendar hotels) -and the **chatbot** (content feed). They are answered by `EP\EpProducts\Middleware\ApiMiddleware` +Endpoints TYPO3 serves to other systems: **MyE&P** (hotel and product content, calendar hotels), +the **chatbot** (content feed) and **n8n** (JSON-LD of content elements). They are answered by `EP\EpProducts\Middleware\ApiMiddleware` before the page resolver, so they do not depend on a page and are never page-cached. The other side of these contracts is documented in MyE&P's `docs/api-consumer-guide.md` @@ -9,7 +9,7 @@ The other side of these contracts is documented in MyE&P's `docs/api-consumer-gu ## Authentication -All endpoints need the shared key `cmsApiKey` from the `ep_products` extension configuration +All endpoints except `/api/json-ld/` (see there) need the shared key `cmsApiKey` from the `ep_products` extension configuration (Settings → Extension Configuration → ep_products, tab ContentFeed): - header `X-Api-Key: ` (preferred, query strings end up in access logs), or @@ -99,3 +99,27 @@ The content feed for the chatbot (`EP\EpProducts\ContentFeed\ContentFeedApi`). Configuration (extension configuration `ep_products`, tab ContentFeed): `contentFeedEnabled`, `contentFeedSites`, `contentFeedLanguages`, `contentFeedExcludedPages`, `contentFeedNewsDetailPages`. + +## `PUT /api/json-ld/` + +n8n writes the JSON-LD (SEO markup) of a content element (`EP\EpProducts\JsonLd\JsonLdApi`). +n8n is the source of truth: the element's `bodytext` is replaced with the posted object wrapped in +`" 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 = ''; + $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 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; + } + } +} diff --git a/packages/ep_products/Classes/Middleware/ApiMiddleware.php b/packages/ep_products/Classes/Middleware/ApiMiddleware.php index c19bcb3..17eabfb 100644 --- a/packages/ep_products/Classes/Middleware/ApiMiddleware.php +++ b/packages/ep_products/Classes/Middleware/ApiMiddleware.php @@ -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); } diff --git a/packages/ep_products/ext_conf_template.txt b/packages/ep_products/ext_conf_template.txt index f239949..f447cd7 100644 --- a/packages/ep_products/ext_conf_template.txt +++ b/packages/ep_products/ext_conf_template.txt @@ -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