prunelle 0.7.4 → 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.
@@ -85,6 +85,7 @@ export const CMS_INLINE_ENABLED_SERVICE = serviceKey<boolean>('prunelle.cms.inli
85
85
  export interface JobsQueueOptions {
86
86
  attempts?: number | undefined
87
87
  backoff?: 'exponential' | 'fixed' | number | undefined
88
+ timeout?: number | undefined
88
89
  }
89
90
 
90
91
  export interface JobsEnqueueOptions {
@@ -240,7 +240,7 @@ export interface ServerRuntimeConfig {
240
240
  assetPrefix?: string | undefined
241
241
  security?: SecurityHeadersOptions | false | undefined
242
242
  trustedOrigins?: string[] | undefined
243
- trustProxy?: TrustProxy | undefined
243
+ trustProxy?: boolean | number | undefined
244
244
  maxRequestBodySize?: number | undefined
245
245
  /** How plain page changes feel without client JS: view transitions between pages, Speculation Rules prefetch on hover, opt-in prerender. */
246
246
  navigation?: NavigationConfig | undefined
@@ -157,54 +157,58 @@ function isPlainRecord(value: unknown): value is Record<string, unknown> {
157
157
  return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Blob)
158
158
  }
159
159
 
160
- function appendFormValue(target: Record<string, unknown>, key: string, value: FormDataEntryValue, forceArray: boolean): void {
160
+ /** A form field whose name both holds a value and nests dotted fields (`a` and `a.b`): the body has no shape that keeps both. */
161
+ class FormFieldConflict extends Error {
162
+ constructor(readonly field: string) {
163
+ super(`form field "${field}" conflicts with another field`)
164
+ }
165
+ }
166
+
167
+ function appendFormValue(target: Record<string, unknown>, key: string, value: FormDataEntryValue, forceArray: boolean, rawKey: string): void {
161
168
  if (!Object.hasOwn(target, key)) {
162
169
  setField(target, key, forceArray ? [value] : value)
163
170
  return
164
171
  }
165
172
  const prev = target[key]
173
+ if (isPlainRecord(prev))
174
+ throw new FormFieldConflict(rawKey)
166
175
  if (Array.isArray(prev))
167
176
  prev.push(value)
168
177
  else
169
178
  setField(target, key, [prev, value])
170
179
  }
171
180
 
172
- /** Parses `FormData` into a plain record, mapping trailing `[]` names to arrays and dotted names (`a.b`, `a.b.c`) to nested objects safely. */
181
+ /** Parses `FormData` into a plain record, mapping trailing `[]` names to arrays and dotted names (`a.b`, `a.b.c`) to nested objects safely; throws `FormFieldConflict` when a name both holds a value and nests others. */
173
182
  export function parseFormData(formData: FormData): Record<string, unknown> {
174
183
  const out: Record<string, unknown> = {}
175
184
  for (const [rawKey, val] of formData.entries()) {
176
185
  const forceArray = rawKey.length > 2 && rawKey.endsWith('[]')
177
186
  const key = forceArray ? rawKey.slice(0, -2) : rawKey
178
187
  if (!key.includes('.')) {
179
- appendFormValue(out, key, val, forceArray)
188
+ appendFormValue(out, key, val, forceArray, rawKey)
180
189
  continue
181
190
  }
182
191
  const parts = key.split('.')
183
192
  if (parts.some(p => UNSAFE_NESTED_KEYS.has(p)))
184
193
  continue
185
194
  if (parts.length > MAX_NESTED_DEPTH || parts.some(p => p.length === 0)) {
186
- appendFormValue(out, key, val, forceArray)
195
+ appendFormValue(out, key, val, forceArray, rawKey)
187
196
  continue
188
197
  }
189
198
  let cur = out
190
- let blocked = false
191
- for (let i = 0; i < parts.length - 1; i++) {
192
- const seg = parts[i]!
199
+ for (const seg of parts.slice(0, -1)) {
193
200
  if (!Object.hasOwn(cur, seg)) {
194
201
  const next: Record<string, unknown> = {}
195
202
  setField(cur, seg, next)
196
203
  cur = next
204
+ continue
197
205
  }
198
- else if (isPlainRecord(cur[seg])) {
199
- cur = cur[seg]
200
- }
201
- else {
202
- blocked = true
203
- break
204
- }
206
+ const held = cur[seg]
207
+ if (!isPlainRecord(held))
208
+ throw new FormFieldConflict(rawKey)
209
+ cur = held
205
210
  }
206
- if (!blocked)
207
- appendFormValue(cur, parts[parts.length - 1]!, val, forceArray)
211
+ appendFormValue(cur, parts[parts.length - 1]!, val, forceArray, rawKey)
208
212
  }
209
213
  return out
210
214
  }
@@ -448,8 +452,12 @@ export async function executeAction(
448
452
  try {
449
453
  rawBody = await parseActionBody(request)
450
454
  }
451
- catch {
452
- return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
455
+ catch (error) {
456
+ if (!(error instanceof FormFieldConflict))
457
+ return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
458
+ const fieldErrors = { [error.field]: 'This field conflicts with another field of the form' }
459
+ return flashAndRedirect('Invalid request body', fieldErrors, undefined)
460
+ ?? Response.json({ ok: false, status: 400, error: 'Invalid request body', fieldErrors }, { status: 400 })
453
461
  }
454
462
  }
455
463
 
@@ -20,9 +20,8 @@ export function appSecret(): { secret: string, ephemeral: boolean } {
20
20
  return { secret, ephemeral: true }
21
21
  }
22
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()
23
+ /** A 32-byte key for `purpose` (`"form-timestamp"`, `"action-flash"`), HKDF-SHA256 (RFC 5869) of the app secret (or of `secret`, for a plugin with a secret of its own) with `"prunelle"` as salt and the purpose as `info`. */
24
+ export function deriveKey(purpose: string, secret: string = appSecret().secret): Buffer {
26
25
  const id = `${purpose}\0${secret}`
27
26
  let key = keyCache.get(id)
28
27
  if (key === undefined) {
@@ -48,16 +47,16 @@ export function safeEqual(a: string, b: string): boolean {
48
47
  return diff === 0
49
48
  }
50
49
 
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}`
50
+ /** `<signature>.<payload>`: the payload as is, behind the HMAC-SHA256 (base64url) of it under the key for `purpose`, derived from the app secret or from `secret`. */
51
+ export function signPayload(purpose: string, payload: string, secret?: string): string {
52
+ return `${hmac(deriveKey(purpose, secret), payload).toString('base64url')}.${payload}`
54
53
  }
55
54
 
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 {
55
+ /** The payload of a `signPayload` value made for `purpose` (and `secret`), or undefined when it is not one or its signature does not match. */
56
+ export function verifyPayload(purpose: string, signed: string, secret?: string): string | undefined {
58
57
  const dot = signed.indexOf('.')
59
58
  if (dot <= 0)
60
59
  return undefined
61
60
  const payload = signed.slice(dot + 1)
62
- return safeEqual(signed.slice(0, dot), hmac(deriveKey(purpose), payload).toString('base64url')) ? payload : undefined
61
+ return safeEqual(signed.slice(0, dot), hmac(deriveKey(purpose, secret), payload).toString('base64url')) ? payload : undefined
63
62
  }
@@ -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 })
@@ -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'
@@ -31,7 +31,7 @@ import { isNotFound, makeRequestContext, runChain } from './http'
31
31
  import { allowedMethodsHeader, hasPublicFavicon, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
32
32
  import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
33
33
  import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
34
- import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, routeCacheKey, serveCachedHit, trackPrivateReads, withCacheControl } from './route-cache'
34
+ import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, parseCacheDuration, routeCacheKey, serveCachedHit, trackPrivateReads, withCacheControl } from './route-cache'
35
35
  import { Router } from './router'
36
36
  import { createFastStaticPageHandler, methodNotAllowed } from './routing'
37
37
  import { styleHashesOf } from './security'
@@ -60,13 +60,20 @@ export interface CompiledRoute {
60
60
  /** Options every document of this route shares; a request adds its body, head and islands. */
61
61
  doc: DocumentOptions
62
62
  headStyleHashes: string[]
63
+ /** The route's `export const idleTimeout` in whole seconds, as `server.timeout()` takes it. */
64
+ idleTimeout: number | undefined
63
65
  }
64
66
 
65
- function routeDocument(manifest: BuildManifest, entry: RouteManifestEntry, lang: string, alwaysLoadRuntime: boolean, navigation: DocumentOptions['navigation'], hasFavicon: boolean): DocumentOptions {
67
+ function routeIdleTimeout(value: unknown): number | undefined {
68
+ const ms = value === undefined ? undefined : parseCacheDuration(value, true)
69
+ return ms === undefined ? undefined : Math.ceil(ms / 1000)
70
+ }
71
+
72
+ function routeDocument(manifest: BuildManifest, entry: RouteManifestEntry, mod: LoadedPageModule, lang: string, alwaysLoadRuntime: boolean, navigation: DocumentOptions['navigation'], hasFavicon: boolean): DocumentOptions {
66
73
  return {
67
74
  body: '',
68
75
  headTags: mergedHeadTags(manifest, entry),
69
- lang,
76
+ lang: typeof mod.lang === 'string' ? mod.lang : lang,
70
77
  runtimeScript: manifest.runtimeScript,
71
78
  chunkImports: manifest.chunkImports,
72
79
  alwaysLoadRuntime,
@@ -104,18 +111,19 @@ export function compileRouteTable(options: RouteTableOptions): { router: Router<
104
111
  const dirMiddlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
105
112
  const hasLoad = Boolean(entry.hasLoad && typeof mod.load === 'function')
106
113
  const dynamic = entry.path.includes(':') || entry.path.includes('*')
107
- const doc = routeDocument(manifest, entry, lang, alwaysLoadRuntime, navigation, hasFavicon)
114
+ const doc = routeDocument(manifest, entry, mod, lang, alwaysLoadRuntime, navigation, hasFavicon)
115
+ const idleTimeout = routeIdleTimeout(mod.idleTimeout)
108
116
 
109
117
  // Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, no route cache, and no intercepting plugin hook
110
118
  const canFastPath = middlewaresFor(entry.path, hasLoad ? 'dynamic' : 'static').length === 0
111
119
  && !pluginIntercepts(entry.path) && !dynamic
112
120
  && dirMiddlewares.length === 0 && !entry.usesRenderContext && entry.cache === undefined
113
- && typeof mod.default === 'function' && mod.GET === undefined
121
+ && typeof mod.default === 'function' && mod.GET === undefined && idleTimeout === undefined
114
122
  if (canFastPath)
115
123
  fastStaticPages.set(entry.path, createFastStaticPageHandler({ ...fast, entry, mod, layouts, doc, reviveScript: manifest.reviveScript, hasIslands: entry.islandChunks.length > 0, hasLoad }))
116
124
 
117
125
  const routeEntry = entry.cache !== undefined && dirMiddlewares.length > 0 ? { ...entry, cache: { ...entry.cache, cacheControl: GATED_ROUTE_CACHE_CONTROL } } : entry
118
- router.add(entry.path, { entry: routeEntry, mod, layouts, dirMiddlewares, middlewares: [...middlewaresFor(entry.path), ...dirMiddlewares], dynamic, doc, headStyleHashes: headTagStyleHashes(doc.headTags) })
126
+ router.add(entry.path, { entry: routeEntry, mod, layouts, dirMiddlewares, middlewares: [...middlewaresFor(entry.path), ...dirMiddlewares], dynamic, doc, headStyleHashes: headTagStyleHashes(doc.headTags), idleTimeout })
119
127
  }
120
128
  return { router, fastStaticPages }
121
129
  }
@@ -182,7 +190,7 @@ async function renderPageDocument(
182
190
  pageProps: Record<string, unknown>,
183
191
  ctx: RequestContext,
184
192
  hasFlash: boolean,
185
- disableTimeout?: () => void,
193
+ setIdleTimeout?: (seconds: number) => void,
186
194
  timing?: DevTiming,
187
195
  privateTracker?: PrivateReadTracker,
188
196
  ): Promise<RenderedPageOutput> {
@@ -192,7 +200,10 @@ async function renderPageDocument(
192
200
  const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, privateTracker?.ctx ?? ctx))
193
201
  if (hasFlash)
194
202
  ctx.cookies.delete(ACTION_ERROR_COOKIE)
195
- const docHead = await deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
203
+ // A route's `export const lang` names the language it is written in, so a plugin head hook such as i18n's cannot replace it.
204
+ const pageLang = typeof route.mod.lang === 'string' ? route.mod.lang : undefined
205
+ const resolvedHead = await deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
206
+ const docHead = pageLang === undefined ? resolvedHead : { ...resolvedHead, lang: pageLang, htmlAttrs: { ...resolvedHead.htmlAttrs, lang: pageLang } }
196
207
  rctx.headFlushed = true
197
208
  const renderedIslands = resolveRenderedIslands(rctx, body)
198
209
  const isStreamed = rctx.pending.length > 0
@@ -212,7 +223,7 @@ async function renderPageDocument(
212
223
  headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
213
224
  return { kind: 'stream', response: markCompressionHandled(new Response(null, { status: 200, headers })) }
214
225
  }
215
- disableTimeout?.()
226
+ setIdleTimeout?.(0)
216
227
  const docShell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
217
228
  const shell = deps.hasHtmlTransformers ? await deps.applyHtmlTransforms(docShell, ctx.url, ctx.request, ctx) : docShell
218
229
  const streamStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docShell, shell))
@@ -350,12 +361,14 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
350
361
  route: CompiledRoute,
351
362
  ctx: RequestContext,
352
363
  cookieStore: CookieStore,
353
- disableTimeout?: () => void,
364
+ setIdleTimeout?: (seconds: number) => void,
354
365
  staticPath?: string,
355
366
  timing?: DevTiming,
356
367
  middlewares: readonly Middleware[] = route.middlewares,
357
368
  ): Promise<Response> {
358
369
  const { entry, mod, doc } = route
370
+ if (route.idleTimeout !== undefined)
371
+ setIdleTimeout?.(route.idleTimeout)
359
372
  const isRegion = hasRegionHeader(ctx.request)
360
373
 
361
374
  const early = await resolvePrerenderedOrApi(deps, route, ctx, isRegion, staticPath)
@@ -412,7 +425,7 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
412
425
  )
413
426
  }
414
427
 
415
- const rendered = await renderPageDocument(deps, route, loaded.data, pageProps, ctx, hasFlash, disableTimeout, timing, privateTracker)
428
+ const rendered = await renderPageDocument(deps, route, loaded.data, pageProps, ctx, hasFlash, setIdleTimeout, timing, privateTracker)
416
429
  if (rendered.kind === 'stream')
417
430
  return rendered.response
418
431
  if (privateTracker?.didReadPrivate())
@@ -324,10 +324,33 @@ export interface SecurityHeadersOptions {
324
324
 
325
325
  const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
326
326
 
327
- /** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
328
- export type TrustProxy = boolean | number
327
+ /** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. The server hands plugins a `ProxyTrust` once `site` is known. */
328
+ export type TrustProxy = boolean | number | ProxyTrust
329
329
 
330
- function proxyHops(trustProxy: TrustProxy): number {
330
+ /** `trustProxy` as the server resolves it with `site`: the trusted hops, and the only hosts an `X-Forwarded-Host` may name, since a proxy that sets `Host` alone passes the client's one through. */
331
+ export interface ProxyTrust {
332
+ readonly hops: number
333
+ readonly hosts: ReadonlySet<string>
334
+ }
335
+
336
+ /** `trustProxy` bound to the hosts of `site` and `trustedOrigins`; unchanged with no proxy or no `site`, as then any forwarded host is the proxy's word. */
337
+ export function resolveTrustProxy(trustProxy: TrustProxy, site: string | undefined, trustedOrigins: Iterable<string> = []): TrustProxy {
338
+ const hops = proxyHops(trustProxy)
339
+ const siteHost = site === undefined ? undefined : URL.parse(site)?.host
340
+ if (hops === 0 || !siteHost)
341
+ return trustProxy
342
+ const hosts = new Set([siteHost])
343
+ for (const origin of trustedOrigins) {
344
+ const host = URL.parse(origin)?.host
345
+ if (host)
346
+ hosts.add(host)
347
+ }
348
+ return { hops, hosts }
349
+ }
350
+
351
+ export function proxyHops(trustProxy: TrustProxy): number {
352
+ if (typeof trustProxy === 'object')
353
+ return trustProxy.hops
331
354
  if (trustProxy === true)
332
355
  return 1
333
356
  if (trustProxy === false || !Number.isFinite(trustProxy))
@@ -370,16 +393,17 @@ function forwardedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?:
370
393
  const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase()
371
394
  if (proto !== 'http' && proto !== 'https')
372
395
  return undefined
373
- const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim() || (requestUrl ?? new URL(request.url)).host
396
+ const forwarded = originOf(proto, forwardedValue(request, 'x-forwarded-host', trustProxy))
397
+ if (forwarded !== undefined && (typeof trustProxy !== 'object' || trustProxy.hosts.has(new URL(forwarded).host)))
398
+ return forwarded
399
+ return originOf(proto, request.headers.get('host')?.trim() || (requestUrl ?? new URL(request.url)).host)
400
+ }
401
+
402
+ function originOf(proto: string, host: string | undefined): string | undefined {
374
403
  if (!host)
375
404
  return undefined
376
- try {
377
- const origin = new URL(`${proto}://${host}`).origin
378
- return origin === 'null' ? undefined : origin
379
- }
380
- catch {
381
- return undefined
382
- }
405
+ const origin = URL.parse(`${proto}://${host}`)?.origin
406
+ return origin === undefined || origin === 'null' ? undefined : origin
383
407
  }
384
408
 
385
409
  /** Returns true when the request arrived over HTTPS (directly, or via X-Forwarded-Proto when `trustProxy` is true). */
@@ -508,8 +532,15 @@ export function verifyOrigin(
508
532
  const fetchSite = request.headers.get('sec-fetch-site')
509
533
  if (fetchSite !== null && fetchSite !== 'same-origin' && fetchSite !== 'none')
510
534
  return { ok: false, reason: `Cross-site request blocked: sec-fetch-site=${fetchSite}` }
535
+ if (fetchSite !== null || !request.headers.has('cookie'))
536
+ return { ok: true }
511
537
 
512
- return { ok: true }
538
+ // A browser too old to send Origin or Sec-Fetch-Site still sends the session cookie: only a same-site Referer vouches for it.
539
+ const referer = request.headers.get('referer')
540
+ const refererOrigin = referer === null ? undefined : URL.parse(referer)?.origin
541
+ if (refererOrigin !== undefined && isTrustedOrigin(refererOrigin, request, trustedOrigins, trustProxy, requestUrl))
542
+ return { ok: true }
543
+ return { ok: false, reason: referer === null ? 'Cross-site request blocked: a cookie came with no Origin, Sec-Fetch-Site or Referer' : `Cross-site request blocked: untrusted referer ${refererOrigin ?? referer}` }
513
544
  }
514
545
 
515
546
  /** The notice a production server prints when it listens on loopback only, which a container's published port or another machine cannot reach; undefined otherwise. */
@@ -20,8 +20,8 @@ export interface ServeHandlerSources {
20
20
  healthPath?: string | undefined
21
21
  healthHandler?: ((request: Request, requestId?: string) => Response | Promise<Response>) | undefined
22
22
  resolveRequestId?: RequestIdResolver | undefined
23
- /** Answers through the app's whole pipeline, with the request's timeout turned off by `disableTimeout` for a long-lived stream. */
24
- runRequest: (req: Request, remoteIp: string | undefined, disableTimeout: () => void) => Promise<Response>
23
+ /** Answers through the app's whole pipeline, `setIdleTimeout` setting the request's idle timeout in seconds: 0 for a long-lived stream, or a route's `export const idleTimeout`. */
24
+ runRequest: (req: Request, remoteIp: string | undefined, setIdleTimeout: (seconds: number) => void) => Promise<Response>
25
25
  runFast: (handler: FastHandler, req: Request, remoteIp: string | undefined) => Response | Promise<Response>
26
26
  notifyError: NotifyError
27
27
  serverError: () => Response
@@ -38,7 +38,7 @@ export const isPlainRead = (request: Request): boolean => isRead(request) && !ha
38
38
  export function serveHandlers(server: () => PrunelleServer | undefined, sources: ServeHandlerSources) {
39
39
  const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone } = sources
40
40
  const ipOf = (req: Request) => server()?.requestIP(req)?.address
41
- const fetchReq = (req: Request) => runRequest(req, ipOf(req), () => server()?.timeout(req, 0))
41
+ const fetchReq = (req: Request) => runRequest(req, ipOf(req), seconds => server()?.timeout(req, seconds))
42
42
  // A file that fails to open answers here, where the request is known: gone since the build is a 404, anything else is reported with it.
43
43
  const serveFile = async (req: Request, file: ServedFile): Promise<Response> => {
44
44
  const reqId = resolveRequestId?.(req)
@@ -30,7 +30,7 @@ export async function startServer(options: StartOptions): Promise<{ app: Prunell
30
30
  let current = first.app
31
31
  const server = current.serve(options.port, options.hostname)
32
32
  const app: PrunelleApp = {
33
- handle: async (request, remoteIp, disableTimeout) => current.handle(request, remoteIp, disableTimeout),
33
+ handle: async (request, remoteIp, setIdleTimeout) => current.handle(request, remoteIp, setIdleTimeout),
34
34
  serve: () => server,
35
35
  closeStreams: async () => current.closeStreams?.(),
36
36
  dispose: async () => {
@@ -73,7 +73,7 @@ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleAp
73
73
  catch {
74
74
  return new Response('Service Unavailable', { status: 503, headers: { ...current().securityHeaders, 'content-type': 'text/plain; charset=utf-8' } })
75
75
  }
76
- return target.handle(request, server.requestIP(request)?.address, () => server.timeout(request, 0))
76
+ return target.handle(request, server.requestIP(request)?.address, seconds => server.timeout(request, seconds))
77
77
  },
78
78
  })
79
79
  }
@@ -150,8 +150,8 @@ function safeClose(controller: ReadableStreamDefaultController<Uint8Array>): boo
150
150
  }
151
151
  }
152
152
 
153
- function trackEventStream(res: Response, active: Set<() => void>, disableTimeout?: () => void): Response {
154
- disableTimeout?.()
153
+ function trackEventStream(res: Response, active: Set<() => void>, setIdleTimeout?: (seconds: number) => void): Response {
154
+ setIdleTimeout?.(0)
155
155
  if (res.body === null)
156
156
  return res
157
157
  const reader = res.body.getReader()
@@ -206,7 +206,7 @@ function trackEventStream(res: Response, active: Set<() => void>, disableTimeout
206
206
  }
207
207
 
208
208
  export interface StreamTracker {
209
- track: (res: Response, disableTimeout?: () => void) => Response
209
+ track: (res: Response, setIdleTimeout?: (seconds: number) => void) => Response
210
210
  /** Registers a streamed page's way to end early; the returned function drops it once the page is done. */
211
211
  trackPage: (end: () => void) => () => void
212
212
  closeAll: () => Promise<void>
@@ -217,7 +217,7 @@ export function createStreamTracker(): StreamTracker {
217
217
  const active = new Set<() => void>()
218
218
  const pages = new Set<() => void>()
219
219
  return {
220
- track: (res, disableTimeout) => trackEventStream(res, active, disableTimeout),
220
+ track: (res, setIdleTimeout) => trackEventStream(res, active, setIdleTimeout),
221
221
  trackPage: (end) => {
222
222
  pages.add(end)
223
223
  return () => { pages.delete(end) }