prunelle 0.7.2 → 0.7.4

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.
@@ -20,10 +20,14 @@ import { styleHashesOf } from './security'
20
20
 
21
21
  export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source'], requestId?: string) => void
22
22
 
23
+ const describeNonError = (error: unknown): string => error instanceof Response
24
+ ? `prunelle: a Response (HTTP ${error.status}) was thrown instead of returned; return it from load() or the route handler instead.`
25
+ : String(error)
26
+
23
27
  /** The text of an error a dev response shows: its stack, which starts with its message. */
24
- export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : String(error)
28
+ export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : describeNonError(error)
25
29
 
26
- const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error)
30
+ const errorMessage = (error: unknown): string => error instanceof Error ? error.message : describeNonError(error)
27
31
 
28
32
  const HTML_ESCAPE_RE = /[&<>"']/g
29
33
  const HTML_ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
@@ -57,11 +61,14 @@ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) |
57
61
  errorHooks.push({ owner: p.name, hook: p.onError })
58
62
  }
59
63
  return (error, request, source, requestId) => {
60
- const info: ServerErrorInfo = requestId !== undefined ? { error, request, source, requestId } : { error, request, source }
64
+ const normalized = error instanceof Response
65
+ ? (void error.body?.cancel().catch(() => undefined), new Error(describeNonError(error)))
66
+ : error
67
+ const info: ServerErrorInfo = requestId !== undefined ? { error: normalized, request, source, requestId } : { error: normalized, request, source }
61
68
  options.sink?.(info)
62
69
  if (errorHooks.length === 0 && (options.dev === true || options.sink === undefined)) {
63
70
  const idSuffix = requestId !== undefined ? ` [${requestId}]` : ''
64
- console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, error)
71
+ console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, normalized)
65
72
  }
66
73
  for (const { owner, hook } of errorHooks) {
67
74
  try {
@@ -89,8 +96,13 @@ interface CompiledStatusPage {
89
96
  doc: DocumentOptions
90
97
  }
91
98
 
99
+ interface StatusPageHit {
100
+ page: CompiledStatusPage
101
+ params?: Record<string, string>
102
+ }
103
+
92
104
  interface StatusPageLookup {
93
- find: (kind: StatusPageKind, url?: URL, routeFile?: string) => { page: CompiledStatusPage, params?: Record<string, string> } | undefined
105
+ findAll: (kind: StatusPageKind, url?: URL, routeFile?: string) => StatusPageHit[]
94
106
  }
95
107
 
96
108
  function dirnamePrefix(file: string): string {
@@ -184,7 +196,16 @@ function buildStatusPageLookup(
184
196
  }
185
197
 
186
198
  return {
187
- find(kind, url, routeFile) {
199
+ findAll(kind, url, routeFile) {
200
+ const out: StatusPageHit[] = []
201
+ const seen = new Set<CompiledStatusPage>()
202
+ const push = (page: CompiledStatusPage, params?: Record<string, string>) => {
203
+ if (seen.has(page))
204
+ return
205
+ seen.add(page)
206
+ out.push(params !== undefined ? { page, params } : { page })
207
+ }
208
+
188
209
  if (routeFile !== undefined) {
189
210
  const dirMap = byDirPrefix.get(kind)
190
211
  if (dirMap !== undefined) {
@@ -192,27 +213,27 @@ function buildStatusPageLookup(
192
213
  while (dir !== undefined) {
193
214
  const hit = dirMap.get(dir)
194
215
  if (hit !== undefined)
195
- return { page: hit }
216
+ push(hit)
196
217
  if (dir === routesPrefix || !dir.startsWith(routesPrefix))
197
218
  break
198
219
  dir = parentDirPrefix(dir)
199
220
  }
200
221
  const rootHit = dirMap.get(routesPrefix)
201
222
  if (rootHit !== undefined)
202
- return { page: rootHit }
223
+ push(rootHit)
203
224
  }
204
- return undefined
225
+ return out
205
226
  }
206
227
 
207
228
  const decoded = decodeRequestPath(url?.pathname ?? '/')
208
229
  if (decoded === undefined)
209
- return undefined
230
+ return out
210
231
  const urlRouter = byUrlRouter.get(kind)
211
232
  if (urlRouter !== undefined) {
212
233
  for (let i = decoded.segments.length; i >= 0; i--) {
213
234
  const matched = urlRouter.match(pathPrefix(decoded, i))
214
235
  if (matched !== undefined)
215
- return { page: matched.data, params: matched.params }
236
+ push(matched.data, matched.params)
216
237
  }
217
238
  }
218
239
  const fallbackGroup = groupUrlRouter.get(kind)
@@ -220,10 +241,10 @@ function buildStatusPageLookup(
220
241
  for (let i = decoded.segments.length; i >= 0; i--) {
221
242
  const matched = fallbackGroup.match(pathPrefix(decoded, i))
222
243
  if (matched !== undefined)
223
- return { page: matched.data, params: matched.params }
244
+ push(matched.data, matched.params)
224
245
  }
225
246
  }
226
- return undefined
247
+ return out
227
248
  },
228
249
  }
229
250
  }
@@ -321,11 +342,11 @@ export function createFallbackPages(options: FallbackPagesOptions) {
321
342
 
322
343
  async function buildErrorResponse(error: unknown, url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
323
344
  const effUrl = url ?? new URL('http://localhost/500')
324
- const found = lookup.find('error', effUrl, routeFile)
325
- if (found !== undefined) {
345
+ const candidates = lookup.findAll('error', effUrl, routeFile)
346
+ // 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.
347
+ const shown = options.dev ? error : Object.assign(new Error('Internal Server Error'), { stack: 'Error: Internal Server Error' })
348
+ for (const found of candidates) {
326
349
  const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
327
- // 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.
328
- const shown = options.dev ? error : Object.assign(new Error('Internal Server Error'), { stack: 'Error: Internal Server Error' })
329
350
  const rendered = await renderCompiledStatusPage(
330
351
  found.page,
331
352
  500,
@@ -338,13 +359,19 @@ export function createFallbackPages(options: FallbackPagesOptions) {
338
359
  if (rendered !== undefined)
339
360
  return rendered
340
361
  }
341
- return new Response(req?.method === 'HEAD' ? null : (options.dev ? errorDetail(error) : 'Internal Server Error'), { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
362
+ const text = options.dev ? errorDetail(error) : 'Internal Server Error'
363
+ if (candidates.length > 0) {
364
+ return new Response(req?.method === 'HEAD' ? null : minimalStatusHtml(500, text, options.lang), {
365
+ status: 500,
366
+ headers: htmlHeaders(false, false, true, fallbackHeadStyleHashes),
367
+ })
368
+ }
369
+ return new Response(req?.method === 'HEAD' ? null : text, { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
342
370
  }
343
371
 
344
372
  async function buildNotFoundResponse(url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
345
373
  const effUrl = url ?? new URL('http://localhost/404')
346
- const found = lookup.find('404', effUrl, routeFile)
347
- if (found !== undefined) {
374
+ for (const found of lookup.findAll('404', effUrl, routeFile)) {
348
375
  const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
349
376
  const rendered = await renderCompiledStatusPage(
350
377
  found.page,
@@ -363,13 +390,17 @@ export function createFallbackPages(options: FallbackPagesOptions) {
363
390
 
364
391
  async function renderDenied(denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
365
392
  const statusKey = String(denied.status)
366
- const statusHit = STATUS_KINDS.has(statusKey) ? lookup.find(statusKey as StatusPageKind, url, routeFile) : undefined
367
- const found = statusHit ?? lookup.find('error', url, routeFile)
368
- if (found !== undefined) {
393
+ const statusHits = STATUS_KINDS.has(statusKey) ? lookup.findAll(statusKey as StatusPageKind, url, routeFile) : []
394
+ for (const found of statusHits) {
395
+ const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
396
+ const props = { status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
397
+ const rendered = await renderCompiledStatusPage(found.page, denied.status, props, url, params, req, ctx)
398
+ if (rendered !== undefined)
399
+ return rendered
400
+ }
401
+ for (const found of lookup.findAll('error', url, routeFile)) {
369
402
  const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
370
- const props = statusHit !== undefined
371
- ? { status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
372
- : { error: new Error(denied.message), status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
403
+ const props = { error: new Error(denied.message), status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
373
404
  const rendered = await renderCompiledStatusPage(found.page, denied.status, props, url, params, req, ctx)
374
405
  if (rendered !== undefined)
375
406
  return rendered
@@ -158,25 +158,49 @@ const warnedMissingIp = new WeakSet<object>()
158
158
 
159
159
  const BRACKETED_RE = /^\[([^\]]+)\](?::\d+)?$/
160
160
  const IPV4_PORT_RE = /^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/
161
- const MAPPED_IPV4_RE = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i
161
+ const IPV4_RE = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/
162
162
  const HEXTET_RE = /^[\da-f]{1,4}$/i
163
163
 
164
+ function parseIpv6Groups(parts: readonly string[], allowDottedLast: boolean): number[] | undefined {
165
+ const out: number[] = []
166
+ for (let i = 0; i < parts.length; i++) {
167
+ const part = parts[i]!
168
+ if (allowDottedLast && i === parts.length - 1 && part.includes('.')) {
169
+ const m = IPV4_RE.exec(part)
170
+ if (m === null)
171
+ return undefined
172
+ const octets = [Number(m[1]), Number(m[2]), Number(m[3]), Number(m[4])]
173
+ if (octets.some(o => o > 255))
174
+ return undefined
175
+ out.push((octets[0]! << 8) | octets[1]!, (octets[2]! << 8) | octets[3]!)
176
+ continue
177
+ }
178
+ if (!HEXTET_RE.test(part))
179
+ return undefined
180
+ out.push(Number.parseInt(part, 16))
181
+ }
182
+ return out
183
+ }
184
+
164
185
  /** The address a rate limit counts: an IPv4 address without its port or its `::ffff:` mapping, or the /64 network of an IPv6 address, any of whose 2^64 addresses one host may use. */
165
186
  export function rateLimitAddress(ip: string): string {
166
187
  const bare = BRACKETED_RE.exec(ip)?.[1] ?? IPV4_PORT_RE.exec(ip)?.[1] ?? ip
167
- const addr = MAPPED_IPV4_RE.exec(bare)?.[1] ?? bare
188
+ const pct = bare.indexOf('%')
189
+ const addr = pct === -1 ? bare : bare.slice(0, pct)
168
190
  const halves = addr.split('::')
169
191
  if (!addr.includes(':') || halves.length > 2)
170
- return addr
171
- const head = halves[0] === '' ? [] : halves[0]!.split(':')
172
- const tail = halves[1] ? halves[1].split(':') : []
173
- // A dotted IPv4 ending holds the last two groups.
174
- const tailGroups = tail.length + (tail.at(-1)?.includes('.') === true ? 1 : 0)
175
- const zeros = halves.length === 2 ? 8 - head.length - tailGroups : 0
176
- const groups = [...head, ...Array.from({ length: Math.max(0, zeros) }, () => '0'), ...tail].slice(0, 4)
177
- if (groups.length < 4 || !groups.every(g => HEXTET_RE.test(g)))
178
- return addr
179
- return `${groups.map(g => Number.parseInt(g, 16).toString(16)).join(':')}::/64`
192
+ return bare
193
+ const head = parseIpv6Groups(halves[0] === '' ? [] : halves[0]!.split(':'), halves.length === 1)
194
+ const tail = parseIpv6Groups(halves[1] ? halves[1].split(':') : [], halves.length === 2)
195
+ if (head === undefined || tail === undefined)
196
+ return bare
197
+ const zeros = halves.length === 2 ? 8 - head.length - tail.length : 0
198
+ if (zeros < 0 || head.length + zeros + tail.length !== 8)
199
+ return bare
200
+ const full = [...head, ...Array.from({ length: zeros }, () => 0), ...tail]
201
+ if (full[0] === 0 && full[1] === 0 && full[2] === 0 && full[3] === 0 && full[4] === 0 && full[5] === 0xFFFF)
202
+ return `${full[6]! >> 8}.${full[6]! & 0xFF}.${full[7]! >> 8}.${full[7]! & 0xFF}`
203
+ return `${full.slice(0, 4).map(g => g.toString(16)).join(':')}::/64`
180
204
  }
181
205
 
182
206
  /** The key `limit` counts `ctx` under: the limit's own `key`, else the client's network (`rateLimitAddress`), else one shared fallback that warns in production. */
@@ -356,19 +356,18 @@ export class RouteCache {
356
356
  headers.age = age
357
357
  if (serverTiming !== undefined)
358
358
  headers['server-timing'] = serverTiming
359
+ if (compressCache !== undefined)
360
+ headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
359
361
  if (etagMatches(request.headers.get('if-none-match'), headers.etag!))
360
362
  return markCompressionHandled(new Response(null, { status: 304, headers }))
361
363
 
362
- if (compressCache !== undefined) {
363
- headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
364
- if (request.method !== 'HEAD') {
365
- const enc = pickEncoding(request.headers.get('accept-encoding'))
366
- if (enc !== undefined) {
367
- const compressed = this.#getOrCompress(entry, html, enc)
368
- if (compressed !== null) {
369
- headers['content-encoding'] = enc
370
- return markCompressionHandled(new Response(compressed, { status: 200, headers }))
371
- }
364
+ if (compressCache !== undefined && request.method !== 'HEAD') {
365
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
366
+ if (enc !== undefined) {
367
+ const compressed = this.#getOrCompress(entry, html, enc)
368
+ if (compressed !== null) {
369
+ headers['content-encoding'] = enc
370
+ return markCompressionHandled(new Response(compressed, { status: 200, headers }))
372
371
  }
373
372
  }
374
373
  }
@@ -24,7 +24,7 @@ import { runWithAppContext } from '../plugins/index'
24
24
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
25
25
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
26
26
  import { ACTION_ERROR_COOKIE, hydrateActionErrorFlash } from './action'
27
- import { compressedHtmlResponse, compressedHtmlStream, markCompressionHandled } from './compress'
27
+ import { compressedHtmlResponse, compressedHtmlStream, markCompressionHandled, mergeVaryValue } from './compress'
28
28
  import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
29
29
  import { endTimer, startTimer } from './health'
30
30
  import { isNotFound, makeRequestContext, runChain } from './http'
@@ -193,6 +193,7 @@ async function renderPageDocument(
193
193
  if (hasFlash)
194
194
  ctx.cookies.delete(ACTION_ERROR_COOKIE)
195
195
  const docHead = await deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
196
+ rctx.headFlushed = true
196
197
  const renderedIslands = resolveRenderedIslands(rctx, body)
197
198
  const isStreamed = rctx.pending.length > 0
198
199
  const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
@@ -206,7 +207,10 @@ async function renderPageDocument(
206
207
  if (ctx.request.method === 'HEAD') {
207
208
  rctx.aborted = true
208
209
  endTimer(timing, 'stream', streamStart)
209
- return { kind: 'stream', response: markCompressionHandled(new Response(null, { status: 200, headers: withRegionVary(deps.htmlHeaders(hasIslands, true, true, trustedStyleHashes), hasRegions) })) }
210
+ const headers = withRegionVary(deps.htmlHeaders(hasIslands, true, true, trustedStyleHashes), hasRegions)
211
+ if (deps.compressCache !== undefined)
212
+ headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
213
+ return { kind: 'stream', response: markCompressionHandled(new Response(null, { status: 200, headers })) }
210
214
  }
211
215
  disableTimeout?.()
212
216
  const docShell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
@@ -259,6 +263,10 @@ async function revalidateCompiledRoute(
259
263
  nonCacheable = true
260
264
  return new Response(null, { status: 404 })
261
265
  }
266
+ if (error instanceof Response) {
267
+ void error.body?.cancel().catch(() => undefined)
268
+ throw new Error(`prunelle: load() threw a Response (HTTP ${error.status}) instead of returning it; return the Response from load() instead.`)
269
+ }
262
270
  throw error
263
271
  }
264
272
  if (isNotFound(data) || data instanceof Response) {
@@ -298,6 +306,10 @@ async function runCompiledRouteLoad(
298
306
  catch (error) {
299
307
  if (isNotFound(error))
300
308
  return { kind: 'response', response: await deps.buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file) }
309
+ if (error instanceof Response) {
310
+ void error.body?.cancel().catch(() => undefined)
311
+ throw new Error(`prunelle: load() threw a Response (HTTP ${error.status}) instead of returning it; return the Response from load() instead.`)
312
+ }
301
313
  throw error
302
314
  }
303
315
  endTimer(timing, 'load', loadStart)
@@ -202,9 +202,9 @@ export class Router<T> {
202
202
  }
203
203
 
204
204
  const parts = path.segments
205
- // A param never receives a separator, a NUL or a dot segment, encoded or not: joined into a path, it would walk out of the folder it names.
206
- const dotSegment = (k: number): boolean => parts[k] === '.' || parts[k] === '..'
207
- const refused = (k: number): boolean => path.encoded?.has(k) === true || dotSegment(k)
205
+ // A param never receives an empty segment, a separator, a NUL or a dot segment, encoded or not: joined into a path, it would walk out of the folder it names.
206
+ const invalidSegment = (k: number): boolean => parts[k] === '' || parts[k] === '.' || parts[k] === '..'
207
+ const refused = (k: number): boolean => path.encoded?.has(k) === true || invalidSegment(k)
208
208
 
209
209
  for (let i = 0; i < dynLen; i++) {
210
210
  const route = this.#dynamicRoutes[i]!
@@ -220,7 +220,7 @@ export class Router<T> {
220
220
  const seg = segs[j]!
221
221
  if (seg.kind === SegmentKind.CatchAll) {
222
222
  for (let k = j; k < parts.length; k++) {
223
- if ((route.encodedSlashes ? dotSegment(k) : refused(k)) || !segmentMatchesParam(seg, parts[k]!)) {
223
+ if ((route.encodedSlashes ? invalidSegment(k) : refused(k)) || !segmentMatchesParam(seg, parts[k]!)) {
224
224
  matched = false
225
225
  break
226
226
  }
@@ -216,10 +216,13 @@ function findTagEndOffset(html: string, start: number): number {
216
216
  return -1
217
217
  }
218
218
 
219
+ const VOID_TAGS = new Set(['br', 'hr', 'img', 'source', 'col', 'wbr', 'input'])
220
+
219
221
  function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
220
222
  let out = ''
221
223
  let i = 0
222
224
  const len = html.length
225
+ const openStack: string[] = []
223
226
 
224
227
  while (i < len) {
225
228
  const lt = html.indexOf('<', i)
@@ -247,19 +250,23 @@ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
247
250
  if (isClosing)
248
251
  pos++
249
252
 
253
+ if (pos >= len || !/[A-Za-z]/.test(html[pos]!)) {
254
+ out += '&lt;'
255
+ i = lt + 1
256
+ continue
257
+ }
250
258
  const nameStart = pos
259
+ pos++
251
260
  while (pos < len && /[A-Za-z0-9:-]/.test(html[pos]!)) pos++
252
261
  const tagName = html.slice(nameStart, pos).toLowerCase()
253
- if (!tagName) {
262
+
263
+ const tagEnd = findTagEndOffset(html, pos)
264
+ if (tagEnd === -1) {
254
265
  out += '&lt;'
255
266
  i = lt + 1
256
267
  continue
257
268
  }
258
269
 
259
- const tagEnd = findTagEndOffset(html, pos)
260
- if (tagEnd === -1)
261
- break
262
-
263
270
  const attrSrc = html.slice(pos, tagEnd)
264
271
  const selfClosing = !isClosing && /\/\s*$/.test(attrSrc)
265
272
  i = tagEnd + 1
@@ -278,8 +285,13 @@ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
278
285
  continue
279
286
 
280
287
  if (isClosing) {
281
- if (tagName !== 'input' && tagName !== 'br' && tagName !== 'hr' && tagName !== 'img')
282
- out += `</${tagName}>`
288
+ if (VOID_TAGS.has(tagName))
289
+ continue
290
+ const openIdx = openStack.lastIndexOf(tagName)
291
+ if (openIdx === -1)
292
+ continue
293
+ openStack.length = openIdx
294
+ out += `</${tagName}>`
283
295
  continue
284
296
  }
285
297
 
@@ -291,6 +303,8 @@ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
291
303
 
292
304
  const safeParts = sanitizeAttributes(tagName, rawAttrs, slotPrefixes)
293
305
  const attrOut = safeParts.length > 0 ? ` ${safeParts.join(' ')}` : ''
306
+ if (!selfClosing && !VOID_TAGS.has(tagName))
307
+ openStack.push(tagName)
294
308
  out += selfClosing ? `<${tagName}${attrOut} />` : `<${tagName}${attrOut}>`
295
309
  }
296
310
 
@@ -402,18 +402,28 @@ export function getClientIp(request: Request, trustProxy: TrustProxy = false, re
402
402
  return remoteIp || undefined
403
403
  }
404
404
 
405
- /** `target` trimmed when it is a path on this site, else `fallback`: an absolute or protocol-relative URL, a backslash or a control character is refused. */
405
+ /** `target` trimmed when it is a path on this site, else `fallback`: an absolute or protocol-relative URL, a backslash or a control character is refused, and non-ASCII characters are percent-encoded. */
406
406
  export function safeRedirect(target: string | null | undefined, fallback = '/'): string {
407
407
  const path = target?.trim()
408
408
  if (path === undefined || !path.startsWith('/') || path.startsWith('//') || path.includes('\\'))
409
409
  return fallback
410
410
  // CR, LF and NUL split the Location header, and a browser drops a tab or newline from a URL, which turns `/\t/host` into `//host`.
411
+ let hasNonAscii = false
411
412
  for (let i = 0; i < path.length; i++) {
412
413
  const code = path.charCodeAt(i)
413
414
  if (code < 0x20 || code === 0x7F)
414
415
  return fallback
416
+ if (code > 0x7E)
417
+ hasNonAscii = true
418
+ }
419
+ if (!hasNonAscii)
420
+ return path
421
+ try {
422
+ return path.replace(/[^\x00-\x7F]+/g, chunk => encodeURI(chunk))
423
+ }
424
+ catch {
425
+ return fallback
415
426
  }
416
- return path
417
427
  }
418
428
 
419
429
  /** Returns true when `origin` matches the request's trusted forwarded origin (or direct origin when none is forwarded) or `trustedOrigins`. */
@@ -438,7 +448,7 @@ export function expectedOrigin(request: Request, trustProxy: TrustProxy, request
438
448
  function isSchemeMismatch(origin: string, expected: string): boolean {
439
449
  const seen = URL.parse(origin)
440
450
  const computed = URL.parse(expected)
441
- return seen !== null && computed !== null && computed.protocol === 'http:' && seen.host === computed.host
451
+ return seen !== null && computed !== null && seen.protocol === 'https:' && computed.protocol === 'http:' && seen.host === computed.host
442
452
  }
443
453
 
444
454
  /** What to log when a POST is refused: the two origins compared, and the config keys that settle it. */
@@ -11,23 +11,16 @@ import { extname, join, resolve } from 'node:path'
11
11
  import { isInside } from '../build/is-inside'
12
12
  import { resolvePlugins } from '../plugins/index'
13
13
  import { createNavigation, cspSha256 } from '../ssr/navigation'
14
+ import { staticMime } from './assets'
14
15
  import { CompressionCache, isCompressibleType } from './compress'
15
16
  import { createErrorNotifier } from './errors'
16
- import { applyHstsHeader, MIME } from './http'
17
+ import { applyHstsHeader } from './http'
17
18
  import { decodeRequestPath } from './request-path'
18
19
  import { buildSecurityHeaderEntries, inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
19
20
  import { createFileServer, servedFile } from './served-file'
20
21
 
21
22
  const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
22
23
 
23
- const EXTRA_STATIC_MIME: Record<string, string> = {
24
- '.htm': 'text/html; charset=utf-8',
25
- '.rss': 'application/rss+xml; charset=utf-8',
26
- '.atom': 'application/atom+xml; charset=utf-8',
27
- '.ics': 'text/calendar; charset=utf-8',
28
- '.csv': 'text/csv; charset=utf-8',
29
- }
30
-
31
24
  export interface StaticDirExtraOptions {
32
25
  navigation?: NavigationConfig | undefined
33
26
  plugins?: readonly PrunellePlugin[] | undefined
@@ -141,7 +134,7 @@ export function createStaticDirServer(
141
134
 
142
135
  function entryFor(rel: string, path: string, all: ReadonlyMap<string, string>): ServedFile {
143
136
  const ext = extname(rel).toLowerCase()
144
- const type = MIME[ext] ?? EXTRA_STATIC_MIME[ext] ?? 'application/octet-stream'
137
+ const type = staticMime(ext)
145
138
  const isHtml = ext === '.html' || ext === '.htm'
146
139
  // An exported page's CSP gains the hashes of its own `<style>` blocks.
147
140
  const csp = isHtml && htmlCsp !== undefined ? withCspHashes(htmlCsp, { styleHashes: inlineStyleHashes(readFileSync(path, 'utf8')) }) : undefined
@@ -37,7 +37,9 @@ export function renderConsentBanner(consent: RequestConsent | undefined, props:
37
37
  const body = props.children !== undefined
38
38
  ? ssrChild(props.children)
39
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>`
40
- const policy = props.policyHref !== undefined ? `<p><a href="${escAttr(props.policyHref)}">Cookie policy</a></p>` : ''
40
+ const policy = props.policyHref !== undefined
41
+ ? `<p><a href="${escAttr(props.policyHref)}">${esc(props.policyLabel ?? 'Cookie policy')}</a></p>`
42
+ : ''
41
43
  return `<section data-ui="consent" aria-labelledby="pru-consent-title">`
42
44
  + `<h2 id="pru-consent-title" data-part="title">${esc(props.title ?? 'Cookies')}</h2>`
43
45
  + `<div data-part="body">${body}${policy}</div>`
@@ -27,6 +27,7 @@ export interface PendingChunk {
27
27
 
28
28
  export interface RenderContext {
29
29
  headParts: string[]
30
+ headKeys: Set<string>
30
31
  title: string | undefined
31
32
  pending: PendingChunk[]
32
33
  nextId: number
@@ -58,8 +59,12 @@ export interface RenderContext {
58
59
  inlineStyles: string[] | undefined
59
60
  /** True once HTTP headers (and CSP) have been flushed for a streamed response. */
60
61
  headersFlushed: boolean
62
+ /** True once `<head>` has been collected for the document shell (subsequent `<Head>` calls in `<Suspense>` are dropped). */
63
+ headFlushed: boolean
61
64
  /** True once the post-flush inline `<style>` warning has been emitted for this request. */
62
65
  warnedStreamStyle: boolean
66
+ /** True once the post-flush `<Head>` warning has been emitted for this request. */
67
+ warnedStreamHead: boolean
63
68
  /** True once the stream/region finished, timed out, was aborted, or was discarded (e.g. HEAD). */
64
69
  aborted: boolean
65
70
  /** Request consent state used by `<ConsentGate>`, `<ConsentBanner>` and `<ConsentPreferences>`. */
@@ -76,6 +81,7 @@ interface RenderScope {
76
81
  outerContexts: ReadonlyMap<symbol, unknown> | undefined
77
82
  island: string | undefined
78
83
  inTarget: boolean
84
+ inSuspense?: boolean
79
85
  formFields: ReadonlyMap<string, FieldConstraint> | undefined
80
86
  }
81
87
 
@@ -207,6 +213,7 @@ export function createRenderContext(
207
213
  ): RenderContext {
208
214
  return {
209
215
  headParts: [],
216
+ headKeys: new Set(),
210
217
  title: undefined,
211
218
  pending: [],
212
219
  nextId: 0,
@@ -228,7 +235,9 @@ export function createRenderContext(
228
235
  inTarget: false,
229
236
  inlineStyles: undefined,
230
237
  headersFlushed: false,
238
+ headFlushed: false,
231
239
  warnedStreamStyle: false,
240
+ warnedStreamHead: false,
232
241
  aborted: false,
233
242
  consent,
234
243
  onCaught,
@@ -274,6 +283,53 @@ export function currentRenderContext(): RenderContext | undefined {
274
283
  }
275
284
 
276
285
  const TITLE_RE = /<title\b[^>]*>([\s\S]*?)<\/title>/gi
286
+ const HEAD_DEDUPE_TAG_RE = /<(meta|link)\b((?:"[^"]*"|'[^']*'|[^>"'])*)>/gi
287
+ const HEAD_ATTR_RE = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g
288
+
289
+ function headTagDedupeKey(tag: string, attrs: string): string | undefined {
290
+ let name = ''
291
+ let property = ''
292
+ let rel = ''
293
+ HEAD_ATTR_RE.lastIndex = 0
294
+ let m: RegExpExecArray | null
295
+ while ((m = HEAD_ATTR_RE.exec(attrs)) !== null) {
296
+ const attrName = m[1]!.toLowerCase()
297
+ const attrVal = (m[2] ?? m[3] ?? m[4] ?? '').trim().toLowerCase()
298
+ if (attrName === 'name')
299
+ name = attrVal
300
+ else if (attrName === 'property')
301
+ property = attrVal
302
+ else if (attrName === 'rel')
303
+ rel = attrVal
304
+ }
305
+ if (tag === 'meta') {
306
+ if (name === 'description' || name.startsWith('og:') || name.startsWith('twitter:'))
307
+ return `meta:${name}`
308
+ if (property.startsWith('og:') || property.startsWith('twitter:'))
309
+ return `meta:${property}`
310
+ return undefined
311
+ }
312
+ if (tag === 'link' && rel.split(/\s+/).includes('canonical'))
313
+ return 'link:canonical'
314
+ return undefined
315
+ }
316
+
317
+ function dedupeHeadTags(html: string, seen: Set<string>): string {
318
+ const added: string[] = []
319
+ HEAD_DEDUPE_TAG_RE.lastIndex = 0
320
+ const out = html.replace(HEAD_DEDUPE_TAG_RE, (full, rawTag: string, attrs: string) => {
321
+ const key = headTagDedupeKey(rawTag.toLowerCase(), attrs)
322
+ if (key === undefined)
323
+ return full
324
+ if (seen.has(key))
325
+ return ''
326
+ added.push(key)
327
+ return full
328
+ })
329
+ for (const key of added)
330
+ seen.add(key)
331
+ return out
332
+ }
277
333
 
278
334
  /** Renders `children`, or `fallback` when they throw or reject; the compiler hands it `children` as a getter, so they render inside the try. */
279
335
  export function Catch(props: CatchProps): Html | Promise<Html> {
@@ -312,12 +368,37 @@ export function ConsentPreferences(props: ConsentTexts): Html {
312
368
  return raw(renderConsentPreferences(renderStorage.getStore()?.consent, props))
313
369
  }
314
370
 
315
- /** Collects document <head> tags during SSR; innermost <title> wins. */
371
+ const STACK_FRAME_RE = /^\s*at\s+(?:async\s+)?([A-Za-z_$][\w$]*)\s+\(/
372
+ const INTERNAL_HEAD_FRAME_RE = /^(?:callerComponentName|Head\d*|head|ssrChild|settle|runWithRenderContext|run)$/
373
+
374
+ function callerComponentName(): string | undefined {
375
+ const stack = new Error().stack
376
+ if (stack === undefined)
377
+ return undefined
378
+ for (const line of stack.split('\n').slice(1)) {
379
+ const match = STACK_FRAME_RE.exec(line)
380
+ if (match !== null && !INTERNAL_HEAD_FRAME_RE.test(match[1]!))
381
+ return match[1]!
382
+ }
383
+ return undefined
384
+ }
385
+
386
+ /** Collects document <head> tags during SSR; innermost <title>, description, og:*, twitter:* and canonical win. */
316
387
  export function Head(props: { children?: PrunelleChild }): Html {
317
388
  const ctx = renderStorage.getStore()
318
389
  if (ctx === undefined)
319
390
  return raw('')
320
391
 
392
+ if (ctx.headersFlushed || ctx.headFlushed || activeScope(ctx).inSuspense === true) {
393
+ if (!ctx.warnedStreamHead) {
394
+ ctx.warnedStreamHead = true
395
+ const component = callerComponentName()
396
+ const where = component !== undefined ? ` in ${component}` : ''
397
+ console.warn(`prunelle: <Head>${where} was rendered inside a streamed <Suspense> boundary after <head> was already sent, so its tags were dropped; move <Head> outside <Suspense> (into the page or layout).`)
398
+ }
399
+ return raw('')
400
+ }
401
+
321
402
  let html = ssrChild(props.children)
322
403
  TITLE_RE.lastIndex = 0
323
404
  const titleMatch = TITLE_RE.exec(html)
@@ -327,6 +408,8 @@ export function Head(props: { children?: PrunelleChild }): Html {
327
408
  TITLE_RE.lastIndex = 0
328
409
  html = html.replace(TITLE_RE, '')
329
410
  }
411
+ if (html !== '')
412
+ html = dedupeHeadTags(html, ctx.headKeys)
330
413
  if (html !== '')
331
414
  ctx.headParts.push(html)
332
415
 
@@ -348,7 +431,7 @@ export function Suspense(props: { fallback?: PrunelleChild, error?: PrunelleChil
348
431
  return raw(ssrChild(props.fallback))
349
432
 
350
433
  const id = ctx.nextId++
351
- const scope = activeScope(ctx)
434
+ const scope: RenderScope = { ...activeScope(ctx), inSuspense: true }
352
435
  // Capture RenderContext and RenderScope so timeout / error fallback renders still see outer Context.Provider and <Region> state.
353
436
  const renderError = (error: unknown): string => {
354
437
  try {