prunelle 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/llms.txt +245 -0
- package/package.json +62 -4
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +43 -0
- package/src/build/bundle.ts +661 -0
- package/src/build/byte-size.ts +11 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +175 -0
- package/src/build/client-prune.ts +168 -0
- package/src/build/compile.ts +130 -0
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +171 -0
- package/src/build/first-load.ts +235 -0
- package/src/build/graph.ts +237 -0
- package/src/build/index.ts +678 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +452 -0
- package/src/build/manifest.ts +204 -0
- package/src/build/output.ts +81 -0
- package/src/build/plugin-host.ts +294 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +288 -0
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +290 -0
- package/src/build/resolve.ts +52 -0
- package/src/build/routes.ts +342 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +209 -0
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +409 -0
- package/src/cli/commands.ts +372 -0
- package/src/cli/docs.ts +403 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +406 -0
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +52 -0
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +367 -0
- package/src/compiler/analyze.ts +651 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +250 -0
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +653 -0
- package/src/compiler/data-keys.ts +302 -0
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +452 -0
- package/src/compiler/dom.ts +641 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +587 -0
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +520 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +511 -0
- package/src/compiler/scope.ts +635 -0
- package/src/compiler/server-only.ts +365 -0
- package/src/compiler/shared.ts +397 -0
- package/src/compiler/signal-reads.ts +246 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +69 -0
- package/src/compiler/ssr.ts +525 -0
- package/src/context.ts +199 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +268 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +24 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +159 -0
- package/src/dev/supervisor.ts +212 -0
- package/src/dev/watchers.ts +276 -0
- package/src/dom/action.ts +187 -0
- package/src/dom/attrs.ts +84 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +579 -0
- package/src/dom/index.ts +329 -0
- package/src/dom/island.ts +318 -0
- package/src/dom/loop.ts +484 -0
- package/src/dom/revive.ts +36 -0
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +92 -0
- package/src/plugins/context.ts +109 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +90 -0
- package/src/plugins/order.ts +148 -0
- package/src/plugins/public.ts +15 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +119 -0
- package/src/plugins/types.ts +278 -0
- package/src/reactivity/graph.ts +259 -0
- package/src/reactivity/index.ts +541 -0
- package/src/reactivity/selector.ts +78 -0
- package/src/reactivity/store.ts +252 -0
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +511 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +168 -0
- package/src/server/compress.ts +646 -0
- package/src/server/consent.ts +290 -0
- package/src/server/cookies.ts +153 -0
- package/src/server/document.ts +286 -0
- package/src/server/env.ts +47 -0
- package/src/server/errors.ts +396 -0
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +588 -0
- package/src/server/index.ts +615 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +131 -0
- package/src/server/page.ts +122 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +267 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +20 -0
- package/src/server/rate-limit.ts +199 -0
- package/src/server/region.ts +96 -0
- package/src/server/request-body.ts +27 -0
- package/src/server/request-path.ts +73 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +424 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +388 -0
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +550 -0
- package/src/server/serve-handlers.ts +93 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +104 -0
- package/src/server/start.ts +143 -0
- package/src/server/static-dir.ts +246 -0
- package/src/server/stream.ts +233 -0
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +399 -0
- package/src/ssr/index.ts +624 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +192 -0
- package/src/style.ts +96 -0
- package/src/test/browser.ts +201 -0
- package/src/test/index.ts +262 -0
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/src/unrenderable.ts +35 -0
- package/templates/_shared/AGENTS.md +10 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/gitignore +8 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +22 -0
- package/templates/_shared/tsconfig.json +25 -0
- package/templates/app/.env.example +8 -0
- package/templates/app/package.json +22 -0
- package/templates/app/prunelle.config.ts +13 -0
- package/templates/app/src/auth.ts +12 -0
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +40 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +47 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +53 -0
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +14 -0
- package/templates/app/tests/app.test.ts +73 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/package.json +22 -0
- package/templates/blog/prunelle.config.ts +23 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +25 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +33 -0
- package/templates/blog/src/styles/app.css +15 -0
- package/templates/fullstack/package.json +19 -0
- package/templates/fullstack/prunelle.config.ts +6 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +28 -0
- package/templates/fullstack/src/routes/_layout.tsx +18 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +39 -0
- package/templates/fullstack/tests/app.test.ts +37 -0
- package/templates/minimal/package.json +19 -0
- package/templates/minimal/prunelle.config.ts +6 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +18 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +32 -0
- package/ts-plugin.cjs +4277 -0
- package/README.md +0 -3
|
@@ -0,0 +1,550 @@
|
|
|
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=(), 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> = { '&': '&', '"': '"', '<': '<', '>': '>' }
|
|
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
|
+
}
|
|
311
|
+
|
|
312
|
+
export interface SecurityHeadersOptions {
|
|
313
|
+
frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
|
|
314
|
+
referrerPolicy?: string | false | undefined
|
|
315
|
+
contentTypeOptions?: boolean | undefined
|
|
316
|
+
permissionsPolicy?: string | false | undefined
|
|
317
|
+
csp?: string | CspDirectives | false | undefined
|
|
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
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
|
|
326
|
+
|
|
327
|
+
/** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
|
|
328
|
+
export type TrustProxy = boolean | number
|
|
329
|
+
|
|
330
|
+
function proxyHops(trustProxy: TrustProxy): number {
|
|
331
|
+
if (trustProxy === true)
|
|
332
|
+
return 1
|
|
333
|
+
if (trustProxy === false || !Number.isFinite(trustProxy))
|
|
334
|
+
return 0
|
|
335
|
+
return Math.max(0, Math.floor(trustProxy))
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// Proxies append to X-Forwarded-*, so only the entries the trusted hops wrote count: the one `hops` from the right.
|
|
339
|
+
// When fewer than `hops` entries exist, return undefined rather than trusting a client-supplied leftmost entry.
|
|
340
|
+
function forwardedValue(request: Request, header: string, trustProxy: TrustProxy): string | undefined {
|
|
341
|
+
const hops = proxyHops(trustProxy)
|
|
342
|
+
if (hops === 0)
|
|
343
|
+
return undefined
|
|
344
|
+
const raw = request.headers.get(header)
|
|
345
|
+
if (raw === null || raw.length === 0)
|
|
346
|
+
return undefined
|
|
347
|
+
let end = raw.length
|
|
348
|
+
let seen = 0
|
|
349
|
+
while (end > 0) {
|
|
350
|
+
const comma = raw.lastIndexOf(',', end - 1)
|
|
351
|
+
let start = comma + 1
|
|
352
|
+
let stop = end
|
|
353
|
+
while (start < stop && raw.charCodeAt(start) <= 32)
|
|
354
|
+
start++
|
|
355
|
+
while (stop > start && raw.charCodeAt(stop - 1) <= 32)
|
|
356
|
+
stop--
|
|
357
|
+
if (start < stop) {
|
|
358
|
+
seen++
|
|
359
|
+
if (seen === hops)
|
|
360
|
+
return start === 0 && stop === raw.length ? raw : raw.slice(start, stop)
|
|
361
|
+
}
|
|
362
|
+
if (comma === -1)
|
|
363
|
+
break
|
|
364
|
+
end = comma
|
|
365
|
+
}
|
|
366
|
+
return undefined
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function forwardedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?: URL): string | undefined {
|
|
370
|
+
const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase()
|
|
371
|
+
if (proto !== 'http' && proto !== 'https')
|
|
372
|
+
return undefined
|
|
373
|
+
const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim() || (requestUrl ?? new URL(request.url)).host
|
|
374
|
+
if (!host)
|
|
375
|
+
return undefined
|
|
376
|
+
try {
|
|
377
|
+
const origin = new URL(`${proto}://${host}`).origin
|
|
378
|
+
return origin === 'null' ? undefined : origin
|
|
379
|
+
}
|
|
380
|
+
catch {
|
|
381
|
+
return undefined
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** Returns true when the request arrived over HTTPS (directly, or via X-Forwarded-Proto when `trustProxy` is true). */
|
|
386
|
+
export function isHttpsRequest(request: Request, trustProxy: TrustProxy = false): boolean {
|
|
387
|
+
if (request.url.startsWith('https:'))
|
|
388
|
+
return true
|
|
389
|
+
const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)
|
|
390
|
+
if (proto === undefined || proto.length !== 5)
|
|
391
|
+
return false
|
|
392
|
+
return proto === 'https' || proto.toLowerCase() === 'https'
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Extracts the client IP from the trusted proxies' X-Forwarded-For header, or falls back to the direct socket IP. */
|
|
396
|
+
export function getClientIp(request: Request, trustProxy: TrustProxy = false, remoteIp?: string): string | undefined {
|
|
397
|
+
if (proxyHops(trustProxy) > 0) {
|
|
398
|
+
const forwarded = forwardedValue(request, 'x-forwarded-for', trustProxy)
|
|
399
|
+
if (forwarded)
|
|
400
|
+
return forwarded
|
|
401
|
+
}
|
|
402
|
+
return remoteIp || undefined
|
|
403
|
+
}
|
|
404
|
+
|
|
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. */
|
|
406
|
+
export function safeRedirect(target: string | null | undefined, fallback = '/'): string {
|
|
407
|
+
const path = target?.trim()
|
|
408
|
+
if (path === undefined || !path.startsWith('/') || path.startsWith('//') || path.includes('\\'))
|
|
409
|
+
return fallback
|
|
410
|
+
// 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`.
|
|
411
|
+
for (let i = 0; i < path.length; i++) {
|
|
412
|
+
const code = path.charCodeAt(i)
|
|
413
|
+
if (code < 0x20 || code === 0x7F)
|
|
414
|
+
return fallback
|
|
415
|
+
}
|
|
416
|
+
return path
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Returns true when `origin` matches the request's trusted forwarded origin (or direct origin when none is forwarded) or `trustedOrigins`. */
|
|
420
|
+
export function isTrustedOrigin(
|
|
421
|
+
origin: string,
|
|
422
|
+
request: Request,
|
|
423
|
+
trustedOrigins?: ReadonlySet<string>,
|
|
424
|
+
trustProxy: TrustProxy = false,
|
|
425
|
+
requestUrl?: URL,
|
|
426
|
+
): boolean {
|
|
427
|
+
if (!origin || origin === 'null')
|
|
428
|
+
return false
|
|
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'
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
|
|
482
|
+
export function verifyOrigin(
|
|
483
|
+
request: Request,
|
|
484
|
+
trustedOrigins?: ReadonlySet<string>,
|
|
485
|
+
trustProxy: TrustProxy = false,
|
|
486
|
+
requestUrl?: URL,
|
|
487
|
+
): { ok: true } | ({ ok: false } & OriginRefusal) {
|
|
488
|
+
if (SAFE_METHODS.has(request.method.toUpperCase()))
|
|
489
|
+
return { ok: true }
|
|
490
|
+
|
|
491
|
+
const origin = request.headers.get('origin')
|
|
492
|
+
if (origin !== null) {
|
|
493
|
+
if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy, requestUrl))
|
|
494
|
+
return { ok: true }
|
|
495
|
+
return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}`, hint: untrustedOriginHint(origin, expectedOrigin(request, trustProxy, requestUrl), trustProxy) }
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const fetchSite = request.headers.get('sec-fetch-site')
|
|
499
|
+
if (fetchSite !== null && fetchSite !== 'same-origin' && fetchSite !== 'none')
|
|
500
|
+
return { ok: false, reason: `Cross-site request blocked: sec-fetch-site=${fetchSite}` }
|
|
501
|
+
|
|
502
|
+
return { ok: true }
|
|
503
|
+
}
|
|
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
|
+
|
|
513
|
+
export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
|
|
514
|
+
if (options === false || options?.csp === false)
|
|
515
|
+
return undefined
|
|
516
|
+
if (typeof options?.csp === 'object')
|
|
517
|
+
return extendCsp(options.csp)
|
|
518
|
+
return options?.csp ?? DEFAULT_CSP
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
export function resolveHstsValue(options: SecurityHeadersOptions | false | undefined): string | undefined {
|
|
522
|
+
if (options === false)
|
|
523
|
+
return undefined
|
|
524
|
+
if (options?.hsts === false)
|
|
525
|
+
return undefined
|
|
526
|
+
return typeof options?.hsts === 'string' ? options.hsts : DEFAULT_HSTS
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined): readonly [string, string][] {
|
|
530
|
+
if (options === false)
|
|
531
|
+
return []
|
|
532
|
+
const opts = options ?? {}
|
|
533
|
+
const entries: [string, string][] = []
|
|
534
|
+
if (opts.contentTypeOptions ?? true)
|
|
535
|
+
entries.push(['x-content-type-options', 'nosniff'])
|
|
536
|
+
if (opts.frameOptions !== false)
|
|
537
|
+
entries.push(['x-frame-options', opts.frameOptions ?? 'SAMEORIGIN'])
|
|
538
|
+
if (opts.referrerPolicy !== false)
|
|
539
|
+
entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
|
|
540
|
+
if (opts.permissionsPolicy !== false)
|
|
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])
|
|
546
|
+
const csp = resolveCspPolicy(opts)
|
|
547
|
+
if (csp !== undefined)
|
|
548
|
+
entries.push(['content-security-policy', csp])
|
|
549
|
+
return entries
|
|
550
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
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
|
+
// 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
|
+
}
|
|
56
|
+
|
|
57
|
+
const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
|
|
58
|
+
const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>): void => {
|
|
59
|
+
const key = toBunRouteKey(path)
|
|
60
|
+
if (key !== undefined && !(key in routes))
|
|
61
|
+
routes[key] = handler
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (healthPath !== undefined && healthHandler !== undefined)
|
|
65
|
+
registerServeRoute(healthPath, req => healthHandler(req))
|
|
66
|
+
|
|
67
|
+
for (const [path, asset] of files.assetMap)
|
|
68
|
+
registerServeRoute(path, req => isRead(req) ? serveFile(req, asset) : fetchReq(req))
|
|
69
|
+
|
|
70
|
+
for (const [path, pub] of files.publicMap) {
|
|
71
|
+
if (pluginRouter.match(literalPath(path)) === undefined)
|
|
72
|
+
registerServeRoute(path, req => isRead(req) ? serveFile(req, pub) : fetchReq(req))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
for (const [path, pre] of fastPrerenderedMap)
|
|
76
|
+
registerServeRoute(path, req => isPlainRead(req) ? serveFile(req, pre) : fetchReq(req))
|
|
77
|
+
|
|
78
|
+
for (const [path, handler] of fastStaticPages)
|
|
79
|
+
registerServeRoute(path, req => isPlainRead(req) ? runFast(handler, req, ipOf(req)) : fetchReq(req))
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
routes,
|
|
83
|
+
fetch: fetchReq,
|
|
84
|
+
error(err: Error) {
|
|
85
|
+
const fallbackReq = new Request('http://localhost/')
|
|
86
|
+
const reqId = resolveRequestId?.(fallbackReq)
|
|
87
|
+
if ('code' in err && err.code === 'ENOENT')
|
|
88
|
+
return reqId !== undefined ? withRequestId(fileGone(), reqId) : fileGone()
|
|
89
|
+
notifyError(err, fallbackReq, 'route', reqId)
|
|
90
|
+
return reqId !== undefined ? withRequestId(serverError(), reqId) : serverError()
|
|
91
|
+
},
|
|
92
|
+
}
|
|
93
|
+
}
|