From 5c0a94f167c4542bacb8e049629840ba9ca6a44f Mon Sep 17 00:00:00 2001 From: Matthijs Iriks Date: Fri, 4 Dec 2026 05:35:30 +0100 Subject: [PATCH] Add the pulse script and the component for the public pages --- CHANGELOG.md | 1 + README.md | 3 +- TOKENS.md | 1 + resources/js/pulse.js | 105 +++++++++++++++++++++ resources/views/components/pulse.blade.php | 5 + src/Modules/Statistics/PulseController.php | 11 +++ src/Modules/Statistics/public-routes.php | 3 + tests/Feature/PulseScriptTest.php | 21 +++++ tests/Feature/StatisticsOffTest.php | 5 + 9 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 resources/js/pulse.js create mode 100644 resources/views/components/pulse.blade.php create mode 100644 tests/Feature/PulseScriptTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index d210bb0..8966498 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ the section is the text of the release in Gitea. join with `manager.revisions.types`. - Editor: Markdown fields get a toolbar, photos from the media library and a server-rendered preview (`POST /manager/markdown`); the media library gets a click-to-set focus point with a square preview. (No cropping or rotating: the file stays as uploaded.) +- Statistics: `` puts the counting script (`/pulse/pulse.js`, no cookies, honours Do Not Track) in the public pages of a site. ## v0.4.0 - 2026-12-04 diff --git a/README.md b/README.md index 5da0ca6..c1d9018 100644 --- a/README.md +++ b/README.md @@ -197,7 +197,8 @@ Off by default (`MANAGER_STATISTICS=true`). The site's own visitor statistics, w a visitor is a code made of the address, the browser and a random key that is deleted after a day (`manager:forget-visitor-keys`, scheduled daily), so a code cannot be traced back afterwards. A browser that sends `DNT` or `Sec-GPC` is not counted. -- **Reporting**: the pages of your site `POST` to `/pulse/view` (`{path, referrer, via, campaign}`, answers `{token}`) and, when the +- **The script**: put `` once in the layout of the public site (`:spa="true"` for a site with a client-side router). It loads `/pulse/pulse.js` (about 2 kB, plain JavaScript, no cookies or storage), reports the page and the time it was in view, and does nothing for a browser with Do Not Track or Global Privacy Control. With the module off the component prints nothing. Behind a Content-Security-Policy allow that one script address. +- **Reporting** (what the script does, for a site that wants to do it itself): the pages of your site `POST` to `/pulse/view` (`{path, referrer, via, campaign}`, answers `{token}`) and, when the visitor leaves, `/pulse/leave` (`{token, seconds}`). No session, rate limited (`manager.statistics.per_minute`). - **Which pages count**: only addresses you name, so nobody can fill the statistics with made-up ones: `manager.statistics.pages`, the posts under `manager.statistics.posts_path` (published ones only), and anything else through diff --git a/TOKENS.md b/TOKENS.md index 2f803d9..c4af3e0 100644 --- a/TOKENS.md +++ b/TOKENS.md @@ -40,3 +40,4 @@ Per stuk werk een rij; zie `dev/token-usage.py`. | 2026-12-04 | Lijsten zonder code (resources) en een eigen bundel met schermen van de site | - | claude-sonnet-5-5 | 27 | 29.948 | 54 | 45.009 | 5.852.776 | 0,08 | | 2026-12-04 | Revisies: geschiedenis van berichten en pagina's, met terugzetten | - | claude-sonnet-5-5 | 6 | 12.423 | 12 | 14.609 | 1.461.419 | 0,03 | | 2026-12-04 | De editor: opmaakknoppen, foto's in de tekst, voorbeeld en een scherpstelpunt in de bibliotheek | - | claude-sonnet-5-5 | 15 | 18.397 | 30 | 28.742 | 3.931.230 | 0,07 | +| 2026-12-04 | Het telscript en de Blade-component voor de publieke pagina's van de statistieken | - | claude-sonnet-5-5 | 8 | 9.037 | 16 | 15.948 | 2.254.948 | 0,04 | diff --git a/resources/js/pulse.js b/resources/js/pulse.js new file mode 100644 index 0000000..fcff87d --- /dev/null +++ b/resources/js/pulse.js @@ -0,0 +1,105 @@ +/* + * Reports a page view of the public site to the statistics of the manager, and how long the page was in view. + * No cookies, no storage, nothing about the visitor: the server decides what it keeps (see the README). A browser that + * asks not to be followed (Do Not Track, Global Privacy Control) is not counted, here and on the server. + * + * + * + * `data-spa` on the script tag: also report the pages a client-side router moves to (history.pushState). + */ +(function () { + 'use strict'; + + var script = document.currentScript; + var base = script && script.src ? script.src.replace(/\/pulse\.js(\?.*)?$/, '') : '/pulse'; + + if (navigator.doNotTrack === '1' || navigator.globalPrivacyControl === true) { + return; + } + + var token = null; + var visible = 0; + var shownAt = document.visibilityState === 'visible' ? Date.now() : null; + var sent = false; + + function params() { + return new URLSearchParams(location.search); + } + + function other(referrer) { + try { + return new URL(referrer).host !== location.host ? referrer : ''; + } catch (e) { + return ''; + } + } + + function report(path, referrer) { + var query = params(); + + fetch(base + '/view', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + credentials: 'omit', + keepalive: true, + body: JSON.stringify({ + path: path, + referrer: referrer, + via: query.get('via') || query.get('utm_source') || '', + campaign: query.get('utm_campaign') || '', + }), + }) + .then(function (response) { return response.ok ? response.json() : null; }) + .then(function (data) { token = data && data.token ? data.token : null; }) + .catch(function () {}); + } + + function leave() { + if (shownAt !== null) { + visible += Date.now() - shownAt; + shownAt = null; + } + + if (token && !sent && visible > 0) { + sent = true; + var body = JSON.stringify({ token: token, seconds: Math.min(Math.round(visible / 1000), 7200) }); + + if (!(navigator.sendBeacon && navigator.sendBeacon(base + '/leave', new Blob([body], { type: 'application/json' })))) { + fetch(base + '/leave', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: body, keepalive: true, credentials: 'omit' }).catch(function () {}); + } + } + } + + function resume() { + shownAt = shownAt === null && document.visibilityState === 'visible' ? Date.now() : shownAt; + sent = false; + } + + document.addEventListener('visibilitychange', function () { + document.visibilityState === 'hidden' ? leave() : resume(); + }); + window.addEventListener('pagehide', leave); + + report(location.pathname, other(document.referrer)); + + if (script && script.hasAttribute('data-spa')) { + var previous = location.pathname; + var push = history.pushState; + + history.pushState = function () { + var result = push.apply(this, arguments); + + if (location.pathname !== previous) { + leave(); + visible = 0; + token = null; + shownAt = Date.now(); + sent = false; + report(location.pathname, location.origin + previous); + previous = location.pathname; + } + + return result; + }; + } +})(); diff --git a/resources/views/components/pulse.blade.php b/resources/views/components/pulse.blade.php new file mode 100644 index 0000000..94f40d9 --- /dev/null +++ b/resources/views/components/pulse.blade.php @@ -0,0 +1,5 @@ +{{-- Counts the page in the statistics of the manager (module `statistics`). Put it once in the layout of the public site. --}} +@props(['spa' => false]) +@if (\Illuminate\Support\Facades\Route::has(\IriksIT\Manager\Support\Names::route('pulse.script'))) + +@endif diff --git a/src/Modules/Statistics/PulseController.php b/src/Modules/Statistics/PulseController.php index 2c1984c..d92ea17 100644 --- a/src/Modules/Statistics/PulseController.php +++ b/src/Modules/Statistics/PulseController.php @@ -5,6 +5,7 @@ namespace IriksIT\Manager\Modules\Statistics; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; +use Symfony\Component\HttpFoundation\BinaryFileResponse; /** * Where the public pages report a page view and the time spent on it. These routes run without @@ -12,6 +13,16 @@ use Illuminate\Http\Response; */ class PulseController { + /** The script of the public pages (`` puts it in the page). */ + public function script(): BinaryFileResponse + { + return response()->file(__DIR__.'/../../../resources/js/pulse.js', [ + 'Content-Type' => 'application/javascript', + 'Cache-Control' => 'public, max-age=3600', + 'X-Content-Type-Options' => 'nosniff', + ]); + } + public function view(Request $request, VisitRecorder $recorder): JsonResponse { // A browser that says its user does not want to be followed is not counted at all. diff --git a/src/Modules/Statistics/public-routes.php b/src/Modules/Statistics/public-routes.php index bec889e..da80677 100644 --- a/src/Modules/Statistics/public-routes.php +++ b/src/Modules/Statistics/public-routes.php @@ -5,6 +5,9 @@ use IriksIT\Manager\Modules\Statistics\PulseController; use IriksIT\Manager\Support\Names; // Visitors of the public site report a page view here. No session, no cookies. +// The script that does the reporting, and the component that puts it in a page: . +Route::get(trim((string) config('manager.statistics.pulse_path', 'pulse'), '/').'/pulse.js', [PulseController::class, 'script'])->name(Names::route('pulse.script')); + Route::prefix(trim((string) config('manager.statistics.pulse_path', 'pulse'), '/'))->middleware('throttle:manager-pulse')->group(function () { Route::post('/view', [PulseController::class, 'view'])->name(Names::route('pulse.view')); Route::post('/leave', [PulseController::class, 'leave'])->name(Names::route('pulse.leave')); diff --git a/tests/Feature/PulseScriptTest.php b/tests/Feature/PulseScriptTest.php new file mode 100644 index 0000000..d6d8fd1 --- /dev/null +++ b/tests/Feature/PulseScriptTest.php @@ -0,0 +1,21 @@ +get('/pulse/pulse.js')->assertOk()->assertHeader('Content-Type', 'application/javascript'); + $script = $response->getFile()->getContent(); + + expect($script)->toContain('/view', '/leave', 'doNotTrack', 'globalPrivacyControl', "credentials: 'omit'") + ->and($response->headers->get('Set-Cookie'))->toBeNull(); +}); + +it('has a component that puts the script in a page', function () { + $html = Blade::render(''); + + expect(trim($html))->toBe(''); + expect(Blade::render(''))->toContain('data-spa'); +}); diff --git a/tests/Feature/StatisticsOffTest.php b/tests/Feature/StatisticsOffTest.php index cc8210e..91f1e6a 100644 --- a/tests/Feature/StatisticsOffTest.php +++ b/tests/Feature/StatisticsOffTest.php @@ -1,5 +1,6 @@ postJson('/pulse/view', ['path' => '/'])->assertNotFound(); }); + +it('puts nothing in a page for the pulse component', function () { + expect(trim(Blade::render('')))->toBe(''); +});