prunelle 0.7.3 → 0.8.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.
Files changed (63) hide show
  1. package/llms.txt +20 -18
  2. package/package.json +1 -1
  3. package/src/a11y/index.ts +9 -2
  4. package/src/build/graph.ts +1 -1
  5. package/src/build/index.ts +30 -31
  6. package/src/build/island-promote.ts +1 -1
  7. package/src/build/output.ts +1 -1
  8. package/src/build/prerender.ts +29 -13
  9. package/src/build/routes.ts +19 -1
  10. package/src/build/static.ts +24 -2
  11. package/src/cli/check-forms.ts +16 -6
  12. package/src/cli/check-links.ts +13 -10
  13. package/src/cli/check-security.ts +94 -12
  14. package/src/cli/check.ts +3 -2
  15. package/src/cli/commands.ts +3 -3
  16. package/src/cli/upgrade.ts +36 -3
  17. package/src/compiler/analyze.ts +16 -2
  18. package/src/compiler/compliance.ts +4 -0
  19. package/src/compiler/dom-attrs.ts +4 -1
  20. package/src/compiler/dom.ts +41 -15
  21. package/src/compiler/emit.ts +1 -1
  22. package/src/compiler/shared.ts +9 -16
  23. package/src/compiler/ssr-helpers.ts +45 -21
  24. package/src/compiler/ssr.ts +32 -16
  25. package/src/context.ts +2 -0
  26. package/src/dev/error-log.ts +1 -1
  27. package/src/dev/index.ts +1 -1
  28. package/src/dev/supervisor.ts +2 -2
  29. package/src/dom/attrs.ts +9 -1
  30. package/src/dom/island.ts +30 -4
  31. package/src/jsx-runtime.ts +1 -1
  32. package/src/plugins/context.ts +18 -1
  33. package/src/plugins/services.ts +1 -0
  34. package/src/plugins/types.ts +1 -1
  35. package/src/reactivity/index.ts +14 -2
  36. package/src/server/action.ts +26 -18
  37. package/src/server/app-secret.ts +8 -9
  38. package/src/server/assets.ts +22 -4
  39. package/src/server/consent.ts +7 -2
  40. package/src/server/cookies.ts +8 -1
  41. package/src/server/document.ts +5 -2
  42. package/src/server/errors.ts +57 -26
  43. package/src/server/health.ts +2 -2
  44. package/src/server/http.ts +1 -1
  45. package/src/server/index.ts +20 -18
  46. package/src/server/page.ts +12 -15
  47. package/src/server/public.ts +1 -1
  48. package/src/server/rate-limit.ts +36 -12
  49. package/src/server/route-cache.ts +9 -10
  50. package/src/server/route-table.ts +38 -13
  51. package/src/server/router.ts +4 -4
  52. package/src/server/sanitize-html.ts +21 -7
  53. package/src/server/security.ts +56 -15
  54. package/src/server/serve-handlers.ts +3 -3
  55. package/src/server/start.ts +2 -2
  56. package/src/server/static-dir.ts +3 -10
  57. package/src/server/stream.ts +4 -4
  58. package/src/ssr/consent-banner.ts +3 -1
  59. package/src/ssr/context.ts +85 -2
  60. package/src/ssr/index.ts +16 -4
  61. package/src/ssr/navigation.ts +1 -1
  62. package/src/style.ts +9 -7
  63. package/src/unrenderable.ts +15 -5
@@ -34,16 +34,34 @@ export interface PrerenderedSources {
34
34
  isFast: (urlPath: string, route: RouteManifestEntry) => boolean
35
35
  }
36
36
 
37
- const EXTRA_PRERENDER_MIME: Record<string, string> = {
37
+ /** Shared MIME table for `public/`, hashed assets, prerendered files and `prunelle start --static`. */
38
+ export const STATIC_MIME: Readonly<Record<string, string>> = {
39
+ ...MIME,
38
40
  '.htm': 'text/html; charset=utf-8',
39
41
  '.rss': 'application/rss+xml; charset=utf-8',
40
42
  '.atom': 'application/atom+xml; charset=utf-8',
41
43
  '.ics': 'text/calendar; charset=utf-8',
42
44
  '.csv': 'text/csv; charset=utf-8',
45
+ '.vtt': 'text/vtt; charset=utf-8',
46
+ '.geojson': 'application/geo+json; charset=utf-8',
47
+ '.mp3': 'audio/mpeg',
48
+ '.ogg': 'audio/ogg',
49
+ '.oga': 'audio/ogg',
50
+ '.ogv': 'video/ogg',
51
+ '.m4a': 'audio/mp4',
52
+ '.wav': 'audio/wav',
53
+ '.flac': 'audio/flac',
54
+ '.opus': 'audio/opus',
55
+ '.zip': 'application/zip',
56
+ }
57
+
58
+ /** MIME type for a file extension, falling back to `application/octet-stream`. */
59
+ export function staticMime(ext: string): string {
60
+ return STATIC_MIME[ext.toLowerCase()] ?? 'application/octet-stream'
43
61
  }
44
62
 
45
63
  function prerenderedMime(ext: string, filePath: string | undefined): string {
46
- const mapped = MIME[ext] ?? EXTRA_PRERENDER_MIME[ext]
64
+ const mapped = STATIC_MIME[ext.toLowerCase()]
47
65
  if (mapped !== undefined)
48
66
  return mapped
49
67
  if (filePath !== undefined) {
@@ -74,7 +92,7 @@ export function createAssets(options: AssetsOptions) {
74
92
 
75
93
  const registerPublic = (rel: string, body: EmbeddedBody, etag?: string, sidecars: ReturnType<typeof sidecarsOf> = { br: undefined, gz: undefined }): void => {
76
94
  const cleanRel = rel.replace(/^\/+/, '')
77
- const type = MIME[extname(cleanRel).toLowerCase()] ?? 'application/octet-stream'
95
+ const type = staticMime(extname(cleanRel))
78
96
  publicMap.set(`/${cleanRel}`, servedFile({
79
97
  key: `p:/${cleanRel}`,
80
98
  source: embedded(body),
@@ -105,7 +123,7 @@ export function createAssets(options: AssetsOptions) {
105
123
  for (const [rel, body] of Object.entries(assets)) {
106
124
  if ((rel.endsWith('.br') || rel.endsWith('.gz')) && rel.slice(0, -3) in assets)
107
125
  continue
108
- const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
126
+ const type = staticMime(extname(rel))
109
127
  const sidecar = (ext: 'br' | 'gz'): FileSource | undefined => {
110
128
  const source = assets[`${rel}.${ext}`] ?? (typeof body === 'string' && existsSync(`${body}.${ext}`) ? `${body}.${ext}` : undefined)
111
129
  return source === undefined ? undefined : embedded(source)
@@ -75,6 +75,8 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
75
75
  continue
76
76
  if (name.includes(',') || name.includes(':'))
77
77
  throw new Error(`prunelle: consent category "${name}" cannot contain "," or ":"`)
78
+ if (name === 'action' || name === 'redirect' || name === 'categories')
79
+ throw new Error(`prunelle: consent category "${name}" is reserved by the consent form; choose another category name.`)
78
80
  categorySet.add(name)
79
81
  categories.push(name)
80
82
  labels[name] = given[item]?.trim() || name
@@ -116,7 +118,10 @@ export function parseConsentCookie(raw: string | undefined, declared: ReadonlySe
116
118
  return version === '' ? { decided: true, decidedAt: undefined, granted: grantedOf(raw.slice(LEGACY_COOKIE_PREFIX.length), declared) } : none
117
119
  if (!raw.startsWith(COOKIE_PREFIX))
118
120
  return none
119
- const [seconds, storedVersion, list] = raw.slice(COOKIE_PREFIX.length).split(':')
121
+ const parts = raw.slice(COOKIE_PREFIX.length).split(':')
122
+ if (parts.length !== 3)
123
+ return none
124
+ const [seconds, storedVersion, list] = parts
120
125
  const at = Number(seconds)
121
126
  if (list === undefined || storedVersion !== version || !Number.isSafeInteger(at) || at <= 0)
122
127
  return none
@@ -243,7 +248,7 @@ async function parseConsentSubmission(
243
248
 
244
249
  const listed = new Set(form.getAll('categories').filter((v): v is string => typeof v === 'string'))
245
250
  for (const cat of config.categories) {
246
- if (listed.has(cat) || isTruthyFormValue(form.get(cat)))
251
+ if (listed.has(cat) || (cat !== 'action' && cat !== 'redirect' && cat !== 'categories' && isTruthyFormValue(form.get(cat))))
247
252
  granted.add(cat)
248
253
  }
249
254
  return { ok: true, granted, redirect }
@@ -73,7 +73,14 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
73
73
  if (sameSite === 'none' && !secure)
74
74
  throw new Error(`prunelle: Cookie "${name}" with sameSite: "none" requires secure: true`)
75
75
 
76
- let out = `${name}=${encodeURIComponent(value)}`
76
+ let encoded: string
77
+ try {
78
+ encoded = encodeURIComponent(value)
79
+ }
80
+ catch {
81
+ throw new TypeError(`prunelle: invalid cookie value for "${name}": contains an unpaired UTF-16 surrogate; sanitize with value.toWellFormed() before setting the cookie.`)
82
+ }
83
+ let out = `${name}=${encoded}`
77
84
  out += `; Path=${path}`
78
85
  if (options.domain !== undefined)
79
86
  out += `; Domain=${options.domain}`
@@ -126,7 +126,9 @@ function withBaseCsp(res: Response, htmlHeaders: HtmlHeaders): Response {
126
126
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
127
127
  }
128
128
 
129
- /** A plugin's HTML page without a CSP of its own gets the app's, its `<style>` blocks hashed like a rendered page's. */
129
+ const HEAD_END_RE = /<\/head\s*>|<body[\s>]/i
130
+
131
+ /** A plugin's HTML page without a CSP of its own gets the app's, with the `<style>` blocks of its `<head>` hashed: one in the body may be content the page echoes, so it stays blocked. */
130
132
  export async function withPluginHtmlCsp(res: Response, htmlHeaders: HtmlHeaders): Promise<Response> {
131
133
  if (res.body === null || res.headers.has('content-security-policy') || !(res.headers.get('content-type') ?? '').trim().toLowerCase().startsWith('text/html'))
132
134
  return res
@@ -138,7 +140,8 @@ export async function withPluginHtmlCsp(res: Response, htmlHeaders: HtmlHeaders)
138
140
  return withBaseCsp(probed.passthrough, htmlHeaders)
139
141
  const html = new TextDecoder().decode(probed.buffered)
140
142
  const headers = new Headers(res.headers)
141
- const csp = htmlHeaders(false, false, true, inlineStyleHashes(html))['content-security-policy']
143
+ const headEnd = HEAD_END_RE.exec(html)?.index ?? 0
144
+ const csp = htmlHeaders(false, false, true, inlineStyleHashes(html.slice(0, headEnd)))['content-security-policy']
142
145
  if (csp !== undefined)
143
146
  headers.set('content-security-policy', csp)
144
147
  return new Response(html, { status: res.status, statusText: res.statusText, headers })
@@ -20,10 +20,14 @@ import { styleHashesOf } from './security'
20
20
 
21
21
  export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source'], requestId?: string) => void
22
22
 
23
+ const describeNonError = (error: unknown): string => error instanceof Response
24
+ ? `prunelle: a Response (HTTP ${error.status}) was thrown instead of returned; return it from load() or the route handler instead.`
25
+ : String(error)
26
+
23
27
  /** The text of an error a dev response shows: its stack, which starts with its message. */
24
- export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : String(error)
28
+ export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : describeNonError(error)
25
29
 
26
- const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error)
30
+ const errorMessage = (error: unknown): string => error instanceof Error ? error.message : describeNonError(error)
27
31
 
28
32
  const HTML_ESCAPE_RE = /[&<>"']/g
29
33
  const HTML_ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
@@ -57,11 +61,14 @@ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) |
57
61
  errorHooks.push({ owner: p.name, hook: p.onError })
58
62
  }
59
63
  return (error, request, source, requestId) => {
60
- const info: ServerErrorInfo = requestId !== undefined ? { error, request, source, requestId } : { error, request, source }
64
+ const normalized = error instanceof Response
65
+ ? (void error.body?.cancel().catch(() => undefined), new Error(describeNonError(error)))
66
+ : error
67
+ const info: ServerErrorInfo = requestId !== undefined ? { error: normalized, request, source, requestId } : { error: normalized, request, source }
61
68
  options.sink?.(info)
62
69
  if (errorHooks.length === 0 && (options.dev === true || options.sink === undefined)) {
63
70
  const idSuffix = requestId !== undefined ? ` [${requestId}]` : ''
64
- console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, error)
71
+ console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, normalized)
65
72
  }
66
73
  for (const { owner, hook } of errorHooks) {
67
74
  try {
@@ -89,8 +96,13 @@ interface CompiledStatusPage {
89
96
  doc: DocumentOptions
90
97
  }
91
98
 
99
+ interface StatusPageHit {
100
+ page: CompiledStatusPage
101
+ params?: Record<string, string>
102
+ }
103
+
92
104
  interface StatusPageLookup {
93
- find: (kind: StatusPageKind, url?: URL, routeFile?: string) => { page: CompiledStatusPage, params?: Record<string, string> } | undefined
105
+ findAll: (kind: StatusPageKind, url?: URL, routeFile?: string) => StatusPageHit[]
94
106
  }
95
107
 
96
108
  function dirnamePrefix(file: string): string {
@@ -184,7 +196,16 @@ function buildStatusPageLookup(
184
196
  }
185
197
 
186
198
  return {
187
- find(kind, url, routeFile) {
199
+ findAll(kind, url, routeFile) {
200
+ const out: StatusPageHit[] = []
201
+ const seen = new Set<CompiledStatusPage>()
202
+ const push = (page: CompiledStatusPage, params?: Record<string, string>) => {
203
+ if (seen.has(page))
204
+ return
205
+ seen.add(page)
206
+ out.push(params !== undefined ? { page, params } : { page })
207
+ }
208
+
188
209
  if (routeFile !== undefined) {
189
210
  const dirMap = byDirPrefix.get(kind)
190
211
  if (dirMap !== undefined) {
@@ -192,27 +213,27 @@ function buildStatusPageLookup(
192
213
  while (dir !== undefined) {
193
214
  const hit = dirMap.get(dir)
194
215
  if (hit !== undefined)
195
- return { page: hit }
216
+ push(hit)
196
217
  if (dir === routesPrefix || !dir.startsWith(routesPrefix))
197
218
  break
198
219
  dir = parentDirPrefix(dir)
199
220
  }
200
221
  const rootHit = dirMap.get(routesPrefix)
201
222
  if (rootHit !== undefined)
202
- return { page: rootHit }
223
+ push(rootHit)
203
224
  }
204
- return undefined
225
+ return out
205
226
  }
206
227
 
207
228
  const decoded = decodeRequestPath(url?.pathname ?? '/')
208
229
  if (decoded === undefined)
209
- return undefined
230
+ return out
210
231
  const urlRouter = byUrlRouter.get(kind)
211
232
  if (urlRouter !== undefined) {
212
233
  for (let i = decoded.segments.length; i >= 0; i--) {
213
234
  const matched = urlRouter.match(pathPrefix(decoded, i))
214
235
  if (matched !== undefined)
215
- return { page: matched.data, params: matched.params }
236
+ push(matched.data, matched.params)
216
237
  }
217
238
  }
218
239
  const fallbackGroup = groupUrlRouter.get(kind)
@@ -220,10 +241,10 @@ function buildStatusPageLookup(
220
241
  for (let i = decoded.segments.length; i >= 0; i--) {
221
242
  const matched = fallbackGroup.match(pathPrefix(decoded, i))
222
243
  if (matched !== undefined)
223
- return { page: matched.data, params: matched.params }
244
+ push(matched.data, matched.params)
224
245
  }
225
246
  }
226
- return undefined
247
+ return out
227
248
  },
228
249
  }
229
250
  }
@@ -321,11 +342,11 @@ export function createFallbackPages(options: FallbackPagesOptions) {
321
342
 
322
343
  async function buildErrorResponse(error: unknown, url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
323
344
  const effUrl = url ?? new URL('http://localhost/500')
324
- const found = lookup.find('error', effUrl, routeFile)
325
- if (found !== undefined) {
345
+ const candidates = lookup.findAll('error', effUrl, routeFile)
346
+ // 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.
347
+ const shown = options.dev ? error : Object.assign(new Error('Internal Server Error'), { stack: 'Error: Internal Server Error' })
348
+ for (const found of candidates) {
326
349
  const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
327
- // 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.
328
- const shown = options.dev ? error : Object.assign(new Error('Internal Server Error'), { stack: 'Error: Internal Server Error' })
329
350
  const rendered = await renderCompiledStatusPage(
330
351
  found.page,
331
352
  500,
@@ -338,13 +359,19 @@ export function createFallbackPages(options: FallbackPagesOptions) {
338
359
  if (rendered !== undefined)
339
360
  return rendered
340
361
  }
341
- return new Response(req?.method === 'HEAD' ? null : (options.dev ? errorDetail(error) : 'Internal Server Error'), { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
362
+ const text = options.dev ? errorDetail(error) : 'Internal Server Error'
363
+ if (candidates.length > 0) {
364
+ return new Response(req?.method === 'HEAD' ? null : minimalStatusHtml(500, text, options.lang), {
365
+ status: 500,
366
+ headers: htmlHeaders(false, false, true, fallbackHeadStyleHashes),
367
+ })
368
+ }
369
+ return new Response(req?.method === 'HEAD' ? null : text, { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
342
370
  }
343
371
 
344
372
  async function buildNotFoundResponse(url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
345
373
  const effUrl = url ?? new URL('http://localhost/404')
346
- const found = lookup.find('404', effUrl, routeFile)
347
- if (found !== undefined) {
374
+ for (const found of lookup.findAll('404', effUrl, routeFile)) {
348
375
  const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
349
376
  const rendered = await renderCompiledStatusPage(
350
377
  found.page,
@@ -363,13 +390,17 @@ export function createFallbackPages(options: FallbackPagesOptions) {
363
390
 
364
391
  async function renderDenied(denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
365
392
  const statusKey = String(denied.status)
366
- const statusHit = STATUS_KINDS.has(statusKey) ? lookup.find(statusKey as StatusPageKind, url, routeFile) : undefined
367
- const found = statusHit ?? lookup.find('error', url, routeFile)
368
- if (found !== undefined) {
393
+ const statusHits = STATUS_KINDS.has(statusKey) ? lookup.findAll(statusKey as StatusPageKind, url, routeFile) : []
394
+ for (const found of statusHits) {
395
+ const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
396
+ const props = { status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
397
+ const rendered = await renderCompiledStatusPage(found.page, denied.status, props, url, params, req, ctx)
398
+ if (rendered !== undefined)
399
+ return rendered
400
+ }
401
+ for (const found of lookup.findAll('error', url, routeFile)) {
369
402
  const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
370
- const props = statusHit !== undefined
371
- ? { status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
372
- : { error: new Error(denied.message), status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
403
+ const props = { error: new Error(denied.message), status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
373
404
  const rendered = await renderCompiledStatusPage(found.page, denied.status, props, url, params, req, ctx)
374
405
  if (rendered !== undefined)
375
406
  return rendered
@@ -2,6 +2,7 @@
2
2
 
3
3
  import type { Middleware, RequestContext } from './http'
4
4
  import type { TrustProxy } from './security'
5
+ import { proxyHops } from './security'
5
6
 
6
7
  export type HealthCheckResult = boolean | void | { ok: boolean, message?: string | undefined }
7
8
  export type HealthCheckFn = () => HealthCheckResult | Promise<HealthCheckResult>
@@ -55,8 +56,7 @@ export function isSafeRequestId(id: string): boolean {
55
56
  return true
56
57
  }
57
58
 
58
- const trustsProxyHeader = (trustProxy: TrustProxy): boolean =>
59
- trustProxy === true || (typeof trustProxy === 'number' && trustProxy > 0)
59
+ const trustsProxyHeader = (trustProxy: TrustProxy): boolean => proxyHops(trustProxy) > 0
60
60
 
61
61
  /** Fast per-server request ID resolver: 8-char random boot prefix + base36 counter (zero `randomUUID` / regex per request). */
62
62
  export function createRequestIdResolver(trustProxy: TrustProxy): RequestIdResolver {
@@ -167,7 +167,7 @@ export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) =>
167
167
  export type PrunelleServer = ReturnType<typeof Bun.serve>
168
168
 
169
169
  export interface PrunelleApp {
170
- handle: (request: Request, remoteIp?: string, disableTimeout?: () => void) => Promise<Response>
170
+ handle: (request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void) => Promise<Response>
171
171
  serve: (port?: number, hostname?: string) => PrunelleServer
172
172
  /** @internal Swaps this app's handlers into a server another app started, with no dropped connection: `prunelle start` reloads a new build with it. */
173
173
  reloadInto?: (server: PrunelleServer) => void
@@ -45,7 +45,7 @@ import { createRouteCache } from './route-cache'
45
45
  import { compileRouteTable, createCompiledRouteRenderer, routeMethodHandler } from './route-table'
46
46
  import { actionRoutePrefix, createAncestorMiddlewareLookup, inferRoutesServerPrefix, methodNotAllowed } from './routing'
47
47
  import { isPlainRead, isRead, serveHandlers } from './serve-handlers'
48
- import { buildSecurityHeaderEntries, isLoopbackHost, logOriginHint, resolveHstsValue, verifyOrigin } from './security'
48
+ import { buildSecurityHeaderEntries, isLoopbackHost, logOriginHint, resolveHstsValue, resolveTrustProxy, verifyOrigin } from './security'
49
49
  import { createStreamTracker } from './stream'
50
50
 
51
51
  /**
@@ -197,10 +197,11 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
197
197
  ): Promise<Response> => {
198
198
  const actionHandler = request.method === 'POST' ? registeredAction : undefined
199
199
  let req = request
200
+ // Any unsafe method, so a cross-site PUT reaches no middleware either.
201
+ const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
202
+ if (!originCheck.ok)
203
+ return refuseCrossSite(request, originCheck, existing?.cookieStore, requestId)
200
204
  if (actionHandler !== undefined) {
201
- const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
202
- if (!originCheck.ok)
203
- return refuseCrossSite(request, originCheck, existing?.cookieStore, requestId)
204
205
  const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore, requestId)
205
206
  if (checked instanceof Response)
206
207
  return checked
@@ -327,7 +328,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
327
328
  const site = config.site?.replace(/\/$/, '') || undefined
328
329
  const trustedOriginsList = config.trustedOrigins ?? []
329
330
  const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
330
- const trustProxy = config.trustProxy ?? false
331
+ const trustProxy = resolveTrustProxy(config.trustProxy ?? false, site, trustedOriginsList)
331
332
  const consent = normalizeConsentConfig(config.consent)
332
333
  const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
333
334
  const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
@@ -440,7 +441,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
440
441
  }
441
442
 
442
443
  // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
443
- async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
444
+ async function handleInternal(request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void, bodyLimited = false): Promise<Response> {
444
445
  const requestId = resolveRequestId(request)
445
446
  try {
446
447
  const url = new URL(request.url)
@@ -522,7 +523,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
522
523
  if (headFallbackPluginDef !== undefined)
523
524
  res = stripHeadBody(res)
524
525
  else if (isEventStream(res))
525
- res = streams.track(res, disableTimeout)
526
+ res = streams.track(res, setIdleTimeout)
526
527
  return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
527
528
  }
528
529
  catch (error) {
@@ -539,6 +540,12 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
539
540
  }
540
541
 
541
542
  const matched = router.match(effective)
543
+ // Before any middleware: an unmatched path, a 405 and a route without a handler for the method are checked too, unless the route opts out.
544
+ if (matched?.data.mod.csrf !== false) {
545
+ const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
546
+ if (!originCheck.ok)
547
+ return refuseCrossSite(request, originCheck, cookieStore, requestId)
548
+ }
542
549
  if (matched === undefined) {
543
550
  if (pluginMatch !== undefined) {
544
551
  ctx.params = pluginMatch.params
@@ -559,13 +566,8 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
559
566
  ctx.params = matched.params
560
567
  const route = matched.data
561
568
 
562
- // CSRF verification & body limit for file-based API routes (opt out of CSRF via `export const csrf = false`)
569
+ // Body limit for file-based API routes; the origin was checked above.
563
570
  if (routeMethodHandler(route.mod, method) !== undefined) {
564
- if (route.mod.csrf !== false) {
565
- const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
566
- if (!originCheck.ok)
567
- return refuseCrossSite(request, originCheck, cookieStore, requestId)
568
- }
569
571
  const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
570
572
  if (checked instanceof Response)
571
573
  return checked
@@ -577,9 +579,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
577
579
  : route.middlewares
578
580
 
579
581
  try {
580
- const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, disableTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
582
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, setIdleTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
581
583
  const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
582
- const res = isEventStream(handledRes) ? streams.track(handledRes, disableTimeout) : handledRes
584
+ const res = isEventStream(handledRes) ? streams.track(handledRes, setIdleTimeout) : handledRes
583
585
  // Compress uncompressed API/middleware responses after the middleware chain unwinds.
584
586
  const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
585
587
  return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
@@ -595,11 +597,11 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
595
597
  }
596
598
  }
597
599
 
598
- function handle(request: Request, remoteIp?: string, disableTimeout?: () => void): Promise<Response> {
599
- return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, disableTimeout))
600
+ function handle(request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void): Promise<Response> {
601
+ return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, setIdleTimeout))
600
602
  }
601
603
 
602
- const runRequest = (req: Request, remoteIp: string | undefined, disableTimeout: () => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, disableTimeout, true))
604
+ const runRequest = (req: Request, remoteIp: string | undefined, setIdleTimeout: (seconds: number) => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, setIdleTimeout, true))
603
605
  const runFast = (handler: FastHandler, req: Request, remoteIp: string | undefined): Response | Promise<Response> => runWithAppContext(serverAppCtx, () => handler(req, remoteIp))
604
606
  const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
605
607
 
@@ -12,6 +12,10 @@ export interface LoadedPageModule {
12
12
  load?: (ctx: RequestContext) => unknown | Promise<unknown>
13
13
  clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
14
14
  csrf?: boolean | undefined
15
+ /** The language the page is written in, for its `<html lang>`, when it differs from `lang` in prunelle.config.ts. */
16
+ lang?: string | undefined
17
+ /** How long this route's request may stay silent before the connection closes, in seconds or a duration string (`'5m'`), `0` for no limit; the server's is 30 s. */
18
+ idleTimeout?: number | string | undefined
15
19
  GET?: (ctx: RequestContext) => Response | Promise<Response>
16
20
  POST?: (ctx: RequestContext) => Response | Promise<Response>
17
21
  PUT?: (ctx: RequestContext) => Response | Promise<Response>
@@ -83,18 +87,14 @@ export function isPlainObject(v: unknown): v is Record<string, unknown> {
83
87
  return typeof v === 'object' && v !== null && !Array.isArray(v)
84
88
  }
85
89
 
86
- function pickObjectKeys(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> | undefined {
87
- if (keys.length === 0)
88
- return undefined
90
+ // The keys of `obj` the island reads, as an object even when it holds none of them: the island reads `data.x` as the server did, on an object.
91
+ function pickObjectKeys(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {
89
92
  const picked: Record<string, unknown> = {}
90
- let count = 0
91
93
  for (const k of keys) {
92
- if (Object.hasOwn(obj, k)) {
94
+ if (Object.hasOwn(obj, k))
93
95
  Object.defineProperty(picked, k, { value: obj[k], enumerable: true, writable: true, configurable: true })
94
- count++
95
- }
96
96
  }
97
- return count > 0 ? picked : undefined
97
+ return picked
98
98
  }
99
99
 
100
100
  export function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mod: LoadedPageModule): Record<string, unknown> {
@@ -105,18 +105,15 @@ export function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mo
105
105
  return subset === undefined ? {} : { data: subset }
106
106
  }
107
107
  if (Array.isArray(mod.clientData)) {
108
- if (!isPlainObject(data))
108
+ if (!isPlainObject(data) || mod.clientData.length === 0)
109
109
  return {}
110
- const subset = pickObjectKeys(data, mod.clientData)
111
- return subset === undefined ? {} : { data: subset }
110
+ return { data: pickObjectKeys(data, mod.clientData) }
112
111
  }
113
112
  if (entry.islandDataKeys !== undefined) {
114
113
  if (entry.islandDataKeys.length === 0)
115
114
  return {}
116
- if (isPlainObject(data)) {
117
- const subset = pickObjectKeys(data, entry.islandDataKeys)
118
- return subset === undefined ? {} : { data: subset }
119
- }
115
+ if (isPlainObject(data))
116
+ return { data: pickObjectKeys(data, entry.islandDataKeys) }
120
117
  }
121
118
  return { data }
122
119
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  export { action, getActionError } from './action'
4
4
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionProtectOptions, ActionResult, ServerAction } from './action'
5
- export { safeEqual } from './app-secret'
5
+ export { deriveKey, safeEqual, signPayload, verifyPayload } from './app-secret'
6
6
  export type { ConsentConfig, RequestConsent } from './consent'
7
7
  export type { CookieOptions, Cookies } from './cookies'
8
8
  export { defineEnv, nodeEnv } from './env'
@@ -158,25 +158,49 @@ const warnedMissingIp = new WeakSet<object>()
158
158
 
159
159
  const BRACKETED_RE = /^\[([^\]]+)\](?::\d+)?$/
160
160
  const IPV4_PORT_RE = /^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/
161
- const MAPPED_IPV4_RE = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i
161
+ const IPV4_RE = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/
162
162
  const HEXTET_RE = /^[\da-f]{1,4}$/i
163
163
 
164
+ function parseIpv6Groups(parts: readonly string[], allowDottedLast: boolean): number[] | undefined {
165
+ const out: number[] = []
166
+ for (let i = 0; i < parts.length; i++) {
167
+ const part = parts[i]!
168
+ if (allowDottedLast && i === parts.length - 1 && part.includes('.')) {
169
+ const m = IPV4_RE.exec(part)
170
+ if (m === null)
171
+ return undefined
172
+ const octets = [Number(m[1]), Number(m[2]), Number(m[3]), Number(m[4])]
173
+ if (octets.some(o => o > 255))
174
+ return undefined
175
+ out.push((octets[0]! << 8) | octets[1]!, (octets[2]! << 8) | octets[3]!)
176
+ continue
177
+ }
178
+ if (!HEXTET_RE.test(part))
179
+ return undefined
180
+ out.push(Number.parseInt(part, 16))
181
+ }
182
+ return out
183
+ }
184
+
164
185
  /** The address a rate limit counts: an IPv4 address without its port or its `::ffff:` mapping, or the /64 network of an IPv6 address, any of whose 2^64 addresses one host may use. */
165
186
  export function rateLimitAddress(ip: string): string {
166
187
  const bare = BRACKETED_RE.exec(ip)?.[1] ?? IPV4_PORT_RE.exec(ip)?.[1] ?? ip
167
- const addr = MAPPED_IPV4_RE.exec(bare)?.[1] ?? bare
188
+ const pct = bare.indexOf('%')
189
+ const addr = pct === -1 ? bare : bare.slice(0, pct)
168
190
  const halves = addr.split('::')
169
191
  if (!addr.includes(':') || halves.length > 2)
170
- return addr
171
- const head = halves[0] === '' ? [] : halves[0]!.split(':')
172
- const tail = halves[1] ? halves[1].split(':') : []
173
- // A dotted IPv4 ending holds the last two groups.
174
- const tailGroups = tail.length + (tail.at(-1)?.includes('.') === true ? 1 : 0)
175
- const zeros = halves.length === 2 ? 8 - head.length - tailGroups : 0
176
- const groups = [...head, ...Array.from({ length: Math.max(0, zeros) }, () => '0'), ...tail].slice(0, 4)
177
- if (groups.length < 4 || !groups.every(g => HEXTET_RE.test(g)))
178
- return addr
179
- return `${groups.map(g => Number.parseInt(g, 16).toString(16)).join(':')}::/64`
192
+ return bare
193
+ const head = parseIpv6Groups(halves[0] === '' ? [] : halves[0]!.split(':'), halves.length === 1)
194
+ const tail = parseIpv6Groups(halves[1] ? halves[1].split(':') : [], halves.length === 2)
195
+ if (head === undefined || tail === undefined)
196
+ return bare
197
+ const zeros = halves.length === 2 ? 8 - head.length - tail.length : 0
198
+ if (zeros < 0 || head.length + zeros + tail.length !== 8)
199
+ return bare
200
+ const full = [...head, ...Array.from({ length: zeros }, () => 0), ...tail]
201
+ if (full[0] === 0 && full[1] === 0 && full[2] === 0 && full[3] === 0 && full[4] === 0 && full[5] === 0xFFFF)
202
+ return `${full[6]! >> 8}.${full[6]! & 0xFF}.${full[7]! >> 8}.${full[7]! & 0xFF}`
203
+ return `${full.slice(0, 4).map(g => g.toString(16)).join(':')}::/64`
180
204
  }
181
205
 
182
206
  /** The key `limit` counts `ctx` under: the limit's own `key`, else the client's network (`rateLimitAddress`), else one shared fallback that warns in production. */
@@ -356,19 +356,18 @@ export class RouteCache {
356
356
  headers.age = age
357
357
  if (serverTiming !== undefined)
358
358
  headers['server-timing'] = serverTiming
359
+ if (compressCache !== undefined)
360
+ headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
359
361
  if (etagMatches(request.headers.get('if-none-match'), headers.etag!))
360
362
  return markCompressionHandled(new Response(null, { status: 304, headers }))
361
363
 
362
- if (compressCache !== undefined) {
363
- headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
364
- if (request.method !== 'HEAD') {
365
- const enc = pickEncoding(request.headers.get('accept-encoding'))
366
- if (enc !== undefined) {
367
- const compressed = this.#getOrCompress(entry, html, enc)
368
- if (compressed !== null) {
369
- headers['content-encoding'] = enc
370
- return markCompressionHandled(new Response(compressed, { status: 200, headers }))
371
- }
364
+ if (compressCache !== undefined && request.method !== 'HEAD') {
365
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
366
+ if (enc !== undefined) {
367
+ const compressed = this.#getOrCompress(entry, html, enc)
368
+ if (compressed !== null) {
369
+ headers['content-encoding'] = enc
370
+ return markCompressionHandled(new Response(compressed, { status: 200, headers }))
372
371
  }
373
372
  }
374
373
  }