source: Klonkt/src/services/StatsService.js@ 08ab8ad

main
Last change on this file since 08ab8ad was e3a5aed, checked in by roboburr <roboburr@…>, 2 months ago

feat(stats): let the admin exclude their own IP from statistics

Logged-in admins were already skipped, but an admin browsing logged out (incognito, another browser)
still inflated the numbers. Admin -> Statistics now shows your current IP with a one-click "Don't
count my visits" toggle, stored in a stats_exclude_ips app_setting and checked on every pageview
(recordPageview/recordPostView). Trust-proxy gives the real client IP; normalised for matching.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 7.9 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/i;
50function isBot(req) {
51 const ua = (req && req.headers && req.headers['user-agent']) || '';
52 if (!ua) return true; // empty UA = script/bot
53 return BOT_RE.test(ua);
54}
55
56// The client IP (trust-proxy gives the real one), normalised: drop an IPv4-mapped-IPv6 prefix
57// and a trailing :port so it matches what the admin sees + stores.
58function clientIp(req) {
59 let ip = (req && (req.ip || (req.socket && req.socket.remoteAddress))) || '';
60 if (ip.startsWith('::ffff:')) ip = ip.slice(7);
61 if (/^\d{1,3}(\.\d{1,3}){3}:\d+$/.test(ip)) ip = ip.split(':')[0];
62 return ip;
63}
64export function currentIp(req) { return clientIp(req); }
65
66// Admin-configured IPs to skip — so an owner browsing logged-OUT (incognito, another browser)
67// doesn't inflate their own stats. Stored as a comma-separated app_setting.
68export function getExcludedIps() {
69 return (getSetting('stats_exclude_ips', '') || '').split(',').map((s) => s.trim()).filter(Boolean);
70}
71export function setExcludedIps(list) {
72 const clean = [...new Set((list || []).map((s) => String(s).trim()).filter(Boolean))].slice(0, 20);
73 setSetting('stats_exclude_ips', clean.join(','));
74}
75function isExcludedIp(req) {
76 try { const ip = clientIp(req); return !!ip && getExcludedIps().includes(ip); } catch { return false; }
77}
78
79// Lazy prepares — tables only exist after initializeDatabase(); this module is
80// imported before that call.
81let _s = null;
82function stmts() {
83 if (_s) return _s;
84 _s = {
85 bumpDaily: db.prepare(`
86 INSERT INTO stat_daily (site_id, day, pageviews) VALUES (?, ?, 1)
87 ON CONFLICT(site_id, day) DO UPDATE SET pageviews = pageviews + 1
88 `),
89 addVisitor: db.prepare('INSERT OR IGNORE INTO stat_visitor_day (site_id, day, visitor_hash) VALUES (?, ?, ?)'),
90 bumpPost: db.prepare('UPDATE posts SET view_count = COALESCE(view_count, 0) + 1 WHERE id = ?'),
91 bumpTrack: db.prepare('UPDATE audio_tracks SET play_count = COALESCE(play_count, 0) + 1 WHERE id = ?'),
92 bumpReferrer: db.prepare(`
93 INSERT INTO stat_referrer (site_id, host, count) VALUES (?, ?, 1)
94 ON CONFLICT(site_id, host) DO UPDATE SET count = count + 1
95 `),
96 };
97 return _s;
98}
99
100// External referrer host from the Referer header (pro stats #5). Empty/own-site/
101// invalid referrers are skipped → only genuine external sources are counted.
102function recordReferrer(siteId, req) {
103 try {
104 const ref = req && req.headers && (req.headers.referer || req.headers.referrer);
105 if (!ref) return;
106 const host = new URL(ref).host.replace(/^www\./, '').toLowerCase();
107 if (!host) return;
108 const own = ((req.headers && req.headers.host) || '').replace(/^www\./, '').toLowerCase();
109 if (host === own) return; // internal navigation does not count as a source
110 stmts().bumpReferrer.run(siteId, host.slice(0, 120));
111 } catch { /* not a valid referrer URL → skip */ }
112}
113
114export function recordPageview(siteId, req) {
115 if (!siteId || isOperator(req) || isBot(req) || isExcludedIp(req)) return;
116 try {
117 const d = today();
118 stmts().bumpDaily.run(siteId, d);
119 stmts().addVisitor.run(siteId, d, visitorHash(req));
120 recordReferrer(siteId, req);
121 } catch { /* stats must never break a request */ }
122}
123
124export function recordPostView(post, req) {
125 if (!post || !post.id || isOperator(req) || isBot(req) || isExcludedIp(req)) return;
126 try {
127 stmts().bumpPost.run(post.id);
128 recordPageview(post.site_id, req);
129 } catch {}
130}
131
132export function recordPlay(trackId) {
133 if (!trackId) return;
134 try { stmts().bumpTrack.run(trackId); } catch {}
135}
136
137// Instance-wide statistics (solo = the site, hub = all sites combined).
138export function getStats(days = 14) {
139 days = [7, 14, 30, 90].includes(Number(days)) ? Number(days) : 14;
140 const pvMap = Object.fromEntries(
141 db.prepare('SELECT day, SUM(pageviews) AS pv FROM stat_daily GROUP BY day').all().map((r) => [r.day, r.pv]),
142 );
143 const visMap = Object.fromEntries(
144 db.prepare('SELECT day, COUNT(*) AS v FROM stat_visitor_day GROUP BY day').all().map((r) => [r.day, r.v]),
145 );
146 const series = [];
147 for (let i = days - 1; i >= 0; i--) {
148 const dt = new Date();
149 dt.setUTCDate(dt.getUTCDate() - i);
150 const d = dt.toISOString().slice(0, 10);
151 series.push({ day: d, pageviews: pvMap[d] || 0, visitors: visMap[d] || 0 });
152 }
153 const totals = {
154 pageviews: series.reduce((s, r) => s + r.pageviews, 0), // last N days
155 visitors: series.reduce((s, r) => s + r.visitors, 0), // sum of daily uniques (cookieless has no alternative)
156 plays: db.prepare('SELECT COALESCE(SUM(play_count), 0) AS n FROM audio_tracks').get().n,
157 postViews: db.prepare('SELECT COALESCE(SUM(view_count), 0) AS n FROM posts').get().n,
158 };
159 const topPosts = db.prepare(`
160 SELECT title, slug, COALESCE(view_count, 0) AS views FROM posts
161 WHERE status = 'published' ORDER BY view_count DESC, published_at DESC LIMIT 5
162 `).all();
163 const topTracks = db.prepare(`
164 SELECT title, COALESCE(play_count, 0) AS plays FROM audio_tracks
165 ORDER BY play_count DESC LIMIT 5
166 `).all();
167 // Top external sources (pro #5) — aggregated instance-wide per host.
168 let referrers = [];
169 try {
170 referrers = db.prepare(
171 'SELECT host, SUM(count) AS n FROM stat_referrer GROUP BY host ORDER BY n DESC LIMIT 10'
172 ).all();
173 } catch { referrers = []; }
174 // All-time totals (cookieless unique visitors = sum of daily uniques).
175 const allTime = {
176 pageviews: db.prepare('SELECT COALESCE(SUM(pageviews),0) AS n FROM stat_daily').get().n,
177 visitorDays: db.prepare('SELECT COUNT(*) AS n FROM stat_visitor_day').get().n,
178 };
179 return { totals, series, topPosts, topTracks, referrers, allTime, days };
180}
Note: See TracBrowser for help on using the repository browser.