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
@@ -3,6 +3,7 @@
3
3
  import type { PluginRouteOptions } from '../plugins/types'
4
4
  import type { RequestContext } from './http'
5
5
  import type { TrustProxy } from './security'
6
+ import { expireCookiesOf } from './cookies'
6
7
  import { wantsJson } from './http'
7
8
  import { isTrustedOrigin, safeRedirect } from './security'
8
9
 
@@ -37,6 +38,8 @@ export interface RequestConsent {
37
38
  readonly labels: Readonly<Record<string, string>>
38
39
  /** Path the consent form posts to. */
39
40
  readonly endpoint: string
41
+ /** The app's `lang`, which picks the language of the default texts of `<ConsentBanner>` and `<ConsentPreferences>`. */
42
+ readonly lang: string
40
43
  has(category: string): boolean
41
44
  all(): Record<string, boolean>
42
45
  }
@@ -49,6 +52,7 @@ export interface NormalizedConsentConfig {
49
52
  readonly maxAge: number
50
53
  readonly endpoint: string
51
54
  readonly version: string
55
+ readonly lang: string
52
56
  }
53
57
 
54
58
  const EMPTY_CONSENT: RequestConsent = {
@@ -57,11 +61,12 @@ const EMPTY_CONSENT: RequestConsent = {
57
61
  categories: [],
58
62
  labels: {},
59
63
  endpoint: DEFAULT_CONSENT_ENDPOINT,
64
+ lang: 'en',
60
65
  has: category => category === 'essential',
61
66
  all: () => ({}),
62
67
  }
63
68
 
64
- export function normalizeConsentConfig(config: ConsentConfig | undefined): NormalizedConsentConfig | undefined {
69
+ export function normalizeConsentConfig(config: ConsentConfig | undefined, lang = 'en'): NormalizedConsentConfig | undefined {
65
70
  if (config === undefined)
66
71
  return undefined
67
72
  const rawList = Array.isArray(config.categories) ? config.categories : Object.keys(config.categories)
@@ -94,6 +99,7 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
94
99
  maxAge: config.maxAge ?? DEFAULT_CONSENT_MAX_AGE,
95
100
  endpoint,
96
101
  version,
102
+ lang,
97
103
  }
98
104
  }
99
105
 
@@ -109,8 +115,8 @@ function grantedOf(list: string, declared: ReadonlySet<string>): Set<string> {
109
115
  return granted
110
116
  }
111
117
 
112
- /** Reads `v2:<seconds>:<policy version>:<categories>`; a choice made under another policy version counts as no choice. */
113
- export function parseConsentCookie(raw: string | undefined, declared: ReadonlySet<string>, version = ''): ParsedConsent {
118
+ /** Reads `v2:<seconds>:<policy version>:<categories>`; a choice made under another policy version, or more than `maxAge` seconds ago, counts as no choice. */
119
+ export function parseConsentCookie(raw: string | undefined, declared: ReadonlySet<string>, version = '', maxAge?: number, now = Date.now()): ParsedConsent {
114
120
  const none: ParsedConsent = { decided: false, decidedAt: undefined, granted: new Set() }
115
121
  if (raw === undefined)
116
122
  return none
@@ -125,6 +131,8 @@ export function parseConsentCookie(raw: string | undefined, declared: ReadonlySe
125
131
  const at = Number(seconds)
126
132
  if (list === undefined || storedVersion !== version || !Number.isSafeInteger(at) || at <= 0)
127
133
  return none
134
+ if (maxAge !== undefined && (at + maxAge) * 1000 < now)
135
+ return none
128
136
  return { decided: true, decidedAt: new Date(at * 1000), granted: grantedOf(list, declared) }
129
137
  }
130
138
 
@@ -133,16 +141,23 @@ export function serializeConsentCookie(granted: ReadonlySet<string>, declared: r
133
141
  return `${COOKIE_PREFIX}${Math.floor(decidedAt.getTime() / 1000)}:${version}:${ordered.join(',')}`
134
142
  }
135
143
 
136
- export function createRequestConsent(rawCookie: string | undefined, config: NormalizedConsentConfig | undefined): RequestConsent {
144
+ export function createRequestConsent(
145
+ rawCookie: string | undefined,
146
+ config: NormalizedConsentConfig | undefined,
147
+ resolveLang?: () => string | undefined,
148
+ ): RequestConsent {
137
149
  if (config === undefined)
138
150
  return EMPTY_CONSENT
139
- const { decided, decidedAt, granted } = parseConsentCookie(rawCookie, config.categorySet, config.version)
151
+ const { decided, decidedAt, granted } = parseConsentCookie(rawCookie, config.categorySet, config.version, config.maxAge)
140
152
  return {
141
153
  decided,
142
154
  decidedAt,
143
155
  categories: config.categories,
144
156
  labels: config.labels,
145
157
  endpoint: config.endpoint,
158
+ get lang(): string {
159
+ return resolveLang?.() ?? config.lang
160
+ },
146
161
  has(category: string): boolean {
147
162
  return category === 'essential' || granted.has(category)
148
163
  },
@@ -281,6 +296,7 @@ export function registerConsentRoute(
281
296
  maxAge: config.maxAge,
282
297
  category: 'essential',
283
298
  })
299
+ expireCookiesOf(ctx.cookies, config.categories.filter(category => !parsed.granted.has(category)))
284
300
 
285
301
  if (wantsJson(ctx.request)) {
286
302
  const consent: Record<string, boolean> = {}
@@ -0,0 +1,78 @@
1
+ // The cookies `<CookieTable>` lists: prunelle's own, each plugin's and the app's, gathered once per server into its app context.
2
+
3
+ import type { BuildManifest } from '../build/manifest'
4
+ import type { AppRuntimeContext, CreateAppContextOptions } from '../plugins/context'
5
+ import type { PrunellePlugin } from '../plugins/types'
6
+ import type { NormalizedConsentConfig } from './consent'
7
+ import { createAppContext } from '../plugins/context'
8
+ import { serviceKey } from '../plugins/services'
9
+ import { ACTION_ERROR_COOKIE, ACTION_ERROR_MAX_AGE } from './action-flash'
10
+
11
+ /** One row of the table; a field left out could not be read from the app's source. */
12
+ export interface CookieRow {
13
+ name?: string | undefined
14
+ purpose?: string | Readonly<Record<string, string>> | undefined
15
+ category?: string | undefined
16
+ lifetime?: number | 'session' | undefined
17
+ }
18
+
19
+ export interface CookieInventory {
20
+ readonly rows: readonly CookieRow[]
21
+ /** The app's `lang`, which picks the language of the table. */
22
+ readonly lang: string
23
+ /** The consent categories' labels, shown in the category column. */
24
+ readonly labels: Readonly<Record<string, string>>
25
+ }
26
+
27
+ export const COOKIE_INVENTORY = serviceKey<CookieInventory>('prunelle.cookies')
28
+
29
+ const CONSENT_PURPOSE = {
30
+ en: 'Keeps your cookie choices, so you are not asked again on each page.',
31
+ fr: 'Garde vos choix de cookies, pour ne pas vous les redemander à chaque page.',
32
+ }
33
+ const ACTION_ERROR_PURPOSE = {
34
+ en: 'Shows the error of a form sent without JavaScript on the page it returns to.',
35
+ fr: 'Affiche l\'erreur d\'un formulaire envoyé sans JavaScript sur la page où il revient.',
36
+ }
37
+
38
+ export interface CookieInventoryOptions {
39
+ consent: NormalizedConsentConfig | undefined
40
+ manifest: Pick<BuildManifest, 'actions' | 'cookies'>
41
+ plugins: readonly PrunellePlugin[]
42
+ site: string | undefined
43
+ lang: string
44
+ }
45
+
46
+ export function cookieInventory({ consent, manifest, plugins, site, lang }: CookieInventoryOptions): CookieInventory {
47
+ const rows: CookieRow[] = []
48
+ if (consent !== undefined)
49
+ rows.push({ name: consent.cookieName, purpose: CONSENT_PURPOSE, category: 'essential', lifetime: consent.maxAge })
50
+ if (manifest.actions.length > 0)
51
+ rows.push({ name: ACTION_ERROR_COOKIE, purpose: ACTION_ERROR_PURPOSE, category: 'essential', lifetime: ACTION_ERROR_MAX_AGE })
52
+ for (const plugin of plugins) {
53
+ const declared = typeof plugin.cookies === 'function' ? plugin.cookies({ site }) : plugin.cookies ?? []
54
+ for (const cookie of declared)
55
+ rows.push({ name: cookie.name, purpose: cookie.purpose, category: cookie.category, lifetime: cookie.maxAge ?? 'session' })
56
+ }
57
+ rows.push(...manifest.cookies ?? [])
58
+ return { rows, lang, labels: consent?.labels ?? {} }
59
+ }
60
+
61
+ export interface ServerAppContextOptions extends Omit<CreateAppContextOptions, 'onRegisterPublicFile'>, Omit<CookieInventoryOptions, 'site'> {
62
+ /** The build's context when the server runs inside one, told of each public file a plugin writes. */
63
+ parent: AppRuntimeContext | undefined
64
+ registerPublicFromDisk: (publicDir: string, rel: string) => void
65
+ }
66
+
67
+ /** The server's app context, holding the cookie inventory `<CookieTable>` renders. */
68
+ export function createServerAppContext({ parent, registerPublicFromDisk, consent, manifest, plugins, lang, ...options }: ServerAppContextOptions): AppRuntimeContext {
69
+ const appCtx = createAppContext({
70
+ ...options,
71
+ onRegisterPublicFile: (rel) => {
72
+ parent?.registerPublicFile(rel)
73
+ registerPublicFromDisk(options.publicDir, rel)
74
+ },
75
+ })
76
+ appCtx.provide(COOKIE_INVENTORY, cookieInventory({ consent, manifest, plugins, site: options.site, lang }))
77
+ return appCtx
78
+ }
@@ -1,6 +1,8 @@
1
1
  // Typed cookie jar for RequestContext (lazy Cookie header parsing, validated & deduplicated Set-Cookie serialization).
2
2
 
3
3
  import { getAppContext } from '../plugins/context'
4
+ import { serviceKey } from '../plugins/services'
5
+ import { COOKIE_INVENTORY } from './cookie-inventory'
4
6
 
5
7
  export interface CookieOptions {
6
8
  path?: string | undefined
@@ -12,6 +14,8 @@ export interface CookieOptions {
12
14
  sameSite?: 'strict' | 'lax' | 'none' | undefined
13
15
  /** Consent category required before setting this cookie, or `'essential'` for a cookie the site cannot work without; omitted, it counts as essential and `prunelle dev` warns. */
14
16
  category?: string | undefined
17
+ /** What the cookie is for, as `<CookieTable>` lists it: read from the source by `prunelle build`, so write it as a literal; ignored when setting the cookie. */
18
+ purpose?: string | undefined
15
19
  }
16
20
 
17
21
  const warnedUncategorized = new Set<string>()
@@ -24,6 +28,59 @@ function warnUncategorized(name: string): void {
24
28
  console.warn(`prunelle: cookie "${name}" was set without a category, so it counts as essential and is set without consent: pass { category: 'essential' } when the site cannot work without it, or its consent category (such as 'analytics') so it waits for the visitor's consent.`)
25
29
  }
26
30
 
31
+ // A category consent does not declare is never granted, so its cookie would vanish without a trace: same once-per-name dev warning.
32
+ function warnUndeclaredCategory(name: string, category: string): void {
33
+ if (warnedUncategorized.has(name) || getAppContext()?.dev !== true)
34
+ return
35
+ warnedUncategorized.add(name)
36
+ console.warn(`prunelle: cookie "${name}" was not set: its category "${category}" is not declared in consent.categories of prunelle.config.ts, so no visitor can ever grant it: fix the category name, or declare it there.`)
37
+ }
38
+
39
+ // The cookies this server instance set under each consent category, kept on AppRuntimeContext so servers stay isolated,
40
+ // paired with COOKIE_INVENTORY so consent withdrawal also expires declared cookies across restarts and worker processes.
41
+ const MAX_REMEMBERED_PER_CATEGORY = 200
42
+ type CategoryCookieMap = Map<string, Map<string, Pick<CookieOptions, 'path' | 'domain'>>>
43
+ const SET_COOKIES_BY_CATEGORY = serviceKey<CategoryCookieMap>('prunelle.cookies.byCategory')
44
+
45
+ function rememberUnderCategory(category: string, name: string, options: CookieOptions): void {
46
+ const appCtx = getAppContext()
47
+ if (appCtx === undefined)
48
+ return
49
+ let byCategory = appCtx.inject(SET_COOKIES_BY_CATEGORY)
50
+ if (byCategory === undefined) {
51
+ byCategory = new Map()
52
+ appCtx.provide(SET_COOKIES_BY_CATEGORY, byCategory)
53
+ }
54
+ let names = byCategory.get(category)
55
+ if (names === undefined) {
56
+ names = new Map()
57
+ byCategory.set(category, names)
58
+ }
59
+ if (names.size < MAX_REMEMBERED_PER_CATEGORY || names.has(name))
60
+ names.set(name, { path: options.path, domain: options.domain })
61
+ }
62
+
63
+ /** Expires, on the visitor's browser, each cookie of these refused categories that the request still carries. */
64
+ export function expireCookiesOf(jar: Cookies, categories: Iterable<string>): void {
65
+ const appCtx = getAppContext()
66
+ const byCategory = appCtx?.inject(SET_COOKIES_BY_CATEGORY)
67
+ const inventory = appCtx?.inject(COOKIE_INVENTORY)
68
+ for (const category of categories) {
69
+ const expired = new Set<string>()
70
+ for (const [name, scope] of byCategory?.get(category) ?? []) {
71
+ expired.add(name)
72
+ if (jar.get(name) !== undefined)
73
+ jar.delete(name, scope)
74
+ }
75
+ for (const row of inventory?.rows ?? []) {
76
+ if (row.category === category && row.name !== undefined && !expired.has(row.name) && jar.get(row.name) !== undefined) {
77
+ expired.add(row.name)
78
+ jar.delete(row.name)
79
+ }
80
+ }
81
+ }
82
+ }
83
+
27
84
  export interface Cookies {
28
85
  get(name: string): string | undefined
29
86
  set(name: string, value: string, options?: CookieOptions): void
@@ -87,10 +144,14 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
87
144
  if (options.maxAge !== undefined) {
88
145
  if (!Number.isFinite(options.maxAge))
89
146
  throw new TypeError(`prunelle: invalid cookie maxAge "${options.maxAge}"`)
90
- out += `; Max-Age=${Math.floor(options.maxAge)}`
147
+ // A fraction above zero rounds up: flooring 0.5 to 0 would delete the cookie it sets.
148
+ out += `; Max-Age=${options.maxAge > 0 ? Math.ceil(options.maxAge) : Math.floor(options.maxAge)}`
91
149
  }
92
- if (options.expires !== undefined)
150
+ if (options.expires !== undefined) {
151
+ if (Number.isNaN(options.expires.getTime()))
152
+ throw new TypeError('prunelle: invalid cookie expires: pass a valid Date.')
93
153
  out += `; Expires=${options.expires.toUTCString()}`
154
+ }
94
155
  if (options.httpOnly ?? true)
95
156
  out += '; HttpOnly'
96
157
  if (secure)
@@ -106,14 +167,16 @@ function cookieKey(name: string, options?: Pick<CookieOptions, 'path' | 'domain'
106
167
  export class CookieStore implements Cookies {
107
168
  #rawHeader: string | null
108
169
  #values: Map<string, string> | undefined
109
- readonly #headers = new Map<string, string>()
170
+ #headers: Map<string, string> | undefined
110
171
  readonly #isHttps: boolean
111
172
  readonly #isConsentGranted: ((category: string) => boolean) | undefined
173
+ readonly #isDeclared: ((category: string) => boolean) | undefined
112
174
 
113
- constructor(cookieHeader: string | null, isHttps = false, isConsentGranted?: (category: string) => boolean) {
175
+ constructor(cookieHeader: string | null, isHttps = false, isConsentGranted?: (category: string) => boolean, isDeclared?: (category: string) => boolean) {
114
176
  this.#rawHeader = cookieHeader
115
177
  this.#isHttps = isHttps
116
178
  this.#isConsentGranted = isConsentGranted
179
+ this.#isDeclared = isDeclared
117
180
  }
118
181
 
119
182
  #ensureValues(): Map<string, string> {
@@ -132,17 +195,21 @@ export class CookieStore implements Cookies {
132
195
  if (options?.category === undefined)
133
196
  warnUncategorized(name)
134
197
  else if (options.category !== 'essential') {
135
- if (this.#isConsentGranted === undefined || !this.#isConsentGranted(options.category))
198
+ if (this.#isConsentGranted === undefined || !this.#isConsentGranted(options.category)) {
199
+ if (this.#isDeclared?.(options.category) === false)
200
+ warnUndeclaredCategory(name, options.category)
136
201
  return
202
+ }
203
+ rememberUnderCategory(options.category, name, options)
137
204
  }
138
205
  const serialized = serializeCookie(name, value, options, this.#isHttps)
139
206
  this.#ensureValues().set(name, value)
140
- this.#headers.set(cookieKey(name, options), serialized)
207
+ ;(this.#headers ??= new Map()).set(cookieKey(name, options), serialized)
141
208
  }
142
209
 
143
210
  delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void {
144
211
  this.#ensureValues().delete(name)
145
- this.#headers.set(cookieKey(name, options), serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
212
+ ;(this.#headers ??= new Map()).set(cookieKey(name, options), serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
146
213
  }
147
214
 
148
215
  all(): Record<string, string> {
@@ -150,10 +217,12 @@ export class CookieStore implements Cookies {
150
217
  }
151
218
 
152
219
  get hasChanges(): boolean {
153
- return this.#headers.size > 0
220
+ return this.#headers !== undefined && this.#headers.size > 0
154
221
  }
155
222
 
156
223
  applyTo(headers: Headers): void {
224
+ if (this.#headers === undefined)
225
+ return
157
226
  for (const serialized of this.#headers.values())
158
227
  headers.append('set-cookie', serialized)
159
228
  }
@@ -0,0 +1,98 @@
1
+ // The `cors` setting of `prunelle.config.ts`: the origins whose scripts may call this app, and the preflight their browser sends first (#430).
2
+
3
+ import { mergeVaryValue } from './compress'
4
+
5
+ export interface CorsConfig {
6
+ /** The origins allowed, each `scheme://host[:port]`; they also pass the CSRF origin check. `'*'` lets any origin read, and keeps the CSRF check on the other methods. */
7
+ origins: readonly string[] | '*'
8
+ /** Lets the browser send cookies and read the answer to a credentialed request (default false); not with `'*'`. */
9
+ credentials?: boolean | undefined
10
+ /** Response headers the calling script may read beyond the CORS-safelisted ones, e.g. `['x-request-id']`. */
11
+ exposeHeaders?: readonly string[] | undefined
12
+ }
13
+
14
+ /** Answers an allowed origin's preflight before `handler`, and adds the CORS headers to what `handler` answers. */
15
+ export type CorsWrap = <A extends unknown[]>(handler: (request: Request, ...args: A) => Response | Promise<Response>) => (request: Request, ...args: A) => Response | Promise<Response>
16
+
17
+ export interface Cors {
18
+ /** The listed origins, which pass the CSRF origin check; none for `'*'`. */
19
+ trusted: readonly string[]
20
+ /** The wrap of the app's handlers, `seal` adding to the preflight what the server adds to its other answers (security headers, HSTS). */
21
+ wrapWith: (seal: (res: Response, request: Request) => Response) => CorsWrap
22
+ }
23
+
24
+ const PREFLIGHT_METHODS = 'GET, HEAD, POST, PUT, PATCH, DELETE'
25
+ const READ_METHODS = 'GET, HEAD'
26
+ // Ten minutes: Chromium caps the preflight cache at two hours, Firefox at one day.
27
+ const PREFLIGHT_MAX_AGE = '600'
28
+
29
+ function assertOrigin(origin: string): void {
30
+ if (URL.parse(origin)?.origin !== origin)
31
+ throw new Error(`prunelle: cors.origins holds "${origin}", which is not an origin: write it as scheme://host[:port], with no path or trailing slash.`)
32
+ }
33
+
34
+ /** `handler` behind the `cors` setting, or `handler` itself without one. */
35
+ export function withCorsSetting(config: CorsConfig | undefined, seal: (res: Response, request: Request) => Response, handler: (request: Request) => Promise<Response>): (request: Request) => Promise<Response> {
36
+ const wrapped = createCors(config)?.wrapWith(seal)(handler)
37
+ return wrapped === undefined ? handler : async request => wrapped(request)
38
+ }
39
+
40
+ export function createCors(config: CorsConfig | undefined): Cors | undefined {
41
+ if (config === undefined)
42
+ return undefined
43
+ const { origins } = config
44
+ const anyOrigin = origins === '*'
45
+ if (!anyOrigin && !Array.isArray(origins))
46
+ throw new Error(`prunelle: cors.origins is ${JSON.stringify(origins)}, which is not a list: write origins: ['https://front.example'], or '*' to let any origin read.`)
47
+ if (anyOrigin && config.credentials === true)
48
+ throw new Error('prunelle: cors.credentials cannot go with origins: \'*\', as browsers refuse that pair: list the origins that may send credentials.')
49
+ const trusted = anyOrigin ? [] : [...origins]
50
+ for (const origin of trusted)
51
+ assertOrigin(origin)
52
+ const allowed = new Set(trusted)
53
+ const exposed = config.exposeHeaders?.join(', ')
54
+
55
+ const allowFor = (origin: string | null): string | undefined => {
56
+ if (anyOrigin)
57
+ return '*'
58
+ return origin !== null && allowed.has(origin) ? origin : undefined
59
+ }
60
+ // Every answer to a listed origin depends on the Origin header, so every answer says so, or a cache would hand one origin's answer to another.
61
+ const decorate = (headers: Headers, allow: string | undefined): void => {
62
+ if (!anyOrigin)
63
+ headers.set('vary', mergeVaryValue(headers.get('vary'), 'Origin'))
64
+ if (allow === undefined)
65
+ return
66
+ headers.set('access-control-allow-origin', allow)
67
+ if (config.credentials === true)
68
+ headers.set('access-control-allow-credentials', 'true')
69
+ }
70
+ const preflight = (request: Request, allow: string): Response => {
71
+ const headers = new Headers({ 'access-control-allow-methods': anyOrigin ? READ_METHODS : PREFLIGHT_METHODS, 'access-control-max-age': PREFLIGHT_MAX_AGE })
72
+ const requested = request.headers.get('access-control-request-headers')
73
+ if (requested !== null)
74
+ headers.set('access-control-allow-headers', requested)
75
+ decorate(headers, allow)
76
+ return new Response(null, { status: 204, headers })
77
+ }
78
+ // A copy, as a response may come with immutable headers (a fetched or a shared one).
79
+ const withHeaders = (res: Response, allow: string | undefined): Response => {
80
+ const out = new Response(res.body, res)
81
+ decorate(out.headers, allow)
82
+ if (allow !== undefined && exposed !== undefined)
83
+ out.headers.set('access-control-expose-headers', exposed)
84
+ return out
85
+ }
86
+ const answer = async (pending: Promise<Response>, allow: string | undefined): Promise<Response> => withHeaders(await pending, allow)
87
+
88
+ return {
89
+ trusted,
90
+ wrapWith: seal => handler => (request, ...args) => {
91
+ const allow = allowFor(request.headers.get('origin'))
92
+ if (allow !== undefined && request.method === 'OPTIONS' && request.headers.has('access-control-request-method'))
93
+ return seal(preflight(request, allow), request)
94
+ const res = handler(request, ...args)
95
+ return res instanceof Response ? withHeaders(res, allow) : answer(res, allow)
96
+ },
97
+ }
98
+ }
@@ -0,0 +1,90 @@
1
+ // The endpoint `security.cspReports` adds: each CSP violation report a browser sends reaches `onError` as a `csp` error.
2
+
3
+ import type { PluginRouteOptions } from '../plugins/types'
4
+ import type { NotifyError } from './errors'
5
+ import type { RequestContext } from './http'
6
+ import { enforceRequestBodyLimit } from './http'
7
+ import { CSP_REPORT_PATH } from './security'
8
+
9
+ /** One violation, read from either format a browser sends. */
10
+ export interface CspViolation {
11
+ directive: string
12
+ blockedUrl: string
13
+ page: string
14
+ sourceFile?: string
15
+ line?: number
16
+ }
17
+
18
+ type Register = (method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions) => void
19
+
20
+ // A report holds one violation of a few hundred bytes; a `report-to` batch holds a handful.
21
+ const MAX_REPORT_BYTES = 16 * 1024
22
+ const REPORT_RATE_LIMIT = { max: 30, windowMs: 60_000 }
23
+ // An extension's own scripts and images trip the page's CSP on every visit, and nothing the app changes stops them.
24
+ const EXTENSION_URL_RE = /^(?:chrome|moz|safari(?:-web)?|ms-browser)-extension:/
25
+
26
+ const MAX_LOGGED_CHARS = 200
27
+
28
+ /** A report field fit for a log line: control characters and the Unicode line separators (U+0085, U+2028, U+2029) become spaces, so a newline cannot forge a line, and a long value is cut. */
29
+ const loggable = (value: string): string => {
30
+ const flat = value.replace(/[\x00-\x1F\x7F\x85\u2028\u2029]/g, ' ')
31
+ return flat.length > MAX_LOGGED_CHARS ? `${flat.slice(0, MAX_LOGGED_CHARS)}...` : flat
32
+ }
33
+
34
+ const text = (value: unknown): string | undefined => typeof value === 'string' && value !== '' ? value : undefined
35
+
36
+ function violation(directive: unknown, blockedUrl: unknown, page: unknown, sourceFile: unknown, line: unknown): CspViolation | undefined {
37
+ const fields = { directive: text(directive), blockedUrl: text(blockedUrl), page: text(page) }
38
+ if (fields.directive === undefined || fields.page === undefined)
39
+ return undefined
40
+ const found: CspViolation = { directive: fields.directive, blockedUrl: fields.blockedUrl ?? 'inline', page: fields.page }
41
+ const file = text(sourceFile)
42
+ if (file !== undefined)
43
+ found.sourceFile = file
44
+ if (typeof line === 'number' && line > 0)
45
+ found.line = line
46
+ return found
47
+ }
48
+
49
+ type Fields = Record<string, unknown>
50
+ const isObject = (value: unknown): value is Fields => typeof value === 'object' && value !== null
51
+
52
+ /** The violations in a report body: `report-uri`'s `{ "csp-report": {...} }` or `report-to`'s array, whose other report types are skipped. Undefined when the body is neither. */
53
+ export function parseCspReports(body: unknown): CspViolation[] | undefined {
54
+ if (Array.isArray(body)) {
55
+ return body.flatMap((report) => {
56
+ if (!isObject(report) || report.type !== 'csp-violation' || !isObject(report.body))
57
+ return []
58
+ const b = report.body
59
+ return violation(b.effectiveDirective, b.blockedURL, b.documentURL, b.sourceFile, b.lineNumber) ?? []
60
+ })
61
+ }
62
+ if (!isObject(body) || !isObject(body['csp-report']))
63
+ return undefined
64
+ const r = body['csp-report']
65
+ const found = violation(r['effective-directive'], r['blocked-uri'], r['document-uri'], r['source-file'], r['line-number'])
66
+ return found === undefined ? [] : [found]
67
+ }
68
+
69
+ const fromExtension = (v: CspViolation): boolean => EXTENSION_URL_RE.test(v.blockedUrl) || EXTENSION_URL_RE.test(v.sourceFile ?? '')
70
+
71
+ export function registerCspReportRoute(register: Register, notifyError: NotifyError): void {
72
+ // A report changes nothing on the server, so it skips the cross-site check, which a page with an opaque origin (a sandboxed frame) would fail with `Origin: null`.
73
+ register('POST', CSP_REPORT_PATH, async (ctx) => {
74
+ const limited = await enforceRequestBodyLimit(ctx.request, MAX_REPORT_BYTES)
75
+ if (!limited.ok)
76
+ return new Response(null, { status: limited.aborted === true ? 400 : 413 })
77
+ const violations = parseCspReports(await limited.request.json().catch(() => undefined))
78
+ if (violations === undefined)
79
+ return new Response(null, { status: 400 })
80
+ for (const v of violations) {
81
+ if (fromExtension(v))
82
+ continue
83
+ const safe: CspViolation = { ...v, directive: loggable(v.directive), blockedUrl: loggable(v.blockedUrl), page: loggable(v.page) }
84
+ if (v.sourceFile !== undefined)
85
+ safe.sourceFile = loggable(v.sourceFile)
86
+ notifyError(new Error(`CSP violation: ${safe.directive} blocked ${safe.blockedUrl} on ${safe.page}`, { cause: safe }), ctx.request, 'csp', ctx.requestId)
87
+ }
88
+ return new Response(null, { status: 204 })
89
+ }, { csrf: false, rateLimit: REPORT_RATE_LIMIT })
90
+ }
@@ -0,0 +1,13 @@
1
+ // A promise or stream whose failure nobody can act on: a body cancelled after the answer is known, a read already raced out. Named here so the intent stays in code, not in an empty handler.
2
+
3
+ function ignoreRejection(): void {}
4
+
5
+ /** Marks a promise whose rejection nobody awaits as handled, so it never surfaces as an unhandled rejection. */
6
+ export function markHandled(promise: Promise<unknown>): void {
7
+ promise.then(undefined, ignoreRejection)
8
+ }
9
+
10
+ /** Cancels a body or reader and waits for it, whatever the outcome: the stream is already past use. */
11
+ export function cancelQuietly(source: { cancel: () => Promise<void> } | null): Promise<void> {
12
+ return (source?.cancel() ?? Promise.resolve()).then(undefined, ignoreRejection)
13
+ }
@@ -30,8 +30,8 @@ export type HtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic:
30
30
  const STYLED_HEADER_CACHE_SIZE = 256
31
31
 
32
32
  // HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
33
- export function createHtmlHeaders(security: SecurityHeadersOptions | false | undefined, securityRecord: Record<string, string>, navigation?: Navigation, plugins: readonly PrunellePlugin[] = []): HtmlHeaders {
34
- const baseCsp = resolveCspPolicy(security)
33
+ export function createHtmlHeaders(security: SecurityHeadersOptions | false | undefined, securityRecord: Record<string, string>, navigation?: Navigation, plugins: readonly PrunellePlugin[] = [], overHttps = false): HtmlHeaders {
34
+ const baseCsp = resolveCspPolicy(security, overHttps)
35
35
  const navStyles = navigation?.styleHashes ?? []
36
36
  const navScripts = [...navigation?.scriptHashes ?? [], ...plugins.flatMap(plugin => plugin.inlineScripts ?? []).map(cspSha256)]
37
37
  const htmlHeaderSets: Record<string, string>[] = []
package/src/server/env.ts CHANGED
@@ -21,7 +21,7 @@ export function devFromEnv(): boolean {
21
21
  return false
22
22
  const where = BINARY_MAIN_RE.test(Bun.main) ? 'inside a compiled binary' : nodeEnv() === 'production' ? 'with NODE_ENV=production' : undefined
23
23
  if (where !== undefined)
24
- throw new Error(`prunelle: PRUNELLE_DEV=1 is set ${where}, where dev mode would open the CMS write routes, the mail outbox and the other dev-only routes to visitors: unset PRUNELLE_DEV, or use prunelle dev.`)
24
+ throw new Error(`prunelle: PRUNELLE_DEV=1 is set ${where}, where dev mode would open the mail outbox and the other dev-only routes to visitors: unset PRUNELLE_DEV, or use prunelle dev.`)
25
25
  return true
26
26
  }
27
27
 
@@ -10,8 +10,10 @@ import type { DeniedInfo, RequestContext } from './http'
10
10
  import type { ParamMatcherMap } from './param-matchers'
11
11
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
12
12
  import { raw, renderDocument, ssrChild } from '../ssr/index'
13
+ import { cancelQuietly } from './discard'
13
14
  import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
14
15
  import { wantsJson } from './http'
16
+ import { errorJsonLine } from './request-log'
15
17
  import { hasPublicFavicon } from './page'
16
18
  import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
17
19
  import { decodeRequestPath, pathPrefix } from './request-path'
@@ -50,6 +52,8 @@ export interface ErrorNotifierOptions {
50
52
  dev?: boolean | undefined
51
53
  /** Hears every unhandled error, hooks or not: how `testApp().errors` fills. */
52
54
  sink?: ((info: ServerErrorInfo) => void) | undefined
55
+ /** `log.format`: `'json'` prints that error as one JSON line. */
56
+ format?: 'text' | 'json' | undefined
53
57
  }
54
58
 
55
59
  export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) | undefined, plugins: readonly PrunellePlugin[], options: ErrorNotifierOptions = {}): NotifyError {
@@ -62,13 +66,16 @@ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) |
62
66
  }
63
67
  return (error, request, source, requestId) => {
64
68
  const normalized = error instanceof Response
65
- ? (void error.body?.cancel().catch(() => undefined), new Error(describeNonError(error)))
69
+ ? (void cancelQuietly(error.body), new Error(describeNonError(error)))
66
70
  : error
67
71
  const info: ServerErrorInfo = requestId !== undefined ? { error: normalized, request, source, requestId } : { error: normalized, request, source }
68
72
  options.sink?.(info)
69
73
  if (errorHooks.length === 0 && (options.dev === true || options.sink === undefined)) {
70
74
  const idSuffix = requestId !== undefined ? ` [${requestId}]` : ''
71
- console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, normalized)
75
+ if (options.format === 'json')
76
+ console.error(errorJsonLine(normalized, request, source, requestId))
77
+ else
78
+ console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, normalized)
72
79
  }
73
80
  for (const { owner, hook } of errorHooks) {
74
81
  try {