@goosetools/goose-tools 0.0.0-stage → 0.1.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 +98 -2
- package/bin/goose-tools.js +61 -0
- package/lib/check/src/agent.js +90 -0
- package/lib/check/src/analyze.js +311 -0
- package/lib/check/src/client.js +136 -0
- package/lib/check/src/copy.js +355 -0
- package/lib/check/src/fixes.js +153 -0
- package/lib/check/src/frame.js +92 -0
- package/lib/check/src/guard.js +441 -0
- package/lib/check/src/index.js +18 -0
- package/lib/check/src/mcp-http.js +169 -0
- package/lib/check/src/mcp.js +153 -0
- package/lib/check/src/scan.js +55 -0
- package/lib/check/src/stack.js +61 -0
- package/lib/check/src/tlds.js +3 -0
- package/lib/check/src/view.js +130 -0
- package/lib/check/src/worker.js +257 -0
- package/lib/engine/src/bots.js +146 -0
- package/lib/engine/src/directives.js +131 -0
- package/lib/engine/src/exposure.js +70 -0
- package/lib/engine/src/frontend.js +157 -0
- package/lib/engine/src/headers.js +76 -0
- package/lib/engine/src/hidden-text.js +425 -0
- package/lib/engine/src/html.js +794 -0
- package/lib/engine/src/index.js +20 -0
- package/lib/engine/src/php.js +316 -0
- package/lib/engine/src/policies.js +234 -0
- package/lib/engine/src/reach.js +199 -0
- package/lib/engine/src/robots.js +275 -0
- package/lib/engine/src/secrets.js +142 -0
- package/lib/engine/src/signals.js +144 -0
- package/lib/rules/data/bots.json.js +1 -0
- package/lib/rules/data/exposure.json.js +1 -0
- package/lib/rules/data/frontend.json.js +1 -0
- package/lib/rules/data/headers.json.js +1 -0
- package/lib/rules/data/secrets.json.js +1 -0
- package/lib/ui/LICENSE-Inter.txt +93 -0
- package/lib/ui/assets.js +5 -0
- package/package.json +37 -4
- package/src/local.js +61 -0
- package/src/mcp.js +61 -0
- package/src/setup.js +395 -0
- package/src/site/auth.js +287 -0
- package/src/site/beacon.js +462 -0
- package/src/site/collect.js +484 -0
- package/src/site/handler.js +405 -0
- package/src/site/index.js +88 -0
- package/src/site/limits.js +48 -0
- package/src/site/pages.js +75 -0
- package/src/site/qr.js +318 -0
- package/src/site/reports.js +1117 -0
- package/src/site/source.js +68 -0
- package/src/site/store-pg.js +225 -0
- package/src/site/store.js +249 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Which kind of source sent a page view. A port of the WordPress plugin's Insights\Source (goose-tools/includes/src/
|
|
2
|
+
// Insights/Source.php), with the same lists, so both products name sources alike.
|
|
3
|
+
//
|
|
4
|
+
// Kinds: direct, search, social, ai, campaign, other, internal. AI assistant counts are a minimum: ChatGPT tags its
|
|
5
|
+
// links with utm_source=chatgpt.com and often sends no referrer, and some AI apps send neither, so part of their
|
|
6
|
+
// visits arrive as direct. Clicks from Google's AI Overviews and AI Mode arrive as Google search.
|
|
7
|
+
|
|
8
|
+
export const KINDS = ['search', 'ai', 'social', 'campaign', 'other', 'direct', 'internal'];
|
|
9
|
+
|
|
10
|
+
export const AI_HOSTS = ['chatgpt.com', 'chat.openai.com', 'perplexity.ai', 'claude.ai', 'copilot.microsoft.com', 'gemini.google.com'];
|
|
11
|
+
|
|
12
|
+
/** @type {[string, RegExp][]} */
|
|
13
|
+
export const SEARCH_HOSTS = [
|
|
14
|
+
['google.com', /^(www\.)?google\.(com?\.)?[a-z]{2,3}$/],
|
|
15
|
+
['bing.com', /^(www\.|cn\.)?bing\.com$/],
|
|
16
|
+
['duckduckgo.com', /^(html\.|lite\.)?duckduckgo\.com$/],
|
|
17
|
+
['search.yahoo.com', /^([a-z]{2}\.)?search\.yahoo\.(com|co\.jp)$/],
|
|
18
|
+
['yandex.com', /^(www\.)?(yandex\.(ru|com|com\.tr|by|kz|ua)|ya\.ru)$/],
|
|
19
|
+
['baidu.com', /^(www\.|m\.)?baidu\.com$/],
|
|
20
|
+
['ecosia.org', /^(www\.)?ecosia\.org$/],
|
|
21
|
+
['search.brave.com', /^search\.brave\.com$/],
|
|
22
|
+
['startpage.com', /^(www\.)?startpage\.com$/],
|
|
23
|
+
['qwant.com', /^(www\.)?qwant\.com$/],
|
|
24
|
+
['naver.com', /^(m\.)?search\.naver\.com$/],
|
|
25
|
+
['seznam.cz', /^(www\.|search\.)?seznam\.cz$/],
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
export const SOCIAL_HOSTS = ['facebook.com', 'messenger.com', 'instagram.com', 'threads.net', 'threads.com', 'x.com', 'twitter.com', 't.co', 'linkedin.com', 'lnkd.in', 'reddit.com', 'youtube.com', 'tiktok.com', 'pinterest.com', 'bsky.app', 'news.ycombinator.com', 'quora.com', 'tumblr.com', 'vk.com', 'mastodon.social', 't.me', 'discord.com', 'snapchat.com'];
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Kind and name of a page view's source. A utm_source tag decides first (an AI host as tag is AI, anything else a
|
|
32
|
+
* campaign), then a referrer from this site (internal), then the referrer's host, then nothing (direct).
|
|
33
|
+
* @param {{internal?: boolean, host?: string, utm?: string}} hit
|
|
34
|
+
* @returns {[kind: string, name: string]} name is '' for direct and internal.
|
|
35
|
+
*/
|
|
36
|
+
export function classify({ internal = false, host = '', utm = '' }) {
|
|
37
|
+
if (utm) {
|
|
38
|
+
const ai = listed(utm, AI_HOSTS);
|
|
39
|
+
return ai ? ['ai', ai] : ['campaign', utm];
|
|
40
|
+
}
|
|
41
|
+
if (internal) return ['internal', ''];
|
|
42
|
+
if (host) return hostSource(host);
|
|
43
|
+
return ['direct', ''];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {string} host Lower case.
|
|
48
|
+
* @returns {[string, string]}
|
|
49
|
+
*/
|
|
50
|
+
export function hostSource(host) {
|
|
51
|
+
const ai = listed(host, AI_HOSTS);
|
|
52
|
+
if (ai) return ['ai', ai];
|
|
53
|
+
for (const [name, re] of SEARCH_HOSTS) if (re.test(host)) return ['search', name];
|
|
54
|
+
if (/(^|\.)pinterest\.(com?\.)?[a-z]{2,3}$/.test(host)) return ['social', 'pinterest.com'];
|
|
55
|
+
const social = listed(host, SOCIAL_HOSTS);
|
|
56
|
+
if (social) return ['social', social];
|
|
57
|
+
return ['other', host.replace(/^www\./, '')];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The list entry a host equals or is a subdomain of, or ''.
|
|
62
|
+
* @param {string} host
|
|
63
|
+
* @param {string[]} hosts
|
|
64
|
+
*/
|
|
65
|
+
function listed(host, hosts) {
|
|
66
|
+
for (const e of hosts) if (host === e || host.endsWith('.' + e)) return e;
|
|
67
|
+
return '';
|
|
68
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// The site's own data in the site's own Postgres database (Supabase is Postgres), through the database client the
|
|
2
|
+
// site already has: `site({ setup, db })`. Design: spec/standalone-database.md in the goose-tools repo. The same calls
|
|
3
|
+
// and results as store.js (the SQLite file), so the route, the reports and the tests do not change.
|
|
4
|
+
//
|
|
5
|
+
// Clients: pg (node-postgres) and the Pool from @neondatabase/serverless (db.query, rows in .rows), Postgres.js
|
|
6
|
+
// (db.unsafe, rows as an array) and neon() over HTTP (db.query, rows as an array). Every statement is a plain string
|
|
7
|
+
// with $1 parameters, never a value written into the SQL, and never a prepared statement, so Supabase's transaction
|
|
8
|
+
// pooler works.
|
|
9
|
+
//
|
|
10
|
+
// Tables, in a schema of their own, goose_tools, so Supabase's Data API never serves them (it serves `public`), with
|
|
11
|
+
// row level security on and no policies, in case the owner ever exposes the schema:
|
|
12
|
+
// - totals (day, kind, key, n), settings (name, value), sessions (hash, expires), as in store.js.
|
|
13
|
+
import { KEEP_DAYS, MAX_KEYS_A_DAY, MAX_TABLE_BYTES, SUM_KEYS, CAPPED, COUNTED, shiftDay } from './limits.js';
|
|
14
|
+
|
|
15
|
+
const S = 'goose_tools';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Creates what is missing, once per process, in one statement (one round trip). Each step runs only when needed: a
|
|
19
|
+
* schema and tables that are there need no create rights, and turning on row level security, which locks the table,
|
|
20
|
+
* runs only where it is off (tables made before, or by hand).
|
|
21
|
+
*/
|
|
22
|
+
const SCHEMA = `DO $gt$ BEGIN
|
|
23
|
+
IF to_regnamespace('${S}') IS NULL THEN CREATE SCHEMA IF NOT EXISTS ${S}; END IF;
|
|
24
|
+
IF to_regclass('${S}.totals') IS NULL THEN CREATE TABLE IF NOT EXISTS ${S}.totals (day text NOT NULL, kind text NOT NULL, key text NOT NULL, n bigint NOT NULL, PRIMARY KEY (day, kind, key)); END IF;
|
|
25
|
+
IF to_regclass('${S}.settings') IS NULL THEN CREATE TABLE IF NOT EXISTS ${S}.settings (name text PRIMARY KEY, value text NOT NULL); END IF;
|
|
26
|
+
IF to_regclass('${S}.sessions') IS NULL THEN CREATE TABLE IF NOT EXISTS ${S}.sessions (hash text PRIMARY KEY, expires bigint NOT NULL); END IF;
|
|
27
|
+
IF NOT (SELECT relrowsecurity FROM pg_class WHERE oid = '${S}.totals'::regclass) THEN ALTER TABLE ${S}.totals ENABLE ROW LEVEL SECURITY; END IF;
|
|
28
|
+
IF NOT (SELECT relrowsecurity FROM pg_class WHERE oid = '${S}.settings'::regclass) THEN ALTER TABLE ${S}.settings ENABLE ROW LEVEL SECURITY; END IF;
|
|
29
|
+
IF NOT (SELECT relrowsecurity FROM pg_class WHERE oid = '${S}.sessions'::regclass) THEN ALTER TABLE ${S}.sessions ENABLE ROW LEVEL SECURITY; END IF;
|
|
30
|
+
END $gt$`;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* One page view's counts in one statement. New keys of a capped kind past MAX_KEYS_A_DAY that day count as '(other)',
|
|
34
|
+
* as store.js add() does: existing keys of the kind are counted, and each new key gets the next place (keys sent twice
|
|
35
|
+
* in one view share a place).
|
|
36
|
+
* Rows are written in one fixed order, so views at once that share rows (a country, a device, the home page) take
|
|
37
|
+
* their locks in the same order and never deadlock.
|
|
38
|
+
* It returns the day's counted views after this one (COUNTED 'all', 0 without that row), for the daily cap.
|
|
39
|
+
* $1 day, $2 kinds, $3 keys, $4 counts, $5 capped (per row), $6 MAX_KEYS_A_DAY, $7 COUNTED.
|
|
40
|
+
*/
|
|
41
|
+
const ADD = `WITH v AS (SELECT * FROM unnest($2::text[], $3::text[], $4::bigint[], $5::boolean[]) AS v(kind, key, n, capped)),
|
|
42
|
+
fresh AS (SELECT v.*, v.capped AND NOT EXISTS (SELECT 1 FROM ${S}.totals t WHERE t.day = $1 AND t.kind = v.kind AND t.key = v.key) AS new FROM v),
|
|
43
|
+
have AS (SELECT kind, COUNT(*) AS c FROM ${S}.totals WHERE day = $1 AND kind IN (SELECT kind FROM fresh WHERE new) GROUP BY kind),
|
|
44
|
+
placed AS (SELECT f.kind, f.key, f.n, CASE WHEN f.new THEN COALESCE(h.c, 0) + DENSE_RANK() OVER (PARTITION BY f.kind, f.new ORDER BY f.key) ELSE 0 END AS place FROM fresh f LEFT JOIN have h ON h.kind = f.kind),
|
|
45
|
+
b AS (SELECT kind, CASE WHEN place > $6 THEN '(other)' ELSE key END AS key, SUM(n) AS n FROM placed GROUP BY 1, 2),
|
|
46
|
+
w AS (INSERT INTO ${S}.totals (day, kind, key, n) SELECT $1, kind, key, n FROM b ORDER BY kind COLLATE "C", key COLLATE "C"
|
|
47
|
+
ON CONFLICT (day, kind, key) DO UPDATE SET n = ${S}.totals.n + excluded.n RETURNING kind, key, n)
|
|
48
|
+
SELECT COALESCE(MAX(n) FILTER (WHERE kind = $7 AND key = 'all'), 0)::float8 AS c FROM w`;
|
|
49
|
+
|
|
50
|
+
/** The SUM_KEYS largest keys of each kind over a period (store.js sumsSql). $1 from, $2 to, $3 kinds, $4 SUM_KEYS. */
|
|
51
|
+
const SUMS = `SELECT kind, key, n FROM (SELECT kind, key, SUM(n)::float8 AS n, ROW_NUMBER() OVER (PARTITION BY kind ORDER BY SUM(n) DESC, key COLLATE "C") AS r
|
|
52
|
+
FROM ${S}.totals WHERE day >= $1 AND day <= $2 AND kind = ANY($3::text[]) GROUP BY kind, key) s WHERE r <= $4 ORDER BY kind COLLATE "C", key COLLATE "C"`;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A function that runs one statement with the site's client and returns its rows.
|
|
56
|
+
* @param {any} db
|
|
57
|
+
* @returns {(text: string, values?: any[]) => Promise<any[]>}
|
|
58
|
+
*/
|
|
59
|
+
export function runner(db) {
|
|
60
|
+
// query first: neon() has both, and its unsafe() only makes a fragment for its templates, without running anything.
|
|
61
|
+
// Postgres.js has no query(); pg has no unsafe().
|
|
62
|
+
if (db && typeof db.query === 'function') {
|
|
63
|
+
return async (text, values = []) => {
|
|
64
|
+
const r = await db.query(text, values);
|
|
65
|
+
return Array.isArray(r) ? r : r.rows;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
if (db && typeof db.unsafe === 'function') return async (text, values = []) => Array.from(await db.unsafe(text, values));
|
|
69
|
+
throw new Error('goose-tools: db must be a Postgres client: pg (a Pool or Client), Postgres.js, or Neon (neon() or its Pool).');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The store, on the site's own Postgres.
|
|
74
|
+
* @param {any} db The site's Postgres client.
|
|
75
|
+
* @param {{maxBytes?: number}} [o] maxBytes: MAX_TABLE_BYTES, for tests.
|
|
76
|
+
*/
|
|
77
|
+
export function openPgStore(db, { maxBytes = MAX_TABLE_BYTES } = {}) {
|
|
78
|
+
const run = runner(db);
|
|
79
|
+
/** @type {Promise<void> | null} */
|
|
80
|
+
let ready = null;
|
|
81
|
+
let pruned = '';
|
|
82
|
+
/** Whether the totals table had passed maxBytes at the day's check: then no new keys of CAPPED kinds that day. */
|
|
83
|
+
let full = false;
|
|
84
|
+
/** Runs once per process; tried again on the next call if it failed (the database was down). */
|
|
85
|
+
const setup = () =>
|
|
86
|
+
(ready ??= run(SCHEMA)
|
|
87
|
+
.catch((e) => {
|
|
88
|
+
// Two cold starts creating the tables at once: one of them loses the race, and the tables are there.
|
|
89
|
+
if (e && (e.code === '23505' || e.code === '42P07' || e.code === '42P06')) return;
|
|
90
|
+
throw e;
|
|
91
|
+
})
|
|
92
|
+
.then(
|
|
93
|
+
() => {},
|
|
94
|
+
(e) => {
|
|
95
|
+
ready = null;
|
|
96
|
+
throw e;
|
|
97
|
+
},
|
|
98
|
+
));
|
|
99
|
+
/** @param {string} text @param {any[]} [values] */
|
|
100
|
+
const q = async (text, values) => {
|
|
101
|
+
await setup();
|
|
102
|
+
return run(text, values);
|
|
103
|
+
};
|
|
104
|
+
const num = (/** @type {any} */ v) => Number(v);
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
db: null,
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Add one page view's counts to a day, in one statement.
|
|
111
|
+
* @param {string} day YYYY-MM-DD (UTC).
|
|
112
|
+
* @param {[kind: string, key: string, n?: number][]} rows
|
|
113
|
+
* @returns {Promise<number>} With a COUNTED row: the day's counted views after this one. Else 0.
|
|
114
|
+
*/
|
|
115
|
+
async add(day, rows) {
|
|
116
|
+
if (!rows.length) return 0;
|
|
117
|
+
if (pruned !== day) {
|
|
118
|
+
// Once a day per process, in one statement: days past KEEP_DAYS and expired sessions, and the table's size.
|
|
119
|
+
const [r] = await q(`WITH a AS (DELETE FROM ${S}.totals WHERE day < $1), b AS (DELETE FROM ${S}.sessions WHERE expires < $2) SELECT pg_total_relation_size('${S}.totals')::float8 AS size`, [shiftDay(day, -KEEP_DAYS), Math.floor(Date.now() / 1000)]);
|
|
120
|
+
full = num(r?.size ?? 0) > maxBytes;
|
|
121
|
+
pruned = day;
|
|
122
|
+
}
|
|
123
|
+
const r = await q(ADD, [day, rows.map((r) => r[0]), rows.map((r) => r[1]), rows.map((r) => r[2] ?? 1), rows.map((r) => CAPPED.has(r[0])), full ? 0 : MAX_KEYS_A_DAY, COUNTED]);
|
|
124
|
+
return num(r[0]?.c ?? 0);
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Totals between two days, inclusive.
|
|
129
|
+
* @param {string} from
|
|
130
|
+
* @param {string} to
|
|
131
|
+
* @returns {Promise<{day: string, kind: string, key: string, n: number}[]>}
|
|
132
|
+
*/
|
|
133
|
+
async totals(from, to) {
|
|
134
|
+
const r = await q(`SELECT day, kind, key, n::float8 AS n FROM ${S}.totals WHERE day >= $1 AND day <= $2 ORDER BY day, kind COLLATE "C", key COLLATE "C"`, [from, to]);
|
|
135
|
+
return r.map((x) => ({ day: x.day, kind: x.kind, key: x.key, n: num(x.n) }));
|
|
136
|
+
},
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* @param {string} from
|
|
140
|
+
* @param {string} to
|
|
141
|
+
* @param {string[]} kinds
|
|
142
|
+
* @returns {Promise<{kind: string, key: string, n: number}[]>}
|
|
143
|
+
*/
|
|
144
|
+
async sums(from, to, kinds) {
|
|
145
|
+
const r = await q(SUMS, [from, to, kinds, SUM_KEYS]);
|
|
146
|
+
return r.map((x) => ({ kind: x.kind, key: x.key, n: num(x.n) }));
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @param {string} from
|
|
151
|
+
* @param {string} to
|
|
152
|
+
* @param {string} kind
|
|
153
|
+
* @param {string[]} keys
|
|
154
|
+
* @returns {Promise<{day: string, key: string, n: number}[]>}
|
|
155
|
+
*/
|
|
156
|
+
async daily(from, to, kind, keys) {
|
|
157
|
+
const r = await q(`SELECT day, key, n::float8 AS n FROM ${S}.totals WHERE day >= $1 AND day <= $2 AND kind = $3 AND key = ANY($4::text[]) ORDER BY day`, [from, to, kind, keys]);
|
|
158
|
+
return r.map((x) => ({ day: x.day, key: x.key, n: num(x.n) }));
|
|
159
|
+
},
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* @param {string} kind
|
|
163
|
+
* @param {string} from
|
|
164
|
+
* @param {string} to
|
|
165
|
+
* @returns {Promise<{day: string, key: string, n: number}[]>}
|
|
166
|
+
*/
|
|
167
|
+
async rows(kind, from, to) {
|
|
168
|
+
const r = await q(`SELECT day, key, n::float8 AS n FROM ${S}.totals WHERE kind = $1 AND day >= $2 AND day <= $3`, [kind, from, to]);
|
|
169
|
+
return r.map((x) => ({ day: x.day, key: x.key, n: num(x.n) }));
|
|
170
|
+
},
|
|
171
|
+
|
|
172
|
+
/** @returns {Promise<string>} */
|
|
173
|
+
async firstDay() {
|
|
174
|
+
const r = await q(`SELECT MIN(day) AS d FROM ${S}.totals`);
|
|
175
|
+
return r[0]?.d ?? '';
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
/** @param {string} name @returns {Promise<string | null>} */
|
|
179
|
+
async get(name) {
|
|
180
|
+
const r = await q(`SELECT value FROM ${S}.settings WHERE name = $1`, [name]);
|
|
181
|
+
return r.length ? r[0].value : null;
|
|
182
|
+
},
|
|
183
|
+
/** @param {string} name @param {string} value */
|
|
184
|
+
async set(name, value) {
|
|
185
|
+
await q(`INSERT INTO ${S}.settings (name, value) VALUES ($1, $2) ON CONFLICT (name) DO UPDATE SET value = excluded.value`, [name, value]);
|
|
186
|
+
},
|
|
187
|
+
/** @param {string} name */
|
|
188
|
+
async remove(name) {
|
|
189
|
+
await q(`DELETE FROM ${S}.settings WHERE name = $1`, [name]);
|
|
190
|
+
},
|
|
191
|
+
/**
|
|
192
|
+
* Set a setting only if it still holds `old` (null: not set), in one statement, so two requests at once cannot
|
|
193
|
+
* both win (store.js setIf).
|
|
194
|
+
* @param {string} name @param {string | null} old @param {string} value
|
|
195
|
+
* @returns {Promise<boolean>} Whether it was set.
|
|
196
|
+
*/
|
|
197
|
+
async setIf(name, old, value) {
|
|
198
|
+
const r = old === null
|
|
199
|
+
? await q(`INSERT INTO ${S}.settings (name, value) VALUES ($1, $2) ON CONFLICT (name) DO NOTHING RETURNING 1 AS ok`, [name, value])
|
|
200
|
+
: await q(`UPDATE ${S}.settings SET value = $3 WHERE name = $1 AND value = $2 RETURNING 1 AS ok`, [name, old, value]);
|
|
201
|
+
return r.length > 0;
|
|
202
|
+
},
|
|
203
|
+
|
|
204
|
+
/** @param {string} hash @param {number} expires Unix seconds. */
|
|
205
|
+
async addSession(hash, expires) {
|
|
206
|
+
await q(`INSERT INTO ${S}.sessions (hash, expires) VALUES ($1, $2)`, [hash, expires]);
|
|
207
|
+
},
|
|
208
|
+
/** @param {string} hash @returns {Promise<number | null>} */
|
|
209
|
+
async session(hash) {
|
|
210
|
+
const r = await q(`SELECT expires::float8 AS expires FROM ${S}.sessions WHERE hash = $1`, [hash]);
|
|
211
|
+
const e = r.length ? num(r[0].expires) : 0;
|
|
212
|
+
return e > Math.floor(Date.now() / 1000) ? e : null;
|
|
213
|
+
},
|
|
214
|
+
/** @param {string} hash */
|
|
215
|
+
async dropSession(hash) {
|
|
216
|
+
await q(`DELETE FROM ${S}.sessions WHERE hash = $1`, [hash]);
|
|
217
|
+
},
|
|
218
|
+
async dropAllSessions() {
|
|
219
|
+
await q(`DELETE FROM ${S}.sessions`);
|
|
220
|
+
},
|
|
221
|
+
|
|
222
|
+
/** The site owns the client: closing it is the site's call. */
|
|
223
|
+
close() {},
|
|
224
|
+
};
|
|
225
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// The site's own data, in a SQLite file in the site (Node's built-in node:sqlite, Node 22.13 or later). Totals only:
|
|
2
|
+
// each page view adds to its day's counts in one upsert. No raw events, no visitor IDs, no rollup job.
|
|
3
|
+
//
|
|
4
|
+
// Tables:
|
|
5
|
+
// - totals (day, kind, key, n): one count per day and thing counted, for example ('2026-11-24', 'page', '/pricing', 12).
|
|
6
|
+
// - settings (name, value): the owner's sign-in (password hash, two-factor key, recovery codes), the site's steps.
|
|
7
|
+
// - sessions (hash, expires): signed-in browsers, by the SHA-256 of their cookie.
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import * as sqlite from 'node:sqlite';
|
|
11
|
+
import { Worker } from 'node:worker_threads';
|
|
12
|
+
|
|
13
|
+
import { KEEP_DAYS, MAX_KEYS_A_DAY, SUM_KEYS, CAPPED, COUNTED, shiftDay, today } from './limits.js';
|
|
14
|
+
|
|
15
|
+
export { KEEP_DAYS, MAX_KEYS_A_DAY, SUM_KEYS, CAPPED, shiftDay, today };
|
|
16
|
+
|
|
17
|
+
const Database = sqlite.Database ?? sqlite.DatabaseSync;
|
|
18
|
+
|
|
19
|
+
const SCHEMA = `
|
|
20
|
+
CREATE TABLE IF NOT EXISTS totals (day TEXT NOT NULL, kind TEXT NOT NULL, key TEXT NOT NULL, n INTEGER NOT NULL, PRIMARY KEY (day, kind, key)) WITHOUT ROWID;
|
|
21
|
+
CREATE TABLE IF NOT EXISTS settings (name TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;
|
|
22
|
+
CREATE TABLE IF NOT EXISTS sessions (hash TEXT PRIMARY KEY, expires INTEGER NOT NULL) WITHOUT ROWID;
|
|
23
|
+
`;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {string} file A path, or ':memory:' for tests.
|
|
27
|
+
*/
|
|
28
|
+
export function openStore(file) {
|
|
29
|
+
if (file !== ':memory:') fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true });
|
|
30
|
+
const db = new Database(file);
|
|
31
|
+
// The wait first: another process (a Next.js worker) may be creating the same file.
|
|
32
|
+
// NORMAL: in WAL mode a commit does not wait for the disk; a power cut can lose only the last few counts.
|
|
33
|
+
db.exec('PRAGMA busy_timeout = 2000; PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;' + SCHEMA);
|
|
34
|
+
|
|
35
|
+
const keyCount = db.prepare('SELECT COUNT(*) AS c FROM totals WHERE day = ? AND kind = ?');
|
|
36
|
+
const hasKey = db.prepare('SELECT 1 FROM totals WHERE day = ? AND kind = ? AND key = ?');
|
|
37
|
+
const countOf = db.prepare('SELECT n FROM totals WHERE day = ? AND kind = ? AND key = ?');
|
|
38
|
+
const getSetting = db.prepare('SELECT value FROM settings WHERE name = ?');
|
|
39
|
+
const putSetting = db.prepare('INSERT INTO settings (name, value) VALUES (?, ?) ON CONFLICT (name) DO UPDATE SET value = excluded.value');
|
|
40
|
+
const dropSetting = db.prepare('DELETE FROM settings WHERE name = ?');
|
|
41
|
+
let pruned = '';
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
db,
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Add one page view's counts to a day, in one statement.
|
|
48
|
+
* @param {string} day YYYY-MM-DD (UTC).
|
|
49
|
+
* @param {[kind: string, key: string, n?: number][]} rows
|
|
50
|
+
* @returns {number} With a COUNTED row: the day's counted views after this one. Else 0.
|
|
51
|
+
*/
|
|
52
|
+
add(day, rows) {
|
|
53
|
+
if (!rows.length) return 0;
|
|
54
|
+
if (pruned !== day) {
|
|
55
|
+
db.prepare('DELETE FROM totals WHERE day < ?').run(shiftDay(day, -KEEP_DAYS));
|
|
56
|
+
db.prepare('DELETE FROM sessions WHERE expires < ?').run(Math.floor(Date.now() / 1000));
|
|
57
|
+
pruned = day;
|
|
58
|
+
}
|
|
59
|
+
// Each kind's key count is read once and kept up to date here, so one beacon's new keys cannot pass the cap.
|
|
60
|
+
/** @type {Map<string, number>} */
|
|
61
|
+
const counts = new Map();
|
|
62
|
+
const bounded = rows.map(([kind, key, n = 1]) => {
|
|
63
|
+
if (CAPPED.has(kind) && !hasKey.get(day, kind, key)) {
|
|
64
|
+
if (!counts.has(kind)) counts.set(kind, /** @type {any} */ (keyCount.get(day, kind)).c);
|
|
65
|
+
const c = /** @type {number} */ (counts.get(kind));
|
|
66
|
+
if (c >= MAX_KEYS_A_DAY) return [kind, '(other)', n];
|
|
67
|
+
counts.set(kind, c + 1);
|
|
68
|
+
}
|
|
69
|
+
return [kind, key, n];
|
|
70
|
+
});
|
|
71
|
+
const sql = `INSERT INTO totals (day, kind, key, n) VALUES ${bounded.map(() => '(?, ?, ?, ?)').join(', ')} ON CONFLICT (day, kind, key) DO UPDATE SET n = n + excluded.n`;
|
|
72
|
+
db.prepare(sql).run(...bounded.flatMap(([kind, key, n]) => [day, kind, key, n]));
|
|
73
|
+
if (!rows.some((r) => r[0] === COUNTED)) return 0;
|
|
74
|
+
return Number(/** @type {any} */ (countOf.get(day, COUNTED, 'all'))?.n ?? 0);
|
|
75
|
+
},
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Totals between two days, inclusive.
|
|
79
|
+
* @param {string} from
|
|
80
|
+
* @param {string} to
|
|
81
|
+
* @returns {{day: string, kind: string, key: string, n: number}[]}
|
|
82
|
+
*/
|
|
83
|
+
totals(from, to) {
|
|
84
|
+
return /** @type {any} */ (db.prepare('SELECT day, kind, key, n FROM totals WHERE day >= ? AND day <= ? ORDER BY day, kind, key').all(from, to));
|
|
85
|
+
},
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Totals between two days, inclusive, summed per kind and key in SQLite: the SUM_KEYS largest keys of each of
|
|
89
|
+
* `kinds`. The dashboard reads these, so a flood of made-up paths cannot load every day's rows into memory. With a
|
|
90
|
+
* data file the sum runs in a worker thread with its own read-only connection, so the site keeps answering while a
|
|
91
|
+
* long period is summed.
|
|
92
|
+
* @param {string} from
|
|
93
|
+
* @param {string} to
|
|
94
|
+
* @param {string[]} kinds
|
|
95
|
+
* @returns {Promise<{kind: string, key: string, n: number}[]>}
|
|
96
|
+
*/
|
|
97
|
+
async sums(from, to, kinds) {
|
|
98
|
+
const args = [from, to, ...kinds, SUM_KEYS];
|
|
99
|
+
const sql = sumsSql(kinds.length);
|
|
100
|
+
if (file !== ':memory:') {
|
|
101
|
+
try {
|
|
102
|
+
return await inWorker(file, sql, args);
|
|
103
|
+
} catch {
|
|
104
|
+
// No worker here (a host that forbids threads): sum on this thread instead.
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return /** @type {any} */ (db.prepare(sql).all(...args));
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Day totals of one kind for some keys (the Pages and Sources tabs' days), between two days. Run like sums().
|
|
112
|
+
* @param {string} from
|
|
113
|
+
* @param {string} to
|
|
114
|
+
* @param {string} kind
|
|
115
|
+
* @param {string[]} keys
|
|
116
|
+
* @returns {Promise<{day: string, key: string, n: number}[]>}
|
|
117
|
+
*/
|
|
118
|
+
async daily(from, to, kind, keys) {
|
|
119
|
+
const args = [from, to, kind, JSON.stringify(keys)];
|
|
120
|
+
const sql = 'SELECT day, key, n FROM totals WHERE day >= ? AND day <= ? AND kind = ? AND key IN (SELECT value FROM json_each(?)) ORDER BY day';
|
|
121
|
+
if (file !== ':memory:') {
|
|
122
|
+
try {
|
|
123
|
+
return await inWorker(file, sql, args);
|
|
124
|
+
} catch {
|
|
125
|
+
// No worker here: read on this thread instead.
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return /** @type {any} */ (db.prepare(sql).all(...args));
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Day totals of one kind between two days, in no order.
|
|
133
|
+
* @param {string} kind
|
|
134
|
+
* @param {string} from
|
|
135
|
+
* @param {string} to
|
|
136
|
+
* @returns {{day: string, key: string, n: number}[]}
|
|
137
|
+
*/
|
|
138
|
+
rows(kind, from, to) {
|
|
139
|
+
return /** @type {any} */ (db.prepare('SELECT day, key, n FROM totals WHERE kind = ? AND day >= ? AND day <= ?').all(kind, from, to));
|
|
140
|
+
},
|
|
141
|
+
|
|
142
|
+
/** The first day any total is stored, or ''. */
|
|
143
|
+
firstDay() {
|
|
144
|
+
return /** @type {any} */ (db.prepare('SELECT MIN(day) AS d FROM totals').get())?.d ?? '';
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
/** @param {string} name */
|
|
148
|
+
get(name) {
|
|
149
|
+
const r = /** @type {any} */ (getSetting.get(name));
|
|
150
|
+
return r ? r.value : null;
|
|
151
|
+
},
|
|
152
|
+
/** @param {string} name @param {string} value */
|
|
153
|
+
set(name, value) {
|
|
154
|
+
putSetting.run(name, value);
|
|
155
|
+
},
|
|
156
|
+
/** @param {string} name */
|
|
157
|
+
remove(name) {
|
|
158
|
+
dropSetting.run(name);
|
|
159
|
+
},
|
|
160
|
+
/**
|
|
161
|
+
* Set a setting only if it still holds `old` (null: not set). Two requests at once cannot both win.
|
|
162
|
+
* @param {string} name @param {string | null} old @param {string} value
|
|
163
|
+
* @returns {boolean} Whether it was set.
|
|
164
|
+
*/
|
|
165
|
+
setIf(name, old, value) {
|
|
166
|
+
const r = /** @type {any} */ (getSetting.get(name));
|
|
167
|
+
if ((r ? r.value : null) !== old) return false;
|
|
168
|
+
putSetting.run(name, value);
|
|
169
|
+
return true;
|
|
170
|
+
},
|
|
171
|
+
|
|
172
|
+
/** @param {string} hash @param {number} expires Unix seconds. */
|
|
173
|
+
addSession(hash, expires) {
|
|
174
|
+
db.prepare('INSERT INTO sessions (hash, expires) VALUES (?, ?)').run(hash, expires);
|
|
175
|
+
},
|
|
176
|
+
/** @param {string} hash */
|
|
177
|
+
session(hash) {
|
|
178
|
+
const r = /** @type {any} */ (db.prepare('SELECT expires FROM sessions WHERE hash = ?').get(hash));
|
|
179
|
+
return r && r.expires > Math.floor(Date.now() / 1000) ? r.expires : null;
|
|
180
|
+
},
|
|
181
|
+
/** @param {string} hash */
|
|
182
|
+
dropSession(hash) {
|
|
183
|
+
db.prepare('DELETE FROM sessions WHERE hash = ?').run(hash);
|
|
184
|
+
},
|
|
185
|
+
dropAllSessions() {
|
|
186
|
+
db.exec('DELETE FROM sessions');
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
close() {
|
|
190
|
+
db.close();
|
|
191
|
+
},
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** @param {number} n Number of kinds. */
|
|
196
|
+
const sumsSql = (n) =>
|
|
197
|
+
`SELECT kind, key, n FROM (SELECT kind, key, SUM(n) AS n, ROW_NUMBER() OVER (PARTITION BY kind ORDER BY SUM(n) DESC, key) AS r FROM totals WHERE day >= ? AND day <= ? AND kind IN (${Array(n).fill('?').join(', ')}) GROUP BY kind, key) WHERE r <= ? ORDER BY kind, key`;
|
|
198
|
+
|
|
199
|
+
// The worker is plain CommonJS text, so a bundler (Next.js) carries it with this file and has no other file to find.
|
|
200
|
+
const WORKER = `
|
|
201
|
+
const { parentPort, workerData } = require('node:worker_threads');
|
|
202
|
+
const sqlite = require('node:sqlite');
|
|
203
|
+
const db = new (sqlite.DatabaseSync || sqlite.Database)(workerData, { readOnly: true });
|
|
204
|
+
db.exec('PRAGMA busy_timeout = 2000');
|
|
205
|
+
parentPort.on('message', ({ id, sql, args }) => {
|
|
206
|
+
try {
|
|
207
|
+
parentPort.postMessage({ id, rows: db.prepare(sql).all(...args) });
|
|
208
|
+
} catch (e) {
|
|
209
|
+
parentPort.postMessage({ id, error: String((e && e.message) || e) });
|
|
210
|
+
}
|
|
211
|
+
});`;
|
|
212
|
+
|
|
213
|
+
/** One worker per data file, started on first use. @type {Map<string, {worker: Worker, waiting: Map<number, [Function, Function]>, next: number}>} */
|
|
214
|
+
const workers = new Map();
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* @param {string} file
|
|
218
|
+
* @param {string} sql
|
|
219
|
+
* @param {any[]} args
|
|
220
|
+
* @returns {Promise<any[]>}
|
|
221
|
+
*/
|
|
222
|
+
function inWorker(file, sql, args) {
|
|
223
|
+
let w = workers.get(file);
|
|
224
|
+
if (!w) {
|
|
225
|
+
const worker = new Worker(WORKER, { eval: true, workerData: path.resolve(file) });
|
|
226
|
+
const waiting = new Map();
|
|
227
|
+
const fail = (/** @type {any} */ e) => {
|
|
228
|
+
workers.delete(file);
|
|
229
|
+
for (const [, [, reject]] of waiting) reject(e);
|
|
230
|
+
waiting.clear();
|
|
231
|
+
};
|
|
232
|
+
worker.on('message', ({ id, rows, error }) => {
|
|
233
|
+
const p = waiting.get(id);
|
|
234
|
+
waiting.delete(id);
|
|
235
|
+
if (p) error ? p[1](new Error(error)) : p[0](rows);
|
|
236
|
+
});
|
|
237
|
+
worker.on('error', fail);
|
|
238
|
+
worker.on('exit', () => fail(new Error('worker stopped')));
|
|
239
|
+
worker.unref(); // Never keeps the site's process running (after the listeners, which would ref it again).
|
|
240
|
+
w = { worker, waiting, next: 0 };
|
|
241
|
+
workers.set(file, w);
|
|
242
|
+
}
|
|
243
|
+
const id = ++w.next;
|
|
244
|
+
const ww = w;
|
|
245
|
+
return new Promise((resolve, reject) => {
|
|
246
|
+
ww.waiting.set(id, [resolve, reject]);
|
|
247
|
+
ww.worker.postMessage({ id, sql, args });
|
|
248
|
+
});
|
|
249
|
+
}
|