prunelle 0.6.0 → 0.7.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/LICENSE +21 -0
- package/llms.txt +48 -43
- package/package.json +4 -1
- package/src/a11y/declaration.ts +106 -72
- package/src/a11y/index.ts +59 -39
- package/src/a11y/rgaa-map.ts +95 -49
- package/src/build/bundle.ts +8 -4
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-plugin.ts +3 -1
- package/src/build/compile.ts +2 -1
- package/src/build/ecoindex.ts +15 -14
- package/src/build/files.ts +6 -0
- package/src/build/first-load.ts +83 -11
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +57 -18
- package/src/build/island-promote.ts +229 -0
- package/src/build/islands.ts +9 -201
- package/src/build/manifest.ts +4 -125
- package/src/build/plugin-host.ts +21 -8
- package/src/build/precompress.ts +1 -1
- package/src/build/prerender.ts +97 -44
- package/src/build/reach.ts +136 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +19 -3
- package/src/build/static-headers.ts +93 -0
- package/src/build/static.ts +2 -0
- package/src/cli/check-forms.ts +97 -48
- package/src/cli/check-imports.ts +25 -0
- package/src/cli/check-links.ts +2 -2
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +33 -7
- package/src/cli/commands.ts +35 -7
- package/src/cli/docs.ts +4 -3
- package/src/cli/inspect.ts +2 -1
- package/src/cli/mcp-tools.ts +7 -5
- package/src/cli/mcp.ts +1 -1
- package/src/cli/new.ts +14 -3
- package/src/cli/render.ts +14 -19
- package/src/cli/upgrade.ts +22 -5
- package/src/compiler/analyze.ts +26 -5
- package/src/compiler/cacheability.ts +2 -2
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +110 -4
- package/src/compiler/compliance-urls.ts +145 -0
- package/src/compiler/compliance.ts +168 -116
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +19 -1
- package/src/compiler/props-body.ts +52 -0
- package/src/compiler/shared.ts +2 -2
- package/src/compiler/ssr.ts +2 -2
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +90 -64
- package/src/dev/host-check.ts +26 -0
- package/src/dev/index.ts +12 -5
- package/src/dev/open-editor.ts +15 -11
- package/src/dev/protocol.ts +2 -0
- package/src/dev/supervisor.ts +8 -0
- package/src/dev/watchers.ts +27 -2
- package/src/dom/action.ts +4 -1
- package/src/dom/extras.ts +1 -2
- package/src/dom/index.ts +13 -2
- package/src/dom/island.ts +22 -10
- package/src/dom/loop.ts +25 -16
- package/src/eco/declaration.ts +257 -0
- package/src/eco/index.ts +65 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +16 -1
- package/src/plugins/load.ts +4 -3
- package/src/plugins/public.ts +2 -2
- package/src/plugins/services.ts +3 -0
- package/src/plugins/types.ts +17 -2
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +38 -37
- package/src/server/action.ts +11 -127
- package/src/server/app-secret.ts +63 -0
- package/src/server/compress.ts +5 -1
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +3 -1
- package/src/server/form-schema.ts +1 -1
- package/src/server/health.ts +46 -15
- package/src/server/http.ts +47 -7
- package/src/server/index.ts +52 -30
- package/src/server/loader.ts +6 -2
- package/src/server/plugin-host.ts +3 -1
- package/src/server/public.ts +4 -3
- package/src/server/rate-limit.ts +52 -9
- package/src/server/route-cache.ts +26 -4
- package/src/server/route-table.ts +7 -3
- package/src/server/routing.ts +3 -87
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +71 -20
- package/src/server/serve-handlers.ts +14 -4
- package/src/server/start.ts +1 -1
- package/src/server/static-dir.ts +27 -4
- package/src/server/stream.ts +28 -6
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +20 -4
- package/src/ssr/index.ts +18 -0
- package/src/ssr/navigation.ts +2 -2
- package/src/style.ts +32 -1
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/src/routes/legal.tsx +10 -1
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +1 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// The app's signing secret, and one key per purpose derived from it with HKDF so a token made for one use never verifies for another.
|
|
2
|
+
// HMAC goes through Bun.CryptoHasher, never `node:crypto`, which would add 2 MB to the server's RSS.
|
|
3
|
+
|
|
4
|
+
const EPHEMERAL_SECRET_KEY = Symbol.for('pru.form.secret')
|
|
5
|
+
const keyCache = new Map<string, Buffer>()
|
|
6
|
+
|
|
7
|
+
const hmac = (key: string | Buffer, data: string | Buffer): Buffer => new Bun.CryptoHasher('sha256', key).update(data).digest()
|
|
8
|
+
|
|
9
|
+
/** The configured secret (`PRUNELLE_FORM_SECRET`, then `AUTH_SECRET`), or one random per process that dies with it. */
|
|
10
|
+
export function appSecret(): { secret: string, ephemeral: boolean } {
|
|
11
|
+
const configured = process.env.PRUNELLE_FORM_SECRET || process.env.AUTH_SECRET
|
|
12
|
+
if (configured)
|
|
13
|
+
return { secret: configured, ephemeral: false }
|
|
14
|
+
const g = globalThis as Record<symbol, string | undefined>
|
|
15
|
+
let secret = g[EPHEMERAL_SECRET_KEY]
|
|
16
|
+
if (secret === undefined) {
|
|
17
|
+
secret = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('hex')
|
|
18
|
+
g[EPHEMERAL_SECRET_KEY] = secret
|
|
19
|
+
}
|
|
20
|
+
return { secret, ephemeral: true }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A 32-byte key for `purpose` (`"form-timestamp"`, `"action-flash"`), HKDF-SHA256 (RFC 5869) of the app secret with `"prunelle"` as salt and the purpose as `info`. */
|
|
24
|
+
export function deriveKey(purpose: string): Buffer {
|
|
25
|
+
const { secret } = appSecret()
|
|
26
|
+
const id = `${purpose}\0${secret}`
|
|
27
|
+
let key = keyCache.get(id)
|
|
28
|
+
if (key === undefined) {
|
|
29
|
+
// One SHA-256 block is the 32 bytes asked for, so the expand step is its first round alone.
|
|
30
|
+
key = hmac(hmac('prunelle', secret), Buffer.concat([Buffer.from(purpose), Buffer.of(1)]))
|
|
31
|
+
if (keyCache.size > 16)
|
|
32
|
+
keyCache.clear()
|
|
33
|
+
keyCache.set(id, key)
|
|
34
|
+
}
|
|
35
|
+
return key
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Compares two secrets (tokens, MACs, OAuth states) in constant time: both are hashed first, so neither their content nor their length shows in the timing.
|
|
40
|
+
* The digests are XORed byte by byte rather than passed to `node:crypto`.
|
|
41
|
+
*/
|
|
42
|
+
export function safeEqual(a: string, b: string): boolean {
|
|
43
|
+
const x = new Bun.CryptoHasher('sha256').update(a).digest()
|
|
44
|
+
const y = new Bun.CryptoHasher('sha256').update(b).digest()
|
|
45
|
+
let diff = 0
|
|
46
|
+
for (let i = 0; i < x.length; i++)
|
|
47
|
+
diff |= x[i]! ^ y[i]!
|
|
48
|
+
return diff === 0
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** `<signature>.<payload>`: the payload as is, behind the HMAC-SHA256 (base64url) of it under the key for `purpose`. */
|
|
52
|
+
export function signPayload(purpose: string, payload: string): string {
|
|
53
|
+
return `${hmac(deriveKey(purpose), payload).toString('base64url')}.${payload}`
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The payload of a `signPayload` value, or undefined when it is not one or its signature does not match. */
|
|
57
|
+
export function verifyPayload(purpose: string, signed: string): string | undefined {
|
|
58
|
+
const dot = signed.indexOf('.')
|
|
59
|
+
if (dot <= 0)
|
|
60
|
+
return undefined
|
|
61
|
+
const payload = signed.slice(dot + 1)
|
|
62
|
+
return safeEqual(signed.slice(0, dot), hmac(deriveKey(purpose), payload).toString('base64url')) ? payload : undefined
|
|
63
|
+
}
|
package/src/server/compress.ts
CHANGED
|
@@ -17,6 +17,9 @@ const COMPRESSIBLE_EXACT = new Set([
|
|
|
17
17
|
'application/atom+xml',
|
|
18
18
|
'application/wasm',
|
|
19
19
|
'image/svg+xml',
|
|
20
|
+
'image/x-icon',
|
|
21
|
+
'font/ttf',
|
|
22
|
+
'font/otf',
|
|
20
23
|
])
|
|
21
24
|
|
|
22
25
|
export function isCompressibleType(contentType: string | null | undefined): boolean {
|
|
@@ -380,7 +383,8 @@ export function compressedHtmlResponse(
|
|
|
380
383
|
if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
|
|
381
384
|
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
382
385
|
if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
|
|
383
|
-
|
|
386
|
+
// SHA-256 of the page, so two pages never share a kept body: a 64-bit hash could be made to collide by a page that renders the query string.
|
|
387
|
+
const staticKey = reuse ? `s:${new Bun.CryptoHasher('sha256').update(html).digest('base64url')}` : undefined
|
|
384
388
|
let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
|
|
385
389
|
if (compressed === undefined)
|
|
386
390
|
compressed = cache.compress(html, enc, staticKey)
|
package/src/server/consent.ts
CHANGED
|
@@ -10,7 +10,10 @@ export const DEFAULT_CONSENT_COOKIE = 'pru_consent'
|
|
|
10
10
|
/** 180 days in seconds (CNIL 6-month guideline for consent retention). */
|
|
11
11
|
export const DEFAULT_CONSENT_MAX_AGE = 15_552_000
|
|
12
12
|
export const DEFAULT_CONSENT_ENDPOINT = '/_pru/consent'
|
|
13
|
-
|
|
13
|
+
// v1 held the granted categories alone; v2 adds when the visitor chose and the policy version they chose under.
|
|
14
|
+
const LEGACY_COOKIE_PREFIX = 'v1:'
|
|
15
|
+
const COOKIE_PREFIX = 'v2:'
|
|
16
|
+
const POLICY_VERSION_RE = /^[\w.-]{1,32}$/
|
|
14
17
|
|
|
15
18
|
export interface ConsentConfig {
|
|
16
19
|
/** Non-essential consent categories (e.g. `['analytics', 'media']` or `{ analytics: 'Audience measurement' }`). */
|
|
@@ -21,11 +24,19 @@ export interface ConsentConfig {
|
|
|
21
24
|
maxAge?: number | undefined
|
|
22
25
|
/** POST endpoint path handling consent form submissions (default: `'/_pru/consent'`). */
|
|
23
26
|
endpoint?: string | undefined
|
|
27
|
+
/** Version of the cookie policy (letters, digits, `.`, `-`, `_`): changing it asks every visitor again. */
|
|
28
|
+
version?: string | undefined
|
|
24
29
|
}
|
|
25
30
|
|
|
26
31
|
export interface RequestConsent {
|
|
27
32
|
readonly decided: boolean
|
|
33
|
+
/** When the visitor made the choice in force, kept in the consent cookie as proof. */
|
|
34
|
+
readonly decidedAt: Date | undefined
|
|
28
35
|
readonly categories: readonly string[]
|
|
36
|
+
/** Each category's label, from `consent.categories`, the name itself when given as a list. */
|
|
37
|
+
readonly labels: Readonly<Record<string, string>>
|
|
38
|
+
/** Path the consent form posts to. */
|
|
39
|
+
readonly endpoint: string
|
|
29
40
|
has(category: string): boolean
|
|
30
41
|
all(): Record<string, boolean>
|
|
31
42
|
}
|
|
@@ -33,14 +44,19 @@ export interface RequestConsent {
|
|
|
33
44
|
export interface NormalizedConsentConfig {
|
|
34
45
|
readonly categories: readonly string[]
|
|
35
46
|
readonly categorySet: ReadonlySet<string>
|
|
47
|
+
readonly labels: Readonly<Record<string, string>>
|
|
36
48
|
readonly cookieName: string
|
|
37
49
|
readonly maxAge: number
|
|
38
50
|
readonly endpoint: string
|
|
51
|
+
readonly version: string
|
|
39
52
|
}
|
|
40
53
|
|
|
41
54
|
const EMPTY_CONSENT: RequestConsent = {
|
|
42
55
|
decided: false,
|
|
56
|
+
decidedAt: undefined,
|
|
43
57
|
categories: [],
|
|
58
|
+
labels: {},
|
|
59
|
+
endpoint: DEFAULT_CONSENT_ENDPOINT,
|
|
44
60
|
has: category => category === 'essential',
|
|
45
61
|
all: () => ({}),
|
|
46
62
|
}
|
|
@@ -49,8 +65,10 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
|
|
|
49
65
|
if (config === undefined)
|
|
50
66
|
return undefined
|
|
51
67
|
const rawList = Array.isArray(config.categories) ? config.categories : Object.keys(config.categories)
|
|
68
|
+
const given: Readonly<Record<string, string>> = Array.isArray(config.categories) ? {} : config.categories as Readonly<Record<string, string>>
|
|
52
69
|
const categories: string[] = []
|
|
53
70
|
const categorySet = new Set<string>()
|
|
71
|
+
const labels: Record<string, string> = {}
|
|
54
72
|
for (const item of rawList) {
|
|
55
73
|
const name = item.trim()
|
|
56
74
|
if (name === '' || name === 'essential' || categorySet.has(name))
|
|
@@ -59,49 +77,67 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
|
|
|
59
77
|
throw new Error(`prunelle: consent category "${name}" cannot contain "," or ":"`)
|
|
60
78
|
categorySet.add(name)
|
|
61
79
|
categories.push(name)
|
|
80
|
+
labels[name] = given[item]?.trim() || name
|
|
62
81
|
}
|
|
82
|
+
const version = config.version?.trim() ?? ''
|
|
83
|
+
if (version !== '' && !POLICY_VERSION_RE.test(version))
|
|
84
|
+
throw new Error(`prunelle: consent version "${config.version}" must be 1 to 32 letters, digits, ".", "-" or "_", such as '2026-11' or '3'`)
|
|
63
85
|
const rawEndpoint = (config.endpoint ?? DEFAULT_CONSENT_ENDPOINT).trim()
|
|
64
86
|
const endpoint = rawEndpoint.startsWith('/') ? rawEndpoint : `/${rawEndpoint}`
|
|
65
87
|
return {
|
|
66
88
|
categories,
|
|
67
89
|
categorySet,
|
|
90
|
+
labels,
|
|
68
91
|
cookieName: config.cookieName ?? DEFAULT_CONSENT_COOKIE,
|
|
69
92
|
maxAge: config.maxAge ?? DEFAULT_CONSENT_MAX_AGE,
|
|
70
93
|
endpoint,
|
|
94
|
+
version,
|
|
71
95
|
}
|
|
72
96
|
}
|
|
73
97
|
|
|
74
|
-
|
|
98
|
+
interface ParsedConsent { decided: boolean, decidedAt: Date | undefined, granted: Set<string> }
|
|
99
|
+
|
|
100
|
+
function grantedOf(list: string, declared: ReadonlySet<string>): Set<string> {
|
|
75
101
|
const granted = new Set<string>()
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
for (const part of payload.split(',')) {
|
|
81
|
-
const cat = part.trim()
|
|
82
|
-
if (declared.has(cat))
|
|
83
|
-
granted.add(cat)
|
|
84
|
-
}
|
|
102
|
+
for (const part of list.split(',')) {
|
|
103
|
+
const cat = part.trim()
|
|
104
|
+
if (declared.has(cat))
|
|
105
|
+
granted.add(cat)
|
|
85
106
|
}
|
|
86
|
-
return
|
|
107
|
+
return granted
|
|
87
108
|
}
|
|
88
109
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
110
|
+
/** Reads `v2:<seconds>:<policy version>:<categories>`; a choice made under another policy version counts as no choice. */
|
|
111
|
+
export function parseConsentCookie(raw: string | undefined, declared: ReadonlySet<string>, version = ''): ParsedConsent {
|
|
112
|
+
const none: ParsedConsent = { decided: false, decidedAt: undefined, granted: new Set() }
|
|
113
|
+
if (raw === undefined)
|
|
114
|
+
return none
|
|
115
|
+
if (raw.startsWith(LEGACY_COOKIE_PREFIX))
|
|
116
|
+
return version === '' ? { decided: true, decidedAt: undefined, granted: grantedOf(raw.slice(LEGACY_COOKIE_PREFIX.length), declared) } : none
|
|
117
|
+
if (!raw.startsWith(COOKIE_PREFIX))
|
|
118
|
+
return none
|
|
119
|
+
const [seconds, storedVersion, list] = raw.slice(COOKIE_PREFIX.length).split(':')
|
|
120
|
+
const at = Number(seconds)
|
|
121
|
+
if (list === undefined || storedVersion !== version || !Number.isSafeInteger(at) || at <= 0)
|
|
122
|
+
return none
|
|
123
|
+
return { decided: true, decidedAt: new Date(at * 1000), granted: grantedOf(list, declared) }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function serializeConsentCookie(granted: ReadonlySet<string>, declared: readonly string[], version = '', decidedAt = new Date()): string {
|
|
127
|
+
const ordered = declared.filter(cat => granted.has(cat))
|
|
128
|
+
return `${COOKIE_PREFIX}${Math.floor(decidedAt.getTime() / 1000)}:${version}:${ordered.join(',')}`
|
|
96
129
|
}
|
|
97
130
|
|
|
98
131
|
export function createRequestConsent(rawCookie: string | undefined, config: NormalizedConsentConfig | undefined): RequestConsent {
|
|
99
132
|
if (config === undefined)
|
|
100
133
|
return EMPTY_CONSENT
|
|
101
|
-
const { decided, granted } = parseConsentCookie(rawCookie, config.categorySet)
|
|
134
|
+
const { decided, decidedAt, granted } = parseConsentCookie(rawCookie, config.categorySet, config.version)
|
|
102
135
|
return {
|
|
103
136
|
decided,
|
|
137
|
+
decidedAt,
|
|
104
138
|
categories: config.categories,
|
|
139
|
+
labels: config.labels,
|
|
140
|
+
endpoint: config.endpoint,
|
|
105
141
|
has(category: string): boolean {
|
|
106
142
|
return category === 'essential' || granted.has(category)
|
|
107
143
|
},
|
|
@@ -232,7 +268,7 @@ export function registerConsentRoute(
|
|
|
232
268
|
if (!parsed.ok)
|
|
233
269
|
return ctx.deny(400, parsed.error)
|
|
234
270
|
|
|
235
|
-
const cookieVal = serializeConsentCookie(parsed.granted, config.categories)
|
|
271
|
+
const cookieVal = serializeConsentCookie(parsed.granted, config.categories, config.version)
|
|
236
272
|
ctx.cookies.set(config.cookieName, cookieVal, {
|
|
237
273
|
httpOnly: true,
|
|
238
274
|
sameSite: 'lax',
|
|
@@ -248,6 +284,7 @@ export function registerConsentRoute(
|
|
|
248
284
|
return ctx.json({ ok: true, decided: true, consent })
|
|
249
285
|
}
|
|
250
286
|
const target = resolveConsentRedirect(ctx.request, ctx.url, parsed.redirect, trustedOrigins, trustProxy)
|
|
251
|
-
|
|
287
|
+
// resolveConsentRedirect only returns this site or a trusted origin.
|
|
288
|
+
return ctx.redirect(target, 303, { external: true })
|
|
252
289
|
}, { csrf: true })
|
|
253
290
|
}
|
package/src/server/cookies.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// Typed cookie jar for RequestContext (lazy Cookie header parsing, validated & deduplicated Set-Cookie serialization).
|
|
2
2
|
|
|
3
|
+
import { getAppContext } from '../plugins/context'
|
|
4
|
+
|
|
3
5
|
export interface CookieOptions {
|
|
4
6
|
path?: string | undefined
|
|
5
7
|
domain?: string | undefined
|
|
@@ -8,10 +10,20 @@ export interface CookieOptions {
|
|
|
8
10
|
httpOnly?: boolean | undefined
|
|
9
11
|
secure?: boolean | undefined
|
|
10
12
|
sameSite?: 'strict' | 'lax' | 'none' | undefined
|
|
11
|
-
/** Consent category required before setting this cookie
|
|
13
|
+
/** Consent category required before setting this cookie, or `'essential'` for a cookie the site cannot work without; omitted, it counts as essential and `prunelle dev` warns. */
|
|
12
14
|
category?: string | undefined
|
|
13
15
|
}
|
|
14
16
|
|
|
17
|
+
const warnedUncategorized = new Set<string>()
|
|
18
|
+
|
|
19
|
+
// Once per cookie name and process, in dev only: production has no one to read it.
|
|
20
|
+
function warnUncategorized(name: string): void {
|
|
21
|
+
if (warnedUncategorized.has(name) || getAppContext()?.dev !== true)
|
|
22
|
+
return
|
|
23
|
+
warnedUncategorized.add(name)
|
|
24
|
+
console.warn(`prunelle: cookie "${name}" was set without a category, so it counts as essential and is set without consent: pass { category: 'essential' } when the site cannot work without it, or its consent category (such as 'analytics') so it waits for the visitor's consent.`)
|
|
25
|
+
}
|
|
26
|
+
|
|
15
27
|
export interface Cookies {
|
|
16
28
|
get(name: string): string | undefined
|
|
17
29
|
set(name: string, value: string, options?: CookieOptions): void
|
|
@@ -110,7 +122,9 @@ export class CookieStore implements Cookies {
|
|
|
110
122
|
}
|
|
111
123
|
|
|
112
124
|
set(name: string, value: string, options?: CookieOptions): void {
|
|
113
|
-
if (options?.category
|
|
125
|
+
if (options?.category === undefined)
|
|
126
|
+
warnUncategorized(name)
|
|
127
|
+
else if (options.category !== 'essential') {
|
|
114
128
|
if (this.#isConsentGranted === undefined || !this.#isConsentGranted(options.category))
|
|
115
129
|
return
|
|
116
130
|
}
|
package/src/server/env.ts
CHANGED
|
@@ -11,6 +11,20 @@ export function nodeEnv(): string | undefined {
|
|
|
11
11
|
return getAppContext()?.nodeEnv ?? process.env[NODE_ENV_KEY]
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
const DEV_KEY = 'PRUNELLE_DEV'
|
|
15
|
+
// A compiled binary runs its entry from Bun's embedded filesystem.
|
|
16
|
+
const BINARY_MAIN_RE = /^\/\$bunfs\//
|
|
17
|
+
|
|
18
|
+
/** Whether `PRUNELLE_DEV=1` asks for dev mode where the caller did not say; it throws under NODE_ENV=production and inside a compiled binary, where the dev-only routes would reach visitors. */
|
|
19
|
+
export function devFromEnv(): boolean {
|
|
20
|
+
if (process.env[DEV_KEY] !== '1')
|
|
21
|
+
return false
|
|
22
|
+
const where = BINARY_MAIN_RE.test(Bun.main) ? 'inside a compiled binary' : nodeEnv() === 'production' ? 'with NODE_ENV=production' : undefined
|
|
23
|
+
if (where !== undefined)
|
|
24
|
+
throw new Error(`prunelle: PRUNELLE_DEV=1 is set ${where}, where dev mode would open the CMS write routes, the mail outbox and the other dev-only routes to visitors: unset PRUNELLE_DEV, or use prunelle dev.`)
|
|
25
|
+
return true
|
|
26
|
+
}
|
|
27
|
+
|
|
14
28
|
export function defineEnv<S extends StandardSchemaV1>(
|
|
15
29
|
schema: S,
|
|
16
30
|
source: Record<string, string | undefined> = process.env,
|
package/src/server/errors.ts
CHANGED
|
@@ -321,10 +321,12 @@ export function createFallbackPages(options: FallbackPagesOptions) {
|
|
|
321
321
|
const found = lookup.find('error', effUrl, routeFile)
|
|
322
322
|
if (found !== undefined) {
|
|
323
323
|
const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
|
|
324
|
+
// Outside dev the page gets a bare error: a thrown message can name a host, a table or a credential, and it lands in HTML anyone can load.
|
|
325
|
+
const shown = options.dev ? error : Object.assign(new Error('Internal Server Error'), { stack: 'Error: Internal Server Error' })
|
|
324
326
|
const rendered = await renderCompiledStatusPage(
|
|
325
327
|
found.page,
|
|
326
328
|
500,
|
|
327
|
-
{ error, status: 500, message: errorMessage(
|
|
329
|
+
{ error: shown, status: 500, message: errorMessage(shown), url: effUrl, params, locals: ctx?.locals ?? {} },
|
|
328
330
|
effUrl,
|
|
329
331
|
params,
|
|
330
332
|
req,
|
|
@@ -42,7 +42,7 @@ const SAFE_INT_MIN = Number.MIN_SAFE_INTEGER
|
|
|
42
42
|
const SAFE_INT_MAX = Number.MAX_SAFE_INTEGER
|
|
43
43
|
const schemaCache = new WeakMap<StandardSchemaV1, ExtractedFormSchema>()
|
|
44
44
|
|
|
45
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
45
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
46
46
|
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
47
47
|
}
|
|
48
48
|
|
package/src/server/health.ts
CHANGED
|
@@ -177,9 +177,13 @@ export function collectHealthChecks(
|
|
|
177
177
|
return entries
|
|
178
178
|
}
|
|
179
179
|
|
|
180
|
-
async function runSingleHealthCheck(entry: HealthCheckEntry): Promise<[string, HealthCheckOutcome]> {
|
|
180
|
+
async function runSingleHealthCheck(entry: HealthCheckEntry, timeoutMs: number, exposeErrors: boolean): Promise<[string, HealthCheckOutcome]> {
|
|
181
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
181
182
|
try {
|
|
182
|
-
const result = await
|
|
183
|
+
const result = await Promise.race([
|
|
184
|
+
entry.fn(),
|
|
185
|
+
new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs} ms`)), timeoutMs) }),
|
|
186
|
+
])
|
|
183
187
|
if (result === true || result === undefined)
|
|
184
188
|
return [entry.name, { ok: true }]
|
|
185
189
|
if (result === false)
|
|
@@ -189,8 +193,20 @@ async function runSingleHealthCheck(entry: HealthCheckEntry): Promise<[string, H
|
|
|
189
193
|
return [entry.name, result.message !== undefined ? { ok: false, error: result.message } : { ok: false }]
|
|
190
194
|
}
|
|
191
195
|
catch (err) {
|
|
192
|
-
|
|
196
|
+
// What a check threw can name a host, a table or a credential: the log keeps it, the answer says only that the check failed (outside dev).
|
|
197
|
+
console.error(`prunelle: health check "${entry.name}" failed: ${err instanceof Error ? err.message : String(err)}`)
|
|
198
|
+
return [entry.name, { ok: false, error: exposeErrors ? (err instanceof Error ? err.message : String(err)) : 'check failed' }]
|
|
193
199
|
}
|
|
200
|
+
finally {
|
|
201
|
+
clearTimeout(timer)
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
interface HealthSnapshot {
|
|
206
|
+
at: number
|
|
207
|
+
status: number
|
|
208
|
+
payload: string
|
|
209
|
+
length: string
|
|
194
210
|
}
|
|
195
211
|
|
|
196
212
|
export interface HealthHandlerOptions {
|
|
@@ -198,11 +214,17 @@ export interface HealthHandlerOptions {
|
|
|
198
214
|
securityRecord: Record<string, string>
|
|
199
215
|
withHsts: (res: Response, request: Request) => Response
|
|
200
216
|
resolveRequestId: RequestIdResolver
|
|
217
|
+
/** Send what a check threw back to the caller (`prunelle dev`); by default the answer only says `check failed`. */
|
|
218
|
+
exposeErrors?: boolean | undefined
|
|
219
|
+
/** How long one answer is reused (default 5000 ms), so a probe loop or a flood runs the checks once per window. */
|
|
220
|
+
cacheMs?: number | undefined
|
|
221
|
+
/** How long one check may take (default 5000 ms) before it counts as failed. */
|
|
222
|
+
timeoutMs?: number | undefined
|
|
201
223
|
}
|
|
202
224
|
|
|
203
225
|
/** Handles `GET`/`HEAD` requests to `${assetPrefix}/health`, returning 200 when healthy and 503 if any check fails. */
|
|
204
226
|
export function createHealthHandler(options: HealthHandlerOptions): (request: Request, requestId?: string) => Response | Promise<Response> {
|
|
205
|
-
const { checks, securityRecord, withHsts, resolveRequestId } = options
|
|
227
|
+
const { checks, securityRecord, withHsts, resolveRequestId, exposeErrors = false, cacheMs = 5000, timeoutMs = 5000 } = options
|
|
206
228
|
const baseHeaders: Record<string, string> = {
|
|
207
229
|
'content-type': 'application/json; charset=utf-8',
|
|
208
230
|
'cache-control': 'no-store',
|
|
@@ -217,6 +239,22 @@ export function createHealthHandler(options: HealthHandlerOptions): (request: Re
|
|
|
217
239
|
return withHsts(res, request)
|
|
218
240
|
}
|
|
219
241
|
|
|
242
|
+
let cached: HealthSnapshot | undefined
|
|
243
|
+
let inflight: Promise<HealthSnapshot> | undefined
|
|
244
|
+
const evaluate = async (): Promise<HealthSnapshot> => {
|
|
245
|
+
const results = await Promise.all(checks.map(entry => runSingleHealthCheck(entry, timeoutMs, exposeErrors)))
|
|
246
|
+
const checkMap: Record<string, HealthCheckOutcome> = {}
|
|
247
|
+
let allOk = true
|
|
248
|
+
for (const [name, outcome] of results) {
|
|
249
|
+
checkMap[name] = outcome
|
|
250
|
+
if (!outcome.ok)
|
|
251
|
+
allOk = false
|
|
252
|
+
}
|
|
253
|
+
const payload = JSON.stringify({ ok: allOk, checks: checkMap })
|
|
254
|
+
cached = { at: Date.now(), status: allOk ? 200 : 503, payload, length: String(Buffer.byteLength(payload, 'utf8')) }
|
|
255
|
+
return cached
|
|
256
|
+
}
|
|
257
|
+
|
|
220
258
|
return (request: Request, requestId?: string): Response | Promise<Response> => {
|
|
221
259
|
const reqId = requestId ?? resolveRequestId(request)
|
|
222
260
|
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
@@ -229,16 +267,9 @@ export function createHealthHandler(options: HealthHandlerOptions): (request: Re
|
|
|
229
267
|
if (checks.length === 0)
|
|
230
268
|
return jsonReply(request, 200, okPayload, okLength, reqId)
|
|
231
269
|
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
checkMap[name] = outcome
|
|
237
|
-
if (!outcome.ok)
|
|
238
|
-
allOk = false
|
|
239
|
-
}
|
|
240
|
-
const payload = JSON.stringify({ ok: allOk, checks: checkMap })
|
|
241
|
-
return jsonReply(request, allOk ? 200 : 503, payload, String(Buffer.byteLength(payload, 'utf8')), reqId)
|
|
242
|
-
})
|
|
270
|
+
if (cached !== undefined && Date.now() - cached.at < cacheMs)
|
|
271
|
+
return jsonReply(request, cached.status, cached.payload, cached.length, reqId)
|
|
272
|
+
inflight ??= evaluate().finally(() => { inflight = undefined })
|
|
273
|
+
return inflight.then(snap => jsonReply(request, snap.status, snap.payload, snap.length, reqId))
|
|
243
274
|
}
|
|
244
275
|
}
|
package/src/server/http.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { CookieStore } from './cookies'
|
|
|
12
12
|
import { nodeEnv } from './env'
|
|
13
13
|
import { resolveFallbackRequestId } from './health'
|
|
14
14
|
import { requestedRegion } from './region'
|
|
15
|
+
import { GATED_ROUTE_CACHE_CONTROL } from './route-cache'
|
|
15
16
|
import { getClientIp, isHttpsRequest } from './security'
|
|
16
17
|
|
|
17
18
|
export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
|
|
@@ -126,6 +127,8 @@ export interface ServerOptions extends ServerRuntimeConfig {
|
|
|
126
127
|
outDir?: string | undefined
|
|
127
128
|
port?: number | undefined
|
|
128
129
|
dev?: boolean | undefined
|
|
130
|
+
/** @internal The address `prunelle dev` binds, from which plugins get `api.devExposed`. */
|
|
131
|
+
devHost?: string | undefined
|
|
129
132
|
nodeEnv?: string | undefined
|
|
130
133
|
/** @internal Imports a built server module by absolute path; `prunelle dev` passes one that keeps unchanged modules loaded. */
|
|
131
134
|
importModule?: ((path: string) => Promise<Record<string, unknown>>) | undefined
|
|
@@ -151,7 +154,8 @@ export interface RequestContext<Params = Record<string, string>> {
|
|
|
151
154
|
readonly region?: string | undefined
|
|
152
155
|
json: (data: unknown, init?: ResponseInit) => Response
|
|
153
156
|
text: (body: string, init?: ResponseInit) => Response
|
|
154
|
-
redirect
|
|
157
|
+
/** A redirect to a path or a URL of this site; one to another site throws unless `{ external: true }` says the app chose that target (never one read from the request). */
|
|
158
|
+
redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308, options?: RedirectOptions) => Response
|
|
155
159
|
deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
|
|
156
160
|
}
|
|
157
161
|
|
|
@@ -171,6 +175,8 @@ export interface PrunelleApp {
|
|
|
171
175
|
inject?: <T>(key: ServiceKey<T>) => T | undefined
|
|
172
176
|
/** Closes active long-lived streams (such as SSE) before `server.stop()` drains normal in-flight HTTP requests. */
|
|
173
177
|
closeStreams?: () => Promise<void>
|
|
178
|
+
/** @internal The security headers each response of this app carries, which the 503 of a build swap in `prunelle start` repeats. */
|
|
179
|
+
securityHeaders?: Readonly<Record<string, string>> | undefined
|
|
174
180
|
/** Runs plugin shutdown hooks and releases timers/resources (safe to call multiple times). */
|
|
175
181
|
dispose?: () => Promise<void>
|
|
176
182
|
}
|
|
@@ -191,6 +197,7 @@ export interface EmbeddedServerConfig extends ServerRuntimeConfig {
|
|
|
191
197
|
outDir?: string | undefined
|
|
192
198
|
publicDir?: string | undefined
|
|
193
199
|
dev?: boolean | undefined
|
|
200
|
+
devHost?: string | undefined
|
|
194
201
|
nodeEnv?: string | undefined
|
|
195
202
|
errorSink?: ((info: ServerErrorInfo) => void) | undefined
|
|
196
203
|
prerender?: boolean | undefined
|
|
@@ -248,6 +255,8 @@ export interface RequestContextOptions {
|
|
|
248
255
|
url?: URL | undefined
|
|
249
256
|
consent?: NormalizedConsentConfig | undefined
|
|
250
257
|
requestId?: string | undefined
|
|
258
|
+
/** The app's `site` is https: cookies get `Secure` even when a proxy the server does not trust hides the scheme. */
|
|
259
|
+
httpsSite?: boolean | undefined
|
|
251
260
|
}
|
|
252
261
|
|
|
253
262
|
// None of these read the request, so every context shares them.
|
|
@@ -281,7 +290,36 @@ export function getDeniedInfo(res: Response): DeniedInfo | undefined {
|
|
|
281
290
|
return DENIED_RESPONSES.get(res)
|
|
282
291
|
}
|
|
283
292
|
|
|
284
|
-
|
|
293
|
+
export interface RedirectOptions {
|
|
294
|
+
/** Allows a target on another site: a payment page, an identity provider, a redirect rule the app wrote itself. */
|
|
295
|
+
external?: boolean | undefined
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const EXTERNAL_REDIRECTS = new WeakSet<Response>()
|
|
299
|
+
|
|
300
|
+
/** Whether `res` came from `ctx.redirect(url, status, { external: true })`: the one kind of cross-site redirect an island's action call follows. */
|
|
301
|
+
export function isExternalRedirect(res: Response): boolean {
|
|
302
|
+
return EXTERNAL_REDIRECTS.has(res)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function sameOrigin(location: string, base: URL): boolean {
|
|
306
|
+
try {
|
|
307
|
+
return new URL(location, base).origin === base.origin
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
return false
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const makeRedirect = (base: URL): RequestContext['redirect'] => (location, status = 302, options) => {
|
|
315
|
+
const external = options?.external === true
|
|
316
|
+
if (!external && !sameOrigin(location, base))
|
|
317
|
+
throw new Error(`prunelle: ctx.redirect("${location}") leaves ${base.origin}: redirect to a path of this site, or pass { external: true } as the third argument when the app chose that address itself (never one read from the request, which makes an open redirect).`)
|
|
318
|
+
const res = new Response(null, { status, headers: { location } })
|
|
319
|
+
if (external)
|
|
320
|
+
EXTERNAL_REDIRECTS.add(res)
|
|
321
|
+
return res
|
|
322
|
+
}
|
|
285
323
|
const deny: RequestContext['deny'] = (status, message, fieldErrors) => {
|
|
286
324
|
const res = Response.json({ ok: false, status, error: message, fieldErrors }, { status })
|
|
287
325
|
DENIED_RESPONSES.set(res, { status, message, fieldErrors })
|
|
@@ -316,7 +354,7 @@ export function makeRequestContext(
|
|
|
316
354
|
let cachedConsentRaw: string | undefined
|
|
317
355
|
const cookieStore = new CookieStore(
|
|
318
356
|
request.headers.get('cookie'),
|
|
319
|
-
isHttpsRequest(request, trustProxy),
|
|
357
|
+
opts?.httpsSite === true || isHttpsRequest(request, trustProxy),
|
|
320
358
|
category => getConsent().has(category),
|
|
321
359
|
)
|
|
322
360
|
const getConsent = (): RequestConsent => {
|
|
@@ -330,9 +368,10 @@ export function makeRequestContext(
|
|
|
330
368
|
const requestId = opts?.requestId ?? resolveFallbackRequestId(request, trustProxy)
|
|
331
369
|
let cachedIp: string | undefined
|
|
332
370
|
let ipComputed = false
|
|
371
|
+
const url = opts?.url ?? new URL(request.url)
|
|
333
372
|
const ctx: RequestContext = {
|
|
334
373
|
request,
|
|
335
|
-
url
|
|
374
|
+
url,
|
|
336
375
|
params,
|
|
337
376
|
cookies: cookieStore,
|
|
338
377
|
get consent() {
|
|
@@ -356,7 +395,7 @@ export function makeRequestContext(
|
|
|
356
395
|
},
|
|
357
396
|
json,
|
|
358
397
|
text,
|
|
359
|
-
redirect,
|
|
398
|
+
redirect: makeRedirect(url),
|
|
360
399
|
deny,
|
|
361
400
|
}
|
|
362
401
|
return { ctx, cookieStore }
|
|
@@ -464,8 +503,9 @@ export function applyHstsHeader(
|
|
|
464
503
|
trustProxy: TrustProxy,
|
|
465
504
|
isDev = false,
|
|
466
505
|
resolvedEnv?: string,
|
|
506
|
+
httpsSite = false,
|
|
467
507
|
): Response {
|
|
468
|
-
if (hstsValue === undefined || isDev || !isHttpsRequest(request, trustProxy))
|
|
508
|
+
if (hstsValue === undefined || isDev || !(httpsSite || isHttpsRequest(request, trustProxy)))
|
|
469
509
|
return res
|
|
470
510
|
const env = resolvedEnv ?? nodeEnv()
|
|
471
511
|
if (env === 'development' || env === 'test')
|
|
@@ -501,7 +541,7 @@ export function finalizeResponse(
|
|
|
501
541
|
if (hasCookies) {
|
|
502
542
|
cookieStore!.applyTo(h)
|
|
503
543
|
const cc = h.get('cache-control')
|
|
504
|
-
if (cc !== null && PUBLIC_CACHE_RE.test(cc))
|
|
544
|
+
if (cc !== null && (PUBLIC_CACHE_RE.test(cc) || cc === GATED_ROUTE_CACHE_CONTROL))
|
|
505
545
|
h.set('cache-control', 'private, no-store')
|
|
506
546
|
}
|
|
507
547
|
for (const [k, v] of entries) {
|