prunelle 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +148 -0
- package/package.json +53 -4
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +613 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +169 -0
- package/src/build/client-prune.ts +118 -0
- package/src/build/compile.ts +128 -0
- package/src/build/files.ts +156 -0
- package/src/build/first-load.ts +164 -0
- package/src/build/graph.ts +247 -0
- package/src/build/index.ts +614 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/islands.ts +641 -0
- package/src/build/manifest.ts +281 -0
- package/src/build/output.ts +84 -0
- package/src/build/plugin-host.ts +220 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +150 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +247 -0
- package/src/build/resolve.ts +50 -0
- package/src/build/routes.ts +338 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +163 -0
- package/src/build/status-pages.ts +127 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +367 -0
- package/src/cli/commands.ts +265 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +335 -0
- package/src/cli/new.ts +41 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +354 -0
- package/src/compiler/analyze.ts +618 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +127 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +497 -0
- package/src/compiler/data-keys.ts +295 -0
- package/src/compiler/dom-attrs.ts +379 -0
- package/src/compiler/dom.ts +566 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +408 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +499 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props.ts +460 -0
- package/src/compiler/scope.ts +568 -0
- package/src/compiler/server-only.ts +326 -0
- package/src/compiler/shared.ts +369 -0
- package/src/compiler/signal-reads.ts +242 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +56 -0
- package/src/compiler/ssr.ts +491 -0
- package/src/context.ts +165 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/index.ts +208 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/protocol.ts +21 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +157 -0
- package/src/dev/supervisor.ts +187 -0
- package/src/dev/watchers.ts +215 -0
- package/src/dom/action.ts +164 -0
- package/src/dom/attrs.ts +72 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +562 -0
- package/src/dom/index.ts +289 -0
- package/src/dom/island.ts +284 -0
- package/src/dom/loop.ts +450 -0
- package/src/dom/revive.ts +36 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +86 -0
- package/src/plugins/context.ts +66 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +70 -0
- package/src/plugins/order.ts +111 -0
- package/src/plugins/public.ts +12 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +35 -0
- package/src/plugins/types.ts +242 -0
- package/src/reactivity/graph.ts +249 -0
- package/src/reactivity/index.ts +533 -0
- package/src/reactivity/selector.ts +51 -0
- package/src/reactivity/store.ts +208 -0
- package/src/server/action-protect.ts +186 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +498 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +136 -0
- package/src/server/compress.ts +560 -0
- package/src/server/consent.ts +253 -0
- package/src/server/cookies.ts +139 -0
- package/src/server/document.ts +271 -0
- package/src/server/env.ts +33 -0
- package/src/server/errors.ts +382 -0
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +508 -0
- package/src/server/index.ts +687 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +118 -0
- package/src/server/page.ts +107 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +256 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +19 -0
- package/src/server/rate-limit.ts +133 -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-table.ts +82 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +377 -0
- package/src/server/security.ts +472 -0
- package/src/server/serve-handlers.ts +83 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +87 -0
- package/src/server/start.ts +99 -0
- package/src/server/static-dir.ts +167 -0
- package/src/server/stream.ts +192 -0
- package/src/ssr/context.ts +350 -0
- package/src/ssr/index.ts +596 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +171 -0
- package/src/style.ts +33 -0
- package/src/test/browser.ts +192 -0
- package/src/test/index.ts +191 -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 +3 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +13 -0
- package/templates/_shared/tsconfig.json +20 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +21 -0
- package/templates/app/prunelle.config.ts +11 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/app/tests/app.test.ts +32 -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 +20 -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 +10 -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 +27 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -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 +29 -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 +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
- package/README.md +0 -3
|
@@ -0,0 +1,472 @@
|
|
|
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
|
+
/** CSP hashes of the app's own `<style>` blocks in `html`, leaving out prunelle's island and Suspense styles (hashed apart). */
|
|
50
|
+
export function inlineStyleHashes(html: string): string[] {
|
|
51
|
+
const hashes: string[] = []
|
|
52
|
+
STYLE_OPEN_RE.lastIndex = 0
|
|
53
|
+
let open = STYLE_OPEN_RE.exec(html)
|
|
54
|
+
while (open !== null) {
|
|
55
|
+
const tagEnd = html.indexOf('>', open.index + 6)
|
|
56
|
+
if (tagEnd === -1)
|
|
57
|
+
break
|
|
58
|
+
STYLE_CLOSE_RE.lastIndex = tagEnd + 1
|
|
59
|
+
const close = STYLE_CLOSE_RE.exec(html)
|
|
60
|
+
if (close === null)
|
|
61
|
+
break
|
|
62
|
+
const content = html.slice(tagEnd + 1, close.index)
|
|
63
|
+
if (content !== PRUNELLE_ISLAND_STYLE && content !== PRUNELLE_SUSPENSE_STYLE) {
|
|
64
|
+
const hash = styleHash(content)
|
|
65
|
+
if (!hashes.includes(hash))
|
|
66
|
+
hashes.push(hash)
|
|
67
|
+
}
|
|
68
|
+
STYLE_OPEN_RE.lastIndex = close.index + 7
|
|
69
|
+
open = STYLE_OPEN_RE.exec(html)
|
|
70
|
+
}
|
|
71
|
+
return hashes
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface ParsedCsp {
|
|
75
|
+
order: string[]
|
|
76
|
+
directives: Map<string, string[]>
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function parseCsp(csp: string): ParsedCsp {
|
|
80
|
+
const directives = new Map<string, string[]>()
|
|
81
|
+
const order: string[] = []
|
|
82
|
+
for (const part of csp.split(';')) {
|
|
83
|
+
const trimmed = part.trim()
|
|
84
|
+
if (!trimmed)
|
|
85
|
+
continue
|
|
86
|
+
const tokens = trimmed.split(/\s+/)
|
|
87
|
+
const name = tokens[0]!.toLowerCase()
|
|
88
|
+
if (!directives.has(name)) {
|
|
89
|
+
order.push(name)
|
|
90
|
+
directives.set(name, tokens.slice(1))
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return { order, directives }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function serializeCsp(parsed: ParsedCsp): string {
|
|
97
|
+
return parsed.order.map((name) => {
|
|
98
|
+
const tokens = parsed.directives.get(name)!
|
|
99
|
+
return tokens.length > 0 ? `${name} ${tokens.join(' ')}` : name
|
|
100
|
+
}).join('; ')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Augments a Content-Security-Policy header with exact SHA-256 hashes (no `'unsafe-inline'` required). */
|
|
104
|
+
export function withCspHashes(
|
|
105
|
+
csp: string,
|
|
106
|
+
opts: { styleHashes?: readonly string[], scriptHashes?: readonly string[] },
|
|
107
|
+
): string {
|
|
108
|
+
const styleHashes = opts.styleHashes ?? []
|
|
109
|
+
const scriptHashes = opts.scriptHashes ?? []
|
|
110
|
+
if (styleHashes.length === 0 && scriptHashes.length === 0)
|
|
111
|
+
return csp
|
|
112
|
+
|
|
113
|
+
const parsed = parseCsp(csp)
|
|
114
|
+
const { order, directives } = parsed
|
|
115
|
+
const defaultSrc = directives.get('default-src') ?? ["'self'"]
|
|
116
|
+
const addHashes = (dirName: string, hashes: readonly string[]) => {
|
|
117
|
+
if (hashes.length === 0)
|
|
118
|
+
return
|
|
119
|
+
let tokens = directives.get(dirName)
|
|
120
|
+
if (tokens === undefined) {
|
|
121
|
+
tokens = [...defaultSrc]
|
|
122
|
+
directives.set(dirName, tokens)
|
|
123
|
+
order.push(dirName)
|
|
124
|
+
}
|
|
125
|
+
if (tokens.includes("'unsafe-inline'"))
|
|
126
|
+
return
|
|
127
|
+
const noneIdx = tokens.indexOf("'none'")
|
|
128
|
+
if (noneIdx !== -1)
|
|
129
|
+
tokens.splice(noneIdx, 1)
|
|
130
|
+
for (const h of hashes) {
|
|
131
|
+
if (!tokens.includes(h))
|
|
132
|
+
tokens.push(h)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
addHashes('style-src', styleHashes)
|
|
137
|
+
if (directives.has('style-src-elem'))
|
|
138
|
+
addHashes('style-src-elem', styleHashes)
|
|
139
|
+
addHashes('script-src', scriptHashes)
|
|
140
|
+
if (directives.has('script-src-elem'))
|
|
141
|
+
addHashes('script-src-elem', scriptHashes)
|
|
142
|
+
|
|
143
|
+
return serializeCsp(parsed)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'"
|
|
147
|
+
export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
|
|
148
|
+
export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
|
|
149
|
+
|
|
150
|
+
export type CspDirectiveValue = string | readonly string[]
|
|
151
|
+
|
|
152
|
+
export interface KnownCspDirectives {
|
|
153
|
+
'default-src'?: CspDirectiveValue | undefined
|
|
154
|
+
'script-src'?: CspDirectiveValue | undefined
|
|
155
|
+
'script-src-elem'?: CspDirectiveValue | undefined
|
|
156
|
+
'script-src-attr'?: CspDirectiveValue | undefined
|
|
157
|
+
'style-src'?: CspDirectiveValue | undefined
|
|
158
|
+
'style-src-elem'?: CspDirectiveValue | undefined
|
|
159
|
+
'style-src-attr'?: CspDirectiveValue | undefined
|
|
160
|
+
'img-src'?: CspDirectiveValue | undefined
|
|
161
|
+
'font-src'?: CspDirectiveValue | undefined
|
|
162
|
+
'connect-src'?: CspDirectiveValue | undefined
|
|
163
|
+
'media-src'?: CspDirectiveValue | undefined
|
|
164
|
+
'object-src'?: CspDirectiveValue | undefined
|
|
165
|
+
'frame-src'?: CspDirectiveValue | undefined
|
|
166
|
+
'child-src'?: CspDirectiveValue | undefined
|
|
167
|
+
'worker-src'?: CspDirectiveValue | undefined
|
|
168
|
+
'manifest-src'?: CspDirectiveValue | undefined
|
|
169
|
+
'base-uri'?: CspDirectiveValue | undefined
|
|
170
|
+
'form-action'?: CspDirectiveValue | undefined
|
|
171
|
+
'frame-ancestors'?: CspDirectiveValue | undefined
|
|
172
|
+
'sandbox'?: CspDirectiveValue | undefined
|
|
173
|
+
'report-to'?: CspDirectiveValue | undefined
|
|
174
|
+
'report-uri'?: CspDirectiveValue | undefined
|
|
175
|
+
'upgrade-insecure-requests'?: CspDirectiveValue | undefined
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export type CspDirectives = Readonly<KnownCspDirectives & Record<string, CspDirectiveValue | undefined>>
|
|
179
|
+
|
|
180
|
+
const isFetchDirective = (name: string): boolean =>
|
|
181
|
+
name.endsWith('-src') || name.endsWith('-src-elem') || name.endsWith('-src-attr')
|
|
182
|
+
|
|
183
|
+
function splitCspTokens(value: CspDirectiveValue): string[] {
|
|
184
|
+
const parts = typeof value === 'string' ? [value] : value
|
|
185
|
+
const tokens: string[] = []
|
|
186
|
+
for (const part of parts) {
|
|
187
|
+
for (const token of part.split(/\s+/)) {
|
|
188
|
+
if (token.length > 0 && !tokens.includes(token))
|
|
189
|
+
tokens.push(token)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return tokens
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function mergeCspDirective(parsed: ParsedCsp, name: string, tokens: readonly string[]): void {
|
|
196
|
+
const { order, directives } = parsed
|
|
197
|
+
const existing = directives.get(name)
|
|
198
|
+
if (existing === undefined) {
|
|
199
|
+
order.push(name)
|
|
200
|
+
if (tokens.length === 0) {
|
|
201
|
+
directives.set(name, [])
|
|
202
|
+
}
|
|
203
|
+
else if (tokens.includes("'none'")) {
|
|
204
|
+
directives.set(name, ["'none'"])
|
|
205
|
+
}
|
|
206
|
+
else if (isFetchDirective(name)) {
|
|
207
|
+
const seeded = (directives.get('default-src') ?? ["'self'"]).filter(t => t !== "'none'")
|
|
208
|
+
for (const token of tokens) {
|
|
209
|
+
if (!seeded.includes(token))
|
|
210
|
+
seeded.push(token)
|
|
211
|
+
}
|
|
212
|
+
directives.set(name, seeded)
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
directives.set(name, [...tokens])
|
|
216
|
+
}
|
|
217
|
+
return
|
|
218
|
+
}
|
|
219
|
+
if (tokens.length === 0)
|
|
220
|
+
return
|
|
221
|
+
if (tokens.includes("'none'")) {
|
|
222
|
+
directives.set(name, ["'none'"])
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
const noneIdx = existing.indexOf("'none'")
|
|
226
|
+
if (noneIdx !== -1)
|
|
227
|
+
existing.splice(noneIdx, 1)
|
|
228
|
+
for (const token of tokens) {
|
|
229
|
+
if (!existing.includes(token))
|
|
230
|
+
existing.push(token)
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Extends a Content-Security-Policy (default: `DEFAULT_CSP`) by merging additional sources into one or more directives. */
|
|
235
|
+
export function extendCsp(extra: CspDirectives, base = DEFAULT_CSP): string {
|
|
236
|
+
const parsed = parseCsp(base)
|
|
237
|
+
for (const [rawName, rawValue] of Object.entries(extra)) {
|
|
238
|
+
if (rawValue === undefined)
|
|
239
|
+
continue
|
|
240
|
+
const name = rawName.trim().toLowerCase()
|
|
241
|
+
if (name.length === 0)
|
|
242
|
+
continue
|
|
243
|
+
mergeCspDirective(parsed, name, splitCspTokens(rawValue))
|
|
244
|
+
}
|
|
245
|
+
return serializeCsp(parsed)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Directives browsers ignore (and log an error for) when delivered via <meta http-equiv="Content-Security-Policy"> (W3C CSP3 §4.2.1).
|
|
249
|
+
const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'sandbox'])
|
|
250
|
+
const EXISTING_META_CSP_RE = /<meta\b[^>]*\bhttp-equiv\s*=\s*(?:"content-security-policy"|'content-security-policy'|content-security-policy\b)/i
|
|
251
|
+
const META_CHARSET_RE = /<meta\b[^>]*\bcharset\s*=\s*[^>]*>/i
|
|
252
|
+
const HEAD_OPEN_RE = /<head\b[^>]*>/i
|
|
253
|
+
const ESC_DOUBLE_ATTR_RE = /[&"<>]/g
|
|
254
|
+
const DOUBLE_ATTR_MAP: Record<string, string> = { '&': '&', '"': '"', '<': '<', '>': '>' }
|
|
255
|
+
|
|
256
|
+
/** Strips directives browsers reject in a `<meta http-equiv="Content-Security-Policy">` element. */
|
|
257
|
+
export function toMetaCsp(csp: string): string {
|
|
258
|
+
const parsed = parseCsp(csp)
|
|
259
|
+
parsed.order = parsed.order.filter(name => !META_CSP_IGNORED.has(name))
|
|
260
|
+
return serializeCsp(parsed)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Injects `<meta http-equiv="Content-Security-Policy">` at the top of `<head>` for static HTML exports. */
|
|
264
|
+
export function injectMetaCsp(html: string, csp: string | null | undefined): string {
|
|
265
|
+
if (!csp || EXISTING_META_CSP_RE.test(html))
|
|
266
|
+
return html
|
|
267
|
+
const metaCsp = toMetaCsp(csp)
|
|
268
|
+
if (metaCsp.length === 0)
|
|
269
|
+
return html
|
|
270
|
+
const headMatch = HEAD_OPEN_RE.exec(html)
|
|
271
|
+
if (headMatch === null)
|
|
272
|
+
return html
|
|
273
|
+
const headEnd = headMatch.index + headMatch[0].length
|
|
274
|
+
const headCloseIdx = html.toLowerCase().indexOf('</head>', headEnd)
|
|
275
|
+
const headSlice = headCloseIdx === -1 ? html.slice(headEnd) : html.slice(headEnd, headCloseIdx)
|
|
276
|
+
const charsetMatch = META_CHARSET_RE.exec(headSlice)
|
|
277
|
+
const insertAt = charsetMatch !== null ? headEnd + charsetMatch.index + charsetMatch[0].length : headEnd
|
|
278
|
+
const escaped = metaCsp.replace(ESC_DOUBLE_ATTR_RE, ch => DOUBLE_ATTR_MAP[ch]!)
|
|
279
|
+
return `${html.slice(0, insertAt)}<meta http-equiv="Content-Security-Policy" content="${escaped}">${html.slice(insertAt)}`
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export interface SecurityHeadersOptions {
|
|
283
|
+
frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
|
|
284
|
+
referrerPolicy?: string | false | undefined
|
|
285
|
+
contentTypeOptions?: boolean | undefined
|
|
286
|
+
permissionsPolicy?: string | false | undefined
|
|
287
|
+
csp?: string | CspDirectives | false | undefined
|
|
288
|
+
hsts?: string | boolean | undefined
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
|
292
|
+
|
|
293
|
+
/** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
|
|
294
|
+
export type TrustProxy = boolean | number
|
|
295
|
+
|
|
296
|
+
function proxyHops(trustProxy: TrustProxy): number {
|
|
297
|
+
if (trustProxy === true)
|
|
298
|
+
return 1
|
|
299
|
+
if (trustProxy === false || !Number.isFinite(trustProxy))
|
|
300
|
+
return 0
|
|
301
|
+
return Math.max(0, Math.floor(trustProxy))
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Proxies append to X-Forwarded-*, so only the entries the trusted hops wrote count: the one `hops` from the right.
|
|
305
|
+
// When fewer than `hops` entries exist, return undefined rather than trusting a client-supplied leftmost entry.
|
|
306
|
+
function forwardedValue(request: Request, header: string, trustProxy: TrustProxy): string | undefined {
|
|
307
|
+
const hops = proxyHops(trustProxy)
|
|
308
|
+
if (hops === 0)
|
|
309
|
+
return undefined
|
|
310
|
+
const raw = request.headers.get(header)
|
|
311
|
+
if (raw === null || raw.length === 0)
|
|
312
|
+
return undefined
|
|
313
|
+
let end = raw.length
|
|
314
|
+
let seen = 0
|
|
315
|
+
while (end > 0) {
|
|
316
|
+
const comma = raw.lastIndexOf(',', end - 1)
|
|
317
|
+
let start = comma + 1
|
|
318
|
+
let stop = end
|
|
319
|
+
while (start < stop && raw.charCodeAt(start) <= 32)
|
|
320
|
+
start++
|
|
321
|
+
while (stop > start && raw.charCodeAt(stop - 1) <= 32)
|
|
322
|
+
stop--
|
|
323
|
+
if (start < stop) {
|
|
324
|
+
seen++
|
|
325
|
+
if (seen === hops)
|
|
326
|
+
return start === 0 && stop === raw.length ? raw : raw.slice(start, stop)
|
|
327
|
+
}
|
|
328
|
+
if (comma === -1)
|
|
329
|
+
break
|
|
330
|
+
end = comma
|
|
331
|
+
}
|
|
332
|
+
return undefined
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function forwardedOrigin(request: Request, trustProxy: TrustProxy): string | undefined {
|
|
336
|
+
const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase()
|
|
337
|
+
if (proto !== 'http' && proto !== 'https')
|
|
338
|
+
return undefined
|
|
339
|
+
const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim()
|
|
340
|
+
if (!host)
|
|
341
|
+
return undefined
|
|
342
|
+
try {
|
|
343
|
+
const origin = new URL(`${proto}://${host}`).origin
|
|
344
|
+
return origin === 'null' ? undefined : origin
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
return undefined
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Returns true when the request arrived over HTTPS (directly, or via X-Forwarded-Proto when `trustProxy` is true). */
|
|
352
|
+
export function isHttpsRequest(request: Request, trustProxy: TrustProxy = false): boolean {
|
|
353
|
+
if (request.url.startsWith('https:'))
|
|
354
|
+
return true
|
|
355
|
+
const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)
|
|
356
|
+
if (proto === undefined || proto.length !== 5)
|
|
357
|
+
return false
|
|
358
|
+
return proto === 'https' || proto.toLowerCase() === 'https'
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Extracts the client IP from the trusted proxies' X-Forwarded-For header, or falls back to the direct socket IP. */
|
|
362
|
+
export function getClientIp(request: Request, trustProxy: TrustProxy = false, remoteIp?: string): string | undefined {
|
|
363
|
+
if (proxyHops(trustProxy) > 0) {
|
|
364
|
+
const forwarded = forwardedValue(request, 'x-forwarded-for', trustProxy)
|
|
365
|
+
if (forwarded)
|
|
366
|
+
return forwarded
|
|
367
|
+
}
|
|
368
|
+
return remoteIp || undefined
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
const sha256 = (text: string): Buffer => new Bun.CryptoHasher('sha256').update(text).digest()
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* 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.
|
|
375
|
+
* The digests are XORed byte by byte rather than passed to `node:crypto`, which would add 2 MB to the server's RSS.
|
|
376
|
+
*/
|
|
377
|
+
export function safeEqual(a: string, b: string): boolean {
|
|
378
|
+
const x = sha256(a)
|
|
379
|
+
const y = sha256(b)
|
|
380
|
+
let diff = 0
|
|
381
|
+
for (let i = 0; i < x.length; i++)
|
|
382
|
+
diff |= x[i]! ^ y[i]!
|
|
383
|
+
return diff === 0
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** `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. */
|
|
387
|
+
export function safeRedirect(target: string | null | undefined, fallback = '/'): string {
|
|
388
|
+
const path = target?.trim()
|
|
389
|
+
if (path === undefined || !path.startsWith('/') || path.startsWith('//') || path.includes('\\'))
|
|
390
|
+
return fallback
|
|
391
|
+
// 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`.
|
|
392
|
+
for (let i = 0; i < path.length; i++) {
|
|
393
|
+
const code = path.charCodeAt(i)
|
|
394
|
+
if (code < 0x20 || code === 0x7F)
|
|
395
|
+
return fallback
|
|
396
|
+
}
|
|
397
|
+
return path
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Returns true when `origin` matches the request's direct (or trusted forwarded) origin or `trustedOrigins`. */
|
|
401
|
+
export function isTrustedOrigin(
|
|
402
|
+
origin: string,
|
|
403
|
+
request: Request,
|
|
404
|
+
trustedOrigins?: ReadonlySet<string>,
|
|
405
|
+
trustProxy: TrustProxy = false,
|
|
406
|
+
requestUrl?: URL,
|
|
407
|
+
): boolean {
|
|
408
|
+
if (!origin || origin === 'null')
|
|
409
|
+
return false
|
|
410
|
+
return origin === (requestUrl?.origin ?? new URL(request.url).origin)
|
|
411
|
+
|| origin === forwardedOrigin(request, trustProxy)
|
|
412
|
+
|| trustedOrigins?.has(origin) === true
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
|
|
416
|
+
export function verifyOrigin(
|
|
417
|
+
request: Request,
|
|
418
|
+
trustedOrigins?: ReadonlySet<string>,
|
|
419
|
+
trustProxy: TrustProxy = false,
|
|
420
|
+
requestUrl?: URL,
|
|
421
|
+
): { ok: true } | { ok: false, reason: string } {
|
|
422
|
+
if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
|
|
423
|
+
return { ok: true }
|
|
424
|
+
|
|
425
|
+
const origin = request.headers.get('origin')
|
|
426
|
+
if (origin !== null) {
|
|
427
|
+
if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy, requestUrl))
|
|
428
|
+
return { ok: true }
|
|
429
|
+
return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}` }
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const fetchSite = request.headers.get('sec-fetch-site')
|
|
433
|
+
if (fetchSite !== null && fetchSite !== 'same-origin' && fetchSite !== 'none')
|
|
434
|
+
return { ok: false, reason: `Cross-site request blocked: sec-fetch-site=${fetchSite}` }
|
|
435
|
+
|
|
436
|
+
return { ok: true }
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
|
|
440
|
+
if (options === false || options?.csp === false)
|
|
441
|
+
return undefined
|
|
442
|
+
if (typeof options?.csp === 'object')
|
|
443
|
+
return extendCsp(options.csp)
|
|
444
|
+
return options?.csp ?? DEFAULT_CSP
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export function resolveHstsValue(options: SecurityHeadersOptions | false | undefined): string | undefined {
|
|
448
|
+
if (options === false)
|
|
449
|
+
return undefined
|
|
450
|
+
if (options?.hsts === false)
|
|
451
|
+
return undefined
|
|
452
|
+
return typeof options?.hsts === 'string' ? options.hsts : DEFAULT_HSTS
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined): readonly [string, string][] {
|
|
456
|
+
if (options === false)
|
|
457
|
+
return []
|
|
458
|
+
const opts = options ?? {}
|
|
459
|
+
const entries: [string, string][] = []
|
|
460
|
+
if (opts.contentTypeOptions ?? true)
|
|
461
|
+
entries.push(['x-content-type-options', 'nosniff'])
|
|
462
|
+
if (opts.frameOptions !== false)
|
|
463
|
+
entries.push(['x-frame-options', opts.frameOptions ?? 'SAMEORIGIN'])
|
|
464
|
+
if (opts.referrerPolicy !== false)
|
|
465
|
+
entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
|
|
466
|
+
if (opts.permissionsPolicy !== false)
|
|
467
|
+
entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
|
|
468
|
+
const csp = resolveCspPolicy(opts)
|
|
469
|
+
if (csp !== undefined)
|
|
470
|
+
entries.push(['content-security-policy', csp])
|
|
471
|
+
return entries
|
|
472
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// One file served as it is (a hashed asset, a public file, a prerendered page, a `--static` file): its headers, validators and encoded variants are fixed when it is listed, so a request only picks one.
|
|
2
|
+
|
|
3
|
+
import type { CompressionCache } from './compress'
|
|
4
|
+
import { statSync } from 'node:fs'
|
|
5
|
+
import { markCompressionHandled, mergeVaryValue, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
|
|
6
|
+
import { etagMatches } from './http'
|
|
7
|
+
|
|
8
|
+
const textEncoder = new TextEncoder()
|
|
9
|
+
|
|
10
|
+
/** A file on disk (or embedded in a binary), bytes, or an HTML string. */
|
|
11
|
+
export type FileSource = { path: string } | { bytes: Uint8Array<ArrayBuffer> } | { text: string }
|
|
12
|
+
|
|
13
|
+
interface Variant {
|
|
14
|
+
body: BodyInit
|
|
15
|
+
headers: Record<string, string>
|
|
16
|
+
/** The file's path and size, for a variant on disk the compression cache may keep in memory. */
|
|
17
|
+
disk: { path: string, size: () => number } | undefined
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ServedFile {
|
|
21
|
+
/** The compression cache key, which changes with the file's version. */
|
|
22
|
+
key: string
|
|
23
|
+
etag: string | undefined
|
|
24
|
+
headers: Record<string, string>
|
|
25
|
+
notModifiedHeaders: Record<string, string>
|
|
26
|
+
/** Headers of the variant compressed here on first request; undefined when the file is never compressed here. */
|
|
27
|
+
compressedHeaders: Record<string, string> | undefined
|
|
28
|
+
br: Variant | undefined
|
|
29
|
+
gz: Variant | undefined
|
|
30
|
+
body: BodyInit
|
|
31
|
+
read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>
|
|
32
|
+
/** The identity body's byte length, read on the first `HEAD`. */
|
|
33
|
+
size: () => number
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ServedFileInit {
|
|
37
|
+
key: string
|
|
38
|
+
source: FileSource
|
|
39
|
+
/** `content-type`, `cache-control` and the security headers. */
|
|
40
|
+
headers: Record<string, string>
|
|
41
|
+
/** Defaults to the source's size and mtime, or a hash of its bytes. */
|
|
42
|
+
etag?: string | undefined
|
|
43
|
+
/** Whether the server may compress it on first request. */
|
|
44
|
+
compressible: boolean
|
|
45
|
+
br?: FileSource | undefined
|
|
46
|
+
gz?: FileSource | undefined
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function bodyOf(source: FileSource): BodyInit {
|
|
50
|
+
return 'path' in source ? Bun.file(source.path) : 'bytes' in source ? source.bytes : source.text
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function bytesOf(source: FileSource): Promise<Uint8Array<ArrayBuffer>> {
|
|
54
|
+
return 'path' in source ? new Uint8Array(await Bun.file(source.path).arrayBuffer()) : 'bytes' in source ? source.bytes : textEncoder.encode(source.text)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** `W/"<size>-<mtime>"` for a file on disk, a hash of the bytes otherwise. */
|
|
58
|
+
export function sourceEtag(source: FileSource): string {
|
|
59
|
+
if ('path' in source) {
|
|
60
|
+
const st = statSync(source.path)
|
|
61
|
+
return `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
|
|
62
|
+
}
|
|
63
|
+
return `W/"${Bun.hash('bytes' in source ? source.bytes : source.text).toString(36)}"`
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function servedFile(init: ServedFileInit): ServedFile {
|
|
67
|
+
const etag = init.etag ?? sourceEtag(init.source)
|
|
68
|
+
const varies = init.compressible || init.br !== undefined || init.gz !== undefined
|
|
69
|
+
const headers: Record<string, string> = { ...init.headers, etag, ...(varies ? { vary: mergeVaryValue(init.headers.vary, 'Accept-Encoding') } : {}) }
|
|
70
|
+
const { 'content-type': _type, ...notModifiedHeaders } = headers
|
|
71
|
+
const onDisk = (path: string): Variant['disk'] => {
|
|
72
|
+
let bytes: number | undefined
|
|
73
|
+
return { path, size: () => bytes ??= Bun.file(path).size }
|
|
74
|
+
}
|
|
75
|
+
const encoded = (source: FileSource | undefined, encoding: string): Variant | undefined =>
|
|
76
|
+
source === undefined ? undefined : { body: bodyOf(source), headers: { ...headers, 'content-encoding': encoding, 'etag': toWeakEtag(etag) }, disk: 'path' in source ? onDisk(source.path) : undefined }
|
|
77
|
+
let size: number | undefined
|
|
78
|
+
return {
|
|
79
|
+
key: `${init.key}:${etag}`,
|
|
80
|
+
etag,
|
|
81
|
+
headers,
|
|
82
|
+
notModifiedHeaders,
|
|
83
|
+
compressedHeaders: init.compressible ? { ...headers, etag: toWeakEtag(etag) } : undefined,
|
|
84
|
+
br: encoded(init.br, 'br'),
|
|
85
|
+
gz: encoded(init.gz, 'gzip'),
|
|
86
|
+
body: bodyOf(init.source),
|
|
87
|
+
read: () => bytesOf(init.source),
|
|
88
|
+
size: () => size ??= 'path' in init.source ? Bun.file(init.source.path).size : 'bytes' in init.source ? init.source.bytes.byteLength : textEncoder.encode(init.source.text).byteLength,
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Answers a request for a listed file: a 304 to a matching `If-None-Match`, its length to a `HEAD`, else a precompressed sidecar, a variant compressed here, or the file. */
|
|
93
|
+
export function createFileServer(options: {
|
|
94
|
+
compressEnabled: boolean
|
|
95
|
+
compressCache: CompressionCache | undefined
|
|
96
|
+
withHsts: (res: Response, request: Request) => Response
|
|
97
|
+
}) {
|
|
98
|
+
const { compressEnabled, compressCache, withHsts } = options
|
|
99
|
+
const done = (res: Response, request: Request): Response => markCompressionHandled(withHsts(res, request))
|
|
100
|
+
|
|
101
|
+
return async function serveFile(request: Request, file: ServedFile, status = 200): Promise<Response> {
|
|
102
|
+
if (status === 200 && file.etag !== undefined && etagMatches(request.headers.get('if-none-match'), file.etag))
|
|
103
|
+
return done(new Response(null, { status: 304, headers: file.notModifiedHeaders }), request)
|
|
104
|
+
if (request.method === 'HEAD')
|
|
105
|
+
return done(new Response(null, { status, headers: { ...file.headers, 'content-length': String(file.size()) } }), request)
|
|
106
|
+
const accept = request.headers.get('accept-encoding')
|
|
107
|
+
if (compressEnabled && (file.br !== undefined || file.gz !== undefined)) {
|
|
108
|
+
const pre = pickPrecompressedEncoding(accept, { br: file.br !== undefined, gz: file.gz !== undefined })
|
|
109
|
+
if (pre !== undefined) {
|
|
110
|
+
const variant = pre === 'br' ? file.br! : file.gz!
|
|
111
|
+
const { disk } = variant
|
|
112
|
+
const kept = disk !== undefined && compressCache?.keeps(disk.size()) === true
|
|
113
|
+
? await compressCache.sidecar(`${file.key}:${pre}`, async () => new Uint8Array(await Bun.file(disk.path).arrayBuffer()))
|
|
114
|
+
: undefined
|
|
115
|
+
return done(new Response(kept ?? variant.body, { status, headers: variant.headers }), request)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (file.compressedHeaders !== undefined && compressCache !== undefined) {
|
|
119
|
+
const enc = pickEncoding(accept)
|
|
120
|
+
if (enc !== undefined) {
|
|
121
|
+
const compressed = await compressCache.file(file.key, enc, file.read)
|
|
122
|
+
if (compressed !== undefined)
|
|
123
|
+
return done(new Response(compressed, { status, headers: { ...file.compressedHeaders, 'content-encoding': enc } }), request)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return done(new Response(file.body, { status, headers: file.headers }), request)
|
|
127
|
+
}
|
|
128
|
+
}
|