prunelle 0.0.0-stage → 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 (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  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/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,252 @@
1
+ // Deep reactive proxy store (tree-shakable: 0 B if unused).
2
+
3
+ import type { Signal } from './index'
4
+ import { batch, isObserving, isTracking, signal, untrack, watchedSignal } from './index'
5
+
6
+ const RAW = Symbol('prunelle.store.raw')
7
+ const OWN_KEYS = Symbol('prunelle.store.keys')
8
+
9
+ // An array method that moves several entries writes each one in turn; batched, its readers see only the finished array, and untracked, an effect calling it does not subscribe to what it writes.
10
+ // Search methods read proxied entries, so fall back to the raw array when given an unwrapped object.
11
+ const arrayMethods = new Map<PropertyKey, (this: unknown[], ...args: unknown[]) => unknown>([
12
+ ...(['copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'] as const).map((name) => {
13
+ const method = Array.prototype[name] as (...args: unknown[]) => unknown
14
+ return [name, function (this: unknown[], ...args: unknown[]) {
15
+ return batch(() => untrack(() => method.apply(this, args)))
16
+ }] as const
17
+ }),
18
+ ...(['includes', 'indexOf', 'lastIndexOf'] as const).map((name) => {
19
+ const method = Array.prototype[name] as (...args: unknown[]) => unknown
20
+ return [name, function (this: unknown[], ...args: unknown[]) {
21
+ const res = method.apply(this, args)
22
+ if ((res === -1 || res === false) && typeof args[0] === 'object' && args[0] !== null) {
23
+ args[0] = unwrap(args[0])
24
+ return method.apply(unwrap(this), args)
25
+ }
26
+ return res
27
+ }] as const
28
+ }),
29
+ ])
30
+
31
+ const proxyCache = new WeakMap<object, object>()
32
+ const depsCache = new WeakMap<object, Map<PropertyKey, Signal<number>>>()
33
+ const verCache = new WeakMap<object, Signal<number>>()
34
+
35
+ function isPlain(value: unknown): value is Record<PropertyKey, unknown> {
36
+ if (typeof value !== 'object' || value === null)
37
+ return false
38
+ if (Array.isArray(value))
39
+ return true
40
+ const proto = Object.getPrototypeOf(value)
41
+ return proto === Object.prototype || proto === null
42
+ }
43
+
44
+ // The target behind a store proxy, or the value itself.
45
+ function unwrap<T>(value: T): T {
46
+ return typeof value === 'object' && value !== null && RAW in value ? (value as Record<symbol, T>)[RAW]! : value
47
+ }
48
+
49
+ function bumpVer(target: object): void {
50
+ const ver = verCache.get(target)
51
+ if (ver !== undefined)
52
+ ver.value = ver.peek() + 1
53
+ }
54
+
55
+ function getDep(target: object, key: PropertyKey): Signal<number> {
56
+ if (!isObserving()) {
57
+ const existing = depsCache.get(target)?.get(key)
58
+ if (existing !== undefined)
59
+ return existing
60
+ let ver = verCache.get(target)
61
+ if (ver === undefined) {
62
+ ver = signal(0)
63
+ verCache.set(target, ver)
64
+ }
65
+ return ver
66
+ }
67
+ let map = depsCache.get(target)
68
+ if (map === undefined) {
69
+ map = new Map()
70
+ depsCache.set(target, map)
71
+ }
72
+ let dep = map.get(key)
73
+ if (dep === undefined) {
74
+ dep = watchedSignal(0, () => {
75
+ if (map!.get(key) === dep) {
76
+ map!.delete(key)
77
+ if (map!.size === 0)
78
+ depsCache.delete(target)
79
+ }
80
+ })
81
+ map.set(key, dep)
82
+ }
83
+ return dep
84
+ }
85
+
86
+ function notifyKey(target: object, key: PropertyKey): void {
87
+ const dep = depsCache.get(target)?.get(key)
88
+ if (dep !== undefined)
89
+ dep.value = dep.peek() + 1
90
+ bumpVer(target)
91
+ }
92
+
93
+ function deleteDep(target: object, key: PropertyKey): void {
94
+ const map = depsCache.get(target)
95
+ const dep = map?.get(key)
96
+ if (dep !== undefined) {
97
+ dep.value = dep.peek() + 1
98
+ map!.delete(key)
99
+ if (map!.size === 0)
100
+ depsCache.delete(target)
101
+ }
102
+ bumpVer(target)
103
+ }
104
+
105
+ function evictTruncated(target: object, nextLen: number, prevLen: number): void {
106
+ const map = depsCache.get(target)
107
+ if (map !== undefined) {
108
+ for (const [k, dep] of map) {
109
+ if (typeof k === 'string') {
110
+ const idx = Number(k)
111
+ if ((idx >>> 0) === idx && idx >= nextLen && idx < prevLen && String(idx) === k) {
112
+ dep.value = dep.peek() + 1
113
+ map.delete(k)
114
+ }
115
+ }
116
+ }
117
+ if (map.size === 0)
118
+ depsCache.delete(target)
119
+ }
120
+ bumpVer(target)
121
+ }
122
+
123
+ function wrap<T extends object>(target: T): T {
124
+ const existing = proxyCache.get(target)
125
+ if (existing !== undefined)
126
+ return existing as T
127
+
128
+ const proxy = new Proxy(target, {
129
+ get(obj, key, receiver) {
130
+ if (key === RAW)
131
+ return obj
132
+ const method = Array.isArray(obj) ? arrayMethods.get(key) : undefined
133
+ if (method !== undefined)
134
+ return method
135
+ if (isTracking()) {
136
+ getDep(obj, key).value
137
+ // A reader of an array's length is walking it (a list loop reads entries untracked), so any entry write reaches it.
138
+ if (key === 'length' && Array.isArray(obj))
139
+ getDep(obj, OWN_KEYS).value
140
+ }
141
+ const value = Reflect.get(obj, key, receiver)
142
+ if (!isPlain(value))
143
+ return value
144
+ const desc = Object.getOwnPropertyDescriptor(obj, key)
145
+ if (desc !== undefined && !desc.configurable && !desc.writable && !desc.get)
146
+ return value
147
+ return wrap(value)
148
+ },
149
+ set(obj, key, value, receiver) {
150
+ const rawValue = unwrap(value)
151
+ const had = Object.prototype.hasOwnProperty.call(obj, key)
152
+ const prev = Reflect.get(obj, key, obj)
153
+ const isArr = Array.isArray(obj)
154
+ const prevLength = isArr ? obj.length : 0
155
+ const ok = Reflect.set(obj, key, rawValue, receiver)
156
+ if (!ok)
157
+ return false
158
+ const changed = !had || !Object.is(prev, rawValue)
159
+ const lenChanged = isArr && obj.length !== prevLength
160
+ if (changed || lenChanged) {
161
+ batch(() => {
162
+ if (changed) {
163
+ notifyKey(obj, key)
164
+ if (!had || isArr)
165
+ notifyKey(obj, OWN_KEYS)
166
+ }
167
+ // Writing past the end grows the array without a later `length` write that differs; truncating drops trailing elements.
168
+ if (lenChanged) {
169
+ if (key !== 'length')
170
+ notifyKey(obj, 'length')
171
+ else if (obj.length < prevLength)
172
+ evictTruncated(obj, obj.length, prevLength)
173
+ }
174
+ })
175
+ }
176
+ return true
177
+ },
178
+ deleteProperty(obj, key) {
179
+ const had = Object.prototype.hasOwnProperty.call(obj, key)
180
+ const ok = Reflect.deleteProperty(obj, key)
181
+ if (had && ok) {
182
+ batch(() => {
183
+ deleteDep(obj, key)
184
+ notifyKey(obj, OWN_KEYS)
185
+ })
186
+ }
187
+ return ok
188
+ },
189
+ has(obj, key) {
190
+ if (key === RAW)
191
+ return true
192
+ if (isTracking())
193
+ getDep(obj, key).value
194
+ return Reflect.has(obj, key)
195
+ },
196
+ ownKeys(obj) {
197
+ if (isTracking())
198
+ getDep(obj, OWN_KEYS).value
199
+ return Reflect.ownKeys(obj)
200
+ },
201
+ })
202
+
203
+ proxyCache.set(target, proxy)
204
+ return proxy
205
+ }
206
+
207
+ export function store<T extends object>(initial: T): T {
208
+ if (!isPlain(initial))
209
+ return initial
210
+ return wrap(initial)
211
+ }
212
+
213
+ export function snapshot<T>(value: T): T {
214
+ return untrack(() => cloneRaw(value, new Map()))
215
+ }
216
+
217
+ /** @internal Test helper: number of tracked dependency keys currently cached for `target`. */
218
+ export function _storeDepsSize(target: object): number {
219
+ return depsCache.get(unwrap(target))?.size ?? 0
220
+ }
221
+
222
+ function cloneRaw<T>(value: T, seen: Map<object, unknown>): T {
223
+ const raw = unwrap(value)
224
+ if (typeof raw !== 'object' || raw === null)
225
+ return raw
226
+ const cached = seen.get(raw)
227
+ if (cached !== undefined)
228
+ return cached as T
229
+ if (Array.isArray(raw)) {
230
+ const copy: unknown[] = []
231
+ copy.length = raw.length
232
+ seen.set(raw, copy)
233
+ for (let i = 0; i < raw.length; i++) {
234
+ if (i in raw)
235
+ copy[i] = cloneRaw(raw[i], seen)
236
+ }
237
+ return copy as unknown as T
238
+ }
239
+ if (isPlain(raw)) {
240
+ const copy: Record<string, unknown> = {}
241
+ seen.set(raw, copy)
242
+ for (const [k, v] of Object.entries(raw)) {
243
+ // Assigning `__proto__` would set the copy's prototype; JSON.parse makes it an own key, so it stays one.
244
+ if (k === '__proto__')
245
+ Object.defineProperty(copy, k, { value: cloneRaw(v, seen), writable: true, enumerable: true, configurable: true })
246
+ else
247
+ copy[k] = cloneRaw(v, seen)
248
+ }
249
+ return copy as T
250
+ }
251
+ return raw as T
252
+ }
@@ -0,0 +1,158 @@
1
+ // The error flash a progressive form leaves behind: a signed 60 s cookie holding the error, the field errors and the values to put back in the form.
2
+
3
+ import type { ActionContext, ActionErrorFlash, ServerAction } from './action'
4
+ import { signPayload, verifyPayload } from './app-secret'
5
+ import { extractFormSchema, isRecord } from './form-schema'
6
+
7
+ export const ACTION_ERROR_COOKIE = '__pru_action_err'
8
+
9
+ const FLASH_PURPOSE = 'action-flash'
10
+ const MAX_FLASH_COOKIE_BYTES = 3500
11
+ const MAX_FLASH_FIELD_CHARS = 512
12
+ // Substrings that are unambiguously sensitive even inside compound identifiers.
13
+ 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
14
+ // Short acronyms/words matched only on token boundaries (after camelCase/punctuation/accent normalization) to avoid false positives like `subscribe`, `article`, `souvenir`, or `description`.
15
+ const SENSITIVE_TOKEN_RE = /\b(?:mot de passe|mdp|pwd|pw|pswd|psw|pass|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
16
+
17
+ function isSensitiveField(name: string): boolean {
18
+ const normalized = name
19
+ .normalize('NFD')
20
+ .replace(/[\u0300-\u036F]/g, '')
21
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
22
+ .replace(/[^a-zA-Z0-9]+/g, ' ')
23
+ .trim()
24
+ return SENSITIVE_SUBSTRING_RE.test(normalized) || SENSITIVE_TOKEN_RE.test(normalized)
25
+ }
26
+
27
+ function parseStringRecord(raw: unknown): Record<string, string> | undefined {
28
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
29
+ return undefined
30
+ const out: Record<string, string> = Object.create(null)
31
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
32
+ if (typeof v !== 'string')
33
+ return undefined
34
+ out[k] = v
35
+ }
36
+ return out
37
+ }
38
+
39
+ function parseActionErrorFlash(raw: unknown): ActionErrorFlash | undefined {
40
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
41
+ return undefined
42
+ const rec = raw as Record<string, unknown>
43
+ if (typeof rec.action !== 'string' || typeof rec.error !== 'string')
44
+ return undefined
45
+ const fieldErrors = rec.fieldErrors === undefined ? undefined : parseStringRecord(rec.fieldErrors)
46
+ if (rec.fieldErrors !== undefined && fieldErrors === undefined)
47
+ return undefined
48
+ const values = rec.values === undefined ? undefined : parseStringRecord(rec.values)
49
+ if (rec.values !== undefined && values === undefined)
50
+ return undefined
51
+ return {
52
+ action: rec.action,
53
+ error: rec.error,
54
+ ...(fieldErrors !== undefined ? { fieldErrors } : {}),
55
+ ...(values !== undefined ? { values } : {}),
56
+ }
57
+ }
58
+
59
+ /** Hydrates `ctx.locals.actionError` from `__pru_action_err` without clearing the cookie yet; returns true when the cookie was present. A cookie whose signature does not match is ignored. */
60
+ export function hydrateActionErrorFlash(ctx: Pick<ActionContext, 'cookies' | 'locals'>): boolean {
61
+ const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
62
+ if (rawFlash === undefined)
63
+ return false
64
+ const payload = verifyPayload(FLASH_PURPOSE, rawFlash)
65
+ if (payload === undefined)
66
+ return true
67
+ let json: unknown
68
+ try {
69
+ json = JSON.parse(payload)
70
+ }
71
+ catch {
72
+ return true
73
+ }
74
+ const parsed = parseActionErrorFlash(json)
75
+ if (parsed !== undefined)
76
+ ctx.locals.actionError = parsed
77
+ return true
78
+ }
79
+
80
+ // A property the schema marks as a secret (`format: "password"`, `writeOnly`).
81
+ function isSecretProperty(jsonSchema: Record<string, unknown>, name: string): boolean {
82
+ const props = jsonSchema.properties
83
+ const prop = isRecord(props) ? props[name] : undefined
84
+ return isRecord(prop) && (prop.format === 'password' || prop.writeOnly === true)
85
+ }
86
+
87
+ const derivedFields = new WeakMap<object, ReadonlySet<string>>()
88
+
89
+ /**
90
+ * The form fields an error may put back in the form: the action's `flashFields` when it lists them, else the fields its schema declares, minus anything that reads as a secret.
91
+ * A schema that cannot describe itself as JSON declares none, so such an action lists `flashFields` to get its form refilled.
92
+ */
93
+ export function flashAllowlist(act: Pick<ServerAction<unknown, unknown>, 'schema' | 'flashFields'>): ReadonlySet<string> {
94
+ if (act.flashFields !== undefined)
95
+ return new Set(act.flashFields)
96
+ if (act.schema === undefined)
97
+ return new Set()
98
+ let names = derivedFields.get(act.schema)
99
+ if (names === undefined) {
100
+ const extracted = extractFormSchema(act.schema)
101
+ names = extracted.ok
102
+ ? new Set([...extracted.fields.keys()].filter(name => !isSensitiveField(name) && !isSecretProperty(extracted.jsonSchema, name)))
103
+ : new Set()
104
+ derivedFields.set(act.schema, names)
105
+ }
106
+ return names
107
+ }
108
+
109
+ function encodedFlashSize(flash: ActionErrorFlash): number {
110
+ return Buffer.byteLength(encodeURIComponent(JSON.stringify(flash)), 'utf8')
111
+ }
112
+
113
+ /** The value of the flash cookie: the signed JSON of the error, its field errors, and the allowed fields of the body that fit under 3.5 KB. */
114
+ export function buildActionErrorFlash(
115
+ actionUrl: string,
116
+ error: string,
117
+ fieldErrors: Record<string, string> | undefined,
118
+ rawBody: unknown,
119
+ allowed: ReadonlySet<string>,
120
+ ): string {
121
+ const trimmedError = error.length > 256 ? error.slice(0, 256) : error
122
+ const base: ActionErrorFlash = {
123
+ action: actionUrl,
124
+ error: trimmedError,
125
+ }
126
+ if (fieldErrors !== undefined) {
127
+ const safeErrors: Record<string, string> = Object.create(null)
128
+ base.fieldErrors = safeErrors
129
+ for (const [k, msg] of Object.entries(fieldErrors)) {
130
+ const trimmed = msg.length > 256 ? msg.slice(0, 256) : msg
131
+ safeErrors[k] = trimmed
132
+ if (encodedFlashSize(base) > MAX_FLASH_COOKIE_BYTES) {
133
+ delete safeErrors[k]
134
+ break
135
+ }
136
+ }
137
+ }
138
+
139
+ const values: Record<string, string> = Object.create(null)
140
+ if (rawBody !== null && typeof rawBody === 'object') {
141
+ for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
142
+ if (typeof v !== 'string' || v.length > MAX_FLASH_FIELD_CHARS || !allowed.has(k))
143
+ continue
144
+ values[k] = v
145
+ const candidate: ActionErrorFlash = { ...base, values }
146
+ if (encodedFlashSize(candidate) > MAX_FLASH_COOKIE_BYTES) {
147
+ delete values[k]
148
+ break
149
+ }
150
+ }
151
+ }
152
+
153
+ const finalFlash: ActionErrorFlash = {
154
+ ...base,
155
+ ...(Object.keys(values).length > 0 ? { values } : {}),
156
+ }
157
+ return signPayload(FLASH_PURPOSE, JSON.stringify(finalFlash))
158
+ }
@@ -0,0 +1,199 @@
1
+ // Built-in spam & abuse protection for public server actions: honeypot field + HMAC-signed render timestamp.
2
+
3
+ import type { ActionContext } from './action'
4
+ import type { RateLimit } from './rate-limit'
5
+ import { getAppContext } from '../plugins/context'
6
+ import { appSecret, deriveKey, safeEqual } from './app-secret'
7
+ import { nodeEnv } from './env'
8
+ import { assertRateLimit } from './rate-limit'
9
+
10
+ export const DEFAULT_HONEYPOT_FIELD = '_pru_hp'
11
+ export const FORM_TIMESTAMP_FIELD = '_pru_ts'
12
+ /** A signed timestamp older than this is refused: a form left open longer is rendered again. */
13
+ export const MAX_FORM_AGE_MS = 2 * 60 * 60 * 1000
14
+ /** What every refusal says, whichever check failed, so a bot learns nothing about which one it tripped. */
15
+ const REJECTED = 'Submission rejected'
16
+
17
+ export interface ActionProtectOptions {
18
+ /** Sliding-window rate limit for submissions to this action. */
19
+ rateLimit?: RateLimit<ActionContext> | undefined
20
+ /** Hidden trap input name (`true` uses `_pru_hp`, or pass a custom field name). Non-empty values are rejected. */
21
+ honeypot?: boolean | string | undefined
22
+ /** Minimum elapsed milliseconds between SSR render and submit; enforced with an HMAC-signed `_pru_ts` token. */
23
+ minTime?: number | undefined
24
+ }
25
+
26
+ const DIGITS_RE = /^\d+$/
27
+ const TIMESTAMP_PURPOSE = 'form-timestamp'
28
+
29
+ // At definition, so a deploy that signs with a per-process key says so at start, not on the first submit.
30
+ function warnEphemeralSecret(): void {
31
+ if (nodeEnv() === 'production' && appSecret().ephemeral)
32
+ console.warn('prunelle: protect.minTime is signing form timestamps with a key made at this start because PRUNELLE_FORM_SECRET and AUTH_SECRET are unset, so a restart or a second instance refuses every form already rendered: set PRUNELLE_FORM_SECRET to 32 random bytes or more.')
33
+ }
34
+
35
+ function timestampSignature(payload: string): string {
36
+ return new Bun.CryptoHasher('sha256', deriveKey(TIMESTAMP_PURPOSE)).update(payload).digest('hex')
37
+ }
38
+
39
+ function timestampPayload(ts: string, actionUrl: string): string {
40
+ return actionUrl !== '' ? `${ts}\0${actionUrl}` : ts
41
+ }
42
+
43
+ function escapeAttrValue(value: string): string {
44
+ return value.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
45
+ }
46
+
47
+ /** Returns the configured honeypot field name, or `undefined` when honeypot is disabled. */
48
+ export function honeypotFieldName(protect: ActionProtectOptions | undefined): string | undefined {
49
+ if (protect?.honeypot === true)
50
+ return DEFAULT_HONEYPOT_FIELD
51
+ if (typeof protect?.honeypot === 'string') {
52
+ const trimmed = protect.honeypot.trim()
53
+ return trimmed !== '' ? trimmed : undefined
54
+ }
55
+ return undefined
56
+ }
57
+
58
+ /** Whether `protect` requires reading the request body (honeypot or minTime). */
59
+ export function needsProtectBody(protect: ActionProtectOptions | undefined): boolean {
60
+ return honeypotFieldName(protect) !== undefined || protect?.minTime !== undefined
61
+ }
62
+
63
+ /** Validates `ActionProtectOptions` eagerly when `action()` is defined. */
64
+ export function assertActionProtect(protect: ActionProtectOptions): void {
65
+ if (protect.rateLimit !== undefined)
66
+ assertRateLimit(protect.rateLimit, 'an action')
67
+ if (protect.minTime !== undefined && (!Number.isFinite(protect.minTime) || protect.minTime < 0))
68
+ throw new Error(`prunelle: protect.minTime of an action is ${String(protect.minTime)}; give a non-negative number of milliseconds.`)
69
+ if (typeof protect.honeypot === 'string' && protect.honeypot.trim() === '')
70
+ throw new Error('prunelle: protect.honeypot of an action must be a non-empty field name.')
71
+ if (protect.minTime !== undefined)
72
+ warnEphemeralSecret()
73
+ }
74
+
75
+ /** Creates an HMAC-SHA256 signed timestamp token (`<timestampMs>.<signatureHex>`), optionally bound to `actionUrl`. */
76
+ export function signFormTimestamp(timestampMs = Date.now(), actionUrl = ''): string {
77
+ const ts = String(Math.trunc(timestampMs))
78
+ const sig = timestampSignature(timestampPayload(ts, actionUrl))
79
+ return `${ts}.${sig}`
80
+ }
81
+
82
+ /** Verifies an HMAC-signed `_pru_ts` token against `minTimeMs`, the two-hour expiry window, and optional `actionUrl`. */
83
+ export function verifyFormTimestamp(
84
+ token: unknown,
85
+ minTimeMs: number,
86
+ now = Date.now(),
87
+ actionUrl = '',
88
+ ): { ok: true } | { ok: false, reason: string } {
89
+ if (typeof token !== 'string')
90
+ return { ok: false, reason: 'Missing form timestamp' }
91
+ const dot = token.indexOf('.')
92
+ if (dot <= 0 || dot === token.length - 1)
93
+ return { ok: false, reason: 'Invalid form timestamp' }
94
+ const tsStr = token.slice(0, dot)
95
+ const sig = token.slice(dot + 1)
96
+ if (!DIGITS_RE.test(tsStr))
97
+ return { ok: false, reason: 'Invalid form timestamp' }
98
+ const expected = timestampSignature(timestampPayload(tsStr, actionUrl))
99
+ if (!safeEqual(sig, expected))
100
+ return { ok: false, reason: 'Invalid form timestamp' }
101
+ const ts = Number(tsStr)
102
+ if (!Number.isFinite(ts))
103
+ return { ok: false, reason: 'Invalid form timestamp' }
104
+ const elapsed = now - ts
105
+ if (elapsed < minTimeMs)
106
+ return { ok: false, reason: 'Form submitted too quickly' }
107
+ if (elapsed > MAX_FORM_AGE_MS)
108
+ return { ok: false, reason: 'Form submission expired' }
109
+ return { ok: true }
110
+ }
111
+
112
+ function isNonEmptyFieldValue(value: unknown): boolean {
113
+ if (Array.isArray(value))
114
+ return value.some(v => v !== '' && v != null)
115
+ return value !== '' && value != null
116
+ }
117
+
118
+ /** Returns a shallow copy of `rawBody` with internal Prunelle protection fields removed. */
119
+ export function stripProtectFields(protect: ActionProtectOptions | undefined, rawBody: unknown): unknown {
120
+ if (protect === undefined || rawBody === null || typeof rawBody !== 'object' || Array.isArray(rawBody))
121
+ return rawBody
122
+ const hpField = honeypotFieldName(protect)
123
+ const hasMinTime = protect.minTime !== undefined
124
+ if (hpField === undefined && !hasMinTime)
125
+ return rawBody
126
+ const obj = rawBody as Record<string, unknown>
127
+ const dropHp = hpField !== undefined && Object.hasOwn(obj, hpField)
128
+ const dropTs = hasMinTime && Object.hasOwn(obj, FORM_TIMESTAMP_FIELD)
129
+ if (!dropHp && !dropTs)
130
+ return rawBody
131
+ const entries: [string, unknown][] = []
132
+ for (const [k, v] of Object.entries(obj)) {
133
+ if ((dropHp && k === hpField) || (dropTs && k === FORM_TIMESTAMP_FIELD))
134
+ continue
135
+ entries.push([k, v])
136
+ }
137
+ return Object.fromEntries(entries)
138
+ }
139
+
140
+ const warnedNoTimestamp = new Set<string>()
141
+
142
+ // Once per action and process, in dev only: in production a submit without the token is a bot's, and only a developer can act on why.
143
+ function warnNoTimestamp(actionUrl: string): void {
144
+ if (warnedNoTimestamp.has(actionUrl) || getAppContext()?.dev !== true)
145
+ return
146
+ warnedNoTimestamp.add(actionUrl)
147
+ console.warn(`prunelle: the action at ${actionUrl} refused a submit with no signed ${FORM_TIMESTAMP_FIELD} timestamp, which protect.minTime requires: prunelle signs one only into a <form action={...}> rendered on the server, so a form an island renders in the browser (after a click, say) has none; render the form in the page's first render and hide it until needed, or drop minTime and rely on the honeypot and rateLimit.`)
148
+ }
149
+
150
+ /** Verifies honeypot and signed timestamp protections and returns the body with internal fields stripped. */
151
+ export function verifyActionProtection(
152
+ protect: ActionProtectOptions | undefined,
153
+ rawBody: unknown,
154
+ now = Date.now(),
155
+ actionUrl = '',
156
+ ): { ok: true, cleanedBody: unknown } | { ok: false, error: string, cleanedBody: unknown } {
157
+ if (protect === undefined)
158
+ return { ok: true, cleanedBody: rawBody }
159
+ const hpField = honeypotFieldName(protect)
160
+ const minTime = protect.minTime
161
+ if (hpField === undefined && minTime === undefined)
162
+ return { ok: true, cleanedBody: rawBody }
163
+
164
+ const cleanedBody = stripProtectFields(protect, rawBody)
165
+ const obj = rawBody !== null && typeof rawBody === 'object' && !Array.isArray(rawBody)
166
+ ? rawBody as Record<string, unknown>
167
+ : undefined
168
+
169
+ if (hpField !== undefined && obj !== undefined && Object.hasOwn(obj, hpField)) {
170
+ if (isNonEmptyFieldValue(obj[hpField]))
171
+ return { ok: false, error: REJECTED, cleanedBody }
172
+ }
173
+
174
+ if (minTime !== undefined) {
175
+ const rawTs = obj !== undefined && Object.hasOwn(obj, FORM_TIMESTAMP_FIELD) ? obj[FORM_TIMESTAMP_FIELD] : undefined
176
+ const token = Array.isArray(rawTs) ? rawTs[0] : rawTs
177
+ const tsResult = verifyFormTimestamp(token, minTime, now, actionUrl)
178
+ if (!tsResult.ok) {
179
+ if (token === undefined)
180
+ warnNoTimestamp(actionUrl)
181
+ return { ok: false, error: REJECTED, cleanedBody }
182
+ }
183
+ }
184
+
185
+ return { ok: true, cleanedBody }
186
+ }
187
+
188
+ /** Renders the SSR hidden protection inputs (visually hidden honeypot + signed timestamp) for `<form action={fn}>`. */
189
+ export function renderProtectFields(protect: ActionProtectOptions | undefined, actionUrl = ''): string {
190
+ if (protect === undefined)
191
+ return ''
192
+ let html = ''
193
+ const hp = honeypotFieldName(protect)
194
+ if (hp !== undefined)
195
+ html += `<input type="text" name="${escapeAttrValue(hp)}" value="" tabindex="-1" autocomplete="off" aria-hidden="true" style="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden">`
196
+ if (protect.minTime !== undefined)
197
+ html += `<input type="hidden" name="${FORM_TIMESTAMP_FIELD}" value="${signFormTimestamp(undefined, actionUrl)}">`
198
+ return html
199
+ }
@@ -0,0 +1,78 @@
1
+ // The app's server actions: their live URLs, the middleware each one runs behind, and invocation with its folder's `_middleware.ts` chain.
2
+
3
+ import type { ActionResult, ServerAction } from './action'
4
+ import type { Middleware, RequestContext } from './http'
5
+ import { invokeActionCore } from './action'
6
+ import { runChain } from './http'
7
+ import { runInRequest } from './request-scope'
8
+
9
+ export interface RegisteredAction {
10
+ act: ServerAction<unknown, unknown>
11
+ /** Plugin middlewares, then the `_middleware.ts` chain of the action's folder. */
12
+ middlewares: Middleware[]
13
+ }
14
+
15
+ export interface ActionRegistry {
16
+ /** Gives `act` its name and live URL and records the middlewares a request to it runs behind. */
17
+ register: (act: ServerAction<unknown, unknown>, name: string, url: string, dirMiddlewares: Middleware[], pluginMiddlewares: readonly Middleware[]) => void
18
+ byUrl: (url: string) => RegisteredAction | undefined
19
+ /** Runs an action with schema validation behind its folder's `_middleware.ts` chain, as an island call would. */
20
+ invoke: <I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext) => Promise<ActionResult<O>>
21
+ /** Runs `fn` as part of the request `ctx`, so the actions it calls run in that request. */
22
+ run: <T>(ctx: RequestContext, fn: () => T) => T
23
+ }
24
+
25
+ export function createActionRegistry(): ActionRegistry {
26
+ const handlers = new Map<string, RegisteredAction>()
27
+ const dirMiddlewaresByRef = new WeakMap<ServerAction<unknown, unknown>, Middleware[]>()
28
+
29
+ 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>) ?? []
31
+ if (dirMiddlewares.length === 0)
32
+ return invokeActionCore(act, input, ctx)
33
+
34
+ let actionResult: ActionResult<O> | undefined
35
+ const res = await runChain(ctx, dirMiddlewares, async () => {
36
+ actionResult = await invokeActionCore(act, input, ctx)
37
+ return new Response(null, { status: actionResult.ok ? 200 : actionResult.status })
38
+ })
39
+ if (actionResult !== undefined)
40
+ return actionResult
41
+ // A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
42
+ const ct = (res.headers.get('content-type') ?? '').toLowerCase()
43
+ if (ct.includes('application/json')) {
44
+ try {
45
+ const body = await res.clone().json() as Record<string, unknown>
46
+ return {
47
+ ok: false,
48
+ status: res.status,
49
+ error: typeof body.error === 'string' ? body.error : res.statusText || 'Forbidden',
50
+ }
51
+ }
52
+ catch {}
53
+ }
54
+ let text = ''
55
+ try {
56
+ text = await res.clone().text()
57
+ }
58
+ catch {}
59
+ return {
60
+ ok: false,
61
+ status: res.status,
62
+ error: text || res.statusText || 'Forbidden',
63
+ }
64
+ }
65
+
66
+ const registry: ActionRegistry = {
67
+ register(act, name, url, dirMiddlewares, pluginMiddlewares) {
68
+ ;(act as { url: string }).url = url
69
+ Object.defineProperty(act, 'name', { value: name, configurable: true })
70
+ dirMiddlewaresByRef.set(act, dirMiddlewares)
71
+ handlers.set(url, { act, middlewares: [...pluginMiddlewares, ...dirMiddlewares] })
72
+ },
73
+ byUrl: url => handlers.get(url),
74
+ invoke,
75
+ run: (ctx, fn) => runInRequest({ ctx, actions: registry }, fn),
76
+ }
77
+ return registry
78
+ }