prunelle 0.9.0 → 0.10.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 (96) hide show
  1. package/llms.txt +18 -18
  2. package/package.json +2 -2
  3. package/src/a11y/declaration.ts +4 -7
  4. package/src/build/bundle.ts +6 -2
  5. package/src/build/index.ts +3 -1
  6. package/src/build/island-promote.ts +42 -2
  7. package/src/build/islands.ts +59 -8
  8. package/src/build/manifest.ts +98 -0
  9. package/src/build/plugin-host.ts +11 -1
  10. package/src/build/prerender.ts +6 -1
  11. package/src/build/reach.ts +4 -3
  12. package/src/build/resolve.ts +5 -1
  13. package/src/build/routes.ts +18 -0
  14. package/src/cli/check-forms.ts +8 -0
  15. package/src/cli/check-links.ts +14 -5
  16. package/src/cli/check.ts +12 -6
  17. package/src/cli/commands.ts +5 -3
  18. package/src/cli/form-opaque-children.ts +40 -0
  19. package/src/compiler/analyze.ts +20 -14
  20. package/src/compiler/cacheability-private.ts +13 -3
  21. package/src/compiler/compliance-contrast.ts +48 -10
  22. package/src/compiler/compliance-rules.ts +72 -0
  23. package/src/compiler/compliance.ts +6 -66
  24. package/src/compiler/dom-attrs.ts +178 -22
  25. package/src/compiler/dom.ts +31 -44
  26. package/src/compiler/emit.ts +17 -6
  27. package/src/compiler/expr-context.ts +260 -207
  28. package/src/compiler/props-body.ts +263 -21
  29. package/src/compiler/props.ts +155 -5
  30. package/src/compiler/signal-reads.ts +142 -29
  31. package/src/compiler/spread-handlers.ts +25 -13
  32. package/src/compiler/ssr-emit.ts +3 -3
  33. package/src/compiler/ssr-helpers.ts +0 -5
  34. package/src/compiler/ssr.ts +4 -2
  35. package/src/dev/host-check.ts +2 -1
  36. package/src/dev/reload.ts +4 -1
  37. package/src/dom/attrs.ts +93 -25
  38. package/src/dom/extras.ts +89 -49
  39. package/src/dom/field-marks.ts +9 -1
  40. package/src/dom/index.ts +19 -13
  41. package/src/dom/loop.ts +259 -188
  42. package/src/dom/prefetch.ts +4 -1
  43. package/src/dom/regions.ts +25 -8
  44. package/src/dom/swap.ts +11 -10
  45. package/src/dom/trusted.ts +4 -4
  46. package/src/eco/declaration.ts +5 -1
  47. package/src/eco/index.ts +3 -0
  48. package/src/index.ts +3 -2
  49. package/src/plugins/config.ts +1 -1
  50. package/src/plugins/public.ts +4 -0
  51. package/src/plugins/types.ts +8 -1
  52. package/src/reactivity/graph.ts +244 -41
  53. package/src/reactivity/hmr.ts +14 -3
  54. package/src/reactivity/index.ts +219 -235
  55. package/src/reactivity/resource.ts +17 -3
  56. package/src/reactivity/seed.ts +118 -16
  57. package/src/reactivity/selector.ts +85 -47
  58. package/src/reactivity/server-seed.ts +31 -23
  59. package/src/reactivity/store.ts +316 -136
  60. package/src/server/action-protect.ts +3 -0
  61. package/src/server/action-registry.ts +5 -1
  62. package/src/server/cache-invalidation.ts +4 -3
  63. package/src/server/compress.ts +52 -17
  64. package/src/server/consent.ts +5 -3
  65. package/src/server/cookies.ts +27 -8
  66. package/src/server/cors.ts +98 -0
  67. package/src/server/csp-report.ts +8 -4
  68. package/src/server/health.ts +9 -0
  69. package/src/server/http.ts +3 -1
  70. package/src/server/index.ts +25 -13
  71. package/src/server/loader.ts +1 -0
  72. package/src/server/plugin-host.ts +41 -9
  73. package/src/server/plugin-route-shadow.ts +24 -0
  74. package/src/server/rate-limit.ts +13 -3
  75. package/src/server/region.ts +19 -2
  76. package/src/server/request-handler.ts +58 -22
  77. package/src/server/request-log.ts +1 -1
  78. package/src/server/route-cache.ts +14 -2
  79. package/src/server/route-table.ts +21 -11
  80. package/src/server/router.ts +2 -1
  81. package/src/server/routing.ts +100 -42
  82. package/src/server/sanitize-html.ts +3 -1
  83. package/src/server/serve-handlers.ts +10 -4
  84. package/src/server/served-file.ts +19 -14
  85. package/src/server/shared-store.ts +10 -1
  86. package/src/server/static-dir.ts +21 -3
  87. package/src/server/webhook.ts +6 -4
  88. package/src/ssr/context.ts +149 -51
  89. package/src/ssr/index.ts +41 -46
  90. package/src/ssr/region.ts +9 -3
  91. package/src/style.ts +12 -5
  92. package/src/test/browser.ts +3 -1
  93. package/src/test/build-reuse.ts +22 -7
  94. package/src/test/index.ts +7 -3
  95. package/src/ts-plugin/diagnostics.ts +56 -18
  96. package/ts-plugin.cjs +465 -131
@@ -358,7 +358,7 @@ function tryAppendVaryAcceptEncoding(res: Response): Response {
358
358
  }
359
359
  }
360
360
 
361
- function withVaryAcceptEncoding(baseHeaders: Record<string, string>): Record<string, string> {
361
+ export function withVaryAcceptEncoding(baseHeaders: Record<string, string>): Record<string, string> {
362
362
  const headers: Record<string, string> = { ...baseHeaders }
363
363
  let existing: string | undefined
364
364
  for (const key of Object.keys(headers)) {
@@ -372,6 +372,46 @@ function withVaryAcceptEncoding(baseHeaders: Record<string, string>): Record<str
372
372
  return headers
373
373
  }
374
374
 
375
+ export interface CompressedHtmlOptions {
376
+ /** `baseHeaders` already includes `vary: Accept-Encoding` and does not set `Cache-Control: no-transform`. */
377
+ varyPremerged?: boolean | undefined
378
+ /** Skip `WeakSet` tracking on paths where `maybeCompressResponse` never runs on the returned response. */
379
+ skipMarkHandled?: boolean | undefined
380
+ requestId?: string | undefined
381
+ serverTiming?: string | undefined
382
+ }
383
+
384
+ function finalizeHtmlHeaders(
385
+ baseHeaders: Record<string, string>,
386
+ addVary: boolean,
387
+ enc: CompressionEncoding | undefined,
388
+ opts: CompressedHtmlOptions | undefined,
389
+ ): Record<string, string> {
390
+ const reqId = opts?.requestId
391
+ const timing = opts?.serverTiming || undefined
392
+ if (!addVary && enc === undefined) {
393
+ if (reqId === undefined && timing === undefined)
394
+ return baseHeaders
395
+ return timing === undefined
396
+ ? { ...baseHeaders, 'x-request-id': reqId! }
397
+ : reqId === undefined ? { ...baseHeaders, 'server-timing': timing } : { ...baseHeaders, 'x-request-id': reqId, 'server-timing': timing }
398
+ }
399
+ const headers = addVary ? withVaryAcceptEncoding(baseHeaders) : { ...baseHeaders }
400
+ if (enc !== undefined) {
401
+ headers['content-encoding'] = enc
402
+ const etag = headers.etag ?? headers.ETag
403
+ if (etag !== undefined) {
404
+ delete headers.ETag
405
+ headers.etag = toWeakEtag(etag)
406
+ }
407
+ }
408
+ if (reqId !== undefined)
409
+ headers['x-request-id'] = reqId
410
+ if (timing !== undefined)
411
+ headers['server-timing'] = timing
412
+ return headers
413
+ }
414
+
375
415
  /** `reuse` keeps the compressed page by content hash, for routes whose HTML holds nothing per visitor. */
376
416
  export function compressedHtmlResponse(
377
417
  html: string,
@@ -380,31 +420,26 @@ export function compressedHtmlResponse(
380
420
  request: Request,
381
421
  cache: CompressionCache | undefined,
382
422
  reuse = false,
423
+ opts?: CompressedHtmlOptions,
383
424
  ): Response {
384
- const noTransform = hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
425
+ const varyPremerged = opts?.varyPremerged === true
426
+ const noTransform = !varyPremerged && hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
427
+ const addVary = cache !== undefined && !noTransform && !varyPremerged
428
+ const finishRes = (res: Response): Response => (opts?.skipMarkHandled === true ? res : markCompressionHandled(res))
429
+
385
430
  if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
386
431
  const enc = pickEncoding(request.headers.get('accept-encoding'))
387
432
  if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
388
433
  // 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.
389
434
  const staticKey = reuse ? `s:${new Bun.CryptoHasher('sha256').update(html).digest('base64url')}` : undefined
390
- let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
391
- if (compressed === undefined)
392
- compressed = cache.compress(html, enc, staticKey)
393
- if (compressed !== undefined) {
394
- const headers = withVaryAcceptEncoding(baseHeaders)
395
- headers['content-encoding'] = enc
396
- const etag = headers.etag ?? headers.ETag
397
- if (etag !== undefined) {
398
- delete headers.ETag
399
- headers.etag = toWeakEtag(etag)
400
- }
401
- return markCompressionHandled(new Response(compressed, { status, headers }))
402
- }
435
+ const compressed = (staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined) ?? cache.compress(html, enc, staticKey)
436
+ if (compressed !== undefined)
437
+ return finishRes(new Response(compressed, { status, headers: finalizeHtmlHeaders(baseHeaders, addVary, enc, opts) }))
403
438
  }
404
439
  }
405
- return markCompressionHandled(new Response(request.method === 'HEAD' ? null : html, {
440
+ return finishRes(new Response(request.method === 'HEAD' ? null : html, {
406
441
  status,
407
- headers: cache !== undefined && !noTransform ? withVaryAcceptEncoding(baseHeaders) : baseHeaders,
442
+ headers: finalizeHtmlHeaders(baseHeaders, addVary, undefined, opts),
408
443
  }))
409
444
  }
410
445
 
@@ -115,8 +115,8 @@ function grantedOf(list: string, declared: ReadonlySet<string>): Set<string> {
115
115
  return granted
116
116
  }
117
117
 
118
- /** Reads `v2:<seconds>:<policy version>:<categories>`; a choice made under another policy version counts as no choice. */
119
- export function parseConsentCookie(raw: string | undefined, declared: ReadonlySet<string>, version = ''): ParsedConsent {
118
+ /** Reads `v2:<seconds>:<policy version>:<categories>`; a choice made under another policy version, or more than `maxAge` seconds ago, counts as no choice. */
119
+ export function parseConsentCookie(raw: string | undefined, declared: ReadonlySet<string>, version = '', maxAge?: number, now = Date.now()): ParsedConsent {
120
120
  const none: ParsedConsent = { decided: false, decidedAt: undefined, granted: new Set() }
121
121
  if (raw === undefined)
122
122
  return none
@@ -131,6 +131,8 @@ export function parseConsentCookie(raw: string | undefined, declared: ReadonlySe
131
131
  const at = Number(seconds)
132
132
  if (list === undefined || storedVersion !== version || !Number.isSafeInteger(at) || at <= 0)
133
133
  return none
134
+ if (maxAge !== undefined && (at + maxAge) * 1000 < now)
135
+ return none
134
136
  return { decided: true, decidedAt: new Date(at * 1000), granted: grantedOf(list, declared) }
135
137
  }
136
138
 
@@ -146,7 +148,7 @@ export function createRequestConsent(
146
148
  ): RequestConsent {
147
149
  if (config === undefined)
148
150
  return EMPTY_CONSENT
149
- const { decided, decidedAt, granted } = parseConsentCookie(rawCookie, config.categorySet, config.version)
151
+ const { decided, decidedAt, granted } = parseConsentCookie(rawCookie, config.categorySet, config.version, config.maxAge)
150
152
  return {
151
153
  decided,
152
154
  decidedAt,
@@ -28,6 +28,14 @@ function warnUncategorized(name: string): void {
28
28
  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.`)
29
29
  }
30
30
 
31
+ // A category consent does not declare is never granted, so its cookie would vanish without a trace: same once-per-name dev warning.
32
+ function warnUndeclaredCategory(name: string, category: string): void {
33
+ if (warnedUncategorized.has(name) || getAppContext()?.dev !== true)
34
+ return
35
+ warnedUncategorized.add(name)
36
+ console.warn(`prunelle: cookie "${name}" was not set: its category "${category}" is not declared in consent.categories of prunelle.config.ts, so no visitor can ever grant it: fix the category name, or declare it there.`)
37
+ }
38
+
31
39
  // The cookies this server instance set under each consent category, kept on AppRuntimeContext so servers stay isolated,
32
40
  // paired with COOKIE_INVENTORY so consent withdrawal also expires declared cookies across restarts and worker processes.
33
41
  const MAX_REMEMBERED_PER_CATEGORY = 200
@@ -136,10 +144,14 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
136
144
  if (options.maxAge !== undefined) {
137
145
  if (!Number.isFinite(options.maxAge))
138
146
  throw new TypeError(`prunelle: invalid cookie maxAge "${options.maxAge}"`)
139
- out += `; Max-Age=${Math.floor(options.maxAge)}`
147
+ // A fraction above zero rounds up: flooring 0.5 to 0 would delete the cookie it sets.
148
+ out += `; Max-Age=${options.maxAge > 0 ? Math.ceil(options.maxAge) : Math.floor(options.maxAge)}`
140
149
  }
141
- if (options.expires !== undefined)
150
+ if (options.expires !== undefined) {
151
+ if (Number.isNaN(options.expires.getTime()))
152
+ throw new TypeError('prunelle: invalid cookie expires: pass a valid Date.')
142
153
  out += `; Expires=${options.expires.toUTCString()}`
154
+ }
143
155
  if (options.httpOnly ?? true)
144
156
  out += '; HttpOnly'
145
157
  if (secure)
@@ -155,14 +167,16 @@ function cookieKey(name: string, options?: Pick<CookieOptions, 'path' | 'domain'
155
167
  export class CookieStore implements Cookies {
156
168
  #rawHeader: string | null
157
169
  #values: Map<string, string> | undefined
158
- readonly #headers = new Map<string, string>()
170
+ #headers: Map<string, string> | undefined
159
171
  readonly #isHttps: boolean
160
172
  readonly #isConsentGranted: ((category: string) => boolean) | undefined
173
+ readonly #isDeclared: ((category: string) => boolean) | undefined
161
174
 
162
- constructor(cookieHeader: string | null, isHttps = false, isConsentGranted?: (category: string) => boolean) {
175
+ constructor(cookieHeader: string | null, isHttps = false, isConsentGranted?: (category: string) => boolean, isDeclared?: (category: string) => boolean) {
163
176
  this.#rawHeader = cookieHeader
164
177
  this.#isHttps = isHttps
165
178
  this.#isConsentGranted = isConsentGranted
179
+ this.#isDeclared = isDeclared
166
180
  }
167
181
 
168
182
  #ensureValues(): Map<string, string> {
@@ -181,18 +195,21 @@ export class CookieStore implements Cookies {
181
195
  if (options?.category === undefined)
182
196
  warnUncategorized(name)
183
197
  else if (options.category !== 'essential') {
184
- if (this.#isConsentGranted === undefined || !this.#isConsentGranted(options.category))
198
+ if (this.#isConsentGranted === undefined || !this.#isConsentGranted(options.category)) {
199
+ if (this.#isDeclared?.(options.category) === false)
200
+ warnUndeclaredCategory(name, options.category)
185
201
  return
202
+ }
186
203
  rememberUnderCategory(options.category, name, options)
187
204
  }
188
205
  const serialized = serializeCookie(name, value, options, this.#isHttps)
189
206
  this.#ensureValues().set(name, value)
190
- this.#headers.set(cookieKey(name, options), serialized)
207
+ ;(this.#headers ??= new Map()).set(cookieKey(name, options), serialized)
191
208
  }
192
209
 
193
210
  delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void {
194
211
  this.#ensureValues().delete(name)
195
- this.#headers.set(cookieKey(name, options), serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
212
+ ;(this.#headers ??= new Map()).set(cookieKey(name, options), serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
196
213
  }
197
214
 
198
215
  all(): Record<string, string> {
@@ -200,10 +217,12 @@ export class CookieStore implements Cookies {
200
217
  }
201
218
 
202
219
  get hasChanges(): boolean {
203
- return this.#headers.size > 0
220
+ return this.#headers !== undefined && this.#headers.size > 0
204
221
  }
205
222
 
206
223
  applyTo(headers: Headers): void {
224
+ if (this.#headers === undefined)
225
+ return
207
226
  for (const serialized of this.#headers.values())
208
227
  headers.append('set-cookie', serialized)
209
228
  }
@@ -0,0 +1,98 @@
1
+ // The `cors` setting of `prunelle.config.ts`: the origins whose scripts may call this app, and the preflight their browser sends first (#430).
2
+
3
+ import { mergeVaryValue } from './compress'
4
+
5
+ export interface CorsConfig {
6
+ /** The origins allowed, each `scheme://host[:port]`; they also pass the CSRF origin check. `'*'` lets any origin read, and keeps the CSRF check on the other methods. */
7
+ origins: readonly string[] | '*'
8
+ /** Lets the browser send cookies and read the answer to a credentialed request (default false); not with `'*'`. */
9
+ credentials?: boolean | undefined
10
+ /** Response headers the calling script may read beyond the CORS-safelisted ones, e.g. `['x-request-id']`. */
11
+ exposeHeaders?: readonly string[] | undefined
12
+ }
13
+
14
+ /** Answers an allowed origin's preflight before `handler`, and adds the CORS headers to what `handler` answers. */
15
+ export type CorsWrap = <A extends unknown[]>(handler: (request: Request, ...args: A) => Response | Promise<Response>) => (request: Request, ...args: A) => Response | Promise<Response>
16
+
17
+ export interface Cors {
18
+ /** The listed origins, which pass the CSRF origin check; none for `'*'`. */
19
+ trusted: readonly string[]
20
+ /** The wrap of the app's handlers, `seal` adding to the preflight what the server adds to its other answers (security headers, HSTS). */
21
+ wrapWith: (seal: (res: Response, request: Request) => Response) => CorsWrap
22
+ }
23
+
24
+ const PREFLIGHT_METHODS = 'GET, HEAD, POST, PUT, PATCH, DELETE'
25
+ const READ_METHODS = 'GET, HEAD'
26
+ // Ten minutes: Chromium caps the preflight cache at two hours, Firefox at one day.
27
+ const PREFLIGHT_MAX_AGE = '600'
28
+
29
+ function assertOrigin(origin: string): void {
30
+ if (URL.parse(origin)?.origin !== origin)
31
+ throw new Error(`prunelle: cors.origins holds "${origin}", which is not an origin: write it as scheme://host[:port], with no path or trailing slash.`)
32
+ }
33
+
34
+ /** `handler` behind the `cors` setting, or `handler` itself without one. */
35
+ export function withCorsSetting(config: CorsConfig | undefined, seal: (res: Response, request: Request) => Response, handler: (request: Request) => Promise<Response>): (request: Request) => Promise<Response> {
36
+ const wrapped = createCors(config)?.wrapWith(seal)(handler)
37
+ return wrapped === undefined ? handler : async request => wrapped(request)
38
+ }
39
+
40
+ export function createCors(config: CorsConfig | undefined): Cors | undefined {
41
+ if (config === undefined)
42
+ return undefined
43
+ const { origins } = config
44
+ const anyOrigin = origins === '*'
45
+ if (!anyOrigin && !Array.isArray(origins))
46
+ throw new Error(`prunelle: cors.origins is ${JSON.stringify(origins)}, which is not a list: write origins: ['https://front.example'], or '*' to let any origin read.`)
47
+ if (anyOrigin && config.credentials === true)
48
+ throw new Error('prunelle: cors.credentials cannot go with origins: \'*\', as browsers refuse that pair: list the origins that may send credentials.')
49
+ const trusted = anyOrigin ? [] : [...origins]
50
+ for (const origin of trusted)
51
+ assertOrigin(origin)
52
+ const allowed = new Set(trusted)
53
+ const exposed = config.exposeHeaders?.join(', ')
54
+
55
+ const allowFor = (origin: string | null): string | undefined => {
56
+ if (anyOrigin)
57
+ return '*'
58
+ return origin !== null && allowed.has(origin) ? origin : undefined
59
+ }
60
+ // Every answer to a listed origin depends on the Origin header, so every answer says so, or a cache would hand one origin's answer to another.
61
+ const decorate = (headers: Headers, allow: string | undefined): void => {
62
+ if (!anyOrigin)
63
+ headers.set('vary', mergeVaryValue(headers.get('vary'), 'Origin'))
64
+ if (allow === undefined)
65
+ return
66
+ headers.set('access-control-allow-origin', allow)
67
+ if (config.credentials === true)
68
+ headers.set('access-control-allow-credentials', 'true')
69
+ }
70
+ const preflight = (request: Request, allow: string): Response => {
71
+ const headers = new Headers({ 'access-control-allow-methods': anyOrigin ? READ_METHODS : PREFLIGHT_METHODS, 'access-control-max-age': PREFLIGHT_MAX_AGE })
72
+ const requested = request.headers.get('access-control-request-headers')
73
+ if (requested !== null)
74
+ headers.set('access-control-allow-headers', requested)
75
+ decorate(headers, allow)
76
+ return new Response(null, { status: 204, headers })
77
+ }
78
+ // A copy, as a response may come with immutable headers (a fetched or a shared one).
79
+ const withHeaders = (res: Response, allow: string | undefined): Response => {
80
+ const out = new Response(res.body, res)
81
+ decorate(out.headers, allow)
82
+ if (allow !== undefined && exposed !== undefined)
83
+ out.headers.set('access-control-expose-headers', exposed)
84
+ return out
85
+ }
86
+ const answer = async (pending: Promise<Response>, allow: string | undefined): Promise<Response> => withHeaders(await pending, allow)
87
+
88
+ return {
89
+ trusted,
90
+ wrapWith: seal => handler => (request, ...args) => {
91
+ const allow = allowFor(request.headers.get('origin'))
92
+ if (allow !== undefined && request.method === 'OPTIONS' && request.headers.has('access-control-request-method'))
93
+ return seal(preflight(request, allow), request)
94
+ const res = handler(request, ...args)
95
+ return res instanceof Response ? withHeaders(res, allow) : answer(res, allow)
96
+ },
97
+ }
98
+ }
@@ -25,9 +25,9 @@ const EXTENSION_URL_RE = /^(?:chrome|moz|safari(?:-web)?|ms-browser)-extension:/
25
25
 
26
26
  const MAX_LOGGED_CHARS = 200
27
27
 
28
- /** A report field fit for a log line: control characters become spaces, so a newline cannot forge a line, and a long value is cut. */
28
+ /** A report field fit for a log line: control characters and the Unicode line separators (U+0085, U+2028, U+2029) become spaces, so a newline cannot forge a line, and a long value is cut. */
29
29
  const loggable = (value: string): string => {
30
- const flat = value.replace(/[\x00-\x1F\x7F]/g, ' ')
30
+ const flat = value.replace(/[\x00-\x1F\x7F\x85\u2028\u2029]/g, ' ')
31
31
  return flat.length > MAX_LOGGED_CHARS ? `${flat.slice(0, MAX_LOGGED_CHARS)}...` : flat
32
32
  }
33
33
 
@@ -78,8 +78,12 @@ export function registerCspReportRoute(register: Register, notifyError: NotifyEr
78
78
  if (violations === undefined)
79
79
  return new Response(null, { status: 400 })
80
80
  for (const v of violations) {
81
- if (!fromExtension(v))
82
- notifyError(new Error(`CSP violation: ${v.directive} blocked ${loggable(v.blockedUrl)} on ${loggable(v.page)}`, { cause: v }), ctx.request, 'csp', ctx.requestId)
81
+ if (fromExtension(v))
82
+ continue
83
+ const safe: CspViolation = { ...v, directive: loggable(v.directive), blockedUrl: loggable(v.blockedUrl), page: loggable(v.page) }
84
+ if (v.sourceFile !== undefined)
85
+ safe.sourceFile = loggable(v.sourceFile)
86
+ notifyError(new Error(`CSP violation: ${safe.directive} blocked ${safe.blockedUrl} on ${safe.page}`, { cause: safe }), ctx.request, 'csp', ctx.requestId)
83
87
  }
84
88
  return new Response(null, { status: 204 })
85
89
  }, { csrf: false, rateLimit: REPORT_RATE_LIMIT })
@@ -30,6 +30,8 @@ export interface PhaseTiming {
30
30
  starts?: Partial<Record<RequestPhaseName, number>> | undefined
31
31
  /** Measured for those hooks in production, never sent as `Server-Timing`. */
32
32
  headerless?: true | undefined
33
+ /** The route template that answered (`/blog/:slug`), told to those hooks. */
34
+ route?: string | undefined
33
35
  }
34
36
 
35
37
  export type RequestIdResolver = (request: Request) => string
@@ -116,6 +118,13 @@ export function observeTiming(request: Request, isDev: boolean): PhaseTiming {
116
118
  return timing
117
119
  }
118
120
 
121
+ /** Tells the access log and `onRequestEnd` hooks which route template answered `request`, when one listens. */
122
+ export function noteRoute(request: Request, route: string): void {
123
+ const timing = observedTimings.get(request)
124
+ if (timing !== undefined)
125
+ timing.route = route
126
+ }
127
+
119
128
  export const createTiming = (isDev: boolean, request: Request): PhaseTiming | undefined => observedTimings.get(request) ?? (isDev ? {} : undefined)
120
129
 
121
130
  export const startTimer = (timing: PhaseTiming | undefined): number => (timing !== undefined ? performance.now() : 0)
@@ -336,7 +336,8 @@ const makeRedirect = (request: Request, trustProxy: TrustProxy, url: URL): Reque
336
336
  if (!sameOrigin(location, baseOrigin))
337
337
  throw new Error(`prunelle: ctx.redirect("${location}") leaves ${baseOrigin}: 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).`)
338
338
  }
339
- const res = new Response(null, { status, headers: { location } })
339
+ // A header holds Latin-1 at most, so a Unicode slug is sent percent-encoded.
340
+ const res = new Response(null, { status, headers: { location: location.toWellFormed().replace(/[^\x00-\x7F]+/g, chunk => encodeURI(chunk)) } })
340
341
  if (external)
341
342
  EXTERNAL_REDIRECTS.add(res)
342
343
  return res
@@ -377,6 +378,7 @@ export function makeRequestContext(
377
378
  request.headers.get('cookie'),
378
379
  opts?.httpsSite === true || isHttpsRequest(request, trustProxy),
379
380
  category => getConsent().has(category),
381
+ category => consentConfig?.categorySet.has(category) === true,
380
382
  )
381
383
  const locals: PrunelleLocals = {}
382
384
  const resolveLocale = (): string | undefined => {
@@ -32,6 +32,7 @@ import { createActionRegistry } from './action-registry'
32
32
  import { createAssets } from './assets'
33
33
  import { CompressionCache } from './compress'
34
34
  import { normalizeConsentConfig } from './consent'
35
+ import { createCors } from './cors'
35
36
  import { createServerAppContext } from './cookie-inventory'
36
37
  import { devFromEnv, nodeEnv } from './env'
37
38
  import { createDocumentHooks, createHtmlHeaders } from './document'
@@ -240,13 +241,19 @@ function createSecurityResponders(
240
241
  const hstsValue = resolveHstsValue(security)
241
242
  // Every response passes here, so it is where a production server first sees it runs behind a proxy it does not trust.
242
243
  let proxyChecked = trustProxy !== false || isDev || resolvedNodeEnv !== 'production'
243
- const withHsts = (res: Response, request: Request): Response => {
244
- if (!proxyChecked && request.headers.has('x-forwarded-proto')) {
245
- proxyChecked = true
246
- console.warn('prunelle: a request came through a proxy (it carries x-forwarded-proto) but trustProxy is off, so ctx.ip and rate limits see the proxy\'s address and https is known from site alone: set trustProxy in prunelle.config.ts to the proxy the server runs behind.')
247
- }
248
- return applyHstsHeader(res, request, hstsValue, trustProxy, isDev, explicitNodeEnv, httpsSite)
249
- }
244
+ const hstsAlwaysOff = hstsValue === undefined || isDev
245
+ const noProxyHsts = !httpsSite && trustProxy === false
246
+ const withHsts = proxyChecked && hstsAlwaysOff
247
+ ? (res: Response): Response => res
248
+ : (res: Response, request: Request): Response => {
249
+ if (!proxyChecked && request.headers.has('x-forwarded-proto')) {
250
+ proxyChecked = true
251
+ console.warn('prunelle: a request came through a proxy (it carries x-forwarded-proto) but trustProxy is off, so ctx.ip and rate limits see the proxy\'s address and https is known from site alone: set trustProxy in prunelle.config.ts to the proxy the server runs behind.')
252
+ }
253
+ if (hstsAlwaysOff || (noProxyHsts && !request.url.startsWith('https:')))
254
+ return res
255
+ return applyHstsHeader(res, request, hstsValue, trustProxy, isDev, explicitNodeEnv, httpsSite)
256
+ }
250
257
  // The one way out of every response not built with the security headers already in place.
251
258
  const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
252
259
  withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
@@ -267,7 +274,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
267
274
  const assetPrefix = (config.assetPrefix ?? '/_pru').replace(/\/$/, '')
268
275
  const site = config.site?.replace(/\/$/, '') || undefined
269
276
  const trustedOriginsList = config.trustedOrigins ?? []
270
- const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
277
+ const cors = createCors(config.cors)
278
+ const csrfOrigins = [...trustedOriginsList, ...cors?.trusted ?? []]
279
+ const trustedOrigins = csrfOrigins.length > 0 ? new Set(csrfOrigins) : undefined
271
280
  const trustProxy = resolveTrustProxy(config.trustProxy ?? false, site, trustedOriginsList)
272
281
  const consent = normalizeConsentConfig(config.consent, lang)
273
282
  const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
@@ -305,7 +314,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
305
314
  const actions = createActionRegistry()
306
315
  const pluginHost = await startPlugins({
307
316
  plugins, config, manifest, appCtx: serverAppCtx, root: serverRoot, outDir: serverOutDir, assetPrefix, site, dev: isDev,
308
- devExposed: config.devHost !== undefined && !isLoopbackHost(config.devHost), trustProxy, trustedOriginsList, trustedOrigins, notifyError,
317
+ devExposed: config.devHost !== undefined && !isLoopbackHost(config.devHost), trustProxy, trustedOriginsList: csrfOrigins, trustedOrigins, notifyError,
309
318
  }, routeCache)
310
319
  const { router: pluginRouter, middlewaresFor, middlewaresForPaths } = pluginHost
311
320
  const healthPath = `${assetPrefix}/health`
@@ -337,7 +346,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
337
346
  renderNotFound = createNotFoundRenderer({ actions, pluginMiddlewaresFor, ancestorMiddlewaresFor, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderDenied, renderError, notifyError, finish })
338
347
  ;({ refuseCrossSite, checkBodyLimit } = createRequestGuards(maxRequestBodySize, finish))
339
348
  ;({ router, fastStaticPages } = compileRouteTable({
340
- manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, hasFavicon, middlewaresFor,
349
+ manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, hasFavicon, middlewaresFor, isGatedByPlugin: pluginHost.isGatedByPlugin,
341
350
  pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
342
351
  fast: { trustProxy, httpsSite, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
343
352
  }))
@@ -368,12 +377,15 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
368
377
  })
369
378
 
370
379
  const observe = createRequestObserver(config.log, pluginHost.requestHooks, isDev)
371
- const handleRequest = (request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, setIdleTimeout))
380
+ const handleInternalRequest = (request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, setIdleTimeout))
381
+ const corsWrap = cors?.wrapWith(finish)
382
+ const withCors = corsWrap?.(handleInternalRequest)
383
+ const handleRequest = withCors === undefined ? handleInternalRequest : async (request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void): Promise<Response> => withCors(request, remoteIp, setIdleTimeout)
372
384
  const handle = observe?.(handleRequest) ?? handleRequest
373
385
 
374
386
  const runRequest = (req: Request, remoteIp: string | undefined, setIdleTimeout: (seconds: number) => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, setIdleTimeout, true))
375
387
  const runFast = (handler: FastHandler, req: Request, remoteIp: string | undefined): Response | Promise<Response> => runWithAppContext(serverAppCtx, () => handler(req, remoteIp))
376
- const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone, observe })
388
+ const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone, observe, cors: corsWrap })
377
389
 
378
390
  return appFacade({ config, plugins, handle, handlers, maxRequestBodySize, pluginHost, actions, inject: serverAppCtx.inject, streams, securityRecord })
379
391
  }
@@ -404,7 +416,7 @@ function appFacade(deps: AppFacadeDeps): PrunelleApp {
404
416
  reloadInto: server => server.reload(handlers(() => server)),
405
417
  perProcessState: () => perProcessState({
406
418
  store: config.store,
407
- limiters: memoryLimiters(),
419
+ limiters: memoryLimiters() + pluginHost.rateLimits.limiters,
408
420
  actionsRateLimited: deps.actions.rateLimited(),
409
421
  cachedRoutes: config.manifest.routes.some(route => route.cache !== undefined),
410
422
  plugins,
@@ -127,6 +127,7 @@ async function serveStaticDir(options: ServerOptions, root: string, outDir: stri
127
127
  httpsSite: !isDev && site?.startsWith('https://') === true,
128
128
  nodeEnv: options.nodeEnv,
129
129
  log: options.log ?? config.log,
130
+ cors: options.cors ?? config.cors,
130
131
  },
131
132
  )
132
133
  }
@@ -14,10 +14,11 @@ import { enforceRequirements } from '../plugins/requires'
14
14
  import { normalizeConsentConfig, registerConsentRoute } from './consent'
15
15
  import { registerCspReportRoute } from './csp-report'
16
16
  import { appSurface } from './surface'
17
- import { assertRateLimit, createRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
17
+ import { assertRateLimit, createServerRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
18
18
  import { openSharedStore, SHARED_STORE } from './shared-store'
19
19
  import type { RequestPath } from './request-path'
20
20
  import type { RouteMatch } from './router'
21
+ import { shadowedPages, shadowMessage } from './plugin-route-shadow'
21
22
  import { Router } from './router'
22
23
 
23
24
  export interface PluginRouteDef {
@@ -28,11 +29,14 @@ export interface PluginRouteDef {
28
29
  trustProxy: TrustProxy
29
30
  /** The catch-all takes an encoded separator for this method (`PluginRouteOptions.encodedSlashes`). */
30
31
  encodedSlashes: boolean
32
+ /** The path as the plugin registered it (`/reset/:token`), told to `onRequestEnd` hooks as the route. */
33
+ path: string
31
34
  }
32
35
 
33
36
  interface ScopedMiddleware {
34
37
  mw: Middleware
35
38
  scope: 'all' | 'rendered' | 'dynamic' | string
39
+ exact?: boolean | undefined
36
40
  }
37
41
 
38
42
  /** What a request reaches, as middleware scopes see it: a page built ahead of time, a page with no `load` that renders the same for everyone, or anything else answered per request. */
@@ -57,7 +61,8 @@ export interface ServerPluginHostOptions {
57
61
  notifyError: NotifyError
58
62
  }
59
63
 
60
- function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, kind: RequestKind): boolean {
64
+ function middlewareAppliesToPath(entry: ScopedMiddleware, path: string, kind: RequestKind): boolean {
65
+ const { scope, exact } = entry
61
66
  if (scope === 'all')
62
67
  return true
63
68
  if (scope === 'rendered')
@@ -66,11 +71,30 @@ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string,
66
71
  return kind === 'dynamic'
67
72
  const normScope = scope.length > 1 && scope.endsWith('/') ? scope.slice(0, -1) : scope
68
73
  const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
74
+ if (exact === true)
75
+ return normPath === normScope
69
76
  if (normScope === '/')
70
77
  return normPath.startsWith('/')
71
78
  return normPath === normScope || normPath.startsWith(`${normScope}/`)
72
79
  }
73
80
 
81
+ /** Whether a path scope covers some URL of a route pattern: `/m/vip` covers `/m/:id` for `/m/vip`, and `/m` covers it whole. */
82
+ function scopeMayCover(scope: string, routePath: string, exact?: boolean): boolean {
83
+ const scopeSegs = scope.split('/').filter(Boolean)
84
+ const routeSegs = routePath.split('/').filter(Boolean)
85
+ if (exact === true && scopeSegs.length !== routeSegs.length) {
86
+ if (!(routeSegs.length > 0 && routeSegs.at(-1)!.startsWith('*') && routeSegs.length - 1 <= scopeSegs.length))
87
+ return false
88
+ }
89
+ for (const [i, seg] of scopeSegs.entries()) {
90
+ const routeSeg = routeSegs[i]
91
+ if (routeSeg === undefined) return false
92
+ if (routeSeg.startsWith('*')) return true
93
+ if (!routeSeg.startsWith(':') && routeSeg !== seg) return false
94
+ }
95
+ return true
96
+ }
97
+
74
98
  /** The methods of `match` that may answer `path`: for a path with an encoded separator, only those that set `encodedSlashes`; none left is no match. */
75
99
  export function takesEncoded(match: RouteMatch<Map<string, PluginRouteDef>> | undefined, path: RequestPath): RouteMatch<Map<string, PluginRouteDef>> | undefined {
76
100
  if (match === undefined || path.encoded === undefined || path.encoded.size === 0)
@@ -109,23 +133,26 @@ function createMiddlewareLookup(scopedMiddlewares: readonly ScopedMiddleware[])
109
133
  const hasPathScopedMiddlewares = scopedMiddlewares.some(m => !isKindScope(m.scope))
110
134
  // With no path-scoped middleware the list depends on the kind alone, so it is worked out once per kind.
111
135
  const byKind: Record<RequestKind, readonly Middleware[]> = {
112
- prerendered: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'prerendered')).map(m => m.mw),
113
- static: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'static')).map(m => m.mw),
136
+ prerendered: scopedMiddlewares.filter(m => middlewareAppliesToPath(m, '/', 'prerendered')).map(m => m.mw),
137
+ static: scopedMiddlewares.filter(m => middlewareAppliesToPath(m, '/', 'static')).map(m => m.mw),
114
138
  dynamic: allMiddlewares,
115
139
  }
116
140
  const middlewaresFor = (path: string, kind: RequestKind = 'dynamic'): readonly Middleware[] => {
117
141
  if (!hasPathScopedMiddlewares)
118
142
  return byKind[kind]
119
- return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, kind)).map(m => m.mw)
143
+ return scopedMiddlewares.filter(m => middlewareAppliesToPath(m, path, kind)).map(m => m.mw)
120
144
  }
121
145
  const middlewaresForPaths = (paths: readonly string[], kind: RequestKind = 'dynamic'): readonly Middleware[] => {
122
146
  if (!hasPathScopedMiddlewares)
123
147
  return byKind[kind]
124
148
  return scopedMiddlewares
125
- .filter(m => paths.some(path => middlewareAppliesToPath(m.scope, path, kind)))
149
+ .filter(m => paths.some(path => middlewareAppliesToPath(m, path, kind)))
126
150
  .map(m => m.mw)
127
151
  }
128
- return { allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths }
152
+ // A middleware scoped to a path guards that part of the site; one scoped to a request kind (sessions, locales, analytics) runs everywhere and only feeds `ctx.locals`.
153
+ const isGatedByPlugin = (routePath: string): boolean =>
154
+ hasPathScopedMiddlewares && scopedMiddlewares.some(m => !isKindScope(m.scope) && scopeMayCover(m.scope, routePath, m.exact))
155
+ return { allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths, isGatedByPlugin }
129
156
  }
130
157
 
131
158
  export async function createServerPluginHost(options: ServerPluginHostOptions) {
@@ -134,7 +161,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
134
161
  if (shared !== undefined)
135
162
  appCtx.provide(SHARED_STORE, shared)
136
163
  // The counters of every limited route and action of this server, dropped with it.
137
- const rateLimits = createRateLimitStore({ shared })
164
+ const rateLimits = createServerRateLimitStore({ shared })
138
165
  const scopedMiddlewares: ScopedMiddleware[] = []
139
166
  const healthChecks: HealthCheckEntry[] = []
140
167
  const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
@@ -187,6 +214,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
187
214
  trustedOrigins: routeTrustedOrigins,
188
215
  trustProxy: routeOptions?.trustProxy ?? trustProxy,
189
216
  encodedSlashes,
217
+ path: normPath,
190
218
  })
191
219
  }
192
220
 
@@ -244,7 +272,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
244
272
  trustedOrigins: options.trustedOriginsList,
245
273
  config: readonlyRuntimeConfig,
246
274
  use(mw: Middleware, middlewareOptions?: MiddlewareOptions) {
247
- scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
275
+ scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all', exact: middlewareOptions?.exact })
248
276
  },
249
277
  route: registerRouteFor(plugin.name),
250
278
  rateLimiter(limit, name) {
@@ -273,6 +301,10 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
273
301
  await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
274
302
  }
275
303
  }
304
+ const claims = [...routeEntries].flatMap(([path, byMethod]) => [...byMethod].map(([method, def]) => ({ plugin: def.plugin, method, path })))
305
+ const [shadow] = shadowedPages(manifest.routes, claims)
306
+ if (shadow !== undefined)
307
+ throw new Error(`prunelle: ${shadowMessage(shadow)}`)
276
308
  }
277
309
  catch (error) {
278
310
  await dispose()