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
@@ -22,6 +22,8 @@ return [
|
|||||||
'ep_products' => [
|
'ep_products' => [
|
||||||
// /api/hotel, /api/product, /api/content/* (X-Api-Key or ?key=)
|
// /api/hotel, /api/product, /api/content/* (X-Api-Key or ?key=)
|
||||||
'cmsApiKey' => '',
|
'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/
|
// MyE&P OAuth2 client credentials (import, price calendar); locally e.g. https://myep.ddev.site/api/
|
||||||
'myEpApiBaseUrl' => '',
|
'myEpApiBaseUrl' => '',
|
||||||
'myEpApiClientId' => '',
|
'myEpApiClientId' => '',
|
||||||
|
|||||||
+27
-3
@@ -1,7 +1,7 @@
|
|||||||
# CMS API
|
# CMS API
|
||||||
|
|
||||||
Endpoints TYPO3 serves to other systems: **MyE&P** (hotel and product content, calendar hotels)
|
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`
|
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.
|
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`
|
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
|
## 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):
|
(Settings → Extension Configuration → ep_products, tab ContentFeed):
|
||||||
|
|
||||||
- header `X-Api-Key: <key>` (preferred, query strings end up in access logs), or
|
- header `X-Api-Key: <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`,
|
Configuration (extension configuration `ep_products`, tab ContentFeed): `contentFeedEnabled`,
|
||||||
`contentFeedSites`, `contentFeedLanguages`, `contentFeedExcludedPages`,
|
`contentFeedSites`, `contentFeedLanguages`, `contentFeedExcludedPages`,
|
||||||
`contentFeedNewsDetailPages`.
|
`contentFeedNewsDetailPages`.
|
||||||
|
|
||||||
|
## `PUT /api/json-ld/<uid>`
|
||||||
|
|
||||||
|
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
|
||||||
|
`<script type="application/ld+json">`, whatever the element held before. Other fields (CType,
|
||||||
|
hidden, …) are left alone; each translation is its own uid.
|
||||||
|
|
||||||
|
- Key: `jsonLdApiKey` (extension configuration `ep_products`, tab JsonLd), only as header
|
||||||
|
`X-Api-Key`; `?key=` is not accepted.
|
||||||
|
- `POST` does the same as `PUT` (n8n's default method).
|
||||||
|
- Body: the JSON-LD object (or array of objects) itself, e.g.
|
||||||
|
`{"@context": "https://schema.org", "@type": "Event", …}`. Pretty-printed when stored;
|
||||||
|
`<` and `>` are escaped as `\u003C`/`\u003E`, so a value cannot close the script element.
|
||||||
|
- `200 {"uid": 13169, "pid": 24, "changed": true}`; `changed: false` when the stored markup is
|
||||||
|
already identical (nothing written).
|
||||||
|
- `400` for invalid JSON or a scalar, `403` for a wrong or missing key, `404` for an unknown or
|
||||||
|
deleted uid, `405` for other methods, `503` when the backend user `_n8n` is missing, `500` with
|
||||||
|
`errors` when DataHandler refuses the write.
|
||||||
|
|
||||||
|
The write goes through DataHandler as the backend user `_n8n` (no password, so no login; group
|
||||||
|
`n8n` with *Tables (modify)* `tt_content` and *Explicitly allow* `tt_content:CType:html`; page
|
||||||
|
permissions are bypassed). Every change is in the element's history, where it can be undone, and
|
||||||
|
clears the page cache.
|
||||||
@@ -8,9 +8,10 @@ use Psr\Http\Message\ServerRequestInterface;
|
|||||||
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
|
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
|
* 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.
|
* 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
|
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
|
// Header first: query-string keys end up in access logs. `key` stays accepted for parity
|
||||||
// with the existing /api/hotel and /api/product calls.
|
// with the existing /api/hotel and /api/product calls.
|
||||||
$provided = $request->getHeaderLine('X-Api-Key');
|
$provided = $request->getHeaderLine('X-Api-Key');
|
||||||
@@ -36,6 +31,25 @@ class ApiKeyAuthenticator
|
|||||||
$provided = (string) ($request->getQueryParams()['key'] ?? '');
|
$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);
|
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 TYPO3\CMS\Core\Database\Connection;
|
||||||
use EP\EpProducts\ContentFeed\ContentFeedApi;
|
use EP\EpProducts\ContentFeed\ContentFeedApi;
|
||||||
use EP\EpProducts\Http\ApiKeyAuthenticator;
|
use EP\EpProducts\Http\ApiKeyAuthenticator;
|
||||||
|
use EP\EpProducts\JsonLd\JsonLdApi;
|
||||||
use EP\EpProducts\Service\MyEpImageService;
|
use EP\EpProducts\Service\MyEpImageService;
|
||||||
use EP\EpProducts\Utility\HotelIconUtility;
|
use EP\EpProducts\Utility\HotelIconUtility;
|
||||||
use Psr\Http\Message\ResponseInterface;
|
use Psr\Http\Message\ResponseInterface;
|
||||||
@@ -28,6 +29,7 @@ class ApiMiddleware implements MiddlewareInterface
|
|||||||
private readonly ImageService $imageService,
|
private readonly ImageService $imageService,
|
||||||
private readonly ContentFeedApi $contentFeedApi,
|
private readonly ContentFeedApi $contentFeedApi,
|
||||||
private readonly ApiKeyAuthenticator $authenticator,
|
private readonly ApiKeyAuthenticator $authenticator,
|
||||||
|
private readonly JsonLdApi $jsonLdApi,
|
||||||
) {
|
) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,6 +53,10 @@ class ApiMiddleware implements MiddlewareInterface
|
|||||||
return $this->contentFeedApi->handle($request);
|
return $this->contentFeedApi->handle($request);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (str_starts_with($path, JsonLdApi::PATH_PREFIX)) {
|
||||||
|
return $this->jsonLdApi->handle($request);
|
||||||
|
}
|
||||||
|
|
||||||
return $handler->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.
|
# 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 =
|
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)
|
# cat=ContentFeed; type=boolean; label=Serve the chatbot content feed (off: all feed endpoints answer 503)
|
||||||
contentFeedEnabled = 1
|
contentFeedEnabled = 1
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user