source: Klonkt/src/services/StatsService.js@ 99a7b40

main
Last change on this file since 99a7b40 was cae8ded, checked in by Robin <roboburr@…>, 6 weeks ago

Een eerlijke User-Agent op al het uitgaande federatieverkeer

Robins vraag (31-7): welke UA gebruiken wij? Het federatieverkeer ging
met de kale Node-default de deur uit. safeFetch zet nu standaard
Klonkt/<versie> (+https://klonkt.com) op elk uitgaand verzoek; een
caller die zelf een User-Agent meegeeft (de EmbedResolver) wint. En het
spiegelbeeld-lek dicht: klonkt staat nu ook in de eigen bot-regex,
zodat een Klonkt-preview-fetch op een andere Klonkt niet als bezoeker
telt.

Changed files:
src/services/ActivityPubService.js

  • KLONKT_UA uit package.json-versie; safeFetch merge't hem als default in de headers

src/services/StatsService.js

  • BOT_RE + klonkt

test/stats-bots.test.js

  • de eigen embed-fetcher telt niet op een andere Klonkt

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 8.4 KB
Line 
1// StatsService — cookie-free statistics (premium module).
2//
3// Counters: posts.view_count, audio_tracks.play_count, and per day/site the number
4// of pageviews (stat_daily) + unique visitors (stat_visitor_day).
5//
6// Unique visitors WITHOUT cookies: a sha256 of IP+UA+daily-salt. The salt rotates
7// every day and is never stored longer → you cannot track someone across days,
8// and the raw IP is never persisted. No persistent identifier, no consent
9// banner required (Plausible/Fathom approach).
10
11import crypto from 'node:crypto';
12import db from '../config/database.js';
13import { getSetting, setSetting } from './SettingsService.js';
14
15function today() {
16 return new Date().toISOString().slice(0, 10); // YYYY-MM-DD (UTC)
17}
18
19// Daily rotating salt (cached in process, persisted in app_settings so that
20// a restart within the same day reuses the same salt).
21let _salt = null, _saltDay = null;
22function dailySalt() {
23 const d = today();
24 if (_salt && _saltDay === d) return _salt;
25 let stored = getSetting('stat_salt', null);
26 if (!stored || getSetting('stat_salt_day', null) !== d) {
27 stored = crypto.randomBytes(16).toString('hex');
28 setSetting('stat_salt', stored);
29 setSetting('stat_salt_day', d);
30 }
31 _salt = stored; _saltDay = d;
32 return stored;
33}
34
35function visitorHash(req) {
36 const ip = (req && (req.ip || (req.socket && req.socket.remoteAddress))) || '';
37 const ua = (req && req.headers && req.headers['user-agent']) || '';
38 return crypto.createHash('sha256').update(dailySalt() + '|' + ip + '|' + ua).digest('hex').slice(0, 32);
39}
40
41// Don't count the owner/admin — otherwise you inflate your own numbers.
42function isOperator(req) {
43 const u = req && req.session && req.session.user;
44 return !!(u && (u.role === 'god' || u.role === 'admin'));
45}
46
47// Skip known bots/crawlers + link-preview fetchers + scripts so they don't inflate
48// view/visitor-day counts. Empty UA = almost always automated.
49const BOT_RE = /bot|crawl|spider|slurp|mediapartners|bingpreview|facebookexternalhit|whatsapp|telegram|discord|twitter|linkedin|embedly|pinterest|redditbot|applebot|petalbot|yandex|baidu|duckduckbot|semrush|ahrefs|mj12|dotbot|uptimerobot|pingdom|statuscake|headless|lighthouse|gptbot|claude|ccbot|perplexity|bytespider|amazonbot|googleother|google-read-aloud|python-requests|scrapy|curl|wget|axios|node-fetch|go-http|java\/|okhttp|libwww|httpclient|mastodon|pleroma|akkoma|misskey|calckey|firefish|friendica|hubzilla|lemmy|pixelfed|peertube|gotosocial|honk|http\.rb|activitypub|klonkt/i;
50function isBot(req) {
51 const ua = (req && req.headers && req.headers['user-agent']) || '';
52 if (!ua) return true; // empty UA = script/bot
53 // A signed request or an ActivityPub content-negotiation is BY DEFINITION a
54 // server fetching, not a reader (Robins vraag, 31-7): one boosted post made
55 // every fediverse instance's link-preview fetch count as a unique visitor.
56 const h = (req && req.headers) || {};
57 if (h['signature']) return true;
58 if (/application\/(activity|ld)\+json/i.test(String(h['accept'] || ''))) return true;
59 return BOT_RE.test(ua);
60}
61
62// The client IP (trust-proxy gives the real one), normalised: drop an IPv4-mapped-IPv6 prefix
63// and a trailing :port so it matches what the admin sees + stores.
64function clientIp(req) {
65 let ip = (req && (req.ip || (req.socket && req.socket.remoteAddress))) || '';
66 if (ip.startsWith('::ffff:')) ip = ip.slice(7);
67 if (/^\d{1,3}(\.\d{1,3}){3}:\d+$/.test(ip)) ip = ip.split(':')[0];
68 return ip;
69}
70export function currentIp(req) { return clientIp(req); }
71
72// Admin-configured IPs to skip — so an owner browsing logged-OUT (incognito, another browser)
73// doesn't inflate their own stats. Stored as a comma-separated app_setting.
74export function getExcludedIps() {
75 return (getSetting('stats_exclude_ips', '') || '').split(',').map((s) => s.trim()).filter(Boolean);
76}
77export function setExcludedIps(list) {
78 const clean = [...new Set((list || []).map((s) => String(s).trim()).filter(Boolean))].slice(0, 20);
79 setSetting('stats_exclude_ips', clean.join(','));
80}
81function isExcludedIp(req) {
82 try { const ip = clientIp(req); return !!ip && getExcludedIps().includes(ip); } catch { return false; }
83}
84
85// Lazy prepares — tables only exist after initializeDatabase(); this module is
86// imported before that call.
87let _s = null;
88function stmts() {
89 if (_s) return _s;
90 _s = {
91 bumpDaily: db.prepare(`
92 INSERT INTO stat_daily (site_id, day, pageviews) VALUES (?, ?, 1)
93 ON CONFLICT(site_id, day) DO UPDATE SET pageviews = pageviews + 1
94 `),
95 addVisitor: db.prepare('INSERT OR IGNORE INTO stat_visitor_day (site_id, day, visitor_hash) VALUES (?, ?, ?)'),
96 bumpPost: db.prepare('UPDATE posts SET view_count = COALESCE(view_count, 0) + 1 WHERE id = ?'),
97 bumpTrack: db.prepare('UPDATE audio_tracks SET play_count = COALESCE(play_count, 0) + 1 WHERE id = ?'),
98 bumpReferrer: db.prepare(`
99 INSERT INTO stat_referrer (site_id, host, count) VALUES (?, ?, 1)
100 ON CONFLICT(site_id, host) DO UPDATE SET count = count + 1
101 `),
102 };
103 return _s;
104}
105
106// External referrer host from the Referer header (pro stats #5). Empty/own-site/
107// invalid referrers are skipped → only genuine external sources are counted.
108function recordReferrer(siteId, req) {
109 try {
110 const ref = req && req.headers && (req.headers.referer || req.headers.referrer);
111 if (!ref) return;
112 const host = new URL(ref).host.replace(/^www\./, '').toLowerCase();
113 if (!host) return;
114 const own = ((req.headers && req.headers.host) || '').replace(/^www\./, '').toLowerCase();
115 if (host === own) return; // internal navigation does not count as a source
116 stmts().bumpReferrer.run(siteId, host.slice(0, 120));
117 } catch { /* not a valid referrer URL → skip */ }
118}
119
120export function recordPageview(siteId, req) {
121 if (!siteId || isOperator(req) || isBot(req) || isExcludedIp(req)) return;
122 try {
123 const d = today();
124 stmts().bumpDaily.run(siteId, d);
125 stmts().addVisitor.run(siteId, d, visitorHash(req));
126 recordReferrer(siteId, req);
127 } catch { /* stats must never break a request */ }
128}
129
130export function recordPostView(post, req) {
131 if (!post || !post.id || isOperator(req) || isBot(req) || isExcludedIp(req)) return;
132 try {
133 stmts().bumpPost.run(post.id);
134 recordPageview(post.site_id, req);
135 } catch {}
136}
137
138export function recordPlay(trackId) {
139 if (!trackId) return;
140 try { stmts().bumpTrack.run(trackId); } catch {}
141}
142
143// Instance-wide statistics (solo = the site, hub = all sites combined).
144export function getStats(days = 14) {
145 days = [7, 14, 30, 90].includes(Number(days)) ? Number(days) : 14;
146 const pvMap = Object.fromEntries(
147 db.prepare('SELECT day, SUM(pageviews) AS pv FROM stat_daily GROUP BY day').all().map((r) => [r.day, r.pv]),
148 );
149 const visMap = Object.fromEntries(
150 db.prepare('SELECT day, COUNT(*) AS v FROM stat_visitor_day GROUP BY day').all().map((r) => [r.day, r.v]),
151 );
152 const series = [];
153 for (let i = days - 1; i >= 0; i--) {
154 const dt = new Date();
155 dt.setUTCDate(dt.getUTCDate() - i);
156 const d = dt.toISOString().slice(0, 10);
157 series.push({ day: d, pageviews: pvMap[d] || 0, visitors: visMap[d] || 0 });
158 }
159 const totals = {
160 pageviews: series.reduce((s, r) => s + r.pageviews, 0), // last N days
161 visitors: series.reduce((s, r) => s + r.visitors, 0), // sum of daily uniques (cookieless has no alternative)
162 plays: db.prepare('SELECT COALESCE(SUM(play_count), 0) AS n FROM audio_tracks').get().n,
163 postViews: db.prepare('SELECT COALESCE(SUM(view_count), 0) AS n FROM posts').get().n,
164 };
165 const topPosts = db.prepare(`
166 SELECT title, slug, COALESCE(view_count, 0) AS views FROM posts
167 WHERE status = 'published' ORDER BY view_count DESC, published_at DESC LIMIT 5
168 `).all();
169 const topTracks = db.prepare(`
170 SELECT title, COALESCE(play_count, 0) AS plays FROM audio_tracks
171 ORDER BY play_count DESC LIMIT 5
172 `).all();
173 // Top external sources (pro #5) — aggregated instance-wide per host.
174 let referrers = [];
175 try {
176 referrers = db.prepare(
177 'SELECT host, SUM(count) AS n FROM stat_referrer GROUP BY host ORDER BY n DESC LIMIT 10'
178 ).all();
179 } catch { referrers = []; }
180 // All-time totals (cookieless unique visitors = sum of daily uniques).
181 const allTime = {
182 pageviews: db.prepare('SELECT COALESCE(SUM(pageviews),0) AS n FROM stat_daily').get().n,
183 visitorDays: db.prepare('SELECT COUNT(*) AS n FROM stat_visitor_day').get().n,
184 };
185 return { totals, series, topPosts, topTracks, referrers, allTime, days };
186}
Note: See TracBrowser for help on using the repository browser.