@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,405 @@
|
|
|
1
|
+
// The /_gt/ route: standard Request in, Response out, so each framework needs only a thin wrapper (next.js, node.js).
|
|
2
|
+
//
|
|
3
|
+
// GET /_gt/s.js the page script (beacon.js)
|
|
4
|
+
// POST /_gt/e one page view (collect.js)
|
|
5
|
+
// GET /_gt/api/state {claimed, signedIn}
|
|
6
|
+
// POST /_gt/api/claim/start setup code -> a new authenticator key and its QR code
|
|
7
|
+
// POST /_gt/api/claim/finish setup code, password, and an authenticator code (or skip: true, two-factor off)
|
|
8
|
+
// -> signed in, 10 recovery codes when two-factor is on
|
|
9
|
+
// POST /_gt/api/login password and an authenticator or recovery code -> signed in
|
|
10
|
+
// POST /_gt/api/logout
|
|
11
|
+
// GET /_gt/api/overview the dashboard's data (signed in); /overview/insights and /overview/performance
|
|
12
|
+
// give one section, ?days= 7, 30, 90 or 180
|
|
13
|
+
// GET /_gt/api/insights/pages the Insights tabs (signed in), ?days= as above
|
|
14
|
+
// GET /_gt/api/insights/sources
|
|
15
|
+
// GET /_gt/api/performance/kinds Performance > Deep dives: speed by kind of page (signed in), ?days= as above
|
|
16
|
+
// GET /_gt/ and below the dashboard page (pages.js)
|
|
17
|
+
//
|
|
18
|
+
// Every answer is no-store and noindex. POSTs other than /e must come from this site (Sec-Fetch-Site or Origin).
|
|
19
|
+
import * as auth from './auth.js';
|
|
20
|
+
import { qrSvg } from './qr.js';
|
|
21
|
+
import { today, toMidnight, COUNTED } from './limits.js';
|
|
22
|
+
import { openPgStore } from './store-pg.js';
|
|
23
|
+
import { collect, readBody, within } from './collect.js';
|
|
24
|
+
import { BEACON_JS } from './beacon.js';
|
|
25
|
+
import { insightsOverview, insightsPages, insightsSources, performanceKinds, performanceOverview } from './reports.js';
|
|
26
|
+
import { page, noDataPage, font, APP_JS } from './pages.js';
|
|
27
|
+
|
|
28
|
+
export const BASE = '/_gt';
|
|
29
|
+
/** A pending authenticator key lasts this long between the two claim steps. */
|
|
30
|
+
const PENDING_SECONDS = 30 * 60;
|
|
31
|
+
/** Failed sign-ins allowed before each new try must wait (doubling, up to 15 minutes). */
|
|
32
|
+
const FREE_TRIES = 5;
|
|
33
|
+
const MAX_WAIT = 15 * 60;
|
|
34
|
+
const MAX_BODY = 4096;
|
|
35
|
+
/** Periods the dashboard offers, in days. */
|
|
36
|
+
export const PERIODS = [7, 30, 90, 180];
|
|
37
|
+
|
|
38
|
+
/** One store per data file per process. */
|
|
39
|
+
const stores = new Map();
|
|
40
|
+
|
|
41
|
+
/** @typedef {ReturnType<typeof import('./store.js').openStore> | ReturnType<typeof openPgStore>} Store */
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @typedef {object} Options
|
|
45
|
+
* @property {string} setup SHA-256 of the setup code (from `npx goose-tools setup`).
|
|
46
|
+
* @property {string} [data] SQLite file. Default .goose-tools/data.sqlite in the working directory.
|
|
47
|
+
* @property {string[]} [steps] Funnel steps: paths of the pages, in order.
|
|
48
|
+
* @property {any} [db] The site's own Postgres client (pg, Postgres.js or Neon). Without it, the SQLite file.
|
|
49
|
+
* @property {number} [dailyLimit] Counted views a day at most (UTC). Past it, counting stops until midnight UTC and
|
|
50
|
+
* the page script sends nothing, so hosts that bill per request are not called for each view. No limit without it.
|
|
51
|
+
* Named by the owner, 2026-11-25: "daily limit", never "cap", in anything an owner reads.
|
|
52
|
+
* @property {Store} [store] For tests.
|
|
53
|
+
* @property {() => number} [now] Milliseconds, for tests.
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
/** @param {Options} o */
|
|
57
|
+
export function createSite(o) {
|
|
58
|
+
if (!o || typeof o.setup !== 'string' || !/^[0-9a-f]{64}$/.test(o.setup)) throw new Error('goose-tools: the route needs setup, the hash `npx goose-tools setup` wrote.');
|
|
59
|
+
if (o.dailyLimit !== undefined && !(Number.isInteger(o.dailyLimit) && o.dailyLimit > 0)) throw new Error('goose-tools: dailyLimit must be a whole number of views a day, such as 10000.');
|
|
60
|
+
const cap = o.dailyLimit ?? 0;
|
|
61
|
+
const now = o.now ?? Date.now;
|
|
62
|
+
/** The day (UTC) this process saw the cap reached: no more writes that day, and the page script sends nothing. */
|
|
63
|
+
let stopped = '';
|
|
64
|
+
const capped = () => cap > 0 && stopped === today(now());
|
|
65
|
+
let openFailed = 0;
|
|
66
|
+
// A db that is not a Postgres client is a clear error when the route loads, as a bad setup hash is.
|
|
67
|
+
/** @type {any} */
|
|
68
|
+
const pg = o.db ? openPgStore(o.db) : null;
|
|
69
|
+
// The site's own Postgres when the route passes db; else the SQLite file, loaded only then (node:sqlite).
|
|
70
|
+
const getStore = async () => {
|
|
71
|
+
if (o.store) return o.store;
|
|
72
|
+
if (pg) return pg;
|
|
73
|
+
const file = o.data ?? '.goose-tools/data.sqlite';
|
|
74
|
+
if (!stores.has(file)) {
|
|
75
|
+
// A file that cannot open is tried again after a minute, and logged once a minute at most.
|
|
76
|
+
if (openFailed && now() - openFailed < 60_000) throw new StoreError(file);
|
|
77
|
+
// The opening itself is kept, so first requests at once share one store.
|
|
78
|
+
stores.set(file, import('./store.js').then(({ openStore }) => openStore(file)));
|
|
79
|
+
}
|
|
80
|
+
const opening = stores.get(file);
|
|
81
|
+
try {
|
|
82
|
+
const store = await opening;
|
|
83
|
+
openFailed = 0;
|
|
84
|
+
return store;
|
|
85
|
+
} catch (e) {
|
|
86
|
+
if (stores.get(file) === opening) {
|
|
87
|
+
stores.delete(file);
|
|
88
|
+
openFailed = now();
|
|
89
|
+
console.error(`goose-tools: cannot open the data file ${file}:`, e);
|
|
90
|
+
}
|
|
91
|
+
throw new StoreError(file);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/** @param {Request} request */
|
|
96
|
+
async function handle(request) {
|
|
97
|
+
const url = new URL(request.url);
|
|
98
|
+
const path = url.pathname.replace(/\/+$/, '') || '/';
|
|
99
|
+
if (path !== BASE && !path.startsWith(BASE + '/')) return null;
|
|
100
|
+
const sub = path.slice(BASE.length) || '/';
|
|
101
|
+
try {
|
|
102
|
+
if (sub === '/s.js') {
|
|
103
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return plain(405, '');
|
|
104
|
+
// A process that has not counted a view today asks the store, so the CDN never keeps the counting script
|
|
105
|
+
// past the cap. Fails open: the counting script.
|
|
106
|
+
if (cap && !capped()) {
|
|
107
|
+
const day = today(now());
|
|
108
|
+
const rows = await within(getStore().then((s) => s.rows(COUNTED, day, day)));
|
|
109
|
+
if ((rows?.[0]?.n ?? 0) >= cap) stopped = day;
|
|
110
|
+
}
|
|
111
|
+
// Kept by the CDN too (s-maxage), so the script is not a function call per view: 10 minutes, so the cap reaches visitors soon. Past the cap, a script that sends nothing, kept by the
|
|
112
|
+
// CDN until midnight UTC and by browsers an hour at most (a raised cap, a CDN copy without an Age header).
|
|
113
|
+
const stop = capped();
|
|
114
|
+
const [body, browser, cdn] = stop ? [NO_COUNT_JS, Math.min(toMidnight(now()), 3600), toMidnight(now())] : [BEACON_JS, 3600, 600];
|
|
115
|
+
return new Response(body, {
|
|
116
|
+
headers: {
|
|
117
|
+
'content-type': 'text/javascript; charset=utf-8',
|
|
118
|
+
'cache-control': `public, max-age=${browser}, s-maxage=${cdn}`,
|
|
119
|
+
'x-content-type-options': 'nosniff',
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
if (sub === '/e') {
|
|
124
|
+
if (capped()) return new Response(null, { status: 204, headers: { 'cache-control': 'no-store' } });
|
|
125
|
+
// The first time this process sees the cap reached that day, collect writes the cap for the dashboard.
|
|
126
|
+
return await collect(request, await getStore(), { now: now(), cap, counted: (n, day) => stopped !== day && Boolean((stopped = day)) });
|
|
127
|
+
}
|
|
128
|
+
if (sub.startsWith('/api/')) return await api(request, url, sub.slice(4), await getStore());
|
|
129
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return plain(405, '');
|
|
130
|
+
// The page's own script and fonts: no secrets in them, so no sign-in needed.
|
|
131
|
+
if (sub === '/app.js') return new Response(APP_JS, { headers: { ...SAFE, 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-cache' } });
|
|
132
|
+
if (sub.startsWith('/fonts/')) {
|
|
133
|
+
const f = font(sub.slice(7));
|
|
134
|
+
return f ? new Response(f, { headers: { 'content-type': 'font/woff2', 'cache-control': 'public, max-age=31536000, immutable', 'x-content-type-options': 'nosniff' } }) : plain(404, '');
|
|
135
|
+
}
|
|
136
|
+
const state = await stateOf(request, await getStore());
|
|
137
|
+
return html(page(!state.claimed ? 'claim' : state.signedIn ? 'dashboard' : 'sign-in', state));
|
|
138
|
+
} catch (e) {
|
|
139
|
+
// Never break the site: a fault in Goose Tools answers 500 here and nothing else.
|
|
140
|
+
if (!(e instanceof StoreError)) console.error('goose-tools:', e);
|
|
141
|
+
// Counting fails open: the page that sent the view never sees an error.
|
|
142
|
+
if (sub === '/e') return new Response(null, { status: 204, headers: { 'cache-control': 'no-store' } });
|
|
143
|
+
// The owner opening /_gt/ on a host with no disk to write to (Vercel functions, a read-only container).
|
|
144
|
+
if (e instanceof StoreError && !sub.startsWith('/api/')) return html(noDataPage(e.file), 503);
|
|
145
|
+
return json(500, { error: 'internal' });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @param {Request} request
|
|
151
|
+
* @param {URL} url
|
|
152
|
+
* @param {string} route
|
|
153
|
+
* @param {Store} store
|
|
154
|
+
*/
|
|
155
|
+
async function api(request, url, route, store) {
|
|
156
|
+
if (route === '/state' && request.method === 'GET') return json(200, await stateOf(request, store));
|
|
157
|
+
if (['/overview', '/overview/insights', '/overview/performance', '/insights/pages', '/insights/sources', '/performance/kinds'].includes(route) && request.method === 'GET') {
|
|
158
|
+
if (!(await stateOf(request, store)).signedIn) return json(401, { error: 'signed_out' });
|
|
159
|
+
const t = now();
|
|
160
|
+
// The period toggle: 7, 30, 90 or 180 days (6 months of history are free, spec section 4).
|
|
161
|
+
const days = PERIODS.includes(Number(url.searchParams.get('days'))) ? Number(url.searchParams.get('days')) : 30;
|
|
162
|
+
const site = url.host;
|
|
163
|
+
if (route === '/overview/insights') return json(200, await insightsOverview(store, { days, now: t, steps: o.steps, site }));
|
|
164
|
+
if (route === '/overview/performance') return json(200, await performanceOverview(store, { days, now: t, site }));
|
|
165
|
+
if (route === '/insights/pages') return json(200, await insightsPages(store, { days, now: t, site }));
|
|
166
|
+
if (route === '/insights/sources') return json(200, await insightsSources(store, { days, now: t, site }));
|
|
167
|
+
if (route === '/performance/kinds') return json(200, await performanceKinds(store, { days, now: t, site }));
|
|
168
|
+
return json(200, { day: today(t), insights: await insightsOverview(store, { days, now: t, steps: o.steps, site }), performance: await performanceOverview(store, { days, now: t, site }) });
|
|
169
|
+
}
|
|
170
|
+
if (request.method !== 'POST') return json(405, { error: 'method' });
|
|
171
|
+
if (!sameSite(request, url)) return json(403, { error: 'cross_site' });
|
|
172
|
+
const body = await readJson(request);
|
|
173
|
+
if (!body) return json(400, { error: 'bad_request' });
|
|
174
|
+
|
|
175
|
+
if (route === '/logout') {
|
|
176
|
+
const token = auth.readSessionToken(request);
|
|
177
|
+
if (token) await store.dropSession(await auth.sessionHash(token));
|
|
178
|
+
return json(200, { ok: true }, { 'set-cookie': auth.sessionCookie(url, '') });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (route === '/claim/start' || route === '/claim/finish') {
|
|
182
|
+
if (await isClaimed(store)) return json(409, { error: 'claimed' });
|
|
183
|
+
// No waits here: a 100-bit code cannot be guessed, and a wait would let a stranger hold off the owner's claim.
|
|
184
|
+
if (!auth.same(await auth.hashSetupCode(String(body.code ?? '')), o.setup)) return json(403, { error: 'setup_code' });
|
|
185
|
+
if (route === '/claim/start') {
|
|
186
|
+
const key = auth.newTotpKey();
|
|
187
|
+
await store.set('pending_totp', JSON.stringify({ key, expires: Math.floor(now() / 1000) + PENDING_SECONDS }));
|
|
188
|
+
const uri = auth.otpauthUri(key, url.hostname);
|
|
189
|
+
return json(200, { key: key.match(/.{4}/g).join(' '), uri, qr: qrSvg(uri, { border: 2, px: 168 }) }); // as the approved screen draws it
|
|
190
|
+
}
|
|
191
|
+
const pending = JSON.parse((await store.get('pending_totp')) || 'null');
|
|
192
|
+
if (!pending || pending.expires < now() / 1000) return json(409, { error: 'start_again' });
|
|
193
|
+
const problem = auth.passwordProblem(body.password);
|
|
194
|
+
if (problem) return json(400, { error: problem, min: auth.MIN_PASSWORD });
|
|
195
|
+
// Two-factor is on by default; the owner may skip it (spec section 4) and turn it on later.
|
|
196
|
+
const skip = body.skip === true;
|
|
197
|
+
const step = skip ? -1 : await auth.totpStep(pending.key, String(body.totp ?? ''), now());
|
|
198
|
+
if (!skip && step < 0) return json(403, { error: 'totp' });
|
|
199
|
+
const recovery = skip ? [] : auth.newRecoveryCodes();
|
|
200
|
+
const password = await auth.hashPassword(body.password);
|
|
201
|
+
const hashes = await Promise.all(recovery.map(auth.hashRecoveryCode));
|
|
202
|
+
// Two finishes at once (Confirm, then Skip): only the first claims. The claim is taken in one step (setIf), so
|
|
203
|
+
// this holds when the store waits on a database between reading and writing.
|
|
204
|
+
const was = await store.get('claimed');
|
|
205
|
+
if ((await isClaimed(store)) || !(await store.setIf('claimed', was, String(Math.floor(now() / 1000))))) return json(409, { error: 'claimed' });
|
|
206
|
+
// The code that claimed, written first: if a later write fails, the site is claimed with this code, and a new
|
|
207
|
+
// code (`setup --new-code`) still opens the claim again.
|
|
208
|
+
await store.set('setup_hash', o.setup);
|
|
209
|
+
await store.set('setup_used', JSON.stringify([...new Set([...JSON.parse((await store.get('setup_used')) || '[]'), o.setup])]));
|
|
210
|
+
// A new claim (a new setup code from `npx goose-tools setup --new-code`) replaces every sign-in setting.
|
|
211
|
+
for (const name of ['totp', 'totp_step', 'recovery', 'devices', 'fails', 'fails_known']) await store.remove(name);
|
|
212
|
+
await store.dropAllSessions();
|
|
213
|
+
await store.set('password', password);
|
|
214
|
+
if (!skip) {
|
|
215
|
+
await store.set('totp', pending.key);
|
|
216
|
+
await store.set('totp_step', String(step));
|
|
217
|
+
await store.set('recovery', JSON.stringify(hashes));
|
|
218
|
+
}
|
|
219
|
+
await store.remove('pending_totp');
|
|
220
|
+
return json(200, { recovery }, { 'set-cookie': await signedIn(request, store, url) });
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (route === '/login') {
|
|
224
|
+
if (!(await isClaimed(store))) return json(409, { error: 'not_claimed' });
|
|
225
|
+
// A browser that signed in before has its own count, so strangers' tries never make the owner wait.
|
|
226
|
+
const fails = (await knownDevice(request, store)) ? 'fails_known' : 'fails';
|
|
227
|
+
// Counted before the slow check, in one step with the wait check, so tries sent at once cannot all start before
|
|
228
|
+
// the wait. Cleared on success.
|
|
229
|
+
const wait = await countTry(store, fails);
|
|
230
|
+
if (wait) return json(429, { error: 'wait', seconds: wait });
|
|
231
|
+
if (!(await auth.checkPassword(String(body.password ?? ''), (await store.get('password')) || ''))) return json(403, { error: 'password' });
|
|
232
|
+
const code = String(body.code ?? '').trim();
|
|
233
|
+
let ok = false;
|
|
234
|
+
if (!(await store.get('totp'))) {
|
|
235
|
+
ok = true; // two-factor skipped at setup: the password alone
|
|
236
|
+
} else if (/^\d[\d\s]{5,}$/.test(code)) {
|
|
237
|
+
const step = await auth.totpStep((await store.get('totp')) || '', code, now());
|
|
238
|
+
// Each code works once: a step at or before the last one used is refused, and two sign-ins at once with the
|
|
239
|
+
// same code cannot both move it on.
|
|
240
|
+
const last = await store.get('totp_step');
|
|
241
|
+
ok = step >= 0 && step > Number(last || -1) && (await store.setIf('totp_step', last, String(step)));
|
|
242
|
+
} else if (code) {
|
|
243
|
+
// Each recovery code works once, also when two sign-ins send it at once.
|
|
244
|
+
const h = await auth.hashRecoveryCode(code);
|
|
245
|
+
for (let tries = 0; tries < 5 && !ok; tries++) {
|
|
246
|
+
const raw = await store.get('recovery');
|
|
247
|
+
const hashes = JSON.parse(raw || '[]');
|
|
248
|
+
const i = hashes.indexOf(h);
|
|
249
|
+
if (i < 0) break;
|
|
250
|
+
hashes.splice(i, 1);
|
|
251
|
+
ok = await store.setIf('recovery', raw, JSON.stringify(hashes));
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (!ok) return json(403, { error: 'code' }); // counted above
|
|
255
|
+
await store.remove(fails);
|
|
256
|
+
const left = JSON.parse((await store.get('recovery')) || '[]').length;
|
|
257
|
+
return json(200, { ok: true, recoveryLeft: left }, { 'set-cookie': await signedIn(request, store, url) });
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return json(404, { error: 'not_found' });
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Claimed with the setup code in the route. A code never used before (`setup --new-code`) opens the claim again, so
|
|
265
|
+
* an owner who lost the password or the data file can start over: changing the route already takes access to the
|
|
266
|
+
* site's code. A code used before (a deploy rolled back) does not.
|
|
267
|
+
* @param {Store} store
|
|
268
|
+
*/
|
|
269
|
+
async function isClaimed(store) {
|
|
270
|
+
if (!(await store.get('claimed'))) return false;
|
|
271
|
+
const claimedWith = await store.get('setup_hash');
|
|
272
|
+
if (!claimedWith || claimedWith === o.setup) return true;
|
|
273
|
+
return JSON.parse((await store.get('setup_used')) || '[]').includes(o.setup);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* A new session, and a device cookie for a browser not yet known (auth.js, "Known browsers").
|
|
278
|
+
* @param {Request} request
|
|
279
|
+
* @param {Store} store
|
|
280
|
+
* @param {URL} url
|
|
281
|
+
* @returns {Promise<string[]>} Set-Cookie values.
|
|
282
|
+
*/
|
|
283
|
+
async function signedIn(request, store, url) {
|
|
284
|
+
const { token, hash } = await auth.newSession();
|
|
285
|
+
await store.addSession(hash, Math.floor(now() / 1000) + auth.SESSION_DAYS * 86400);
|
|
286
|
+
const cookies = [auth.sessionCookie(url, token)];
|
|
287
|
+
if (!(await knownDevice(request, store))) {
|
|
288
|
+
const { token: t } = await auth.newSession(); // the same 256 random bits
|
|
289
|
+
const list = JSON.parse((await store.get('devices')) || '[]');
|
|
290
|
+
await store.set('devices', JSON.stringify([await auth.deviceHash(t), ...list].slice(0, auth.DEVICES)));
|
|
291
|
+
cookies.push(auth.deviceCookie(url, t));
|
|
292
|
+
}
|
|
293
|
+
return cookies;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* The request comes from a browser that signed in before.
|
|
298
|
+
* @param {Request} request
|
|
299
|
+
* @param {Store} store
|
|
300
|
+
*/
|
|
301
|
+
async function knownDevice(request, store) {
|
|
302
|
+
const token = auth.readDeviceToken(request);
|
|
303
|
+
return Boolean(token) && JSON.parse((await store.get('devices')) || '[]').includes(await auth.deviceHash(token));
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Count a try, unless it must wait: the seconds left to wait (the try is not counted), or 0 (counted). The count is
|
|
308
|
+
* written only if no other try changed it meanwhile (setIf), so tries sent at once are each counted.
|
|
309
|
+
* @param {Store} store
|
|
310
|
+
* @param {string} name 'fails' or 'fails_known'.
|
|
311
|
+
*/
|
|
312
|
+
async function countTry(store, name) {
|
|
313
|
+
for (let tries = 0; tries < 20; tries++) {
|
|
314
|
+
const raw = await store.get(name);
|
|
315
|
+
const f = JSON.parse(raw || '{"n":0,"last":0}');
|
|
316
|
+
const t = Math.floor(now() / 1000);
|
|
317
|
+
if (f.n >= FREE_TRIES) {
|
|
318
|
+
const wait = Math.max(0, f.last + Math.min(2 ** (f.n - FREE_TRIES), MAX_WAIT) - t);
|
|
319
|
+
if (wait) return wait;
|
|
320
|
+
}
|
|
321
|
+
if (await store.setIf(name, raw, JSON.stringify({ n: f.n + 1, last: t }))) return 0;
|
|
322
|
+
}
|
|
323
|
+
return 1; // Too many tries at this moment: wait a second.
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* @param {Request} request
|
|
328
|
+
* @param {Store} store
|
|
329
|
+
*/
|
|
330
|
+
async function stateOf(request, store) {
|
|
331
|
+
const claimed = await isClaimed(store);
|
|
332
|
+
const token = auth.readSessionToken(request);
|
|
333
|
+
const signedIn = claimed && Boolean(token) && Boolean(await store.session(await auth.sessionHash(token)));
|
|
334
|
+
// Whether sign-in asks for a code after the password (two-factor can be skipped at setup).
|
|
335
|
+
return { claimed, signedIn, twoFactor: Boolean(await store.get('totp')) };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return {
|
|
339
|
+
handle,
|
|
340
|
+
/** Next.js App Router: `export const { GET, POST } = site(...)` in app/%5Fgt/[[...path]]/route.js. */
|
|
341
|
+
GET: async (/** @type {Request} */ r) => (await handle(r)) ?? plain(404, ''),
|
|
342
|
+
POST: async (/** @type {Request} */ r) => (await handle(r)) ?? plain(404, ''),
|
|
343
|
+
HEAD: async (/** @type {Request} */ r) => (await handle(r)) ?? plain(404, ''),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** The data file could not open (already logged). */
|
|
348
|
+
class StoreError extends Error {
|
|
349
|
+
/** @param {string} file */
|
|
350
|
+
constructor(file) {
|
|
351
|
+
super(`goose-tools: cannot open the data file ${file}`);
|
|
352
|
+
this.file = file;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Sent from a page of this site, by the browser's own headers.
|
|
358
|
+
* @param {Request} request
|
|
359
|
+
* @param {URL} url
|
|
360
|
+
*/
|
|
361
|
+
function sameSite(request, url) {
|
|
362
|
+
const site = request.headers.get('sec-fetch-site');
|
|
363
|
+
if (site) return site === 'same-origin';
|
|
364
|
+
const origin = request.headers.get('origin');
|
|
365
|
+
return !origin || origin === url.origin;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** @param {Request} request */
|
|
369
|
+
async function readJson(request) {
|
|
370
|
+
try {
|
|
371
|
+
if ((parseInt(request.headers.get('content-length') ?? '', 10) || 0) > MAX_BODY) return null;
|
|
372
|
+
const raw = await readBody(request, MAX_BODY);
|
|
373
|
+
if (raw === null) return null;
|
|
374
|
+
const v = JSON.parse(raw);
|
|
375
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : null;
|
|
376
|
+
} catch {
|
|
377
|
+
return null;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** The page script once the day's cap is reached. */
|
|
382
|
+
const NO_COUNT_JS = '// Counting stopped for today at the daily limit. It starts again at midnight UTC.\n';
|
|
383
|
+
|
|
384
|
+
const SAFE = { 'cache-control': 'no-store', 'x-robots-tag': 'noindex, nofollow', 'x-content-type-options': 'nosniff', 'referrer-policy': 'same-origin' };
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* @param {number} status
|
|
388
|
+
* @param {object} body
|
|
389
|
+
* @param {Record<string, string | string[]>} [extra]
|
|
390
|
+
*/
|
|
391
|
+
function json(status, body, extra = {}) {
|
|
392
|
+
const headers = new Headers({ ...SAFE, 'content-type': 'application/json' });
|
|
393
|
+
for (const [k, v] of Object.entries(extra)) for (const x of [v].flat()) headers.append(k, x);
|
|
394
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** @param {string} body @param {number} [status] */
|
|
398
|
+
function html(body, status = 200) {
|
|
399
|
+
return new Response(body, { status, headers: { ...SAFE, 'content-type': 'text/html; charset=utf-8', 'x-frame-options': 'DENY', 'content-security-policy': "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" } });
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** @param {number} status @param {string} body */
|
|
403
|
+
function plain(status, body) {
|
|
404
|
+
return new Response(body, { status, headers: { ...SAFE, 'content-type': 'text/plain; charset=utf-8' } });
|
|
405
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// `import { site } from '@goosetools/goose-tools/site'`: the /_gt/ route for the owner's site. Node 22.13 or later.
|
|
2
|
+
//
|
|
3
|
+
// Next.js (App Router), app/%5Fgt/[[...path]]/route.js, written by `npx goose-tools setup`:
|
|
4
|
+
// import { site } from '@goosetools/goose-tools/site';
|
|
5
|
+
// export const runtime = 'nodejs';
|
|
6
|
+
// export const dynamic = 'force-dynamic';
|
|
7
|
+
// export const { GET, POST, HEAD } = site({ setup: '<hash>' });
|
|
8
|
+
// (A folder named _gt would be private in Next.js; %5F is its documented way to start a URL segment with "_".)
|
|
9
|
+
//
|
|
10
|
+
// Node (http, Express, Fastify's raw handler):
|
|
11
|
+
// import { site, nodeHandler } from '@goosetools/goose-tools/site';
|
|
12
|
+
// const gt = nodeHandler(site({ setup: '<hash>' }));
|
|
13
|
+
// http.createServer(async (req, res) => { if (await gt(req, res)) return; ... });
|
|
14
|
+
// app.use(gt); // Express: calls next() for anything outside /_gt/
|
|
15
|
+
import { createSite, BASE } from './handler.js';
|
|
16
|
+
|
|
17
|
+
export { createSite as site, BASE };
|
|
18
|
+
|
|
19
|
+
const MAX_BODY = 64 * 1024;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {ReturnType<typeof createSite>} s
|
|
23
|
+
* @returns {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse, next?: () => void) => Promise<boolean>}
|
|
24
|
+
*/
|
|
25
|
+
export function nodeHandler(s) {
|
|
26
|
+
return async (req, res, next) => {
|
|
27
|
+
const path = (req.url || '/').split('?')[0];
|
|
28
|
+
if (path !== BASE && !path.startsWith(BASE + '/')) {
|
|
29
|
+
if (next) next();
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
return await answer(s, req, res, next);
|
|
34
|
+
} catch (e) {
|
|
35
|
+
// Never take the server down: a dropped upload or a bad Host header ends here, not as an unhandled rejection.
|
|
36
|
+
console.error('goose-tools:', e);
|
|
37
|
+
if (!res.headersSent && !res.destroyed) res.writeHead(path === BASE + '/e' ? 204 : 500, { 'cache-control': 'no-store' }).end();
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @param {ReturnType<typeof createSite>} s
|
|
45
|
+
* @param {import('node:http').IncomingMessage} req
|
|
46
|
+
* @param {import('node:http').ServerResponse} res
|
|
47
|
+
* @param {() => void} [next]
|
|
48
|
+
*/
|
|
49
|
+
async function answer(s, req, res, next) {
|
|
50
|
+
const proto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim() || (/** @type {any} */ (req.socket).encrypted ? 'https' : 'http');
|
|
51
|
+
const host = req.headers['x-forwarded-host'] || req.headers.host || 'localhost';
|
|
52
|
+
const headers = new Headers();
|
|
53
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
54
|
+
if (Array.isArray(v)) v.forEach((x) => headers.append(k, x));
|
|
55
|
+
else if (v !== undefined) headers.set(k, v);
|
|
56
|
+
}
|
|
57
|
+
let body;
|
|
58
|
+
const parsed = /** @type {any} */ (req);
|
|
59
|
+
if (req.method !== 'GET' && req.method !== 'HEAD' && (parsed._body || req.readableEnded)) {
|
|
60
|
+
// Express: express.json(), urlencoded() or text() came first and read the stream. Rebuild the body from req.body.
|
|
61
|
+
const b = parsed.body;
|
|
62
|
+
body = Buffer.isBuffer(b) || typeof b === 'string' ? b : b && typeof b === 'object' ? (req.url || '').startsWith(BASE + '/e') ? new URLSearchParams(b).toString() : JSON.stringify(b) : undefined;
|
|
63
|
+
headers.delete('content-length');
|
|
64
|
+
} else if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
65
|
+
const chunks = [];
|
|
66
|
+
let size = 0;
|
|
67
|
+
for await (const c of req) {
|
|
68
|
+
size += c.length;
|
|
69
|
+
if (size > MAX_BODY) {
|
|
70
|
+
res.writeHead((req.url || '').startsWith(BASE + '/e') ? 204 : 413).end(); // counting never answers an error
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
chunks.push(c);
|
|
74
|
+
}
|
|
75
|
+
body = Buffer.concat(chunks);
|
|
76
|
+
}
|
|
77
|
+
const r = await s.handle(new Request(`${proto}://${host}${req.url}`, { method: req.method, headers, body }));
|
|
78
|
+
if (!r) {
|
|
79
|
+
if (next) next();
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
const out = /** @type {Record<string, string | string[]>} */ (Object.fromEntries(r.headers));
|
|
83
|
+
const cookies = r.headers.getSetCookie();
|
|
84
|
+
if (cookies.length) out['set-cookie'] = cookies; // each cookie its own header
|
|
85
|
+
res.writeHead(r.status, out);
|
|
86
|
+
res.end(req.method === 'HEAD' ? undefined : Buffer.from(await r.arrayBuffer()));
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Limits and day helpers both stores share (store.js for the SQLite file, store-pg.js for the site's own Postgres).
|
|
2
|
+
// Kept apart so a site on Postgres never loads node:sqlite.
|
|
3
|
+
|
|
4
|
+
/** Days of history kept on the free plan (spec section 4: 6 months). */
|
|
5
|
+
export const KEEP_DAYS = 183;
|
|
6
|
+
/** Distinct keys counted a day per kind in CAPPED; past this, new keys count under "(other)" so the file cannot be flooded. */
|
|
7
|
+
export const MAX_KEYS_A_DAY = 2000;
|
|
8
|
+
/**
|
|
9
|
+
* Size of the totals table in the site's own Postgres past which new keys of CAPPED kinds count as "(other)", so
|
|
10
|
+
* made-up beacons cannot fill the owner's database (Supabase's free plan turns the whole database read-only near a
|
|
11
|
+
* full disk). Checked once a day per process.
|
|
12
|
+
*/
|
|
13
|
+
export const MAX_TABLE_BYTES = 200 * 1024 * 1024;
|
|
14
|
+
/** Keys per kind the dashboard reads for a period (store.sums), as many as the plugin's speed report lists. */
|
|
15
|
+
export const SUM_KEYS = 5000;
|
|
16
|
+
/**
|
|
17
|
+
* Kinds whose keys come from what a beacon sends (paths, hosts, campaign tags), so they are capped a day. The other
|
|
18
|
+
* kinds have a fixed set of keys (countries, devices, hours, histogram buckets). See collect.js for every kind.
|
|
19
|
+
*/
|
|
20
|
+
export const CAPPED = new Set(['page', 'continued', 'source', 'speed', ...['lcp', 'inp', 'cls', 'ttfb'].flatMap((m) => ['good', 'ni', 'poor'].map((r) => `speed.${m}.${r}`)), 'ttfb.ms', 'ttfb.n', 'script.ms', 'script.views', 'script.inp', 'load.ms', 'call.ms', 'call.n']);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The daily cap on counted views (spec/standalone-database.md section 5), when the route sets `cap`. Each counted
|
|
24
|
+
* view also adds 1 to COUNTED 'all', in the same statement. A process that sees the cap reached writes CAP <cap>
|
|
25
|
+
* once, so the dashboard can tell the days counting stopped and at which cap.
|
|
26
|
+
*/
|
|
27
|
+
export const COUNTED = 'counted';
|
|
28
|
+
export const CAP = 'cap';
|
|
29
|
+
|
|
30
|
+
/** Seconds from `ms` to the next midnight UTC, at least 1. @param {number} ms */
|
|
31
|
+
export function toMidnight(ms) {
|
|
32
|
+
return Math.max(1, Math.ceil((Date.parse(today(ms) + 'T00:00:00Z') + 86_400_000 - ms) / 1000));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {string} day YYYY-MM-DD
|
|
37
|
+
* @param {number} days
|
|
38
|
+
*/
|
|
39
|
+
export function shiftDay(day, days) {
|
|
40
|
+
const d = new Date(day + 'T00:00:00Z');
|
|
41
|
+
d.setUTCDate(d.getUTCDate() + days);
|
|
42
|
+
return d.toISOString().slice(0, 10);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param {number} [ms] */
|
|
46
|
+
export function today(ms = Date.now()) {
|
|
47
|
+
return new Date(ms).toISOString().slice(0, 10);
|
|
48
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// The /_gt/ page: one HTML shell; the screen (check/design/build/site.jsx) comes from /_gt/app.js.
|
|
2
|
+
//
|
|
3
|
+
// Built screens: first sign-in with the setup code (approved 2026-11-24), Sign in (approved prototype), the
|
|
4
|
+
// dashboard with Performance and Insights (approved 2026-11-24), and the page shown when the data file cannot open.
|
|
5
|
+
//
|
|
6
|
+
// lib/ui/assets.js is built by `npm run sync` (check/design/build/build.mjs, GT_SITE=1). It is one module of strings,
|
|
7
|
+
// so a bundler carries it with the route and nothing is read from disk at run time.
|
|
8
|
+
import { CSS, APP_JS, FONTS } from '../../lib/ui/assets.js';
|
|
9
|
+
|
|
10
|
+
export { APP_JS };
|
|
11
|
+
|
|
12
|
+
/** @type {Map<string, Uint8Array>} */
|
|
13
|
+
const fonts = new Map();
|
|
14
|
+
|
|
15
|
+
/** @param {string} name */
|
|
16
|
+
export function font(name) {
|
|
17
|
+
if (!Object.hasOwn(FONTS, name)) return null;
|
|
18
|
+
if (!fonts.has(name)) fonts.set(name, Uint8Array.from(atob(FONTS[name]), (c) => c.charCodeAt(0)));
|
|
19
|
+
return fonts.get(name);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {'claim' | 'sign-in' | 'dashboard'} kind
|
|
24
|
+
* @param {{twoFactor?: boolean}} [o]
|
|
25
|
+
*/
|
|
26
|
+
export function page(kind, o = {}) {
|
|
27
|
+
return `<!doctype html>
|
|
28
|
+
<html lang="en">
|
|
29
|
+
<head>
|
|
30
|
+
<meta charset="utf-8">
|
|
31
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
32
|
+
<meta name="robots" content="noindex, nofollow">
|
|
33
|
+
<title>Goose Tools</title>
|
|
34
|
+
<style>${CSS}</style>
|
|
35
|
+
</head>
|
|
36
|
+
<body data-gt-page="${kind}" data-gt-two-factor="${o.twoFactor ? 'true' : 'false'}">
|
|
37
|
+
<div id="gt-app"></div>
|
|
38
|
+
<script src="/_gt/app.js" defer></script>
|
|
39
|
+
</body>
|
|
40
|
+
</html>
|
|
41
|
+
`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** @param {string} v */
|
|
45
|
+
const esc = (v) => v.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* In place of the dashboard when the data file cannot open (a host with no persistent disk). Plain HTML with the screens'
|
|
49
|
+
* own styles: no script, since nothing on it changes. Text approved by the owner, 2026-11-24 and 2026-11-25.
|
|
50
|
+
* @param {string} file
|
|
51
|
+
*/
|
|
52
|
+
export function noDataPage(file) {
|
|
53
|
+
return `<!doctype html>
|
|
54
|
+
<html lang="en">
|
|
55
|
+
<head>
|
|
56
|
+
<meta charset="utf-8">
|
|
57
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
58
|
+
<meta name="robots" content="noindex, nofollow">
|
|
59
|
+
<title>Goose Tools</title>
|
|
60
|
+
<style>${CSS}</style>
|
|
61
|
+
</head>
|
|
62
|
+
<body>
|
|
63
|
+
<div class="gt-screens"><div class="wrap goosesec"><div class="goosesec-panel"><div class="gs-grid">
|
|
64
|
+
<section class="gs-panel gs-panel--wide" aria-labelledby="gt-nodata">
|
|
65
|
+
<div class="gs-panel__head"><div><h2 id="gt-nodata">The data file can't be opened</h2><p>Page views are not being counted.</p></div></div>
|
|
66
|
+
<p>The file is <code>${esc(file)}</code>. The data file must be on a persistent local disk, on one server.</p>
|
|
67
|
+
<p>Set where it goes with the <code>data</code> option in the route, for example <code>site({ setup: '…', data: '/var/data/goose-tools.sqlite' })</code>.</p>
|
|
68
|
+
<p>On Vercel, the data can go in your own Postgres database instead, such as Supabase or Neon. Run <code>vercel link</code>, then <code>npx goose-tools setup</code>.</p>
|
|
69
|
+
<p><a href="https://www.npmjs.com/package/goose-tools#where-it-runs">See where it runs</a></p>
|
|
70
|
+
</section>
|
|
71
|
+
</div></div></div></div>
|
|
72
|
+
</body>
|
|
73
|
+
</html>
|
|
74
|
+
`;
|
|
75
|
+
}
|