prunelle 0.1.1 → 0.7.2

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 (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -46,20 +46,46 @@ export function styleHashesOf(styles: Iterable<string> | undefined): string[] {
46
46
  const STYLE_OPEN_RE = /<style(?=[\s>/])/gi
47
47
  const STYLE_CLOSE_RE = /<\/style(?=[\s>])/gi
48
48
 
49
+ function findStyleTagEnd(html: string, start: number): { end: number, selfClosing: boolean } | undefined {
50
+ let quote = 0
51
+ for (let i = start; i < html.length; i++) {
52
+ const ch = html.charCodeAt(i)
53
+ if (quote !== 0) {
54
+ if (ch === quote)
55
+ quote = 0
56
+ }
57
+ else if (ch === 34 || ch === 39) {
58
+ quote = ch
59
+ }
60
+ else if (ch === 62) {
61
+ let prev = i - 1
62
+ while (prev >= start && html.charCodeAt(prev) <= 32)
63
+ prev--
64
+ return { end: i, selfClosing: prev >= start && html.charCodeAt(prev) === 47 }
65
+ }
66
+ }
67
+ return undefined
68
+ }
69
+
49
70
  /** CSP hashes of the app's own `<style>` blocks in `html`, leaving out prunelle's island and Suspense styles (hashed apart). */
50
71
  export function inlineStyleHashes(html: string): string[] {
51
72
  const hashes: string[] = []
52
73
  STYLE_OPEN_RE.lastIndex = 0
53
74
  let open = STYLE_OPEN_RE.exec(html)
54
75
  while (open !== null) {
55
- const tagEnd = html.indexOf('>', open.index + 6)
56
- if (tagEnd === -1)
76
+ const tag = findStyleTagEnd(html, open.index + 6)
77
+ if (tag === undefined)
57
78
  break
58
- STYLE_CLOSE_RE.lastIndex = tagEnd + 1
79
+ if (tag.selfClosing) {
80
+ STYLE_OPEN_RE.lastIndex = tag.end + 1
81
+ open = STYLE_OPEN_RE.exec(html)
82
+ continue
83
+ }
84
+ STYLE_CLOSE_RE.lastIndex = tag.end + 1
59
85
  const close = STYLE_CLOSE_RE.exec(html)
60
86
  if (close === null)
61
87
  break
62
- const content = html.slice(tagEnd + 1, close.index)
88
+ const content = html.slice(tag.end + 1, close.index)
63
89
  if (content !== PRUNELLE_ISLAND_STYLE && content !== PRUNELLE_SUSPENSE_STYLE) {
64
90
  const hash = styleHash(content)
65
91
  if (!hashes.includes(hash))
@@ -71,28 +97,47 @@ export function inlineStyleHashes(html: string): string[] {
71
97
  return hashes
72
98
  }
73
99
 
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
100
+ interface ParsedCsp {
101
+ order: string[]
102
+ directives: Map<string, string[]>
103
+ }
83
104
 
84
- const rawParts = csp.split(';').map(s => s.trim()).filter(Boolean)
105
+ function parseCsp(csp: string): ParsedCsp {
85
106
  const directives = new Map<string, string[]>()
86
107
  const order: string[] = []
87
- for (const part of rawParts) {
88
- const tokens = part.split(/\s+/)
108
+ for (const part of csp.split(';')) {
109
+ const trimmed = part.trim()
110
+ if (!trimmed)
111
+ continue
112
+ const tokens = trimmed.split(/\s+/)
89
113
  const name = tokens[0]!.toLowerCase()
90
114
  if (!directives.has(name)) {
91
115
  order.push(name)
92
116
  directives.set(name, tokens.slice(1))
93
117
  }
94
118
  }
119
+ return { order, directives }
120
+ }
95
121
 
122
+ function serializeCsp(parsed: ParsedCsp): string {
123
+ return parsed.order.map((name) => {
124
+ const tokens = parsed.directives.get(name)!
125
+ return tokens.length > 0 ? `${name} ${tokens.join(' ')}` : name
126
+ }).join('; ')
127
+ }
128
+
129
+ /** Augments a Content-Security-Policy header with exact SHA-256 hashes (no `'unsafe-inline'` required). */
130
+ export function withCspHashes(
131
+ csp: string,
132
+ opts: { styleHashes?: readonly string[], scriptHashes?: readonly string[] },
133
+ ): string {
134
+ const styleHashes = opts.styleHashes ?? []
135
+ const scriptHashes = opts.scriptHashes ?? []
136
+ if (styleHashes.length === 0 && scriptHashes.length === 0)
137
+ return csp
138
+
139
+ const parsed = parseCsp(csp)
140
+ const { order, directives } = parsed
96
141
  const defaultSrc = directives.get('default-src') ?? ["'self'"]
97
142
  const addHashes = (dirName: string, hashes: readonly string[]) => {
98
143
  if (hashes.length === 0)
@@ -121,26 +166,163 @@ export function withCspHashes(
121
166
  if (directives.has('script-src-elem'))
122
167
  addHashes('script-src-elem', scriptHashes)
123
168
 
124
- return order.map((name) => {
125
- const tokens = directives.get(name)!
126
- return tokens.length > 0 ? `${name} ${tokens.join(' ')}` : name
127
- }).join('; ')
169
+ return serializeCsp(parsed)
128
170
  }
129
171
 
130
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'"
131
173
  export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
132
- 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'
177
+
178
+ export type CspDirectiveValue = string | readonly string[]
179
+
180
+ export interface KnownCspDirectives {
181
+ 'default-src'?: CspDirectiveValue | undefined
182
+ 'script-src'?: CspDirectiveValue | undefined
183
+ 'script-src-elem'?: CspDirectiveValue | undefined
184
+ 'script-src-attr'?: CspDirectiveValue | undefined
185
+ 'style-src'?: CspDirectiveValue | undefined
186
+ 'style-src-elem'?: CspDirectiveValue | undefined
187
+ 'style-src-attr'?: CspDirectiveValue | undefined
188
+ 'img-src'?: CspDirectiveValue | undefined
189
+ 'font-src'?: CspDirectiveValue | undefined
190
+ 'connect-src'?: CspDirectiveValue | undefined
191
+ 'media-src'?: CspDirectiveValue | undefined
192
+ 'object-src'?: CspDirectiveValue | undefined
193
+ 'frame-src'?: CspDirectiveValue | undefined
194
+ 'child-src'?: CspDirectiveValue | undefined
195
+ 'worker-src'?: CspDirectiveValue | undefined
196
+ 'manifest-src'?: CspDirectiveValue | undefined
197
+ 'base-uri'?: CspDirectiveValue | undefined
198
+ 'form-action'?: CspDirectiveValue | undefined
199
+ 'frame-ancestors'?: CspDirectiveValue | undefined
200
+ 'sandbox'?: CspDirectiveValue | undefined
201
+ 'report-to'?: CspDirectiveValue | undefined
202
+ 'report-uri'?: CspDirectiveValue | undefined
203
+ 'upgrade-insecure-requests'?: CspDirectiveValue | undefined
204
+ }
205
+
206
+ export type CspDirectives = Readonly<KnownCspDirectives & Record<string, CspDirectiveValue | undefined>>
207
+
208
+ const isFetchDirective = (name: string): boolean =>
209
+ name.endsWith('-src') || name.endsWith('-src-elem') || name.endsWith('-src-attr')
210
+
211
+ function splitCspTokens(value: CspDirectiveValue): string[] {
212
+ const parts = typeof value === 'string' ? [value] : value
213
+ const tokens: string[] = []
214
+ for (const part of parts) {
215
+ for (const token of part.split(/\s+/)) {
216
+ if (token.length > 0 && !tokens.includes(token))
217
+ tokens.push(token)
218
+ }
219
+ }
220
+ return tokens
221
+ }
222
+
223
+ function mergeCspDirective(parsed: ParsedCsp, name: string, tokens: readonly string[]): void {
224
+ const { order, directives } = parsed
225
+ const existing = directives.get(name)
226
+ if (existing === undefined) {
227
+ order.push(name)
228
+ if (tokens.length === 0) {
229
+ directives.set(name, [])
230
+ }
231
+ else if (tokens.includes("'none'")) {
232
+ directives.set(name, ["'none'"])
233
+ }
234
+ else if (isFetchDirective(name)) {
235
+ const seeded = (directives.get('default-src') ?? ["'self'"]).filter(t => t !== "'none'")
236
+ for (const token of tokens) {
237
+ if (!seeded.includes(token))
238
+ seeded.push(token)
239
+ }
240
+ directives.set(name, seeded)
241
+ }
242
+ else {
243
+ directives.set(name, [...tokens])
244
+ }
245
+ return
246
+ }
247
+ if (tokens.length === 0)
248
+ return
249
+ if (tokens.includes("'none'")) {
250
+ directives.set(name, ["'none'"])
251
+ return
252
+ }
253
+ const noneIdx = existing.indexOf("'none'")
254
+ if (noneIdx !== -1)
255
+ existing.splice(noneIdx, 1)
256
+ for (const token of tokens) {
257
+ if (!existing.includes(token))
258
+ existing.push(token)
259
+ }
260
+ }
261
+
262
+ /** Extends a Content-Security-Policy (default: `DEFAULT_CSP`) by merging additional sources into one or more directives. */
263
+ export function extendCsp(extra: CspDirectives, base = DEFAULT_CSP): string {
264
+ const parsed = parseCsp(base)
265
+ for (const [rawName, rawValue] of Object.entries(extra)) {
266
+ if (rawValue === undefined)
267
+ continue
268
+ const name = rawName.trim().toLowerCase()
269
+ if (name.length === 0)
270
+ continue
271
+ mergeCspDirective(parsed, name, splitCspTokens(rawValue))
272
+ }
273
+ return serializeCsp(parsed)
274
+ }
275
+
276
+ // Directives browsers ignore (and log an error for) when delivered via <meta http-equiv="Content-Security-Policy"> (W3C CSP3 §4.2.1).
277
+ const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'sandbox'])
278
+ const EXISTING_META_CSP_RE = /<meta\b[^>]*\bhttp-equiv\s*=\s*(?:"content-security-policy"|'content-security-policy'|content-security-policy\b)/i
279
+ const META_CHARSET_RE = /<meta\b[^>]*\bcharset\s*=\s*[^>]*>/i
280
+ const HEAD_OPEN_RE = /<head\b[^>]*>/i
281
+ const ESC_DOUBLE_ATTR_RE = /[&"<>]/g
282
+ const DOUBLE_ATTR_MAP: Record<string, string> = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }
283
+
284
+ /** Strips directives browsers reject in a `<meta http-equiv="Content-Security-Policy">` element. */
285
+ export function toMetaCsp(csp: string): string {
286
+ const parsed = parseCsp(csp)
287
+ parsed.order = parsed.order.filter(name => !META_CSP_IGNORED.has(name))
288
+ return serializeCsp(parsed)
289
+ }
290
+
291
+ /** Injects `<meta http-equiv="Content-Security-Policy">` at the top of `<head>` for static HTML exports. */
292
+ export function injectMetaCsp(html: string, csp: string | null | undefined): string {
293
+ if (!csp)
294
+ return html
295
+ const metaCsp = toMetaCsp(csp)
296
+ if (metaCsp.length === 0)
297
+ return html
298
+ const headMatch = HEAD_OPEN_RE.exec(html)
299
+ if (headMatch === null)
300
+ return html
301
+ const headEnd = headMatch.index + headMatch[0].length
302
+ const headCloseIdx = html.toLowerCase().indexOf('</head>', headEnd)
303
+ const headSlice = headCloseIdx === -1 ? html.slice(headEnd) : html.slice(headEnd, headCloseIdx)
304
+ if (EXISTING_META_CSP_RE.test(headSlice))
305
+ return html
306
+ const charsetMatch = META_CHARSET_RE.exec(headSlice)
307
+ const insertAt = charsetMatch !== null ? headEnd + charsetMatch.index + charsetMatch[0].length : headEnd
308
+ const escaped = metaCsp.replace(ESC_DOUBLE_ATTR_RE, ch => DOUBLE_ATTR_MAP[ch]!)
309
+ return `${html.slice(0, insertAt)}<meta http-equiv="Content-Security-Policy" content="${escaped}">${html.slice(insertAt)}`
310
+ }
133
311
 
134
312
  export interface SecurityHeadersOptions {
135
313
  frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
136
314
  referrerPolicy?: string | false | undefined
137
315
  contentTypeOptions?: boolean | undefined
138
316
  permissionsPolicy?: string | false | undefined
139
- csp?: string | false | undefined
317
+ csp?: string | CspDirectives | false | undefined
140
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
141
323
  }
142
324
 
143
- const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
325
+ const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
144
326
 
145
327
  /** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
146
328
  export type TrustProxy = boolean | number
@@ -184,11 +366,11 @@ function forwardedValue(request: Request, header: string, trustProxy: TrustProxy
184
366
  return undefined
185
367
  }
186
368
 
187
- function forwardedOrigin(request: Request, trustProxy: TrustProxy): string | undefined {
369
+ function forwardedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?: URL): string | undefined {
188
370
  const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase()
189
371
  if (proto !== 'http' && proto !== 'https')
190
372
  return undefined
191
- const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim()
373
+ const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim() || (requestUrl ?? new URL(request.url)).host
192
374
  if (!host)
193
375
  return undefined
194
376
  try {
@@ -220,21 +402,6 @@ export function getClientIp(request: Request, trustProxy: TrustProxy = false, re
220
402
  return remoteIp || undefined
221
403
  }
222
404
 
223
- const sha256 = (text: string): Buffer => new Bun.CryptoHasher('sha256').update(text).digest()
224
-
225
- /**
226
- * 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.
227
- * The digests are XORed byte by byte rather than passed to `node:crypto`, which would add 2 MB to the server's RSS.
228
- */
229
- export function safeEqual(a: string, b: string): boolean {
230
- const x = sha256(a)
231
- const y = sha256(b)
232
- let diff = 0
233
- for (let i = 0; i < x.length; i++)
234
- diff |= x[i]! ^ y[i]!
235
- return diff === 0
236
- }
237
-
238
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. */
239
406
  export function safeRedirect(target: string | null | undefined, fallback = '/'): string {
240
407
  const path = target?.trim()
@@ -249,7 +416,7 @@ export function safeRedirect(target: string | null | undefined, fallback = '/'):
249
416
  return path
250
417
  }
251
418
 
252
- /** Returns true when `origin` matches the request's direct (or trusted forwarded) origin or `trustedOrigins`. */
419
+ /** Returns true when `origin` matches the request's trusted forwarded origin (or direct origin when none is forwarded) or `trustedOrigins`. */
253
420
  export function isTrustedOrigin(
254
421
  origin: string,
255
422
  request: Request,
@@ -259,9 +426,56 @@ export function isTrustedOrigin(
259
426
  ): boolean {
260
427
  if (!origin || origin === 'null')
261
428
  return false
262
- return origin === (requestUrl?.origin ?? new URL(request.url).origin)
263
- || origin === forwardedOrigin(request, trustProxy)
264
- || 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
+ export function expectedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?: URL): string {
434
+ return forwardedOrigin(request, trustProxy, requestUrl) ?? 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'
265
479
  }
266
480
 
267
481
  /** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
@@ -270,15 +484,15 @@ export function verifyOrigin(
270
484
  trustedOrigins?: ReadonlySet<string>,
271
485
  trustProxy: TrustProxy = false,
272
486
  requestUrl?: URL,
273
- ): { ok: true } | { ok: false, reason: string } {
274
- if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
487
+ ): { ok: true } | ({ ok: false } & OriginRefusal) {
488
+ if (SAFE_METHODS.has(request.method.toUpperCase()))
275
489
  return { ok: true }
276
490
 
277
491
  const origin = request.headers.get('origin')
278
492
  if (origin !== null) {
279
493
  if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy, requestUrl))
280
494
  return { ok: true }
281
- 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) }
282
496
  }
283
497
 
284
498
  const fetchSite = request.headers.get('sec-fetch-site')
@@ -288,11 +502,19 @@ export function verifyOrigin(
288
502
  return { ok: true }
289
503
  }
290
504
 
291
- export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
292
- if (options === false)
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))
293
508
  return undefined
294
- if (options?.csp === false)
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
+
513
+ export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
514
+ if (options === false || options?.csp === false)
295
515
  return undefined
516
+ if (typeof options?.csp === 'object')
517
+ return extendCsp(options.csp)
296
518
  return options?.csp ?? DEFAULT_CSP
297
519
  }
298
520
 
@@ -317,7 +539,12 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
317
539
  entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
318
540
  if (opts.permissionsPolicy !== false)
319
541
  entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
320
- if (opts.csp !== false)
321
- entries.push(['content-security-policy', opts.csp ?? DEFAULT_CSP])
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])
546
+ const csp = resolveCspPolicy(opts)
547
+ if (csp !== undefined)
548
+ entries.push(['content-security-policy', csp])
322
549
  return entries
323
550
  }
@@ -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,23 @@ 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
+ // 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
+ }
37
56
 
38
57
  const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
39
58
  const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>): void => {
@@ -42,16 +61,19 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
42
61
  routes[key] = handler
43
62
  }
44
63
 
64
+ if (healthPath !== undefined && healthHandler !== undefined)
65
+ registerServeRoute(healthPath, req => healthHandler(req))
66
+
45
67
  for (const [path, asset] of files.assetMap)
46
- registerServeRoute(path, req => isRead(req) ? files.serveFile(req, asset) : fetchReq(req))
68
+ registerServeRoute(path, req => isRead(req) ? serveFile(req, asset) : fetchReq(req))
47
69
 
48
70
  for (const [path, pub] of files.publicMap) {
49
71
  if (pluginRouter.match(literalPath(path)) === undefined)
50
- registerServeRoute(path, req => isRead(req) ? files.serveFile(req, pub) : fetchReq(req))
72
+ registerServeRoute(path, req => isRead(req) ? serveFile(req, pub) : fetchReq(req))
51
73
  }
52
74
 
53
75
  for (const [path, pre] of fastPrerenderedMap)
54
- registerServeRoute(path, req => isPlainRead(req) ? files.serveFile(req, pre) : fetchReq(req))
76
+ registerServeRoute(path, req => isPlainRead(req) ? serveFile(req, pre) : fetchReq(req))
55
77
 
56
78
  for (const [path, handler] of fastStaticPages)
57
79
  registerServeRoute(path, req => isPlainRead(req) ? runFast(handler, req, ipOf(req)) : fetchReq(req))
@@ -60,10 +82,12 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
60
82
  routes,
61
83
  fetch: fetchReq,
62
84
  error(err: Error) {
85
+ const fallbackReq = new Request('http://localhost/')
86
+ const reqId = resolveRequestId?.(fallbackReq)
63
87
  if ('code' in err && err.code === 'ENOENT')
64
- return fileGone()
65
- notifyError(err, new Request('http://localhost/'), 'route')
66
- return serverError()
88
+ return reqId !== undefined ? withRequestId(fileGone(), reqId) : fileGone()
89
+ notifyError(err, fallbackReq, 'route', reqId)
90
+ return reqId !== undefined ? withRequestId(serverError(), reqId) : serverError()
67
91
  },
68
92
  }
69
93
  }
@@ -5,6 +5,22 @@ export interface StandardSchemaIssue {
5
5
  readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined
6
6
  }
7
7
 
8
+ export type StandardJSONSchemaTarget =
9
+ | 'draft-2020-12'
10
+ | 'draft-07'
11
+ | 'openapi-3.0'
12
+ | ({} & string)
13
+
14
+ export interface StandardJSONSchemaOptions {
15
+ readonly target: StandardJSONSchemaTarget
16
+ readonly libraryOptions?: Record<string, unknown> | undefined
17
+ }
18
+
19
+ export interface StandardJSONSchemaConverter {
20
+ readonly input: (options: StandardJSONSchemaOptions) => Record<string, unknown>
21
+ readonly output?: ((options: StandardJSONSchemaOptions) => Record<string, unknown>) | undefined
22
+ }
23
+
8
24
  export interface StandardSchemaV1<Input = unknown, Output = Input> {
9
25
  readonly '~standard': {
10
26
  readonly version: 1
@@ -17,6 +33,7 @@ export interface StandardSchemaV1<Input = unknown, Output = Input> {
17
33
  | { readonly issues: ReadonlyArray<StandardSchemaIssue> }
18
34
  >
19
35
  readonly types?: { readonly input: Input, readonly output: Output } | undefined
36
+ readonly jsonSchema?: StandardJSONSchemaConverter | undefined
20
37
  }
21
38
  }
22
39