prunelle 0.1.1 → 0.2.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 (48) hide show
  1. package/llms.txt +12 -12
  2. package/package.json +1 -1
  3. package/src/build/client-entries.ts +3 -2
  4. package/src/build/compile.ts +2 -1
  5. package/src/build/index.ts +68 -29
  6. package/src/build/manifest.ts +18 -1
  7. package/src/build/output.ts +2 -2
  8. package/src/build/precompress.ts +15 -2
  9. package/src/build/prerender.ts +2 -2
  10. package/src/build/routes.ts +171 -10
  11. package/src/build/static.ts +71 -17
  12. package/src/build/status-pages.ts +127 -0
  13. package/src/cli/check-forms.ts +654 -0
  14. package/src/cli/check-links.ts +619 -0
  15. package/src/cli/check.ts +37 -4
  16. package/src/cli/commands.ts +5 -3
  17. package/src/cli/inspect.ts +21 -2
  18. package/src/cli/upgrade-names.ts +73 -13
  19. package/src/cli/upgrade.ts +137 -16
  20. package/src/compiler/compliance-rgaa.ts +502 -0
  21. package/src/compiler/compliance.ts +119 -220
  22. package/src/compiler/ssr.ts +121 -24
  23. package/src/dom/action.ts +4 -1
  24. package/src/dom/island.ts +5 -5
  25. package/src/plugins/config.ts +1 -1
  26. package/src/plugins/types.ts +13 -0
  27. package/src/server/action-protect.ts +186 -0
  28. package/src/server/action.ts +33 -10
  29. package/src/server/errors.ts +291 -62
  30. package/src/server/form-schema.ts +343 -0
  31. package/src/server/health.ts +244 -0
  32. package/src/server/http.ts +84 -17
  33. package/src/server/index.ts +162 -91
  34. package/src/server/param-matchers.ts +112 -0
  35. package/src/server/plugin-host.ts +40 -14
  36. package/src/server/public.ts +3 -3
  37. package/src/server/route-table.ts +5 -2
  38. package/src/server/router.ts +125 -40
  39. package/src/server/routing.ts +95 -57
  40. package/src/server/security.ts +171 -22
  41. package/src/server/serve-handlers.ts +21 -7
  42. package/src/ssr/context.ts +49 -0
  43. package/src/ssr/index.ts +120 -1
  44. package/src/test/browser.ts +6 -0
  45. package/src/test/index.ts +17 -3
  46. package/templates/_shared/src/routes/legal.tsx +5 -0
  47. package/templates/blog/prunelle.config.ts +1 -1
  48. package/templates/blog/src/routes/index.tsx +4 -0
@@ -10,9 +10,11 @@ import type { NormalizedConsentConfig } from './consent'
10
10
  import type { CookieStore } from './cookies'
11
11
  import type { HtmlHeaders } from './document'
12
12
  import type { NotifyError } from './errors'
13
- import type { Middleware, RequestContext } from './http'
13
+ import type { DevTiming, RequestIdResolver } from './health'
14
+ import type { DeniedInfo, Middleware, RequestContext } from './http'
14
15
  import type { PrunelleLocals } from './index'
15
16
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
+ import type { ParamMatcherMap } from './param-matchers'
16
18
  import type { RequestPath } from './request-path'
17
19
  import type { TrustProxy } from './security'
18
20
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
@@ -20,18 +22,24 @@ import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
20
22
  import { keepScrollTag } from '../ssr/navigation'
21
23
  import { compressedHtmlResponse, maybeCompressResponse } from './compress'
22
24
  import { headTagStyleHashes, mergeStyleHashes } from './document'
23
- import { isNotFound, makeRequestContext } from './http'
25
+ import { createTiming, endTimer, finishRenderTiming, formatServerTiming, resolveFallbackRequestId, startTimer } from './health'
26
+ import { acceptsHtml, getDeniedInfo, isNotFound, makeRequestContext } from './http'
24
27
  import { pickPageIslandProps } from './page'
28
+ import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
25
29
  import { withRegionVary } from './region'
26
30
  import { pathPrefix } from './request-path'
27
31
  import { Router } from './router'
28
32
  import { styleHashesOf } from './security'
29
33
 
30
34
  const MIDDLEWARE_BASENAME_RE = /(?:^|\/)_middleware\.js$/
35
+ const ROUTE_GROUP_RE = /^\([^/()]+\)$/
36
+ const OPTIONAL_PARAM_SEG_RE = /^\[\[([^\[\]]+)\]\]$/
37
+ const CATCH_ALL_SEG_RE = /^\[\.\.\.([^\[\]]+)\]$/
38
+ const PARAM_SEG_RE = /^\[([^\[\]]+)\]$/
31
39
  const CATCH_ALL_BRACKET_RE = /\[\.\.\.([^\]]+)\]/g
32
40
  const PARAM_BRACKET_RE = /\[([^\]]+)\]/g
33
41
 
34
- export type FastHandler = (req: Request, remoteIp?: string, url?: URL) => Response | Promise<Response>
42
+ export type FastHandler = (req: Request, remoteIp?: string, url?: URL, requestId?: string) => Response | Promise<Response>
35
43
 
36
44
 
37
45
  export function methodNotAllowed(allow: string): Response {
@@ -50,10 +58,26 @@ function dirnamePrefix(file: string): string {
50
58
  return slash === -1 ? '' : file.slice(0, slash + 1)
51
59
  }
52
60
 
61
+ function convertDirSegment(seg: string): string {
62
+ const opt = OPTIONAL_PARAM_SEG_RE.exec(seg)
63
+ if (opt !== null)
64
+ return `:${opt[1]}?`
65
+ const catchAll = CATCH_ALL_SEG_RE.exec(seg)
66
+ if (catchAll !== null)
67
+ return `*${catchAll[1]}`
68
+ const param = PARAM_SEG_RE.exec(seg)
69
+ if (param !== null)
70
+ return `:${param[1]}`
71
+ return seg.replace(CATCH_ALL_BRACKET_RE, '*$1').replace(PARAM_BRACKET_RE, ':$1')
72
+ }
73
+
53
74
  function dirToRoutePattern(relDir: string): string {
54
75
  if (relDir === '')
55
76
  return '/'
56
- return `/${relDir.replace(CATCH_ALL_BRACKET_RE, '*$1').replace(PARAM_BRACKET_RE, ':$1')}`
77
+ const parts = relDir.split('/').filter(p => p !== '' && !ROUTE_GROUP_RE.test(p))
78
+ if (parts.length === 0)
79
+ return '/'
80
+ return `/${parts.map(convertDirSegment).join('/')}`
57
81
  }
58
82
 
59
83
  /** Infers the compiled module prefix for files under `routesDir` (e.g. `'server/'` or `'server/src/routes/'`). */
@@ -66,9 +90,17 @@ export function inferRoutesServerPrefix(manifest: BuildManifest): string {
66
90
  const fileParts = route.file.split('/')
67
91
  const pathSegs = route.path === '/' ? [] : route.path.replace(/^\/|\/$/g, '').split('/')
68
92
  const isIndex = fileParts[fileParts.length - 1] === 'index.js'
69
- const routePartCount = pathSegs.length + (isIndex ? 1 : 0)
70
- if (routePartCount <= fileParts.length) {
71
- const prefixParts = fileParts.slice(0, fileParts.length - routePartCount)
93
+ let remaining = pathSegs.length + (isIndex ? 1 : 0)
94
+ let idx = fileParts.length
95
+ while (idx > 0 && remaining > 0) {
96
+ idx--
97
+ if (!ROUTE_GROUP_RE.test(fileParts[idx]!))
98
+ remaining--
99
+ }
100
+ while (idx > 0 && ROUTE_GROUP_RE.test(fileParts[idx - 1]!))
101
+ idx--
102
+ if (remaining === 0) {
103
+ const prefixParts = fileParts.slice(0, idx)
72
104
  return prefixParts.length === 0 ? '' : `${prefixParts.join('/')}/`
73
105
  }
74
106
  }
@@ -107,6 +139,7 @@ export function createAncestorMiddlewareLookup(
107
139
  manifest: BuildManifest,
108
140
  modules: Record<string, unknown>,
109
141
  routesPrefix: string,
142
+ paramMatchers: ParamMatcherMap = BUILTIN_PARAM_MATCHERS,
110
143
  ): (path: RequestPath) => AncestorMiddlewareMatch | undefined {
111
144
  const byPattern = new Map<string, Middleware[]>()
112
145
  const seenModules = new Set<string>()
@@ -122,6 +155,9 @@ export function createAncestorMiddlewareLookup(
122
155
  return
123
156
  const rel = modKey.slice(routesPrefix.length)
124
157
  const relDir = rel.replace(MIDDLEWARE_BASENAME_RE, '')
158
+ // A `(group)` middleware only applies to routes/actions inside that group, never to unrelated unmatched URLs.
159
+ if (relDir !== '' && relDir.split('/').some(p => ROUTE_GROUP_RE.test(p)))
160
+ return
125
161
  const pattern = dirToRoutePattern(relDir)
126
162
  let list = byPattern.get(pattern)
127
163
  if (list === undefined) {
@@ -147,7 +183,7 @@ export function createAncestorMiddlewareLookup(
147
183
  if (byPattern.size === 0)
148
184
  return () => undefined
149
185
 
150
- const dirRouter = new Router<Middleware[]>()
186
+ const dirRouter = new Router<Middleware[]>(paramMatchers)
151
187
  for (const [pattern, list] of byPattern)
152
188
  dirRouter.add(pattern, list)
153
189
 
@@ -182,34 +218,21 @@ export interface FastStaticPageOptions {
182
218
  htmlHeaders: HtmlHeaders
183
219
  compressCache: CompressionCache | undefined
184
220
  actions: ActionRegistry
185
- buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext) => Promise<Response>
186
- renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext) => Promise<Response>
221
+ buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
222
+ renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
223
+ renderDenied?: ((denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>) | undefined
187
224
  notifyError: NotifyError
188
- finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
225
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
189
226
  withHsts: (res: Response, request: Request) => Response
227
+ dev?: boolean | undefined
228
+ resolveRequestId?: RequestIdResolver | undefined
190
229
  }
191
230
 
192
231
  /** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
193
232
  export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
194
- const {
195
- entry,
196
- mod,
197
- layouts,
198
- doc,
199
- reviveScript,
200
- hasIslands,
201
- hasLoad,
202
- trustProxy,
203
- consent,
204
- htmlHeaders,
205
- compressCache,
206
- actions,
207
- buildNotFoundResponse,
208
- renderError,
209
- notifyError,
210
- finish,
211
- withHsts,
212
- } = options
233
+ const { entry, mod, layouts, doc, reviveScript, hasIslands, hasLoad, trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts } = options
234
+ const isDev = options.dev === true
235
+ const getRequestId: RequestIdResolver = options.resolveRequestId ?? (req => resolveFallbackRequestId(req, trustProxy))
213
236
 
214
237
  const eagerChunks = entry.eagerIslandChunks ?? entry.islandChunks
215
238
  const shellAround = (preloadChunks: string[]): [string, string] => {
@@ -223,42 +246,46 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
223
246
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
224
247
 
225
248
  const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
226
- notifyError(error, request, 'route')
227
- return renderError(error, cookieStore, url, request, ctx)
249
+ notifyError(error, request, 'route', ctx?.requestId)
250
+ return renderError(error, cookieStore, url, request, ctx, entry.file)
228
251
  }
229
- const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore?: CookieStore): Response => {
252
+ const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response => {
230
253
  const html = (rctx.revives ? revivingPrefix : docPrefix) + body + keepScrollTag(body) + docSuffix
231
254
  const styleHashes = mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles))
232
255
  const headers = withRegionVary(htmlHeaders(hasIslands, false, true, styleHashes), rctx.regionNames.size > 0)
233
256
  const res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad)
234
- return cookieStore?.hasChanges ? finish(res, request, cookieStore) : withHsts(res, request)
257
+ res.headers.set('x-request-id', ctx.requestId)
258
+ const st = timing !== undefined ? finishRenderTiming(timing) : undefined
259
+ if (st !== undefined)
260
+ res.headers.set('server-timing', st)
261
+ return cookieStore.hasChanges ? finish(res, request, cookieStore, ctx.requestId, st) : withHsts(res, request)
235
262
  }
236
263
  const layoutProps = (inner: string, url: URL, locals: PrunelleLocals) => ({ children: raw(inner), url, params: {}, locals })
237
264
 
238
- const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
265
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
239
266
  try {
240
- return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore)
267
+ return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore, ctx, timing)
241
268
  }
242
269
  catch (error) {
243
270
  return fail(error, request, url, cookieStore, ctx)
244
271
  }
245
272
  }
246
273
 
247
- const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
274
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
248
275
  if (layouts.length === 0)
249
- return respondHtml(inner, request, rctx, cookieStore)
276
+ return respondHtml(inner, request, rctx, cookieStore, ctx, timing)
250
277
  if (singleLayout !== undefined) {
251
278
  const wrapped = singleLayout.default(layoutProps(inner, url, locals))
252
279
  if (wrapped instanceof Promise)
253
- return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx)
254
- return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore)
280
+ return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx, timing)
281
+ return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore, ctx, timing)
255
282
  }
256
283
  return (async () => {
257
284
  try {
258
285
  let cur = inner
259
286
  for (let i = layouts.length - 1; i >= 0; i--)
260
287
  cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
261
- return respondHtml(cur, request, rctx, cookieStore)
288
+ return respondHtml(cur, request, rctx, cookieStore, ctx, timing)
262
289
  }
263
290
  catch (error) {
264
291
  return fail(error, request, url, cookieStore, ctx)
@@ -266,16 +293,18 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
266
293
  })()
267
294
  }
268
295
 
269
- const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
296
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
270
297
  try {
271
- return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx)
298
+ return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
272
299
  }
273
300
  catch (error) {
274
301
  return fail(error, request, url, cookieStore, ctx)
275
302
  }
276
303
  }
277
304
 
278
- const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
305
+ const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
306
+ if (timing !== undefined)
307
+ timing.render = performance.now()
279
308
  const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
280
309
  if (entry.isIsland && entry.islandChunk !== undefined) {
281
310
  return wrapLayouts(ssrIsland(
@@ -285,47 +314,56 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
285
314
  entry.islandHydrate as HydrateStrategy | undefined,
286
315
  true,
287
316
  mod.default!.name,
288
- ), request, url, locals, rctx, cookieStore, ctx)
317
+ ), request, url, locals, rctx, cookieStore, ctx, timing)
289
318
  }
290
319
  const rendered = mod.default!(pageProps)
291
320
  if (rendered instanceof Promise)
292
- return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx)
293
- return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx)
321
+ return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx, timing)
322
+ return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
294
323
  }
295
324
 
296
- return (request, remoteIp, url = new URL(request.url)) => {
297
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent })
325
+ return (request, remoteIp, url = new URL(request.url), requestId?: string) => {
326
+ const reqId = requestId ?? getRequestId(request)
327
+ const timing = createTiming(isDev)
328
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent, requestId: reqId })
298
329
  if (request.method === 'HEAD' && typeof mod.HEAD === 'function') {
299
330
  return actions.run(ctx, async () => {
300
331
  try {
301
- return finish(await mod.HEAD!(ctx), request, cookieStore)
332
+ return finish(await mod.HEAD!(ctx), request, cookieStore, reqId, formatServerTiming(timing))
302
333
  }
303
334
  catch (error) {
304
335
  return fail(error, request, url, cookieStore, ctx)
305
336
  }
306
337
  })
307
338
  }
308
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route'))
339
+ const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route', reqId))
309
340
  try {
310
341
  if (!hasLoad)
311
- return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx)))
342
+ return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx, timing)))
312
343
 
313
344
  return actions.run(ctx, async () => {
314
345
  let loaded: unknown
346
+ const loadStart = startTimer(timing)
315
347
  try {
316
348
  loaded = await mod.load!(ctx)
317
349
  }
318
350
  catch (error) {
319
351
  if (isNotFound(error))
320
- return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx), request, compressCache), request, cookieStore)
352
+ return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
321
353
  return fail(error, request, url, cookieStore, ctx)
322
354
  }
355
+ endTimer(timing, 'load', loadStart)
323
356
  if (isNotFound(loaded))
324
- return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx), request, compressCache), request, cookieStore)
325
- if (loaded instanceof Response)
326
- return finish(await maybeCompressResponse(loaded, request, compressCache), request, cookieStore)
357
+ return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
358
+ if (loaded instanceof Response) {
359
+ const denied = getDeniedInfo(loaded)
360
+ const out = denied !== undefined && renderDenied !== undefined && acceptsHtml(request)
361
+ ? await renderDenied(denied, url, request, ctx, entry.file)
362
+ : loaded
363
+ return finish(await maybeCompressResponse(out, request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
364
+ }
327
365
  try {
328
- return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx))
366
+ return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx, timing))
329
367
  }
330
368
  catch (error) {
331
369
  return fail(error, request, url, cookieStore, ctx)
@@ -71,28 +71,47 @@ export function inlineStyleHashes(html: string): string[] {
71
71
  return hashes
72
72
  }
73
73
 
74
- /** Augments a Content-Security-Policy header with exact SHA-256 hashes (no `'unsafe-inline'` required). */
75
- export function withCspHashes(
76
- csp: string,
77
- opts: { styleHashes?: readonly string[], scriptHashes?: readonly string[] },
78
- ): string {
79
- const styleHashes = opts.styleHashes ?? []
80
- const scriptHashes = opts.scriptHashes ?? []
81
- if (styleHashes.length === 0 && scriptHashes.length === 0)
82
- return csp
74
+ interface ParsedCsp {
75
+ order: string[]
76
+ directives: Map<string, string[]>
77
+ }
83
78
 
84
- const rawParts = csp.split(';').map(s => s.trim()).filter(Boolean)
79
+ function parseCsp(csp: string): ParsedCsp {
85
80
  const directives = new Map<string, string[]>()
86
81
  const order: string[] = []
87
- for (const part of rawParts) {
88
- const tokens = part.split(/\s+/)
82
+ for (const part of csp.split(';')) {
83
+ const trimmed = part.trim()
84
+ if (!trimmed)
85
+ continue
86
+ const tokens = trimmed.split(/\s+/)
89
87
  const name = tokens[0]!.toLowerCase()
90
88
  if (!directives.has(name)) {
91
89
  order.push(name)
92
90
  directives.set(name, tokens.slice(1))
93
91
  }
94
92
  }
93
+ return { order, directives }
94
+ }
95
+
96
+ function serializeCsp(parsed: ParsedCsp): string {
97
+ return parsed.order.map((name) => {
98
+ const tokens = parsed.directives.get(name)!
99
+ return tokens.length > 0 ? `${name} ${tokens.join(' ')}` : name
100
+ }).join('; ')
101
+ }
102
+
103
+ /** Augments a Content-Security-Policy header with exact SHA-256 hashes (no `'unsafe-inline'` required). */
104
+ export function withCspHashes(
105
+ csp: string,
106
+ opts: { styleHashes?: readonly string[], scriptHashes?: readonly string[] },
107
+ ): string {
108
+ const styleHashes = opts.styleHashes ?? []
109
+ const scriptHashes = opts.scriptHashes ?? []
110
+ if (styleHashes.length === 0 && scriptHashes.length === 0)
111
+ return csp
95
112
 
113
+ const parsed = parseCsp(csp)
114
+ const { order, directives } = parsed
96
115
  const defaultSrc = directives.get('default-src') ?? ["'self'"]
97
116
  const addHashes = (dirName: string, hashes: readonly string[]) => {
98
117
  if (hashes.length === 0)
@@ -121,22 +140,151 @@ export function withCspHashes(
121
140
  if (directives.has('script-src-elem'))
122
141
  addHashes('script-src-elem', scriptHashes)
123
142
 
124
- return order.map((name) => {
125
- const tokens = directives.get(name)!
126
- return tokens.length > 0 ? `${name} ${tokens.join(' ')}` : name
127
- }).join('; ')
143
+ return serializeCsp(parsed)
128
144
  }
129
145
 
130
146
  export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'"
131
147
  export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
132
148
  export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
133
149
 
150
+ export type CspDirectiveValue = string | readonly string[]
151
+
152
+ export interface KnownCspDirectives {
153
+ 'default-src'?: CspDirectiveValue | undefined
154
+ 'script-src'?: CspDirectiveValue | undefined
155
+ 'script-src-elem'?: CspDirectiveValue | undefined
156
+ 'script-src-attr'?: CspDirectiveValue | undefined
157
+ 'style-src'?: CspDirectiveValue | undefined
158
+ 'style-src-elem'?: CspDirectiveValue | undefined
159
+ 'style-src-attr'?: CspDirectiveValue | undefined
160
+ 'img-src'?: CspDirectiveValue | undefined
161
+ 'font-src'?: CspDirectiveValue | undefined
162
+ 'connect-src'?: CspDirectiveValue | undefined
163
+ 'media-src'?: CspDirectiveValue | undefined
164
+ 'object-src'?: CspDirectiveValue | undefined
165
+ 'frame-src'?: CspDirectiveValue | undefined
166
+ 'child-src'?: CspDirectiveValue | undefined
167
+ 'worker-src'?: CspDirectiveValue | undefined
168
+ 'manifest-src'?: CspDirectiveValue | undefined
169
+ 'base-uri'?: CspDirectiveValue | undefined
170
+ 'form-action'?: CspDirectiveValue | undefined
171
+ 'frame-ancestors'?: CspDirectiveValue | undefined
172
+ 'sandbox'?: CspDirectiveValue | undefined
173
+ 'report-to'?: CspDirectiveValue | undefined
174
+ 'report-uri'?: CspDirectiveValue | undefined
175
+ 'upgrade-insecure-requests'?: CspDirectiveValue | undefined
176
+ }
177
+
178
+ export type CspDirectives = Readonly<KnownCspDirectives & Record<string, CspDirectiveValue | undefined>>
179
+
180
+ const isFetchDirective = (name: string): boolean =>
181
+ name.endsWith('-src') || name.endsWith('-src-elem') || name.endsWith('-src-attr')
182
+
183
+ function splitCspTokens(value: CspDirectiveValue): string[] {
184
+ const parts = typeof value === 'string' ? [value] : value
185
+ const tokens: string[] = []
186
+ for (const part of parts) {
187
+ for (const token of part.split(/\s+/)) {
188
+ if (token.length > 0 && !tokens.includes(token))
189
+ tokens.push(token)
190
+ }
191
+ }
192
+ return tokens
193
+ }
194
+
195
+ function mergeCspDirective(parsed: ParsedCsp, name: string, tokens: readonly string[]): void {
196
+ const { order, directives } = parsed
197
+ const existing = directives.get(name)
198
+ if (existing === undefined) {
199
+ order.push(name)
200
+ if (tokens.length === 0) {
201
+ directives.set(name, [])
202
+ }
203
+ else if (tokens.includes("'none'")) {
204
+ directives.set(name, ["'none'"])
205
+ }
206
+ else if (isFetchDirective(name)) {
207
+ const seeded = (directives.get('default-src') ?? ["'self'"]).filter(t => t !== "'none'")
208
+ for (const token of tokens) {
209
+ if (!seeded.includes(token))
210
+ seeded.push(token)
211
+ }
212
+ directives.set(name, seeded)
213
+ }
214
+ else {
215
+ directives.set(name, [...tokens])
216
+ }
217
+ return
218
+ }
219
+ if (tokens.length === 0)
220
+ return
221
+ if (tokens.includes("'none'")) {
222
+ directives.set(name, ["'none'"])
223
+ return
224
+ }
225
+ const noneIdx = existing.indexOf("'none'")
226
+ if (noneIdx !== -1)
227
+ existing.splice(noneIdx, 1)
228
+ for (const token of tokens) {
229
+ if (!existing.includes(token))
230
+ existing.push(token)
231
+ }
232
+ }
233
+
234
+ /** Extends a Content-Security-Policy (default: `DEFAULT_CSP`) by merging additional sources into one or more directives. */
235
+ export function extendCsp(extra: CspDirectives, base = DEFAULT_CSP): string {
236
+ const parsed = parseCsp(base)
237
+ for (const [rawName, rawValue] of Object.entries(extra)) {
238
+ if (rawValue === undefined)
239
+ continue
240
+ const name = rawName.trim().toLowerCase()
241
+ if (name.length === 0)
242
+ continue
243
+ mergeCspDirective(parsed, name, splitCspTokens(rawValue))
244
+ }
245
+ return serializeCsp(parsed)
246
+ }
247
+
248
+ // Directives browsers ignore (and log an error for) when delivered via <meta http-equiv="Content-Security-Policy"> (W3C CSP3 §4.2.1).
249
+ const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'sandbox'])
250
+ const EXISTING_META_CSP_RE = /<meta\b[^>]*\bhttp-equiv\s*=\s*(?:"content-security-policy"|'content-security-policy'|content-security-policy\b)/i
251
+ const META_CHARSET_RE = /<meta\b[^>]*\bcharset\s*=\s*[^>]*>/i
252
+ const HEAD_OPEN_RE = /<head\b[^>]*>/i
253
+ const ESC_DOUBLE_ATTR_RE = /[&"<>]/g
254
+ const DOUBLE_ATTR_MAP: Record<string, string> = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }
255
+
256
+ /** Strips directives browsers reject in a `<meta http-equiv="Content-Security-Policy">` element. */
257
+ export function toMetaCsp(csp: string): string {
258
+ const parsed = parseCsp(csp)
259
+ parsed.order = parsed.order.filter(name => !META_CSP_IGNORED.has(name))
260
+ return serializeCsp(parsed)
261
+ }
262
+
263
+ /** Injects `<meta http-equiv="Content-Security-Policy">` at the top of `<head>` for static HTML exports. */
264
+ export function injectMetaCsp(html: string, csp: string | null | undefined): string {
265
+ if (!csp || EXISTING_META_CSP_RE.test(html))
266
+ return html
267
+ const metaCsp = toMetaCsp(csp)
268
+ if (metaCsp.length === 0)
269
+ return html
270
+ const headMatch = HEAD_OPEN_RE.exec(html)
271
+ if (headMatch === null)
272
+ return html
273
+ const headEnd = headMatch.index + headMatch[0].length
274
+ const headCloseIdx = html.toLowerCase().indexOf('</head>', headEnd)
275
+ const headSlice = headCloseIdx === -1 ? html.slice(headEnd) : html.slice(headEnd, headCloseIdx)
276
+ const charsetMatch = META_CHARSET_RE.exec(headSlice)
277
+ const insertAt = charsetMatch !== null ? headEnd + charsetMatch.index + charsetMatch[0].length : headEnd
278
+ const escaped = metaCsp.replace(ESC_DOUBLE_ATTR_RE, ch => DOUBLE_ATTR_MAP[ch]!)
279
+ return `${html.slice(0, insertAt)}<meta http-equiv="Content-Security-Policy" content="${escaped}">${html.slice(insertAt)}`
280
+ }
281
+
134
282
  export interface SecurityHeadersOptions {
135
283
  frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
136
284
  referrerPolicy?: string | false | undefined
137
285
  contentTypeOptions?: boolean | undefined
138
286
  permissionsPolicy?: string | false | undefined
139
- csp?: string | false | undefined
287
+ csp?: string | CspDirectives | false | undefined
140
288
  hsts?: string | boolean | undefined
141
289
  }
142
290
 
@@ -289,10 +437,10 @@ export function verifyOrigin(
289
437
  }
290
438
 
291
439
  export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
292
- if (options === false)
293
- return undefined
294
- if (options?.csp === false)
440
+ if (options === false || options?.csp === false)
295
441
  return undefined
442
+ if (typeof options?.csp === 'object')
443
+ return extendCsp(options.csp)
296
444
  return options?.csp ?? DEFAULT_CSP
297
445
  }
298
446
 
@@ -317,7 +465,8 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
317
465
  entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
318
466
  if (opts.permissionsPolicy !== false)
319
467
  entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
320
- if (opts.csp !== false)
321
- entries.push(['content-security-policy', opts.csp ?? DEFAULT_CSP])
468
+ const csp = resolveCspPolicy(opts)
469
+ if (csp !== undefined)
470
+ entries.push(['content-security-policy', csp])
322
471
  return entries
323
472
  }
@@ -2,10 +2,12 @@
2
2
 
3
3
  import type { createAssets, ServedFile } from './assets'
4
4
  import type { NotifyError } from './errors'
5
+ import type { RequestIdResolver } from './health'
5
6
  import type { PrunelleServer } from './http'
6
7
  import type { RequestPath } from './request-path'
7
8
  import type { FastHandler } from './routing'
8
9
  import { ACTION_ERROR_COOKIE } from './action'
10
+ import { withRequestId } from './health'
9
11
  import { hasRegionHeader } from './region'
10
12
  import { literalPath } from './request-path'
11
13
  import { toBunRouteKey } from './routing'
@@ -15,6 +17,9 @@ export interface ServeHandlerSources {
15
17
  fastPrerenderedMap: ReadonlyMap<string, ServedFile>
16
18
  fastStaticPages: ReadonlyMap<string, FastHandler>
17
19
  pluginRouter: { match: (path: RequestPath) => unknown }
20
+ healthPath?: string | undefined
21
+ healthHandler?: ((request: Request, requestId?: string) => Response | Promise<Response>) | undefined
22
+ resolveRequestId?: RequestIdResolver | undefined
18
23
  /** Answers through the app's whole pipeline, with the request's timeout turned off by `disableTimeout` for a long-lived stream. */
19
24
  runRequest: (req: Request, remoteIp: string | undefined, disableTimeout: () => void) => Promise<Response>
20
25
  runFast: (handler: FastHandler, req: Request, remoteIp: string | undefined) => Response | Promise<Response>
@@ -31,9 +36,13 @@ export const hasActionErrorCookie = (request: Request): boolean => (request.head
31
36
  export const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request) && !hasRegionHeader(request)
32
37
 
33
38
  export function serveHandlers(server: () => PrunelleServer | undefined, sources: ServeHandlerSources) {
34
- const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, runRequest, runFast, notifyError, serverError, fileGone } = sources
39
+ const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone } = sources
35
40
  const ipOf = (req: Request) => server()?.requestIP(req)?.address
36
41
  const fetchReq = (req: Request) => runRequest(req, ipOf(req), () => server()?.timeout(req, 0))
42
+ const serveFile = (req: Request, file: ServedFile): Promise<Response> =>
43
+ resolveRequestId === undefined
44
+ ? files.serveFile(req, file)
45
+ : files.serveFile(req, file).then(res => withRequestId(res, resolveRequestId(req)))
37
46
 
38
47
  const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
39
48
  const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>): void => {
@@ -42,16 +51,19 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
42
51
  routes[key] = handler
43
52
  }
44
53
 
54
+ if (healthPath !== undefined && healthHandler !== undefined)
55
+ registerServeRoute(healthPath, req => healthHandler(req))
56
+
45
57
  for (const [path, asset] of files.assetMap)
46
- registerServeRoute(path, req => isRead(req) ? files.serveFile(req, asset) : fetchReq(req))
58
+ registerServeRoute(path, req => isRead(req) ? serveFile(req, asset) : fetchReq(req))
47
59
 
48
60
  for (const [path, pub] of files.publicMap) {
49
61
  if (pluginRouter.match(literalPath(path)) === undefined)
50
- registerServeRoute(path, req => isRead(req) ? files.serveFile(req, pub) : fetchReq(req))
62
+ registerServeRoute(path, req => isRead(req) ? serveFile(req, pub) : fetchReq(req))
51
63
  }
52
64
 
53
65
  for (const [path, pre] of fastPrerenderedMap)
54
- registerServeRoute(path, req => isPlainRead(req) ? files.serveFile(req, pre) : fetchReq(req))
66
+ registerServeRoute(path, req => isPlainRead(req) ? serveFile(req, pre) : fetchReq(req))
55
67
 
56
68
  for (const [path, handler] of fastStaticPages)
57
69
  registerServeRoute(path, req => isPlainRead(req) ? runFast(handler, req, ipOf(req)) : fetchReq(req))
@@ -60,10 +72,12 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
60
72
  routes,
61
73
  fetch: fetchReq,
62
74
  error(err: Error) {
75
+ const fallbackReq = new Request('http://localhost/')
76
+ const reqId = resolveRequestId?.(fallbackReq)
63
77
  if ('code' in err && err.code === 'ENOENT')
64
- return fileGone()
65
- notifyError(err, new Request('http://localhost/'), 'route')
66
- return serverError()
78
+ return reqId !== undefined ? withRequestId(fileGone(), reqId) : fileGone()
79
+ notifyError(err, fallbackReq, 'route', reqId)
80
+ return reqId !== undefined ? withRequestId(serverError(), reqId) : serverError()
67
81
  },
68
82
  }
69
83
  }