Einwilligung, die tatsächlich zurückhält, und Pflichtseiten

Ein Hinweis, der nur fragt und sonst nichts ändert, ist Theater. Deshalb zwei
Hälften, und die zweite ist die wichtigere.

Die Frage: serverseitig gerendert, per Formular beantwortet, ohne JavaScript -
die öffentlichen Seiten laufen mit script-src 'none', und ein Banner mit
Skript wäre das eine, was diese Regel bricht. "Alle akzeptieren" und "Nur
notwendige" sind dieselbe Art Knopf, gleich groß, nebeneinander. Die
Entscheidung steht in einem eigenen Cookie: Fassung der Frage, gewährte
Gruppen, Zeitpunkt. Keine Kennung, kein Serverabgleich, ein halbes Jahr. Kein
CSRF-Token, absichtlich: die Anfrage ändert nichts auf dem Server, und ein
Token bräuchte für jeden Besucher eine Sitzung - genau das, was ein
Einwilligungshinweis vermeiden soll. Geprüft wird stattdessen das
Rücksprungziel.

Das Zurückhalten: der neue Block "Externer Inhalt" (Dokumentschema v14) lädt
ohne Einwilligung nichts - kein iframe, keine Adresse im Markup, frame-src
'none'. Der Platzhalter nennt den Anbieter; sein Knopf gewährt genau diese
Gruppe und nimmt die vorher gewährten mit. Erst danach kommt der Host in die
Sicherheitsrichtlinie, und nur dieser. Im Editor bleibt es immer ein
Platzhalter.

Datenschutz und Impressum sind keine Einstellung mehr: fehlen sie, warnt die
Verwaltung und legt sie auf Knopfdruck als Gerüst an, mit NOCH AUSZUFÜLLEN an
jeder Pflichtangabe. Den Text schreibt das CMS nicht - das ist eine rechtliche
Aussage über eine Firma. Verlinkt werden beide aus dem Template, nicht aus dem
Fußbereich: ein Pflichtlink, den man löschen kann, ist keiner.

Dazu der Fehler, den Umut im Screenshot gesehen hat: die Wortmarke stand als
Buchstabenkolonne in einem 60 Pixel breiten Kasten. .site-header war noch ein
Flexcontainer aus der Zeit des handgeschriebenen Markups und quetschte die
Sektion zusammen, und design.css band jede Designklasse an #main - wo Kopf-
und Fußbereich seit ADR 026 nicht mehr liegen. Beides behoben.

Neu im Ausbauplan: Statistik (serverseitige, wiedererkennungsfreie Zählung,
die deshalb keine Einwilligung braucht), Inhalte und Ladeverhalten prüfen
(Blättern überall, minimal laden, Ladebudget), Installer (Schritt für Schritt
im Browser, Migration inklusive).

245 PHP-Tests / 976 Assertions unter PHP 8.2.12 und 8.4.22. Der Browsertest
fand zwei Fehler von mir: grauer Text auf dunklem Fußbereich mit 2,24:1, und
das fixierte Banner verdeckte den Einwilligungsknopf am Seitenende.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kantarciandClaude Opus 5 committed 2026-09-12 19:27:41 +02:00
1 parent 84d471acd9
commit ee446f1ea1
30 files changed
+1298 -154

No files matched your search

+179
View File
@@ -0,0 +1,179 @@
<?php
namespace App\Content;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* The visitor's decision about groups of content that may not load without consent.
*
* Two things matter here, and the banner is the smaller one. The banner only asks; what makes the
* answer worth anything is that an embed does not load until it has been given - that is why
* `granted()` is asked in the renderer and not only in the template.
*
* The decision lives in one first-party cookie and nowhere else: no server record, no identifier,
* no third party. The cookie holds the version of the question, the groups that were granted and
* when - nothing about the person. It is deliberately not signed: it describes what this browser
* chose, so a forged value can only change what that same browser gets shown.
*/
final class Consent
{
public const COOKIE = 'kant_consent';
/**
* Necessary content is not a group: it is what remains when nothing is granted, and it is
* never asked about. Only these two can be asked about.
*/
public const GROUPS = [
'statistics' => 'Statistik',
'external' => 'Externe Inhalte',
];
public const GROUP_HELP = [
'statistics' => 'Messung, wie die Website benutzt wird.',
'external' => 'Inhalte von anderen Anbietern, etwa Karten, Videos, Bewertungen oder ein Chat. Sie sehen die Adresse dieser Seite und deine IP-Adresse, sobald sie geladen werden.',
];
/**
* Half a year, then the question is asked again. Long enough not to be a nuisance, short
* enough that a decision is not silently eternal.
*/
public const MAX_AGE = 15552000;
/** Raise this when the groups or their meaning change: an old answer then no longer counts. */
public const VERSION = 1;
public function __construct(private SiteSettings $settings)
{
}
/** Which groups this site asks about at all. Empty means: nothing to consent to. */
public function askedGroups(): array
{
$settings = $this->settings->load();
if (!$settings['consentBanner']) {
return [];
}
return array_values(array_intersect(array_keys(self::GROUPS), $settings['consentGroups']));
}
/**
* The stored decision, or null when there is none that still counts.
*
* @return array{granted: list<string>, at: int}|null
*/
public function decision(Request $request): ?array
{
$raw = $request->cookies->get(self::COOKIE);
if (!is_string($raw) || strlen($raw) > 200) {
return null;
}
$parts = explode('|', $raw);
if (3 !== count($parts) || (string) self::VERSION !== $parts[0]) {
return null;
}
$at = filter_var($parts[2], FILTER_VALIDATE_INT);
if (false === $at || $at <= 0 || $at + self::MAX_AGE < time()) {
return null;
}
$granted = array_values(array_intersect(
array_keys(self::GROUPS),
'' === $parts[1] ? [] : explode(',', $parts[1]),
));
return ['granted' => $granted, 'at' => $at];
}
/**
* Whether a group may load.
*
* A group this site never asks about counts as granted: otherwise switching the banner off
* would silently hide content that needs no consent.
*/
public function granted(Request $request, string $group): bool
{
if (!in_array($group, $this->askedGroups(), true)) {
return true;
}
return in_array($group, $this->decision($request)['granted'] ?? [], true);
}
/** Whether this request should be shown the question. */
public function needsBanner(Request $request): bool
{
return [] !== $this->askedGroups() && null === $this->decision($request);
}
/** @param list<string> $groups */
public function remember(Request $request, Response $response, array $groups): void
{
$granted = array_values(array_intersect($this->askedGroups(), $groups));
$response->headers->setCookie(Cookie::create(
self::COOKIE,
sprintf('%d|%s|%d', self::VERSION, implode(',', $granted), time()),
time() + self::MAX_AGE,
'/',
null,
$request->isSecure(),
// No script needs to read it: the banner is rendered by the server.
true,
false,
Cookie::SAMESITE_LAX,
));
}
public function forget(Response $response): void
{
$response->headers->clearCookie(self::COOKIE, '/');
}
/**
* The two mandatory pages, as link path => label, for the note every page carries.
*
* It sits in this class because the templates already have it at hand, and because the note
* belongs next to the consent link: both are things a visitor must be able to reach from
* anywhere, not things an editor can delete out of the footer by accident.
*
* @return array<string, string>
*/
public function legalLinks(): array
{
$settings = $this->settings->load();
$links = [];
foreach (['privacyPath' => 'Datenschutz', 'imprintPath' => 'Impressum'] as $key => $label) {
if ('' !== $settings[$key]) {
$links[$settings[$key]] = $label;
}
}
return $links;
}
/** What the banner and the consent page need to render. */
public function state(Request $request): array
{
$settings = $this->settings->load();
$decision = $this->decision($request);
return [
'groups' => array_map(
static fn (string $group): array => [
'key' => $group,
'name' => self::GROUPS[$group],
'help' => self::GROUP_HELP[$group],
'granted' => in_array($group, $decision['granted'] ?? [], true),
],
$this->askedGroups(),
),
'decided' => null !== $decision,
'decidedAt' => $decision['at'] ?? null,
'text' => $settings['consentText'],
'privacyPath' => $settings['privacyPath'],
'imprintPath' => $settings['imprintPath'],
];
}
}
+51
View File
@@ -50,6 +50,57 @@ final class DemoContent
}
/** The first draft of a newly created page: valid, empty enough to replace, with exactly one H1. */
/**
* The two pages a German business website must have. Not demo content and not optional: they
* are created with a skeleton whose gaps are marked, because the text is a legal statement
* about a real company - the CMS can prepare the structure, not write the declaration.
*/
public const LEGAL = [
'datenschutz' => 'Datenschutzerklärung',
'impressum' => 'Impressum',
];
public static function legalPage(string $kind): array
{
$sections = 'impressum' === $kind
? [
['Angaben gemäß § 5 DDG', "Firmenname\nStraße und Hausnummer\nPostleitzahl und Ort\n\nNOCH AUSZUFÜLLEN: Rechtsform, Vertretungsberechtigte, Registergericht und Registernummer, Umsatzsteuer-Identifikationsnummer."],
['Kontakt', "Telefon: \nE-Mail: \n\nNOCH AUSZUFÜLLEN: eine Adresse, unter der eine Anfrage tatsächlich beantwortet wird."],
['Verantwortlich für den Inhalt', 'NOCH AUSZUFÜLLEN: Name und Adresse der verantwortlichen Person, falls von oben abweichend. Bei redaktionellen Inhalten nach § 18 Abs. 2 MStV erforderlich.'],
['Streitschlichtung', 'NOCH AUSZUFÜLLEN oder entfernen: Hinweis auf eine Verbraucherschlichtungsstelle, sofern eine Teilnahmepflicht besteht.'],
]
: [
['Verantwortliche Stelle', "Firmenname\nStraße und Hausnummer\nPostleitzahl und Ort\nE-Mail: \n\nNOCH AUSZUFÜLLEN: gegebenenfalls Datenschutzbeauftragte oder Datenschutzbeauftragter mit Kontaktdaten."],
['Welche Daten beim Besuch anfallen', "Beim Aufruf dieser Website verarbeitet der Server technisch notwendige Daten: abgerufene Adresse, Zeitpunkt, übertragene Datenmenge, Browser- und Betriebssystemangaben sowie die IP-Adresse.\n\nNOCH AUSZUFÜLLEN: Speicherdauer der Serverprotokolle und Name des Hosters, mit dem ein Vertrag über die Auftragsverarbeitung besteht."],
['Cookies und Einwilligung', "Diese Website setzt von sich aus keine Cookies zur Analyse oder Werbung. Wird eine Einwilligung abgefragt, speichert ein einzelnes Cookie dieser Website ausschließlich die Entscheidung selbst – ohne Kennung, für ein halbes Jahr. Die Entscheidung lässt sich jederzeit unter /einwilligung ändern.\n\nNOCH PRÜFEN: Dieser Abschnitt muss zu den tatsächlich eingebundenen Inhalten passen."],
['Eingebettete Inhalte anderer Anbieter', 'NOCH AUSZUFÜLLEN: Für jeden eingebetteten Inhalt Anbieter, Zweck, Rechtsgrundlage und Empfängerland angeben. Ohne Einwilligung wird ein solcher Inhalt nicht geladen und es entsteht keine Verbindung zum Anbieter.'],
['Kontaktformular', 'NOCH AUSZUFÜLLEN: Welche Felder erhoben werden, wofür die Angaben verwendet werden, wie lange eine Anfrage gespeichert bleibt und auf welcher Rechtsgrundlage.'],
['Deine Rechte', 'Auskunft, Berichtigung, Löschung, Einschränkung der Verarbeitung, Datenübertragbarkeit und Widerspruch. Eine erteilte Einwilligung kann jederzeit widerrufen werden. Außerdem besteht ein Beschwerderecht bei einer Datenschutzaufsichtsbehörde.'],
];
$blocks = [
self::section('legal-hero', [
self::heading('legal-heading', self::LEGAL[$kind], 1),
self::text('legal-intro', 'Diese Seite wurde von KantSites angelegt und muss noch ausgefüllt werden. Die mit „NOCH AUSZUFÜLLEN“ markierten Stellen sind Pflichtangaben; der Text ist keine Rechtsberatung.'),
], 'mint'),
];
foreach ($sections as $index => [$title, $text]) {
$blocks[] = self::section('legal-'.$index, [
self::heading('legal-title-'.$index, $title, 2),
self::text('legal-text-'.$index, $text),
], 'paper', 'narrow');
}
return [
'schemaVersion' => 3,
'title' => self::LEGAL[$kind],
'description' => 'impressum' === $kind
? 'Anbieterkennzeichnung und Kontaktangaben.'
: 'Wie diese Website mit personenbezogenen Daten umgeht.',
'blocks' => $blocks,
];
}
public static function starter(string $title, string $type = 'page'): array
{
return [
+21 -2
View File
@@ -23,6 +23,8 @@ final class DocumentValidator
public const V9_TYPES = ['breadcrumb'];
/** Schema v11: a link to a reusable section, resolved when the page is served. */
public const V11_TYPES = ['partialref', 'menu'];
/** Schema v14: content from a third party, which stays unloaded until consent is given. */
public const V14_TYPES = ['embed'];
/**
* @param bool $requireHeading A page needs exactly one main heading. A header, a footer or a
@@ -32,7 +34,7 @@ final class DocumentValidator
public function validate(array $document, bool $requireHeading = true): void
{
$schemaVersion = $document['schemaVersion'] ?? null;
$this->require(in_array($schemaVersion, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], true), 'Unsupported document schema.');
$this->require(in_array($schemaVersion, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], true), 'Unsupported document schema.');
$this->text($document['title'] ?? null, 160);
$this->text($document['description'] ?? null, 320);
$this->require(is_array($document['blocks'] ?? null) && array_is_list($document['blocks']), 'Blocks must be a list.');
@@ -60,7 +62,7 @@ final class DocumentValidator
// page: a deactivated plugin must never make stored content unreadable. Nothing from
// props is rendered for such a block, so unvalidated values never reach the output.
$plugin = $schemaVersion >= 4 && is_string($type) && 1 === preg_match('/^[a-z][a-z0-9]{1,30}\.[a-z][a-z0-9-]{1,40}$/D', $type);
$this->require(in_array($type, ['section', 'row', 'column', 'heading', 'text', 'image', 'button'], true) || ($schemaVersion >= 3 && 'gallery' === $type) || ($schemaVersion >= 5 && 'postlist' === $type) || ($schemaVersion >= 6 && in_array($type, self::V6_TYPES, true)) || ($schemaVersion >= 7 && in_array($type, self::V7_TYPES, true)) || ($schemaVersion >= 8 && in_array($type, self::V8_TYPES, true)) || ($schemaVersion >= 9 && in_array($type, self::V9_TYPES, true)) || ($schemaVersion >= 11 && in_array($type, self::V11_TYPES, true)) || $plugin, 'Unknown block type. Preserve source until its plugin is available.');
$this->require(in_array($type, ['section', 'row', 'column', 'heading', 'text', 'image', 'button'], true) || ($schemaVersion >= 3 && 'gallery' === $type) || ($schemaVersion >= 5 && 'postlist' === $type) || ($schemaVersion >= 6 && in_array($type, self::V6_TYPES, true)) || ($schemaVersion >= 7 && in_array($type, self::V7_TYPES, true)) || ($schemaVersion >= 8 && in_array($type, self::V8_TYPES, true)) || ($schemaVersion >= 9 && in_array($type, self::V9_TYPES, true)) || ($schemaVersion >= 11 && in_array($type, self::V11_TYPES, true)) || ($schemaVersion >= 14 && in_array($type, self::V14_TYPES, true)) || $plugin, 'Unknown block type. Preserve source until its plugin is available.');
// An accordion entry only ever renders inside an accordion; at the top level or anywhere
// else it would produce a details element without its group.
$this->require('accordionitem' !== $type || 'accordion' === $parentType, 'An accordion entry belongs into an accordion.');
@@ -179,6 +181,23 @@ final class DocumentValidator
// change reaches every page that links it and a page cannot alter a shared section.
$this->require(is_string($props['partial'] ?? null) && 1 === preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $props['partial']) && strlen($props['partial']) <= 80, 'Invalid section address.');
}
if ('embed' === $type) {
// Everything about the embed is validated here, because the address ends up in an
// iframe and in the content security policy of the page.
$this->require(isset(Consent::GROUPS[$props['group'] ?? '']), 'Unbekannte Einwilligungsgruppe.');
// The title is what a screen reader announces for the frame, so it is not optional.
$this->text($props['title'] ?? null, 160);
$this->text($props['provider'] ?? null, 80);
$this->text($props['hint'] ?? null, 300, true);
$url = $props['url'] ?? null;
$this->require(is_string($url) && strlen($url) <= 400 && str_starts_with($url, 'https://'), 'Ein eingebetteter Inhalt braucht eine HTTPS-Adresse.');
$host = parse_url($url, PHP_URL_HOST);
// The host becomes part of frame-src, so it must be a plain name - no credentials, no
// port, nothing that could smuggle a second source into the policy.
$this->require(is_string($host) && 1 === preg_match('/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/D', $host), 'Die Adresse des eingebetteten Inhalts braucht einen einfachen Hostnamen.');
$this->require(null === parse_url($url, PHP_URL_PORT) && null === parse_url($url, PHP_URL_USER), 'Die Adresse darf keinen Port und keine Zugangsdaten enthalten.');
$this->require(is_int($props['height'] ?? null) && $props['height'] >= 150 && $props['height'] <= 1200, 'Die Höhe liegt zwischen 150 und 1200 Pixeln.');
}
if ('form' === $type) {
// Only the address is content. Fields, recipient and consent text stay in the database,
// so a stored document can never redirect a submission or change what is asked.
+1 -1
View File
@@ -9,7 +9,7 @@ use Doctrine\DBAL\Connection;
final class PageRepository
{
/** Reserved because the application already answers under these paths. */
public const RESERVED_SLUGS = ['admin', 'media', 'assets', 'favicon', 'kategorie', 'schlagwort', 'feed', 'beitraege'];
public const RESERVED_SLUGS = ['admin', 'media', 'assets', 'favicon', 'kategorie', 'schlagwort', 'feed', 'beitraege', 'einwilligung'];
public const MAX_DEPTH = 4;
public function __construct(private Connection $db, private DocumentValidator $validator, private SiteSettings $settings, private RichText $richText = new RichText())
+56
View File
@@ -27,6 +27,13 @@ final class SiteSettings
'robotsExtra' => '',
// Which stored page answers at the site root. Everything else derives from this.
'homePath' => 'home',
// The consent question. Off by default, because a site that loads nothing from third
// parties has nothing to ask about, and a banner without a reason is only in the way.
'consentBanner' => false,
'consentGroups' => ['external'],
'consentText' => '',
'privacyPath' => '',
'imprintPath' => '',
];
public function __construct(private Connection $db)
@@ -94,12 +101,61 @@ final class SiteSettings
}
$values['homePath'] = $home;
$values['consentBanner'] = (bool) ($input['consentBanner'] ?? false);
$values['consentGroups'] = array_values(array_intersect(
array_keys(Consent::GROUPS),
array_map(static fn (mixed $group): string => (string) $group, (array) ($input['consentGroups'] ?? [])),
));
$values['consentText'] = mb_substr(trim((string) ($input['consentText'] ?? '')), 0, 600);
foreach (['privacyPath', 'imprintPath'] as $key) {
$path = trim(trim((string) ($input[$key] ?? '')), '/');
if ('' !== $path && 1 !== preg_match('#^[a-z0-9]+(?:[-/][a-z0-9]+)*$#D', $path)) {
throw new InvalidPage('Die Adresse der Datenschutz- beziehungsweise Impressumsseite darf nur Kleinbuchstaben, Ziffern, Bindestriche und Schrägstriche enthalten.');
}
$values[$key] = $path;
}
// Privacy statement and imprint are not a feature that can be switched off: a German
// business website needs both, and both have to be reachable from every page. What the
// CMS cannot do is write them, so it only insists that the pages exist.
foreach (['privacyPath' => 'Datenschutzerklärung', 'imprintPath' => 'Impressum'] as $key => $label) {
if ('' !== $values[$key] && false === $this->db->fetchOne('SELECT id FROM page WHERE website_id = ? AND path = ? AND deleted_at IS NULL', ['default', $values[$key]])) {
throw new InvalidPage(sprintf('Es gibt keine Seite mit der Adresse /%s für die %s.', $values[$key], $label));
}
}
if ($values['consentBanner']) {
if ([] === $values['consentGroups']) {
throw new InvalidPage('Ohne eine Gruppe gibt es nichts zu fragen. Wähle mindestens eine, oder schalte den Hinweis ab.');
}
// A consent banner without a way to read the details is not consent.
if ('' === $values['privacyPath']) {
throw new InvalidPage('Ein Einwilligungshinweis braucht die Adresse der Datenschutzseite.');
}
}
$this->db->executeStatement('UPDATE website SET settings = ? WHERE id = ?', [
json_encode($values, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
'default',
]);
}
/**
* Which of the two mandatory pages are missing, by their settings key.
*
* @return array<string, string> key => label
*/
public function missingLegalPages(): array
{
$settings = $this->load();
$missing = [];
foreach (['privacyPath' => 'Datenschutzerklärung', 'imprintPath' => 'Impressum'] as $key => $label) {
if ('' === $settings[$key]) {
$missing[$key] = $label;
}
}
return $missing;
}
/** The stored path of the page that answers at the site root. */
public function homePath(): string
{