prunelle 0.6.0 → 0.7.1

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 (128) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +48 -43
  3. package/package.json +4 -1
  4. package/src/a11y/declaration.ts +106 -72
  5. package/src/a11y/index.ts +59 -39
  6. package/src/a11y/rgaa-map.ts +95 -49
  7. package/src/build/bundle.ts +8 -4
  8. package/src/build/byte-size.ts +11 -0
  9. package/src/build/client-plugin.ts +3 -1
  10. package/src/build/compile.ts +2 -1
  11. package/src/build/ecoindex.ts +25 -16
  12. package/src/build/files.ts +6 -0
  13. package/src/build/first-load.ts +83 -11
  14. package/src/build/graph.ts +29 -39
  15. package/src/build/index.ts +61 -18
  16. package/src/build/island-promote.ts +250 -0
  17. package/src/build/islands.ts +12 -201
  18. package/src/build/manifest.ts +4 -125
  19. package/src/build/plugin-host.ts +21 -8
  20. package/src/build/precompress.ts +1 -1
  21. package/src/build/prerender.ts +97 -44
  22. package/src/build/reach.ts +136 -0
  23. package/src/build/render-rules.ts +2 -2
  24. package/src/build/report.ts +25 -3
  25. package/src/build/static-headers.ts +93 -0
  26. package/src/build/static.ts +2 -0
  27. package/src/cli/check-forms.ts +97 -48
  28. package/src/cli/check-imports.ts +25 -0
  29. package/src/cli/check-links.ts +2 -2
  30. package/src/cli/check-security.ts +64 -0
  31. package/src/cli/check.ts +37 -7
  32. package/src/cli/commands.ts +35 -7
  33. package/src/cli/docs.ts +4 -3
  34. package/src/cli/inspect.ts +2 -1
  35. package/src/cli/mcp-tools.ts +7 -5
  36. package/src/cli/mcp.ts +1 -1
  37. package/src/cli/new.ts +14 -3
  38. package/src/cli/render.ts +14 -19
  39. package/src/cli/upgrade.ts +22 -5
  40. package/src/compiler/analyze.ts +27 -5
  41. package/src/compiler/cacheability.ts +2 -2
  42. package/src/compiler/compliance-eco.ts +71 -0
  43. package/src/compiler/compliance-rgaa.ts +110 -4
  44. package/src/compiler/compliance-urls.ts +146 -0
  45. package/src/compiler/compliance.ts +168 -116
  46. package/src/compiler/foreign-imports.ts +88 -0
  47. package/src/compiler/mistakes.ts +19 -1
  48. package/src/compiler/props-body.ts +60 -0
  49. package/src/compiler/shared.ts +2 -2
  50. package/src/compiler/ssr.ts +2 -2
  51. package/src/context.ts +34 -0
  52. package/src/dev/error-log.ts +90 -64
  53. package/src/dev/host-check.ts +32 -0
  54. package/src/dev/index.ts +17 -7
  55. package/src/dev/open-editor.ts +36 -12
  56. package/src/dev/protocol.ts +2 -0
  57. package/src/dev/supervisor.ts +8 -0
  58. package/src/dev/watchers.ts +27 -2
  59. package/src/dom/action.ts +4 -1
  60. package/src/dom/extras.ts +1 -2
  61. package/src/dom/index.ts +28 -6
  62. package/src/dom/island.ts +22 -10
  63. package/src/dom/loop.ts +60 -27
  64. package/src/eco/declaration.ts +257 -0
  65. package/src/eco/index.ts +65 -0
  66. package/src/index.ts +2 -2
  67. package/src/jsx-runtime.ts +2 -2
  68. package/src/plugins/config.ts +1 -1
  69. package/src/plugins/context.ts +44 -1
  70. package/src/plugins/load.ts +4 -3
  71. package/src/plugins/public.ts +2 -2
  72. package/src/plugins/services.ts +3 -0
  73. package/src/plugins/types.ts +17 -2
  74. package/src/server/action-flash.ts +158 -0
  75. package/src/server/action-protect.ts +38 -37
  76. package/src/server/action.ts +11 -127
  77. package/src/server/app-secret.ts +63 -0
  78. package/src/server/compress.ts +5 -1
  79. package/src/server/consent.ts +59 -22
  80. package/src/server/cookies.ts +16 -2
  81. package/src/server/env.ts +14 -0
  82. package/src/server/errors.ts +3 -1
  83. package/src/server/form-schema.ts +1 -1
  84. package/src/server/health.ts +46 -15
  85. package/src/server/http.ts +56 -8
  86. package/src/server/index.ts +59 -30
  87. package/src/server/loader.ts +10 -2
  88. package/src/server/plugin-host.ts +3 -1
  89. package/src/server/public.ts +4 -3
  90. package/src/server/rate-limit.ts +52 -9
  91. package/src/server/route-cache.ts +26 -4
  92. package/src/server/route-table.ts +7 -3
  93. package/src/server/routing.ts +3 -87
  94. package/src/server/sanitize-html.ts +309 -0
  95. package/src/server/security.ts +73 -22
  96. package/src/server/serve-handlers.ts +14 -4
  97. package/src/server/start.ts +1 -1
  98. package/src/server/static-dir.ts +31 -5
  99. package/src/server/stream.ts +28 -6
  100. package/src/ssr/consent-banner.ts +58 -0
  101. package/src/ssr/context.ts +20 -4
  102. package/src/ssr/index.ts +18 -0
  103. package/src/ssr/navigation.ts +2 -2
  104. package/src/style.ts +64 -1
  105. package/templates/_shared/gitignore +5 -0
  106. package/templates/_shared/src/routes/legal.tsx +10 -1
  107. package/templates/app/.env.example +4 -0
  108. package/templates/app/package.json +2 -1
  109. package/templates/app/prunelle.config.ts +2 -0
  110. package/templates/app/src/auth.ts +4 -6
  111. package/templates/app/src/mail.ts +4 -0
  112. package/templates/app/src/routes/_layout.tsx +9 -1
  113. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  114. package/templates/app/src/routes/login.tsx +49 -30
  115. package/templates/app/src/routes/privacy.tsx +25 -0
  116. package/templates/app/src/styles/app.css +8 -1
  117. package/templates/app/tests/app.test.ts +44 -3
  118. package/templates/blog/package.json +1 -1
  119. package/templates/blog/src/routes/_layout.tsx +6 -1
  120. package/templates/blog/src/routes/index.tsx +1 -1
  121. package/templates/blog/src/styles/app.css +6 -1
  122. package/templates/fullstack/package.json +1 -1
  123. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  124. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  125. package/templates/fullstack/src/styles/app.css +11 -1
  126. package/templates/minimal/package.json +1 -1
  127. package/templates/minimal/src/routes/_layout.tsx +4 -0
  128. package/templates/minimal/src/styles/app.css +11 -1
@@ -10,7 +10,10 @@ export const DEFAULT_CONSENT_COOKIE = 'pru_consent'
10
10
  /** 180 days in seconds (CNIL 6-month guideline for consent retention). */
11
11
  export const DEFAULT_CONSENT_MAX_AGE = 15_552_000
12
12
  export const DEFAULT_CONSENT_ENDPOINT = '/_pru/consent'
13
- const COOKIE_VERSION_PREFIX = 'v1:'
13
+ // v1 held the granted categories alone; v2 adds when the visitor chose and the policy version they chose under.
14
+ const LEGACY_COOKIE_PREFIX = 'v1:'
15
+ const COOKIE_PREFIX = 'v2:'
16
+ const POLICY_VERSION_RE = /^[\w.-]{1,32}$/
14
17
 
15
18
  export interface ConsentConfig {
16
19
  /** Non-essential consent categories (e.g. `['analytics', 'media']` or `{ analytics: 'Audience measurement' }`). */
@@ -21,11 +24,19 @@ export interface ConsentConfig {
21
24
  maxAge?: number | undefined
22
25
  /** POST endpoint path handling consent form submissions (default: `'/_pru/consent'`). */
23
26
  endpoint?: string | undefined
27
+ /** Version of the cookie policy (letters, digits, `.`, `-`, `_`): changing it asks every visitor again. */
28
+ version?: string | undefined
24
29
  }
25
30
 
26
31
  export interface RequestConsent {
27
32
  readonly decided: boolean
33
+ /** When the visitor made the choice in force, kept in the consent cookie as proof. */
34
+ readonly decidedAt: Date | undefined
28
35
  readonly categories: readonly string[]
36
+ /** Each category's label, from `consent.categories`, the name itself when given as a list. */
37
+ readonly labels: Readonly<Record<string, string>>
38
+ /** Path the consent form posts to. */
39
+ readonly endpoint: string
29
40
  has(category: string): boolean
30
41
  all(): Record<string, boolean>
31
42
  }
@@ -33,14 +44,19 @@ export interface RequestConsent {
33
44
  export interface NormalizedConsentConfig {
34
45
  readonly categories: readonly string[]
35
46
  readonly categorySet: ReadonlySet<string>
47
+ readonly labels: Readonly<Record<string, string>>
36
48
  readonly cookieName: string
37
49
  readonly maxAge: number
38
50
  readonly endpoint: string
51
+ readonly version: string
39
52
  }
40
53
 
41
54
  const EMPTY_CONSENT: RequestConsent = {
42
55
  decided: false,
56
+ decidedAt: undefined,
43
57
  categories: [],
58
+ labels: {},
59
+ endpoint: DEFAULT_CONSENT_ENDPOINT,
44
60
  has: category => category === 'essential',
45
61
  all: () => ({}),
46
62
  }
@@ -49,8 +65,10 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
49
65
  if (config === undefined)
50
66
  return undefined
51
67
  const rawList = Array.isArray(config.categories) ? config.categories : Object.keys(config.categories)
68
+ const given: Readonly<Record<string, string>> = Array.isArray(config.categories) ? {} : config.categories as Readonly<Record<string, string>>
52
69
  const categories: string[] = []
53
70
  const categorySet = new Set<string>()
71
+ const labels: Record<string, string> = {}
54
72
  for (const item of rawList) {
55
73
  const name = item.trim()
56
74
  if (name === '' || name === 'essential' || categorySet.has(name))
@@ -59,49 +77,67 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
59
77
  throw new Error(`prunelle: consent category "${name}" cannot contain "," or ":"`)
60
78
  categorySet.add(name)
61
79
  categories.push(name)
80
+ labels[name] = given[item]?.trim() || name
62
81
  }
82
+ const version = config.version?.trim() ?? ''
83
+ if (version !== '' && !POLICY_VERSION_RE.test(version))
84
+ throw new Error(`prunelle: consent version "${config.version}" must be 1 to 32 letters, digits, ".", "-" or "_", such as '2026-11' or '3'`)
63
85
  const rawEndpoint = (config.endpoint ?? DEFAULT_CONSENT_ENDPOINT).trim()
64
86
  const endpoint = rawEndpoint.startsWith('/') ? rawEndpoint : `/${rawEndpoint}`
65
87
  return {
66
88
  categories,
67
89
  categorySet,
90
+ labels,
68
91
  cookieName: config.cookieName ?? DEFAULT_CONSENT_COOKIE,
69
92
  maxAge: config.maxAge ?? DEFAULT_CONSENT_MAX_AGE,
70
93
  endpoint,
94
+ version,
71
95
  }
72
96
  }
73
97
 
74
- export function parseConsentCookie(raw: string | undefined, declared: ReadonlySet<string>): { decided: boolean, granted: Set<string> } {
98
+ interface ParsedConsent { decided: boolean, decidedAt: Date | undefined, granted: Set<string> }
99
+
100
+ function grantedOf(list: string, declared: ReadonlySet<string>): Set<string> {
75
101
  const granted = new Set<string>()
76
- if (raw === undefined || !raw.startsWith(COOKIE_VERSION_PREFIX))
77
- return { decided: false, granted }
78
- const payload = raw.slice(COOKIE_VERSION_PREFIX.length)
79
- if (payload !== '') {
80
- for (const part of payload.split(',')) {
81
- const cat = part.trim()
82
- if (declared.has(cat))
83
- granted.add(cat)
84
- }
102
+ for (const part of list.split(',')) {
103
+ const cat = part.trim()
104
+ if (declared.has(cat))
105
+ granted.add(cat)
85
106
  }
86
- return { decided: true, granted }
107
+ return granted
87
108
  }
88
109
 
89
- export function serializeConsentCookie(granted: ReadonlySet<string>, declared: readonly string[]): string {
90
- const ordered: string[] = []
91
- for (const cat of declared) {
92
- if (granted.has(cat))
93
- ordered.push(cat)
94
- }
95
- return `${COOKIE_VERSION_PREFIX}${ordered.join(',')}`
110
+ /** Reads `v2:<seconds>:<policy version>:<categories>`; a choice made under another policy version counts as no choice. */
111
+ export function parseConsentCookie(raw: string | undefined, declared: ReadonlySet<string>, version = ''): ParsedConsent {
112
+ const none: ParsedConsent = { decided: false, decidedAt: undefined, granted: new Set() }
113
+ if (raw === undefined)
114
+ return none
115
+ if (raw.startsWith(LEGACY_COOKIE_PREFIX))
116
+ return version === '' ? { decided: true, decidedAt: undefined, granted: grantedOf(raw.slice(LEGACY_COOKIE_PREFIX.length), declared) } : none
117
+ if (!raw.startsWith(COOKIE_PREFIX))
118
+ return none
119
+ const [seconds, storedVersion, list] = raw.slice(COOKIE_PREFIX.length).split(':')
120
+ const at = Number(seconds)
121
+ if (list === undefined || storedVersion !== version || !Number.isSafeInteger(at) || at <= 0)
122
+ return none
123
+ return { decided: true, decidedAt: new Date(at * 1000), granted: grantedOf(list, declared) }
124
+ }
125
+
126
+ export function serializeConsentCookie(granted: ReadonlySet<string>, declared: readonly string[], version = '', decidedAt = new Date()): string {
127
+ const ordered = declared.filter(cat => granted.has(cat))
128
+ return `${COOKIE_PREFIX}${Math.floor(decidedAt.getTime() / 1000)}:${version}:${ordered.join(',')}`
96
129
  }
97
130
 
98
131
  export function createRequestConsent(rawCookie: string | undefined, config: NormalizedConsentConfig | undefined): RequestConsent {
99
132
  if (config === undefined)
100
133
  return EMPTY_CONSENT
101
- const { decided, granted } = parseConsentCookie(rawCookie, config.categorySet)
134
+ const { decided, decidedAt, granted } = parseConsentCookie(rawCookie, config.categorySet, config.version)
102
135
  return {
103
136
  decided,
137
+ decidedAt,
104
138
  categories: config.categories,
139
+ labels: config.labels,
140
+ endpoint: config.endpoint,
105
141
  has(category: string): boolean {
106
142
  return category === 'essential' || granted.has(category)
107
143
  },
@@ -232,7 +268,7 @@ export function registerConsentRoute(
232
268
  if (!parsed.ok)
233
269
  return ctx.deny(400, parsed.error)
234
270
 
235
- const cookieVal = serializeConsentCookie(parsed.granted, config.categories)
271
+ const cookieVal = serializeConsentCookie(parsed.granted, config.categories, config.version)
236
272
  ctx.cookies.set(config.cookieName, cookieVal, {
237
273
  httpOnly: true,
238
274
  sameSite: 'lax',
@@ -248,6 +284,7 @@ export function registerConsentRoute(
248
284
  return ctx.json({ ok: true, decided: true, consent })
249
285
  }
250
286
  const target = resolveConsentRedirect(ctx.request, ctx.url, parsed.redirect, trustedOrigins, trustProxy)
251
- return ctx.redirect(target, 303)
287
+ // resolveConsentRedirect only returns this site or a trusted origin.
288
+ return ctx.redirect(target, 303, { external: true })
252
289
  }, { csrf: true })
253
290
  }
@@ -1,5 +1,7 @@
1
1
  // Typed cookie jar for RequestContext (lazy Cookie header parsing, validated & deduplicated Set-Cookie serialization).
2
2
 
3
+ import { getAppContext } from '../plugins/context'
4
+
3
5
  export interface CookieOptions {
4
6
  path?: string | undefined
5
7
  domain?: string | undefined
@@ -8,10 +10,20 @@ export interface CookieOptions {
8
10
  httpOnly?: boolean | undefined
9
11
  secure?: boolean | undefined
10
12
  sameSite?: 'strict' | 'lax' | 'none' | undefined
11
- /** Consent category required before setting this cookie (omit or `'essential'` for strictly necessary cookies). */
13
+ /** 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. */
12
14
  category?: string | undefined
13
15
  }
14
16
 
17
+ const warnedUncategorized = new Set<string>()
18
+
19
+ // Once per cookie name and process, in dev only: production has no one to read it.
20
+ function warnUncategorized(name: string): void {
21
+ if (warnedUncategorized.has(name) || getAppContext()?.dev !== true)
22
+ return
23
+ warnedUncategorized.add(name)
24
+ 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
+ }
26
+
15
27
  export interface Cookies {
16
28
  get(name: string): string | undefined
17
29
  set(name: string, value: string, options?: CookieOptions): void
@@ -110,7 +122,9 @@ export class CookieStore implements Cookies {
110
122
  }
111
123
 
112
124
  set(name: string, value: string, options?: CookieOptions): void {
113
- if (options?.category !== undefined && options.category !== 'essential') {
125
+ if (options?.category === undefined)
126
+ warnUncategorized(name)
127
+ else if (options.category !== 'essential') {
114
128
  if (this.#isConsentGranted === undefined || !this.#isConsentGranted(options.category))
115
129
  return
116
130
  }
package/src/server/env.ts CHANGED
@@ -11,6 +11,20 @@ export function nodeEnv(): string | undefined {
11
11
  return getAppContext()?.nodeEnv ?? process.env[NODE_ENV_KEY]
12
12
  }
13
13
 
14
+ const DEV_KEY = 'PRUNELLE_DEV'
15
+ // A compiled binary runs its entry from Bun's embedded filesystem.
16
+ const BINARY_MAIN_RE = /^\/\$bunfs\//
17
+
18
+ /** Whether `PRUNELLE_DEV=1` asks for dev mode where the caller did not say; it throws under NODE_ENV=production and inside a compiled binary, where the dev-only routes would reach visitors. */
19
+ export function devFromEnv(): boolean {
20
+ if (process.env[DEV_KEY] !== '1')
21
+ return false
22
+ const where = BINARY_MAIN_RE.test(Bun.main) ? 'inside a compiled binary' : nodeEnv() === 'production' ? 'with NODE_ENV=production' : undefined
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.`)
25
+ return true
26
+ }
27
+
14
28
  export function defineEnv<S extends StandardSchemaV1>(
15
29
  schema: S,
16
30
  source: Record<string, string | undefined> = process.env,
@@ -321,10 +321,12 @@ export function createFallbackPages(options: FallbackPagesOptions) {
321
321
  const found = lookup.find('error', effUrl, routeFile)
322
322
  if (found !== undefined) {
323
323
  const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
324
+ // Outside dev the page gets a bare error: a thrown message can name a host, a table or a credential, and it lands in HTML anyone can load.
325
+ const shown = options.dev ? error : Object.assign(new Error('Internal Server Error'), { stack: 'Error: Internal Server Error' })
324
326
  const rendered = await renderCompiledStatusPage(
325
327
  found.page,
326
328
  500,
327
- { error, status: 500, message: errorMessage(error), url: effUrl, params, locals: ctx?.locals ?? {} },
329
+ { error: shown, status: 500, message: errorMessage(shown), url: effUrl, params, locals: ctx?.locals ?? {} },
328
330
  effUrl,
329
331
  params,
330
332
  req,
@@ -42,7 +42,7 @@ const SAFE_INT_MIN = Number.MIN_SAFE_INTEGER
42
42
  const SAFE_INT_MAX = Number.MAX_SAFE_INTEGER
43
43
  const schemaCache = new WeakMap<StandardSchemaV1, ExtractedFormSchema>()
44
44
 
45
- function isRecord(value: unknown): value is Record<string, unknown> {
45
+ export function isRecord(value: unknown): value is Record<string, unknown> {
46
46
  return value !== null && typeof value === 'object' && !Array.isArray(value)
47
47
  }
48
48
 
@@ -177,9 +177,13 @@ export function collectHealthChecks(
177
177
  return entries
178
178
  }
179
179
 
180
- async function runSingleHealthCheck(entry: HealthCheckEntry): Promise<[string, HealthCheckOutcome]> {
180
+ async function runSingleHealthCheck(entry: HealthCheckEntry, timeoutMs: number, exposeErrors: boolean): Promise<[string, HealthCheckOutcome]> {
181
+ let timer: ReturnType<typeof setTimeout> | undefined
181
182
  try {
182
- const result = await entry.fn()
183
+ const result = await Promise.race([
184
+ entry.fn(),
185
+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs} ms`)), timeoutMs) }),
186
+ ])
183
187
  if (result === true || result === undefined)
184
188
  return [entry.name, { ok: true }]
185
189
  if (result === false)
@@ -189,8 +193,20 @@ async function runSingleHealthCheck(entry: HealthCheckEntry): Promise<[string, H
189
193
  return [entry.name, result.message !== undefined ? { ok: false, error: result.message } : { ok: false }]
190
194
  }
191
195
  catch (err) {
192
- return [entry.name, { ok: false, error: err instanceof Error ? err.message : String(err) }]
196
+ // What a check threw can name a host, a table or a credential: the log keeps it, the answer says only that the check failed (outside dev).
197
+ console.error(`prunelle: health check "${entry.name}" failed: ${err instanceof Error ? err.message : String(err)}`)
198
+ return [entry.name, { ok: false, error: exposeErrors ? (err instanceof Error ? err.message : String(err)) : 'check failed' }]
193
199
  }
200
+ finally {
201
+ clearTimeout(timer)
202
+ }
203
+ }
204
+
205
+ interface HealthSnapshot {
206
+ at: number
207
+ status: number
208
+ payload: string
209
+ length: string
194
210
  }
195
211
 
196
212
  export interface HealthHandlerOptions {
@@ -198,11 +214,17 @@ export interface HealthHandlerOptions {
198
214
  securityRecord: Record<string, string>
199
215
  withHsts: (res: Response, request: Request) => Response
200
216
  resolveRequestId: RequestIdResolver
217
+ /** Send what a check threw back to the caller (`prunelle dev`); by default the answer only says `check failed`. */
218
+ exposeErrors?: boolean | undefined
219
+ /** How long one answer is reused (default 5000 ms), so a probe loop or a flood runs the checks once per window. */
220
+ cacheMs?: number | undefined
221
+ /** How long one check may take (default 5000 ms) before it counts as failed. */
222
+ timeoutMs?: number | undefined
201
223
  }
202
224
 
203
225
  /** Handles `GET`/`HEAD` requests to `${assetPrefix}/health`, returning 200 when healthy and 503 if any check fails. */
204
226
  export function createHealthHandler(options: HealthHandlerOptions): (request: Request, requestId?: string) => Response | Promise<Response> {
205
- const { checks, securityRecord, withHsts, resolveRequestId } = options
227
+ const { checks, securityRecord, withHsts, resolveRequestId, exposeErrors = false, cacheMs = 5000, timeoutMs = 5000 } = options
206
228
  const baseHeaders: Record<string, string> = {
207
229
  'content-type': 'application/json; charset=utf-8',
208
230
  'cache-control': 'no-store',
@@ -217,6 +239,22 @@ export function createHealthHandler(options: HealthHandlerOptions): (request: Re
217
239
  return withHsts(res, request)
218
240
  }
219
241
 
242
+ let cached: HealthSnapshot | undefined
243
+ let inflight: Promise<HealthSnapshot> | undefined
244
+ const evaluate = async (): Promise<HealthSnapshot> => {
245
+ const results = await Promise.all(checks.map(entry => runSingleHealthCheck(entry, timeoutMs, exposeErrors)))
246
+ const checkMap: Record<string, HealthCheckOutcome> = {}
247
+ let allOk = true
248
+ for (const [name, outcome] of results) {
249
+ checkMap[name] = outcome
250
+ if (!outcome.ok)
251
+ allOk = false
252
+ }
253
+ const payload = JSON.stringify({ ok: allOk, checks: checkMap })
254
+ cached = { at: Date.now(), status: allOk ? 200 : 503, payload, length: String(Buffer.byteLength(payload, 'utf8')) }
255
+ return cached
256
+ }
257
+
220
258
  return (request: Request, requestId?: string): Response | Promise<Response> => {
221
259
  const reqId = requestId ?? resolveRequestId(request)
222
260
  if (request.method !== 'GET' && request.method !== 'HEAD') {
@@ -229,16 +267,9 @@ export function createHealthHandler(options: HealthHandlerOptions): (request: Re
229
267
  if (checks.length === 0)
230
268
  return jsonReply(request, 200, okPayload, okLength, reqId)
231
269
 
232
- return Promise.all(checks.map(runSingleHealthCheck)).then((results) => {
233
- const checkMap: Record<string, HealthCheckOutcome> = {}
234
- let allOk = true
235
- for (const [name, outcome] of results) {
236
- checkMap[name] = outcome
237
- if (!outcome.ok)
238
- allOk = false
239
- }
240
- const payload = JSON.stringify({ ok: allOk, checks: checkMap })
241
- return jsonReply(request, allOk ? 200 : 503, payload, String(Buffer.byteLength(payload, 'utf8')), reqId)
242
- })
270
+ if (cached !== undefined && Date.now() - cached.at < cacheMs)
271
+ return jsonReply(request, cached.status, cached.payload, cached.length, reqId)
272
+ inflight ??= evaluate().finally(() => { inflight = undefined })
273
+ return inflight.then(snap => jsonReply(request, snap.status, snap.payload, snap.length, reqId))
243
274
  }
244
275
  }
@@ -12,7 +12,8 @@ import { CookieStore } from './cookies'
12
12
  import { nodeEnv } from './env'
13
13
  import { resolveFallbackRequestId } from './health'
14
14
  import { requestedRegion } from './region'
15
- import { getClientIp, isHttpsRequest } from './security'
15
+ import { GATED_ROUTE_CACHE_CONTROL } from './route-cache'
16
+ import { expectedOrigin, getClientIp, isHttpsRequest } from './security'
16
17
 
17
18
  export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
18
19
 
@@ -126,6 +127,8 @@ export interface ServerOptions extends ServerRuntimeConfig {
126
127
  outDir?: string | undefined
127
128
  port?: number | undefined
128
129
  dev?: boolean | undefined
130
+ /** @internal The address `prunelle dev` binds, from which plugins get `api.devExposed`. */
131
+ devHost?: string | undefined
129
132
  nodeEnv?: string | undefined
130
133
  /** @internal Imports a built server module by absolute path; `prunelle dev` passes one that keeps unchanged modules loaded. */
131
134
  importModule?: ((path: string) => Promise<Record<string, unknown>>) | undefined
@@ -151,7 +154,8 @@ export interface RequestContext<Params = Record<string, string>> {
151
154
  readonly region?: string | undefined
152
155
  json: (data: unknown, init?: ResponseInit) => Response
153
156
  text: (body: string, init?: ResponseInit) => Response
154
- redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
157
+ /** A redirect to a path or a URL of this site; one to another site throws unless `{ external: true }` says the app chose that target (never one read from the request). */
158
+ redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308, options?: RedirectOptions) => Response
155
159
  deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
156
160
  }
157
161
 
@@ -171,6 +175,8 @@ export interface PrunelleApp {
171
175
  inject?: <T>(key: ServiceKey<T>) => T | undefined
172
176
  /** Closes active long-lived streams (such as SSE) before `server.stop()` drains normal in-flight HTTP requests. */
173
177
  closeStreams?: () => Promise<void>
178
+ /** @internal The security headers each response of this app carries, which the 503 of a build swap in `prunelle start` repeats. */
179
+ securityHeaders?: Readonly<Record<string, string>> | undefined
174
180
  /** Runs plugin shutdown hooks and releases timers/resources (safe to call multiple times). */
175
181
  dispose?: () => Promise<void>
176
182
  }
@@ -191,6 +197,7 @@ export interface EmbeddedServerConfig extends ServerRuntimeConfig {
191
197
  outDir?: string | undefined
192
198
  publicDir?: string | undefined
193
199
  dev?: boolean | undefined
200
+ devHost?: string | undefined
194
201
  nodeEnv?: string | undefined
195
202
  errorSink?: ((info: ServerErrorInfo) => void) | undefined
196
203
  prerender?: boolean | undefined
@@ -248,6 +255,8 @@ export interface RequestContextOptions {
248
255
  url?: URL | undefined
249
256
  consent?: NormalizedConsentConfig | undefined
250
257
  requestId?: string | undefined
258
+ /** The app's `site` is https: cookies get `Secure` even when a proxy the server does not trust hides the scheme. */
259
+ httpsSite?: boolean | undefined
251
260
  }
252
261
 
253
262
  // None of these read the request, so every context shares them.
@@ -281,7 +290,44 @@ export function getDeniedInfo(res: Response): DeniedInfo | undefined {
281
290
  return DENIED_RESPONSES.get(res)
282
291
  }
283
292
 
284
- const redirect: RequestContext['redirect'] = (location, status = 302) => new Response(null, { status, headers: { location } })
293
+ export interface RedirectOptions {
294
+ /** Allows a target on another site: a payment page, an identity provider, a redirect rule the app wrote itself. */
295
+ external?: boolean | undefined
296
+ }
297
+
298
+ const EXTERNAL_REDIRECTS = new WeakSet<Response>()
299
+
300
+ /** Whether `res` came from `ctx.redirect(url, status, { external: true })`: the one kind of cross-site redirect an island's action call follows. */
301
+ export function isExternalRedirect(res: Response): boolean {
302
+ return EXTERNAL_REDIRECTS.has(res)
303
+ }
304
+
305
+ const REDIRECT_CONTROL_CHAR_RE = /[\u0000-\u001F\u007F]/
306
+ const NON_HIERARCHICAL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:(?!\/\/)/i
307
+
308
+ function sameOrigin(location: string, baseOrigin: string): boolean {
309
+ if (baseOrigin === 'null' || REDIRECT_CONTROL_CHAR_RE.test(location) || NON_HIERARCHICAL_SCHEME_RE.test(location.trimStart()))
310
+ return false
311
+ try {
312
+ return new URL(location, baseOrigin).origin === baseOrigin
313
+ }
314
+ catch {
315
+ return false
316
+ }
317
+ }
318
+
319
+ const makeRedirect = (request: Request, trustProxy: TrustProxy, url: URL): RequestContext['redirect'] => (location, status = 302, options) => {
320
+ const external = options?.external === true
321
+ if (!external) {
322
+ const baseOrigin = expectedOrigin(request, trustProxy, url)
323
+ if (!sameOrigin(location, baseOrigin))
324
+ throw new Error(`prunelle: ctx.redirect("${location}") leaves ${baseOrigin}: redirect to a path of this site, or pass { external: true } as the third argument when the app chose that address itself (never one read from the request, which makes an open redirect).`)
325
+ }
326
+ const res = new Response(null, { status, headers: { location } })
327
+ if (external)
328
+ EXTERNAL_REDIRECTS.add(res)
329
+ return res
330
+ }
285
331
  const deny: RequestContext['deny'] = (status, message, fieldErrors) => {
286
332
  const res = Response.json({ ok: false, status, error: message, fieldErrors }, { status })
287
333
  DENIED_RESPONSES.set(res, { status, message, fieldErrors })
@@ -316,7 +362,7 @@ export function makeRequestContext(
316
362
  let cachedConsentRaw: string | undefined
317
363
  const cookieStore = new CookieStore(
318
364
  request.headers.get('cookie'),
319
- isHttpsRequest(request, trustProxy),
365
+ opts?.httpsSite === true || isHttpsRequest(request, trustProxy),
320
366
  category => getConsent().has(category),
321
367
  )
322
368
  const getConsent = (): RequestConsent => {
@@ -330,9 +376,10 @@ export function makeRequestContext(
330
376
  const requestId = opts?.requestId ?? resolveFallbackRequestId(request, trustProxy)
331
377
  let cachedIp: string | undefined
332
378
  let ipComputed = false
379
+ const url = opts?.url ?? new URL(request.url)
333
380
  const ctx: RequestContext = {
334
381
  request,
335
- url: opts?.url ?? new URL(request.url),
382
+ url,
336
383
  params,
337
384
  cookies: cookieStore,
338
385
  get consent() {
@@ -356,7 +403,7 @@ export function makeRequestContext(
356
403
  },
357
404
  json,
358
405
  text,
359
- redirect,
406
+ redirect: makeRedirect(request, trustProxy, url),
360
407
  deny,
361
408
  }
362
409
  return { ctx, cookieStore }
@@ -464,8 +511,9 @@ export function applyHstsHeader(
464
511
  trustProxy: TrustProxy,
465
512
  isDev = false,
466
513
  resolvedEnv?: string,
514
+ httpsSite = false,
467
515
  ): Response {
468
- if (hstsValue === undefined || isDev || !isHttpsRequest(request, trustProxy))
516
+ if (hstsValue === undefined || isDev || !(httpsSite || isHttpsRequest(request, trustProxy)))
469
517
  return res
470
518
  const env = resolvedEnv ?? nodeEnv()
471
519
  if (env === 'development' || env === 'test')
@@ -501,7 +549,7 @@ export function finalizeResponse(
501
549
  if (hasCookies) {
502
550
  cookieStore!.applyTo(h)
503
551
  const cc = h.get('cache-control')
504
- if (cc !== null && PUBLIC_CACHE_RE.test(cc))
552
+ if (cc !== null && (PUBLIC_CACHE_RE.test(cc) || cc === GATED_ROUTE_CACHE_CONTROL))
505
553
  h.set('cache-control', 'private, no-store')
506
554
  }
507
555
  for (const [k, v] of entries) {