@prunellejs/analytics 0.7.2 → 0.7.4
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/llms.txt +1 -1
- package/package.json +2 -2
- package/src/consent.ts +3 -1
- package/src/index.ts +35 -194
- package/src/prerender.ts +129 -0
- package/src/request.ts +191 -0
- package/src/vitals.ts +9 -1
package/llms.txt
CHANGED
|
@@ -16,7 +16,7 @@ Register in `prunelle.config.ts` `plugins`:
|
|
|
16
16
|
- `secret`: optional hash salt (defaults to `process.env.ANALYTICS_SECRET` or a random ephemeral per-process 32-byte secret). Visitor ID is `SHA-256(YYYY-MM-DD, secret, ip, userAgent, hostname)` — daily-rotating, no cookies, no persistent storage.
|
|
17
17
|
- `sendIp`: default `false`. Raw client IP is NEVER forwarded to providers unless `sendIp: true`.
|
|
18
18
|
- `requiresConsent` / `consentCategory`: consent gating automatically turns on (`'analytics'`) when `sendIp: true` or the provider requires it (see `provider`). Applies to page views, custom events, and Web Vitals (`onVital` and `provider.sendVital`). Override with `consentCategory: 'analytics'` or `consentCategory: false`. The category must be declared in `consent.categories` (`requires()`: a production start refuses, dev and `prunelle check` warn); `prunelle check` warns about `sendIp: true` with consent off.
|
|
19
|
-
- `viewEndpoint`: first-party CSRF-protected POST endpoint (default `'/_pru/analytics/view'`, or `false` to count no prefetched page). A prefetch that would be counted is answered with `x-pru-view: <viewEndpoint>` instead of being counted
|
|
19
|
+
- `viewEndpoint`: first-party CSRF-protected POST endpoint (default `'/_pru/analytics/view'`, or `false` to count no prefetched/prerendered page). When on, counted HTML answers carry `Vary: Purpose, Sec-Purpose`. A prefetch or prerender that would be counted is answered with `x-pru-view: <viewEndpoint>` instead of being counted: `@prunellejs/spa` posts the path and query with `navigator.sendBeacon` when it opens the cached page, and a browser speculation-rules prefetch/prerender answer includes a tiny inline beacon script (allowed via CSP SHA-256 hash; 0 B on normal visits) that fires on activation (`prerenderingchange` when `document.prerendering` is true, else immediately). The beacon counts one view through the middleware's filters (bot, `exclude`, consent, query stripping), takes the `Referer` of the page left, answers `400` to a body that is not a same-origin path of at most 2000 characters, and `204` otherwise.
|
|
20
20
|
- `eventEndpoint`: first-party CSRF-protected POST endpoint (default `'/_pru/analytics/event'`, or `false` to disable). Event URLs are confined to same-origin (`site` or request origin).
|
|
21
21
|
- `webVitals`: default `false` (0 B JS). Set `true` or `{ endpoint?, sampleRate?, onVital? }` to emit a `<1.5 KB` `<script defer src="/_pru/analytics-vitals-*.js">` collecting LCP, session-window CLS, p98 INP, FCP, and TTFB, sent in one beacon when the page hides to `POST /_pru/analytics/vitals` (CSRF-protected; `onVital` runs per metric; `sampleRate: 0.1` measures one view in ten). Under consent the tag is `<script defer src="/_pru/analytics/vitals.js">`, answered only to a visitor who granted the category (an empty script otherwise, `private, no-cache` with an ETag).
|
|
22
22
|
- `ignoreBots`: default `true`, on page views, events and vitals (the last two answer 204). Event and vitals bodies over 16 KiB get 413. An event is refused with 400 past: name 100 characters, `url` or `path` 2000, 30 props, 64 character keys, 100 character string values. Props are dropped unless their key is in `eventProps: string[]` (default none).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/analytics",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
4
4
|
"description": "CNIL-compliant server-side first-party audience measurement, custom events, and optional Web Vitals plugin for Prunelle",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -22,6 +22,6 @@
|
|
|
22
22
|
"directory": "packages/plugin-analytics"
|
|
23
23
|
},
|
|
24
24
|
"peerDependencies": {
|
|
25
|
-
"prunelle": "^0.7.
|
|
25
|
+
"prunelle": "^0.7.4"
|
|
26
26
|
}
|
|
27
27
|
}
|
package/src/consent.ts
CHANGED
|
@@ -20,9 +20,11 @@ export function resolveConsentCategory(options: AnalyticsOptions, site: string |
|
|
|
20
20
|
if (options.consentCategory === false)
|
|
21
21
|
return undefined
|
|
22
22
|
if (typeof options.consentCategory === 'string') {
|
|
23
|
+
const trimmed = options.consentCategory.trim()
|
|
24
|
+
if (trimmed.toLowerCase() === 'essential')
|
|
25
|
+
throw new Error('prunelle: @prunellejs/analytics consentCategory cannot be "essential" (essential is always granted and cannot be declared in consent.categories): set requiresConsent: false to count without consent.')
|
|
23
26
|
if (options.requiresConsent === false)
|
|
24
27
|
return undefined
|
|
25
|
-
const trimmed = options.consentCategory.trim()
|
|
26
28
|
return trimmed !== '' ? trimmed : 'analytics'
|
|
27
29
|
}
|
|
28
30
|
const { provider } = options
|
package/src/index.ts
CHANGED
|
@@ -5,14 +5,29 @@ import type { PrunellePlugin } from 'prunelle/config'
|
|
|
5
5
|
import type { Middleware, RateLimit, RequestContext } from 'prunelle/server'
|
|
6
6
|
import type {
|
|
7
7
|
AnalyticsEvent,
|
|
8
|
-
AnalyticsEventProps,
|
|
9
8
|
AnalyticsOptions,
|
|
10
9
|
AnalyticsPageview,
|
|
11
10
|
WebVitalsOptions,
|
|
12
11
|
} from './types'
|
|
13
12
|
import { definePlugin } from 'prunelle/config'
|
|
14
|
-
import { resolveConsentCategory } from './consent'
|
|
15
13
|
import { escAttr, safeRedirect } from 'prunelle/server'
|
|
14
|
+
import { resolveConsentCategory } from './consent'
|
|
15
|
+
import {
|
|
16
|
+
buildViewBeaconScript,
|
|
17
|
+
scriptCspHash,
|
|
18
|
+
withPrerenderBeacon,
|
|
19
|
+
withVaryPurpose,
|
|
20
|
+
withViewHeader,
|
|
21
|
+
} from './prerender'
|
|
22
|
+
import {
|
|
23
|
+
etagMatches,
|
|
24
|
+
parseEventPayload,
|
|
25
|
+
parseSameOriginCandidate,
|
|
26
|
+
parseViewPath,
|
|
27
|
+
readBodyText,
|
|
28
|
+
readJsonBody,
|
|
29
|
+
resolveBaseOrigin,
|
|
30
|
+
} from './request'
|
|
16
31
|
import {
|
|
17
32
|
coarseUserAgent,
|
|
18
33
|
computeVisitorId,
|
|
@@ -55,13 +70,6 @@ export const DEFAULT_VIEW_ENDPOINT = '/_pru/analytics/view'
|
|
|
55
70
|
export const DEFAULT_MAX_PENDING = 64
|
|
56
71
|
export const DEFAULT_RATE_LIMIT: RateLimit<RequestContext> = { max: 60, windowMs: 60_000 }
|
|
57
72
|
|
|
58
|
-
const VIEW_HEADER = 'x-pru-view'
|
|
59
|
-
const MAX_EVENT_NAME_LEN = 100
|
|
60
|
-
const MAX_PROP_KEYS = 30
|
|
61
|
-
const MAX_URL_LEN = 2000
|
|
62
|
-
const MAX_BODY_BYTES = 16 * 1024
|
|
63
|
-
const MAX_PROP_KEY_LEN = 64
|
|
64
|
-
const MAX_PROP_STR_LEN = 100
|
|
65
73
|
export const DEFAULT_OPT_OUT_ENDPOINT = '/_pru/analytics/opt-out'
|
|
66
74
|
/** The essential cookie that marks a visitor who opted out of being counted. */
|
|
67
75
|
export const OPT_OUT_COOKIE = 'pru_no_count'
|
|
@@ -94,168 +102,11 @@ function normalizeWebVitals(webVitals: AnalyticsOptions['webVitals']): WebVitals
|
|
|
94
102
|
}
|
|
95
103
|
}
|
|
96
104
|
|
|
97
|
-
// Keys outside `allowed` are dropped, never refused, so a client that sends more than the app lists still counts its event.
|
|
98
|
-
function sanitizeEventProps(raw: unknown, allowed: ReadonlySet<string>): AnalyticsEventProps | undefined | null {
|
|
99
|
-
if (raw === undefined || raw === null)
|
|
100
|
-
return undefined
|
|
101
|
-
if (typeof raw !== 'object' || Array.isArray(raw))
|
|
102
|
-
return null
|
|
103
|
-
const out: AnalyticsEventProps = {}
|
|
104
|
-
let count = 0
|
|
105
|
-
let seen = 0
|
|
106
|
-
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
|
|
107
|
-
const key = k.trim()
|
|
108
|
-
if (key === '' || key.length > MAX_PROP_KEY_LEN || ++seen > MAX_PROP_KEYS)
|
|
109
|
-
return null
|
|
110
|
-
if (!allowed.has(key))
|
|
111
|
-
continue
|
|
112
|
-
if (typeof v === 'string') {
|
|
113
|
-
if (v.length > MAX_PROP_STR_LEN)
|
|
114
|
-
return null
|
|
115
|
-
out[key] = v
|
|
116
|
-
}
|
|
117
|
-
else if (typeof v === 'number' && Number.isFinite(v))
|
|
118
|
-
out[key] = v
|
|
119
|
-
else if (typeof v === 'boolean')
|
|
120
|
-
out[key] = v
|
|
121
|
-
else
|
|
122
|
-
return null
|
|
123
|
-
count++
|
|
124
|
-
}
|
|
125
|
-
return count > 0 ? out : undefined
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function parseSameOriginCandidate(
|
|
129
|
-
raw: unknown,
|
|
130
|
-
baseOrigin: string,
|
|
131
|
-
requestOrigin: string,
|
|
132
|
-
): URL | undefined {
|
|
133
|
-
if (typeof raw !== 'string')
|
|
134
|
-
return undefined
|
|
135
|
-
const trimmed = raw.trim()
|
|
136
|
-
if (trimmed === '')
|
|
137
|
-
return undefined
|
|
138
|
-
let parsed: URL
|
|
139
|
-
try {
|
|
140
|
-
parsed = new URL(trimmed, baseOrigin)
|
|
141
|
-
}
|
|
142
|
-
catch {
|
|
143
|
-
return undefined
|
|
144
|
-
}
|
|
145
|
-
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
146
|
-
return undefined
|
|
147
|
-
if (parsed.origin !== baseOrigin && parsed.origin !== requestOrigin)
|
|
148
|
-
return undefined
|
|
149
|
-
return parsed
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function resolveBaseOrigin(site: string | undefined, requestOrigin: string): string {
|
|
153
|
-
if (site !== undefined && site !== '' && URL.canParse(site)) {
|
|
154
|
-
const parsed = new URL(site)
|
|
155
|
-
if (parsed.protocol === 'http:' || parsed.protocol === 'https:')
|
|
156
|
-
return parsed.origin
|
|
157
|
-
}
|
|
158
|
-
return requestOrigin
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
function resolveEventLocation(
|
|
162
|
-
rawUrl: unknown,
|
|
163
|
-
rawPath: unknown,
|
|
164
|
-
ctx: RequestContext,
|
|
165
|
-
site: string | undefined,
|
|
166
|
-
overrideHostname: string | undefined,
|
|
167
|
-
includeQueryParams: readonly string[] | undefined,
|
|
168
|
-
): { url: string, path: string, hostname: string } {
|
|
169
|
-
const requestOrigin = ctx.url.origin
|
|
170
|
-
const baseOrigin = resolveBaseOrigin(site, requestOrigin)
|
|
171
|
-
const targetUrl = parseSameOriginCandidate(rawUrl, baseOrigin, requestOrigin)
|
|
172
|
-
?? parseSameOriginCandidate(rawPath, baseOrigin, requestOrigin)
|
|
173
|
-
?? parseSameOriginCandidate(ctx.request.headers.get('referer'), baseOrigin, requestOrigin)
|
|
174
|
-
?? new URL('/', baseOrigin)
|
|
175
|
-
return resolveCanonicalLocation(targetUrl, site, overrideHostname, includeQueryParams)
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
type BodyFailure = { ok: false, status: 400 | 413, reason: string }
|
|
179
|
-
type JsonBody = { ok: true, value: unknown } | BodyFailure
|
|
180
|
-
|
|
181
|
-
const TOO_LARGE: BodyFailure = { ok: false, status: 413, reason: `body over ${MAX_BODY_BYTES} bytes` }
|
|
182
|
-
|
|
183
|
-
// Reads at most MAX_BODY_BYTES: a larger declared length is refused before reading, and a stream that outgrows it is cancelled.
|
|
184
|
-
async function readBodyText(request: Request): Promise<string | BodyFailure> {
|
|
185
|
-
if (Number(request.headers.get('content-length')) > MAX_BODY_BYTES)
|
|
186
|
-
return TOO_LARGE
|
|
187
|
-
if (request.body === null)
|
|
188
|
-
return ''
|
|
189
|
-
const reader = request.body.getReader()
|
|
190
|
-
const chunks: Uint8Array[] = []
|
|
191
|
-
let size = 0
|
|
192
|
-
try {
|
|
193
|
-
for (;;) {
|
|
194
|
-
const { done, value } = await reader.read()
|
|
195
|
-
if (done)
|
|
196
|
-
break
|
|
197
|
-
size += value.byteLength
|
|
198
|
-
if (size > MAX_BODY_BYTES) {
|
|
199
|
-
await reader.cancel().catch(() => undefined)
|
|
200
|
-
return TOO_LARGE
|
|
201
|
-
}
|
|
202
|
-
chunks.push(value)
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
catch {
|
|
206
|
-
return { ok: false, status: 400, reason: 'unreadable body' }
|
|
207
|
-
}
|
|
208
|
-
return new TextDecoder().decode(Buffer.concat(chunks))
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
async function readJsonBody(request: Request): Promise<JsonBody> {
|
|
212
|
-
const text = await readBodyText(request)
|
|
213
|
-
if (typeof text !== 'string')
|
|
214
|
-
return text
|
|
215
|
-
if (text.trim() === '')
|
|
216
|
-
return { ok: false, status: 400, reason: 'empty body' }
|
|
217
|
-
try {
|
|
218
|
-
return { ok: true, value: JSON.parse(text) as unknown }
|
|
219
|
-
}
|
|
220
|
-
catch {
|
|
221
|
-
return { ok: false, status: 400, reason: 'body is not JSON' }
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
|
|
225
105
|
function logDrop(dev: boolean, kind: 'event' | 'vital', reason: string): void {
|
|
226
106
|
if (dev)
|
|
227
107
|
console.warn(`@prunellejs/analytics: dropped ${kind}: ${reason}`)
|
|
228
108
|
}
|
|
229
109
|
|
|
230
|
-
function parseEventPayload(
|
|
231
|
-
raw: unknown,
|
|
232
|
-
ctx: RequestContext,
|
|
233
|
-
site: string | undefined,
|
|
234
|
-
overrideHostname: string | undefined,
|
|
235
|
-
includeQueryParams: readonly string[] | undefined,
|
|
236
|
-
allowedProps: ReadonlySet<string>,
|
|
237
|
-
): { name: string, url: string, path: string, hostname: string, props?: AnalyticsEventProps | undefined } | string {
|
|
238
|
-
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
239
|
-
return 'payload is not an object'
|
|
240
|
-
const obj = raw as Record<string, unknown>
|
|
241
|
-
if (typeof obj.name !== 'string')
|
|
242
|
-
return 'name is not a string'
|
|
243
|
-
const name = obj.name.trim()
|
|
244
|
-
if (name === '' || name.length > MAX_EVENT_NAME_LEN)
|
|
245
|
-
return `name is empty or over ${MAX_EVENT_NAME_LEN} characters`
|
|
246
|
-
if ([obj.url, obj.path].some(v => typeof v === 'string' && v.length > MAX_URL_LEN))
|
|
247
|
-
return `url or path over ${MAX_URL_LEN} characters`
|
|
248
|
-
const props = sanitizeEventProps(obj.props, allowedProps)
|
|
249
|
-
if (props === null)
|
|
250
|
-
return `props invalid or past the caps (${MAX_PROP_KEYS} keys, ${MAX_PROP_KEY_LEN} character keys, ${MAX_PROP_STR_LEN} character strings)`
|
|
251
|
-
const loc = resolveEventLocation(obj.url, obj.path, ctx, site, overrideHostname, includeQueryParams)
|
|
252
|
-
return {
|
|
253
|
-
name,
|
|
254
|
-
...loc,
|
|
255
|
-
...(props !== undefined ? { props } : {}),
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
|
|
259
110
|
function reportError(
|
|
260
111
|
onError: AnalyticsOptions['onError'],
|
|
261
112
|
error: unknown,
|
|
@@ -306,6 +157,7 @@ function internalPathTest(cfg: RuntimeConfig, assetPrefix: string): (pathname: s
|
|
|
306
157
|
|| pathname.startsWith(`${assetPrefix}/`)
|
|
307
158
|
|| isDefaultSensitivePath(pathname)
|
|
308
159
|
|| (cfg.eventEndpoint !== false && pathname === cfg.eventEndpoint)
|
|
160
|
+
|| (cfg.viewEndpoint !== false && pathname === cfg.viewEndpoint)
|
|
309
161
|
|| (cfg.optOutEndpoint !== false && pathname === cfg.optOutEndpoint)
|
|
310
162
|
|| (cfg.webVitals !== undefined && pathname === cfg.webVitals.endpoint)
|
|
311
163
|
}
|
|
@@ -316,28 +168,21 @@ function createPageviewMiddleware(
|
|
|
316
168
|
site: string | undefined,
|
|
317
169
|
dispatch: DispatchFn,
|
|
318
170
|
): Middleware {
|
|
171
|
+
const beaconScript = cfg.viewEndpoint === false ? undefined : buildViewBeaconScript(cfg.viewEndpoint)
|
|
172
|
+
const beaconHash = beaconScript === undefined ? undefined : scriptCspHash(beaconScript)
|
|
319
173
|
return async (ctx, next) => {
|
|
320
174
|
const res = await next()
|
|
321
175
|
if (ctx.request.method !== 'GET' || isInternalPath(ctx.url.pathname) || !isHtmlSuccessResponse(res) || !isCountable(cfg, ctx))
|
|
322
176
|
return res
|
|
323
177
|
if (!isPrefetchRequest(ctx.request)) {
|
|
324
178
|
countPageview(cfg, site, dispatch, ctx, res.status)
|
|
325
|
-
return res
|
|
179
|
+
return cfg.viewEndpoint === false ? res : withVaryPurpose(res)
|
|
326
180
|
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
function withView(res: Response, endpoint: string): Response {
|
|
333
|
-
try {
|
|
334
|
-
res.headers.set(VIEW_HEADER, endpoint)
|
|
335
|
-
return res
|
|
336
|
-
}
|
|
337
|
-
catch {
|
|
338
|
-
const headers = new Headers(res.headers)
|
|
339
|
-
headers.set(VIEW_HEADER, endpoint)
|
|
340
|
-
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
181
|
+
if (cfg.viewEndpoint === false)
|
|
182
|
+
return res
|
|
183
|
+
if (ctx.request.headers.has('x-pru-spa') || ctx.request.headers.has('x-pru-region'))
|
|
184
|
+
return withViewHeader(res, cfg.viewEndpoint)
|
|
185
|
+
return withPrerenderBeacon(res, cfg.viewEndpoint, beaconScript!, beaconHash!)
|
|
341
186
|
}
|
|
342
187
|
}
|
|
343
188
|
|
|
@@ -387,14 +232,6 @@ function countPageview(cfg: RuntimeConfig, site: string | undefined, dispatch: D
|
|
|
387
232
|
dispatch(() => cfg.provider.sendPageview(pageview), 'pageview')
|
|
388
233
|
}
|
|
389
234
|
|
|
390
|
-
// The body is the page path and query, as `navigator.sendBeacon` sends it: anything that does not resolve to a path of this origin is refused.
|
|
391
|
-
function parseViewPath(raw: string, origin: string): URL | undefined {
|
|
392
|
-
if (raw.length > MAX_URL_LEN || !raw.startsWith('/') || raw.startsWith('//') || raw.startsWith('/\\') || !URL.canParse(raw, origin))
|
|
393
|
-
return undefined
|
|
394
|
-
const url = new URL(raw, origin)
|
|
395
|
-
return url.origin === origin ? url : undefined
|
|
396
|
-
}
|
|
397
|
-
|
|
398
235
|
function createViewHandler(
|
|
399
236
|
cfg: RuntimeConfig,
|
|
400
237
|
isInternalPath: (pathname: string) => boolean,
|
|
@@ -426,13 +263,15 @@ function createEventHandler(
|
|
|
426
263
|
logDrop(dev, 'event', 'bot user agent')
|
|
427
264
|
return new Response(null, { status: 204 })
|
|
428
265
|
}
|
|
266
|
+
if (isOptedOut(ctx)) {
|
|
267
|
+
logDrop(dev, 'event', 'visitor opted out')
|
|
268
|
+
return new Response(null, { status: 204 })
|
|
269
|
+
}
|
|
429
270
|
const parsedBody = await readJsonBody(ctx.request)
|
|
430
271
|
if (!parsedBody.ok) {
|
|
431
272
|
logDrop(dev, 'event', parsedBody.reason)
|
|
432
273
|
return ctx.deny(parsedBody.status, parsedBody.status === 413 ? 'Request body too large' : 'Invalid JSON body')
|
|
433
274
|
}
|
|
434
|
-
if (isOptedOut(ctx))
|
|
435
|
-
return new Response(null, { status: 204 })
|
|
436
275
|
const parsed = parseEventPayload(parsedBody.value, ctx, site, cfg.overrideHostname, cfg.includeQueryParams, cfg.allowedProps)
|
|
437
276
|
if (typeof parsed === 'string') {
|
|
438
277
|
logDrop(dev, 'event', parsed)
|
|
@@ -477,13 +316,15 @@ function createVitalsHandler(
|
|
|
477
316
|
logDrop(dev, 'vital', 'bot user agent')
|
|
478
317
|
return new Response(null, { status: 204 })
|
|
479
318
|
}
|
|
319
|
+
if (isOptedOut(ctx)) {
|
|
320
|
+
logDrop(dev, 'vital', 'visitor opted out')
|
|
321
|
+
return new Response(null, { status: 204 })
|
|
322
|
+
}
|
|
480
323
|
const parsedBody = await readJsonBody(ctx.request)
|
|
481
324
|
if (!parsedBody.ok) {
|
|
482
325
|
logDrop(dev, 'vital', parsedBody.reason)
|
|
483
326
|
return ctx.deny(parsedBody.status, parsedBody.status === 413 ? 'Request body too large' : 'Invalid JSON body')
|
|
484
327
|
}
|
|
485
|
-
if (isOptedOut(ctx))
|
|
486
|
-
return new Response(null, { status: 204 })
|
|
487
328
|
const received = parseWebVitalPayloads(parsedBody.value, ctx.request)
|
|
488
329
|
if (received === undefined) {
|
|
489
330
|
logDrop(dev, 'vital', 'invalid Web Vital payload')
|
|
@@ -521,7 +362,7 @@ function createVitalsScriptHandler(script: string, category: string): (ctx: Requ
|
|
|
521
362
|
const granted = ctx.consent.has(category)
|
|
522
363
|
const etag = `"${granted ? version : 'off'}"`
|
|
523
364
|
const headers = { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'private, no-cache', 'etag': etag }
|
|
524
|
-
if (ctx.request.headers.get('if-none-match')
|
|
365
|
+
if (etagMatches(ctx.request.headers.get('if-none-match'), etag))
|
|
525
366
|
return new Response(null, { status: 304, headers })
|
|
526
367
|
return new Response(granted ? script : '', { headers })
|
|
527
368
|
}
|
package/src/prerender.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Browser speculation-rules prerender/prefetch activation beacon, Vary: Purpose/Sec-Purpose, and CSP script hashing.
|
|
2
|
+
|
|
3
|
+
import { brotliDecompressSync, gunzipSync, inflateSync } from 'node:zlib'
|
|
4
|
+
|
|
5
|
+
const VIEW_HEADER = 'x-pru-view'
|
|
6
|
+
const VARY_PURPOSE_TOKENS = ['Purpose', 'Sec-Purpose'] as const
|
|
7
|
+
|
|
8
|
+
/** Tiny inline script injected only on browser speculation-rules prefetch/prerender HTML answers so activation counts one view. */
|
|
9
|
+
export function buildViewBeaconScript(endpoint: string): string {
|
|
10
|
+
const ep = JSON.stringify(endpoint).replace(/</g, '\\u003c')
|
|
11
|
+
return `(()=>{let s=()=>navigator.sendBeacon?.(${ep},location.pathname+location.search);document.prerendering?document.addEventListener("prerenderingchange",s,{once:!0}):s()})()`
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function scriptCspHash(script: string): string {
|
|
15
|
+
return `'sha256-${new Bun.CryptoHasher('sha256').update(script).digest('base64')}'`
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function appendVary(headers: Headers, tokens: readonly string[]): void {
|
|
19
|
+
const existing = headers.get('vary')
|
|
20
|
+
if (existing === null || existing.trim() === '') {
|
|
21
|
+
headers.set('vary', tokens.join(', '))
|
|
22
|
+
return
|
|
23
|
+
}
|
|
24
|
+
const parts = existing.split(',').map(v => v.trim()).filter(Boolean)
|
|
25
|
+
const seen = new Set(parts.map(v => v.toLowerCase()))
|
|
26
|
+
if (seen.has('*'))
|
|
27
|
+
return
|
|
28
|
+
for (const token of tokens) {
|
|
29
|
+
if (!seen.has(token.toLowerCase())) {
|
|
30
|
+
parts.push(token)
|
|
31
|
+
seen.add(token.toLowerCase())
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
headers.set('vary', parts.join(', '))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function appendCspScriptHash(csp: string, hash: string): string {
|
|
38
|
+
const entries = csp.split(';').map(s => s.trim()).filter(Boolean).map((raw) => {
|
|
39
|
+
const [name, ...tokens] = raw.split(/\s+/)
|
|
40
|
+
return { name: name!.toLowerCase(), tokens }
|
|
41
|
+
})
|
|
42
|
+
const byName = new Map(entries.map(e => [e.name, e.tokens]))
|
|
43
|
+
const fallback = byName.get('default-src') ?? ["'self'"]
|
|
44
|
+
const patch = (dir: string): void => {
|
|
45
|
+
let tokens = byName.get(dir)
|
|
46
|
+
if (tokens === undefined) {
|
|
47
|
+
tokens = [...fallback]
|
|
48
|
+
entries.push({ name: dir, tokens })
|
|
49
|
+
byName.set(dir, tokens)
|
|
50
|
+
}
|
|
51
|
+
if (tokens.some(t => t.toLowerCase() === "'unsafe-inline'"))
|
|
52
|
+
return
|
|
53
|
+
const noneIdx = tokens.findIndex(t => t.toLowerCase() === "'none'")
|
|
54
|
+
if (noneIdx !== -1)
|
|
55
|
+
tokens.splice(noneIdx, 1)
|
|
56
|
+
if (!tokens.includes(hash))
|
|
57
|
+
tokens.push(hash)
|
|
58
|
+
}
|
|
59
|
+
patch('script-src')
|
|
60
|
+
if (byName.has('script-src-elem'))
|
|
61
|
+
patch('script-src-elem')
|
|
62
|
+
return entries.map(e => (e.tokens.length > 0 ? `${e.name} ${e.tokens.join(' ')}` : e.name)).join('; ')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function mutateHeaders(res: Response, mutate: (headers: Headers) => void): Response {
|
|
66
|
+
try {
|
|
67
|
+
mutate(res.headers)
|
|
68
|
+
return res
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
const headers = new Headers(res.headers)
|
|
72
|
+
mutate(headers)
|
|
73
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Appends `Vary: Purpose, Sec-Purpose` so shared caches do not mix plain answers with prefetch/prerender answers. */
|
|
78
|
+
export function withVaryPurpose(res: Response): Response {
|
|
79
|
+
return mutateHeaders(res, headers => appendVary(headers, VARY_PURPOSE_TOKENS))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Marks a `@prunellejs/spa` prefetch answer with `x-pru-view` and `Vary: Purpose, Sec-Purpose` (0 B added to HTML). */
|
|
83
|
+
export function withViewHeader(res: Response, endpoint: string): Response {
|
|
84
|
+
return mutateHeaders(res, (headers) => {
|
|
85
|
+
headers.set(VIEW_HEADER, endpoint)
|
|
86
|
+
appendVary(headers, VARY_PURPOSE_TOKENS)
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function decodeHtmlBody(res: Response): Promise<string | undefined> {
|
|
91
|
+
const enc = res.headers.get('content-encoding')?.trim().toLowerCase()
|
|
92
|
+
if (enc === undefined || enc === '' || enc === 'identity')
|
|
93
|
+
return res.text()
|
|
94
|
+
if (enc !== 'gzip' && enc !== 'br' && enc !== 'deflate' && enc !== 'zstd')
|
|
95
|
+
return undefined
|
|
96
|
+
const buf = new Uint8Array(await res.arrayBuffer())
|
|
97
|
+
if (enc === 'gzip')
|
|
98
|
+
return new TextDecoder().decode(gunzipSync(buf))
|
|
99
|
+
if (enc === 'br')
|
|
100
|
+
return new TextDecoder().decode(brotliDecompressSync(buf))
|
|
101
|
+
if (enc === 'deflate')
|
|
102
|
+
return new TextDecoder().decode(inflateSync(buf))
|
|
103
|
+
return new TextDecoder().decode(Bun.zstdDecompressSync(buf))
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function injectBeforeBodyClose(html: string, tag: string): string {
|
|
107
|
+
const idx = html.toLowerCase().lastIndexOf('</body>')
|
|
108
|
+
return idx === -1 ? `${html}${tag}` : `${html.slice(0, idx)}${tag}${html.slice(idx)}`
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Marks a browser speculation-rules prefetch/prerender HTML answer with `x-pru-view`, `Vary: Purpose, Sec-Purpose`, and the activation beacon script + CSP hash. */
|
|
112
|
+
export async function withPrerenderBeacon(res: Response, endpoint: string, script: string, hash: string): Promise<Response> {
|
|
113
|
+
if (res.body === null)
|
|
114
|
+
return withViewHeader(res, endpoint)
|
|
115
|
+
const html = await decodeHtmlBody(res)
|
|
116
|
+
if (html === undefined)
|
|
117
|
+
return withViewHeader(res, endpoint)
|
|
118
|
+
const headers = new Headers(res.headers)
|
|
119
|
+
headers.set(VIEW_HEADER, endpoint)
|
|
120
|
+
appendVary(headers, VARY_PURPOSE_TOKENS)
|
|
121
|
+
headers.delete('content-encoding')
|
|
122
|
+
headers.delete('content-length')
|
|
123
|
+
headers.delete('etag')
|
|
124
|
+
const csp = headers.get('content-security-policy')
|
|
125
|
+
if (csp !== null && csp.trim() !== '')
|
|
126
|
+
headers.set('content-security-policy', appendCspScriptHash(csp, hash))
|
|
127
|
+
const nextHtml = injectBeforeBodyClose(html, `<script>${script}</script>`)
|
|
128
|
+
return new Response(nextHtml, { status: res.status, statusText: res.statusText, headers })
|
|
129
|
+
}
|
package/src/request.ts
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// Request body, URL, event payload, and ETag helpers for @prunellejs/analytics endpoints.
|
|
2
|
+
|
|
3
|
+
import type { RequestContext } from 'prunelle/server'
|
|
4
|
+
import type { AnalyticsEventProps } from './types'
|
|
5
|
+
import { resolveCanonicalLocation } from './visitor'
|
|
6
|
+
|
|
7
|
+
const MAX_EVENT_NAME_LEN = 100
|
|
8
|
+
const MAX_PROP_KEYS = 30
|
|
9
|
+
const MAX_URL_LEN = 2000
|
|
10
|
+
const MAX_BODY_BYTES = 16 * 1024
|
|
11
|
+
const MAX_PROP_KEY_LEN = 64
|
|
12
|
+
const MAX_PROP_STR_LEN = 100
|
|
13
|
+
|
|
14
|
+
export type BodyFailure = { ok: false, status: 400 | 413, reason: string }
|
|
15
|
+
export type JsonBody = { ok: true, value: unknown } | BodyFailure
|
|
16
|
+
|
|
17
|
+
const TOO_LARGE: BodyFailure = { ok: false, status: 413, reason: `body over ${MAX_BODY_BYTES} bytes` }
|
|
18
|
+
|
|
19
|
+
// Keys outside `allowed` are dropped, never refused, so a client that sends more than the app lists still counts its event.
|
|
20
|
+
function sanitizeEventProps(raw: unknown, allowed: ReadonlySet<string>): AnalyticsEventProps | undefined | null {
|
|
21
|
+
if (raw === undefined || raw === null)
|
|
22
|
+
return undefined
|
|
23
|
+
if (typeof raw !== 'object' || Array.isArray(raw))
|
|
24
|
+
return null
|
|
25
|
+
const out: AnalyticsEventProps = {}
|
|
26
|
+
let count = 0
|
|
27
|
+
let seen = 0
|
|
28
|
+
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
|
|
29
|
+
const key = k.trim()
|
|
30
|
+
if (key === '' || key.length > MAX_PROP_KEY_LEN || ++seen > MAX_PROP_KEYS)
|
|
31
|
+
return null
|
|
32
|
+
if (!allowed.has(key))
|
|
33
|
+
continue
|
|
34
|
+
if (typeof v === 'string') {
|
|
35
|
+
if (v.length > MAX_PROP_STR_LEN)
|
|
36
|
+
return null
|
|
37
|
+
out[key] = v
|
|
38
|
+
}
|
|
39
|
+
else if (typeof v === 'number' && Number.isFinite(v)) {
|
|
40
|
+
out[key] = v
|
|
41
|
+
}
|
|
42
|
+
else if (typeof v === 'boolean') {
|
|
43
|
+
out[key] = v
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
return null
|
|
47
|
+
}
|
|
48
|
+
count++
|
|
49
|
+
}
|
|
50
|
+
return count > 0 ? out : undefined
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function parseSameOriginCandidate(
|
|
54
|
+
raw: unknown,
|
|
55
|
+
baseOrigin: string,
|
|
56
|
+
requestOrigin: string,
|
|
57
|
+
): URL | undefined {
|
|
58
|
+
if (typeof raw !== 'string')
|
|
59
|
+
return undefined
|
|
60
|
+
const trimmed = raw.trim()
|
|
61
|
+
if (trimmed === '')
|
|
62
|
+
return undefined
|
|
63
|
+
let parsed: URL
|
|
64
|
+
try {
|
|
65
|
+
parsed = new URL(trimmed, baseOrigin)
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return undefined
|
|
69
|
+
}
|
|
70
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
71
|
+
return undefined
|
|
72
|
+
if (parsed.origin !== baseOrigin && parsed.origin !== requestOrigin)
|
|
73
|
+
return undefined
|
|
74
|
+
return parsed
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function resolveBaseOrigin(site: string | undefined, requestOrigin: string): string {
|
|
78
|
+
if (site !== undefined && site !== '' && URL.canParse(site)) {
|
|
79
|
+
const parsed = new URL(site)
|
|
80
|
+
if (parsed.protocol === 'http:' || parsed.protocol === 'https:')
|
|
81
|
+
return parsed.origin
|
|
82
|
+
}
|
|
83
|
+
return requestOrigin
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function resolveEventLocation(
|
|
87
|
+
rawUrl: unknown,
|
|
88
|
+
rawPath: unknown,
|
|
89
|
+
ctx: RequestContext,
|
|
90
|
+
site: string | undefined,
|
|
91
|
+
overrideHostname: string | undefined,
|
|
92
|
+
includeQueryParams: readonly string[] | undefined,
|
|
93
|
+
): { url: string, path: string, hostname: string } {
|
|
94
|
+
const requestOrigin = ctx.url.origin
|
|
95
|
+
const baseOrigin = resolveBaseOrigin(site, requestOrigin)
|
|
96
|
+
const targetUrl = parseSameOriginCandidate(rawUrl, baseOrigin, requestOrigin)
|
|
97
|
+
?? parseSameOriginCandidate(rawPath, baseOrigin, requestOrigin)
|
|
98
|
+
?? parseSameOriginCandidate(ctx.request.headers.get('referer'), baseOrigin, requestOrigin)
|
|
99
|
+
?? new URL('/', baseOrigin)
|
|
100
|
+
return resolveCanonicalLocation(targetUrl, site, overrideHostname, includeQueryParams)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Reads at most MAX_BODY_BYTES: a larger declared length is refused before reading, and a stream that outgrows it is cancelled.
|
|
104
|
+
export async function readBodyText(request: Request): Promise<string | BodyFailure> {
|
|
105
|
+
if (Number(request.headers.get('content-length')) > MAX_BODY_BYTES)
|
|
106
|
+
return TOO_LARGE
|
|
107
|
+
if (request.body === null)
|
|
108
|
+
return ''
|
|
109
|
+
const reader = request.body.getReader()
|
|
110
|
+
const chunks: Uint8Array[] = []
|
|
111
|
+
let size = 0
|
|
112
|
+
try {
|
|
113
|
+
for (;;) {
|
|
114
|
+
const { done, value } = await reader.read()
|
|
115
|
+
if (done)
|
|
116
|
+
break
|
|
117
|
+
size += value.byteLength
|
|
118
|
+
if (size > MAX_BODY_BYTES) {
|
|
119
|
+
await reader.cancel().catch(() => undefined)
|
|
120
|
+
return TOO_LARGE
|
|
121
|
+
}
|
|
122
|
+
chunks.push(value)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return { ok: false, status: 400, reason: 'unreadable body' }
|
|
127
|
+
}
|
|
128
|
+
return new TextDecoder().decode(Buffer.concat(chunks))
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function readJsonBody(request: Request): Promise<JsonBody> {
|
|
132
|
+
const text = await readBodyText(request)
|
|
133
|
+
if (typeof text !== 'string')
|
|
134
|
+
return text
|
|
135
|
+
if (text.trim() === '')
|
|
136
|
+
return { ok: false, status: 400, reason: 'empty body' }
|
|
137
|
+
try {
|
|
138
|
+
return { ok: true, value: JSON.parse(text) as unknown }
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return { ok: false, status: 400, reason: 'body is not JSON' }
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function parseEventPayload(
|
|
146
|
+
raw: unknown,
|
|
147
|
+
ctx: RequestContext,
|
|
148
|
+
site: string | undefined,
|
|
149
|
+
overrideHostname: string | undefined,
|
|
150
|
+
includeQueryParams: readonly string[] | undefined,
|
|
151
|
+
allowedProps: ReadonlySet<string>,
|
|
152
|
+
): { name: string, url: string, path: string, hostname: string, props?: AnalyticsEventProps | undefined } | string {
|
|
153
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
154
|
+
return 'payload is not an object'
|
|
155
|
+
const obj = raw as Record<string, unknown>
|
|
156
|
+
if (typeof obj.name !== 'string')
|
|
157
|
+
return 'name is not a string'
|
|
158
|
+
const name = obj.name.trim()
|
|
159
|
+
if (name === '' || name.length > MAX_EVENT_NAME_LEN)
|
|
160
|
+
return `name is empty or over ${MAX_EVENT_NAME_LEN} characters`
|
|
161
|
+
if ([obj.url, obj.path].some(v => typeof v === 'string' && v.length > MAX_URL_LEN))
|
|
162
|
+
return `url or path over ${MAX_URL_LEN} characters`
|
|
163
|
+
const props = sanitizeEventProps(obj.props, allowedProps)
|
|
164
|
+
if (props === null)
|
|
165
|
+
return `props invalid or past the caps (${MAX_PROP_KEYS} keys, ${MAX_PROP_KEY_LEN} character keys, ${MAX_PROP_STR_LEN} character strings)`
|
|
166
|
+
const loc = resolveEventLocation(obj.url, obj.path, ctx, site, overrideHostname, includeQueryParams)
|
|
167
|
+
return {
|
|
168
|
+
name,
|
|
169
|
+
...loc,
|
|
170
|
+
...(props !== undefined ? { props } : {}),
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// The body is the page path and query, as `navigator.sendBeacon` sends it: anything that does not resolve to a path of this origin is refused.
|
|
175
|
+
export function parseViewPath(raw: string, origin: string): URL | undefined {
|
|
176
|
+
if (raw.length > MAX_URL_LEN || !raw.startsWith('/') || raw.startsWith('//') || raw.startsWith('/\\') || !URL.canParse(raw, origin))
|
|
177
|
+
return undefined
|
|
178
|
+
const url = new URL(raw, origin)
|
|
179
|
+
return url.origin === origin ? url : undefined
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function etagMatches(header: string | null, etag: string): boolean {
|
|
183
|
+
if (header === null)
|
|
184
|
+
return false
|
|
185
|
+
const trimmed = header.trim()
|
|
186
|
+
if (trimmed === '*')
|
|
187
|
+
return true
|
|
188
|
+
const stripWeak = (v: string) => (v.startsWith('W/') || v.startsWith('w/') ? v.slice(2) : v)
|
|
189
|
+
const target = stripWeak(etag)
|
|
190
|
+
return trimmed.split(',').some(part => stripWeak(part.trim()) === target)
|
|
191
|
+
}
|
package/src/vitals.ts
CHANGED
|
@@ -67,7 +67,15 @@ export function parseWebVitalPayloads(raw: unknown, request: Request): WebVitalM
|
|
|
67
67
|
}
|
|
68
68
|
if (raw.length > MAX_VITALS_PER_BEACON)
|
|
69
69
|
return undefined
|
|
70
|
-
const
|
|
70
|
+
const seen = new Set<WebVitalName>()
|
|
71
|
+
const vitals: WebVitalMetric[] = []
|
|
72
|
+
for (const entry of raw) {
|
|
73
|
+
const parsed = parseWebVitalPayload(entry, request)
|
|
74
|
+
if (parsed !== undefined && !seen.has(parsed.name)) {
|
|
75
|
+
seen.add(parsed.name)
|
|
76
|
+
vitals.push(parsed)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
71
79
|
return vitals.length === 0 ? undefined : vitals
|
|
72
80
|
}
|
|
73
81
|
|