restruct / silverstripe-video-consent-gate
YouTube and Vimeo embeds that make no request to YouTube or Vimeo before consent: lite players behind a consent gate, a click-to-play placeholder with a self-hosted poster, and an opt-in filter for raw iframes in HTML content.
Package info
github.com/restruct/silverstripe-video-consent-gate
Type:silverstripe-vendormodule
pkg:composer/restruct/silverstripe-video-consent-gate
Requires
- php: ^8.1
- psr/simple-cache: ^1 || ^2 || ^3
- silverstripe/framework: ^5.4 || ^6
- silverstripe/vendor-plugin: ^2 || ^3
Requires (Dev)
- phpunit/phpunit: ^9.6 || ^11
Suggests
- ext-curl: Required for the poster endpoint: without it no poster is fetched (the placeholder image is served)
- fromholdio/silverstripe-embedfield: Render its EmbedObject (YouTube/Vimeo) through the consent gate via $VideoGate
Provides
None
Conflicts
None
Replaces
None
README
YouTube and Vimeo embeds that make no request to YouTube or Vimeo before the visitor consents.
A plain YouTube or Vimeo iframe contacts the provider the moment the page loads: the player, its scripts, the poster image, and (for YouTube) cookies or local storage, whether or not the visitor accepted them in your cookie banner. Under the GDPR and the ePrivacy rules that is processing without consent. This module replaces such embeds with:
- a click-to-play placeholder, rendered server-side: the video's own poster (served from your domain), a centred play button and a short note that the video plays via YouTube/Vimeo, which may set cookies;
- an inert
<lite-youtube>/<lite-vimeo>element, whose library is only imported after consent: either consent given in your consent banner (through a consent adapter), or the click on the placeholder, which counts as consent for the videos on that page only (nothing is stored); - once playing, privacy-friendlier players:
youtube-nocookie.comwithmodestbranding=2&rel=0, Vimeo withdnt=1, unlisted Vimeo videos (with theirh=hash) supported.
Requirements: PHP 8.1+, silverstripe/framework ^5.4 or ^6, ext-curl for the poster endpoint (without it the
neutral placeholder image is served). No CMS dependency; no front-end build step.
Install
composer require restruct/silverstripe-video-consent-gate
Then flush (?flush=1, or vendor/bin/sake db:build --flush on SS6, vendor/bin/sake dev/build flush=1 on SS5).
Use
In a template, from a YouTube or Vimeo URL (watch, share, embed, nocookie, shorts, playlist, vimeo.com page or
player URL; a start time in the URL, t=/start= or Vimeo's #t=, is kept):
$VideoGate($VideoURL, $Title)
From PHP:
use Restruct\Silverstripe\VideoConsentGate\Model\VideoRef; use Restruct\Silverstripe\VideoConsentGate\View\VideoGate; # From a URL; null when the URL is not a YouTube/Vimeo video $html = VideoGate::forUrl('https://youtu.be/dQw4w9WgXcQ', ['title' => 'Intro', 'width' => 640, 'height' => 480]); # From provider + id $html = VideoGate::create()->render(VideoRef::vimeo('76979871', 'ab12cd34ef'));
width/height only set the aspect ratio (16:9 when left out). Rendering adds the gate script (an ES module) and
the stylesheet through Requirements; switch that off to bundle them yourself:
Restruct\Silverstripe\VideoConsentGate\View\VideoGate: include_requirements: false
Content loaded later (AJAX) can be activated with initVideoConsentGate(root), exported by
client/dist/js/video-consent-gate.js.
Consent adapters
The gate asks a consent adapter whether consent is already given, and to call back when it is given later.
consent_adapter |
Behaviour |
|---|---|
none (default) |
No consent platform: every video waits for its click-to-play placeholder. |
consent-studio |
consent.studio: loads the players once the configured category (default marketing) is granted, now or later in the banner. |
custom |
Your own ES module, see below. |
Restruct\Silverstripe\VideoConsentGate\View\VideoGate: consent_adapter: consent-studio # consent.studio categories: functional, analytics, marketing consent_category: marketing
The consent.studio adapter reads window.consentStudio.api.consentState.has<Category>() and listens on window
for consent-studio__updated__granted__<category> and consent-studio__updated. Because the banner is often
injected asynchronously (for instance by a tag manager), it polls for window.consentStudio every 250 ms for up to
15 s, then also hooks consentStudio.lifecycle.deferUntilIntegrations(). Sources: the consent.studio
JavaScript API and
window events articles.
An unknown adapter name, or custom without a module, falls back to none: a configuration mistake never loads
players without consent.
Writing an adapter
An adapter is an ES module whose default export takes { category } and returns two functions:
// app/client/js/my-cmp-adapter.js export default function createAdapter({ category }) { return { // true when consent for the category is already known to be given hasConsent: () => !!window.MyCmp?.hasConsent(category), // call fn (once is enough) when consent is given later onConsent: (fn) => window.addEventListener('my-cmp:granted', fn), }; }
Restruct\Silverstripe\VideoConsentGate\View\VideoGate: consent_adapter: custom adapter_module: 'app: client/js/my-cmp-adapter.js'
client/dist/js/adapters/none.js and consent-studio.js are the reference implementations.
Output filter for raw iframes
YouTube/Vimeo iframes that editors paste into content (or that oEmbed inserted) bypass the gate. Two ways to gate them, both leaving the stored content unchanged:
Whole responses (the usual choice): an HTTP middleware, registered by the module, its iframe rewriting
off by default. (The same middleware adds missing gate assets to cached gate markup, on by default and
independent of enabled: see "Cached gate markup".)
Restruct\Silverstripe\VideoConsentGate\Filter\IframeFilterMiddleware: enabled: true # request paths it never touches (the CMS admin URL is added automatically) excluded_url_prefixes: [admin, dev]
It only rewrites text/html responses of front-end requests; JSON, XML, files, the CMS and dev tools pass through
untouched, and so does any HTML without a YouTube/Vimeo iframe, byte for byte. Each <iframe> whose src is a
YouTube (incl. nocookie, playlists) or Vimeo (incl. unlisted hash) embed becomes the gate, keeping its title and
its width/height aspect ratio; a paragraph that holds nothing but the iframe is replaced along with it.
The HTML is read in one forward pass, the way a browser tokenises it as far as it matters here: tags to their
real end (quotes only open a value right after =, / separates attributes), comments to -->, <! and <?
constructs to the first >, and the content of <script>, <style>, <textarea>, <title>, <noscript>,
<template> and similar elements to their end tag; iframes there are left alone. URLs are read the way a browser
repairs them (\ as /, missing slashes after the scheme, percent-encoded or dotted hosts). The filter fails
closed: any iframe whose src (or srcdoc, which browsers prefer) mentions youtube, youtu.be, ytimg or vimeo
and is not a video the lite players can show (a channel live stream, a Vimeo event, a look-alike host, an
unrecognised id) becomes a placeholder with the same note; it links out to the provider (new window, the URL
rebuilt from its parsed parts) only when the host really is the provider's. Other iframes are left alone.
Because the middleware runs after the page was rendered, it adds the gate stylesheet before </head> and
the script before </body> itself, each unless the page already loads it. Running it twice changes nothing more.
One field: $Content.VideoGated in a template (an extension on DBHTMLText), or
IframeRewriter::create()->rewrite($html) from PHP.
The module does not replace the HTMLText field class, so it does not clash with modules that do.
Cached gate markup
Rendering a gate adds its script and stylesheet through Requirements in that same request. Gate HTML served
from a cache was rendered in an earlier request, so nothing adds them and the page shows an unstyled placeholder
with a play button that does nothing. That happens with core's embed shortcode cache (EmbedShortcodeProvider
returns cached HTML without rendering, so a project template calling $VideoGate there is skipped), with
<% cached %> blocks, and with static or full-page caches that store a fragment. Two safety nets, both on by
default:
-
The middleware adds what is missing.
IframeFilterMiddleware(registered by the module) adds the stylesheet before</head>and the script before</body>to a front-end HTML document that contains a gate (data-vcg, ordata-vcg-externalfor a link-out placeholder, which only needs the stylesheet) but no<link>/<script>for that file. It works whether or not its iframe rewriting (enabled) is on:Restruct\Silverstripe\VideoConsentGate\Filter\IframeFilterMiddleware: # default true; false leaves pages with cached gate markup as they are add_missing_assets: true
On by default because it only acts when a gate is present and its assets are not: any other response, HEAD requests, 304 and other body-less or redirect responses, non-HTML, the CMS, dev tools and AJAX fragments (no
</head>) pass through byte for byte, at the cost of one string search per front-end HTML page. Without it, a cached gate is broken until the cache expires. A page served by a full-page cache that stores the final response (a CDN, a static publisher rendering through the app) already has the assets, because the middleware ran when it was rendered. -
The gate markup carries its own fallback, for sites that remove the middleware or put a cache in front of it that stores fragments: a module script tag inside each gate, and the stylesheet URL as
data-vcg-css. The script adds the stylesheet to<head>when no<link>on the page loads that file. It is asrcscript with no inline code, so ascript-src 'self'Content Security Policy allows it (under a nonce-only policy it is blocked like any script without the nonce; the middleware still covers that case). The URLs are the onesRequirementsuses, and a browser runs a module script once per URL, so the extra tags cost nothing whenRequirementsloads the script too; if cached markup carries an older URL (another?m=), the second copy finds every gate already handled and the stylesheet already linked, and does nothing. Link-out placeholders carry onlydata-vcg-css(nothing in them may load anything by itself); the middleware covers them. Switch the fallback off with:Restruct\Silverstripe\VideoConsentGate\View\VideoGate: template_asset_fallback: false
Neither adds anything when VideoGate.include_requirements is off: the project loads the assets itself, so make
sure every page that can show a gate does. The same goes for gates rendered with 'requirements' => false (no
template fallback; the middleware still adds assets to the page). If you combine the gate files into a bundle
under another name with Requirements::combine_files(), switch include_requirements off as well, or the
middleware adds the originals next to the bundle. Markup cached by 0.1.0 has no template fallback; the middleware
fixes those pages.
fromholdio/silverstripe-embedfield bridge
With fromholdio/silverstripe-embedfield installed, its
EmbedObject gains $VideoGate: the stored video (SourceURL, else URL) through the gate, with its stored
Title and the aspect ratio from Width/Height. It returns nothing for non-video embeds, so a theme override of
Fromholdio/EmbedField/Model/EmbedObject_video.ss can be:
<% if $VideoGate %>$VideoGate<% else %>$EmbedHTML<% end_if %>
The stored ThumbnailURL is deliberately not used as the poster: it points at the provider's image host, so
showing it would contact the provider before consent. The poster endpoint fetches the same image server-side.
The bridge class has a file-level class_exists guard and its config an Only: classexists condition, so the
module works (and flushes) without embedfield installed.
Poster endpoint
The placeholder's poster comes from /videoposter/youtube/<id>?s=<signature> and
/videoposter/vimeo/<id>?h=<hash>&s=<signature> on your own domain. The server fetches the image once, on first view, and caches it; the visitor's browser never contacts the
provider for it. YouTube: i.ytimg.com maxresdefault, falling back to hqdefault (not every video has the
former). Vimeo: the oEmbed API on vimeo.com, then its thumbnail_url on *.vimeocdn.com. Playlists have no
single poster and show a neutral placeholder. When no poster can be fetched, a neutral placeholder image is served
with a short cache lifetime.
Config (Restruct\Silverstripe\VideoConsentGate\Control\PosterController) |
Default |
|---|---|
url_segment |
videoposter |
max_age (browser cache of a poster, s) |
604800 (7 days) |
failure_max_age (browser cache of the placeholder, s) |
600 |
cache_ttl (server cache of a poster, s) |
2592000 (30 days) |
failure_ttl (server cache of a failed fetch, s) |
3600 |
signing_secret |
empty: SS_VIDEO_CONSENT_GATE_SECRET, else stored in the database (see below) |
Config (Restruct\Silverstripe\VideoConsentGate\Poster\PosterFetcher) |
Default |
|---|---|
max_bytes |
2097152 (2 MB) |
connect_timeout / timeout (s) |
3 / 5 |
allowed_mime_types |
image/jpeg, image/png, image/webp |
Cache storage. Posters are kept in Psr\SimpleCache\CacheInterface.VideoConsentGatePoster, by default a
plain Symfony FilesystemAdapter in TEMP_PATH/video-consent-gate (Poster\PosterCacheFactory). Not the
CacheFactory default on purpose: with opcache on that is PhpFilesAdapter, which compiles every entry into a PHP
file held in opcache, and with silverstripe/versioned it segments every cache per reading mode, which would store
each poster twice. Disk use is one file per video shown, typically 50 to 300 KB (max_bytes caps it at 2 MB), plus a
tiny entry per failed fetch; a flush of TEMP_PATH empties it and posters are fetched again on their next view.
Any PSR-16 cache can be swapped in through the Injector. Nothing is stored in assets.
Signed links. Every poster link carries s=, an HMAC-SHA256 (first 128 bits, hex) over provider|id|hash;
a request without a valid signature gets the neutral placeholder (short failure_max_age) without any cache or
upstream access. The endpoint therefore only fetches posters for videos your own pages link to. The secret is,
in this order: PosterController.signing_secret; the environment variable SS_VIDEO_CONSENT_GATE_SECRET
(recommended: any long random string); else a random 32-byte secret generated on first use and stored in the
database (table VideoConsentGate_Secret, one row, created by dev/build), so it survives releases and is the
same on every server. It is never derived from paths or credentials. In live mode without config or env value a
notice is logged recommending the env var. Changing the secret invalidates links already cached in pages or CDNs.
To move the endpoint, set url_segment and add a Director rule for it (the shipped rule for videoposter is in
the YAML block videoconsentgate-routes):
--- Name: app-videoposter After: '#videoconsentgate-routes' --- Restruct\Silverstripe\VideoConsentGate\Control\PosterController: url_segment: 'media/poster' SilverStripe\Control\Director: rules: 'media/poster': 'Restruct\Silverstripe\VideoConsentGate\Control\PosterController'
Security notes
The endpoint makes server-side requests on behalf of anonymous visitors, so it is built as an SSRF-sensitive endpoint:
- No URL comes from the request. Only a provider name and an id do, validated against strict patterns
(YouTube: 11 characters
[A-Za-z0-9_-]; Vimeo: up to 12 digits, optional hash up to 32 alphanumerics), and only with a valid signature (above). A malformed id or unknown provider is a 404, a bad signature the placeholder; neither causes an upstream request. - Fixed hosts. Upstream URLs are built on
i.ytimg.comandvimeo.com. The only URL taken from a response, Vimeo'sthumbnail_url, must behttpson*.vimeocdn.com, without port or credentials. - Address check at request time. The host is resolved (IPv4 through the system resolver, then AAAA) and every returned address must be public: loopback, private, carrier-grade NAT, link-local (including the cloud metadata address), unique-local, multicast, reserved, documentation, benchmarking, ORCHID, SIIT, local-use NAT64 and SRv6 ranges are refused, as are NAT64/6to4/mapped forms that embed such an IPv4 address. One refused answer refuses the host.
- The connection goes to the checked address (DNS rebinding). The fetch uses ext-curl directly
(
Net\CurlTransport), not an HTTP client library that may pick a stream handler and ignore these settings: the checked address is pinned withCURLOPT_RESOLVE(the URL's host still goes intoHostand TLS verification), and the address curl actually connected to is compared with it afterwards. A DNS answer that changes between check and connect cannot move the connection. Without ext-curl nothing is fetched (fail closed). - Transport limits. https only (
CURLOPT_PROTOCOLS), redirects returned but never followed, proxies from the environment ignored (CURLOPT_PROXY '',NOPROXY *), connect and total timeouts, and the size cap enforced both from a declaredContent-Length(CURLOPT_MAXFILESIZE) and while reading (the transfer is aborted as soon as more thanmax_bytesarrived). - Images only. The response must declare
image/jpeg,image/pngorimage/webpand its bytes must sniff as one of those. SVG is never accepted. Responses carryX-Content-Type-Options: nosniffand aContent-Security-Policy: default-src 'none'; sandbox. - Bounded upstream load. Failures are cached too (1 hour by default), so an invalid or removed video does not hit upstream on every view.
Titles and the player libraries
Both vendored libraries build their player iframe as an HTML string with the video title interpolated into
title="..."; because getAttribute() returns the decoded title, a title with a quote (an oEmbed title, an iframe's
title, a $VideoGate title) could inject attributes. The gate script patches both libraries after import to
build the iframe with DOM APIs, the template sets disablenoscript so lite-youtube does not build its noscript copy
from that string, and, as a second layer, VideoGate::cleanTitle() makes every title valid UTF-8 (Windows-1252 is
assumed for other bytes), drops control characters and < >, and turns " into '.
Styling
client/dist/css/video-consent-gate.css is plain CSS built on custom properties (--vcg-bg, --vcg-radius,
--vcg-button-bg, --vcg-note-bg, ...): override them in your own stylesheet, or switch include_requirements
off and style .vcg, .vcg__placeholder, .vcg__poster, .vcg__play, .vcg__note yourself. Keep the
data-vcg* attributes in the markup if you override the template
(templates/Restruct/Silverstripe/VideoConsentGate/View/VideoGate.ss): the gate script relies on them.
Translations
lang/en.yml and lang/nl.yml. Keys under Restruct\Silverstripe\VideoConsentGate\View\VideoGate: PLAY,
PLAY_SHORT, NOTE and WATCH_ON (with a {provider} placeholder), NEW_WINDOW.
Known behaviour
- iOS Safari needs a second tap. It will not autoplay an embedded player with sound from a tap outside the player, so after the placeholder tap the player appears and needs one more tap. Building the iframe directly with autoplay was tried and did not avoid it.
- Consent withdrawn later in the banner does not unload players already loaded on the current page; the next page view is gated again.
- Without JavaScript the placeholder stays and the video does not play.
- Once consented, the players behave as their libraries do (lite-youtube fetches its own poster from
i.ytimg.com, lite-vimeo uses Vimeo's oEmbed and CDN).
Third-party code
Vendored, unmodified apart from a header comment and the removed sourceMappingURL line, loaded by dynamic
import() only after consent:
| Package | Version | Licence | Path |
|---|---|---|---|
| @justinribeiro/lite-youtube | 1.9.0 | MIT | client/dist/vendor/lite-youtube/ |
| @slightlyoff/lite-vimeo | 0.1.4 | MIT | client/dist/vendor/lite-vimeo/ |
Both match the npm tarballs' published sha512 integrity. Both are patched at runtime by the gate script, not in
the vendored files: the player iframe is built with DOM APIs (see "Titles and the player libraries"), lite-youtube
builds no noscript copy, and lite-vimeo gets the unlisted-video hash for its thumbnail lookup and dnt=1&autoplay=1
for the player. tests/js/player-sinks.test.mjs (node --test tests/js/*.test.mjs) checks the patches against
the vendored files.
Tests
PHPUnit from a host project (see .github/workflows/ci.yml), plus node --test tests/js/*.test.mjs. No test
reaches the internet: HTTP is doubled, and the real-curl tests (CurlTransportTest, PinnedPosterFetchTest) start
php -S 127.0.0.2:<port> themselves, use *.localhost hosts (resolved to loopback by curl) and pin every
connection to 127.0.0.2; they skip when that server cannot start. CI also runs CurlTransportTest in a network
namespace with loopback only, where the runner allows it.
Licence
MIT, see LICENSE. The vendored libraries keep their own MIT licences (LICENSE files next to them).