prunelle 0.1.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +23 -19
- package/package.json +8 -2
- package/src/a11y/declaration.ts +335 -0
- package/src/a11y/index.ts +446 -0
- package/src/a11y/rgaa-map.ts +184 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +80 -36
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +8 -4
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +11 -9
- package/src/build/ecoindex.ts +229 -0
- package/src/build/index.ts +174 -108
- package/src/build/islands.ts +2 -2
- package/src/build/manifest.ts +66 -5
- package/src/build/output.ts +2 -2
- package/src/build/plugin-host.ts +91 -33
- package/src/build/precompress.ts +15 -2
- package/src/build/prerender.ts +128 -46
- package/src/build/report.ts +23 -2
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static.ts +137 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +52 -5
- package/src/cli/commands.ts +86 -4
- package/src/cli/docs.ts +402 -0
- package/src/cli/inspect.ts +31 -2
- package/src/cli/mcp-tools.ts +480 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +2 -2
- package/src/cli/render.ts +261 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +137 -16
- package/src/compiler/analyze.ts +20 -6
- package/src/compiler/cacheability.ts +592 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +120 -221
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +12 -11
- package/src/compiler/expr-context.ts +167 -57
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +56 -17
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +216 -84
- package/src/dev/error-log.ts +151 -0
- package/src/dev/index.ts +84 -34
- package/src/dev/open-editor.ts +204 -0
- package/src/dev/protocol.ts +1 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +42 -25
- package/src/dev/watchers.ts +47 -11
- package/src/dom/action.ts +4 -1
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +2 -2
- package/src/dom/island.ts +11 -10
- package/src/plugins/config.ts +4 -4
- package/src/plugins/index.ts +2 -2
- package/src/plugins/public.ts +5 -2
- package/src/plugins/services.ts +62 -0
- package/src/plugins/types.ts +32 -0
- package/src/server/action-protect.ts +198 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +82 -27
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +91 -9
- package/src/server/errors.ts +303 -65
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +128 -31
- package/src/server/index.ts +230 -260
- package/src/server/loader.ts +5 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +123 -88
- package/src/server/public.ts +3 -3
- package/src/server/rate-limit.ts +58 -35
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +423 -0
- package/src/server/route-table.ts +339 -8
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +196 -63
- package/src/server/security.ts +208 -32
- package/src/server/serve-handlers.ts +21 -7
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +61 -8
- package/src/server/stream.ts +41 -22
- package/src/ssr/context.ts +85 -3
- package/src/ssr/index.ts +120 -1
- package/src/ssr/region.ts +31 -19
- package/src/test/browser.ts +6 -0
- package/src/test/index.ts +17 -3
- package/src/ts-plugin/diagnostics.ts +378 -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/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +5 -0
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/index.tsx +4 -0
- 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
|
+
}
|
|
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
|
+
}
|
|
95
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,157 @@ 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
174
|
export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
|
|
133
175
|
|
|
176
|
+
export type CspDirectiveValue = string | readonly string[]
|
|
177
|
+
|
|
178
|
+
export interface KnownCspDirectives {
|
|
179
|
+
'default-src'?: CspDirectiveValue | undefined
|
|
180
|
+
'script-src'?: CspDirectiveValue | undefined
|
|
181
|
+
'script-src-elem'?: CspDirectiveValue | undefined
|
|
182
|
+
'script-src-attr'?: CspDirectiveValue | undefined
|
|
183
|
+
'style-src'?: CspDirectiveValue | undefined
|
|
184
|
+
'style-src-elem'?: CspDirectiveValue | undefined
|
|
185
|
+
'style-src-attr'?: CspDirectiveValue | undefined
|
|
186
|
+
'img-src'?: CspDirectiveValue | undefined
|
|
187
|
+
'font-src'?: CspDirectiveValue | undefined
|
|
188
|
+
'connect-src'?: CspDirectiveValue | undefined
|
|
189
|
+
'media-src'?: CspDirectiveValue | undefined
|
|
190
|
+
'object-src'?: CspDirectiveValue | undefined
|
|
191
|
+
'frame-src'?: CspDirectiveValue | undefined
|
|
192
|
+
'child-src'?: CspDirectiveValue | undefined
|
|
193
|
+
'worker-src'?: CspDirectiveValue | undefined
|
|
194
|
+
'manifest-src'?: CspDirectiveValue | undefined
|
|
195
|
+
'base-uri'?: CspDirectiveValue | undefined
|
|
196
|
+
'form-action'?: CspDirectiveValue | undefined
|
|
197
|
+
'frame-ancestors'?: CspDirectiveValue | undefined
|
|
198
|
+
'sandbox'?: CspDirectiveValue | undefined
|
|
199
|
+
'report-to'?: CspDirectiveValue | undefined
|
|
200
|
+
'report-uri'?: CspDirectiveValue | undefined
|
|
201
|
+
'upgrade-insecure-requests'?: CspDirectiveValue | undefined
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export type CspDirectives = Readonly<KnownCspDirectives & Record<string, CspDirectiveValue | undefined>>
|
|
205
|
+
|
|
206
|
+
const isFetchDirective = (name: string): boolean =>
|
|
207
|
+
name.endsWith('-src') || name.endsWith('-src-elem') || name.endsWith('-src-attr')
|
|
208
|
+
|
|
209
|
+
function splitCspTokens(value: CspDirectiveValue): string[] {
|
|
210
|
+
const parts = typeof value === 'string' ? [value] : value
|
|
211
|
+
const tokens: string[] = []
|
|
212
|
+
for (const part of parts) {
|
|
213
|
+
for (const token of part.split(/\s+/)) {
|
|
214
|
+
if (token.length > 0 && !tokens.includes(token))
|
|
215
|
+
tokens.push(token)
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return tokens
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function mergeCspDirective(parsed: ParsedCsp, name: string, tokens: readonly string[]): void {
|
|
222
|
+
const { order, directives } = parsed
|
|
223
|
+
const existing = directives.get(name)
|
|
224
|
+
if (existing === undefined) {
|
|
225
|
+
order.push(name)
|
|
226
|
+
if (tokens.length === 0) {
|
|
227
|
+
directives.set(name, [])
|
|
228
|
+
}
|
|
229
|
+
else if (tokens.includes("'none'")) {
|
|
230
|
+
directives.set(name, ["'none'"])
|
|
231
|
+
}
|
|
232
|
+
else if (isFetchDirective(name)) {
|
|
233
|
+
const seeded = (directives.get('default-src') ?? ["'self'"]).filter(t => t !== "'none'")
|
|
234
|
+
for (const token of tokens) {
|
|
235
|
+
if (!seeded.includes(token))
|
|
236
|
+
seeded.push(token)
|
|
237
|
+
}
|
|
238
|
+
directives.set(name, seeded)
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
directives.set(name, [...tokens])
|
|
242
|
+
}
|
|
243
|
+
return
|
|
244
|
+
}
|
|
245
|
+
if (tokens.length === 0)
|
|
246
|
+
return
|
|
247
|
+
if (tokens.includes("'none'")) {
|
|
248
|
+
directives.set(name, ["'none'"])
|
|
249
|
+
return
|
|
250
|
+
}
|
|
251
|
+
const noneIdx = existing.indexOf("'none'")
|
|
252
|
+
if (noneIdx !== -1)
|
|
253
|
+
existing.splice(noneIdx, 1)
|
|
254
|
+
for (const token of tokens) {
|
|
255
|
+
if (!existing.includes(token))
|
|
256
|
+
existing.push(token)
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Extends a Content-Security-Policy (default: `DEFAULT_CSP`) by merging additional sources into one or more directives. */
|
|
261
|
+
export function extendCsp(extra: CspDirectives, base = DEFAULT_CSP): string {
|
|
262
|
+
const parsed = parseCsp(base)
|
|
263
|
+
for (const [rawName, rawValue] of Object.entries(extra)) {
|
|
264
|
+
if (rawValue === undefined)
|
|
265
|
+
continue
|
|
266
|
+
const name = rawName.trim().toLowerCase()
|
|
267
|
+
if (name.length === 0)
|
|
268
|
+
continue
|
|
269
|
+
mergeCspDirective(parsed, name, splitCspTokens(rawValue))
|
|
270
|
+
}
|
|
271
|
+
return serializeCsp(parsed)
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Directives browsers ignore (and log an error for) when delivered via <meta http-equiv="Content-Security-Policy"> (W3C CSP3 §4.2.1).
|
|
275
|
+
const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'sandbox'])
|
|
276
|
+
const EXISTING_META_CSP_RE = /<meta\b[^>]*\bhttp-equiv\s*=\s*(?:"content-security-policy"|'content-security-policy'|content-security-policy\b)/i
|
|
277
|
+
const META_CHARSET_RE = /<meta\b[^>]*\bcharset\s*=\s*[^>]*>/i
|
|
278
|
+
const HEAD_OPEN_RE = /<head\b[^>]*>/i
|
|
279
|
+
const ESC_DOUBLE_ATTR_RE = /[&"<>]/g
|
|
280
|
+
const DOUBLE_ATTR_MAP: Record<string, string> = { '&': '&', '"': '"', '<': '<', '>': '>' }
|
|
281
|
+
|
|
282
|
+
/** Strips directives browsers reject in a `<meta http-equiv="Content-Security-Policy">` element. */
|
|
283
|
+
export function toMetaCsp(csp: string): string {
|
|
284
|
+
const parsed = parseCsp(csp)
|
|
285
|
+
parsed.order = parsed.order.filter(name => !META_CSP_IGNORED.has(name))
|
|
286
|
+
return serializeCsp(parsed)
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Injects `<meta http-equiv="Content-Security-Policy">` at the top of `<head>` for static HTML exports. */
|
|
290
|
+
export function injectMetaCsp(html: string, csp: string | null | undefined): string {
|
|
291
|
+
if (!csp)
|
|
292
|
+
return html
|
|
293
|
+
const metaCsp = toMetaCsp(csp)
|
|
294
|
+
if (metaCsp.length === 0)
|
|
295
|
+
return html
|
|
296
|
+
const headMatch = HEAD_OPEN_RE.exec(html)
|
|
297
|
+
if (headMatch === null)
|
|
298
|
+
return html
|
|
299
|
+
const headEnd = headMatch.index + headMatch[0].length
|
|
300
|
+
const headCloseIdx = html.toLowerCase().indexOf('</head>', headEnd)
|
|
301
|
+
const headSlice = headCloseIdx === -1 ? html.slice(headEnd) : html.slice(headEnd, headCloseIdx)
|
|
302
|
+
if (EXISTING_META_CSP_RE.test(headSlice))
|
|
303
|
+
return html
|
|
304
|
+
const charsetMatch = META_CHARSET_RE.exec(headSlice)
|
|
305
|
+
const insertAt = charsetMatch !== null ? headEnd + charsetMatch.index + charsetMatch[0].length : headEnd
|
|
306
|
+
const escaped = metaCsp.replace(ESC_DOUBLE_ATTR_RE, ch => DOUBLE_ATTR_MAP[ch]!)
|
|
307
|
+
return `${html.slice(0, insertAt)}<meta http-equiv="Content-Security-Policy" content="${escaped}">${html.slice(insertAt)}`
|
|
308
|
+
}
|
|
309
|
+
|
|
134
310
|
export interface SecurityHeadersOptions {
|
|
135
311
|
frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
|
|
136
312
|
referrerPolicy?: string | false | undefined
|
|
137
313
|
contentTypeOptions?: boolean | undefined
|
|
138
314
|
permissionsPolicy?: string | false | undefined
|
|
139
|
-
csp?: string | false | undefined
|
|
315
|
+
csp?: string | CspDirectives | false | undefined
|
|
140
316
|
hsts?: string | boolean | undefined
|
|
141
317
|
}
|
|
142
318
|
|
|
143
|
-
const
|
|
319
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
|
|
144
320
|
|
|
145
321
|
/** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
|
|
146
322
|
export type TrustProxy = boolean | number
|
|
@@ -249,7 +425,7 @@ export function safeRedirect(target: string | null | undefined, fallback = '/'):
|
|
|
249
425
|
return path
|
|
250
426
|
}
|
|
251
427
|
|
|
252
|
-
/** Returns true when `origin` matches the request's
|
|
428
|
+
/** Returns true when `origin` matches the request's trusted forwarded origin (or direct origin when none is forwarded) or `trustedOrigins`. */
|
|
253
429
|
export function isTrustedOrigin(
|
|
254
430
|
origin: string,
|
|
255
431
|
request: Request,
|
|
@@ -259,9 +435,8 @@ export function isTrustedOrigin(
|
|
|
259
435
|
): boolean {
|
|
260
436
|
if (!origin || origin === 'null')
|
|
261
437
|
return false
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|| trustedOrigins?.has(origin) === true
|
|
438
|
+
const expectedOrigin = forwardedOrigin(request, trustProxy) ?? requestUrl?.origin ?? new URL(request.url).origin
|
|
439
|
+
return origin === expectedOrigin || trustedOrigins?.has(origin) === true
|
|
265
440
|
}
|
|
266
441
|
|
|
267
442
|
/** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
|
|
@@ -271,7 +446,7 @@ export function verifyOrigin(
|
|
|
271
446
|
trustProxy: TrustProxy = false,
|
|
272
447
|
requestUrl?: URL,
|
|
273
448
|
): { ok: true } | { ok: false, reason: string } {
|
|
274
|
-
if (
|
|
449
|
+
if (SAFE_METHODS.has(request.method.toUpperCase()))
|
|
275
450
|
return { ok: true }
|
|
276
451
|
|
|
277
452
|
const origin = request.headers.get('origin')
|
|
@@ -289,10 +464,10 @@ export function verifyOrigin(
|
|
|
289
464
|
}
|
|
290
465
|
|
|
291
466
|
export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
|
|
292
|
-
if (options === false)
|
|
293
|
-
return undefined
|
|
294
|
-
if (options?.csp === false)
|
|
467
|
+
if (options === false || options?.csp === false)
|
|
295
468
|
return undefined
|
|
469
|
+
if (typeof options?.csp === 'object')
|
|
470
|
+
return extendCsp(options.csp)
|
|
296
471
|
return options?.csp ?? DEFAULT_CSP
|
|
297
472
|
}
|
|
298
473
|
|
|
@@ -317,7 +492,8 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
|
|
|
317
492
|
entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
|
|
318
493
|
if (opts.permissionsPolicy !== false)
|
|
319
494
|
entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
|
|
320
|
-
|
|
321
|
-
|
|
495
|
+
const csp = resolveCspPolicy(opts)
|
|
496
|
+
if (csp !== undefined)
|
|
497
|
+
entries.push(['content-security-policy', csp])
|
|
322
498
|
return entries
|
|
323
499
|
}
|
|
@@ -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,13 @@ 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
|
+
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)))
|
|
37
46
|
|
|
38
47
|
const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
|
|
39
48
|
const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>): void => {
|
|
@@ -42,16 +51,19 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
|
|
|
42
51
|
routes[key] = handler
|
|
43
52
|
}
|
|
44
53
|
|
|
54
|
+
if (healthPath !== undefined && healthHandler !== undefined)
|
|
55
|
+
registerServeRoute(healthPath, req => healthHandler(req))
|
|
56
|
+
|
|
45
57
|
for (const [path, asset] of files.assetMap)
|
|
46
|
-
registerServeRoute(path, req => isRead(req) ?
|
|
58
|
+
registerServeRoute(path, req => isRead(req) ? serveFile(req, asset) : fetchReq(req))
|
|
47
59
|
|
|
48
60
|
for (const [path, pub] of files.publicMap) {
|
|
49
61
|
if (pluginRouter.match(literalPath(path)) === undefined)
|
|
50
|
-
registerServeRoute(path, req => isRead(req) ?
|
|
62
|
+
registerServeRoute(path, req => isRead(req) ? serveFile(req, pub) : fetchReq(req))
|
|
51
63
|
}
|
|
52
64
|
|
|
53
65
|
for (const [path, pre] of fastPrerenderedMap)
|
|
54
|
-
registerServeRoute(path, req => isPlainRead(req) ?
|
|
66
|
+
registerServeRoute(path, req => isPlainRead(req) ? serveFile(req, pre) : fetchReq(req))
|
|
55
67
|
|
|
56
68
|
for (const [path, handler] of fastStaticPages)
|
|
57
69
|
registerServeRoute(path, req => isPlainRead(req) ? runFast(handler, req, ipOf(req)) : fetchReq(req))
|
|
@@ -60,10 +72,12 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
|
|
|
60
72
|
routes,
|
|
61
73
|
fetch: fetchReq,
|
|
62
74
|
error(err: Error) {
|
|
75
|
+
const fallbackReq = new Request('http://localhost/')
|
|
76
|
+
const reqId = resolveRequestId?.(fallbackReq)
|
|
63
77
|
if ('code' in err && err.code === 'ENOENT')
|
|
64
|
-
return fileGone()
|
|
65
|
-
notifyError(err,
|
|
66
|
-
return serverError()
|
|
78
|
+
return reqId !== undefined ? withRequestId(fileGone(), reqId) : fileGone()
|
|
79
|
+
notifyError(err, fallbackReq, 'route', reqId)
|
|
80
|
+
return reqId !== undefined ? withRequestId(serverError(), reqId) : serverError()
|
|
67
81
|
},
|
|
68
82
|
}
|
|
69
83
|
}
|
package/src/server/start.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// `prunelle start`: serves the built app, and reloads it in-process when a `prunelle build` swaps a new outDir in, so a deploy needs no restart.
|
|
2
2
|
|
|
3
|
-
import type { FSWatcher } from 'node:fs'
|
|
4
3
|
import type { PrunelleApp, PrunelleServer } from './http'
|
|
5
4
|
import { existsSync, readdirSync, watch } from 'node:fs'
|
|
6
5
|
import { basename, dirname, join, relative } from 'node:path'
|
|
@@ -15,17 +14,27 @@ export interface StartOptions {
|
|
|
15
14
|
hostname: string
|
|
16
15
|
}
|
|
17
16
|
|
|
17
|
+
async function disposeApp(app: PrunelleApp): Promise<void> {
|
|
18
|
+
try {
|
|
19
|
+
await app.closeStreams?.()
|
|
20
|
+
await app.dispose?.()
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
console.error('prunelle start: failed to dispose previous build:', err)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
18
27
|
/** The server, and an app that forwards to whichever build it serves, for `handleSignals()`. */
|
|
19
28
|
export async function startServer(options: StartOptions): Promise<{ app: PrunelleApp, server: PrunelleServer }> {
|
|
20
29
|
const first = await startBuiltApp({ root: options.root })
|
|
21
30
|
let current = first.app
|
|
22
31
|
const server = current.serve(options.port, options.hostname)
|
|
23
32
|
const app: PrunelleApp = {
|
|
24
|
-
handle: async (request, remoteIp) => current.handle(request, remoteIp),
|
|
33
|
+
handle: async (request, remoteIp, disableTimeout) => current.handle(request, remoteIp, disableTimeout),
|
|
25
34
|
serve: () => server,
|
|
26
35
|
closeStreams: async () => current.closeStreams?.(),
|
|
27
36
|
dispose: async () => {
|
|
28
|
-
watcher?.
|
|
37
|
+
watcher?.stop()
|
|
29
38
|
await current.dispose?.()
|
|
30
39
|
},
|
|
31
40
|
}
|
|
@@ -36,58 +45,82 @@ export async function startServer(options: StartOptions): Promise<{ app: Prunell
|
|
|
36
45
|
}
|
|
37
46
|
|
|
38
47
|
/** Watches the folder holding `outDir` for the rename a build's swap makes, then loads the new build and swaps its handlers in. */
|
|
39
|
-
function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleApp, setCurrent: (app: PrunelleApp) => void, root: string, server: PrunelleServer):
|
|
48
|
+
function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleApp, setCurrent: (app: PrunelleApp) => void, root: string, server: PrunelleServer): { stop: () => void } {
|
|
40
49
|
const name = basename(outDir)
|
|
41
50
|
const shown = relative(root, outDir) || '.'
|
|
42
51
|
// A `--static` export has no manifest: the folder being back with files in it is the sign.
|
|
43
52
|
const landed = (): boolean => existsSync(join(outDir, 'manifest.json')) || (isStatic && existsSync(outDir) && readdirSync(outDir).length > 0)
|
|
44
|
-
let held: { promise: Promise<PrunelleApp>, resolve: (app: PrunelleApp) => void } | undefined
|
|
53
|
+
let held: { promise: Promise<PrunelleApp>, resolve: (app: PrunelleApp) => void, reject: (err: unknown) => void } | undefined
|
|
45
54
|
let loading = false
|
|
46
55
|
let again = false
|
|
56
|
+
let disposed = false
|
|
47
57
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
48
58
|
|
|
49
59
|
// From the first rename until the new build answers, requests wait for it: no page of the old build links an asset the new one dropped.
|
|
50
60
|
const hold = (): void => {
|
|
51
|
-
if (held !== undefined)
|
|
61
|
+
if (held !== undefined || disposed)
|
|
52
62
|
return
|
|
53
|
-
const { promise, resolve } = Promise.withResolvers<PrunelleApp>()
|
|
54
|
-
|
|
55
|
-
|
|
63
|
+
const { promise, resolve, reject } = Promise.withResolvers<PrunelleApp>()
|
|
64
|
+
void promise.catch(() => undefined)
|
|
65
|
+
held = { promise, resolve, reject }
|
|
66
|
+
server.reload({
|
|
67
|
+
routes: {},
|
|
68
|
+
fetch: async (request: Request) => {
|
|
69
|
+
let target: PrunelleApp
|
|
70
|
+
try {
|
|
71
|
+
target = await promise
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return new Response('Service Unavailable', { status: 503, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
75
|
+
}
|
|
76
|
+
return target.handle(request, server.requestIP(request)?.address, () => server.timeout(request, 0))
|
|
77
|
+
},
|
|
78
|
+
})
|
|
56
79
|
}
|
|
57
80
|
|
|
58
81
|
const swapIn = async (): Promise<void> => {
|
|
82
|
+
if (disposed)
|
|
83
|
+
return
|
|
59
84
|
if (loading) {
|
|
60
85
|
again = true
|
|
61
86
|
return
|
|
62
87
|
}
|
|
63
88
|
loading = true
|
|
64
89
|
const prev = current()
|
|
90
|
+
let loaded: PrunelleApp | undefined
|
|
65
91
|
try {
|
|
66
92
|
if (!landed())
|
|
67
93
|
throw new Error(isStatic ? `${shown}/ is missing or empty` : `${shown}/manifest.json is missing`)
|
|
68
|
-
|
|
94
|
+
loaded = (await startBuiltApp({ root, outDir })).app
|
|
95
|
+
if (disposed) {
|
|
96
|
+
await disposeApp(loaded)
|
|
97
|
+
loading = false
|
|
98
|
+
return
|
|
99
|
+
}
|
|
100
|
+
setCurrent(loaded)
|
|
69
101
|
console.log(`prunelle start: serving the new build in ${shown}/`)
|
|
70
102
|
}
|
|
71
103
|
catch (err) {
|
|
72
104
|
console.error(`prunelle start: the build in ${shown}/ failed to load, so the previous one keeps answering: ${err instanceof Error ? err.message : String(err)}`)
|
|
73
105
|
}
|
|
74
106
|
loading = false
|
|
107
|
+
const swapped = loaded !== undefined && current() !== prev
|
|
75
108
|
if (again) {
|
|
76
109
|
again = false
|
|
110
|
+
if (swapped)
|
|
111
|
+
void disposeApp(prev)
|
|
77
112
|
void swapIn()
|
|
78
113
|
return
|
|
79
114
|
}
|
|
80
115
|
current().reloadInto!(server)
|
|
81
116
|
held?.resolve(current())
|
|
82
117
|
held = undefined
|
|
83
|
-
if (
|
|
84
|
-
await prev
|
|
85
|
-
await prev.dispose?.()
|
|
86
|
-
}
|
|
118
|
+
if (swapped)
|
|
119
|
+
await disposeApp(prev)
|
|
87
120
|
}
|
|
88
121
|
|
|
89
122
|
const watcher = watch(dirname(outDir), (_event, file) => {
|
|
90
|
-
if (file !== name)
|
|
123
|
+
if (file !== name || disposed)
|
|
91
124
|
return
|
|
92
125
|
hold()
|
|
93
126
|
clearTimeout(timer)
|
|
@@ -95,5 +128,16 @@ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleAp
|
|
|
95
128
|
timer = setTimeout(() => void swapIn(), landed() ? 0 : SWAP_TIMEOUT_MS)
|
|
96
129
|
})
|
|
97
130
|
watcher.on('error', err => console.error(`prunelle start: stopped watching ${shown}/ for new builds: ${err.message}`))
|
|
98
|
-
return
|
|
131
|
+
return {
|
|
132
|
+
stop() {
|
|
133
|
+
disposed = true
|
|
134
|
+
clearTimeout(timer)
|
|
135
|
+
timer = undefined
|
|
136
|
+
watcher.close()
|
|
137
|
+
if (held !== undefined) {
|
|
138
|
+
held.reject(new Error('prunelle start: server disposed while reloading build'))
|
|
139
|
+
held = undefined
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
}
|
|
99
143
|
}
|