prunelle 0.0.0-stage → 0.5.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 (200) hide show
  1. package/llms.txt +152 -0
  2. package/package.json +59 -4
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/ambient.d.ts +6 -0
  7. package/src/attrs.ts +43 -0
  8. package/src/build/bundle.ts +657 -0
  9. package/src/build/carry.ts +57 -0
  10. package/src/build/client-entries.ts +107 -0
  11. package/src/build/client-plugin.ts +173 -0
  12. package/src/build/client-prune.ts +168 -0
  13. package/src/build/compile.ts +129 -0
  14. package/src/build/ecoindex.ts +229 -0
  15. package/src/build/files.ts +156 -0
  16. package/src/build/first-load.ts +164 -0
  17. package/src/build/graph.ts +247 -0
  18. package/src/build/index.ts +641 -0
  19. package/src/build/is-inside.ts +12 -0
  20. package/src/build/islands.ts +641 -0
  21. package/src/build/manifest.ts +325 -0
  22. package/src/build/output.ts +84 -0
  23. package/src/build/plugin-host.ts +278 -0
  24. package/src/build/precompress.ts +139 -0
  25. package/src/build/prerender.ts +232 -0
  26. package/src/build/render-rules.ts +205 -0
  27. package/src/build/report.ts +268 -0
  28. package/src/build/resolve.ts +52 -0
  29. package/src/build/routes.ts +342 -0
  30. package/src/build/server-entry.ts +38 -0
  31. package/src/build/static.ts +207 -0
  32. package/src/build/status-pages.ts +127 -0
  33. package/src/build/style-bundles.ts +526 -0
  34. package/src/cli/check-forms.ts +654 -0
  35. package/src/cli/check-links.ts +619 -0
  36. package/src/cli/check.ts +381 -0
  37. package/src/cli/commands.ts +345 -0
  38. package/src/cli/docs.ts +402 -0
  39. package/src/cli/index.ts +70 -0
  40. package/src/cli/inspect.ts +345 -0
  41. package/src/cli/mcp-tools.ts +480 -0
  42. package/src/cli/mcp.ts +205 -0
  43. package/src/cli/new.ts +41 -0
  44. package/src/cli/render.ts +261 -0
  45. package/src/cli/upgrade-names.ts +209 -0
  46. package/src/cli/upgrade.ts +354 -0
  47. package/src/compiler/analyze.ts +632 -0
  48. package/src/compiler/ast.ts +82 -0
  49. package/src/compiler/browser-globals.ts +127 -0
  50. package/src/compiler/cacheability.ts +592 -0
  51. package/src/compiler/compliance-rgaa.ts +502 -0
  52. package/src/compiler/compliance.ts +497 -0
  53. package/src/compiler/data-keys.ts +295 -0
  54. package/src/compiler/dev-source.ts +87 -0
  55. package/src/compiler/dom-attrs.ts +452 -0
  56. package/src/compiler/dom.ts +567 -0
  57. package/src/compiler/emit.ts +131 -0
  58. package/src/compiler/expr-context.ts +518 -0
  59. package/src/compiler/index.ts +8 -0
  60. package/src/compiler/interactivity.ts +366 -0
  61. package/src/compiler/mistakes.ts +499 -0
  62. package/src/compiler/node-env.ts +50 -0
  63. package/src/compiler/patch.ts +97 -0
  64. package/src/compiler/props.ts +511 -0
  65. package/src/compiler/scope.ts +607 -0
  66. package/src/compiler/server-only.ts +326 -0
  67. package/src/compiler/shared.ts +369 -0
  68. package/src/compiler/signal-reads.ts +242 -0
  69. package/src/compiler/slots.ts +227 -0
  70. package/src/compiler/ssr-helpers.ts +555 -0
  71. package/src/compiler/ssr-island.ts +90 -0
  72. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  73. package/src/compiler/ssr.ts +526 -0
  74. package/src/context.ts +165 -0
  75. package/src/dev/child.ts +30 -0
  76. package/src/dev/error-log.ts +151 -0
  77. package/src/dev/index.ts +258 -0
  78. package/src/dev/modules.ts +68 -0
  79. package/src/dev/open-editor.ts +204 -0
  80. package/src/dev/protocol.ts +22 -0
  81. package/src/dev/queue.ts +79 -0
  82. package/src/dev/reload.ts +159 -0
  83. package/src/dev/supervisor.ts +204 -0
  84. package/src/dev/watchers.ts +251 -0
  85. package/src/dom/action.ts +164 -0
  86. package/src/dom/attrs.ts +84 -0
  87. package/src/dom/claim.ts +120 -0
  88. package/src/dom/extras.ts +562 -0
  89. package/src/dom/index.ts +289 -0
  90. package/src/dom/island.ts +285 -0
  91. package/src/dom/loop.ts +450 -0
  92. package/src/dom/revive.ts +36 -0
  93. package/src/index.ts +22 -0
  94. package/src/jsx-runtime.ts +566 -0
  95. package/src/plugins/config.ts +86 -0
  96. package/src/plugins/context.ts +66 -0
  97. package/src/plugins/index.ts +14 -0
  98. package/src/plugins/load.ts +70 -0
  99. package/src/plugins/order.ts +111 -0
  100. package/src/plugins/public.ts +15 -0
  101. package/src/plugins/requires.ts +47 -0
  102. package/src/plugins/services.ts +97 -0
  103. package/src/plugins/types.ts +261 -0
  104. package/src/reactivity/graph.ts +249 -0
  105. package/src/reactivity/index.ts +533 -0
  106. package/src/reactivity/selector.ts +51 -0
  107. package/src/reactivity/store.ts +208 -0
  108. package/src/server/action-protect.ts +198 -0
  109. package/src/server/action-registry.ts +78 -0
  110. package/src/server/action.ts +530 -0
  111. package/src/server/app-entry.ts +23 -0
  112. package/src/server/assets.ts +168 -0
  113. package/src/server/compress.ts +642 -0
  114. package/src/server/consent.ts +253 -0
  115. package/src/server/cookies.ts +139 -0
  116. package/src/server/document.ts +271 -0
  117. package/src/server/env.ts +33 -0
  118. package/src/server/errors.ts +391 -0
  119. package/src/server/form-schema.ts +343 -0
  120. package/src/server/health.ts +244 -0
  121. package/src/server/http.ts +538 -0
  122. package/src/server/index.ts +586 -0
  123. package/src/server/lifecycle.ts +75 -0
  124. package/src/server/loader.ts +123 -0
  125. package/src/server/page.ts +107 -0
  126. package/src/server/param-matchers.ts +112 -0
  127. package/src/server/plugin-host.ts +265 -0
  128. package/src/server/prerendered.ts +71 -0
  129. package/src/server/public.ts +19 -0
  130. package/src/server/rate-limit.ts +156 -0
  131. package/src/server/region.ts +96 -0
  132. package/src/server/request-body.ts +27 -0
  133. package/src/server/request-path.ts +73 -0
  134. package/src/server/request-scope.ts +22 -0
  135. package/src/server/route-cache.ts +423 -0
  136. package/src/server/route-table.ts +410 -0
  137. package/src/server/router.ts +261 -0
  138. package/src/server/routing.ts +472 -0
  139. package/src/server/security.ts +499 -0
  140. package/src/server/serve-handlers.ts +83 -0
  141. package/src/server/served-file.ts +128 -0
  142. package/src/server/standard-schema.ts +87 -0
  143. package/src/server/start.ts +143 -0
  144. package/src/server/static-dir.ts +220 -0
  145. package/src/server/stream.ts +211 -0
  146. package/src/ssr/context.ts +383 -0
  147. package/src/ssr/index.ts +596 -0
  148. package/src/ssr/navigation.ts +96 -0
  149. package/src/ssr/region.ts +183 -0
  150. package/src/style.ts +33 -0
  151. package/src/test/browser.ts +192 -0
  152. package/src/test/index.ts +191 -0
  153. package/src/ts-plugin/diagnostics.ts +378 -0
  154. package/src/ts-plugin/fixes.ts +364 -0
  155. package/src/ts-plugin/index.ts +194 -0
  156. package/src/unrenderable.ts +35 -0
  157. package/templates/_shared/AGENTS.md +10 -0
  158. package/templates/_shared/CLAUDE.md +1 -0
  159. package/templates/_shared/gitignore +3 -0
  160. package/templates/_shared/mcp.json +11 -0
  161. package/templates/_shared/public/robots.txt +2 -0
  162. package/templates/_shared/src/routes/legal.tsx +13 -0
  163. package/templates/_shared/tsconfig.json +25 -0
  164. package/templates/app/.env.example +4 -0
  165. package/templates/app/package.json +21 -0
  166. package/templates/app/prunelle.config.ts +11 -0
  167. package/templates/app/src/auth.ts +14 -0
  168. package/templates/app/src/routes/_layout.tsx +32 -0
  169. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  171. package/templates/app/src/routes/index.tsx +15 -0
  172. package/templates/app/src/routes/login.tsx +34 -0
  173. package/templates/app/src/styles/app.css +7 -0
  174. package/templates/app/tests/app.test.ts +32 -0
  175. package/templates/blog/content/posts/welcome.md +9 -0
  176. package/templates/blog/package.json +22 -0
  177. package/templates/blog/prunelle.config.ts +23 -0
  178. package/templates/blog/src/posts.ts +26 -0
  179. package/templates/blog/src/routes/_layout.tsx +20 -0
  180. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  181. package/templates/blog/src/routes/index.tsx +33 -0
  182. package/templates/blog/src/styles/app.css +10 -0
  183. package/templates/fullstack/package.json +19 -0
  184. package/templates/fullstack/prunelle.config.ts +6 -0
  185. package/templates/fullstack/src/actions/greet.ts +19 -0
  186. package/templates/fullstack/src/components/Counter.tsx +10 -0
  187. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  188. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  189. package/templates/fullstack/src/routes/api/health.ts +5 -0
  190. package/templates/fullstack/src/routes/index.tsx +13 -0
  191. package/templates/fullstack/src/styles/app.css +29 -0
  192. package/templates/fullstack/tests/app.test.ts +37 -0
  193. package/templates/minimal/package.json +19 -0
  194. package/templates/minimal/prunelle.config.ts +6 -0
  195. package/templates/minimal/src/components/Counter.tsx +10 -0
  196. package/templates/minimal/src/routes/_layout.tsx +14 -0
  197. package/templates/minimal/src/routes/index.tsx +11 -0
  198. package/templates/minimal/src/styles/app.css +22 -0
  199. package/ts-plugin.cjs +4277 -0
  200. package/README.md +0 -3
@@ -0,0 +1,499 @@
1
+ // Built-in security basics: CSRF/Origin verification on state-changing requests + safe default headers + strict CSP hashes.
2
+
3
+
4
+ import { PRUNELLE_STREAM_SCRIPT } from '../ssr/context'
5
+ import { PRUNELLE_ISLAND_STYLE, PRUNELLE_SUSPENSE_STYLE } from '../ssr/index'
6
+ import { cspSha256 } from '../ssr/navigation'
7
+
8
+ export const PRUNELLE_ISLAND_STYLE_HASH = cspSha256(PRUNELLE_ISLAND_STYLE)
9
+ export const PRUNELLE_SUSPENSE_STYLE_HASH = cspSha256(PRUNELLE_SUSPENSE_STYLE)
10
+ export const PRUNELLE_STREAM_SCRIPT_HASH = cspSha256(PRUNELLE_STREAM_SCRIPT)
11
+
12
+ const STYLE_HASH_CACHE_SIZE = 256
13
+ const styleHashCache = new Map<string, string>()
14
+
15
+ // Hashes stay cached by content with LRU eviction so a layout's fixed block costs one SHA-256 per process.
16
+ function styleHash(content: string): string {
17
+ let hash = styleHashCache.get(content)
18
+ if (hash !== undefined) {
19
+ styleHashCache.delete(content)
20
+ styleHashCache.set(content, hash)
21
+ return hash
22
+ }
23
+ hash = cspSha256(content)
24
+ if (styleHashCache.size >= STYLE_HASH_CACHE_SIZE)
25
+ styleHashCache.delete(styleHashCache.keys().next().value!)
26
+ styleHashCache.set(content, hash)
27
+ return hash
28
+ }
29
+
30
+ /** Deduplicated CSP SHA-256 hashes of trusted inline `<style>` contents, leaving out prunelle's island and Suspense styles. */
31
+ export function styleHashesOf(styles: Iterable<string> | undefined): string[] {
32
+ if (styles === undefined)
33
+ return []
34
+ const hashes: string[] = []
35
+ for (const content of styles) {
36
+ if (content === PRUNELLE_ISLAND_STYLE || content === PRUNELLE_SUSPENSE_STYLE)
37
+ continue
38
+ const hash = styleHash(content)
39
+ if (!hashes.includes(hash))
40
+ hashes.push(hash)
41
+ }
42
+ return hashes
43
+ }
44
+
45
+ // A regex finds the next tag ~10x faster than `indexOf('<style')`, which stalls on every `<span` and `<strong` of a large page.
46
+ const STYLE_OPEN_RE = /<style(?=[\s>/])/gi
47
+ const STYLE_CLOSE_RE = /<\/style(?=[\s>])/gi
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
+
70
+ /** CSP hashes of the app's own `<style>` blocks in `html`, leaving out prunelle's island and Suspense styles (hashed apart). */
71
+ export function inlineStyleHashes(html: string): string[] {
72
+ const hashes: string[] = []
73
+ STYLE_OPEN_RE.lastIndex = 0
74
+ let open = STYLE_OPEN_RE.exec(html)
75
+ while (open !== null) {
76
+ const tag = findStyleTagEnd(html, open.index + 6)
77
+ if (tag === undefined)
78
+ break
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
85
+ const close = STYLE_CLOSE_RE.exec(html)
86
+ if (close === null)
87
+ break
88
+ const content = html.slice(tag.end + 1, close.index)
89
+ if (content !== PRUNELLE_ISLAND_STYLE && content !== PRUNELLE_SUSPENSE_STYLE) {
90
+ const hash = styleHash(content)
91
+ if (!hashes.includes(hash))
92
+ hashes.push(hash)
93
+ }
94
+ STYLE_OPEN_RE.lastIndex = close.index + 7
95
+ open = STYLE_OPEN_RE.exec(html)
96
+ }
97
+ return hashes
98
+ }
99
+
100
+ interface ParsedCsp {
101
+ order: string[]
102
+ directives: Map<string, string[]>
103
+ }
104
+
105
+ function parseCsp(csp: string): ParsedCsp {
106
+ const directives = new Map<string, string[]>()
107
+ const order: string[] = []
108
+ for (const part of csp.split(';')) {
109
+ const trimmed = part.trim()
110
+ if (!trimmed)
111
+ continue
112
+ const tokens = trimmed.split(/\s+/)
113
+ const name = tokens[0]!.toLowerCase()
114
+ if (!directives.has(name)) {
115
+ order.push(name)
116
+ directives.set(name, tokens.slice(1))
117
+ }
118
+ }
119
+ return { order, directives }
120
+ }
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
141
+ const defaultSrc = directives.get('default-src') ?? ["'self'"]
142
+ const addHashes = (dirName: string, hashes: readonly string[]) => {
143
+ if (hashes.length === 0)
144
+ return
145
+ let tokens = directives.get(dirName)
146
+ if (tokens === undefined) {
147
+ tokens = [...defaultSrc]
148
+ directives.set(dirName, tokens)
149
+ order.push(dirName)
150
+ }
151
+ if (tokens.includes("'unsafe-inline'"))
152
+ return
153
+ const noneIdx = tokens.indexOf("'none'")
154
+ if (noneIdx !== -1)
155
+ tokens.splice(noneIdx, 1)
156
+ for (const h of hashes) {
157
+ if (!tokens.includes(h))
158
+ tokens.push(h)
159
+ }
160
+ }
161
+
162
+ addHashes('style-src', styleHashes)
163
+ if (directives.has('style-src-elem'))
164
+ addHashes('style-src-elem', styleHashes)
165
+ addHashes('script-src', scriptHashes)
166
+ if (directives.has('script-src-elem'))
167
+ addHashes('script-src-elem', scriptHashes)
168
+
169
+ return serializeCsp(parsed)
170
+ }
171
+
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
+ export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
174
+ export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
175
+
176
+ export type CspDirectiveValue = string | readonly string[]
177
+
178
+ export interface KnownCspDirectives {
179
+ 'default-src'?: CspDirectiveValue | undefined
180
+ 'script-src'?: CspDirectiveValue | undefined
181
+ 'script-src-elem'?: CspDirectiveValue | undefined
182
+ 'script-src-attr'?: CspDirectiveValue | undefined
183
+ 'style-src'?: CspDirectiveValue | undefined
184
+ 'style-src-elem'?: CspDirectiveValue | undefined
185
+ 'style-src-attr'?: CspDirectiveValue | undefined
186
+ 'img-src'?: CspDirectiveValue | undefined
187
+ 'font-src'?: CspDirectiveValue | undefined
188
+ 'connect-src'?: CspDirectiveValue | undefined
189
+ 'media-src'?: CspDirectiveValue | undefined
190
+ 'object-src'?: CspDirectiveValue | undefined
191
+ 'frame-src'?: CspDirectiveValue | undefined
192
+ 'child-src'?: CspDirectiveValue | undefined
193
+ 'worker-src'?: CspDirectiveValue | undefined
194
+ 'manifest-src'?: CspDirectiveValue | undefined
195
+ 'base-uri'?: CspDirectiveValue | undefined
196
+ 'form-action'?: CspDirectiveValue | undefined
197
+ 'frame-ancestors'?: CspDirectiveValue | undefined
198
+ 'sandbox'?: CspDirectiveValue | undefined
199
+ 'report-to'?: CspDirectiveValue | undefined
200
+ 'report-uri'?: CspDirectiveValue | undefined
201
+ 'upgrade-insecure-requests'?: CspDirectiveValue | undefined
202
+ }
203
+
204
+ export type CspDirectives = Readonly<KnownCspDirectives & Record<string, CspDirectiveValue | undefined>>
205
+
206
+ const isFetchDirective = (name: string): boolean =>
207
+ name.endsWith('-src') || name.endsWith('-src-elem') || name.endsWith('-src-attr')
208
+
209
+ function splitCspTokens(value: CspDirectiveValue): string[] {
210
+ const parts = typeof value === 'string' ? [value] : value
211
+ const tokens: string[] = []
212
+ for (const part of parts) {
213
+ for (const token of part.split(/\s+/)) {
214
+ if (token.length > 0 && !tokens.includes(token))
215
+ tokens.push(token)
216
+ }
217
+ }
218
+ return tokens
219
+ }
220
+
221
+ function mergeCspDirective(parsed: ParsedCsp, name: string, tokens: readonly string[]): void {
222
+ const { order, directives } = parsed
223
+ const existing = directives.get(name)
224
+ if (existing === undefined) {
225
+ order.push(name)
226
+ if (tokens.length === 0) {
227
+ directives.set(name, [])
228
+ }
229
+ else if (tokens.includes("'none'")) {
230
+ directives.set(name, ["'none'"])
231
+ }
232
+ else if (isFetchDirective(name)) {
233
+ const seeded = (directives.get('default-src') ?? ["'self'"]).filter(t => t !== "'none'")
234
+ for (const token of tokens) {
235
+ if (!seeded.includes(token))
236
+ seeded.push(token)
237
+ }
238
+ directives.set(name, seeded)
239
+ }
240
+ else {
241
+ directives.set(name, [...tokens])
242
+ }
243
+ return
244
+ }
245
+ if (tokens.length === 0)
246
+ return
247
+ if (tokens.includes("'none'")) {
248
+ directives.set(name, ["'none'"])
249
+ return
250
+ }
251
+ const noneIdx = existing.indexOf("'none'")
252
+ if (noneIdx !== -1)
253
+ existing.splice(noneIdx, 1)
254
+ for (const token of tokens) {
255
+ if (!existing.includes(token))
256
+ existing.push(token)
257
+ }
258
+ }
259
+
260
+ /** Extends a Content-Security-Policy (default: `DEFAULT_CSP`) by merging additional sources into one or more directives. */
261
+ export function extendCsp(extra: CspDirectives, base = DEFAULT_CSP): string {
262
+ const parsed = parseCsp(base)
263
+ for (const [rawName, rawValue] of Object.entries(extra)) {
264
+ if (rawValue === undefined)
265
+ continue
266
+ const name = rawName.trim().toLowerCase()
267
+ if (name.length === 0)
268
+ continue
269
+ mergeCspDirective(parsed, name, splitCspTokens(rawValue))
270
+ }
271
+ return serializeCsp(parsed)
272
+ }
273
+
274
+ // Directives browsers ignore (and log an error for) when delivered via <meta http-equiv="Content-Security-Policy"> (W3C CSP3 §4.2.1).
275
+ const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'sandbox'])
276
+ const EXISTING_META_CSP_RE = /<meta\b[^>]*\bhttp-equiv\s*=\s*(?:"content-security-policy"|'content-security-policy'|content-security-policy\b)/i
277
+ const META_CHARSET_RE = /<meta\b[^>]*\bcharset\s*=\s*[^>]*>/i
278
+ const HEAD_OPEN_RE = /<head\b[^>]*>/i
279
+ const ESC_DOUBLE_ATTR_RE = /[&"<>]/g
280
+ const DOUBLE_ATTR_MAP: Record<string, string> = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }
281
+
282
+ /** Strips directives browsers reject in a `<meta http-equiv="Content-Security-Policy">` element. */
283
+ export function toMetaCsp(csp: string): string {
284
+ const parsed = parseCsp(csp)
285
+ parsed.order = parsed.order.filter(name => !META_CSP_IGNORED.has(name))
286
+ return serializeCsp(parsed)
287
+ }
288
+
289
+ /** Injects `<meta http-equiv="Content-Security-Policy">` at the top of `<head>` for static HTML exports. */
290
+ export function injectMetaCsp(html: string, csp: string | null | undefined): string {
291
+ if (!csp)
292
+ return html
293
+ const metaCsp = toMetaCsp(csp)
294
+ if (metaCsp.length === 0)
295
+ return html
296
+ const headMatch = HEAD_OPEN_RE.exec(html)
297
+ if (headMatch === null)
298
+ return html
299
+ const headEnd = headMatch.index + headMatch[0].length
300
+ const headCloseIdx = html.toLowerCase().indexOf('</head>', headEnd)
301
+ const headSlice = headCloseIdx === -1 ? html.slice(headEnd) : html.slice(headEnd, headCloseIdx)
302
+ if (EXISTING_META_CSP_RE.test(headSlice))
303
+ return html
304
+ const charsetMatch = META_CHARSET_RE.exec(headSlice)
305
+ const insertAt = charsetMatch !== null ? headEnd + charsetMatch.index + charsetMatch[0].length : headEnd
306
+ const escaped = metaCsp.replace(ESC_DOUBLE_ATTR_RE, ch => DOUBLE_ATTR_MAP[ch]!)
307
+ return `${html.slice(0, insertAt)}<meta http-equiv="Content-Security-Policy" content="${escaped}">${html.slice(insertAt)}`
308
+ }
309
+
310
+ export interface SecurityHeadersOptions {
311
+ frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
312
+ referrerPolicy?: string | false | undefined
313
+ contentTypeOptions?: boolean | undefined
314
+ permissionsPolicy?: string | false | undefined
315
+ csp?: string | CspDirectives | false | undefined
316
+ hsts?: string | boolean | undefined
317
+ }
318
+
319
+ const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
320
+
321
+ /** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
322
+ export type TrustProxy = boolean | number
323
+
324
+ function proxyHops(trustProxy: TrustProxy): number {
325
+ if (trustProxy === true)
326
+ return 1
327
+ if (trustProxy === false || !Number.isFinite(trustProxy))
328
+ return 0
329
+ return Math.max(0, Math.floor(trustProxy))
330
+ }
331
+
332
+ // Proxies append to X-Forwarded-*, so only the entries the trusted hops wrote count: the one `hops` from the right.
333
+ // When fewer than `hops` entries exist, return undefined rather than trusting a client-supplied leftmost entry.
334
+ function forwardedValue(request: Request, header: string, trustProxy: TrustProxy): string | undefined {
335
+ const hops = proxyHops(trustProxy)
336
+ if (hops === 0)
337
+ return undefined
338
+ const raw = request.headers.get(header)
339
+ if (raw === null || raw.length === 0)
340
+ return undefined
341
+ let end = raw.length
342
+ let seen = 0
343
+ while (end > 0) {
344
+ const comma = raw.lastIndexOf(',', end - 1)
345
+ let start = comma + 1
346
+ let stop = end
347
+ while (start < stop && raw.charCodeAt(start) <= 32)
348
+ start++
349
+ while (stop > start && raw.charCodeAt(stop - 1) <= 32)
350
+ stop--
351
+ if (start < stop) {
352
+ seen++
353
+ if (seen === hops)
354
+ return start === 0 && stop === raw.length ? raw : raw.slice(start, stop)
355
+ }
356
+ if (comma === -1)
357
+ break
358
+ end = comma
359
+ }
360
+ return undefined
361
+ }
362
+
363
+ function forwardedOrigin(request: Request, trustProxy: TrustProxy): string | undefined {
364
+ const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase()
365
+ if (proto !== 'http' && proto !== 'https')
366
+ return undefined
367
+ const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim()
368
+ if (!host)
369
+ return undefined
370
+ try {
371
+ const origin = new URL(`${proto}://${host}`).origin
372
+ return origin === 'null' ? undefined : origin
373
+ }
374
+ catch {
375
+ return undefined
376
+ }
377
+ }
378
+
379
+ /** Returns true when the request arrived over HTTPS (directly, or via X-Forwarded-Proto when `trustProxy` is true). */
380
+ export function isHttpsRequest(request: Request, trustProxy: TrustProxy = false): boolean {
381
+ if (request.url.startsWith('https:'))
382
+ return true
383
+ const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)
384
+ if (proto === undefined || proto.length !== 5)
385
+ return false
386
+ return proto === 'https' || proto.toLowerCase() === 'https'
387
+ }
388
+
389
+ /** Extracts the client IP from the trusted proxies' X-Forwarded-For header, or falls back to the direct socket IP. */
390
+ export function getClientIp(request: Request, trustProxy: TrustProxy = false, remoteIp?: string): string | undefined {
391
+ if (proxyHops(trustProxy) > 0) {
392
+ const forwarded = forwardedValue(request, 'x-forwarded-for', trustProxy)
393
+ if (forwarded)
394
+ return forwarded
395
+ }
396
+ return remoteIp || undefined
397
+ }
398
+
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
+ /** `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
+ export function safeRedirect(target: string | null | undefined, fallback = '/'): string {
416
+ const path = target?.trim()
417
+ if (path === undefined || !path.startsWith('/') || path.startsWith('//') || path.includes('\\'))
418
+ return fallback
419
+ // CR, LF and NUL split the Location header, and a browser drops a tab or newline from a URL, which turns `/\t/host` into `//host`.
420
+ for (let i = 0; i < path.length; i++) {
421
+ const code = path.charCodeAt(i)
422
+ if (code < 0x20 || code === 0x7F)
423
+ return fallback
424
+ }
425
+ return path
426
+ }
427
+
428
+ /** Returns true when `origin` matches the request's trusted forwarded origin (or direct origin when none is forwarded) or `trustedOrigins`. */
429
+ export function isTrustedOrigin(
430
+ origin: string,
431
+ request: Request,
432
+ trustedOrigins?: ReadonlySet<string>,
433
+ trustProxy: TrustProxy = false,
434
+ requestUrl?: URL,
435
+ ): boolean {
436
+ if (!origin || origin === 'null')
437
+ return false
438
+ const expectedOrigin = forwardedOrigin(request, trustProxy) ?? requestUrl?.origin ?? new URL(request.url).origin
439
+ return origin === expectedOrigin || trustedOrigins?.has(origin) === true
440
+ }
441
+
442
+ /** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
443
+ export function verifyOrigin(
444
+ request: Request,
445
+ trustedOrigins?: ReadonlySet<string>,
446
+ trustProxy: TrustProxy = false,
447
+ requestUrl?: URL,
448
+ ): { ok: true } | { ok: false, reason: string } {
449
+ if (SAFE_METHODS.has(request.method.toUpperCase()))
450
+ return { ok: true }
451
+
452
+ const origin = request.headers.get('origin')
453
+ if (origin !== null) {
454
+ if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy, requestUrl))
455
+ return { ok: true }
456
+ return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}` }
457
+ }
458
+
459
+ const fetchSite = request.headers.get('sec-fetch-site')
460
+ if (fetchSite !== null && fetchSite !== 'same-origin' && fetchSite !== 'none')
461
+ return { ok: false, reason: `Cross-site request blocked: sec-fetch-site=${fetchSite}` }
462
+
463
+ return { ok: true }
464
+ }
465
+
466
+ export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
467
+ if (options === false || options?.csp === false)
468
+ return undefined
469
+ if (typeof options?.csp === 'object')
470
+ return extendCsp(options.csp)
471
+ return options?.csp ?? DEFAULT_CSP
472
+ }
473
+
474
+ export function resolveHstsValue(options: SecurityHeadersOptions | false | undefined): string | undefined {
475
+ if (options === false)
476
+ return undefined
477
+ if (options?.hsts === false)
478
+ return undefined
479
+ return typeof options?.hsts === 'string' ? options.hsts : DEFAULT_HSTS
480
+ }
481
+
482
+ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined): readonly [string, string][] {
483
+ if (options === false)
484
+ return []
485
+ const opts = options ?? {}
486
+ const entries: [string, string][] = []
487
+ if (opts.contentTypeOptions ?? true)
488
+ entries.push(['x-content-type-options', 'nosniff'])
489
+ if (opts.frameOptions !== false)
490
+ entries.push(['x-frame-options', opts.frameOptions ?? 'SAMEORIGIN'])
491
+ if (opts.referrerPolicy !== false)
492
+ entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
493
+ if (opts.permissionsPolicy !== false)
494
+ entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
495
+ const csp = resolveCspPolicy(opts)
496
+ if (csp !== undefined)
497
+ entries.push(['content-security-policy', csp])
498
+ return entries
499
+ }
@@ -0,0 +1,83 @@
1
+ // The handlers `Bun.serve()` runs for an app: its native route table of files and fast pages, its fetch fallback and its error answer. `serve()` starts a server with them, `reloadInto()` swaps them into one already listening.
2
+
3
+ import type { createAssets, ServedFile } from './assets'
4
+ import type { NotifyError } from './errors'
5
+ import type { RequestIdResolver } from './health'
6
+ import type { PrunelleServer } from './http'
7
+ import type { RequestPath } from './request-path'
8
+ import type { FastHandler } from './routing'
9
+ import { ACTION_ERROR_COOKIE } from './action'
10
+ import { withRequestId } from './health'
11
+ import { hasRegionHeader } from './region'
12
+ import { literalPath } from './request-path'
13
+ import { toBunRouteKey } from './routing'
14
+
15
+ export interface ServeHandlerSources {
16
+ files: ReturnType<typeof createAssets>
17
+ fastPrerenderedMap: ReadonlyMap<string, ServedFile>
18
+ fastStaticPages: ReadonlyMap<string, FastHandler>
19
+ pluginRouter: { match: (path: RequestPath) => unknown }
20
+ healthPath?: string | undefined
21
+ healthHandler?: ((request: Request, requestId?: string) => Response | Promise<Response>) | undefined
22
+ resolveRequestId?: RequestIdResolver | undefined
23
+ /** Answers through the app's whole pipeline, with the request's timeout turned off by `disableTimeout` for a long-lived stream. */
24
+ runRequest: (req: Request, remoteIp: string | undefined, disableTimeout: () => void) => Promise<Response>
25
+ runFast: (handler: FastHandler, req: Request, remoteIp: string | undefined) => Response | Promise<Response>
26
+ notifyError: NotifyError
27
+ serverError: () => Response
28
+ fileGone: () => Response
29
+ }
30
+
31
+ export const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
32
+
33
+ export const hasActionErrorCookie = (request: Request): boolean => (request.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
34
+
35
+ // A read the pre-rendered and fast static paths may answer: nothing to flash back to the page, and not a partial <Region> request.
36
+ export const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request) && !hasRegionHeader(request)
37
+
38
+ export function serveHandlers(server: () => PrunelleServer | undefined, sources: ServeHandlerSources) {
39
+ const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone } = sources
40
+ const ipOf = (req: Request) => server()?.requestIP(req)?.address
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)))
46
+
47
+ const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
48
+ const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>): void => {
49
+ const key = toBunRouteKey(path)
50
+ if (key !== undefined && !(key in routes))
51
+ routes[key] = handler
52
+ }
53
+
54
+ if (healthPath !== undefined && healthHandler !== undefined)
55
+ registerServeRoute(healthPath, req => healthHandler(req))
56
+
57
+ for (const [path, asset] of files.assetMap)
58
+ registerServeRoute(path, req => isRead(req) ? serveFile(req, asset) : fetchReq(req))
59
+
60
+ for (const [path, pub] of files.publicMap) {
61
+ if (pluginRouter.match(literalPath(path)) === undefined)
62
+ registerServeRoute(path, req => isRead(req) ? serveFile(req, pub) : fetchReq(req))
63
+ }
64
+
65
+ for (const [path, pre] of fastPrerenderedMap)
66
+ registerServeRoute(path, req => isPlainRead(req) ? serveFile(req, pre) : fetchReq(req))
67
+
68
+ for (const [path, handler] of fastStaticPages)
69
+ registerServeRoute(path, req => isPlainRead(req) ? runFast(handler, req, ipOf(req)) : fetchReq(req))
70
+
71
+ return {
72
+ routes,
73
+ fetch: fetchReq,
74
+ error(err: Error) {
75
+ const fallbackReq = new Request('http://localhost/')
76
+ const reqId = resolveRequestId?.(fallbackReq)
77
+ if ('code' in err && err.code === 'ENOENT')
78
+ return reqId !== undefined ? withRequestId(fileGone(), reqId) : fileGone()
79
+ notifyError(err, fallbackReq, 'route', reqId)
80
+ return reqId !== undefined ? withRequestId(serverError(), reqId) : serverError()
81
+ },
82
+ }
83
+ }