@harshankur/viewcounter 3.3.0 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -10
- package/constants.js +12 -1
- package/db/DatabaseManager.js +20 -4
- package/db/adminSchema.js +17 -0
- package/db/visitorSalt.js +137 -0
- package/middleware/validation.js +2 -0
- package/package.json +2 -2
- package/routes/analytics.js +1 -1
- package/tracker/tracker.js +54 -16
- package/utils/errorUtils.js +3 -0
- package/utils/privacyUtils.js +18 -3
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
[](https://viewcounter.harshankur.com)
|
|
4
4
|
[](LICENSE)
|
|
5
5
|
[](https://github.com/harshankur/viewcounter/actions/workflows/test.yml)
|
|
6
|
-
[](TEST_REPORT.md)
|
|
7
7
|
[](https://www.npmjs.com/package/@harshankur/viewcounter)
|
|
8
8
|
[](https://www.npmjs.com/package/@harshankur/viewcounter#provenance)
|
|
9
9
|
|
|
@@ -12,13 +12,48 @@ A comprehensive Node.js/Express analytics server for tracking website views with
|
|
|
12
12
|
## 📖 Documentation
|
|
13
13
|
Visit our [Interactive Documentation](https://viewcounter.harshankur.com) for detailed API specifications, debugging tips, and integration guides.
|
|
14
14
|
|
|
15
|
-
## 🛡️ GDPR
|
|
16
|
-
**
|
|
15
|
+
## 🛡️ Built for GDPR Compliance, Privacy-First
|
|
16
|
+
**Built for GDPR compliance, by design.** This project is built from the ground up to respect user privacy and adhere to modern ethical standards:
|
|
17
17
|
- **Nothing on the visitor's device**: no cookie, no localStorage, no sessionStorage, and no identifier sent with a view, so the tracker needs no consent banner under the ePrivacy rules on device storage. (The optional admin UI signs its operator in with a session cookie; tracking never sets one.)
|
|
18
18
|
- **Data Sovereignty**: You own your data. Analytics never leave your private infrastructure.
|
|
19
|
-
- **Minimal Collection**: records what analytics needs, each in a form that does not identify a person. [What Gets Tracked?](#what-gets-tracked) lists every field, where it comes from, and how it is stored; the raw IP address, the user agent, and the query string are never stored.
|
|
19
|
+
- **Minimal Collection**: records what analytics needs, each in a form that does not identify a person directly. [What Gets Tracked?](#what-gets-tracked) lists every field, where it comes from, and how it is stored; the raw IP address, the user agent, and the query string are never stored.
|
|
20
20
|
- **Bots left out**: crawlers, link previewers, and automated browsers are recognised and never stored, only counted per minute by name.
|
|
21
21
|
|
|
22
|
+
### What is still yours to do
|
|
23
|
+
|
|
24
|
+
ViewCounter does its part, and that is what "built for GDPR compliance" means.
|
|
25
|
+
Compliance itself belongs to whoever runs it, and a few things no software can
|
|
26
|
+
do for you:
|
|
27
|
+
|
|
28
|
+
- **Say so.** Mention in your privacy notice that visits are counted, what is
|
|
29
|
+
recorded ([What Gets Tracked?](#what-gets-tracked)), and for how long.
|
|
30
|
+
- **Have a legal basis.** For plain visit counting this is normally legitimate
|
|
31
|
+
interest; that judgement is yours to make and record.
|
|
32
|
+
- **Keep personal details out.** ViewCounter stores what you send in custom
|
|
33
|
+
event data and the optional `sessionId` as given. Do not put names, email
|
|
34
|
+
addresses, or account IDs there.
|
|
35
|
+
- **Answer requests.** During its window (a day by default) a visitor hash is
|
|
36
|
+
pseudonymous: whoever holds both the server secret and that window's salt
|
|
37
|
+
could tie it to a known address and browser. A few minutes after the window
|
|
38
|
+
ends the salt is deleted and, as long as no copy of it survives (next point),
|
|
39
|
+
nobody can, you included. What remains is a masked address
|
|
40
|
+
and coarse details. Treat it as personal data all the same: a visitor may
|
|
41
|
+
ask what is held or ask for erasure, which the admin UI does
|
|
42
|
+
([Deleting, and GDPR](#deleting-and-gdpr)).
|
|
43
|
+
- **Keep no copies of the salts.** The `_visitor_salts` table holds the salts
|
|
44
|
+
of the windows now running and nothing else. A copy of an old salt, wherever
|
|
45
|
+
it is, keeps the one thing whose deletion makes old hashes untraceable:
|
|
46
|
+
- **Backups**: exclude the table
|
|
47
|
+
(`mysqldump --ignore-table=<database>._visitor_salts`). Restoring without
|
|
48
|
+
it is harmless: a new salt is made on the next view.
|
|
49
|
+
- **The binary log**: MySQL 8 has it on by default and keeps 30 days, salts
|
|
50
|
+
included. If you do not replicate, turn it off (`skip-log-bin`) or leave
|
|
51
|
+
this database out of it (`binlog-ignore-db`); otherwise shorten
|
|
52
|
+
`binlog_expire_logs_seconds` to what you can accept. MariaDB has it off
|
|
53
|
+
unless you turned it on.
|
|
54
|
+
|
|
55
|
+
This is a description of the software, not legal advice.
|
|
56
|
+
|
|
22
57
|
### 🔄 Data Privacy Lifecycle
|
|
23
58
|
```mermaid
|
|
24
59
|
graph LR
|
|
@@ -39,7 +74,8 @@ We believe in total transparency regarding your visitors' data:
|
|
|
39
74
|
2. **Immediate Masking**: Before being saved, the IP is masked (IPv4 last octet zeroed; IPv6 interface identifier zeroed).
|
|
40
75
|
3. **Keyed, Not Just Hashed**: The visitor identifier is an HMAC-SHA-256 keyed with a 32-byte server secret generated on first run and stored at mode `0600`. This matters: an *unkeyed* hash of an IP is reversible by exhausting the 2^32 IPv4 space, which takes about an hour on one CPU core. Without the secret, that search is infeasible.
|
|
41
76
|
4. **Rotating**: The hash also mixes in a time window (`UNIQUE_VISITOR_WINDOW_HOURS`), so the same visitor hashes differently after each window and their visits cannot be linked over time.
|
|
42
|
-
5. **
|
|
77
|
+
5. **Salted, and the salt is thrown away**: each window has its own random salt, kept in the `_visitor_salts` table only while the window lasts and deleted a few minutes after it ends, by a timer, whether or not anyone visits. From then on the hashes of that window cannot be recomputed from a known address and browser by anyone, the secret's holder included. The salt is useless without the server secret, which is never in the database.
|
|
78
|
+
6. **Automated Guards**: [`tests/privacyFailSafe.test.js`](tests/privacyFailSafe.test.js) asserts that no raw IP or User-Agent reaches either the bound parameters *or* the SQL text of any statement, and that the hash is genuinely keyed. CI runs it on every push, so a change that started storing raw IPs would fail the build.
|
|
43
79
|
|
|
44
80
|
## ✨ Features
|
|
45
81
|
|
|
@@ -393,7 +429,10 @@ Content-Type: text/plain # or application/json
|
|
|
393
429
|
{"appId": "blog", "id": "<the id /registerView returned>", "ms": 42000, "scroll": 80}
|
|
394
430
|
```
|
|
395
431
|
How long the page was visible (`ms`, up to 6 hours) and how much of it had been
|
|
396
|
-
on screen (`scroll`, 0 to 100).
|
|
432
|
+
on screen (`scroll`, 0 to 100). `scroll` is optional: leave it out for a page
|
|
433
|
+
that fits its window, where there is nothing to scroll, and the view keeps no
|
|
434
|
+
depth and stays out of the scroll averages. The tracker script does this
|
|
435
|
+
itself. A later report can only raise either. Each
|
|
397
436
|
report also marks the view as seen just now, which keeps its visitor in the
|
|
398
437
|
admin's **Right now** for the next few minutes; the tracker script sends one
|
|
399
438
|
every half minute while the page is being read. A report
|
|
@@ -622,7 +661,7 @@ returned by any API.
|
|
|
622
661
|
|-------|-----------|-----------|-----|
|
|
623
662
|
| **Timestamp** | Server | When the view was recorded | Everything over time |
|
|
624
663
|
| **Masked IP** | Request | IPv4 with the last octet zeroed, IPv6 with the interface identifier zeroed | Abuse investigation at network level, never a person |
|
|
625
|
-
| **Visitor hash** | IP and User-Agent, with a secret | HMAC-SHA-256, keyed with a server secret, rotating every window | Unique views, visitors, and visits; never returned |
|
|
664
|
+
| **Visitor hash** | IP and User-Agent, with a secret | HMAC-SHA-256, keyed with a server secret and the window's salt, rotating every window; the salt is deleted when the window ends | Unique views, visitors, and visits; never returned |
|
|
626
665
|
| **Country** | IP, looked up in memory | Two-letter code | Where visitors are |
|
|
627
666
|
| **Region, City** | IP, with an optional [city database](#location-data) | Names, such as Bavaria and Munich | Where visitors are, more finely |
|
|
628
667
|
| **Language** | `Accept-Language` | Primary subtag only, such as `de` (never `de-CH`, never a list) | Which languages to write in |
|
|
@@ -635,7 +674,7 @@ returned by any API.
|
|
|
635
674
|
| **Device Size** | `deviceSize` | small, medium, large | Layout decisions |
|
|
636
675
|
| **Browser, OS, and versions** | User-Agent, parsed in memory | Names and versions, such as Chrome 140 on macOS 15 | Compatibility |
|
|
637
676
|
| **Device Type** | User-Agent | desktop, mobile, tablet, tv, console, wearable | Compatibility |
|
|
638
|
-
| **Time on page, Scroll depth, Last seen** | The tracker script's `/engage` report | Milliseconds visible (at most 6 hours); percent of the page seen; when the page last reported | Whether pages are read |
|
|
677
|
+
| **Time on page, Scroll depth, Last seen** | The tracker script's `/engage` report | Milliseconds visible (at most 6 hours); percent of the page seen, empty for a page that fits its window; when the page last reported | Whether pages are read |
|
|
639
678
|
| **Event Type, Event Data** | `/event` | Type name; JSON up to 4 kB, as your site sends it | Custom events |
|
|
640
679
|
| **Session ID** | `sessionId` (optional) | As your site sends it | Your own grouping; the tracker never sends one |
|
|
641
680
|
|
|
@@ -666,7 +705,10 @@ This setting prevents counting the same visitor multiple times within a time win
|
|
|
666
705
|
- If no: it is stored as a unique view
|
|
667
706
|
|
|
668
707
|
The window is also how often the visitor hash rotates, so it bounds how long
|
|
669
|
-
the same person counts as one visitor.
|
|
708
|
+
the same person counts as one visitor. It is the lifetime of the window's salt
|
|
709
|
+
as well: the longer the window, the longer a hash stays traceable by whoever
|
|
710
|
+
holds the secret and the salt. A day is what privacy-first analytics commonly
|
|
711
|
+
uses; lengthen it knowingly.
|
|
670
712
|
|
|
671
713
|
**Examples:**
|
|
672
714
|
- `24` (default): the same visitor counts once per day
|
|
@@ -692,7 +734,7 @@ because a browser on your site must be able to reach them. Everything that
|
|
|
692
734
|
- ✅ **Authenticated, scoped read API**: every analytics endpoint requires `x-api-key`, compared in constant time, and each key is authorized against the specific `appId` requested. Fails closed when unconfigured.
|
|
693
735
|
- ✅ **Separate admin tier**: provisioning apps uses its own credential; a read key cannot provision and an admin key cannot read.
|
|
694
736
|
- ✅ **Per-tenant rate limits**: an `appId`-keyed budget alongside the per-IP limit.
|
|
695
|
-
- ✅ **Keyed visitor hashing**: HMAC-SHA-256 with a persisted 32-byte server secret
|
|
737
|
+
- ✅ **Keyed visitor hashing**: HMAC-SHA-256 with a persisted 32-byte server secret and a per-window salt that is deleted when the window ends, so stored hashes are not reversible to an IP, and after their window not even recomputable.
|
|
696
738
|
- ✅ **SQL injection prevention**: every value is a bound parameter; the only interpolated identifier is `appId`, gated by the allowlist.
|
|
697
739
|
- ✅ **Explicit CORS allowlist**: no wildcard, and writes can be bound to registered origins per app.
|
|
698
740
|
- ✅ **Proxy-aware IP derivation**: client-supplied forwarding headers are not trusted unless `TRUST_PROXY` says so.
|
|
@@ -969,6 +1011,7 @@ automated browsers.
|
|
|
969
1011
|
| `data-spa` | `true` | Treat history changes as page views |
|
|
970
1012
|
| `data-hash` | none | Fragment prefixes, comma-separated (`#docs/,#spec/`), that count as their own page, for pages that route by fragment. Any other fragment stays part of the same page. A matching fragment is stored whole as part of the page, so list only prefixes whose fragments carry nothing private. As a referrer, such a page is its path alone |
|
|
971
1013
|
| `data-heartbeat` | `true` | Report time on page every half minute while the page is visible and in use, not only when it is hidden or left. It keeps the visitor in the admin's **Right now** while they read one page, and saves the time of a tab the browser closes without warning. It stops after half an hour without any input |
|
|
1014
|
+
| `data-campaigns` | `true` | Send the landing URL's `utm_*` tags with the view |
|
|
972
1015
|
| `data-outbound` | `true` | Record clicks on links to other sites, as `outbound` events |
|
|
973
1016
|
| `data-downloads` | `true` | Record clicks on downloads (pdf, zip, dmg, docx, and so on), as `download` events |
|
|
974
1017
|
| `data-respect-dnt` | `false` | Send nothing when the browser's Do Not Track is on |
|
package/constants.js
CHANGED
|
@@ -97,7 +97,7 @@ const DATABASE = {
|
|
|
97
97
|
QUERY_TIMEOUT_MS: 5_000,
|
|
98
98
|
CONNECT_TIMEOUT_MS: 10_000,
|
|
99
99
|
DEFAULT_PORT: 3306,
|
|
100
|
-
SCHEMA_VERSION: '
|
|
100
|
+
SCHEMA_VERSION: 'schema_v7',
|
|
101
101
|
/** Rows given a public_id per statement when backfilling an old table. */
|
|
102
102
|
BACKFILL_BATCH_SIZE: 500,
|
|
103
103
|
};
|
|
@@ -123,6 +123,14 @@ const PRIVACY = {
|
|
|
123
123
|
/** Owner-only. The secret is what makes visitor hashes irreversible. */
|
|
124
124
|
SECRET_FILE_MODE: 0o600,
|
|
125
125
|
SECRET_FILENAME: '.visitor-secret',
|
|
126
|
+
/**
|
|
127
|
+
* How long after its window ended a visitor salt may still exist, so that
|
|
128
|
+
* instances whose clocks differ by a little agree on the window's salt
|
|
129
|
+
* right up to its end.
|
|
130
|
+
*/
|
|
131
|
+
SALT_GRACE_MS: 5 * 60 * 1000,
|
|
132
|
+
/** How often ended windows' salts are looked for and deleted. */
|
|
133
|
+
SALT_PRUNE_INTERVAL_MS: 5 * 60 * 1000,
|
|
126
134
|
/** Rejects a key short enough to be guessable. */
|
|
127
135
|
MIN_API_KEY_LENGTH: 32,
|
|
128
136
|
/**
|
|
@@ -371,6 +379,8 @@ const ADMIN_SESSIONS_TABLE = '_admin_sessions';
|
|
|
371
379
|
const VIEW_LOG_TABLE = '_view_log';
|
|
372
380
|
/** Tracking requests that were not stored, counted per minute. */
|
|
373
381
|
const TRACKING_REJECTIONS_TABLE = '_tracking_rejections';
|
|
382
|
+
/** The salt of the current visitor-hash window, deleted when the window ends. */
|
|
383
|
+
const VISITOR_SALTS_TABLE = '_visitor_salts';
|
|
374
384
|
|
|
375
385
|
/** The tracking pipeline's own bounds. */
|
|
376
386
|
const TRACKING = {
|
|
@@ -540,6 +550,7 @@ module.exports = {
|
|
|
540
550
|
ADMIN_SESSIONS_TABLE,
|
|
541
551
|
VIEW_LOG_TABLE,
|
|
542
552
|
TRACKING_REJECTIONS_TABLE,
|
|
553
|
+
VISITOR_SALTS_TABLE,
|
|
543
554
|
TRACKING,
|
|
544
555
|
TRACKING_OUTCOME,
|
|
545
556
|
REJECTION_REASON,
|
package/db/DatabaseManager.js
CHANGED
|
@@ -33,6 +33,7 @@ const {
|
|
|
33
33
|
} = require('./adminSchema');
|
|
34
34
|
const LogRepository = require('./LogRepository');
|
|
35
35
|
const AdminRepository = require('./AdminRepository');
|
|
36
|
+
const { createVisitorSaltStore } = require('./visitorSalt');
|
|
36
37
|
|
|
37
38
|
/**
|
|
38
39
|
* Columns returned for a session lookup.
|
|
@@ -182,6 +183,7 @@ class DatabaseManager {
|
|
|
182
183
|
this.mode = config.mode || 'connect';
|
|
183
184
|
this.logs = new LogRepository(this);
|
|
184
185
|
this.admin = new AdminRepository(this);
|
|
186
|
+
this.visitorSalts = createVisitorSaltStore(() => this.pool);
|
|
185
187
|
}
|
|
186
188
|
|
|
187
189
|
/**
|
|
@@ -203,6 +205,10 @@ class DatabaseManager {
|
|
|
203
205
|
logger.info(`Assigned public IDs to ${result.backfilled} existing row(s) in '${appId}'`);
|
|
204
206
|
}
|
|
205
207
|
}
|
|
208
|
+
|
|
209
|
+
// From here on the salts of ended visitor-hash windows are deleted on
|
|
210
|
+
// the clock, whether or not anyone visits.
|
|
211
|
+
this.visitorSalts.start();
|
|
206
212
|
}
|
|
207
213
|
|
|
208
214
|
/** @throws {Error} when a query is attempted before initialize() */
|
|
@@ -457,12 +463,19 @@ class DatabaseManager {
|
|
|
457
463
|
|
|
458
464
|
// Privacy boundary. Neither the raw IP nor the raw User-Agent is bound
|
|
459
465
|
// into any statement below; only the masked address and the keyed,
|
|
460
|
-
// rotating hash derived from them.
|
|
466
|
+
// rotating hash derived from them. The hash is also salted with a
|
|
467
|
+
// value that is deleted when its window ends, so that afterwards not
|
|
468
|
+
// even the secret's holder can recompute it.
|
|
469
|
+
if (!visitorSecret) throw getError(ErrorType.SECRET_UNAVAILABLE);
|
|
470
|
+
const now = Date.now();
|
|
471
|
+
const salt = await this.visitorSalts.current(uniqueWindowHours, now);
|
|
461
472
|
const hashedVisitor = PrivacyUtils.generateVisitorHash(
|
|
462
473
|
ip,
|
|
463
474
|
userAgent,
|
|
464
475
|
visitorSecret,
|
|
465
476
|
uniqueWindowHours,
|
|
477
|
+
now,
|
|
478
|
+
salt,
|
|
466
479
|
);
|
|
467
480
|
const maskedIp = PrivacyUtils.maskIP(ip);
|
|
468
481
|
|
|
@@ -556,7 +569,8 @@ class DatabaseManager {
|
|
|
556
569
|
* what it had.
|
|
557
570
|
*
|
|
558
571
|
* @param {string} appId already validated
|
|
559
|
-
* @param {{ viewId: string, engagedMs: number, scrollDepth: number }} engagement
|
|
572
|
+
* @param {{ viewId: string, engagedMs: number, scrollDepth: number|null }} engagement
|
|
573
|
+
* `scrollDepth` is null for a page that did not scroll, which leaves the stored depth as it was
|
|
560
574
|
* @returns {Promise<boolean>} whether a view was updated
|
|
561
575
|
*/
|
|
562
576
|
async addEngagement(appId, { viewId, engagedMs, scrollDepth }) {
|
|
@@ -564,11 +578,12 @@ class DatabaseManager {
|
|
|
564
578
|
const [result] = await this.pool.query(
|
|
565
579
|
`UPDATE \`${appId}\`
|
|
566
580
|
SET engaged_ms = GREATEST(COALESCE(engaged_ms, 0), ?),
|
|
567
|
-
scroll_depth =
|
|
581
|
+
scroll_depth = CASE WHEN ? IS NULL THEN scroll_depth
|
|
582
|
+
ELSE GREATEST(COALESCE(scroll_depth, 0), ?) END,
|
|
568
583
|
last_seen_at = NOW()
|
|
569
584
|
WHERE public_id = ? AND ${LIVE_ROW}
|
|
570
585
|
AND timestamp > DATE_SUB(NOW(), INTERVAL ? HOUR)`,
|
|
571
|
-
[engagedMs, scrollDepth, viewId, TRACKING.ENGAGE_WINDOW_HOURS]
|
|
586
|
+
[engagedMs, scrollDepth, scrollDepth, viewId, TRACKING.ENGAGE_WINDOW_HOURS]
|
|
572
587
|
);
|
|
573
588
|
return result.affectedRows > 0;
|
|
574
589
|
}
|
|
@@ -813,6 +828,7 @@ class DatabaseManager {
|
|
|
813
828
|
* Gracefully close all connections
|
|
814
829
|
*/
|
|
815
830
|
async close() {
|
|
831
|
+
this.visitorSalts.stop();
|
|
816
832
|
if (this.pool) {
|
|
817
833
|
await this.pool.end();
|
|
818
834
|
this.pool = null;
|
package/db/adminSchema.js
CHANGED
|
@@ -14,6 +14,7 @@ const {
|
|
|
14
14
|
DATABASE,
|
|
15
15
|
FIELD_MAX_LENGTH,
|
|
16
16
|
TRACKING_REJECTIONS_TABLE,
|
|
17
|
+
VISITOR_SALTS_TABLE,
|
|
17
18
|
VIEW_LOG_TABLE,
|
|
18
19
|
} = require('../constants');
|
|
19
20
|
const { getError, logWarning, ErrorType, WarningType } = require('../utils/errorUtils');
|
|
@@ -61,6 +62,20 @@ const TRACKING_COLUMNS = [
|
|
|
61
62
|
{ name: 'last_seen_at', ddl: 'DATETIME DEFAULT NULL' },
|
|
62
63
|
];
|
|
63
64
|
|
|
65
|
+
/**
|
|
66
|
+
* The salt of the current visitor-hash window (db/visitorSalt.js). One row at
|
|
67
|
+
* a time: the rows of windows that have ended are deleted, which is the point.
|
|
68
|
+
*/
|
|
69
|
+
const VISITOR_SALTS_DDL = `
|
|
70
|
+
CREATE TABLE IF NOT EXISTS \`${VISITOR_SALTS_TABLE}\` (
|
|
71
|
+
\`rotation_hours\` INT UNSIGNED NOT NULL,
|
|
72
|
+
\`window_id\` BIGINT UNSIGNED NOT NULL,
|
|
73
|
+
\`salt\` CHAR(64) NOT NULL,
|
|
74
|
+
\`created_at\` DATETIME NOT NULL,
|
|
75
|
+
PRIMARY KEY (\`rotation_hours\`, \`window_id\`)
|
|
76
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
|
77
|
+
`;
|
|
78
|
+
|
|
64
79
|
/** Indexes the admin columns need, keyed by index name. */
|
|
65
80
|
const ADMIN_INDEXES = {
|
|
66
81
|
uq_public_id: 'UNIQUE INDEX `uq_public_id` (`public_id`)',
|
|
@@ -307,6 +322,7 @@ async function ensureLogTables(pool) {
|
|
|
307
322
|
await pool.query(VIEW_LOG_DDL);
|
|
308
323
|
await pool.query(TRACKING_REJECTIONS_DDL);
|
|
309
324
|
await pool.query(ADMIN_SESSIONS_DDL);
|
|
325
|
+
await pool.query(VISITOR_SALTS_DDL);
|
|
310
326
|
|
|
311
327
|
const viewLogColumns = await readColumns(pool, VIEW_LOG_TABLE);
|
|
312
328
|
for (const column of VIEW_LOG_ADDED_COLUMNS) {
|
|
@@ -325,6 +341,7 @@ module.exports = {
|
|
|
325
341
|
VIEW_LOG_ADDED_COLUMNS,
|
|
326
342
|
TRACKING_REJECTIONS_DDL,
|
|
327
343
|
ADMIN_SESSIONS_DDL,
|
|
344
|
+
VISITOR_SALTS_DDL,
|
|
328
345
|
NEW_TABLE_ADMIN_COLUMNS,
|
|
329
346
|
NEW_TABLE_ADMIN_INDEXES,
|
|
330
347
|
backfillPublicIds,
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The salt of each visitor-hash window.
|
|
3
|
+
*
|
|
4
|
+
* A visitor hash is keyed with the server secret and with a random salt that
|
|
5
|
+
* exists only for the window it belongs to. Once the window is over the salt
|
|
6
|
+
* is deleted, and from then on nobody, the operator included, can recompute a
|
|
7
|
+
* hash of that window from a known address and browser: the records it left
|
|
8
|
+
* can no longer be tied to anyone.
|
|
9
|
+
*
|
|
10
|
+
* The salt lives in the database so that a restart, or a second instance,
|
|
11
|
+
* within the window keeps telling the same visitors apart. It is useless
|
|
12
|
+
* without the server secret, which is never in the database.
|
|
13
|
+
*
|
|
14
|
+
* Deletion goes by the clock, not by traffic: a salt is removed a few minutes
|
|
15
|
+
* after its window ended (the grace covers instances whose clocks differ),
|
|
16
|
+
* by a timer and by every read, whether or not another view ever arrives.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const crypto = require('crypto');
|
|
20
|
+
|
|
21
|
+
const { PRIVACY, VISITOR_SALTS_TABLE } = require('../constants');
|
|
22
|
+
const PrivacyUtils = require('../utils/privacyUtils');
|
|
23
|
+
const { getError, logWarning, ErrorType, WarningType } = require('../utils/errorUtils');
|
|
24
|
+
|
|
25
|
+
const TABLE = `\`${VISITOR_SALTS_TABLE}\``;
|
|
26
|
+
const SALT_PATTERN = new RegExp(`^[0-9a-f]{${PRIVACY.SECRET_BYTES * 2}}$`);
|
|
27
|
+
const MS_PER_HOUR = 60 * 60 * 1000;
|
|
28
|
+
|
|
29
|
+
/** When the window `windowId` of length `hours` is over, in epoch millis. */
|
|
30
|
+
const windowEnd = (hours, windowId) => (windowId + 1) * hours * MS_PER_HOUR;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {() => { query: Function }} getPool the manager's pool, read on each use
|
|
34
|
+
* @returns {{
|
|
35
|
+
* current: (rotationHours: number, now?: number) => Promise<string>,
|
|
36
|
+
* prune: (now?: number) => Promise<number>,
|
|
37
|
+
* start: (intervalMs?: number) => void,
|
|
38
|
+
* stop: () => void,
|
|
39
|
+
* }}
|
|
40
|
+
*/
|
|
41
|
+
function createVisitorSaltStore(getPool) {
|
|
42
|
+
/**
|
|
43
|
+
* The salts in use, and the reads under way, by `hours:windowId`. The
|
|
44
|
+
* service hashes page views and custom events over different window
|
|
45
|
+
* lengths, so there is one entry per length in use: a handful at most.
|
|
46
|
+
* @type {Map<string, { salt?: string, promise?: Promise<string>, end: number }>}
|
|
47
|
+
*/
|
|
48
|
+
const windows = new Map();
|
|
49
|
+
let timer = null;
|
|
50
|
+
|
|
51
|
+
/** Forget, in memory too, every window that is over. */
|
|
52
|
+
function forgetEnded(now) {
|
|
53
|
+
for (const [key, entry] of windows) {
|
|
54
|
+
if (entry.end + PRIVACY.SALT_GRACE_MS <= now) windows.delete(key);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Delete the salt of every window that ended more than the grace ago.
|
|
60
|
+
* @param {number} [now] epoch millis
|
|
61
|
+
* @returns {Promise<number>} salts deleted
|
|
62
|
+
*/
|
|
63
|
+
async function prune(now = Date.now()) {
|
|
64
|
+
forgetEnded(now);
|
|
65
|
+
const [result] = await getPool().query(
|
|
66
|
+
`DELETE FROM ${TABLE} WHERE (window_id + 1) * rotation_hours * ${MS_PER_HOUR} + ? <= ?`,
|
|
67
|
+
[PRIVACY.SALT_GRACE_MS, now]);
|
|
68
|
+
return (result && result.affectedRows) || 0;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function read(hours, windowId, now) {
|
|
72
|
+
const pool = getPool();
|
|
73
|
+
// Whoever gets there first decides the window's salt; everyone reads that one.
|
|
74
|
+
await pool.query(
|
|
75
|
+
`INSERT IGNORE INTO ${TABLE} (rotation_hours, window_id, salt, created_at) VALUES (?, ?, ?, NOW())`,
|
|
76
|
+
[hours, windowId, crypto.randomBytes(PRIVACY.SECRET_BYTES).toString('hex')]);
|
|
77
|
+
const [rows] = await pool.query(
|
|
78
|
+
`SELECT salt FROM ${TABLE} WHERE rotation_hours = ? AND window_id = ?`, [hours, windowId]);
|
|
79
|
+
const salt = Array.isArray(rows) && rows[0] ? rows[0].salt : null;
|
|
80
|
+
// Failing closed is deliberate: a hash made without the salt would
|
|
81
|
+
// stay recomputable for ever while looking like the others.
|
|
82
|
+
if (typeof salt !== 'string' || !SALT_PATTERN.test(salt)) throw getError(ErrorType.SECRET_UNAVAILABLE);
|
|
83
|
+
// A new window is the moment the one before it ended.
|
|
84
|
+
await prune(now);
|
|
85
|
+
return salt;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
/**
|
|
90
|
+
* @param {number} rotationHours the unique-visitor window
|
|
91
|
+
* @param {number} [now] epoch millis; pass the same value to the hash
|
|
92
|
+
* @returns {Promise<string>} hex salt of the window `now` falls in
|
|
93
|
+
*/
|
|
94
|
+
async current(rotationHours, now = Date.now()) {
|
|
95
|
+
const hours = PrivacyUtils.rotationHours(rotationHours);
|
|
96
|
+
const windowId = PrivacyUtils.currentWindowId(hours, now);
|
|
97
|
+
const key = `${hours}:${windowId}`;
|
|
98
|
+
const known = windows.get(key);
|
|
99
|
+
if (known) return known.salt || known.promise;
|
|
100
|
+
|
|
101
|
+
const entry = { end: windowEnd(hours, windowId) };
|
|
102
|
+
entry.promise = read(hours, windowId, now).then((salt) => {
|
|
103
|
+
entry.salt = salt;
|
|
104
|
+
return salt;
|
|
105
|
+
}, (error) => {
|
|
106
|
+
// Nothing is remembered of a failed read: the next view tries again.
|
|
107
|
+
if (windows.get(key) === entry) windows.delete(key);
|
|
108
|
+
throw error;
|
|
109
|
+
});
|
|
110
|
+
windows.set(key, entry);
|
|
111
|
+
return entry.promise;
|
|
112
|
+
},
|
|
113
|
+
|
|
114
|
+
prune,
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Prune now and then on an interval, so a salt goes when its window
|
|
118
|
+
* ends even on a site nobody visits for days. The timer is unref'd:
|
|
119
|
+
* it never keeps the process alive on its own.
|
|
120
|
+
* @param {number} [intervalMs]
|
|
121
|
+
*/
|
|
122
|
+
start(intervalMs = PRIVACY.SALT_PRUNE_INTERVAL_MS) {
|
|
123
|
+
if (timer) return;
|
|
124
|
+
const run = () => prune().catch((cause) => logWarning(WarningType.SALT_PRUNE_FAILED, { cause: cause.message }));
|
|
125
|
+
run();
|
|
126
|
+
timer = setInterval(run, intervalMs);
|
|
127
|
+
timer.unref();
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
stop() {
|
|
131
|
+
clearInterval(timer);
|
|
132
|
+
timer = null;
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
module.exports = { createVisitorSaltStore };
|
package/middleware/validation.js
CHANGED
|
@@ -103,7 +103,9 @@ const validateEngage = (allowedValues) => [
|
|
|
103
103
|
.matches(UUID_PATTERN).withMessage('id must be a view ID'),
|
|
104
104
|
body('ms')
|
|
105
105
|
.isInt({ min: 0, max: TRACKING.MAX_ENGAGED_MS }).withMessage(`ms must be an integer between 0 and ${TRACKING.MAX_ENGAGED_MS}`),
|
|
106
|
+
// Absent for a page that fits its window: there was nothing to scroll.
|
|
106
107
|
body('scroll')
|
|
108
|
+
.optional({ values: 'null' })
|
|
107
109
|
.isInt({ min: 0, max: 100 }).withMessage('scroll must be an integer between 0 and 100'),
|
|
108
110
|
];
|
|
109
111
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@harshankur/viewcounter",
|
|
3
3
|
"description": "A middleware backend server that registers views to my db server when requested to register a view from my other projects.",
|
|
4
|
-
"version": "3.
|
|
4
|
+
"version": "3.4.0",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"engines": {
|
|
7
7
|
"node": ">=24"
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"i18n-iso-countries": "^7.14.0",
|
|
50
50
|
"jest": "^30.4.2",
|
|
51
51
|
"jest-html-reporter": "^4.4.0",
|
|
52
|
-
"supertest": "^7.
|
|
52
|
+
"supertest": "^7.3.1",
|
|
53
53
|
"topojson-client": "^3.1.0",
|
|
54
54
|
"world-atlas": "^2.0.2"
|
|
55
55
|
},
|
package/routes/analytics.js
CHANGED
|
@@ -480,7 +480,7 @@ function createAnalyticsRouter({ config, dbManager, isReady = () => true, geo =
|
|
|
480
480
|
const updated = await dbManager.addEngagement(appId, {
|
|
481
481
|
viewId: id,
|
|
482
482
|
engagedMs: Number(ms),
|
|
483
|
-
scrollDepth: Number(scroll),
|
|
483
|
+
scrollDepth: scroll === undefined || scroll === null ? null : Number(scroll),
|
|
484
484
|
});
|
|
485
485
|
if (!updated) reject(req, REJECTION_REASON.UNKNOWN_VIEW);
|
|
486
486
|
return res.status(HTTP_STATUS.NO_CONTENT).end();
|
package/tracker/tracker.js
CHANGED
|
@@ -1,17 +1,31 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* viewcounter tracker
|
|
2
|
+
* viewcounter tracker
|
|
3
|
+
*
|
|
4
|
+
* If you found this on a site you were visiting: this is viewcounter, a
|
|
5
|
+
* privacy-first view counter that the site runs on its own server. It is built
|
|
6
|
+
* for GDPR compliance:
|
|
7
|
+
* - it sets no cookie and stores nothing on your device;
|
|
8
|
+
* - it sends nothing that identifies you or your device;
|
|
9
|
+
* - the server never stores your IP address or your browser's user agent.
|
|
10
|
+
* It keeps a masked address, a visitor hash that changes every day by
|
|
11
|
+
* default, and coarse details such as your country, browser and system,
|
|
12
|
+
* so nothing it keeps identifies you directly.
|
|
13
|
+
* Check it yourself: the source is at https://github.com/harshankur/viewcounter
|
|
14
|
+
* and the homepage at https://viewcounter.harshankur.com.
|
|
15
|
+
*
|
|
16
|
+
* For site owners:
|
|
3
17
|
*
|
|
4
18
|
* <script defer src="https://your-server/tracker.js" data-app="blog"></script>
|
|
5
19
|
*
|
|
6
20
|
* Records a view of each page (including page changes in single-page apps),
|
|
7
|
-
* how long it was visible and
|
|
21
|
+
* how long it was visible and, on a page that scrolls, how far (reported when the page
|
|
8
22
|
* is hidden or left, and every half minute while it is being read), clicks on links to
|
|
9
23
|
* other sites and on downloads, and the campaign tags of the landing URL.
|
|
10
24
|
* The page before is sent as its origin and path only.
|
|
11
25
|
*
|
|
12
26
|
* It stores nothing on the visitor's device (no cookie, no localStorage, no
|
|
13
27
|
* sessionStorage), so it needs no consent banner, and it sends no identifier:
|
|
14
|
-
* the server tells repeat visits apart with a hash it rotates every day.
|
|
28
|
+
* the server tells repeat visits apart with a hash it rotates every day by default.
|
|
15
29
|
*
|
|
16
30
|
* Options, as attributes on the script tag:
|
|
17
31
|
* data-app="blog" required: the app ID the views belong to
|
|
@@ -23,6 +37,7 @@
|
|
|
23
37
|
* these as its own page (hash-routed pages)
|
|
24
38
|
* data-heartbeat="false" report time on page only when the page is
|
|
25
39
|
* hidden or left, not while it is being read
|
|
40
|
+
* data-campaigns="false" do not send the landing URL's utm_* tags
|
|
26
41
|
* data-outbound="false" do not record clicks on links to other sites
|
|
27
42
|
* data-downloads="false" do not record clicks on downloads
|
|
28
43
|
* data-respect-dnt="true" send nothing when Do Not Track is on
|
|
@@ -53,10 +68,19 @@
|
|
|
53
68
|
const IDLE_MS = 30 * 60 * 1000;
|
|
54
69
|
|
|
55
70
|
const deviceSize = () => (innerWidth < 768 ? 'small' : innerWidth < 1200 ? 'medium' : 'large');
|
|
56
|
-
/**
|
|
71
|
+
/**
|
|
72
|
+
* How much of the page has been on screen, from 0 to 100, or null for a
|
|
73
|
+
* page that fits the window: there is nothing to scroll, so "all of it"
|
|
74
|
+
* would say nothing about the reader.
|
|
75
|
+
*/
|
|
57
76
|
const seen = () => {
|
|
58
77
|
const height = Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0);
|
|
59
|
-
return height <=
|
|
78
|
+
return height <= innerHeight + 1 ? null : Math.min(100, Math.round(((scrollY + innerHeight) / height) * 100));
|
|
79
|
+
};
|
|
80
|
+
/** Note how far the page on screen has been scrolled, if it scrolls at all (it may have grown since it loaded). */
|
|
81
|
+
const measure = () => {
|
|
82
|
+
const depth = view ? seen() : null;
|
|
83
|
+
if (depth !== null) view.scroll = Math.max(view.scroll === null ? 0 : view.scroll, depth);
|
|
60
84
|
};
|
|
61
85
|
|
|
62
86
|
/** A URL's origin and path: its query and fragment can carry tokens or emails. */
|
|
@@ -85,10 +109,12 @@
|
|
|
85
109
|
function reportEngagement(of = view, alive = false) {
|
|
86
110
|
if (!of || !of.id) return;
|
|
87
111
|
const ms = Math.min(MAX_ENGAGED_MS, Math.round(of.visibleMs + (of.visibleSince === null ? 0 : performance.now() - of.visibleSince)));
|
|
88
|
-
|
|
112
|
+
const scroll = of.scroll === null ? -1 : of.scroll;
|
|
113
|
+
if (!alive && ms <= of.sentMs && scroll <= of.sentScroll) return;
|
|
89
114
|
of.sentMs = ms;
|
|
90
|
-
of.sentScroll =
|
|
91
|
-
|
|
115
|
+
of.sentScroll = scroll;
|
|
116
|
+
// A page that never scrolled reports its time alone.
|
|
117
|
+
const body = JSON.stringify({ appId: app, id: of.id, ms, scroll: of.scroll === null ? undefined : of.scroll });
|
|
92
118
|
// text/plain needs no CORS preflight, so the beacon survives the page closing.
|
|
93
119
|
if (!(navigator.sendBeacon && navigator.sendBeacon(`${base}engage`, new Blob([body], { type: 'text/plain' })))) {
|
|
94
120
|
fetch(`${base}engage`, { method: 'POST', body, keepalive: true, credentials: 'omit', headers: { 'Content-Type': 'text/plain' } })
|
|
@@ -98,11 +124,15 @@
|
|
|
98
124
|
|
|
99
125
|
function pageview() {
|
|
100
126
|
// The page being left stops counting here, and reports what it has.
|
|
127
|
+
// It is still the one on screen (a single-page app draws the next
|
|
128
|
+
// only after changing the address), so this is its last measure.
|
|
101
129
|
if (view) {
|
|
102
130
|
if (view.visibleSince !== null) view.visibleMs += performance.now() - view.visibleSince;
|
|
103
131
|
view.visibleSince = null;
|
|
132
|
+
measure();
|
|
104
133
|
reportEngagement();
|
|
105
134
|
}
|
|
135
|
+
const first = !view;
|
|
106
136
|
const params = new URLSearchParams({
|
|
107
137
|
appId: app,
|
|
108
138
|
deviceSize: deviceSize(),
|
|
@@ -112,10 +142,12 @@
|
|
|
112
142
|
});
|
|
113
143
|
// Only the campaign tags: the rest of a query string can carry
|
|
114
144
|
// emails, tokens, or IDs, and never leaves the page.
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
const
|
|
118
|
-
|
|
145
|
+
if (option('campaigns', true)) {
|
|
146
|
+
const query = new URLSearchParams(location.search);
|
|
147
|
+
for (const key of UTM) {
|
|
148
|
+
const value = query.get(key);
|
|
149
|
+
if (value) params.set(key, value.slice(0, 100));
|
|
150
|
+
}
|
|
119
151
|
}
|
|
120
152
|
|
|
121
153
|
const current = {
|
|
@@ -123,11 +155,15 @@
|
|
|
123
155
|
startedAt: Date.now(),
|
|
124
156
|
visibleMs: 0,
|
|
125
157
|
visibleSince: document.visibilityState === 'visible' ? performance.now() : null,
|
|
126
|
-
scroll:
|
|
158
|
+
scroll: null,
|
|
127
159
|
sentMs: 0,
|
|
128
|
-
sentScroll:
|
|
160
|
+
sentScroll: -1,
|
|
129
161
|
};
|
|
130
162
|
view = current;
|
|
163
|
+
// A page that has just loaded can be measured. After a navigation the
|
|
164
|
+
// old page is still on screen, and its depth is not the new one's:
|
|
165
|
+
// the new page is measured when it is scrolled, hidden, or reports.
|
|
166
|
+
if (first) measure();
|
|
131
167
|
fetch(`${base}registerView?${params}`, { keepalive: true, credentials: 'omit', referrerPolicy: 'no-referrer' })
|
|
132
168
|
.then((response) => (response.ok ? response.json() : null))
|
|
133
169
|
.then((result) => {
|
|
@@ -186,7 +222,7 @@
|
|
|
186
222
|
scrollQueued = true;
|
|
187
223
|
requestAnimationFrame(() => {
|
|
188
224
|
scrollQueued = false;
|
|
189
|
-
|
|
225
|
+
measure();
|
|
190
226
|
});
|
|
191
227
|
}, { passive: true });
|
|
192
228
|
|
|
@@ -195,12 +231,13 @@
|
|
|
195
231
|
if (document.visibilityState === 'hidden') {
|
|
196
232
|
if (view.visibleSince !== null) view.visibleMs += performance.now() - view.visibleSince;
|
|
197
233
|
view.visibleSince = null;
|
|
234
|
+
measure();
|
|
198
235
|
reportEngagement();
|
|
199
236
|
} else if (view.visibleSince === null) {
|
|
200
237
|
view.visibleSince = performance.now();
|
|
201
238
|
}
|
|
202
239
|
});
|
|
203
|
-
addEventListener('pagehide', () => reportEngagement());
|
|
240
|
+
addEventListener('pagehide', () => { measure(); reportEngagement(); });
|
|
204
241
|
|
|
205
242
|
// While the page is being read, report as it goes: the server then knows the
|
|
206
243
|
// visitor is still there, and a tab the browser kills without warning (common
|
|
@@ -215,6 +252,7 @@
|
|
|
215
252
|
if (!view || document.visibilityState !== 'visible' || performance.now() - lastInput > IDLE_MS) return;
|
|
216
253
|
// The server takes reports for a view for a day. A page open longer says no more.
|
|
217
254
|
if (Date.now() - view.startedAt > ENGAGE_WINDOW_MS) return;
|
|
255
|
+
measure();
|
|
218
256
|
reportEngagement(view, true);
|
|
219
257
|
}, HEARTBEAT_MS);
|
|
220
258
|
}
|
package/utils/errorUtils.js
CHANGED
|
@@ -48,6 +48,7 @@ const WarningType = {
|
|
|
48
48
|
TRACKING_LOG_WRITE_FAILED: 'TRACKING_LOG_WRITE_FAILED',
|
|
49
49
|
ADMIN_LOG_WRITE_FAILED: 'ADMIN_LOG_WRITE_FAILED',
|
|
50
50
|
TRASH_PURGE_FAILED: 'TRASH_PURGE_FAILED',
|
|
51
|
+
SALT_PRUNE_FAILED: 'SALT_PRUNE_FAILED',
|
|
51
52
|
};
|
|
52
53
|
|
|
53
54
|
/**
|
|
@@ -124,6 +125,8 @@ const WARNING_MESSAGES = {
|
|
|
124
125
|
`Automatic view log pruning failed: ${info?.cause}`,
|
|
125
126
|
[WarningType.TRASH_PURGE_FAILED]: (info) =>
|
|
126
127
|
`Automatic trash purge failed for '${info?.appId}': ${info?.cause}`,
|
|
128
|
+
[WarningType.SALT_PRUNE_FAILED]: (info) =>
|
|
129
|
+
`Could not delete the visitor salts of ended windows (it is tried again shortly): ${info?.cause}`,
|
|
127
130
|
};
|
|
128
131
|
|
|
129
132
|
/**
|
package/utils/privacyUtils.js
CHANGED
|
@@ -61,8 +61,17 @@ class PrivacyUtils {
|
|
|
61
61
|
* @returns {number}
|
|
62
62
|
*/
|
|
63
63
|
static currentWindowId(rotationHours, now = Date.now()) {
|
|
64
|
-
|
|
65
|
-
|
|
64
|
+
return Math.floor(now / (this.rotationHours(rotationHours) * MS_PER_HOUR));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The length of a rotation window, in hours: the unique-visitor window,
|
|
69
|
+
* and never less than MIN_ROTATION_HOURS.
|
|
70
|
+
* @param {number} rotationHours
|
|
71
|
+
* @returns {number}
|
|
72
|
+
*/
|
|
73
|
+
static rotationHours(rotationHours) {
|
|
74
|
+
return Math.max(Number(rotationHours) || 0, MIN_ROTATION_HOURS);
|
|
66
75
|
}
|
|
67
76
|
|
|
68
77
|
/**
|
|
@@ -80,6 +89,10 @@ class PrivacyUtils {
|
|
|
80
89
|
* @param {string} secret Server secret from utils/secretStore.js
|
|
81
90
|
* @param {number} [rotationHours] Window length, defaults to the unique-visitor window
|
|
82
91
|
* @param {number} [now] epoch millis, injectable for tests
|
|
92
|
+
* @param {string} [salt] The window's own salt (db/visitorSalt.js), which
|
|
93
|
+
* is deleted when the window ends. With it, a hash cannot be recomputed
|
|
94
|
+
* afterwards even by whoever holds the secret. Without it, the window
|
|
95
|
+
* id alone separates the windows, and the secret holder still can.
|
|
83
96
|
* @returns {string} HMAC-SHA-256 hex digest
|
|
84
97
|
* @throws {Error} ErrorType.SECRET_UNAVAILABLE when no secret is supplied
|
|
85
98
|
*/
|
|
@@ -89,6 +102,7 @@ class PrivacyUtils {
|
|
|
89
102
|
secret,
|
|
90
103
|
rotationHours = SERVER.DEFAULT_UNIQUE_VISITOR_WINDOW_HOURS,
|
|
91
104
|
now = Date.now(),
|
|
105
|
+
salt = '',
|
|
92
106
|
) {
|
|
93
107
|
if (!secret) {
|
|
94
108
|
// Failing closed is deliberate: silently hashing without the key
|
|
@@ -98,7 +112,8 @@ class PrivacyUtils {
|
|
|
98
112
|
}
|
|
99
113
|
|
|
100
114
|
const windowId = this.currentWindowId(rotationHours, now);
|
|
101
|
-
|
|
115
|
+
// The unsalted form is kept byte for byte, for callers that use this helper on its own.
|
|
116
|
+
const input = salt ? `${salt}|${ip}|${userAgent}|${windowId}` : `${ip}|${userAgent}|${windowId}`;
|
|
102
117
|
|
|
103
118
|
return crypto.createHmac('sha256', secret).update(input).digest('hex');
|
|
104
119
|
}
|