prunelle 0.1.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/llms.txt +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +89 -41
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +15 -0
- package/src/build/first-load.ts +85 -14
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +225 -122
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +14 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +115 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +177 -39
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +48 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +139 -39
- 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 +101 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -22
- package/src/compiler/analyze.ts +87 -54
- package/src/compiler/browser-globals.ts +140 -17
- 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 +407 -352
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +260 -81
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +94 -34
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +57 -40
- package/src/dom/index.ts +54 -14
- package/src/dom/island.ts +102 -68
- package/src/dom/loop.ts +66 -32
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +18 -12
- package/src/plugins/context.ts +44 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +64 -20
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +188 -152
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +308 -65
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +186 -39
- package/src/server/index.ts +272 -273
- package/src/server/loader.ts +15 -2
- package/src/server/page.ts +15 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +356 -11
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +279 -52
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/standard-schema.ts +17 -0
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +91 -12
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +106 -8
- package/src/ssr/index.ts +151 -4
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +40 -19
- package/src/style.ts +64 -1
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- 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/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
- package/ts-plugin.cjs +4277 -0
package/src/server/security.ts
CHANGED
|
@@ -46,20 +46,46 @@ export function styleHashesOf(styles: Iterable<string> | undefined): string[] {
|
|
|
46
46
|
const STYLE_OPEN_RE = /<style(?=[\s>/])/gi
|
|
47
47
|
const STYLE_CLOSE_RE = /<\/style(?=[\s>])/gi
|
|
48
48
|
|
|
49
|
+
function findStyleTagEnd(html: string, start: number): { end: number, selfClosing: boolean } | undefined {
|
|
50
|
+
let quote = 0
|
|
51
|
+
for (let i = start; i < html.length; i++) {
|
|
52
|
+
const ch = html.charCodeAt(i)
|
|
53
|
+
if (quote !== 0) {
|
|
54
|
+
if (ch === quote)
|
|
55
|
+
quote = 0
|
|
56
|
+
}
|
|
57
|
+
else if (ch === 34 || ch === 39) {
|
|
58
|
+
quote = ch
|
|
59
|
+
}
|
|
60
|
+
else if (ch === 62) {
|
|
61
|
+
let prev = i - 1
|
|
62
|
+
while (prev >= start && html.charCodeAt(prev) <= 32)
|
|
63
|
+
prev--
|
|
64
|
+
return { end: i, selfClosing: prev >= start && html.charCodeAt(prev) === 47 }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return undefined
|
|
68
|
+
}
|
|
69
|
+
|
|
49
70
|
/** CSP hashes of the app's own `<style>` blocks in `html`, leaving out prunelle's island and Suspense styles (hashed apart). */
|
|
50
71
|
export function inlineStyleHashes(html: string): string[] {
|
|
51
72
|
const hashes: string[] = []
|
|
52
73
|
STYLE_OPEN_RE.lastIndex = 0
|
|
53
74
|
let open = STYLE_OPEN_RE.exec(html)
|
|
54
75
|
while (open !== null) {
|
|
55
|
-
const
|
|
56
|
-
if (
|
|
76
|
+
const tag = findStyleTagEnd(html, open.index + 6)
|
|
77
|
+
if (tag === undefined)
|
|
57
78
|
break
|
|
58
|
-
|
|
79
|
+
if (tag.selfClosing) {
|
|
80
|
+
STYLE_OPEN_RE.lastIndex = tag.end + 1
|
|
81
|
+
open = STYLE_OPEN_RE.exec(html)
|
|
82
|
+
continue
|
|
83
|
+
}
|
|
84
|
+
STYLE_CLOSE_RE.lastIndex = tag.end + 1
|
|
59
85
|
const close = STYLE_CLOSE_RE.exec(html)
|
|
60
86
|
if (close === null)
|
|
61
87
|
break
|
|
62
|
-
const content = html.slice(
|
|
88
|
+
const content = html.slice(tag.end + 1, close.index)
|
|
63
89
|
if (content !== PRUNELLE_ISLAND_STYLE && content !== PRUNELLE_SUSPENSE_STYLE) {
|
|
64
90
|
const hash = styleHash(content)
|
|
65
91
|
if (!hashes.includes(hash))
|
|
@@ -71,28 +97,47 @@ export function inlineStyleHashes(html: string): string[] {
|
|
|
71
97
|
return hashes
|
|
72
98
|
}
|
|
73
99
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
): string {
|
|
79
|
-
const styleHashes = opts.styleHashes ?? []
|
|
80
|
-
const scriptHashes = opts.scriptHashes ?? []
|
|
81
|
-
if (styleHashes.length === 0 && scriptHashes.length === 0)
|
|
82
|
-
return csp
|
|
100
|
+
interface ParsedCsp {
|
|
101
|
+
order: string[]
|
|
102
|
+
directives: Map<string, string[]>
|
|
103
|
+
}
|
|
83
104
|
|
|
84
|
-
|
|
105
|
+
function parseCsp(csp: string): ParsedCsp {
|
|
85
106
|
const directives = new Map<string, string[]>()
|
|
86
107
|
const order: string[] = []
|
|
87
|
-
for (const part of
|
|
88
|
-
const
|
|
108
|
+
for (const part of csp.split(';')) {
|
|
109
|
+
const trimmed = part.trim()
|
|
110
|
+
if (!trimmed)
|
|
111
|
+
continue
|
|
112
|
+
const tokens = trimmed.split(/\s+/)
|
|
89
113
|
const name = tokens[0]!.toLowerCase()
|
|
90
114
|
if (!directives.has(name)) {
|
|
91
115
|
order.push(name)
|
|
92
116
|
directives.set(name, tokens.slice(1))
|
|
93
117
|
}
|
|
94
118
|
}
|
|
119
|
+
return { order, directives }
|
|
120
|
+
}
|
|
95
121
|
|
|
122
|
+
function serializeCsp(parsed: ParsedCsp): string {
|
|
123
|
+
return parsed.order.map((name) => {
|
|
124
|
+
const tokens = parsed.directives.get(name)!
|
|
125
|
+
return tokens.length > 0 ? `${name} ${tokens.join(' ')}` : name
|
|
126
|
+
}).join('; ')
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Augments a Content-Security-Policy header with exact SHA-256 hashes (no `'unsafe-inline'` required). */
|
|
130
|
+
export function withCspHashes(
|
|
131
|
+
csp: string,
|
|
132
|
+
opts: { styleHashes?: readonly string[], scriptHashes?: readonly string[] },
|
|
133
|
+
): string {
|
|
134
|
+
const styleHashes = opts.styleHashes ?? []
|
|
135
|
+
const scriptHashes = opts.scriptHashes ?? []
|
|
136
|
+
if (styleHashes.length === 0 && scriptHashes.length === 0)
|
|
137
|
+
return csp
|
|
138
|
+
|
|
139
|
+
const parsed = parseCsp(csp)
|
|
140
|
+
const { order, directives } = parsed
|
|
96
141
|
const defaultSrc = directives.get('default-src') ?? ["'self'"]
|
|
97
142
|
const addHashes = (dirName: string, hashes: readonly string[]) => {
|
|
98
143
|
if (hashes.length === 0)
|
|
@@ -121,26 +166,163 @@ export function withCspHashes(
|
|
|
121
166
|
if (directives.has('script-src-elem'))
|
|
122
167
|
addHashes('script-src-elem', scriptHashes)
|
|
123
168
|
|
|
124
|
-
return
|
|
125
|
-
const tokens = directives.get(name)!
|
|
126
|
-
return tokens.length > 0 ? `${name} ${tokens.join(' ')}` : name
|
|
127
|
-
}).join('; ')
|
|
169
|
+
return serializeCsp(parsed)
|
|
128
170
|
}
|
|
129
171
|
|
|
130
172
|
export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'"
|
|
131
173
|
export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
|
|
132
|
-
export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
|
|
174
|
+
export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), accelerometer=(), gyroscope=(), magnetometer=(), browsing-topics=()'
|
|
175
|
+
export const DEFAULT_COOP = 'same-origin'
|
|
176
|
+
export const DEFAULT_CORP = 'same-origin'
|
|
177
|
+
|
|
178
|
+
export type CspDirectiveValue = string | readonly string[]
|
|
179
|
+
|
|
180
|
+
export interface KnownCspDirectives {
|
|
181
|
+
'default-src'?: CspDirectiveValue | undefined
|
|
182
|
+
'script-src'?: CspDirectiveValue | undefined
|
|
183
|
+
'script-src-elem'?: CspDirectiveValue | undefined
|
|
184
|
+
'script-src-attr'?: CspDirectiveValue | undefined
|
|
185
|
+
'style-src'?: CspDirectiveValue | undefined
|
|
186
|
+
'style-src-elem'?: CspDirectiveValue | undefined
|
|
187
|
+
'style-src-attr'?: CspDirectiveValue | undefined
|
|
188
|
+
'img-src'?: CspDirectiveValue | undefined
|
|
189
|
+
'font-src'?: CspDirectiveValue | undefined
|
|
190
|
+
'connect-src'?: CspDirectiveValue | undefined
|
|
191
|
+
'media-src'?: CspDirectiveValue | undefined
|
|
192
|
+
'object-src'?: CspDirectiveValue | undefined
|
|
193
|
+
'frame-src'?: CspDirectiveValue | undefined
|
|
194
|
+
'child-src'?: CspDirectiveValue | undefined
|
|
195
|
+
'worker-src'?: CspDirectiveValue | undefined
|
|
196
|
+
'manifest-src'?: CspDirectiveValue | undefined
|
|
197
|
+
'base-uri'?: CspDirectiveValue | undefined
|
|
198
|
+
'form-action'?: CspDirectiveValue | undefined
|
|
199
|
+
'frame-ancestors'?: CspDirectiveValue | undefined
|
|
200
|
+
'sandbox'?: CspDirectiveValue | undefined
|
|
201
|
+
'report-to'?: CspDirectiveValue | undefined
|
|
202
|
+
'report-uri'?: CspDirectiveValue | undefined
|
|
203
|
+
'upgrade-insecure-requests'?: CspDirectiveValue | undefined
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export type CspDirectives = Readonly<KnownCspDirectives & Record<string, CspDirectiveValue | undefined>>
|
|
207
|
+
|
|
208
|
+
const isFetchDirective = (name: string): boolean =>
|
|
209
|
+
name.endsWith('-src') || name.endsWith('-src-elem') || name.endsWith('-src-attr')
|
|
210
|
+
|
|
211
|
+
function splitCspTokens(value: CspDirectiveValue): string[] {
|
|
212
|
+
const parts = typeof value === 'string' ? [value] : value
|
|
213
|
+
const tokens: string[] = []
|
|
214
|
+
for (const part of parts) {
|
|
215
|
+
for (const token of part.split(/\s+/)) {
|
|
216
|
+
if (token.length > 0 && !tokens.includes(token))
|
|
217
|
+
tokens.push(token)
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return tokens
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function mergeCspDirective(parsed: ParsedCsp, name: string, tokens: readonly string[]): void {
|
|
224
|
+
const { order, directives } = parsed
|
|
225
|
+
const existing = directives.get(name)
|
|
226
|
+
if (existing === undefined) {
|
|
227
|
+
order.push(name)
|
|
228
|
+
if (tokens.length === 0) {
|
|
229
|
+
directives.set(name, [])
|
|
230
|
+
}
|
|
231
|
+
else if (tokens.includes("'none'")) {
|
|
232
|
+
directives.set(name, ["'none'"])
|
|
233
|
+
}
|
|
234
|
+
else if (isFetchDirective(name)) {
|
|
235
|
+
const seeded = (directives.get('default-src') ?? ["'self'"]).filter(t => t !== "'none'")
|
|
236
|
+
for (const token of tokens) {
|
|
237
|
+
if (!seeded.includes(token))
|
|
238
|
+
seeded.push(token)
|
|
239
|
+
}
|
|
240
|
+
directives.set(name, seeded)
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
directives.set(name, [...tokens])
|
|
244
|
+
}
|
|
245
|
+
return
|
|
246
|
+
}
|
|
247
|
+
if (tokens.length === 0)
|
|
248
|
+
return
|
|
249
|
+
if (tokens.includes("'none'")) {
|
|
250
|
+
directives.set(name, ["'none'"])
|
|
251
|
+
return
|
|
252
|
+
}
|
|
253
|
+
const noneIdx = existing.indexOf("'none'")
|
|
254
|
+
if (noneIdx !== -1)
|
|
255
|
+
existing.splice(noneIdx, 1)
|
|
256
|
+
for (const token of tokens) {
|
|
257
|
+
if (!existing.includes(token))
|
|
258
|
+
existing.push(token)
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Extends a Content-Security-Policy (default: `DEFAULT_CSP`) by merging additional sources into one or more directives. */
|
|
263
|
+
export function extendCsp(extra: CspDirectives, base = DEFAULT_CSP): string {
|
|
264
|
+
const parsed = parseCsp(base)
|
|
265
|
+
for (const [rawName, rawValue] of Object.entries(extra)) {
|
|
266
|
+
if (rawValue === undefined)
|
|
267
|
+
continue
|
|
268
|
+
const name = rawName.trim().toLowerCase()
|
|
269
|
+
if (name.length === 0)
|
|
270
|
+
continue
|
|
271
|
+
mergeCspDirective(parsed, name, splitCspTokens(rawValue))
|
|
272
|
+
}
|
|
273
|
+
return serializeCsp(parsed)
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Directives browsers ignore (and log an error for) when delivered via <meta http-equiv="Content-Security-Policy"> (W3C CSP3 §4.2.1).
|
|
277
|
+
const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'sandbox'])
|
|
278
|
+
const EXISTING_META_CSP_RE = /<meta\b[^>]*\bhttp-equiv\s*=\s*(?:"content-security-policy"|'content-security-policy'|content-security-policy\b)/i
|
|
279
|
+
const META_CHARSET_RE = /<meta\b[^>]*\bcharset\s*=\s*[^>]*>/i
|
|
280
|
+
const HEAD_OPEN_RE = /<head\b[^>]*>/i
|
|
281
|
+
const ESC_DOUBLE_ATTR_RE = /[&"<>]/g
|
|
282
|
+
const DOUBLE_ATTR_MAP: Record<string, string> = { '&': '&', '"': '"', '<': '<', '>': '>' }
|
|
283
|
+
|
|
284
|
+
/** Strips directives browsers reject in a `<meta http-equiv="Content-Security-Policy">` element. */
|
|
285
|
+
export function toMetaCsp(csp: string): string {
|
|
286
|
+
const parsed = parseCsp(csp)
|
|
287
|
+
parsed.order = parsed.order.filter(name => !META_CSP_IGNORED.has(name))
|
|
288
|
+
return serializeCsp(parsed)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Injects `<meta http-equiv="Content-Security-Policy">` at the top of `<head>` for static HTML exports. */
|
|
292
|
+
export function injectMetaCsp(html: string, csp: string | null | undefined): string {
|
|
293
|
+
if (!csp)
|
|
294
|
+
return html
|
|
295
|
+
const metaCsp = toMetaCsp(csp)
|
|
296
|
+
if (metaCsp.length === 0)
|
|
297
|
+
return html
|
|
298
|
+
const headMatch = HEAD_OPEN_RE.exec(html)
|
|
299
|
+
if (headMatch === null)
|
|
300
|
+
return html
|
|
301
|
+
const headEnd = headMatch.index + headMatch[0].length
|
|
302
|
+
const headCloseIdx = html.toLowerCase().indexOf('</head>', headEnd)
|
|
303
|
+
const headSlice = headCloseIdx === -1 ? html.slice(headEnd) : html.slice(headEnd, headCloseIdx)
|
|
304
|
+
if (EXISTING_META_CSP_RE.test(headSlice))
|
|
305
|
+
return html
|
|
306
|
+
const charsetMatch = META_CHARSET_RE.exec(headSlice)
|
|
307
|
+
const insertAt = charsetMatch !== null ? headEnd + charsetMatch.index + charsetMatch[0].length : headEnd
|
|
308
|
+
const escaped = metaCsp.replace(ESC_DOUBLE_ATTR_RE, ch => DOUBLE_ATTR_MAP[ch]!)
|
|
309
|
+
return `${html.slice(0, insertAt)}<meta http-equiv="Content-Security-Policy" content="${escaped}">${html.slice(insertAt)}`
|
|
310
|
+
}
|
|
133
311
|
|
|
134
312
|
export interface SecurityHeadersOptions {
|
|
135
313
|
frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
|
|
136
314
|
referrerPolicy?: string | false | undefined
|
|
137
315
|
contentTypeOptions?: boolean | undefined
|
|
138
316
|
permissionsPolicy?: string | false | undefined
|
|
139
|
-
csp?: string | false | undefined
|
|
317
|
+
csp?: string | CspDirectives | false | undefined
|
|
140
318
|
hsts?: string | boolean | undefined
|
|
319
|
+
/** `Cross-Origin-Opener-Policy` (default `same-origin`): another site's window cannot keep a handle on this one. `'same-origin-allow-popups'` keeps a payment or sign-in popup working. */
|
|
320
|
+
crossOriginOpenerPolicy?: string | false | undefined
|
|
321
|
+
/** `Cross-Origin-Resource-Policy` (default `same-origin`): another site cannot embed this one's images, scripts or fonts. Use `'cross-origin'` for assets meant to be hotlinked. */
|
|
322
|
+
crossOriginResourcePolicy?: string | false | undefined
|
|
141
323
|
}
|
|
142
324
|
|
|
143
|
-
const
|
|
325
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
|
|
144
326
|
|
|
145
327
|
/** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
|
|
146
328
|
export type TrustProxy = boolean | number
|
|
@@ -184,11 +366,11 @@ function forwardedValue(request: Request, header: string, trustProxy: TrustProxy
|
|
|
184
366
|
return undefined
|
|
185
367
|
}
|
|
186
368
|
|
|
187
|
-
function forwardedOrigin(request: Request, trustProxy: TrustProxy): string | undefined {
|
|
369
|
+
function forwardedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?: URL): string | undefined {
|
|
188
370
|
const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase()
|
|
189
371
|
if (proto !== 'http' && proto !== 'https')
|
|
190
372
|
return undefined
|
|
191
|
-
const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim()
|
|
373
|
+
const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim() || (requestUrl ?? new URL(request.url)).host
|
|
192
374
|
if (!host)
|
|
193
375
|
return undefined
|
|
194
376
|
try {
|
|
@@ -220,21 +402,6 @@ export function getClientIp(request: Request, trustProxy: TrustProxy = false, re
|
|
|
220
402
|
return remoteIp || undefined
|
|
221
403
|
}
|
|
222
404
|
|
|
223
|
-
const sha256 = (text: string): Buffer => new Bun.CryptoHasher('sha256').update(text).digest()
|
|
224
|
-
|
|
225
|
-
/**
|
|
226
|
-
* Compares two secrets (tokens, MACs, OAuth states) in constant time: both are hashed first, so neither their content nor their length shows in the timing.
|
|
227
|
-
* The digests are XORed byte by byte rather than passed to `node:crypto`, which would add 2 MB to the server's RSS.
|
|
228
|
-
*/
|
|
229
|
-
export function safeEqual(a: string, b: string): boolean {
|
|
230
|
-
const x = sha256(a)
|
|
231
|
-
const y = sha256(b)
|
|
232
|
-
let diff = 0
|
|
233
|
-
for (let i = 0; i < x.length; i++)
|
|
234
|
-
diff |= x[i]! ^ y[i]!
|
|
235
|
-
return diff === 0
|
|
236
|
-
}
|
|
237
|
-
|
|
238
405
|
/** `target` trimmed when it is a path on this site, else `fallback`: an absolute or protocol-relative URL, a backslash or a control character is refused. */
|
|
239
406
|
export function safeRedirect(target: string | null | undefined, fallback = '/'): string {
|
|
240
407
|
const path = target?.trim()
|
|
@@ -249,7 +416,7 @@ export function safeRedirect(target: string | null | undefined, fallback = '/'):
|
|
|
249
416
|
return path
|
|
250
417
|
}
|
|
251
418
|
|
|
252
|
-
/** Returns true when `origin` matches the request's
|
|
419
|
+
/** Returns true when `origin` matches the request's trusted forwarded origin (or direct origin when none is forwarded) or `trustedOrigins`. */
|
|
253
420
|
export function isTrustedOrigin(
|
|
254
421
|
origin: string,
|
|
255
422
|
request: Request,
|
|
@@ -259,9 +426,56 @@ export function isTrustedOrigin(
|
|
|
259
426
|
): boolean {
|
|
260
427
|
if (!origin || origin === 'null')
|
|
261
428
|
return false
|
|
262
|
-
return origin === (requestUrl
|
|
263
|
-
|
|
264
|
-
|
|
429
|
+
return origin === expectedOrigin(request, trustProxy, requestUrl) || trustedOrigins?.has(origin) === true
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** The origin this server takes the request to be on: the trusted forwarded one, else the one it was reached at. */
|
|
433
|
+
export function expectedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?: URL): string {
|
|
434
|
+
return forwardedOrigin(request, trustProxy, requestUrl) ?? requestUrl?.origin ?? new URL(request.url).origin
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Whether `origin` is the https twin of the http `expected` origin: the same host, so only the scheme can differ. */
|
|
438
|
+
function isSchemeMismatch(origin: string, expected: string): boolean {
|
|
439
|
+
const seen = URL.parse(origin)
|
|
440
|
+
const computed = URL.parse(expected)
|
|
441
|
+
return seen !== null && computed !== null && computed.protocol === 'http:' && seen.host === computed.host
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** What to log when a POST is refused: the two origins compared, and the config keys that settle it. */
|
|
445
|
+
function untrustedOriginHint(origin: string, expected: string, trustProxy: TrustProxy): string {
|
|
446
|
+
const head = `prunelle: a POST was refused as cross-site: its Origin is ${origin} but the origin this server computes is ${expected}.`
|
|
447
|
+
if (isSchemeMismatch(origin, expected))
|
|
448
|
+
return `${head} The page is served over https and the server sees http, as behind a TLS proxy: set trustProxy in prunelle.config.ts (true for one proxy, or the number of proxies) and have the proxy send x-forwarded-proto. To accept another site, add its origin to trustedOrigins.`
|
|
449
|
+
if (proxyHops(trustProxy) > 0)
|
|
450
|
+
return `${head} trustProxy is on: check the proxy sends x-forwarded-proto and x-forwarded-host, or list the origin in trustedOrigins in prunelle.config.ts.`
|
|
451
|
+
return `${head} Behind a proxy, set trustProxy in prunelle.config.ts; to accept another site, add its origin to trustedOrigins.`
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
let hintLogged = false
|
|
455
|
+
|
|
456
|
+
/** Logs a refused origin's fix, the first time only: later refusals of a misconfigured proxy would repeat it on every POST. */
|
|
457
|
+
export function logOriginHint(hint: string | undefined): void {
|
|
458
|
+
if (hint === undefined || hintLogged)
|
|
459
|
+
return
|
|
460
|
+
hintLogged = true
|
|
461
|
+
console.warn(hint)
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Lets the next `logOriginHint` log again; for tests. */
|
|
465
|
+
export function resetOriginHint(): void {
|
|
466
|
+
hintLogged = false
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Why a request was refused as cross-site, and the fix to log for it when the cause is a wrong origin. */
|
|
470
|
+
export interface OriginRefusal {
|
|
471
|
+
reason: string
|
|
472
|
+
hint?: string | undefined
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** Whether `host` (a hostname or a bind address, IPv6 with or without brackets) names this machine alone. */
|
|
476
|
+
export function isLoopbackHost(host: string): boolean {
|
|
477
|
+
const bare = host.toLowerCase().replace(/^\[|\]$/g, '')
|
|
478
|
+
return bare === 'localhost' || bare === '127.0.0.1' || bare === '::1'
|
|
265
479
|
}
|
|
266
480
|
|
|
267
481
|
/** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
|
|
@@ -270,15 +484,15 @@ export function verifyOrigin(
|
|
|
270
484
|
trustedOrigins?: ReadonlySet<string>,
|
|
271
485
|
trustProxy: TrustProxy = false,
|
|
272
486
|
requestUrl?: URL,
|
|
273
|
-
): { ok: true } | { ok: false
|
|
274
|
-
if (
|
|
487
|
+
): { ok: true } | ({ ok: false } & OriginRefusal) {
|
|
488
|
+
if (SAFE_METHODS.has(request.method.toUpperCase()))
|
|
275
489
|
return { ok: true }
|
|
276
490
|
|
|
277
491
|
const origin = request.headers.get('origin')
|
|
278
492
|
if (origin !== null) {
|
|
279
493
|
if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy, requestUrl))
|
|
280
494
|
return { ok: true }
|
|
281
|
-
return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}
|
|
495
|
+
return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}`, hint: untrustedOriginHint(origin, expectedOrigin(request, trustProxy, requestUrl), trustProxy) }
|
|
282
496
|
}
|
|
283
497
|
|
|
284
498
|
const fetchSite = request.headers.get('sec-fetch-site')
|
|
@@ -288,11 +502,19 @@ export function verifyOrigin(
|
|
|
288
502
|
return { ok: true }
|
|
289
503
|
}
|
|
290
504
|
|
|
291
|
-
|
|
292
|
-
|
|
505
|
+
/** The notice a production server prints when it listens on loopback only, which a container's published port or another machine cannot reach; undefined otherwise. */
|
|
506
|
+
export function loopbackBindNotice(hostname: string, fromHost: boolean): string | undefined {
|
|
507
|
+
if (!isLoopbackHost(hostname))
|
|
293
508
|
return undefined
|
|
294
|
-
|
|
509
|
+
const source = fromHost ? 'HOST or --host' : 'the default, as neither HOST nor --host is set'
|
|
510
|
+
return `prunelle: the server listens on ${hostname} (${source}), which only this machine reaches: in a container or behind another host, set HOST=0.0.0.0 or pass --host so the published port answers.`
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
|
|
514
|
+
if (options === false || options?.csp === false)
|
|
295
515
|
return undefined
|
|
516
|
+
if (typeof options?.csp === 'object')
|
|
517
|
+
return extendCsp(options.csp)
|
|
296
518
|
return options?.csp ?? DEFAULT_CSP
|
|
297
519
|
}
|
|
298
520
|
|
|
@@ -317,7 +539,12 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
|
|
|
317
539
|
entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
|
|
318
540
|
if (opts.permissionsPolicy !== false)
|
|
319
541
|
entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
|
|
320
|
-
if (opts.
|
|
321
|
-
entries.push(['
|
|
542
|
+
if (opts.crossOriginOpenerPolicy !== false)
|
|
543
|
+
entries.push(['cross-origin-opener-policy', opts.crossOriginOpenerPolicy ?? DEFAULT_COOP])
|
|
544
|
+
if (opts.crossOriginResourcePolicy !== false)
|
|
545
|
+
entries.push(['cross-origin-resource-policy', opts.crossOriginResourcePolicy ?? DEFAULT_CORP])
|
|
546
|
+
const csp = resolveCspPolicy(opts)
|
|
547
|
+
if (csp !== undefined)
|
|
548
|
+
entries.push(['content-security-policy', csp])
|
|
322
549
|
return entries
|
|
323
550
|
}
|
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
import type { createAssets, ServedFile } from './assets'
|
|
4
4
|
import type { NotifyError } from './errors'
|
|
5
|
+
import type { RequestIdResolver } from './health'
|
|
5
6
|
import type { PrunelleServer } from './http'
|
|
6
7
|
import type { RequestPath } from './request-path'
|
|
7
8
|
import type { FastHandler } from './routing'
|
|
8
9
|
import { ACTION_ERROR_COOKIE } from './action'
|
|
10
|
+
import { withRequestId } from './health'
|
|
9
11
|
import { hasRegionHeader } from './region'
|
|
10
12
|
import { literalPath } from './request-path'
|
|
11
13
|
import { toBunRouteKey } from './routing'
|
|
@@ -15,6 +17,9 @@ export interface ServeHandlerSources {
|
|
|
15
17
|
fastPrerenderedMap: ReadonlyMap<string, ServedFile>
|
|
16
18
|
fastStaticPages: ReadonlyMap<string, FastHandler>
|
|
17
19
|
pluginRouter: { match: (path: RequestPath) => unknown }
|
|
20
|
+
healthPath?: string | undefined
|
|
21
|
+
healthHandler?: ((request: Request, requestId?: string) => Response | Promise<Response>) | undefined
|
|
22
|
+
resolveRequestId?: RequestIdResolver | undefined
|
|
18
23
|
/** Answers through the app's whole pipeline, with the request's timeout turned off by `disableTimeout` for a long-lived stream. */
|
|
19
24
|
runRequest: (req: Request, remoteIp: string | undefined, disableTimeout: () => void) => Promise<Response>
|
|
20
25
|
runFast: (handler: FastHandler, req: Request, remoteIp: string | undefined) => Response | Promise<Response>
|
|
@@ -31,9 +36,23 @@ export const hasActionErrorCookie = (request: Request): boolean => (request.head
|
|
|
31
36
|
export const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request) && !hasRegionHeader(request)
|
|
32
37
|
|
|
33
38
|
export function serveHandlers(server: () => PrunelleServer | undefined, sources: ServeHandlerSources) {
|
|
34
|
-
const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, runRequest, runFast, notifyError, serverError, fileGone } = sources
|
|
39
|
+
const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone } = sources
|
|
35
40
|
const ipOf = (req: Request) => server()?.requestIP(req)?.address
|
|
36
41
|
const fetchReq = (req: Request) => runRequest(req, ipOf(req), () => server()?.timeout(req, 0))
|
|
42
|
+
// A file that fails to open answers here, where the request is known: gone since the build is a 404, anything else is reported with it.
|
|
43
|
+
const serveFile = async (req: Request, file: ServedFile): Promise<Response> => {
|
|
44
|
+
const reqId = resolveRequestId?.(req)
|
|
45
|
+
const tagged = (res: Response): Response => reqId === undefined ? res : withRequestId(res, reqId)
|
|
46
|
+
try {
|
|
47
|
+
return tagged(await files.serveFile(req, file))
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
if (err instanceof Error && 'code' in err && err.code === 'ENOENT')
|
|
51
|
+
return tagged(fileGone())
|
|
52
|
+
notifyError(err, req, 'route', reqId)
|
|
53
|
+
return tagged(serverError())
|
|
54
|
+
}
|
|
55
|
+
}
|
|
37
56
|
|
|
38
57
|
const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
|
|
39
58
|
const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>): void => {
|
|
@@ -42,16 +61,19 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
|
|
|
42
61
|
routes[key] = handler
|
|
43
62
|
}
|
|
44
63
|
|
|
64
|
+
if (healthPath !== undefined && healthHandler !== undefined)
|
|
65
|
+
registerServeRoute(healthPath, req => healthHandler(req))
|
|
66
|
+
|
|
45
67
|
for (const [path, asset] of files.assetMap)
|
|
46
|
-
registerServeRoute(path, req => isRead(req) ?
|
|
68
|
+
registerServeRoute(path, req => isRead(req) ? serveFile(req, asset) : fetchReq(req))
|
|
47
69
|
|
|
48
70
|
for (const [path, pub] of files.publicMap) {
|
|
49
71
|
if (pluginRouter.match(literalPath(path)) === undefined)
|
|
50
|
-
registerServeRoute(path, req => isRead(req) ?
|
|
72
|
+
registerServeRoute(path, req => isRead(req) ? serveFile(req, pub) : fetchReq(req))
|
|
51
73
|
}
|
|
52
74
|
|
|
53
75
|
for (const [path, pre] of fastPrerenderedMap)
|
|
54
|
-
registerServeRoute(path, req => isPlainRead(req) ?
|
|
76
|
+
registerServeRoute(path, req => isPlainRead(req) ? serveFile(req, pre) : fetchReq(req))
|
|
55
77
|
|
|
56
78
|
for (const [path, handler] of fastStaticPages)
|
|
57
79
|
registerServeRoute(path, req => isPlainRead(req) ? runFast(handler, req, ipOf(req)) : fetchReq(req))
|
|
@@ -60,10 +82,12 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
|
|
|
60
82
|
routes,
|
|
61
83
|
fetch: fetchReq,
|
|
62
84
|
error(err: Error) {
|
|
85
|
+
const fallbackReq = new Request('http://localhost/')
|
|
86
|
+
const reqId = resolveRequestId?.(fallbackReq)
|
|
63
87
|
if ('code' in err && err.code === 'ENOENT')
|
|
64
|
-
return fileGone()
|
|
65
|
-
notifyError(err,
|
|
66
|
-
return serverError()
|
|
88
|
+
return reqId !== undefined ? withRequestId(fileGone(), reqId) : fileGone()
|
|
89
|
+
notifyError(err, fallbackReq, 'route', reqId)
|
|
90
|
+
return reqId !== undefined ? withRequestId(serverError(), reqId) : serverError()
|
|
67
91
|
},
|
|
68
92
|
}
|
|
69
93
|
}
|
|
@@ -5,6 +5,22 @@ export interface StandardSchemaIssue {
|
|
|
5
5
|
readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined
|
|
6
6
|
}
|
|
7
7
|
|
|
8
|
+
export type StandardJSONSchemaTarget =
|
|
9
|
+
| 'draft-2020-12'
|
|
10
|
+
| 'draft-07'
|
|
11
|
+
| 'openapi-3.0'
|
|
12
|
+
| ({} & string)
|
|
13
|
+
|
|
14
|
+
export interface StandardJSONSchemaOptions {
|
|
15
|
+
readonly target: StandardJSONSchemaTarget
|
|
16
|
+
readonly libraryOptions?: Record<string, unknown> | undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface StandardJSONSchemaConverter {
|
|
20
|
+
readonly input: (options: StandardJSONSchemaOptions) => Record<string, unknown>
|
|
21
|
+
readonly output?: ((options: StandardJSONSchemaOptions) => Record<string, unknown>) | undefined
|
|
22
|
+
}
|
|
23
|
+
|
|
8
24
|
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
9
25
|
readonly '~standard': {
|
|
10
26
|
readonly version: 1
|
|
@@ -17,6 +33,7 @@ export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
|
17
33
|
| { readonly issues: ReadonlyArray<StandardSchemaIssue> }
|
|
18
34
|
>
|
|
19
35
|
readonly types?: { readonly input: Input, readonly output: Output } | undefined
|
|
36
|
+
readonly jsonSchema?: StandardJSONSchemaConverter | undefined
|
|
20
37
|
}
|
|
21
38
|
}
|
|
22
39
|
|