prunelle 0.1.1 → 0.5.1
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 +3 -2
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +8 -4
- package/src/build/client-prune.ts +11 -2
- package/src/build/compile.ts +2 -1
- package/src/build/ecoindex.ts +229 -0
- package/src/build/index.ts +121 -44
- 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 +2 -2
- package/src/build/report.ts +23 -2
- package/src/build/resolve.ts +4 -3
- package/src/build/routes.ts +175 -10
- package/src/build/static.ts +71 -17
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +338 -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 +17 -3
- 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.ts +7 -7
- package/src/compiler/ssr.ts +135 -37
- package/src/dev/error-log.ts +151 -0
- package/src/dev/index.ts +60 -29
- package/src/dev/open-editor.ts +204 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +3 -0
- package/src/dom/action.ts +4 -1
- 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/errors.ts +291 -62
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +86 -19
- package/src/server/index.ts +158 -219
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +40 -14
- 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 +365 -0
- package/src/server/route-table.ts +302 -6
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +187 -61
- package/src/server/security.ts +208 -32
- package/src/server/serve-handlers.ts +21 -7
- package/src/ssr/context.ts +49 -0
- package/src/ssr/index.ts +120 -1
- 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/ssr/context.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import type { CatchProps, ConsentGateProps } from '../context'
|
|
5
5
|
import type { Html, PrunelleChild } from '../jsx-runtime'
|
|
6
|
+
import type { FieldConstraint } from '../server/form-schema'
|
|
6
7
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
7
8
|
import { registerServerContextBridge } from '../context'
|
|
8
9
|
import { raw, ssrChild } from './index'
|
|
@@ -55,6 +56,8 @@ export interface RenderContext {
|
|
|
55
56
|
consent: { has(category: string): boolean } | undefined
|
|
56
57
|
/** Reports an error a `<Catch>` rendered its fallback for, to the app's error hook. */
|
|
57
58
|
onCaught: ((error: unknown) => void) | undefined
|
|
59
|
+
/** Actions referenced via `useAction(fn).action` during this request, keyed by action URL. */
|
|
60
|
+
formActions: Map<string, unknown> | undefined
|
|
58
61
|
}
|
|
59
62
|
|
|
60
63
|
interface RenderScope {
|
|
@@ -63,12 +66,25 @@ interface RenderScope {
|
|
|
63
66
|
outerContexts: ReadonlyMap<symbol, unknown> | undefined
|
|
64
67
|
island: string | undefined
|
|
65
68
|
inTarget: boolean
|
|
69
|
+
formFields: ReadonlyMap<string, FieldConstraint> | undefined
|
|
66
70
|
}
|
|
67
71
|
|
|
68
72
|
const STORAGE_KEY = Symbol.for('pru.render.storage')
|
|
69
73
|
const SCOPE_STORAGE_KEY = Symbol.for('pru.render.scope.storage')
|
|
70
74
|
const renderStorage: AsyncLocalStorage<RenderContext> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderContext> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RenderContext>())
|
|
71
75
|
const scopeStorage: AsyncLocalStorage<RenderScope> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderScope> | undefined>)[SCOPE_STORAGE_KEY] ??= new AsyncLocalStorage<RenderScope>())
|
|
76
|
+
let fallbackFormAction: { url: string, action: unknown } | undefined
|
|
77
|
+
let fallbackFormFields: ReadonlyMap<string, FieldConstraint> | undefined
|
|
78
|
+
|
|
79
|
+
;(globalThis as { __pruAct?: (url: string, action: unknown) => void }).__pruAct = (url, action) => {
|
|
80
|
+
if (url === '')
|
|
81
|
+
return
|
|
82
|
+
const ctx = renderStorage.getStore()
|
|
83
|
+
if (ctx !== undefined)
|
|
84
|
+
(ctx.formActions ??= new Map()).set(url, action)
|
|
85
|
+
else
|
|
86
|
+
fallbackFormAction = { url, action }
|
|
87
|
+
}
|
|
72
88
|
|
|
73
89
|
function activeScope(ctx: RenderContext): RenderScope {
|
|
74
90
|
const scope = scopeStorage.getStore()
|
|
@@ -80,6 +96,38 @@ function activeScope(ctx: RenderContext): RenderScope {
|
|
|
80
96
|
outerContexts: ctx.outerContexts,
|
|
81
97
|
island: ctx.island,
|
|
82
98
|
inTarget: ctx.inTarget,
|
|
99
|
+
formFields: undefined,
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function lookupFormAction(url: string): unknown {
|
|
104
|
+
const ctx = renderStorage.getStore()
|
|
105
|
+
if (ctx !== undefined)
|
|
106
|
+
return ctx.formActions?.get(url)
|
|
107
|
+
return fallbackFormAction?.url === url ? fallbackFormAction.action : undefined
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function currentFormFields(): ReadonlyMap<string, FieldConstraint> | undefined {
|
|
111
|
+
const ctx = renderStorage.getStore()
|
|
112
|
+
return ctx !== undefined ? activeScope(ctx).formFields : fallbackFormFields
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function runWithFormFields<T>(fields: ReadonlyMap<string, FieldConstraint>, fn: () => T): T {
|
|
116
|
+
const ctx = renderStorage.getStore()
|
|
117
|
+
if (ctx !== undefined)
|
|
118
|
+
return scopeStorage.run({ ...activeScope(ctx), formFields: fields }, fn)
|
|
119
|
+
const prev = fallbackFormFields
|
|
120
|
+
fallbackFormFields = fields
|
|
121
|
+
try {
|
|
122
|
+
const out = fn()
|
|
123
|
+
if (out instanceof Promise)
|
|
124
|
+
return out.finally(() => { fallbackFormFields = prev }) as T
|
|
125
|
+
fallbackFormFields = prev
|
|
126
|
+
return out
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
fallbackFormFields = prev
|
|
130
|
+
throw err
|
|
83
131
|
}
|
|
84
132
|
}
|
|
85
133
|
|
|
@@ -165,6 +213,7 @@ export function createRenderContext(
|
|
|
165
213
|
inlineStyles: undefined,
|
|
166
214
|
consent,
|
|
167
215
|
onCaught,
|
|
216
|
+
formActions: undefined,
|
|
168
217
|
}
|
|
169
218
|
}
|
|
170
219
|
|
package/src/ssr/index.ts
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
// Prunelle SSR runtime: flat string concatenation with fast-path escaping and zero-overhead islands.
|
|
2
2
|
|
|
3
3
|
import type { Html, HydrateStrategy, PrunelleChild } from '../jsx-runtime'
|
|
4
|
+
import type { ServerAction } from '../server/action'
|
|
5
|
+
import type { FieldConstraint } from '../server/form-schema'
|
|
4
6
|
import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
|
|
5
7
|
import { renderOnServer } from '../reactivity/index'
|
|
8
|
+
import { renderProtectFields } from '../server/action-protect'
|
|
9
|
+
import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
|
|
6
10
|
import { styleText } from '../style'
|
|
7
11
|
import { assertRenderable } from '../unrenderable'
|
|
8
|
-
import { currentRenderContext, PRUNELLE_STREAM_SCRIPT, renderIsland } from './context'
|
|
12
|
+
import { currentFormFields, currentRenderContext, lookupFormAction, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
|
|
9
13
|
import { keepScrollTag } from './navigation'
|
|
10
14
|
export { ssrStyleBlock } from './context'
|
|
11
15
|
|
|
@@ -143,6 +147,8 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
|
|
|
143
147
|
if (props == null || typeof props !== 'object')
|
|
144
148
|
return ''
|
|
145
149
|
let out = ''
|
|
150
|
+
let formPresent = 0
|
|
151
|
+
const trackForm = (tag === 'input' || tag === 'select' || tag === 'textarea') && currentFormFields() !== undefined
|
|
146
152
|
for (const [rawKey, value] of Object.entries(props)) {
|
|
147
153
|
if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
|
|
148
154
|
continue
|
|
@@ -151,8 +157,121 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
|
|
|
151
157
|
const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
|
|
152
158
|
if (isBlockedAttr(name))
|
|
153
159
|
continue
|
|
160
|
+
if (trackForm && value !== undefined) {
|
|
161
|
+
const bit = FORM_ATTR_BITS[name.toLowerCase()]
|
|
162
|
+
if (bit !== undefined)
|
|
163
|
+
formPresent |= bit
|
|
164
|
+
}
|
|
154
165
|
out += name === 'style' ? ssrStyle(value) : ssrAttr(name, value, tag)
|
|
155
166
|
}
|
|
167
|
+
if (trackForm && typeof props.name === 'string')
|
|
168
|
+
out += ssrFormAttrs(tag, props.name, formPresent, props.type)
|
|
169
|
+
return out
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const FORM_ATTR_BITS: Record<string, number> = {
|
|
173
|
+
type: 1,
|
|
174
|
+
required: 2,
|
|
175
|
+
minlength: 4,
|
|
176
|
+
maxlength: 8,
|
|
177
|
+
min: 16,
|
|
178
|
+
max: 32,
|
|
179
|
+
step: 64,
|
|
180
|
+
pattern: 128,
|
|
181
|
+
}
|
|
182
|
+
const TEXT_INPUT_TYPES = new Set(['text', 'search', 'url', 'tel', 'email', 'password'])
|
|
183
|
+
const NON_REQUIRED_INPUT_TYPES = new Set(['hidden', 'submit', 'button', 'reset', 'image'])
|
|
184
|
+
|
|
185
|
+
function resolveActionForForm(action: unknown): ServerAction<unknown, unknown> | undefined {
|
|
186
|
+
if (typeof action === 'function' && (action as { __pruAction?: boolean }).__pruAction === true)
|
|
187
|
+
return action as ServerAction<unknown, unknown>
|
|
188
|
+
if (typeof action === 'string') {
|
|
189
|
+
const found = lookupFormAction(action)
|
|
190
|
+
if (typeof found === 'function' && (found as { __pruAction?: boolean }).__pruAction === true)
|
|
191
|
+
return found as ServerAction<unknown, unknown>
|
|
192
|
+
}
|
|
193
|
+
return undefined
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function formFieldsOf(act: ServerAction<unknown, unknown>): ReadonlyMap<string, FieldConstraint> | undefined {
|
|
197
|
+
if (act.schema === undefined)
|
|
198
|
+
return undefined
|
|
199
|
+
const extracted = extractFormSchema(act.schema)
|
|
200
|
+
return extracted.ok && extracted.fields.size > 0 ? extracted.fields : undefined
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Wraps an action-bound `<form>` render during SSR: injects schema constraints for child fields and appends honeypot / signed timestamp inputs. */
|
|
204
|
+
export function ssrForm(action: unknown, render: (action: unknown) => string): string {
|
|
205
|
+
const act = resolveActionForForm(action)
|
|
206
|
+
if (act === undefined)
|
|
207
|
+
return `${render(action)}</form>`
|
|
208
|
+
const hidden = renderProtectFields(act.protect, act.url)
|
|
209
|
+
const fields = formFieldsOf(act)
|
|
210
|
+
const body = fields !== undefined ? runWithFormFields(fields, () => render(action)) : render(action)
|
|
211
|
+
return `${body}${hidden}</form>`
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Async variant of `ssrForm` for action-bound `<form>` elements containing `await`. */
|
|
215
|
+
export async function ssrFormAsync(action: unknown, render: (action: unknown) => Promise<string>): Promise<string> {
|
|
216
|
+
const act = resolveActionForForm(action)
|
|
217
|
+
if (act === undefined)
|
|
218
|
+
return `${await render(action)}</form>`
|
|
219
|
+
const hidden = renderProtectFields(act.protect, act.url)
|
|
220
|
+
const fields = formFieldsOf(act)
|
|
221
|
+
const body = fields !== undefined ? await runWithFormFields(fields, () => render(action)) : await render(action)
|
|
222
|
+
return `${body}${hidden}</form>`
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Emits schema-derived HTML5 constraint attributes on `<input>`, `<select>`, and `<textarea>` inside an action-bound `<form>`. */
|
|
226
|
+
export function ssrFormAttrs(tag: 'input' | 'select' | 'textarea', name: unknown, present: number, inputType?: unknown): string {
|
|
227
|
+
const fields = currentFormFields()
|
|
228
|
+
if (fields === undefined || typeof name !== 'string' || name === '')
|
|
229
|
+
return ''
|
|
230
|
+
const c = lookupFieldConstraint(fields, name)
|
|
231
|
+
if (c === undefined)
|
|
232
|
+
return ''
|
|
233
|
+
|
|
234
|
+
let out = ''
|
|
235
|
+
const explicitType = typeof inputType === 'string' ? inputType.toLowerCase() : undefined
|
|
236
|
+
let effectiveType: string | undefined
|
|
237
|
+
if (tag === 'input') {
|
|
238
|
+
if (explicitType === undefined && (present & 1) === 0 && c.type !== undefined) {
|
|
239
|
+
out += ` type="${c.type}"`
|
|
240
|
+
effectiveType = c.type
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
effectiveType = explicitType ?? 'text'
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const skipRequired = tag === 'input' && (
|
|
248
|
+
NON_REQUIRED_INPUT_TYPES.has(effectiveType!)
|
|
249
|
+
|| (effectiveType === 'checkbox' && c.isArray === true)
|
|
250
|
+
)
|
|
251
|
+
if (c.required === true && (present & 2) === 0 && !skipRequired)
|
|
252
|
+
out += ' required'
|
|
253
|
+
|
|
254
|
+
const supportsLength = tag === 'textarea' || (tag === 'input' && TEXT_INPUT_TYPES.has(effectiveType!))
|
|
255
|
+
if (supportsLength) {
|
|
256
|
+
if (c.minLength !== undefined && (present & 4) === 0)
|
|
257
|
+
out += ` minlength="${c.minLength}"`
|
|
258
|
+
if (c.maxLength !== undefined && (present & 8) === 0)
|
|
259
|
+
out += ` maxlength="${c.maxLength}"`
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (tag === 'input') {
|
|
263
|
+
if (effectiveType === 'number' || effectiveType === 'range') {
|
|
264
|
+
if (c.min !== undefined && (present & 16) === 0)
|
|
265
|
+
out += ` min="${c.min}"`
|
|
266
|
+
if (c.max !== undefined && (present & 32) === 0)
|
|
267
|
+
out += ` max="${c.max}"`
|
|
268
|
+
if (c.step !== undefined && (present & 64) === 0)
|
|
269
|
+
out += ` step="${c.step}"`
|
|
270
|
+
}
|
|
271
|
+
if (TEXT_INPUT_TYPES.has(effectiveType!) && c.pattern !== undefined && (present & 128) === 0)
|
|
272
|
+
out += ` pattern="${escAttr(c.pattern)}"`
|
|
273
|
+
}
|
|
274
|
+
|
|
156
275
|
return out
|
|
157
276
|
}
|
|
158
277
|
|
package/src/test/browser.ts
CHANGED
|
@@ -23,6 +23,8 @@ export interface BrowserPage {
|
|
|
23
23
|
/** Moves the pointer over the first element matching `selector`, as a visitor hovering a link does. */
|
|
24
24
|
hover(selector: string): Promise<void>
|
|
25
25
|
fill(selector: string, value: string): Promise<void>
|
|
26
|
+
/** Presses a key (`'Escape'`, `'ArrowRight'`, `'Tab'`) through the browser's keyboard input pipeline. */
|
|
27
|
+
press(key: string): Promise<void>
|
|
26
28
|
/** The text content of the first element matching `selector`. */
|
|
27
29
|
text(selector: string): Promise<string>
|
|
28
30
|
close(): Promise<void>
|
|
@@ -53,6 +55,7 @@ interface Page {
|
|
|
53
55
|
click(selector: string, options: { timeout: number }): Promise<void>
|
|
54
56
|
hover(selector: string, options: { timeout: number }): Promise<void>
|
|
55
57
|
fill(selector: string, value: string, options: { timeout: number }): Promise<void>
|
|
58
|
+
keyboard: { press(key: string): Promise<void> }
|
|
56
59
|
locator(selector: string): { first: () => { innerText: (options: { timeout: number }) => Promise<string> } }
|
|
57
60
|
}
|
|
58
61
|
interface BrowserContext {
|
|
@@ -126,6 +129,9 @@ function wrapPage(page: Page, context: BrowserContext, timeout: number, url: str
|
|
|
126
129
|
async fill(selector, value) {
|
|
127
130
|
await page.fill(selector, value, { timeout })
|
|
128
131
|
},
|
|
132
|
+
async press(key) {
|
|
133
|
+
await page.keyboard.press(key)
|
|
134
|
+
},
|
|
129
135
|
async text(selector) {
|
|
130
136
|
return await page.locator(selector).first().innerText({ timeout })
|
|
131
137
|
},
|