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
@@ -1,9 +1,10 @@
1
1
  // Standalone `--static` directory server (used when `outDir` holds exported HTML without `manifest.json`): every file is listed once at startup, so a request is a map lookup.
2
2
 
3
3
  import type { FSWatcher } from 'node:fs'
4
- import type { PrunellePlugin, ServerErrorInfo } from '../plugins/index'
4
+ import type { LogConfig, PrunellePlugin, ServerErrorInfo } from '../plugins/index'
5
5
  import type { NavigationConfig } from '../ssr/navigation'
6
- import type { PrunelleApp, PrunelleServer } from './http'
6
+ import type { CorsConfig } from './cors'
7
+ import type { PrunelleApp, PrunelleServer, ServeOptions } from './http'
7
8
  import type { SecurityHeadersOptions, TrustProxy } from './security'
8
9
  import type { FileSource, ServedFile } from './served-file'
9
10
  import { readdirSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
@@ -13,12 +14,25 @@ import { resolvePlugins } from '../plugins/index'
13
14
  import { createNavigation, cspSha256 } from '../ssr/navigation'
14
15
  import { staticMime } from './assets'
15
16
  import { CompressionCache, isCompressibleType } from './compress'
17
+ import { withCorsSetting } from './cors'
16
18
  import { createErrorNotifier } from './errors'
17
19
  import { applyHstsHeader } from './http'
20
+ import { createRequestObserver } from './request-log'
18
21
  import { decodeRequestPath } from './request-path'
19
- import { buildSecurityHeaderEntries, inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
22
+ import { buildSecurityHeaderEntries, inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes, withoutCspReports } from './security'
20
23
  import { createFileServer, servedFile } from './served-file'
21
24
 
25
+ // The extensions `prunelle build --static` gives an extension-less API route by its content type (`CONTENT_TYPE_EXT` in `build/prerender.ts`).
26
+ const PRERENDERED_API_EXTS = new Set(['.json', '.xml', '.rss', '.atom', '.txt', '.ics', '.csv'])
27
+
28
+ // An extension-less API route the export wrote as `x.json`, `x.xml` or `x.txt` is also served at `x`.
29
+ function aliasApiRoute(table: Map<string, ServedFile>, rel: string, entry: ServedFile): void {
30
+ const ext = extname(rel)
31
+ const bare = rel.slice(0, -ext.length)
32
+ if (PRERENDERED_API_EXTS.has(ext) && extname(bare) === '' && !table.has(bare))
33
+ table.set(bare, entry)
34
+ }
35
+
22
36
  const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
23
37
 
24
38
  export interface StaticDirExtraOptions {
@@ -29,6 +43,8 @@ export interface StaticDirExtraOptions {
29
43
  errorSink?: ((info: ServerErrorInfo) => void) | undefined
30
44
  httpsSite?: boolean | undefined
31
45
  nodeEnv?: string | undefined
46
+ log?: LogConfig | undefined
47
+ cors?: CorsConfig | undefined
32
48
  }
33
49
 
34
50
  function findNotFound(rel: string | undefined, byDir: ReadonlyMap<string, ServedFile>): ServedFile | undefined {
@@ -99,10 +115,10 @@ export function createStaticDirServer(
99
115
  realRoot = absRoot // listed as empty below, which answers 404s
100
116
  }
101
117
  const compressCache = compressEnabled ? new CompressionCache() : undefined
102
- const securityEntries = buildSecurityHeaderEntries(security)
118
+ const securityEntries = buildSecurityHeaderEntries(withoutCspReports(security))
103
119
  const securityRecord = Object.fromEntries(securityEntries)
104
- const baseCsp = resolveCspPolicy(security)
105
- const nav = extra !== undefined ? createNavigation(extra.navigation) : undefined
120
+ const baseCsp = resolveCspPolicy(withoutCspReports(security))
121
+ const nav = extra !== undefined ? createNavigation(extra.navigation, assetPrefix) : undefined
106
122
  const plugins = extra?.plugins !== undefined ? resolvePlugins(extra.plugins) : []
107
123
  const extraStyleHashes = [PRUNELLE_ISLAND_STYLE_HASH, ...(nav?.styleHashes ?? [])]
108
124
  const extraScriptHashes = [
@@ -118,7 +134,7 @@ export function createStaticDirServer(
118
134
  ? (res: Response) => res
119
135
  : (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev, extra?.nodeEnv, httpsSite)
120
136
  const serveFileUnguarded = createFileServer({ compressEnabled, compressCache, withHsts })
121
- const notifyError = createErrorNotifier(extra?.onError, plugins, { dev: isDev, sink: extra?.errorSink })
137
+ const notifyError = createErrorNotifier(extra?.onError, plugins, { dev: isDev, sink: extra?.errorSink, format: extra?.log?.format })
122
138
  // A file that fails to open answers here, where the request is known: gone since the listing is a 404, anything else is reported.
123
139
  const serveFile = async (req: Request, file: ServedFile, status?: number): Promise<Response> => {
124
140
  try {
@@ -157,7 +173,7 @@ export function createStaticDirServer(
157
173
  })
158
174
  }
159
175
 
160
- // Each file at its own path, then `x.html` at `x` and `x/index.html` at `x`, a real file always winning.
176
+ // Each file at its own path, then `x.html` at `x`, `x/index.html` at `x` and an exported `x.json` at `x`, a real file always winning.
161
177
  function buildTable(): { table: Map<string, ServedFile>, notFoundByDir: Map<string, ServedFile> } {
162
178
  const files = listFiles(absRoot, realRoot)
163
179
  const table = new Map<string, ServedFile>()
@@ -181,6 +197,9 @@ export function createStaticDirServer(
181
197
  table.set(dir, entry)
182
198
  }
183
199
  }
200
+ // Last, so a page (`x.html`, `x/index.html`) keeps `x` over a data file beside it.
201
+ for (const [rel, entry] of [...table])
202
+ aliasApiRoute(table, rel, entry)
184
203
  return { table, notFoundByDir }
185
204
  }
186
205
 
@@ -199,7 +218,8 @@ export function createStaticDirServer(
199
218
  console.warn(`prunelle start: files changed in ${absRoot} will be served only after a restart: ${err instanceof Error ? err.message : String(err)}`)
200
219
  }
201
220
 
202
- const handle = async (req: Request): Promise<Response> => {
221
+ // Behind `cors`, a preflight carries the headers the other answers do.
222
+ const answer = withCorsSetting(extra?.cors, (res, req) => withHsts(new Response(null, { status: res.status, headers: { ...securityRecord, ...Object.fromEntries(res.headers) } }), req), async (req: Request): Promise<Response> => {
203
223
  if (!isRead(req))
204
224
  return withHsts(new Response('Method Not Allowed', { status: 405, headers: { ...securityRecord, allow: 'GET, HEAD' } }), req)
205
225
  const rel = requestedRel(new URL(req.url).pathname)
@@ -210,7 +230,9 @@ export function createStaticDirServer(
210
230
  if (notFound !== undefined)
211
231
  return serveFile(req, notFound, 404)
212
232
  return withHsts(new Response('Not Found', { status: 404, headers: securityRecord }), req)
213
- }
233
+ })
234
+ const observe = createRequestObserver(extra?.log, [], isDev)
235
+ const handle = observe?.(answer) ?? answer
214
236
 
215
237
  const error = (): Response => new Response('Internal Server Error', {
216
238
  status: 500,
@@ -225,8 +247,8 @@ export function createStaticDirServer(
225
247
  return {
226
248
  handle,
227
249
  securityHeaders: securityRecord,
228
- serve(port = 3000, hostname = '127.0.0.1') {
229
- return Bun.serve({ port, hostname, idleTimeout: 30, development: false, fetch: handle, error: lastResort })
250
+ serve(port = 3000, hostname = '127.0.0.1', options: ServeOptions = {}) {
251
+ return Bun.serve({ port, hostname, reusePort: options.reusePort === true, idleTimeout: 30, development: false, fetch: handle, error: lastResort })
230
252
  },
231
253
  reloadInto(server: PrunelleServer) {
232
254
  server.reload({ routes: {}, fetch: handle, error: lastResort })
@@ -3,6 +3,7 @@
3
3
  import type { PendingChunk, RenderContext, SettledChunk } from '../ssr/context'
4
4
  import { getAppContext, runWithAppContext } from '../plugins/index'
5
5
  import { streamChunkScript } from '../ssr/context'
6
+ import { cancelQuietly } from './discard'
6
7
  import { currentRequest, runInRequest } from './request-scope'
7
8
 
8
9
  const textEncoder = new TextEncoder()
@@ -165,7 +166,7 @@ function trackEventStream(res: Response, active: Set<() => void>, setIdleTimeout
165
166
  closed = true
166
167
  active.delete(closeStream!)
167
168
  safeClose(controller)
168
- void reader.cancel().catch(() => undefined)
169
+ void cancelQuietly(reader)
169
170
  }
170
171
  active.add(closeStream)
171
172
  },
@@ -0,0 +1,39 @@
1
+ // What outside clients can call: the app's server actions and API routes, each with the JSON Schema of its input.
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import type { AppSurface, SurfaceInput } from '../plugins/types'
5
+ import { isServerAction } from './action'
6
+ import { extractFormSchema } from './form-schema'
7
+ import { isStandardSchema } from './route-input'
8
+ import { HTTP_METHOD_EXPORTS } from './route-table'
9
+
10
+ function inputOf(schema: unknown): SurfaceInput {
11
+ if (!isStandardSchema(schema))
12
+ return { kind: 'none' }
13
+ const extracted = extractFormSchema(schema)
14
+ return extracted.ok ? { kind: 'json', schema: extracted.jsonSchema } : { kind: 'unsupported', vendor: extracted.vendor, reason: extracted.reason }
15
+ }
16
+
17
+ /** A route is an API route when it answers methods and renders no page. */
18
+ function apiMethods(mod: Record<string, unknown>): string[] {
19
+ if (typeof mod.default === 'function')
20
+ return []
21
+ return [...HTTP_METHOD_EXPORTS].filter(method => typeof mod[method] === 'function')
22
+ }
23
+
24
+ export function appSurface(manifest: BuildManifest, modules: Record<string, unknown>): AppSurface {
25
+ const actions: AppSurface['actions'][number][] = []
26
+ for (const entry of manifest.actions) {
27
+ const act = (modules[entry.file] as Record<string, unknown> | undefined)?.[entry.exportName]
28
+ if (isServerAction(act))
29
+ actions.push({ name: entry.exportName, url: entry.url, input: inputOf(act.schema), rateLimited: act.rateLimit !== undefined })
30
+ }
31
+ const routes: AppSurface['routes'][number][] = []
32
+ for (const entry of manifest.routes) {
33
+ const mod = modules[entry.file] as Record<string, unknown> | undefined
34
+ const methods = mod === undefined ? [] : apiMethods(mod)
35
+ if (methods.length > 0)
36
+ routes.push({ path: entry.path, methods, input: inputOf(mod!.schema) })
37
+ }
38
+ return { actions, routes }
39
+ }
@@ -0,0 +1,50 @@
1
+ // Webhook signatures: a route that turns off the cross-site check (`export const csrf = false`) proves the sender with one of these instead.
2
+
3
+ import { hmac, safeEqual } from './app-secret'
4
+
5
+ /** `standard` is Standard Webhooks (Svix, Resend, Clerk and others), `stripe` Stripe's `Stripe-Signature`, `github` GitHub's `X-Hub-Signature-256`. */
6
+ export type WebhookScheme = 'standard' | 'stripe' | 'github'
7
+
8
+ export interface VerifyWebhookOptions {
9
+ /** How far the signed timestamp may be from now, for the schemes that sign one (5 minutes). GitHub signs none. */
10
+ toleranceSeconds?: number | undefined
11
+ }
12
+
13
+ const TOLERANCE_SECONDS = 300
14
+ const STANDARD_PREFIX = 'whsec_'
15
+
16
+ /** The request's body when it carries a valid signature for `scheme` under `secret`, signed within `toleranceSeconds` where the scheme signs a time; undefined otherwise. It reads the body, so the route parses the text this returns. */
17
+ export async function verifyWebhook(request: Request, scheme: WebhookScheme, secret: string | undefined, options: VerifyWebhookOptions = {}): Promise<string | undefined> {
18
+ if (!secret)
19
+ throw new Error(`prunelle: verifyWebhook('${scheme}') got no secret: pass the signing secret the sender shows, read from an environment variable`)
20
+ // The signature covers the bytes the sender wrote: decoding them first would turn a non-UTF-8 byte into U+FFFD and fail a valid body.
21
+ const bytes = Buffer.from(await request.arrayBuffer())
22
+ const body = new TextDecoder().decode(bytes)
23
+ const headers = request.headers
24
+ const tolerance = options.toleranceSeconds ?? TOLERANCE_SECONDS
25
+ if (scheme === 'github') {
26
+ const signature = headers.get('x-hub-signature-256') ?? ''
27
+ return safeEqual(signature, `sha256=${hmac(secret, bytes).toString('hex')}`) ? body : undefined
28
+ }
29
+ if (scheme === 'stripe') {
30
+ const fields = (headers.get('stripe-signature') ?? '').split(',').map(field => field.split('='))
31
+ const timestamp = fields.find(([key]) => key === 't')?.[1]
32
+ if (timestamp === undefined || !fresh(timestamp, tolerance))
33
+ return undefined
34
+ const expected = hmac(secret, Buffer.concat([Buffer.from(`${timestamp}.`), bytes])).toString('hex')
35
+ return fields.some(([key, value]) => key === 'v1' && value !== undefined && safeEqual(value, expected)) ? body : undefined
36
+ }
37
+ const id = headers.get('webhook-id')
38
+ const timestamp = headers.get('webhook-timestamp')
39
+ if (id === null || timestamp === null || !fresh(timestamp, tolerance))
40
+ return undefined
41
+ const key = Buffer.from(secret.startsWith(STANDARD_PREFIX) ? secret.slice(STANDARD_PREFIX.length) : secret, 'base64')
42
+ const expected = hmac(key, Buffer.concat([Buffer.from(`${id}.${timestamp}.`), bytes])).toString('base64')
43
+ const signatures = (headers.get('webhook-signature') ?? '').split(' ')
44
+ return signatures.some(entry => entry.startsWith('v1,') && safeEqual(entry.slice(3), expected)) ? body : undefined
45
+ }
46
+
47
+ function fresh(timestamp: string, toleranceSeconds: number): boolean {
48
+ const seconds = Number(timestamp)
49
+ return /^\d+$/.test(timestamp) && Math.abs(Date.now() / 1000 - seconds) <= toleranceSeconds
50
+ }
@@ -0,0 +1,168 @@
1
+ // `prunelle start --workers <n>`: n processes of `prunelle start` listening on one port with SO_REUSEPORT, the kernel spreading connections across them.
2
+ // The primary serves nothing: it gives the workers one signing secret, passes a stop signal on to them, and starts again one that dies after it listened.
3
+ // Each worker tells the primary it listens over the IPC channel Bun opens between them, and stops when that channel closes, as it does when the primary is killed.
4
+
5
+ import process from 'node:process'
6
+
7
+ /** `<index>/<count>` in a worker's environment; its absence means the process serves alone. */
8
+ export const WORKER_ENV = 'PRUNELLE_WORKER'
9
+ /** The secret every worker signs with when the app sets none, so a form one rendered is accepted by the others. */
10
+ export const WORKERS_SECRET_ENV = 'PRUNELLE_WORKERS_SECRET'
11
+
12
+ /** What a worker sends the primary once it listens. */
13
+ export const READY_MESSAGE = 'prunelle:ready'
14
+
15
+ const SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const
16
+ const RESTART_DELAY_MS = 1000
17
+ const WORKER_RE = /^(\d+)\/(\d+)$/
18
+
19
+ /** This process's place among the workers of a `prunelle start --workers`, or undefined when it serves alone. */
20
+ export function workerOf(env: Record<string, string | undefined> = process.env): { index: number, count: number } | undefined {
21
+ const match = WORKER_RE.exec(env[WORKER_ENV] ?? '')
22
+ return match === null ? undefined : { index: Number(match[1]), count: Number(match[2]) }
23
+ }
24
+
25
+ /** In a worker: stops it the way SIGTERM does once the primary is gone, whose stop signal would never come, and SO_REUSEPORT would let a new primary's workers share the port with it. */
26
+ export function followPrimary(): void {
27
+ process.once('disconnect', () => process.kill(process.pid, 'SIGTERM'))
28
+ }
29
+
30
+ /** In a worker: tells the primary it listens, so a later exit is a crash to recover from rather than a failure to start. */
31
+ export function reportListening(): void {
32
+ process.send?.(READY_MESSAGE)
33
+ }
34
+
35
+ /** The count `--workers` asks for, a whole number from 1 or `auto` for one per CPU core; undefined when it is neither. */
36
+ export function parseWorkers(value: string, cores: number = navigator.hardwareConcurrency): number | undefined {
37
+ if (value === 'auto')
38
+ return Math.max(1, cores)
39
+ const count = Number(value)
40
+ return Number.isInteger(count) && count >= 1 ? count : undefined
41
+ }
42
+
43
+ const RATE_LIMIT_CLAUSE = 'each counts rate limits alone, so a client gets its limit once per process'
44
+
45
+ export interface PerProcessInput {
46
+ store: string | undefined
47
+ /** Limiters counting in the process's memory, with or without a `store`: the app's own `createRateLimitStore()` ones and the unnamed ones of plugins. */
48
+ limiters: number
49
+ actionsRateLimited: boolean
50
+ cachedRoutes: boolean
51
+ plugins: readonly { perProcess?: string | undefined }[]
52
+ }
53
+
54
+ /** What each process keeps alone when several serve the app with no `store`, one clause each. */
55
+ export function perProcessState(input: PerProcessInput): string[] {
56
+ // A `store` shares the named limiters; the ones counting in memory stay per process.
57
+ if (input.store !== undefined)
58
+ return input.limiters > 0 ? [RATE_LIMIT_CLAUSE] : []
59
+ const clauses: string[] = []
60
+ if (input.limiters > 0 || input.actionsRateLimited)
61
+ clauses.push(RATE_LIMIT_CLAUSE)
62
+ if (input.cachedRoutes)
63
+ clauses.push('invalidateCache() drops a cached page in the process that ran it only')
64
+ for (const plugin of input.plugins) {
65
+ if (plugin.perProcess !== undefined)
66
+ clauses.push(plugin.perProcess)
67
+ }
68
+ return clauses
69
+ }
70
+
71
+ export interface SuperviseOptions {
72
+ count: number
73
+ /** What each worker runs: this `prunelle start` again, which reads its place from `PRUNELLE_WORKER` and sends `READY_MESSAGE` once it listens. The others start once the first has. */
74
+ command: string[]
75
+ env?: Record<string, string | undefined> | undefined
76
+ log?: ((message: string) => void) | undefined
77
+ /** @internal How long a worker that died waits before it starts again (1 s). */
78
+ restartDelayMs?: number | undefined
79
+ }
80
+
81
+ export interface Supervisor {
82
+ /** Passes `signal` on to every worker and starts none again. */
83
+ stop: (signal?: typeof SIGNALS[number]) => void
84
+ /** The highest exit code of the workers, once the last has exited after a stop. */
85
+ exited: Promise<number>
86
+ }
87
+
88
+ /** Starts the first worker, the others once it listens, starts again one that dies after it listened, and stops them all on SIGTERM, SIGINT or SIGHUP, or when one exits before it listens. */
89
+ export function superviseWorkers(options: SuperviseOptions): Supervisor {
90
+ const env = options.env ?? process.env
91
+ // A worker starting workers would start more on each restart, until the machine runs out of memory.
92
+ if (workerOf(env) !== undefined)
93
+ throw new Error(`prunelle: a worker of prunelle start --workers cannot start workers of its own: unset ${WORKER_ENV} in the environment that runs prunelle start`)
94
+ const log = options.log ?? ((message: string) => console.error(message))
95
+ const secret = env.PRUNELLE_FORM_SECRET || env.AUTH_SECRET ? undefined : Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('hex')
96
+ const workers = new Map<number, Bun.Subprocess>()
97
+ const timers = new Set<ReturnType<typeof setTimeout>>()
98
+ let stopping = false
99
+ let exitCode = 0
100
+ let resolveExited!: (code: number) => void
101
+ const exited = new Promise<number>(resolve => resolveExited = resolve)
102
+
103
+ const settle = (): void => {
104
+ if (stopping && workers.size === 0 && timers.size === 0) {
105
+ for (const [signal, listener] of listeners)
106
+ process.off(signal, listener)
107
+ resolveExited(exitCode)
108
+ }
109
+ }
110
+
111
+ const stop = (signal: typeof SIGNALS[number] = 'SIGTERM'): void => {
112
+ stopping = true
113
+ for (const timer of timers)
114
+ clearTimeout(timer)
115
+ timers.clear()
116
+ for (const worker of workers.values())
117
+ worker.kill(signal)
118
+ settle()
119
+ }
120
+
121
+ // The others wait for the first to listen: a config that fails to load is then reported by one worker, not by each.
122
+ let othersStarted = false
123
+ const start = (index: number): void => {
124
+ let listening = false
125
+ const worker = Bun.spawn(options.command, {
126
+ env: { ...env, [WORKER_ENV]: `${index}/${options.count}`, ...(secret === undefined ? {} : { [WORKERS_SECRET_ENV]: secret }) },
127
+ stdio: ['ignore', 'inherit', 'inherit'],
128
+ ipc: (message) => {
129
+ if (message !== READY_MESSAGE)
130
+ return
131
+ listening = true
132
+ if (othersStarted)
133
+ return
134
+ othersStarted = true
135
+ for (let other = 2; other <= options.count && !stopping; other++)
136
+ start(other)
137
+ },
138
+ })
139
+ workers.set(index, worker)
140
+ void worker.exited.then((code) => {
141
+ workers.delete(index)
142
+ if (stopping) {
143
+ exitCode = Math.max(exitCode, code)
144
+ return settle()
145
+ }
146
+ // Starting it again would fail the same way. Exit code 0 is a stop signal that reached the worker before the primary, as Ctrl-C does.
147
+ if (!listening) {
148
+ log(code === 0
149
+ ? `prunelle start: worker ${index} stopped before it listened, so every worker is stopped`
150
+ : `prunelle start: worker ${index} exited with code ${code} before it listened, so every worker is stopped: its error is above`)
151
+ exitCode = code
152
+ return stop()
153
+ }
154
+ log(`prunelle start: worker ${index} exited with code ${code}; starting it again`)
155
+ const timer = setTimeout(() => {
156
+ timers.delete(timer)
157
+ start(index)
158
+ }, options.restartDelayMs ?? RESTART_DELAY_MS)
159
+ timers.add(timer)
160
+ })
161
+ }
162
+
163
+ const listeners = SIGNALS.map(signal => [signal, () => stop(signal)] as const)
164
+ for (const [signal, listener] of listeners)
165
+ process.on(signal, listener)
166
+ start(1)
167
+ return { stop, exited }
168
+ }
@@ -2,6 +2,8 @@
2
2
 
3
3
  import type { ConsentBannerProps, ConsentTexts } from '../context'
4
4
  import type { RequestConsent } from '../server/consent'
5
+ import type { ConsentDefaults } from './consent-texts'
6
+ import { consentDefaults } from './consent-texts'
5
7
  import { esc, escAttr, ssrChild } from './index'
6
8
 
7
9
  function requireCategories(consent: RequestConsent, tag: string): void {
@@ -9,52 +11,54 @@ function requireCategories(consent: RequestConsent, tag: string): void {
9
11
  throw new Error(`prunelle: <${tag}> has no consent category to ask about: declare them in prunelle.config.ts, such as consent: { categories: { analytics: 'Audience measurement' } }.`)
10
12
  }
11
13
 
12
- function checkboxes(consent: RequestConsent, legend: string | undefined): string {
14
+ function checkboxes(consent: RequestConsent, legend: string): string {
13
15
  const boxes = consent.categories.map((category) => {
14
16
  const checked = consent.has(category) ? ' checked' : ''
15
17
  return `<label data-part="choice"><input type="checkbox" name="categories" value="${escAttr(category)}"${checked}> ${esc(consent.labels[category] ?? category)}</label>`
16
18
  })
17
- return `<fieldset data-part="choices"><legend>${esc(legend ?? 'Cookies by purpose')}</legend>${boxes.join('')}</fieldset>`
19
+ return `<fieldset data-part="choices"><legend>${esc(legend)}</legend>${boxes.join('')}</fieldset>`
18
20
  }
19
21
 
20
22
  // Refuse comes first and looks the same as Accept: the CNIL asks for a refusal as easy as a consent.
21
- function decisionButtons(texts: ConsentTexts): string {
22
- return `<button type="submit" name="action" value="reject-all" data-ui="button">${esc(texts.refuse ?? 'Refuse all')}</button>`
23
- + `<button type="submit" name="action" value="accept-all" data-ui="button">${esc(texts.accept ?? 'Accept all')}</button>`
23
+ function decisionButtons(texts: ConsentTexts, defaults: ConsentDefaults): string {
24
+ return `<button type="submit" name="action" value="reject-all" data-ui="button">${esc(texts.refuse ?? defaults.refuse)}</button>`
25
+ + `<button type="submit" name="action" value="accept-all" data-ui="button">${esc(texts.accept ?? defaults.accept)}</button>`
24
26
  }
25
27
 
26
- function saveButton(texts: ConsentTexts): string {
27
- return `<button type="submit" name="action" value="save" data-ui="button">${esc(texts.save ?? 'Save my choices')}</button>`
28
+ function saveButton(texts: ConsentTexts, defaults: ConsentDefaults): string {
29
+ return `<button type="submit" name="action" value="save" data-ui="button">${esc(texts.save ?? defaults.save)}</button>`
28
30
  }
29
31
 
30
- export function renderConsentBanner(consent: RequestConsent | undefined, props: ConsentBannerProps): string {
32
+ export function renderConsentBanner(consent: RequestConsent | undefined, props: ConsentBannerProps, lang?: string): string {
31
33
  if (consent === undefined)
32
34
  return ''
33
35
  requireCategories(consent, 'ConsentBanner')
34
36
  if (consent.decided)
35
37
  return ''
38
+ const defaults = consentDefaults(lang ?? consent.lang)
36
39
  const labels = consent.categories.map(category => consent.labels[category] ?? category).join(', ')
37
40
  const body = props.children !== undefined
38
41
  ? ssrChild(props.children)
39
- : `<p>This site would like to set cookies for: ${esc(labels)}. You can accept or refuse them, and change your mind at any time.</p>`
42
+ : `<p>${defaults.body(esc(labels))}</p>`
40
43
  const policy = props.policyHref !== undefined
41
- ? `<p><a href="${escAttr(props.policyHref)}">${esc(props.policyLabel ?? 'Cookie policy')}</a></p>`
44
+ ? `<p><a href="${escAttr(props.policyHref)}">${esc(props.policyLabel ?? defaults.policy)}</a></p>`
42
45
  : ''
43
46
  return `<section data-ui="consent" aria-labelledby="pru-consent-title">`
44
- + `<h2 id="pru-consent-title" data-part="title">${esc(props.title ?? 'Cookies')}</h2>`
47
+ + `<h2 id="pru-consent-title" data-part="title">${esc(props.title ?? defaults.title)}</h2>`
45
48
  + `<div data-part="body">${body}${policy}</div>`
46
49
  + `<form method="post" action="${escAttr(consent.endpoint)}" data-part="form">`
47
- + `<div data-part="actions">${decisionButtons(props)}</div>`
48
- + `<details data-part="details"><summary>${esc(props.choose ?? 'Choose')}</summary>${checkboxes(consent, props.legend)}${saveButton(props)}</details>`
50
+ + `<div data-part="actions">${decisionButtons(props, defaults)}</div>`
51
+ + `<details data-part="details"><summary>${esc(props.choose ?? defaults.choose)}</summary>${checkboxes(consent, props.legend ?? defaults.legend)}${saveButton(props, defaults)}</details>`
49
52
  + `</form></section>`
50
53
  }
51
54
 
52
- export function renderConsentPreferences(consent: RequestConsent | undefined, texts: ConsentTexts): string {
55
+ export function renderConsentPreferences(consent: RequestConsent | undefined, texts: ConsentTexts, lang?: string): string {
53
56
  if (consent === undefined)
54
57
  return ''
55
58
  requireCategories(consent, 'ConsentPreferences')
59
+ const defaults = consentDefaults(lang ?? consent.lang)
56
60
  return `<form method="post" action="${escAttr(consent.endpoint)}" data-ui="consent" data-part="preferences">`
57
- + `${checkboxes(consent, texts.legend)}`
58
- + `<div data-part="actions">${saveButton(texts)}${decisionButtons(texts)}</div>`
61
+ + `${checkboxes(consent, texts.legend ?? defaults.legend)}`
62
+ + `<div data-part="actions">${saveButton(texts, defaults)}${decisionButtons(texts, defaults)}</div>`
59
63
  + `</form>`
60
64
  }
@@ -0,0 +1,40 @@
1
+ // The default texts of <ConsentBanner> and <ConsentPreferences>, in the language of the app's `lang`.
2
+
3
+ export interface ConsentDefaults {
4
+ title: string
5
+ /** The sentence of the banner, given the labels of the categories it asks about. */
6
+ body: (labels: string) => string
7
+ policy: string
8
+ accept: string
9
+ refuse: string
10
+ save: string
11
+ choose: string
12
+ legend: string
13
+ }
14
+
15
+ const ENGLISH: ConsentDefaults = {
16
+ title: 'Cookies',
17
+ body: labels => `This site would like to set cookies for: ${labels}. You can accept or refuse them, and change your mind at any time.`,
18
+ policy: 'Cookie policy',
19
+ accept: 'Accept all',
20
+ refuse: 'Refuse all',
21
+ save: 'Save my choices',
22
+ choose: 'Choose',
23
+ legend: 'Cookies by purpose',
24
+ }
25
+
26
+ const FRENCH: ConsentDefaults = {
27
+ title: 'Cookies',
28
+ body: labels => `Ce site souhaite déposer des cookies pour : ${labels}. Vous pouvez les accepter ou les refuser, et changer d'avis à tout moment.`,
29
+ policy: 'Politique de cookies',
30
+ accept: 'Tout accepter',
31
+ refuse: 'Tout refuser',
32
+ save: 'Enregistrer mes choix',
33
+ choose: 'Choisir',
34
+ legend: 'Cookies par finalité',
35
+ }
36
+
37
+ /** French for `fr`, `fr-CA` and the like, English for any other language. */
38
+ export function consentDefaults(lang: string): ConsentDefaults {
39
+ return lang.split('-', 1)[0]!.toLowerCase() === 'fr' ? FRENCH : ENGLISH
40
+ }