prunelle 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +48 -43
  3. package/package.json +4 -1
  4. package/src/a11y/declaration.ts +106 -72
  5. package/src/a11y/index.ts +59 -39
  6. package/src/a11y/rgaa-map.ts +95 -49
  7. package/src/build/bundle.ts +8 -4
  8. package/src/build/byte-size.ts +11 -0
  9. package/src/build/client-plugin.ts +3 -1
  10. package/src/build/compile.ts +2 -1
  11. package/src/build/ecoindex.ts +15 -14
  12. package/src/build/files.ts +6 -0
  13. package/src/build/first-load.ts +83 -11
  14. package/src/build/graph.ts +29 -39
  15. package/src/build/index.ts +57 -18
  16. package/src/build/island-promote.ts +229 -0
  17. package/src/build/islands.ts +9 -201
  18. package/src/build/manifest.ts +4 -125
  19. package/src/build/plugin-host.ts +21 -8
  20. package/src/build/precompress.ts +1 -1
  21. package/src/build/prerender.ts +97 -44
  22. package/src/build/reach.ts +136 -0
  23. package/src/build/render-rules.ts +2 -2
  24. package/src/build/report.ts +19 -3
  25. package/src/build/static-headers.ts +93 -0
  26. package/src/build/static.ts +2 -0
  27. package/src/cli/check-forms.ts +97 -48
  28. package/src/cli/check-imports.ts +25 -0
  29. package/src/cli/check-links.ts +2 -2
  30. package/src/cli/check-security.ts +64 -0
  31. package/src/cli/check.ts +33 -7
  32. package/src/cli/commands.ts +35 -7
  33. package/src/cli/docs.ts +4 -3
  34. package/src/cli/inspect.ts +2 -1
  35. package/src/cli/mcp-tools.ts +7 -5
  36. package/src/cli/mcp.ts +1 -1
  37. package/src/cli/new.ts +14 -3
  38. package/src/cli/render.ts +14 -19
  39. package/src/cli/upgrade.ts +22 -5
  40. package/src/compiler/analyze.ts +26 -5
  41. package/src/compiler/cacheability.ts +2 -2
  42. package/src/compiler/compliance-eco.ts +71 -0
  43. package/src/compiler/compliance-rgaa.ts +110 -4
  44. package/src/compiler/compliance-urls.ts +145 -0
  45. package/src/compiler/compliance.ts +168 -116
  46. package/src/compiler/foreign-imports.ts +88 -0
  47. package/src/compiler/mistakes.ts +19 -1
  48. package/src/compiler/props-body.ts +52 -0
  49. package/src/compiler/shared.ts +2 -2
  50. package/src/compiler/ssr.ts +2 -2
  51. package/src/context.ts +34 -0
  52. package/src/dev/error-log.ts +90 -64
  53. package/src/dev/host-check.ts +26 -0
  54. package/src/dev/index.ts +12 -5
  55. package/src/dev/open-editor.ts +15 -11
  56. package/src/dev/protocol.ts +2 -0
  57. package/src/dev/supervisor.ts +8 -0
  58. package/src/dev/watchers.ts +27 -2
  59. package/src/dom/action.ts +4 -1
  60. package/src/dom/extras.ts +1 -2
  61. package/src/dom/index.ts +13 -2
  62. package/src/dom/island.ts +22 -10
  63. package/src/dom/loop.ts +25 -16
  64. package/src/eco/declaration.ts +257 -0
  65. package/src/eco/index.ts +65 -0
  66. package/src/index.ts +2 -2
  67. package/src/jsx-runtime.ts +2 -2
  68. package/src/plugins/config.ts +1 -1
  69. package/src/plugins/context.ts +16 -1
  70. package/src/plugins/load.ts +4 -3
  71. package/src/plugins/public.ts +2 -2
  72. package/src/plugins/services.ts +3 -0
  73. package/src/plugins/types.ts +17 -2
  74. package/src/server/action-flash.ts +158 -0
  75. package/src/server/action-protect.ts +38 -37
  76. package/src/server/action.ts +11 -127
  77. package/src/server/app-secret.ts +63 -0
  78. package/src/server/compress.ts +5 -1
  79. package/src/server/consent.ts +59 -22
  80. package/src/server/cookies.ts +16 -2
  81. package/src/server/env.ts +14 -0
  82. package/src/server/errors.ts +3 -1
  83. package/src/server/form-schema.ts +1 -1
  84. package/src/server/health.ts +46 -15
  85. package/src/server/http.ts +47 -7
  86. package/src/server/index.ts +52 -30
  87. package/src/server/loader.ts +6 -2
  88. package/src/server/plugin-host.ts +3 -1
  89. package/src/server/public.ts +4 -3
  90. package/src/server/rate-limit.ts +52 -9
  91. package/src/server/route-cache.ts +26 -4
  92. package/src/server/route-table.ts +7 -3
  93. package/src/server/routing.ts +3 -87
  94. package/src/server/sanitize-html.ts +309 -0
  95. package/src/server/security.ts +71 -20
  96. package/src/server/serve-handlers.ts +14 -4
  97. package/src/server/start.ts +1 -1
  98. package/src/server/static-dir.ts +27 -4
  99. package/src/server/stream.ts +28 -6
  100. package/src/ssr/consent-banner.ts +58 -0
  101. package/src/ssr/context.ts +20 -4
  102. package/src/ssr/index.ts +18 -0
  103. package/src/ssr/navigation.ts +2 -2
  104. package/src/style.ts +32 -1
  105. package/templates/_shared/gitignore +5 -0
  106. package/templates/_shared/src/routes/legal.tsx +10 -1
  107. package/templates/app/.env.example +4 -0
  108. package/templates/app/package.json +2 -1
  109. package/templates/app/prunelle.config.ts +2 -0
  110. package/templates/app/src/auth.ts +4 -6
  111. package/templates/app/src/mail.ts +4 -0
  112. package/templates/app/src/routes/_layout.tsx +9 -1
  113. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  114. package/templates/app/src/routes/login.tsx +49 -30
  115. package/templates/app/src/routes/privacy.tsx +25 -0
  116. package/templates/app/src/styles/app.css +8 -1
  117. package/templates/app/tests/app.test.ts +44 -3
  118. package/templates/blog/package.json +1 -1
  119. package/templates/blog/src/routes/_layout.tsx +6 -1
  120. package/templates/blog/src/routes/index.tsx +1 -1
  121. package/templates/blog/src/styles/app.css +6 -1
  122. package/templates/fullstack/package.json +1 -1
  123. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  124. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  125. package/templates/fullstack/src/styles/app.css +11 -1
  126. package/templates/minimal/package.json +1 -1
  127. package/templates/minimal/src/routes/_layout.tsx +4 -0
  128. package/templates/minimal/src/styles/app.css +11 -1
@@ -16,7 +16,6 @@ import type { PrunelleLocals } from './index'
16
16
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
17
  import type { ParamMatcherMap } from './param-matchers'
18
18
  import type { RequestPath } from './request-path'
19
- import type { RouteCache, RouteCacheSpec } from './route-cache'
20
19
  import type { TrustProxy } from './security'
21
20
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
22
21
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
@@ -29,7 +28,6 @@ import { pickPageIslandProps } from './page'
29
28
  import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
30
29
  import { withRegionVary } from './region'
31
30
  import { decodeRequestPath, pathPrefix } from './request-path'
32
- import { isCacheableRequest, serveCachedHit, withCacheControl } from './route-cache'
33
31
  import { Router } from './router'
34
32
  import { styleHashesOf } from './security'
35
33
 
@@ -226,7 +224,6 @@ export interface FastStaticPageOptions {
226
224
  consent?: NormalizedConsentConfig | undefined
227
225
  htmlHeaders: HtmlHeaders
228
226
  compressCache: CompressionCache | undefined
229
- routeCache?: RouteCache | undefined
230
227
  actions: ActionRegistry
231
228
  buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
232
229
  renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
@@ -236,73 +233,7 @@ export interface FastStaticPageOptions {
236
233
  withHsts: (res: Response, request: Request) => Response
237
234
  dev?: boolean | undefined
238
235
  resolveRequestId?: RequestIdResolver | undefined
239
- }
240
-
241
- interface FastRevalidateContext {
242
- entry: RouteManifestEntry
243
- mod: LoadedPageModule
244
- layouts: LoadedLayoutModule[]
245
- hasLoad: boolean
246
- hasIslands: boolean
247
- trustProxy: TrustProxy
248
- consent: NormalizedConsentConfig | undefined
249
- htmlHeaders: HtmlHeaders
250
- routeCache: RouteCache
251
- actions: ActionRegistry
252
- notifyError: NotifyError
253
- getRequestId: RequestIdResolver
254
- docPrefix: string
255
- revivingPrefix: string
256
- docSuffix: string
257
- headStyleHashes: string[]
258
- }
259
-
260
- async function revalidateFastStaticRoute(
261
- rc: FastRevalidateContext,
262
- url: URL,
263
- cacheKey: string,
264
- cacheSpec: RouteCacheSpec,
265
- ): Promise<void> {
266
- const bgReq = new Request(url.href, { method: 'GET' })
267
- const bgReqId = rc.getRequestId(bgReq)
268
- const { ctx, cookieStore } = makeRequestContext(bgReq, {}, { trustProxy: rc.trustProxy, url, consent: rc.consent, requestId: bgReqId })
269
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => rc.notifyError(error, bgReq, 'route', bgReqId))
270
- await rc.actions.run(ctx, async () => {
271
- let data: unknown
272
- if (rc.hasLoad) {
273
- try {
274
- data = await rc.mod.load!(ctx)
275
- }
276
- catch (error) {
277
- if (isNotFound(error)) {
278
- rc.routeCache.delete(cacheKey)
279
- return
280
- }
281
- throw error
282
- }
283
- if (isNotFound(data) || data instanceof Response) {
284
- rc.routeCache.delete(cacheKey)
285
- return
286
- }
287
- }
288
- const body = await runWithRenderContext(rctx, async () => {
289
- const pageProps: Record<string, unknown> = { params: {}, locals: ctx.locals, url, ...(data !== undefined ? { data } : {}) }
290
- let cur = rc.entry.isIsland && rc.entry.islandChunk !== undefined
291
- ? ssrIsland(rc.entry.islandChunk, () => ssrChild(rc.mod.default!(pageProps) as Html), pickPageIslandProps(data, rc.entry, rc.mod), rc.entry.islandHydrate as HydrateStrategy | undefined, true, rc.mod.default!.name)
292
- : ssrChild(await rc.mod.default!(pageProps) as Html)
293
- for (let i = rc.layouts.length - 1; i >= 0; i--)
294
- cur = ssrChild(await rc.layouts[i]!.default({ children: raw(cur), url, params: {}, locals: ctx.locals }) as Html)
295
- return cur
296
- })
297
- if (cookieStore.hasChanges) {
298
- rc.routeCache.delete(cacheKey)
299
- return
300
- }
301
- const html = (rctx.revives ? rc.revivingPrefix : rc.docPrefix) + body + keepScrollTag(body) + rc.docSuffix
302
- const styleHashes = mergeStyleHashes(rc.headStyleHashes, styleHashesOf(rctx.inlineStyles))
303
- const headers = withCacheControl(withRegionVary(rc.htmlHeaders(rc.hasIslands, false, true, styleHashes), rctx.regionNames.size > 0), cacheSpec.cacheControl)
304
- rc.routeCache.set(cacheKey, html, headers, cacheSpec)
305
- })
236
+ httpsSite?: boolean | undefined
306
237
  }
307
238
 
308
239
  function buildFastDocShell(doc: DocumentOptions, eagerChunks: string[], reviveScript: string | undefined, hasIslands: boolean): { docPrefix: string, revivingPrefix: string, docSuffix: string } {
@@ -318,16 +249,12 @@ function buildFastDocShell(doc: DocumentOptions, eagerChunks: string[], reviveSc
318
249
 
319
250
  /** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
320
251
  export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
321
- const { entry, mod, layouts, doc, reviveScript, hasIslands, hasLoad, trustProxy, consent, htmlHeaders, compressCache, routeCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts } = options
252
+ const { entry, mod, layouts, doc, reviveScript, hasIslands, hasLoad, trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts } = options
322
253
  const isDev = options.dev === true
323
254
  const getRequestId: RequestIdResolver = options.resolveRequestId ?? (req => resolveFallbackRequestId(req, trustProxy))
324
- const cacheSpec = routeCache !== undefined ? entry.cache : undefined
325
255
  const { docPrefix, revivingPrefix, docSuffix } = buildFastDocShell(doc, entry.eagerIslandChunks ?? entry.islandChunks, reviveScript, hasIslands)
326
256
  const headStyleHashes = headTagStyleHashes(doc.headTags)
327
257
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
328
- const revalidateCtx: FastRevalidateContext | undefined = cacheSpec !== undefined && routeCache !== undefined
329
- ? { entry, mod, layouts, hasLoad, hasIslands, trustProxy, consent, htmlHeaders, routeCache, actions, notifyError, getRequestId, docPrefix, revivingPrefix, docSuffix, headStyleHashes }
330
- : undefined
331
258
 
332
259
  const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
333
260
  notifyError(error, request, 'route', ctx?.requestId)
@@ -338,11 +265,6 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
338
265
  const styleHashes = mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles))
339
266
  const headers = withRegionVary(htmlHeaders(hasIslands, false, true, styleHashes), rctx.regionNames.size > 0)
340
267
  const st = timing !== undefined ? finishRenderTiming(timing) : undefined
341
- if (cacheSpec !== undefined && routeCache !== undefined && !cookieStore.hasChanges && isCacheableRequest(request)) {
342
- const cachedHeaders = withCacheControl(headers, cacheSpec.cacheControl)
343
- const stored = routeCache.set(ctx.url.pathname + ctx.url.search, html, cachedHeaders, cacheSpec)
344
- return withHsts(routeCache.respondMiss(stored, html, cachedHeaders, request, ctx.requestId, compressCache, st), request)
345
- }
346
268
  const res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad)
347
269
  res.headers.set('x-request-id', ctx.requestId)
348
270
  if (st !== undefined)
@@ -413,14 +335,8 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
413
335
 
414
336
  return (request, remoteIp, url = new URL(request.url), requestId?: string) => {
415
337
  const reqId = requestId ?? getRequestId(request)
416
- if (revalidateCtx !== undefined && cacheSpec !== undefined && routeCache !== undefined && !(request.method === 'HEAD' && typeof mod.HEAD === 'function') && isCacheableRequest(request)) {
417
- const cacheKey = url.pathname + url.search
418
- const cached = serveCachedHit(routeCache, cacheKey, request, reqId, compressCache, () => revalidateFastStaticRoute(revalidateCtx, url, cacheKey, cacheSpec), error => notifyError(error, request, 'route', reqId))
419
- if (cached !== undefined)
420
- return withHsts(cached, request)
421
- }
422
338
  const timing = createTiming(isDev)
423
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent, requestId: reqId })
339
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite: options.httpsSite, remoteIp, url, consent, requestId: reqId })
424
340
  if (request.method === 'HEAD' && typeof mod.HEAD === 'function') {
425
341
  return actions.run(ctx, async () => {
426
342
  try {
@@ -0,0 +1,309 @@
1
+ // HTML allow-list sanitizer for rendered Markdown, shared by @prunellejs/content and the @prunellejs/cms preview: drops dangerous tags, non-allowlisted attributes and unsafe URL schemes.
2
+
3
+ const DROP_CONTENT_TAGS = new Set([
4
+ 'script',
5
+ 'style',
6
+ 'iframe',
7
+ 'object',
8
+ 'applet',
9
+ 'noscript',
10
+ 'template',
11
+ ])
12
+
13
+ const ALLOWED_MD_TAGS = new Set([
14
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
15
+ 'p', 'br', 'hr', 'div', 'span', 'section', 'article', 'aside', 'header', 'footer', 'nav', 'main',
16
+ 'a', 'img', 'picture', 'source',
17
+ 'pre', 'code', 'kbd', 'samp', 'var',
18
+ 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
19
+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col',
20
+ 'blockquote', 'q', 'cite', 'abbr', 'time', 'mark', 'small', 'ins', 'del', 's', 'u', 'b', 'i', 'strong', 'em', 'sup', 'sub', 'wbr',
21
+ 'details', 'summary', 'figure', 'figcaption',
22
+ 'input',
23
+ ])
24
+
25
+ // Strict attribute allowlist: blocks event handlers (on*), data-pru-*, data-persist, DOM clobbering (id/name), style, etc.
26
+ const GLOBAL_ALLOWED_ATTRS = new Set([
27
+ 'class',
28
+ 'title',
29
+ 'lang',
30
+ 'dir',
31
+ 'role',
32
+ 'aria-label',
33
+ 'aria-hidden',
34
+ 'aria-current',
35
+ 'aria-expanded',
36
+ 'aria-level',
37
+ 'aria-description',
38
+ 'aria-roledescription',
39
+ ])
40
+
41
+ const TAG_ALLOWED_ATTRS: Record<string, ReadonlySet<string>> = {
42
+ a: new Set(['href', 'rel', 'target', 'hreflang']),
43
+ img: new Set(['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading', 'decoding', 'fetchpriority']),
44
+ source: new Set(['src', 'srcset', 'sizes', 'type', 'media', 'width', 'height']),
45
+ blockquote: new Set(['cite']),
46
+ q: new Set(['cite']),
47
+ del: new Set(['cite', 'datetime']),
48
+ ins: new Set(['cite', 'datetime']),
49
+ time: new Set(['datetime']),
50
+ ol: new Set(['start', 'reversed', 'type']),
51
+ li: new Set(['value']),
52
+ th: new Set(['colspan', 'rowspan', 'scope', 'align', 'valign', 'abbr']),
53
+ td: new Set(['colspan', 'rowspan', 'align', 'valign', 'abbr']),
54
+ col: new Set(['span', 'align']),
55
+ colgroup: new Set(['span', 'align']),
56
+ details: new Set(['open']),
57
+ }
58
+
59
+ const URL_ATTRS = new Set(['href', 'src', 'cite'])
60
+ const SAFE_DATA_IMAGE_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i
61
+ const SAFE_SCHEME_RE = /^(?:https?|mailto|tel):/i
62
+ const HAS_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
63
+
64
+ function decodeHtmlEntities(rawVal: string): string {
65
+ return rawVal
66
+ .replace(/&#x([0-9a-f]+);?/gi, (_, hex: string) => {
67
+ const cp = Number.parseInt(hex, 16)
68
+ return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
69
+ })
70
+ .replace(/&#([0-9]+);?/g, (_, dec: string) => {
71
+ const cp = Number.parseInt(dec, 10)
72
+ return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
73
+ })
74
+ .replace(/&(colon|tab|newline|amp);/gi, (_, name: string) => {
75
+ const lower = name.toLowerCase()
76
+ if (lower === 'colon') return ':'
77
+ if (lower === 'tab') return '\t'
78
+ if (lower === 'newline') return '\n'
79
+ return '&'
80
+ })
81
+ }
82
+
83
+ function isSafeUrl(val: string): boolean {
84
+ const cleaned = decodeHtmlEntities(val).replace(/[\u0000-\u0020\u007F]+/g, '').trim()
85
+ if (cleaned === '')
86
+ return true
87
+ if (SAFE_SCHEME_RE.test(cleaned) || SAFE_DATA_IMAGE_RE.test(cleaned))
88
+ return true
89
+ if (HAS_SCHEME_RE.test(cleaned))
90
+ return false
91
+ return true
92
+ }
93
+
94
+ function parseTagAttributes(attrSrc: string): Array<{ name: string, value: string | null }> {
95
+ const attrs: Array<{ name: string, value: string | null }> = []
96
+ let i = 0
97
+ const len = attrSrc.length
98
+ while (i < len) {
99
+ while (i < len && /[\s/]/.test(attrSrc[i]!)) i++
100
+ if (i >= len) break
101
+ const nameStart = i
102
+ while (i < len && !/[\s=/>"'<]/.test(attrSrc[i]!)) i++
103
+ const name = attrSrc.slice(nameStart, i).toLowerCase()
104
+ if (!name) {
105
+ i++
106
+ continue
107
+ }
108
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
109
+ if (attrSrc[i] !== '=') {
110
+ attrs.push({ name, value: null })
111
+ continue
112
+ }
113
+ i++ // skip '='
114
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
115
+ if (i >= len) {
116
+ attrs.push({ name, value: '' })
117
+ break
118
+ }
119
+ const quote = attrSrc[i]!
120
+ if (quote === '"' || quote === '\'') {
121
+ i++
122
+ const valStart = i
123
+ while (i < len && attrSrc[i] !== quote) i++
124
+ attrs.push({ name, value: attrSrc.slice(valStart, i) })
125
+ if (i < len) i++
126
+ }
127
+ else {
128
+ const valStart = i
129
+ while (i < len && !/[\s>]/.test(attrSrc[i]!)) i++
130
+ attrs.push({ name, value: attrSrc.slice(valStart, i) })
131
+ }
132
+ }
133
+ return attrs
134
+ }
135
+
136
+ function sanitizeInputTag(rawAttrs: Array<{ name: string, value: string | null }>): string {
137
+ const typeAttr = rawAttrs.find(a => a.name === 'type')
138
+ if (typeAttr?.value?.toLowerCase() !== 'checkbox')
139
+ return ''
140
+ const safeParts = ['type="checkbox"']
141
+ for (const a of rawAttrs) {
142
+ if (a.name === 'class' && a.value !== null)
143
+ safeParts.push(`class="${a.value.replaceAll('"', '&quot;')}"`)
144
+ else if (a.name === 'disabled')
145
+ safeParts.push('disabled')
146
+ else if (a.name === 'checked')
147
+ safeParts.push('checked')
148
+ }
149
+ return `<input ${safeParts.join(' ')}>`
150
+ }
151
+
152
+ type AllowedSlotPrefixes = string | ReadonlySet<string> | undefined
153
+
154
+ function matchesSlotPrefix(value: string | null, allowed: AllowedSlotPrefixes): boolean {
155
+ if (value === null || allowed === undefined)
156
+ return false
157
+ if (typeof allowed === 'string')
158
+ return value.startsWith(allowed)
159
+ for (const prefix of allowed) {
160
+ if (value.startsWith(prefix))
161
+ return true
162
+ }
163
+ return false
164
+ }
165
+
166
+ function isAllowedAttr(tagName: string, name: string, value: string | null, slotPrefixes: AllowedSlotPrefixes): boolean {
167
+ if (tagName === 'div' && name === 'data-pru-md-slot')
168
+ return matchesSlotPrefix(value, slotPrefixes)
169
+ return GLOBAL_ALLOWED_ATTRS.has(name) || TAG_ALLOWED_ATTRS[tagName]?.has(name) === true
170
+ }
171
+
172
+ function sanitizeAttributes(
173
+ tagName: string,
174
+ rawAttrs: Array<{ name: string, value: string | null }>,
175
+ slotPrefixes: AllowedSlotPrefixes,
176
+ ): string[] {
177
+ const safeParts: string[] = []
178
+ for (const a of rawAttrs) {
179
+ if (!isAllowedAttr(tagName, a.name, a.value, slotPrefixes))
180
+ continue
181
+ if (URL_ATTRS.has(a.name)) {
182
+ if (a.value === null || !isSafeUrl(a.value))
183
+ continue
184
+ }
185
+ else if (a.name === 'srcset' && a.value !== null) {
186
+ const candidates = a.value.split(',').map(s => s.trim().split(/\s+/)[0] ?? '')
187
+ if (!candidates.every(isSafeUrl))
188
+ continue
189
+ }
190
+ if (a.value === null)
191
+ safeParts.push(a.name)
192
+ else
193
+ safeParts.push(`${a.name}="${a.value.replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')}"`)
194
+ }
195
+ return safeParts
196
+ }
197
+
198
+ function findTagEndOffset(html: string, start: number): number {
199
+ let tagEnd = start
200
+ const len = html.length
201
+ let inQuote: string | null = null
202
+ while (tagEnd < len) {
203
+ const c = html[tagEnd]!
204
+ if (inQuote !== null) {
205
+ if (c === inQuote)
206
+ inQuote = null
207
+ }
208
+ else if (c === '"' || c === '\'') {
209
+ inQuote = c
210
+ }
211
+ else if (c === '>') {
212
+ return tagEnd
213
+ }
214
+ tagEnd++
215
+ }
216
+ return -1
217
+ }
218
+
219
+ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
220
+ let out = ''
221
+ let i = 0
222
+ const len = html.length
223
+
224
+ while (i < len) {
225
+ const lt = html.indexOf('<', i)
226
+ if (lt === -1) {
227
+ out += html.slice(i)
228
+ break
229
+ }
230
+ out += html.slice(i, lt)
231
+
232
+ // Strip HTML comments (including HTML5 `--!>` closer)
233
+ if (html.startsWith('<!--', lt)) {
234
+ const endStd = html.indexOf('-->', lt + 4)
235
+ const endBang = html.indexOf('--!>', lt + 4)
236
+ if (endStd === -1 && endBang === -1)
237
+ i = len
238
+ else if (endBang !== -1 && (endStd === -1 || endBang < endStd))
239
+ i = endBang + 4
240
+ else
241
+ i = endStd + 3
242
+ continue
243
+ }
244
+
245
+ let pos = lt + 1
246
+ const isClosing = html[pos] === '/'
247
+ if (isClosing)
248
+ pos++
249
+
250
+ const nameStart = pos
251
+ while (pos < len && /[A-Za-z0-9:-]/.test(html[pos]!)) pos++
252
+ const tagName = html.slice(nameStart, pos).toLowerCase()
253
+ if (!tagName) {
254
+ out += '&lt;'
255
+ i = lt + 1
256
+ continue
257
+ }
258
+
259
+ const tagEnd = findTagEndOffset(html, pos)
260
+ if (tagEnd === -1)
261
+ break
262
+
263
+ const attrSrc = html.slice(pos, tagEnd)
264
+ const selfClosing = !isClosing && /\/\s*$/.test(attrSrc)
265
+ i = tagEnd + 1
266
+
267
+ if (!isClosing && DROP_CONTENT_TAGS.has(tagName)) {
268
+ if (!selfClosing) {
269
+ const closeRe = new RegExp(`</${tagName}\\b[^<>]*>`, 'gi')
270
+ closeRe.lastIndex = i
271
+ const m = closeRe.exec(html)
272
+ i = m ? m.index + m[0].length : len
273
+ }
274
+ continue
275
+ }
276
+
277
+ if (!ALLOWED_MD_TAGS.has(tagName))
278
+ continue
279
+
280
+ if (isClosing) {
281
+ if (tagName !== 'input' && tagName !== 'br' && tagName !== 'hr' && tagName !== 'img')
282
+ out += `</${tagName}>`
283
+ continue
284
+ }
285
+
286
+ const rawAttrs = parseTagAttributes(attrSrc)
287
+ if (tagName === 'input') {
288
+ out += sanitizeInputTag(rawAttrs)
289
+ continue
290
+ }
291
+
292
+ const safeParts = sanitizeAttributes(tagName, rawAttrs, slotPrefixes)
293
+ const attrOut = safeParts.length > 0 ? ` ${safeParts.join(' ')}` : ''
294
+ out += selfClosing ? `<${tagName}${attrOut} />` : `<${tagName}${attrOut}>`
295
+ }
296
+
297
+ return out
298
+ }
299
+
300
+ export function sanitizeMarkdownHtml(html: string, slotPrefixes?: AllowedSlotPrefixes): string {
301
+ let current = html
302
+ for (let pass = 0; pass < 3; pass++) {
303
+ const next = sanitizePass(current, slotPrefixes)
304
+ if (next === current)
305
+ return next
306
+ current = next
307
+ }
308
+ return current
309
+ }
@@ -171,7 +171,9 @@ export function withCspHashes(
171
171
 
172
172
  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'"
173
173
  export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
174
- export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
174
+ export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), accelerometer=(), gyroscope=(), magnetometer=(), browsing-topics=()'
175
+ export const DEFAULT_COOP = 'same-origin'
176
+ export const DEFAULT_CORP = 'same-origin'
175
177
 
176
178
  export type CspDirectiveValue = string | readonly string[]
177
179
 
@@ -314,6 +316,10 @@ export interface SecurityHeadersOptions {
314
316
  permissionsPolicy?: string | false | undefined
315
317
  csp?: string | CspDirectives | false | undefined
316
318
  hsts?: string | boolean | undefined
319
+ /** `Cross-Origin-Opener-Policy` (default `same-origin`): another site's window cannot keep a handle on this one. `'same-origin-allow-popups'` keeps a payment or sign-in popup working. */
320
+ crossOriginOpenerPolicy?: string | false | undefined
321
+ /** `Cross-Origin-Resource-Policy` (default `same-origin`): another site cannot embed this one's images, scripts or fonts. Use `'cross-origin'` for assets meant to be hotlinked. */
322
+ crossOriginResourcePolicy?: string | false | undefined
317
323
  }
318
324
 
319
325
  const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
@@ -396,21 +402,6 @@ export function getClientIp(request: Request, trustProxy: TrustProxy = false, re
396
402
  return remoteIp || undefined
397
403
  }
398
404
 
399
- const sha256 = (text: string): Buffer => new Bun.CryptoHasher('sha256').update(text).digest()
400
-
401
- /**
402
- * Compares two secrets (tokens, MACs, OAuth states) in constant time: both are hashed first, so neither their content nor their length shows in the timing.
403
- * The digests are XORed byte by byte rather than passed to `node:crypto`, which would add 2 MB to the server's RSS.
404
- */
405
- export function safeEqual(a: string, b: string): boolean {
406
- const x = sha256(a)
407
- const y = sha256(b)
408
- let diff = 0
409
- for (let i = 0; i < x.length; i++)
410
- diff |= x[i]! ^ y[i]!
411
- return diff === 0
412
- }
413
-
414
405
  /** `target` trimmed when it is a path on this site, else `fallback`: an absolute or protocol-relative URL, a backslash or a control character is refused. */
415
406
  export function safeRedirect(target: string | null | undefined, fallback = '/'): string {
416
407
  const path = target?.trim()
@@ -435,8 +426,56 @@ export function isTrustedOrigin(
435
426
  ): boolean {
436
427
  if (!origin || origin === 'null')
437
428
  return false
438
- const expectedOrigin = forwardedOrigin(request, trustProxy) ?? requestUrl?.origin ?? new URL(request.url).origin
439
- return origin === expectedOrigin || trustedOrigins?.has(origin) === true
429
+ return origin === expectedOrigin(request, trustProxy, requestUrl) || trustedOrigins?.has(origin) === true
430
+ }
431
+
432
+ /** The origin this server takes the request to be on: the trusted forwarded one, else the one it was reached at. */
433
+ function expectedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?: URL): string {
434
+ return forwardedOrigin(request, trustProxy) ?? requestUrl?.origin ?? new URL(request.url).origin
435
+ }
436
+
437
+ /** Whether `origin` is the https twin of the http `expected` origin: the same host, so only the scheme can differ. */
438
+ function isSchemeMismatch(origin: string, expected: string): boolean {
439
+ const seen = URL.parse(origin)
440
+ const computed = URL.parse(expected)
441
+ return seen !== null && computed !== null && computed.protocol === 'http:' && seen.host === computed.host
442
+ }
443
+
444
+ /** What to log when a POST is refused: the two origins compared, and the config keys that settle it. */
445
+ function untrustedOriginHint(origin: string, expected: string, trustProxy: TrustProxy): string {
446
+ const head = `prunelle: a POST was refused as cross-site: its Origin is ${origin} but the origin this server computes is ${expected}.`
447
+ if (isSchemeMismatch(origin, expected))
448
+ return `${head} The page is served over https and the server sees http, as behind a TLS proxy: set trustProxy in prunelle.config.ts (true for one proxy, or the number of proxies) and have the proxy send x-forwarded-proto. To accept another site, add its origin to trustedOrigins.`
449
+ if (proxyHops(trustProxy) > 0)
450
+ return `${head} trustProxy is on: check the proxy sends x-forwarded-proto and x-forwarded-host, or list the origin in trustedOrigins in prunelle.config.ts.`
451
+ return `${head} Behind a proxy, set trustProxy in prunelle.config.ts; to accept another site, add its origin to trustedOrigins.`
452
+ }
453
+
454
+ let hintLogged = false
455
+
456
+ /** Logs a refused origin's fix, the first time only: later refusals of a misconfigured proxy would repeat it on every POST. */
457
+ export function logOriginHint(hint: string | undefined): void {
458
+ if (hint === undefined || hintLogged)
459
+ return
460
+ hintLogged = true
461
+ console.warn(hint)
462
+ }
463
+
464
+ /** Lets the next `logOriginHint` log again; for tests. */
465
+ export function resetOriginHint(): void {
466
+ hintLogged = false
467
+ }
468
+
469
+ /** Why a request was refused as cross-site, and the fix to log for it when the cause is a wrong origin. */
470
+ export interface OriginRefusal {
471
+ reason: string
472
+ hint?: string | undefined
473
+ }
474
+
475
+ /** Whether `host` (a hostname or a bind address, IPv6 with or without brackets) names this machine alone. */
476
+ export function isLoopbackHost(host: string): boolean {
477
+ const bare = host.toLowerCase().replace(/^\[|\]$/g, '')
478
+ return bare === 'localhost' || bare === '127.0.0.1' || bare === '::1'
440
479
  }
441
480
 
442
481
  /** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
@@ -445,7 +484,7 @@ export function verifyOrigin(
445
484
  trustedOrigins?: ReadonlySet<string>,
446
485
  trustProxy: TrustProxy = false,
447
486
  requestUrl?: URL,
448
- ): { ok: true } | { ok: false, reason: string } {
487
+ ): { ok: true } | ({ ok: false } & OriginRefusal) {
449
488
  if (SAFE_METHODS.has(request.method.toUpperCase()))
450
489
  return { ok: true }
451
490
 
@@ -453,7 +492,7 @@ export function verifyOrigin(
453
492
  if (origin !== null) {
454
493
  if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy, requestUrl))
455
494
  return { ok: true }
456
- return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}` }
495
+ return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}`, hint: untrustedOriginHint(origin, expectedOrigin(request, trustProxy, requestUrl), trustProxy) }
457
496
  }
458
497
 
459
498
  const fetchSite = request.headers.get('sec-fetch-site')
@@ -463,6 +502,14 @@ export function verifyOrigin(
463
502
  return { ok: true }
464
503
  }
465
504
 
505
+ /** 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. */
506
+ export function loopbackBindNotice(hostname: string, fromHost: boolean): string | undefined {
507
+ if (!isLoopbackHost(hostname))
508
+ return undefined
509
+ const source = fromHost ? 'HOST or --host' : 'the default, as neither HOST nor --host is set'
510
+ return `prunelle: the server listens on ${hostname} (${source}), which only this machine reaches: in a container or behind another host, set HOST=0.0.0.0 or pass --host so the published port answers.`
511
+ }
512
+
466
513
  export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
467
514
  if (options === false || options?.csp === false)
468
515
  return undefined
@@ -492,6 +539,10 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
492
539
  entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
493
540
  if (opts.permissionsPolicy !== false)
494
541
  entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
542
+ if (opts.crossOriginOpenerPolicy !== false)
543
+ entries.push(['cross-origin-opener-policy', opts.crossOriginOpenerPolicy ?? DEFAULT_COOP])
544
+ if (opts.crossOriginResourcePolicy !== false)
545
+ entries.push(['cross-origin-resource-policy', opts.crossOriginResourcePolicy ?? DEFAULT_CORP])
495
546
  const csp = resolveCspPolicy(opts)
496
547
  if (csp !== undefined)
497
548
  entries.push(['content-security-policy', csp])
@@ -39,10 +39,20 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
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
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)))
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
+ const serveFile = async (req: Request, file: ServedFile): Promise<Response> => {
44
+ const reqId = resolveRequestId?.(req)
45
+ const tagged = (res: Response): Response => reqId === undefined ? res : withRequestId(res, reqId)
46
+ try {
47
+ return tagged(await files.serveFile(req, file))
48
+ }
49
+ catch (err) {
50
+ if (err instanceof Error && 'code' in err && err.code === 'ENOENT')
51
+ return tagged(fileGone())
52
+ notifyError(err, req, 'route', reqId)
53
+ return tagged(serverError())
54
+ }
55
+ }
46
56
 
47
57
  const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
48
58
  const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>): void => {
@@ -71,7 +71,7 @@ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleAp
71
71
  target = await promise
72
72
  }
73
73
  catch {
74
- return new Response('Service Unavailable', { status: 503, headers: { 'content-type': 'text/plain; charset=utf-8' } })
74
+ return new Response('Service Unavailable', { status: 503, headers: { ...current().securityHeaders, 'content-type': 'text/plain; charset=utf-8' } })
75
75
  }
76
76
  return target.handle(request, server.requestIP(request)?.address, () => server.timeout(request, 0))
77
77
  },