prunelle 0.8.0 → 0.10.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 (209) hide show
  1. package/llms.txt +68 -51
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +10 -17
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +94 -136
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +14 -6
  14. package/src/build/index.ts +23 -11
  15. package/src/build/island-promote.ts +42 -2
  16. package/src/build/islands.ts +63 -9
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +117 -1
  19. package/src/build/plugin-host.ts +13 -1
  20. package/src/build/prerender.ts +8 -3
  21. package/src/build/reach.ts +18 -4
  22. package/src/build/report.ts +1 -1
  23. package/src/build/resolve.ts +5 -1
  24. package/src/build/route-types.ts +16 -0
  25. package/src/build/routes.ts +42 -15
  26. package/src/build/seed-ids.ts +65 -0
  27. package/src/build/seed-writes.ts +111 -0
  28. package/src/build/static-headers.ts +2 -2
  29. package/src/build/static.ts +1 -1
  30. package/src/cli/check-cache.ts +51 -0
  31. package/src/cli/check-consent.ts +95 -0
  32. package/src/cli/check-forms.ts +10 -2
  33. package/src/cli/check-links-patterns.ts +101 -0
  34. package/src/cli/check-links.ts +30 -105
  35. package/src/cli/check-regions.ts +185 -0
  36. package/src/cli/check-security.ts +50 -6
  37. package/src/cli/check.ts +49 -21
  38. package/src/cli/commands.ts +138 -16
  39. package/src/cli/docs.ts +21 -2
  40. package/src/cli/form-opaque-children.ts +40 -0
  41. package/src/cli/index.ts +1 -1
  42. package/src/cli/inspect.ts +2 -0
  43. package/src/cli/mcp-tools.ts +2 -2
  44. package/src/cli/new.ts +9 -5
  45. package/src/cli/upgrade-names.ts +14 -2
  46. package/src/cli/upgrade.ts +3 -0
  47. package/src/compiler/analyze.ts +22 -16
  48. package/src/compiler/cacheability-private.ts +13 -3
  49. package/src/compiler/cacheability.ts +24 -2
  50. package/src/compiler/compliance-contrast.ts +322 -0
  51. package/src/compiler/compliance-empty.ts +24 -0
  52. package/src/compiler/compliance-rgaa-content.ts +95 -0
  53. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  54. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  55. package/src/compiler/compliance-rgaa.ts +19 -0
  56. package/src/compiler/compliance-rules.ts +72 -0
  57. package/src/compiler/compliance-third-party.ts +59 -0
  58. package/src/compiler/compliance-urls.ts +52 -0
  59. package/src/compiler/compliance.ts +61 -93
  60. package/src/compiler/cookie-inventory.ts +119 -0
  61. package/src/compiler/dom-attrs.ts +178 -22
  62. package/src/compiler/dom.ts +31 -44
  63. package/src/compiler/emit.ts +17 -6
  64. package/src/compiler/expr-context.ts +260 -207
  65. package/src/compiler/foreign-imports.ts +5 -3
  66. package/src/compiler/mistakes.ts +18 -9
  67. package/src/compiler/props-body.ts +263 -21
  68. package/src/compiler/props-pattern.ts +211 -0
  69. package/src/compiler/props.ts +324 -343
  70. package/src/compiler/signal-reads.ts +142 -29
  71. package/src/compiler/spread-handlers.ts +25 -13
  72. package/src/compiler/ssr-emit.ts +510 -0
  73. package/src/compiler/ssr-helpers.ts +165 -121
  74. package/src/compiler/ssr.ts +28 -441
  75. package/src/context.ts +14 -1
  76. package/src/dev/child.ts +1 -1
  77. package/src/dev/host-check.ts +2 -1
  78. package/src/dev/hot-islands.ts +71 -0
  79. package/src/dev/index.ts +31 -18
  80. package/src/dev/protocol.ts +1 -1
  81. package/src/dev/queue.ts +3 -2
  82. package/src/dev/reload.ts +5 -2
  83. package/src/dev/supervisor.ts +3 -1
  84. package/src/dev/watchers.ts +6 -2
  85. package/src/dom/action.ts +97 -14
  86. package/src/dom/attrs.ts +93 -25
  87. package/src/dom/extras.ts +91 -50
  88. package/src/dom/field-marks.ts +32 -0
  89. package/src/dom/hot.ts +9 -0
  90. package/src/dom/index.ts +44 -18
  91. package/src/dom/island-hot.ts +29 -0
  92. package/src/dom/island.ts +13 -2
  93. package/src/dom/loop.ts +259 -188
  94. package/src/dom/prefetch.ts +135 -0
  95. package/src/dom/regions.ts +515 -0
  96. package/src/dom/swap.ts +246 -0
  97. package/src/dom/trusted.ts +22 -0
  98. package/src/dom/upload.ts +44 -0
  99. package/src/eco/declaration.ts +44 -41
  100. package/src/eco/index.ts +8 -5
  101. package/src/href.ts +31 -0
  102. package/src/index.ts +12 -5
  103. package/src/plugins/config.ts +1 -1
  104. package/src/plugins/context.ts +7 -1
  105. package/src/plugins/daily.ts +27 -0
  106. package/src/plugins/index.ts +3 -3
  107. package/src/plugins/order.ts +1 -1
  108. package/src/plugins/public.ts +12 -5
  109. package/src/plugins/services.ts +88 -14
  110. package/src/plugins/types.ts +128 -10
  111. package/src/reactivity/graph.ts +244 -41
  112. package/src/reactivity/hmr.ts +101 -0
  113. package/src/reactivity/index.ts +243 -239
  114. package/src/reactivity/resource.ts +129 -0
  115. package/src/reactivity/seed.ts +141 -0
  116. package/src/reactivity/selector.ts +85 -47
  117. package/src/reactivity/server-seed.ts +202 -0
  118. package/src/reactivity/store.ts +331 -97
  119. package/src/rgpd/draft.ts +171 -0
  120. package/src/rgpd/forms.ts +85 -0
  121. package/src/rgpd/index.ts +57 -0
  122. package/src/server/action-flash.ts +1 -0
  123. package/src/server/action-protect.ts +3 -0
  124. package/src/server/action-registry.ts +11 -9
  125. package/src/server/action.ts +51 -19
  126. package/src/server/app-secret.ts +14 -8
  127. package/src/server/cache-invalidation.ts +97 -0
  128. package/src/server/compress.ts +55 -18
  129. package/src/server/consent.ts +21 -5
  130. package/src/server/cookie-inventory.ts +78 -0
  131. package/src/server/cookies.ts +77 -8
  132. package/src/server/cors.ts +98 -0
  133. package/src/server/csp-report.ts +90 -0
  134. package/src/server/discard.ts +13 -0
  135. package/src/server/document.ts +2 -2
  136. package/src/server/env.ts +1 -1
  137. package/src/server/errors.ts +9 -2
  138. package/src/server/field-errors.ts +91 -0
  139. package/src/server/form-schema.ts +16 -11
  140. package/src/server/health.ts +41 -11
  141. package/src/server/http.ts +28 -11
  142. package/src/server/index.ts +122 -307
  143. package/src/server/loader.ts +2 -0
  144. package/src/server/page.ts +3 -9
  145. package/src/server/plugin-host.ts +66 -16
  146. package/src/server/plugin-route-shadow.ts +24 -0
  147. package/src/server/public.ts +14 -3
  148. package/src/server/rate-limit.ts +49 -10
  149. package/src/server/region.ts +22 -2
  150. package/src/server/request-handler.ts +406 -0
  151. package/src/server/request-log.ts +94 -0
  152. package/src/server/route-cache.ts +55 -8
  153. package/src/server/route-input.ts +54 -0
  154. package/src/server/route-table.ts +53 -27
  155. package/src/server/router.ts +2 -1
  156. package/src/server/routing.ts +104 -45
  157. package/src/server/sanitize-html.ts +4 -2
  158. package/src/server/security.ts +38 -8
  159. package/src/server/serve-handlers.ts +16 -6
  160. package/src/server/served-file.ts +19 -14
  161. package/src/server/shared-store.ts +323 -0
  162. package/src/server/start.ts +12 -5
  163. package/src/server/static-dir.ts +34 -12
  164. package/src/server/stream.ts +2 -1
  165. package/src/server/surface.ts +39 -0
  166. package/src/server/webhook.ts +50 -0
  167. package/src/server/workers.ts +168 -0
  168. package/src/ssr/consent-banner.ts +20 -16
  169. package/src/ssr/consent-texts.ts +40 -0
  170. package/src/ssr/context.ts +174 -53
  171. package/src/ssr/cookie-table.ts +75 -0
  172. package/src/ssr/index.ts +63 -58
  173. package/src/ssr/navigation.ts +161 -14
  174. package/src/ssr/region.ts +9 -3
  175. package/src/style.ts +12 -5
  176. package/src/test/browser.ts +53 -23
  177. package/src/test/build-reuse.ts +85 -0
  178. package/src/test/index.ts +51 -8
  179. package/src/test/mount.ts +53 -0
  180. package/src/test/outside.ts +94 -0
  181. package/src/ts-plugin/diagnostics.ts +56 -18
  182. package/templates/_shared/AGENTS.md +1 -1
  183. package/templates/_shared/Dockerfile +22 -0
  184. package/templates/_shared/dockerignore +9 -0
  185. package/templates/_shared/gitignore +2 -0
  186. package/templates/app/.env.example +3 -1
  187. package/templates/app/compose.yaml +32 -0
  188. package/templates/app/db/migrations/001_notes.sql +7 -0
  189. package/templates/app/db/schema.ts +11 -0
  190. package/templates/app/package.json +1 -0
  191. package/templates/app/prunelle.config.ts +6 -0
  192. package/templates/app/src/actions/notes.ts +26 -0
  193. package/templates/app/src/auth.ts +4 -2
  194. package/templates/app/src/db.ts +5 -0
  195. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  196. package/templates/app/src/routes/privacy.tsx +6 -2
  197. package/templates/app/tests/app.test.ts +14 -3
  198. package/templates/plugin/AGENTS.md +11 -0
  199. package/templates/plugin/CLAUDE.md +1 -0
  200. package/templates/plugin/README.md +27 -0
  201. package/templates/plugin/gitignore +2 -0
  202. package/templates/plugin/llms.txt +19 -0
  203. package/templates/plugin/package.json +33 -0
  204. package/templates/plugin/src/index.ts +40 -0
  205. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  206. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  207. package/templates/plugin/tests/plugin.test.ts +42 -0
  208. package/templates/plugin/tsconfig.json +19 -0
  209. package/ts-plugin.cjs +4058 -2246
@@ -0,0 +1,85 @@
1
+ // The app's own forms that collect an email or a phone number, one processing per file for `prunelle rgpd`.
2
+
3
+ import type { JSXElement, Node } from 'oxc-parser'
4
+ import type { ProcessingDeclaration } from '../plugins/types'
5
+ import { readFileSync } from 'node:fs'
6
+ import { basename, join } from 'node:path'
7
+ import { parseSync } from 'oxc-parser'
8
+ import { isNotSourceDir, relPosix, walkFiles, walkRoutes } from '../build/files'
9
+ import { fileToRoutePath } from '../build/routes'
10
+ import { walk } from '../compiler/ast'
11
+ import { isPersonalDataInput } from '../compiler/compliance'
12
+ import { findAttr, staticStringValueOf } from '../compiler/compliance-rgaa'
13
+ import { jsxTagName } from '../compiler/shared'
14
+
15
+ const FIELD_TAGS = new Set(['input', 'textarea', 'select'])
16
+
17
+ function attr(el: JSXElement, name: string): string | undefined {
18
+ const found = findAttr(el.openingElement.attributes, name)
19
+ return found === undefined ? undefined : staticStringValueOf(found.value)
20
+ }
21
+
22
+ // `adresse e-mail (champ email)` for a field collecting an email, `champ message` for any other named one.
23
+ function describeField(el: JSXElement): string | undefined {
24
+ const name = attr(el, 'name')
25
+ if (!isPersonalDataInput(el))
26
+ return name === undefined ? undefined : `champ ${name}`
27
+ const kind = attr(el, 'type')?.toLowerCase() === 'email' || name?.toLowerCase() === 'email' ? 'adresse e-mail' : 'numéro de téléphone'
28
+ return name === undefined ? kind : `${kind} (champ ${name})`
29
+ }
30
+
31
+ function fieldsOf(form: JSXElement): JSXElement[] {
32
+ const fields: JSXElement[] = []
33
+ walk(form, (node): undefined => {
34
+ if (node.type === 'JSXElement' && FIELD_TAGS.has(jsxTagName(node.openingElement.name)))
35
+ fields.push(node)
36
+ return undefined
37
+ })
38
+ return fields
39
+ }
40
+
41
+ // Every field of a form that holds a personal-data input, and such an input outside any form; a form posting under a plugin's path is that plugin's processing.
42
+ function collectedData(program: Node, claimed: readonly string[]): string[] {
43
+ const data = new Set<string>()
44
+ walk(program, (node): boolean | undefined => {
45
+ if (node.type !== 'JSXElement')
46
+ return undefined
47
+ if (jsxTagName(node.openingElement.name) === 'form') {
48
+ const action = attr(node, 'action')
49
+ const fields = fieldsOf(node)
50
+ if (!claimed.some(path => action?.startsWith(path) === true) && fields.some(isPersonalDataInput)) {
51
+ for (const described of fields.map(describeField)) {
52
+ if (described !== undefined)
53
+ data.add(described)
54
+ }
55
+ }
56
+ return false
57
+ }
58
+ if (isPersonalDataInput(node))
59
+ data.add(describeField(node)!)
60
+ return undefined
61
+ })
62
+ return [...data]
63
+ }
64
+
65
+ export function formProcessing(root: string, routesDir: string, claimed: readonly string[]): ProcessingDeclaration[] {
66
+ const keep = { skipDir: isNotSourceDir, keep: (entry: { name: string }) => entry.name.endsWith('.tsx') }
67
+ const files = [...new Set([...walkFiles(join(root, 'src'), keep), ...walkFiles(routesDir, keep)])].sort()
68
+ const pages = new Set(walkRoutes(routesDir).filter(file => !basename(file).startsWith('_')))
69
+ const processing: ProcessingDeclaration[] = []
70
+ for (const file of files) {
71
+ const code = readFileSync(file, 'utf8')
72
+ if (!code.includes('<input'))
73
+ continue
74
+ const data = collectedData(parseSync(file, code, { lang: 'tsx' }).program, claimed)
75
+ if (data.length === 0)
76
+ continue
77
+ processing.push({
78
+ name: pages.has(file) ? `Formulaire de la page ${fileToRoutePath(routesDir, file)}` : `Formulaire de ${relPosix(root, file)}`,
79
+ purpose: '[à compléter : finalité du formulaire]',
80
+ people: 'les personnes qui remplissent ce formulaire',
81
+ data,
82
+ })
83
+ }
84
+ return processing
85
+ }
@@ -0,0 +1,57 @@
1
+ // `prunelle rgpd`: the personal data the plugins declare and the app's forms collect, and the privacy notice and record of processing drafted from it.
2
+
3
+ import type { ProcessingDeclaration } from '../plugins/types'
4
+ import type { PrivacyNoticeDraft } from './draft'
5
+ import { resolve } from 'node:path'
6
+ import { loadConfig } from '../plugins/load'
7
+ import { draftPrivacyNotice } from './draft'
8
+ import { formProcessing } from './forms'
9
+
10
+ export { draftPrivacyNotice, REGISTER_PATH } from './draft'
11
+ export type { DraftedFile, PrivacyNoticeDraft, PrivacyNoticeOptions } from './draft'
12
+
13
+ export interface RgpdRunOptions {
14
+ root: string
15
+ /** Draft the notice, at this path (`''` for `<routesDir>/confidentialite.tsx`), and the record of processing. */
16
+ draft?: string | undefined
17
+ force?: boolean | undefined
18
+ organization?: string | undefined
19
+ contactEmail?: string | undefined
20
+ }
21
+
22
+ export interface RgpdRunResult {
23
+ processing: ProcessingDeclaration[]
24
+ drafted?: PrivacyNoticeDraft | undefined
25
+ }
26
+
27
+ export async function runRgpd(options: RgpdRunOptions): Promise<RgpdRunResult> {
28
+ const root = resolve(options.root)
29
+ const config = await loadConfig(root)
30
+ const routesDir = resolve(root, config.routesDir ?? 'src/routes')
31
+ const declared = (config.plugins ?? []).flatMap(plugin => typeof plugin.processing === 'function' ? plugin.processing({ site: config.site }) : plugin.processing ?? [])
32
+ const processing = [...declared, ...formProcessing(root, routesDir, declared.flatMap(p => p.formActions ?? []))]
33
+ if (options.draft === undefined)
34
+ return { processing }
35
+ const drafted = draftPrivacyNotice({
36
+ root,
37
+ routesDir,
38
+ outPath: options.draft === '' ? undefined : options.draft,
39
+ processing,
40
+ organization: options.organization,
41
+ contactEmail: options.contactEmail,
42
+ force: options.force,
43
+ })
44
+ return { processing, drafted }
45
+ }
46
+
47
+ export function formatRgpdResult(result: RgpdRunResult): string {
48
+ const lines = ['prunelle rgpd: the personal data the plugins declare and the app\'s forms collect']
49
+ for (const p of result.processing)
50
+ lines.push(` ${p.name}: ${p.data.join(', ')}`)
51
+ if (result.processing.length === 0)
52
+ lines.push(' none found')
53
+ lines.push(result.drafted === undefined
54
+ ? 'prunelle rgpd --draft writes the privacy notice and the record of processing from it.'
55
+ : `prunelle rgpd: drafted the privacy notice at ${result.drafted.notice.relativePath} and the record of processing at ${result.drafted.register.relativePath}: fill in each [à compléter ...] before publishing the notice, and keep the record out of the site.`)
56
+ return lines.join('\n')
57
+ }
@@ -5,6 +5,7 @@ import { signPayload, verifyPayload } from './app-secret'
5
5
  import { extractFormSchema, isRecord } from './form-schema'
6
6
 
7
7
  export const ACTION_ERROR_COOKIE = '__pru_action_err'
8
+ export const ACTION_ERROR_MAX_AGE = 60
8
9
 
9
10
  const FLASH_PURPOSE = 'action-flash'
10
11
  const MAX_FLASH_COOKIE_BYTES = 3500
@@ -68,6 +68,9 @@ export function assertActionProtect(protect: ActionProtectOptions): void {
68
68
  throw new Error(`prunelle: protect.minTime of an action is ${String(protect.minTime)}; give a non-negative number of milliseconds.`)
69
69
  if (typeof protect.honeypot === 'string' && protect.honeypot.trim() === '')
70
70
  throw new Error('prunelle: protect.honeypot of an action must be a non-empty field name.')
71
+ // parseFormData nests `a.b` and `a[]`, so the field a bot fills would never be found under its own name.
72
+ if (typeof protect.honeypot === 'string' && /[.[\]]/.test(protect.honeypot))
73
+ throw new Error(`prunelle: protect.honeypot "${protect.honeypot.trim()}" holds a "." or a "[", which the form parser nests, so the trap would never trip: name it with letters, digits, "-" or "_", such as "website_url".`)
71
74
  if (protect.minTime !== undefined)
72
75
  warnEphemeralSecret()
73
76
  }
@@ -16,6 +16,8 @@ export interface ActionRegistry {
16
16
  /** Gives `act` its name and live URL and records the middlewares a request to it runs behind. */
17
17
  register: (act: ServerAction<unknown, unknown>, name: string, url: string, dirMiddlewares: Middleware[], pluginMiddlewares: readonly Middleware[]) => void
18
18
  byUrl: (url: string) => RegisteredAction | undefined
19
+ /** Whether a registered action counts its calls with `rateLimit`. */
20
+ rateLimited: () => boolean
19
21
  /** Runs an action with schema validation behind its folder's `_middleware.ts` chain, as an island call would. */
20
22
  invoke: <I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext) => Promise<ActionResult<O>>
21
23
  /** Runs `fn` as part of the request `ctx`, so the actions it calls run in that request. */
@@ -25,9 +27,12 @@ export interface ActionRegistry {
25
27
  export function createActionRegistry(): ActionRegistry {
26
28
  const handlers = new Map<string, RegisteredAction>()
27
29
  const dirMiddlewaresByRef = new WeakMap<ServerAction<unknown, unknown>, Middleware[]>()
30
+ const dirMiddlewaresByUrl = new Map<string, Middleware[]>()
28
31
 
29
32
  async function invoke<I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>> {
30
- const dirMiddlewares = dirMiddlewaresByRef.get(act as unknown as ServerAction<unknown, unknown>) ?? []
33
+ const dirMiddlewares = dirMiddlewaresByRef.get(act as unknown as ServerAction<unknown, unknown>)
34
+ ?? (act.url ? dirMiddlewaresByUrl.get(act.url) : undefined)
35
+ ?? []
31
36
  if (dirMiddlewares.length === 0)
32
37
  return invokeActionCore(act, input, ctx)
33
38
 
@@ -41,21 +46,16 @@ export function createActionRegistry(): ActionRegistry {
41
46
  // A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
42
47
  const ct = (res.headers.get('content-type') ?? '').toLowerCase()
43
48
  if (ct.includes('application/json')) {
44
- try {
45
- const body = await res.clone().json() as Record<string, unknown>
49
+ const body = await res.clone().json().catch(() => null) as Record<string, unknown> | null
50
+ if (body !== null) {
46
51
  return {
47
52
  ok: false,
48
53
  status: res.status,
49
54
  error: typeof body.error === 'string' ? body.error : res.statusText || 'Forbidden',
50
55
  }
51
56
  }
52
- catch {}
53
57
  }
54
- let text = ''
55
- try {
56
- text = await res.clone().text()
57
- }
58
- catch {}
58
+ const text = await res.clone().text().catch(() => '')
59
59
  return {
60
60
  ok: false,
61
61
  status: res.status,
@@ -68,9 +68,11 @@ export function createActionRegistry(): ActionRegistry {
68
68
  ;(act as { url: string }).url = url
69
69
  Object.defineProperty(act, 'name', { value: name, configurable: true })
70
70
  dirMiddlewaresByRef.set(act, dirMiddlewares)
71
+ dirMiddlewaresByUrl.set(url, dirMiddlewares)
71
72
  handlers.set(url, { act, middlewares: [...pluginMiddlewares, ...dirMiddlewares] })
72
73
  },
73
74
  byUrl: url => handlers.get(url),
75
+ rateLimited: () => [...handlers.values()].some(({ act }) => act.rateLimit !== undefined),
74
76
  invoke,
75
77
  run: (ctx, fn) => runInRequest({ ctx, actions: registry }, fn),
76
78
  }
@@ -3,12 +3,13 @@
3
3
  import type { ActionProtectOptions } from './action-protect'
4
4
  import type { Cookies } from './cookies'
5
5
  import type { RequestContext } from './http'
6
- import type { PrunelleLocals } from './index'
6
+ import type { PrunelleLocals } from './public'
7
7
  import type { RateLimit, RateLimiter } from './rate-limit'
8
8
  import type { TrustProxy } from './security'
9
9
  import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
10
- import { ACTION_ERROR_COOKIE, buildActionErrorFlash, flashAllowlist } from './action-flash'
10
+ import { ACTION_ERROR_COOKIE, ACTION_ERROR_MAX_AGE, buildActionErrorFlash, flashAllowlist } from './action-flash'
11
11
  import { assertActionProtect, needsProtectBody, verifyActionProtection } from './action-protect'
12
+ import { extractFormSchema } from './form-schema'
12
13
  import { isExternalRedirect, wantsJson } from './http'
13
14
  import { assertRateLimit, hitFor, tooManyRequests } from './rate-limit'
14
15
  import { currentRequest } from './request-scope'
@@ -18,7 +19,7 @@ import { validateSchema } from './standard-schema'
18
19
  export { ACTION_ERROR_COOKIE, hydrateActionErrorFlash } from './action-flash'
19
20
  export type { ActionProtectOptions } from './action-protect'
20
21
 
21
- declare module './index' {
22
+ declare module './public' {
22
23
  interface PrunelleLocals {
23
24
  actionError?: ActionErrorFlash | undefined
24
25
  }
@@ -293,6 +294,33 @@ function setField(target: Record<string, unknown>, key: string, value: unknown):
293
294
  Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
294
295
  }
295
296
 
297
+ // Coerces known array fields declared in the schema's JSON Schema before validation so single-checked or unchecked checkbox groups work regardless of custom/localized error messages.
298
+ function coerceFormArraysFromSchema(schema: StandardSchemaV1, body: Record<string, unknown>): { body: Record<string, unknown>, hasJsonSchema: boolean } {
299
+ const extracted = extractFormSchema(schema)
300
+ if (!extracted.ok)
301
+ return { body, hasJsonSchema: false }
302
+ let out: Record<string, unknown> | undefined
303
+ for (const [pathKey, constraint] of extracted.fields) {
304
+ if (constraint.isArray !== true)
305
+ continue
306
+ const path = pathKey.split('.')
307
+ if (path.length > MAX_NESTED_DEPTH || path.some(p => p.length === 0 || (path.length > 1 && UNSAFE_NESTED_KEYS.has(p))))
308
+ continue
309
+ const current = getAtPath(out ?? body, path)
310
+ if (current.has) {
311
+ if (Array.isArray(current.value))
312
+ continue
313
+ out ??= { ...body }
314
+ setAtPath(out, path, [current.value])
315
+ }
316
+ else if (constraint.required === true) {
317
+ out ??= { ...body }
318
+ setAtPath(out, path, [])
319
+ }
320
+ }
321
+ return { body: out ?? body, hasJsonSchema: true }
322
+ }
323
+
296
324
  const ARRAY_WORD_RE = /\barray\b/i
297
325
  const MISSING_WORD_RE = /\b(?:required|missing|undefined)\b/i
298
326
  const NON_ARRAY_TYPE_RE = /\b(?:string|number|boolean|object|file|date|bigint|symbol)\b/i
@@ -391,20 +419,22 @@ export async function invokeActionCore<I, O>(
391
419
  const ok = result.status >= 200 && result.status < 300
392
420
  const ct = (result.headers.get('content-type') ?? '').toLowerCase()
393
421
  if (ct.includes('application/json')) {
394
- try {
395
- const body = await result.clone().json() as Record<string, unknown>
422
+ // A body that is not JSON after all falls through to the status-only result below.
423
+ const body = await result.clone().json().catch(() => undefined) as Record<string, unknown> | null | undefined
424
+ if (body !== undefined) {
396
425
  if (typeof body === 'object' && body !== null && 'ok' in body)
397
426
  return body as unknown as ActionResult<O>
398
- return ok
399
- ? { ok: true, data: body as O }
400
- : {
401
- ok: false,
402
- status: result.status,
403
- error: typeof body.error === 'string' ? body.error : result.statusText,
404
- ...(body.fieldErrors !== undefined ? { fieldErrors: body.fieldErrors as Record<string, string> } : {}),
405
- }
427
+ if (ok)
428
+ return { ok: true, data: body as O }
429
+ if (body !== null) {
430
+ return {
431
+ ok: false,
432
+ status: result.status,
433
+ error: typeof body.error === 'string' ? body.error : result.statusText,
434
+ ...(body.fieldErrors !== undefined ? { fieldErrors: body.fieldErrors as Record<string, string> } : {}),
435
+ }
436
+ }
406
437
  }
407
- catch {}
408
438
  }
409
439
  return ok
410
440
  ? { ok: true, data: undefined as O }
@@ -429,14 +459,14 @@ export async function executeAction(
429
459
  ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, error, fieldErrors, flattenFlashBody(rawBody), flashAllowlist(act)), {
430
460
  httpOnly: true,
431
461
  sameSite: 'lax',
432
- maxAge: 60,
462
+ maxAge: ACTION_ERROR_MAX_AGE,
433
463
  category: 'essential',
434
464
  })
435
465
  return new Response(null, { status: 303, headers: { location: back.href } })
436
466
  }
437
467
 
438
468
  // Enforce rate limit before parsing bodies or running schema/protection checks so invalid floods cannot bypass throttling.
439
- const retryAfter = limiter !== undefined && act.rateLimit !== undefined ? hitFor(limiter, act.rateLimit, ctx) : 0
469
+ const retryAfter = limiter !== undefined && act.rateLimit !== undefined ? await hitFor(limiter, act.rateLimit, ctx) : 0
440
470
  if (retryAfter > 0) {
441
471
  const redirected = flashAndRedirect('Too many requests', undefined, undefined)
442
472
  if (redirected === undefined)
@@ -471,9 +501,11 @@ export async function executeAction(
471
501
  }
472
502
 
473
503
  if (act.schema !== undefined) {
474
- let checked = await validateSchema(act.schema, cleanBody)
475
- if (!checked.ok && !isJsonBody(request) && cleanBody !== null && typeof cleanBody === 'object' && !Array.isArray(cleanBody))
476
- checked = await retryWithFormArrays(act.schema, cleanBody as Record<string, unknown>, checked)
504
+ const formBody = !isJsonBody(request) && isPlainRecord(cleanBody) ? cleanBody : undefined
505
+ const coerced = formBody !== undefined ? coerceFormArraysFromSchema(act.schema, formBody) : undefined
506
+ let checked = await validateSchema(act.schema, coerced !== undefined ? coerced.body : cleanBody)
507
+ if (!checked.ok && formBody !== undefined && coerced !== undefined && !coerced.hasJsonSchema)
508
+ checked = await retryWithFormArrays(act.schema, formBody, checked)
477
509
  if (!checked.ok) {
478
510
  // Zero-JS progressive HTML <form> submit: flash fieldErrors + safe submitted values (<4KB) and redirect 303 back to trusted Referer
479
511
  const redirected = flashAndRedirect('Validation failed', checked.fieldErrors, cleanBody)
@@ -1,23 +1,29 @@
1
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
2
  // HMAC goes through Bun.CryptoHasher, never `node:crypto`, which would add 2 MB to the server's RSS.
3
3
 
4
+ import { workerOf, WORKERS_SECRET_ENV } from './workers'
5
+
4
6
  const EPHEMERAL_SECRET_KEY = Symbol.for('pru.form.secret')
5
7
  const keyCache = new Map<string, Buffer>()
6
8
 
7
- const hmac = (key: string | Buffer, data: string | Buffer): Buffer => new Bun.CryptoHasher('sha256', key).update(data).digest()
9
+ export const hmac = (key: string | Buffer, data: string | Buffer): Buffer => new Bun.CryptoHasher('sha256', key).update(data).digest()
8
10
 
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 }
11
+ /** A random secret that dies with this start: the process's, or the one a `prunelle start --workers` gives all its workers. A plugin derives its own ephemeral keys from it with `deriveKey`, so the workers agree on them. */
12
+ export function startSecret(): string {
14
13
  const g = globalThis as Record<symbol, string | undefined>
15
- let secret = g[EPHEMERAL_SECRET_KEY]
14
+ // Read in a worker only: a value left in the shell of a lone process would make its secret fixed and known.
15
+ let secret = g[EPHEMERAL_SECRET_KEY] ?? (workerOf() === undefined ? undefined : process.env[WORKERS_SECRET_ENV])
16
16
  if (secret === undefined) {
17
17
  secret = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('hex')
18
18
  g[EPHEMERAL_SECRET_KEY] = secret
19
19
  }
20
- return { secret, ephemeral: true }
20
+ return secret
21
+ }
22
+
23
+ /** The configured secret (`PRUNELLE_FORM_SECRET`, then `AUTH_SECRET`), or `startSecret()`. */
24
+ export function appSecret(): { secret: string, ephemeral: boolean } {
25
+ const configured = process.env.PRUNELLE_FORM_SECRET || process.env.AUTH_SECRET
26
+ return configured ? { secret: configured, ephemeral: false } : { secret: startSecret(), ephemeral: true }
21
27
  }
22
28
 
23
29
  /** A 32-byte key for `purpose` (`"form-timestamp"`, `"action-flash"`), HKDF-SHA256 (RFC 5869) of the app secret (or of `secret`, for a plugin with a secret of its own) with `"prunelle"` as salt and the purpose as `info`. */
@@ -0,0 +1,97 @@
1
+ // `invalidateCache()`: drops cached route renders in this process and, through the shared store, in every other.
2
+
3
+ import type { AppRuntimeContext } from '../plugins/context'
4
+ import type { RouteCache } from './route-cache'
5
+ import type { SharedStore } from './shared-store'
6
+ import { getAppContext } from '../plugins/context'
7
+ import { serviceKey } from '../plugins/services'
8
+ import { SHARED_STORE } from './shared-store'
9
+
10
+ /** A path (`'/posts/hello'`), the pages under one (`'/posts/*'`), or a tag the route declares in `export const cache = { maxAge, tags }`. */
11
+ export type CacheTarget = string | { tag: string }
12
+
13
+ type Invalidate = (targets: readonly CacheTarget[]) => Promise<void>
14
+
15
+ const CACHE_INVALIDATION = serviceKey<Invalidate>('prunelle.cacheInvalidation')
16
+ const CHANNEL = 'cache'
17
+ const BASE = 'http://prunelle.invalid'
18
+
19
+ // Compared without a trailing slash, so `/posts/a` also drops the render of `/posts/a/`, and `/` becomes the empty prefix of every path.
20
+ const trimmed = (pathname: string): string => pathname.endsWith('/') ? pathname.slice(0, -1) : pathname
21
+
22
+ function pathnameOf(target: string): string {
23
+ if (!target.startsWith('/'))
24
+ throw new Error(`prunelle: invalidateCache() takes a path starting with "/", not "${target}": write '/${target}', '/${target}/*' for the pages under it, or { tag: '...' }.`)
25
+ if (/\?[^/]*=/.test(target))
26
+ throw new Error(`prunelle: invalidateCache() takes a path without its query, not "${target}": a path drops the renders of every query.`)
27
+ // A path is read as written, so a slug such as "100%", "what?" or "a#b" names its own page; a "%" opening a valid escape stays an escape.
28
+ return trimmed(new URL(target.replace(/%(?![0-9a-f]{2})/gi, '%25').replaceAll('?', '%3F').replaceAll('#', '%23'), BASE).pathname)
29
+ }
30
+
31
+ /** Whether a render of `pathname`, from a route declaring `tags`, is one of `targets`; throws on a target that names nothing. */
32
+ export function cacheTargetMatcher(targets: readonly CacheTarget[]): (pathname: string, tags: readonly string[]) => boolean {
33
+ const paths = new Set<string>()
34
+ const prefixes: string[] = []
35
+ const tags = new Set<string>()
36
+ for (const target of targets) {
37
+ if (typeof target !== 'string') {
38
+ if (typeof target.tag !== 'string' || target.tag === '')
39
+ throw new Error('prunelle: invalidateCache() got an empty tag: name one a route declares in `export const cache = { maxAge, tags }`.')
40
+ tags.add(target.tag)
41
+ continue
42
+ }
43
+ const star = target.indexOf('*')
44
+ if (star !== -1 && (star !== target.length - 1 || !target.endsWith('/*')))
45
+ throw new Error(`prunelle: invalidateCache() takes a "*" only at the end, after a "/", not "${target}": write '/posts/*' for every page under /posts.`)
46
+ if (star === -1)
47
+ paths.add(pathnameOf(target))
48
+ else
49
+ prefixes.push(pathnameOf(target.slice(0, -1)))
50
+ }
51
+ return (pathname, routeTags) => {
52
+ const path = trimmed(pathname)
53
+ return paths.has(path)
54
+ || prefixes.some(prefix => path === prefix || path.startsWith(`${prefix}/`))
55
+ || routeTags.some(tag => tags.has(tag))
56
+ }
57
+ }
58
+
59
+ /** Gives the server's `invalidateCache()` its route cache, and the store that carries it to the other processes once the plugins opened it. */
60
+ export function serveCacheInvalidation(appCtx: AppRuntimeContext, routeCache: RouteCache | undefined): void {
61
+ let failing = false
62
+ appCtx.provide(CACHE_INVALIDATION, (targets) => {
63
+ routeCache?.invalidate(cacheTargetMatcher(targets))
64
+ const shared = appCtx.inject(SHARED_STORE)
65
+ if (shared === undefined)
66
+ return Promise.resolve()
67
+ return shared.publish(CHANNEL, JSON.stringify(targets)).then(() => {
68
+ failing = false
69
+ }, (error: unknown) => {
70
+ if (!failing)
71
+ console.error('prunelle: invalidateCache() dropped the renders of this process, but could not reach the others through the shared store:', error)
72
+ failing = true
73
+ })
74
+ })
75
+ }
76
+
77
+ /** Drops in this process the renders another process's `invalidateCache()` named. */
78
+ export function receiveCacheInvalidation(shared: SharedStore | undefined, routeCache: RouteCache | undefined): void {
79
+ if (shared === undefined || routeCache === undefined)
80
+ return
81
+ shared.subscribe(CHANNEL, (payload) => {
82
+ try {
83
+ routeCache.invalidate(cacheTargetMatcher(JSON.parse(payload) as CacheTarget[]))
84
+ }
85
+ catch (error) {
86
+ console.error('prunelle: a cache invalidation from another process could not be read:', error)
87
+ }
88
+ })
89
+ }
90
+
91
+ /** Drops the cached renders of the `export const cache` routes any target matches, in this process at once and in every process sharing `store` once the promise settles; it never rejects, logging a store it cannot reach. */
92
+ export function invalidateCache(...targets: [CacheTarget, ...CacheTarget[]]): Promise<void> {
93
+ const invalidate = getAppContext()?.inject(CACHE_INVALIDATION)
94
+ if (invalidate === undefined)
95
+ throw new Error('prunelle: invalidateCache() ran outside the app\'s server: call it from an action, a route, load() or a plugin\'s server code.')
96
+ return invalidate(targets)
97
+ }
@@ -1,6 +1,8 @@
1
1
  // Zero-dependency native HTTP compression (Bun.zstdCompressSync / Bun.gzipSync) with bounded byte-budget LRU.
2
2
  // `node:zlib` (3 MB of RSS) loads only with the first page streamed to a client taking gzip and not zstd, as Bun has no streaming gzip of its own that flushes.
3
3
 
4
+ import { markHandled } from './discard'
5
+
4
6
  export type CompressionEncoding = 'zstd' | 'gzip'
5
7
  export type PrecompressedEncoding = 'br' | 'gzip'
6
8
 
@@ -134,7 +136,7 @@ export async function readBufferedOrPassThrough(
134
136
 
135
137
  while (true) {
136
138
  const readPromise = reader.read()
137
- void readPromise.catch(() => undefined)
139
+ markHandled(readPromise)
138
140
  const tick = Promise.resolve().then(() => Promise.resolve()).then((): typeof PENDING => PENDING)
139
141
  const outcome = await Promise.race([readPromise, tick])
140
142
  if (outcome === PENDING) {
@@ -356,7 +358,7 @@ function tryAppendVaryAcceptEncoding(res: Response): Response {
356
358
  }
357
359
  }
358
360
 
359
- function withVaryAcceptEncoding(baseHeaders: Record<string, string>): Record<string, string> {
361
+ export function withVaryAcceptEncoding(baseHeaders: Record<string, string>): Record<string, string> {
360
362
  const headers: Record<string, string> = { ...baseHeaders }
361
363
  let existing: string | undefined
362
364
  for (const key of Object.keys(headers)) {
@@ -370,6 +372,46 @@ function withVaryAcceptEncoding(baseHeaders: Record<string, string>): Record<str
370
372
  return headers
371
373
  }
372
374
 
375
+ export interface CompressedHtmlOptions {
376
+ /** `baseHeaders` already includes `vary: Accept-Encoding` and does not set `Cache-Control: no-transform`. */
377
+ varyPremerged?: boolean | undefined
378
+ /** Skip `WeakSet` tracking on paths where `maybeCompressResponse` never runs on the returned response. */
379
+ skipMarkHandled?: boolean | undefined
380
+ requestId?: string | undefined
381
+ serverTiming?: string | undefined
382
+ }
383
+
384
+ function finalizeHtmlHeaders(
385
+ baseHeaders: Record<string, string>,
386
+ addVary: boolean,
387
+ enc: CompressionEncoding | undefined,
388
+ opts: CompressedHtmlOptions | undefined,
389
+ ): Record<string, string> {
390
+ const reqId = opts?.requestId
391
+ const timing = opts?.serverTiming || undefined
392
+ if (!addVary && enc === undefined) {
393
+ if (reqId === undefined && timing === undefined)
394
+ return baseHeaders
395
+ return timing === undefined
396
+ ? { ...baseHeaders, 'x-request-id': reqId! }
397
+ : reqId === undefined ? { ...baseHeaders, 'server-timing': timing } : { ...baseHeaders, 'x-request-id': reqId, 'server-timing': timing }
398
+ }
399
+ const headers = addVary ? withVaryAcceptEncoding(baseHeaders) : { ...baseHeaders }
400
+ if (enc !== undefined) {
401
+ headers['content-encoding'] = enc
402
+ const etag = headers.etag ?? headers.ETag
403
+ if (etag !== undefined) {
404
+ delete headers.ETag
405
+ headers.etag = toWeakEtag(etag)
406
+ }
407
+ }
408
+ if (reqId !== undefined)
409
+ headers['x-request-id'] = reqId
410
+ if (timing !== undefined)
411
+ headers['server-timing'] = timing
412
+ return headers
413
+ }
414
+
373
415
  /** `reuse` keeps the compressed page by content hash, for routes whose HTML holds nothing per visitor. */
374
416
  export function compressedHtmlResponse(
375
417
  html: string,
@@ -378,31 +420,26 @@ export function compressedHtmlResponse(
378
420
  request: Request,
379
421
  cache: CompressionCache | undefined,
380
422
  reuse = false,
423
+ opts?: CompressedHtmlOptions,
381
424
  ): Response {
382
- const noTransform = hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
425
+ const varyPremerged = opts?.varyPremerged === true
426
+ const noTransform = !varyPremerged && hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
427
+ const addVary = cache !== undefined && !noTransform && !varyPremerged
428
+ const finishRes = (res: Response): Response => (opts?.skipMarkHandled === true ? res : markCompressionHandled(res))
429
+
383
430
  if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
384
431
  const enc = pickEncoding(request.headers.get('accept-encoding'))
385
432
  if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
386
433
  // 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
434
  const staticKey = reuse ? `s:${new Bun.CryptoHasher('sha256').update(html).digest('base64url')}` : undefined
388
- let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
389
- if (compressed === undefined)
390
- compressed = cache.compress(html, enc, staticKey)
391
- if (compressed !== undefined) {
392
- const headers = withVaryAcceptEncoding(baseHeaders)
393
- headers['content-encoding'] = enc
394
- const etag = headers.etag ?? headers.ETag
395
- if (etag !== undefined) {
396
- delete headers.ETag
397
- headers.etag = toWeakEtag(etag)
398
- }
399
- return markCompressionHandled(new Response(compressed, { status, headers }))
400
- }
435
+ const compressed = (staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined) ?? cache.compress(html, enc, staticKey)
436
+ if (compressed !== undefined)
437
+ return finishRes(new Response(compressed, { status, headers: finalizeHtmlHeaders(baseHeaders, addVary, enc, opts) }))
401
438
  }
402
439
  }
403
- return markCompressionHandled(new Response(request.method === 'HEAD' ? null : html, {
440
+ return finishRes(new Response(request.method === 'HEAD' ? null : html, {
404
441
  status,
405
- headers: cache !== undefined && !noTransform ? withVaryAcceptEncoding(baseHeaders) : baseHeaders,
442
+ headers: finalizeHtmlHeaders(baseHeaders, addVary, undefined, opts),
406
443
  }))
407
444
  }
408
445