prunelle 0.1.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -1,55 +1,29 @@
1
1
  // Unified server actions: works as both progressive <form action={fn} method="post"> and typed island RPC.
2
2
 
3
+ import type { ActionProtectOptions } from './action-protect'
3
4
  import type { Cookies } from './cookies'
5
+ import type { RequestContext } from './http'
4
6
  import type { PrunelleLocals } from './index'
5
7
  import type { RateLimit, RateLimiter } from './rate-limit'
6
8
  import type { TrustProxy } from './security'
7
9
  import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
8
- import { wantsJson } from './http'
10
+ import { ACTION_ERROR_COOKIE, buildActionErrorFlash, flashAllowlist } from './action-flash'
11
+ import { assertActionProtect, needsProtectBody, verifyActionProtection } from './action-protect'
12
+ import { isExternalRedirect, wantsJson } from './http'
9
13
  import { assertRateLimit, hitFor, tooManyRequests } from './rate-limit'
10
14
  import { currentRequest } from './request-scope'
11
15
  import { isTrustedOrigin } from './security'
12
16
  import { validateSchema } from './standard-schema'
13
17
 
18
+ export { ACTION_ERROR_COOKIE, hydrateActionErrorFlash } from './action-flash'
19
+ export type { ActionProtectOptions } from './action-protect'
20
+
14
21
  declare module './index' {
15
22
  interface PrunelleLocals {
16
23
  actionError?: ActionErrorFlash | undefined
17
24
  }
18
25
  }
19
26
 
20
- export const ACTION_ERROR_COOKIE = '__pru_action_err'
21
-
22
- const MAX_FLASH_COOKIE_BYTES = 3500
23
- const MAX_FLASH_FIELD_CHARS = 512
24
- // Substrings that are unambiguously sensitive even inside compound identifiers.
25
- const SENSITIVE_SUBSTRING_RE = /password|passwd|passphrase|passcode|motdepasse|secret|token|jeton|credit|debit|card|carte|iban|routing|account|compte|bank|banque|bancaire|securite|vitale|passeport|passport|fiscal|impot|crypto|sante|medical|health|biometr|credential|private|session|bearer|csrf|xsrf|naissance/i
26
- // Short acronyms/words matched only on token boundaries (after camelCase/punctuation/accent normalization) to avoid false positives like `subscribe`, `article`, `souvenir`, or `description`.
27
- const SENSITIVE_TOKEN_RE = /\b(?:mot de passe|mdp|pwd|pin|cvv|cvc|csc|ccv|rib|bic|sepa|cb|nir|secu|insee|cni|siret|siren|permis|ssn|sin|nin|tin|pan|otp|totp|mfa|2fa|auth|key|cle|code|tax|jwt)\b/i
28
-
29
- function isSensitiveField(name: string): boolean {
30
- const normalized = name
31
- .normalize('NFD')
32
- .replace(/[\u0300-\u036f]/g, '')
33
- .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
34
- .replace(/[^a-zA-Z0-9]+/g, ' ')
35
- .trim()
36
- return SENSITIVE_SUBSTRING_RE.test(normalized) || SENSITIVE_TOKEN_RE.test(normalized)
37
- }
38
-
39
- /** Hydrates `ctx.locals.actionError` from `__pru_action_err` without clearing the cookie yet; returns true when the cookie was present. */
40
- export function hydrateActionErrorFlash(ctx: Pick<ActionContext, 'cookies' | 'locals'>): boolean {
41
- const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
42
- if (rawFlash === undefined)
43
- return false
44
- try {
45
- const parsed: unknown = JSON.parse(rawFlash)
46
- if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed))
47
- ctx.locals.actionError = parsed as unknown as ActionErrorFlash
48
- }
49
- catch {}
50
- return true
51
- }
52
-
53
27
  /** Converts 3xx action/middleware redirects into a 204 + `x-pru-redirect` header for `actionStub` (`x-pru-action: 1`), preventing double-fetch and cross-origin CORS failures in browsers. */
54
28
  export function finishActionRedirect(res: Response, request: Request): Response {
55
29
  if (request.headers.get('x-pru-action') !== '1' || res.status < 300 || res.status >= 400)
@@ -61,14 +35,19 @@ export function finishActionRedirect(res: Response, request: Request): Response
61
35
  for (const cookie of res.headers.getSetCookie())
62
36
  headers.append('set-cookie', cookie)
63
37
  headers.set('x-pru-redirect', location)
38
+ // The call from an island follows a target on another site only when the app said it chose it.
39
+ if (isExternalRedirect(res))
40
+ headers.set('x-pru-redirect-external', '1')
64
41
  return new Response(null, { status: 204, headers })
65
42
  }
66
43
 
67
44
  export interface ActionOptions {
68
- /** Explicit allowlist of form field names permitted in the progressive-form validation error flash cookie. */
45
+ /** The form fields an error puts back in the form, in place of the fields the schema declares (minus anything that reads as a secret); a schema with no JSON Schema output declares none, so list them here. */
69
46
  flashFields?: readonly string[] | undefined
70
47
  /** How often one client may submit it: past `max` per `windowMs`, a call from script gets a 429 with `Retry-After` and a form comes back with the error. */
71
48
  rateLimit?: RateLimit<ActionContext> | undefined
49
+ /** Public form spam & abuse protection: rate limit, hidden honeypot field, and minimum render-to-submit time. */
50
+ protect?: ActionProtectOptions | undefined
72
51
  }
73
52
 
74
53
  export interface ActionErrorFlash {
@@ -88,7 +67,7 @@ export interface ActionContext {
88
67
  cookies: Cookies
89
68
  locals: PrunelleLocals
90
69
  ip?: string | undefined
91
- redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
70
+ redirect: RequestContext['redirect']
92
71
  deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
93
72
  }
94
73
 
@@ -103,6 +82,7 @@ export interface ServerAction<Input, Output> {
103
82
  readonly schema: StandardSchemaV1 | undefined
104
83
  readonly flashFields: readonly string[] | undefined
105
84
  readonly rateLimit: RateLimit<ActionContext> | undefined
85
+ readonly protect: ActionProtectOptions | undefined
106
86
  readonly handler: (input: never, ctx: ActionContext) => Output | Response | Promise<Output | Response>
107
87
  toString(): string
108
88
  }
@@ -132,8 +112,11 @@ export function action(
132
112
  ? (maybeHandlerOrOpts as (input: never, ctx: ActionContext) => unknown)
133
113
  : ((_input: never, ctx: ActionContext) => (schemaOrHandler as (c: ActionContext) => unknown)(ctx))
134
114
  const options = hasSchema ? maybeOpts : (maybeHandlerOrOpts as ActionOptions | undefined)
135
- if (options?.rateLimit !== undefined)
136
- assertRateLimit(options.rateLimit, 'an action')
115
+ if (options?.protect !== undefined)
116
+ assertActionProtect(options.protect)
117
+ const effectiveRateLimit = options?.protect?.rateLimit ?? options?.rateLimit
118
+ if (effectiveRateLimit !== undefined && options?.protect?.rateLimit === undefined)
119
+ assertRateLimit(effectiveRateLimit, 'an action')
137
120
 
138
121
  const fn = (async (input: unknown) => {
139
122
  const scope = currentRequest()
@@ -148,7 +131,8 @@ export function action(
148
131
  __pruAction: { value: true, enumerable: false },
149
132
  schema: { value: schema, enumerable: false },
150
133
  flashFields: { value: options?.flashFields, enumerable: false },
151
- rateLimit: { value: options?.rateLimit, enumerable: false },
134
+ rateLimit: { value: effectiveRateLimit, enumerable: false },
135
+ protect: { value: options?.protect, enumerable: false },
152
136
  handler: { value: handler, enumerable: false },
153
137
  url: { value: '', writable: true, enumerable: true },
154
138
  toString: {
@@ -167,7 +151,7 @@ export function isServerAction(value: unknown): value is ServerAction<unknown, u
167
151
  }
168
152
 
169
153
  async function parseActionBody(boundedReq: Request): Promise<unknown> {
170
- const contentType = boundedReq.headers.get('content-type') ?? ''
154
+ const contentType = (boundedReq.headers.get('content-type') ?? '').toLowerCase()
171
155
  if (contentType.includes('application/json'))
172
156
  return boundedReq.json()
173
157
 
@@ -193,7 +177,7 @@ async function parseActionBody(boundedReq: Request): Promise<unknown> {
193
177
  }
194
178
 
195
179
  function isJsonBody(request: Request): boolean {
196
- return (request.headers.get('content-type') ?? '').includes('application/json')
180
+ return (request.headers.get('content-type') ?? '').toLowerCase().includes('application/json')
197
181
  }
198
182
 
199
183
  // The page a form came from, when its origin is one this server trusts: where a no-JS submit goes back to.
@@ -278,64 +262,6 @@ async function retryWithFormArrays(schema: StandardSchemaV1, body: Record<string
278
262
  return kept.length === wrapped.length ? second : validateSchema(schema, retried)
279
263
  }
280
264
 
281
- function encodedFlashSize(flash: ActionErrorFlash): number {
282
- return Buffer.byteLength(encodeURIComponent(JSON.stringify(flash)), 'utf8')
283
- }
284
-
285
- function buildActionErrorFlash(
286
- actionUrl: string,
287
- error: string,
288
- fieldErrors: Record<string, string> | undefined,
289
- rawBody: unknown,
290
- flashFields?: readonly string[],
291
- ): string {
292
- const trimmedError = error.length > 256 ? error.slice(0, 256) : error
293
- const base: ActionErrorFlash = {
294
- action: actionUrl,
295
- error: trimmedError,
296
- }
297
- if (fieldErrors !== undefined) {
298
- const safeErrors: Record<string, string> = {}
299
- base.fieldErrors = safeErrors
300
- for (const [k, msg] of Object.entries(fieldErrors)) {
301
- const trimmed = msg.length > 256 ? msg.slice(0, 256) : msg
302
- safeErrors[k] = trimmed
303
- if (encodedFlashSize(base) > MAX_FLASH_COOKIE_BYTES) {
304
- delete safeErrors[k]
305
- break
306
- }
307
- }
308
- }
309
-
310
- const allowSet = flashFields !== undefined ? new Set(flashFields) : undefined
311
- const values: Record<string, string> = {}
312
- if (rawBody !== null && typeof rawBody === 'object') {
313
- for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
314
- if (typeof v !== 'string' || v.length > MAX_FLASH_FIELD_CHARS)
315
- continue
316
- if (allowSet !== undefined) {
317
- if (!allowSet.has(k))
318
- continue
319
- }
320
- else if (isSensitiveField(k)) {
321
- continue
322
- }
323
- values[k] = v
324
- const candidate: ActionErrorFlash = { ...base, values }
325
- if (encodedFlashSize(candidate) > MAX_FLASH_COOKIE_BYTES) {
326
- delete values[k]
327
- break
328
- }
329
- }
330
- }
331
-
332
- const finalFlash: ActionErrorFlash = {
333
- ...base,
334
- ...(Object.keys(values).length > 0 ? { values } : {}),
335
- }
336
- return JSON.stringify(finalFlash)
337
- }
338
-
339
265
  /** Programmatic action invocation with Standard Schema validation (used by `ServerPluginAPI.invokeAction` inside middleware chains). */
340
266
  export async function invokeActionCore<I, O>(
341
267
  act: ServerAction<I, O>,
@@ -362,7 +288,7 @@ export async function invokeActionCore<I, O>(
362
288
  if (result.status >= 300 && result.status < 400)
363
289
  return { ok: true, data: result as unknown as O }
364
290
  const ok = result.status >= 200 && result.status < 300
365
- const ct = result.headers.get('content-type') ?? ''
291
+ const ct = (result.headers.get('content-type') ?? '').toLowerCase()
366
292
  if (ct.includes('application/json')) {
367
293
  try {
368
294
  const body = await result.clone().json() as Record<string, unknown>
@@ -399,30 +325,53 @@ export async function executeAction(
399
325
  const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy, ctx.url)
400
326
  if (back === undefined)
401
327
  return undefined
402
- ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, error, fieldErrors, rawBody, act.flashFields), {
328
+ ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, error, fieldErrors, rawBody, flashAllowlist(act)), {
403
329
  httpOnly: true,
404
330
  sameSite: 'lax',
405
331
  maxAge: 60,
332
+ category: 'essential',
406
333
  })
407
334
  return new Response(null, { status: 303, headers: { location: back.href } })
408
335
  }
409
336
 
337
+ // Enforce rate limit before parsing bodies or running schema/protection checks so invalid floods cannot bypass throttling.
338
+ const retryAfter = limiter !== undefined && act.rateLimit !== undefined ? hitFor(limiter, act.rateLimit, ctx) : 0
339
+ if (retryAfter > 0) {
340
+ const redirected = flashAndRedirect('Too many requests', undefined, undefined)
341
+ if (redirected === undefined)
342
+ return tooManyRequests(retryAfter)
343
+ redirected.headers.set('retry-after', String(retryAfter))
344
+ return redirected
345
+ }
346
+
410
347
  let rawBody: unknown
411
348
  let input: unknown
412
- if (act.schema !== undefined) {
349
+ const wantsBody = act.schema !== undefined || needsProtectBody(act.protect)
350
+ if (wantsBody) {
413
351
  try {
414
352
  rawBody = await parseActionBody(request)
415
353
  }
416
354
  catch {
417
355
  return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
418
356
  }
357
+ }
419
358
 
420
- let checked = await validateSchema(act.schema, rawBody)
421
- if (!checked.ok && !isJsonBody(request) && rawBody !== null && typeof rawBody === 'object' && !Array.isArray(rawBody))
422
- checked = await retryWithFormArrays(act.schema, rawBody as Record<string, unknown>, checked)
359
+ const protectedBody = verifyActionProtection(act.protect, rawBody, Date.now(), act.url)
360
+ const cleanBody = protectedBody.cleanedBody
361
+ if (!protectedBody.ok) {
362
+ const redirected = flashAndRedirect(protectedBody.error, undefined, cleanBody)
363
+ if (redirected !== undefined)
364
+ return redirected
365
+ return Response.json({ ok: false, status: 400, error: protectedBody.error }, { status: 400 })
366
+ }
367
+
368
+ if (act.schema !== undefined) {
369
+ let checked = await validateSchema(act.schema, cleanBody)
370
+ if (!checked.ok && !isJsonBody(request) && cleanBody !== null && typeof cleanBody === 'object' && !Array.isArray(cleanBody))
371
+ checked = await retryWithFormArrays(act.schema, cleanBody as Record<string, unknown>, checked)
423
372
  if (!checked.ok) {
424
373
  // Zero-JS progressive HTML <form> submit: flash fieldErrors + safe submitted values (<4KB) and redirect 303 back to trusted Referer
425
- const redirected = flashAndRedirect('Validation failed', checked.fieldErrors, rawBody)
374
+ const redirected = flashAndRedirect('Validation failed', checked.fieldErrors, cleanBody)
426
375
  if (redirected !== undefined)
427
376
  return redirected
428
377
  return Response.json(
@@ -433,16 +382,6 @@ export async function executeAction(
433
382
  input = checked.value
434
383
  }
435
384
 
436
- // Counted once the body is read, so a refused form comes back with what was typed in it.
437
- const retryAfter = limiter !== undefined && act.rateLimit !== undefined ? hitFor(limiter, act.rateLimit, ctx) : 0
438
- if (retryAfter > 0) {
439
- const redirected = flashAndRedirect('Too many requests', undefined, rawBody)
440
- if (redirected === undefined)
441
- return tooManyRequests(retryAfter)
442
- redirected.headers.set('retry-after', String(retryAfter))
443
- return redirected
444
- }
445
-
446
385
  // Track exact Response instances produced by `ctx.deny()` so zero-JS form submits flash & 303-redirect while custom Responses (redirects, downloads, custom JSON) pass through untouched.
447
386
  let deniedResponses: Map<Response, { message: string, fieldErrors?: Record<string, string> | undefined }> | undefined
448
387
  const actionCtx: ActionContext = Object.create(ctx, {
@@ -460,7 +399,7 @@ export async function executeAction(
460
399
  if (result instanceof Response) {
461
400
  const denied = deniedResponses?.get(result)
462
401
  if (denied !== undefined) {
463
- const redirected = flashAndRedirect(denied.message, denied.fieldErrors, rawBody)
402
+ const redirected = flashAndRedirect(denied.message, denied.fieldErrors, cleanBody)
464
403
  if (redirected !== undefined)
465
404
  return redirected
466
405
  }
@@ -0,0 +1,63 @@
1
+ // The app's signing secret, and one key per purpose derived from it with HKDF so a token made for one use never verifies for another.
2
+ // HMAC goes through Bun.CryptoHasher, never `node:crypto`, which would add 2 MB to the server's RSS.
3
+
4
+ const EPHEMERAL_SECRET_KEY = Symbol.for('pru.form.secret')
5
+ const keyCache = new Map<string, Buffer>()
6
+
7
+ const hmac = (key: string | Buffer, data: string | Buffer): Buffer => new Bun.CryptoHasher('sha256', key).update(data).digest()
8
+
9
+ /** The configured secret (`PRUNELLE_FORM_SECRET`, then `AUTH_SECRET`), or one random per process that dies with it. */
10
+ export function appSecret(): { secret: string, ephemeral: boolean } {
11
+ const configured = process.env.PRUNELLE_FORM_SECRET || process.env.AUTH_SECRET
12
+ if (configured)
13
+ return { secret: configured, ephemeral: false }
14
+ const g = globalThis as Record<symbol, string | undefined>
15
+ let secret = g[EPHEMERAL_SECRET_KEY]
16
+ if (secret === undefined) {
17
+ secret = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('hex')
18
+ g[EPHEMERAL_SECRET_KEY] = secret
19
+ }
20
+ return { secret, ephemeral: true }
21
+ }
22
+
23
+ /** A 32-byte key for `purpose` (`"form-timestamp"`, `"action-flash"`), HKDF-SHA256 (RFC 5869) of the app secret with `"prunelle"` as salt and the purpose as `info`. */
24
+ export function deriveKey(purpose: string): Buffer {
25
+ const { secret } = appSecret()
26
+ const id = `${purpose}\0${secret}`
27
+ let key = keyCache.get(id)
28
+ if (key === undefined) {
29
+ // One SHA-256 block is the 32 bytes asked for, so the expand step is its first round alone.
30
+ key = hmac(hmac('prunelle', secret), Buffer.concat([Buffer.from(purpose), Buffer.of(1)]))
31
+ if (keyCache.size > 16)
32
+ keyCache.clear()
33
+ keyCache.set(id, key)
34
+ }
35
+ return key
36
+ }
37
+
38
+ /**
39
+ * 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.
40
+ * The digests are XORed byte by byte rather than passed to `node:crypto`.
41
+ */
42
+ export function safeEqual(a: string, b: string): boolean {
43
+ const x = new Bun.CryptoHasher('sha256').update(a).digest()
44
+ const y = new Bun.CryptoHasher('sha256').update(b).digest()
45
+ let diff = 0
46
+ for (let i = 0; i < x.length; i++)
47
+ diff |= x[i]! ^ y[i]!
48
+ return diff === 0
49
+ }
50
+
51
+ /** `<signature>.<payload>`: the payload as is, behind the HMAC-SHA256 (base64url) of it under the key for `purpose`. */
52
+ export function signPayload(purpose: string, payload: string): string {
53
+ return `${hmac(deriveKey(purpose), payload).toString('base64url')}.${payload}`
54
+ }
55
+
56
+ /** The payload of a `signPayload` value, or undefined when it is not one or its signature does not match. */
57
+ export function verifyPayload(purpose: string, signed: string): string | undefined {
58
+ const dot = signed.indexOf('.')
59
+ if (dot <= 0)
60
+ return undefined
61
+ const payload = signed.slice(dot + 1)
62
+ return safeEqual(signed.slice(0, dot), hmac(deriveKey(purpose), payload).toString('base64url')) ? payload : undefined
63
+ }
@@ -34,6 +34,26 @@ export interface PrerenderedSources {
34
34
  isFast: (urlPath: string, route: RouteManifestEntry) => boolean
35
35
  }
36
36
 
37
+ const EXTRA_PRERENDER_MIME: Record<string, string> = {
38
+ '.htm': 'text/html; charset=utf-8',
39
+ '.rss': 'application/rss+xml; charset=utf-8',
40
+ '.atom': 'application/atom+xml; charset=utf-8',
41
+ '.ics': 'text/calendar; charset=utf-8',
42
+ '.csv': 'text/csv; charset=utf-8',
43
+ }
44
+
45
+ function prerenderedMime(ext: string, filePath: string | undefined): string {
46
+ const mapped = MIME[ext] ?? EXTRA_PRERENDER_MIME[ext]
47
+ if (mapped !== undefined)
48
+ return mapped
49
+ if (filePath !== undefined) {
50
+ const probed = Bun.file(filePath).type
51
+ if (probed && probed !== 'application/octet-stream')
52
+ return probed
53
+ }
54
+ return 'application/octet-stream'
55
+ }
56
+
37
57
  const embedded = (body: EmbeddedBody): FileSource => typeof body === 'string' ? { path: body } : { bytes: body }
38
58
 
39
59
 
@@ -102,6 +122,12 @@ export function createAssets(options: AssetsOptions) {
102
122
  }))
103
123
  }
104
124
 
125
+ const nonHtmlSecurity: Record<string, string> = {}
126
+ for (const [k, v] of Object.entries(securityRecord)) {
127
+ if (k !== 'content-security-policy')
128
+ nonHtmlSecurity[k] = v
129
+ }
130
+
105
131
  // Prerendered pages (zero-copy file paths preferred; raw HTML strings supported). `fast` holds those nothing may intercept.
106
132
  function collectPrerendered(routes: readonly RouteManifestEntry[], sources: PrerenderedSources): { all: Map<string, ServedFile>, fast: Map<string, ServedFile> } {
107
133
  const all = new Map<string, ServedFile>()
@@ -115,13 +141,19 @@ export function createAssets(options: AssetsOptions) {
115
141
  const source: FileSource | undefined = filePath !== undefined ? { path: filePath } : html !== undefined ? { text: html } : undefined
116
142
  if (source === undefined)
117
143
  continue
144
+ const ext = extname(relHtml).toLowerCase()
145
+ const isHtml = ext === '.html' || ext === '.htm' || (ext === '' && html !== undefined)
118
146
  const sidecars = sidecarsOf(sources.prerenderedFiles, relHtml)
147
+ const type = isHtml ? 'text/html; charset=utf-8' : prerenderedMime(ext, filePath)
148
+ const headers = isHtml
149
+ ? sources.htmlHeaders(route, urlPath)
150
+ : { 'content-type': type, ...nonHtmlSecurity }
119
151
  const entry = servedFile({
120
152
  key: `pre:${urlPath}`,
121
153
  source,
122
154
  etag: sources.prerenderedEtags[relHtml],
123
- headers: sources.htmlHeaders(route, urlPath),
124
- compressible: sidecars.br === undefined && sidecars.gz === undefined && compressCache !== undefined,
155
+ headers,
156
+ compressible: sidecars.br === undefined && sidecars.gz === undefined && (isHtml ? compressCache !== undefined : compressible(type)),
125
157
  ...sidecars,
126
158
  })
127
159
  all.set(urlPath, entry)
@@ -17,6 +17,9 @@ const COMPRESSIBLE_EXACT = new Set([
17
17
  'application/atom+xml',
18
18
  'application/wasm',
19
19
  'image/svg+xml',
20
+ 'image/x-icon',
21
+ 'font/ttf',
22
+ 'font/otf',
20
23
  ])
21
24
 
22
25
  export function isCompressibleType(contentType: string | null | undefined): boolean {
@@ -380,7 +383,8 @@ export function compressedHtmlResponse(
380
383
  if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
381
384
  const enc = pickEncoding(request.headers.get('accept-encoding'))
382
385
  if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
383
- const staticKey = reuse ? `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}` : undefined
386
+ // SHA-256 of the page, so two pages never share a kept body: a 64-bit hash could be made to collide by a page that renders the query string.
387
+ const staticKey = reuse ? `s:${new Bun.CryptoHasher('sha256').update(html).digest('base64url')}` : undefined
384
388
  let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
385
389
  if (compressed === undefined)
386
390
  compressed = cache.compress(html, enc, staticKey)
@@ -438,34 +442,111 @@ function zstdFrames(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array
438
442
  }, { highWaterMark: 0 })
439
443
  }
440
444
 
445
+ function tryCloseController(controller: ReadableStreamDefaultController<Uint8Array>): boolean {
446
+ try {
447
+ controller.close()
448
+ return true
449
+ }
450
+ catch {
451
+ return false
452
+ }
453
+ }
454
+
455
+ function tryErrorController(controller: ReadableStreamDefaultController<Uint8Array>, error: unknown): boolean {
456
+ try {
457
+ controller.error(error)
458
+ return true
459
+ }
460
+ catch {
461
+ return false
462
+ }
463
+ }
464
+
441
465
  /** One gzip stream flushed after each chunk: concatenated gzip members would stop a browser after the first. */
442
466
  async function gzipFlushed(body: ReadableStream<Uint8Array>): Promise<ReadableStream<Uint8Array>> {
443
467
  const { constants, createGzip } = await (zlib ??= import('node:zlib'))
444
468
  const compressor = createGzip({ level: GZIP_PER_RESPONSE, flush: constants.Z_SYNC_FLUSH })
445
469
  const reader = body.getReader()
470
+ let closed = false
446
471
  let ended: Promise<void> | undefined
472
+ let resolveEnded: (() => void) | undefined
473
+ const markEnded = (): void => {
474
+ resolveEnded?.()
475
+ resolveEnded = undefined
476
+ }
447
477
  return new ReadableStream<Uint8Array>({
448
478
  start(controller) {
449
- compressor.on('data', (chunk: Uint8Array) => controller.enqueue(chunk))
450
- compressor.once('end', () => controller.close())
451
- compressor.once('error', error => controller.error(error))
479
+ compressor.on('data', (chunk: Uint8Array) => {
480
+ if (closed)
481
+ return
482
+ try {
483
+ controller.enqueue(chunk)
484
+ }
485
+ catch {
486
+ closed = true
487
+ markEnded()
488
+ compressor.destroy()
489
+ }
490
+ })
491
+ compressor.once('end', () => {
492
+ if (!closed) {
493
+ closed = true
494
+ tryCloseController(controller)
495
+ }
496
+ markEnded()
497
+ })
498
+ compressor.on('error', (error: unknown) => {
499
+ if (!closed) {
500
+ closed = true
501
+ tryErrorController(controller, error)
502
+ }
503
+ markEnded()
504
+ })
505
+ compressor.once('close', () => {
506
+ closed = true
507
+ markEnded()
508
+ })
452
509
  },
453
510
  async pull() {
511
+ if (closed)
512
+ return
454
513
  if (ended !== undefined)
455
514
  return ended
456
- const next = await reader.read().catch((error: unknown) => {
515
+ let next: Awaited<ReturnType<typeof reader.read>>
516
+ try {
517
+ next = await reader.read()
518
+ }
519
+ catch (error: unknown) {
520
+ closed = true
521
+ markEnded()
457
522
  compressor.destroy()
458
523
  throw error
459
- })
524
+ }
525
+ if (closed)
526
+ return
460
527
  if (next.done) {
461
- ended = new Promise(resolve => compressor.once('end', resolve))
528
+ if (compressor.readableEnded || compressor.destroyed) {
529
+ closed = true
530
+ return
531
+ }
532
+ ended = new Promise<void>((resolve) => {
533
+ resolveEnded = resolve
534
+ })
462
535
  compressor.end()
463
536
  return ended
464
537
  }
465
538
  // The compressor emits the flushed bytes before it calls back, so each chunk leaves before the next one is read.
466
- await new Promise<void>((resolve, reject) => compressor.write(next.value, error => error ? reject(error) : resolve()))
539
+ await new Promise<void>((resolve, reject) => {
540
+ if (closed || compressor.destroyed) {
541
+ resolve()
542
+ return
543
+ }
544
+ compressor.write(next.value, error => (error && !closed ? reject(error) : resolve()))
545
+ })
467
546
  },
468
547
  cancel(reason) {
548
+ closed = true
549
+ markEnded()
469
550
  compressor.destroy()
470
551
  return reader.cancel(reason)
471
552
  },
@@ -512,11 +593,13 @@ export async function maybeCompressResponse(
512
593
  return res
513
594
 
514
595
  const cl = res.headers.get('content-length')
596
+ const clBytes = cl !== null && cl.trim() !== '' ? Number(cl) : Number.NaN
597
+ const hasValidCl = Number.isFinite(clBytes) && clBytes >= 0
515
598
  const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
516
599
  if (enc === undefined)
517
600
  return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
518
601
 
519
- if (cl !== null && Number(cl) < MIN_COMPRESS_BYTES)
602
+ if (hasValidCl && clBytes < MIN_COMPRESS_BYTES)
520
603
  return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
521
604
 
522
605
  if (res.body === null)
@@ -538,8 +621,11 @@ export async function maybeCompressResponse(
538
621
  return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
539
622
  }
540
623
 
624
+ if (hasValidCl && clBytes > MAX_BUFFERED_PROBE_BYTES)
625
+ return isHtml(res) ? compressedStream(res, res.body, enc) : markCompressionHandled(tryAppendVaryAcceptEncoding(res))
626
+
541
627
  let raw: Uint8Array<ArrayBuffer>
542
- if (cl !== null) {
628
+ if (hasValidCl) {
543
629
  raw = new Uint8Array(await res.arrayBuffer())
544
630
  }
545
631
  else {