prunelle 0.1.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) 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 +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  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 +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -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 +636 -0
  36. package/src/cli/check-imports.ts +31 -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 +101 -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 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. 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: {
@@ -166,34 +150,78 @@ export function isServerAction(value: unknown): value is ServerAction<unknown, u
166
150
  return typeof value === 'function' && (value as { __pruAction?: boolean }).__pruAction === true
167
151
  }
168
152
 
169
- async function parseActionBody(boundedReq: Request): Promise<unknown> {
170
- const contentType = boundedReq.headers.get('content-type') ?? ''
171
- if (contentType.includes('application/json'))
172
- return boundedReq.json()
153
+ const UNSAFE_NESTED_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
154
+ const MAX_NESTED_DEPTH = 10
155
+
156
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
157
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Blob)
158
+ }
159
+
160
+ function appendFormValue(target: Record<string, unknown>, key: string, value: FormDataEntryValue, forceArray: boolean): void {
161
+ if (!Object.hasOwn(target, key)) {
162
+ setField(target, key, forceArray ? [value] : value)
163
+ return
164
+ }
165
+ const prev = target[key]
166
+ if (Array.isArray(prev))
167
+ prev.push(value)
168
+ else
169
+ setField(target, key, [prev, value])
170
+ }
173
171
 
174
- if (contentType.includes('multipart/form-data') || contentType.includes('application/x-www-form-urlencoded')) {
175
- // A Map then fromEntries makes every name an own property, `constructor` and `__proto__` included.
176
- const fields = new Map<string, FormDataEntryValue | FormDataEntryValue[]>()
177
- for (const [key, val] of (await boundedReq.formData()).entries()) {
178
- const prev = fields.get(key)
179
- if (prev === undefined) {
180
- fields.set(key, val)
172
+ /** Parses `FormData` into a plain record, mapping trailing `[]` names to arrays and dotted names (`a.b`, `a.b.c`) to nested objects safely. */
173
+ export function parseFormData(formData: FormData): Record<string, unknown> {
174
+ const out: Record<string, unknown> = {}
175
+ for (const [rawKey, val] of formData.entries()) {
176
+ const forceArray = rawKey.length > 2 && rawKey.endsWith('[]')
177
+ const key = forceArray ? rawKey.slice(0, -2) : rawKey
178
+ if (!key.includes('.')) {
179
+ appendFormValue(out, key, val, forceArray)
180
+ continue
181
+ }
182
+ const parts = key.split('.')
183
+ if (parts.some(p => UNSAFE_NESTED_KEYS.has(p)))
184
+ continue
185
+ if (parts.length > MAX_NESTED_DEPTH || parts.some(p => p.length === 0)) {
186
+ appendFormValue(out, key, val, forceArray)
187
+ continue
188
+ }
189
+ let cur = out
190
+ let blocked = false
191
+ for (let i = 0; i < parts.length - 1; i++) {
192
+ const seg = parts[i]!
193
+ if (!Object.hasOwn(cur, seg)) {
194
+ const next: Record<string, unknown> = {}
195
+ setField(cur, seg, next)
196
+ cur = next
181
197
  }
182
- else if (Array.isArray(prev)) {
183
- prev.push(val)
198
+ else if (isPlainRecord(cur[seg])) {
199
+ cur = cur[seg]
184
200
  }
185
201
  else {
186
- fields.set(key, [prev, val])
202
+ blocked = true
203
+ break
187
204
  }
188
205
  }
189
- return Object.fromEntries(fields)
206
+ if (!blocked)
207
+ appendFormValue(cur, parts[parts.length - 1]!, val, forceArray)
190
208
  }
209
+ return out
210
+ }
211
+
212
+ async function parseActionBody(boundedReq: Request): Promise<unknown> {
213
+ const contentType = (boundedReq.headers.get('content-type') ?? '').toLowerCase()
214
+ if (contentType.includes('application/json'))
215
+ return boundedReq.json()
216
+
217
+ if (contentType.includes('multipart/form-data') || contentType.includes('application/x-www-form-urlencoded'))
218
+ return parseFormData(await boundedReq.formData())
191
219
 
192
220
  return undefined
193
221
  }
194
222
 
195
223
  function isJsonBody(request: Request): boolean {
196
- return (request.headers.get('content-type') ?? '').includes('application/json')
224
+ return (request.headers.get('content-type') ?? '').toLowerCase().includes('application/json')
197
225
  }
198
226
 
199
227
  // The page a form came from, when its origin is one this server trusts: where a no-JS submit goes back to.
@@ -213,10 +241,48 @@ function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> |
213
241
  return isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy, requestUrl) ? refUrl : undefined
214
242
  }
215
243
 
216
- function topLevelKey(issue: StandardSchemaIssue): string | undefined {
217
- const seg = issue.path?.length === 1 ? issue.path[0] : undefined
218
- const key = typeof seg === 'object' && seg !== null ? seg.key : seg
219
- return typeof key === 'string' ? key : undefined
244
+ function issuePathSegments(issue: StandardSchemaIssue): string[] | undefined {
245
+ if (!issue.path || issue.path.length === 0 || issue.path.length > MAX_NESTED_DEPTH)
246
+ return undefined
247
+ const out: string[] = []
248
+ for (const seg of issue.path) {
249
+ const key = typeof seg === 'object' && seg !== null ? seg.key : seg
250
+ if (typeof key !== 'string' || key.length === 0 || (issue.path.length > 1 && UNSAFE_NESTED_KEYS.has(key)))
251
+ return undefined
252
+ out.push(key)
253
+ }
254
+ return out
255
+ }
256
+
257
+ function getAtPath(obj: Record<string, unknown>, path: readonly string[]): { has: boolean, value: unknown } {
258
+ let cur: unknown = obj
259
+ for (let i = 0; i < path.length - 1; i++) {
260
+ if (!isPlainRecord(cur) || !Object.hasOwn(cur, path[i]!))
261
+ return { has: false, value: undefined }
262
+ cur = cur[path[i]!]
263
+ }
264
+ const leaf = path[path.length - 1]!
265
+ if (!isPlainRecord(cur) || !Object.hasOwn(cur, leaf))
266
+ return { has: false, value: undefined }
267
+ return { has: true, value: cur[leaf] }
268
+ }
269
+
270
+ function setAtPath(obj: Record<string, unknown>, path: readonly string[], value: unknown, remove = false): boolean {
271
+ let cur = obj
272
+ for (let i = 0; i < path.length - 1; i++) {
273
+ const seg = path[i]!
274
+ if (!Object.hasOwn(cur, seg) || !isPlainRecord(cur[seg]))
275
+ return false
276
+ const cloned = { ...cur[seg] }
277
+ setField(cur, seg, cloned)
278
+ cur = cloned
279
+ }
280
+ const leaf = path[path.length - 1]!
281
+ if (remove)
282
+ delete cur[leaf]
283
+ else
284
+ setField(cur, leaf, value)
285
+ return true
220
286
  }
221
287
 
222
288
  function setField(target: Record<string, unknown>, key: string, value: unknown): void {
@@ -227,7 +293,7 @@ const ARRAY_WORD_RE = /\barray\b/i
227
293
  const MISSING_WORD_RE = /\b(?:required|missing|undefined)\b/i
228
294
  const NON_ARRAY_TYPE_RE = /\b(?:string|number|boolean|object|file|date|bigint|symbol)\b/i
229
295
 
230
- function looksLikeFormArrayMismatch(issue: StandardSchemaIssue, body: Record<string, unknown>, key: string): boolean {
296
+ function looksLikeFormArrayMismatch(issue: StandardSchemaIssue, hasValue: boolean): boolean {
231
297
  const meta = issue as { code?: unknown, expected?: unknown, type?: unknown }
232
298
  if (typeof meta.expected === 'string')
233
299
  return ARRAY_WORD_RE.test(meta.expected)
@@ -242,98 +308,55 @@ function looksLikeFormArrayMismatch(issue: StandardSchemaIssue, body: Record<str
242
308
  if (ARRAY_WORD_RE.test(issue.message))
243
309
  return true
244
310
  // An unchecked checkbox group is omitted from FormData; generic "Required"/"missing" messages without a non-array type may be expecting [].
245
- return !Object.hasOwn(body, key) && MISSING_WORD_RE.test(issue.message) && !NON_ARRAY_TYPE_RE.test(issue.message)
311
+ return !hasValue && MISSING_WORD_RE.test(issue.message) && !NON_ARRAY_TYPE_RE.test(issue.message)
246
312
  }
247
313
 
248
- // A form sends one checked box as a single value and none as nothing, so a field the schema wants as an array fails. Each failing top-level field whose issue looks like a missing/non-array type mismatch is retried as an array, and the array is kept only where it clears that field's issue.
314
+ // A form sends one checked box as a single value and none as nothing, so a field the schema wants as an array fails. Each failing field whose issue looks like a missing/non-array type mismatch is retried as an array, and the array is kept only where it clears that field's issue.
249
315
  async function retryWithFormArrays(schema: StandardSchemaV1, body: Record<string, unknown>, failed: ValidationFailure): Promise<ValidationResult<unknown>> {
250
- const retried = { ...body }
251
- const wrapped: string[] = []
316
+ const retried: Record<string, unknown> = { ...body }
317
+ const wrapped = new Map<string, string[]>()
252
318
  for (const issue of failed.issues) {
253
- const key = topLevelKey(issue)
254
- if (key === undefined || Array.isArray(retried[key]) || wrapped.includes(key))
319
+ const path = issuePathSegments(issue)
320
+ if (path === undefined)
321
+ continue
322
+ const pathKey = path.join('.')
323
+ if (wrapped.has(pathKey))
255
324
  continue
256
- if (!looksLikeFormArrayMismatch(issue, body, key))
325
+ const current = getAtPath(retried, path)
326
+ if (Array.isArray(current.value) || !looksLikeFormArrayMismatch(issue, current.has))
257
327
  continue
258
- setField(retried, key, Object.hasOwn(body, key) ? [body[key]] : [])
259
- wrapped.push(key)
328
+ if (setAtPath(retried, path, current.has ? [current.value] : []))
329
+ wrapped.set(pathKey, path)
260
330
  }
261
- if (wrapped.length === 0)
331
+ if (wrapped.size === 0)
262
332
  return failed
263
333
  const second = await validateSchema(schema, retried)
264
334
  if (second.ok)
265
335
  return second
266
- const stillFailing = new Set(second.issues.map(topLevelKey))
267
- const kept = wrapped.filter(key => !stillFailing.has(key))
336
+ const stillFailing = new Set(second.issues.map(i => issuePathSegments(i)?.join('.')))
337
+ const kept = [...wrapped.keys()].filter(k => !stillFailing.has(k))
268
338
  if (kept.length === 0)
269
339
  return failed
270
- for (const key of wrapped) {
271
- if (kept.includes(key))
340
+ for (const [pathKey, path] of wrapped) {
341
+ if (kept.includes(pathKey))
272
342
  continue
273
- if (Object.hasOwn(body, key))
274
- setField(retried, key, body[key])
275
- else
276
- delete retried[key]
343
+ const orig = getAtPath(body, path)
344
+ setAtPath(retried, path, orig.value, !orig.has)
277
345
  }
278
- return kept.length === wrapped.length ? second : validateSchema(schema, retried)
346
+ return kept.length === wrapped.size ? second : validateSchema(schema, retried)
279
347
  }
280
348
 
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
- }
349
+ function flattenFlashBody(rawBody: unknown, prefix = '', out: Record<string, unknown> = Object.create(null), depth = 0): unknown {
350
+ if (!isPlainRecord(rawBody) || depth > MAX_NESTED_DEPTH)
351
+ return depth === 0 ? rawBody : out
352
+ for (const [k, v] of Object.entries(rawBody)) {
353
+ const full = prefix === '' ? k : `${prefix}.${k}`
354
+ if (typeof v === 'string')
355
+ setField(out, full, v)
356
+ else if (isPlainRecord(v))
357
+ flattenFlashBody(v, full, out, depth + 1)
308
358
  }
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)
359
+ return out
337
360
  }
338
361
 
339
362
  /** Programmatic action invocation with Standard Schema validation (used by `ServerPluginAPI.invokeAction` inside middleware chains). */
@@ -362,7 +385,7 @@ export async function invokeActionCore<I, O>(
362
385
  if (result.status >= 300 && result.status < 400)
363
386
  return { ok: true, data: result as unknown as O }
364
387
  const ok = result.status >= 200 && result.status < 300
365
- const ct = result.headers.get('content-type') ?? ''
388
+ const ct = (result.headers.get('content-type') ?? '').toLowerCase()
366
389
  if (ct.includes('application/json')) {
367
390
  try {
368
391
  const body = await result.clone().json() as Record<string, unknown>
@@ -399,30 +422,53 @@ export async function executeAction(
399
422
  const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy, ctx.url)
400
423
  if (back === undefined)
401
424
  return undefined
402
- ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, error, fieldErrors, rawBody, act.flashFields), {
425
+ ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, error, fieldErrors, flattenFlashBody(rawBody), flashAllowlist(act)), {
403
426
  httpOnly: true,
404
427
  sameSite: 'lax',
405
428
  maxAge: 60,
429
+ category: 'essential',
406
430
  })
407
431
  return new Response(null, { status: 303, headers: { location: back.href } })
408
432
  }
409
433
 
434
+ // Enforce rate limit before parsing bodies or running schema/protection checks so invalid floods cannot bypass throttling.
435
+ const retryAfter = limiter !== undefined && act.rateLimit !== undefined ? hitFor(limiter, act.rateLimit, ctx) : 0
436
+ if (retryAfter > 0) {
437
+ const redirected = flashAndRedirect('Too many requests', undefined, undefined)
438
+ if (redirected === undefined)
439
+ return tooManyRequests(retryAfter)
440
+ redirected.headers.set('retry-after', String(retryAfter))
441
+ return redirected
442
+ }
443
+
410
444
  let rawBody: unknown
411
445
  let input: unknown
412
- if (act.schema !== undefined) {
446
+ const wantsBody = act.schema !== undefined || needsProtectBody(act.protect)
447
+ if (wantsBody) {
413
448
  try {
414
449
  rawBody = await parseActionBody(request)
415
450
  }
416
451
  catch {
417
452
  return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
418
453
  }
454
+ }
455
+
456
+ const protectedBody = verifyActionProtection(act.protect, rawBody, Date.now(), act.url)
457
+ const cleanBody = protectedBody.cleanedBody
458
+ if (!protectedBody.ok) {
459
+ const redirected = flashAndRedirect(protectedBody.error, undefined, cleanBody)
460
+ if (redirected !== undefined)
461
+ return redirected
462
+ return Response.json({ ok: false, status: 400, error: protectedBody.error }, { status: 400 })
463
+ }
419
464
 
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)
465
+ if (act.schema !== undefined) {
466
+ let checked = await validateSchema(act.schema, cleanBody)
467
+ if (!checked.ok && !isJsonBody(request) && cleanBody !== null && typeof cleanBody === 'object' && !Array.isArray(cleanBody))
468
+ checked = await retryWithFormArrays(act.schema, cleanBody as Record<string, unknown>, checked)
423
469
  if (!checked.ok) {
424
470
  // 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)
471
+ const redirected = flashAndRedirect('Validation failed', checked.fieldErrors, cleanBody)
426
472
  if (redirected !== undefined)
427
473
  return redirected
428
474
  return Response.json(
@@ -433,16 +479,6 @@ export async function executeAction(
433
479
  input = checked.value
434
480
  }
435
481
 
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
482
  // 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
483
  let deniedResponses: Map<Response, { message: string, fieldErrors?: Record<string, string> | undefined }> | undefined
448
484
  const actionCtx: ActionContext = Object.create(ctx, {
@@ -460,7 +496,7 @@ export async function executeAction(
460
496
  if (result instanceof Response) {
461
497
  const denied = deniedResponses?.get(result)
462
498
  if (denied !== undefined) {
463
- const redirected = flashAndRedirect(denied.message, denied.fieldErrors, rawBody)
499
+ const redirected = flashAndRedirect(denied.message, denied.fieldErrors, cleanBody)
464
500
  if (redirected !== undefined)
465
501
  return redirected
466
502
  }
@@ -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)