prunelle 0.7.3 → 0.7.7
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.
- package/llms.txt +19 -17
- package/package.json +1 -1
- package/src/a11y/index.ts +9 -2
- package/src/build/index.ts +30 -31
- package/src/build/output.ts +1 -1
- package/src/build/prerender.ts +29 -13
- package/src/build/routes.ts +19 -1
- package/src/build/static.ts +24 -2
- package/src/cli/check-forms.ts +16 -6
- package/src/cli/check-links.ts +12 -9
- package/src/cli/check-security.ts +87 -12
- package/src/cli/check.ts +1 -1
- package/src/cli/commands.ts +3 -3
- package/src/cli/upgrade.ts +36 -3
- package/src/compiler/compliance.ts +2 -0
- package/src/compiler/dom.ts +41 -15
- package/src/compiler/ssr-helpers.ts +45 -21
- package/src/compiler/ssr.ts +32 -16
- package/src/context.ts +2 -0
- package/src/dev/error-log.ts +1 -1
- package/src/dev/index.ts +1 -1
- package/src/dev/supervisor.ts +2 -2
- package/src/dom/attrs.ts +1 -1
- package/src/dom/island.ts +30 -4
- package/src/jsx-runtime.ts +1 -1
- package/src/plugins/context.ts +18 -1
- package/src/plugins/services.ts +1 -0
- package/src/reactivity/index.ts +14 -2
- package/src/server/action.ts +26 -18
- package/src/server/assets.ts +22 -4
- package/src/server/consent.ts +7 -2
- package/src/server/cookies.ts +8 -1
- package/src/server/errors.ts +57 -26
- package/src/server/http.ts +1 -1
- package/src/server/index.ts +18 -16
- package/src/server/page.ts +4 -0
- package/src/server/rate-limit.ts +36 -12
- package/src/server/route-cache.ts +9 -10
- package/src/server/route-table.ts +38 -13
- package/src/server/router.ts +4 -4
- package/src/server/sanitize-html.ts +21 -7
- package/src/server/security.ts +13 -3
- package/src/server/serve-handlers.ts +3 -3
- package/src/server/start.ts +2 -2
- package/src/server/static-dir.ts +3 -10
- package/src/server/stream.ts +4 -4
- package/src/ssr/consent-banner.ts +3 -1
- package/src/ssr/context.ts +85 -2
- package/src/ssr/index.ts +16 -4
- package/src/ssr/navigation.ts +1 -1
- package/src/style.ts +9 -7
- package/src/unrenderable.ts +15 -5
package/src/server/page.ts
CHANGED
|
@@ -12,6 +12,10 @@ export interface LoadedPageModule {
|
|
|
12
12
|
load?: (ctx: RequestContext) => unknown | Promise<unknown>
|
|
13
13
|
clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
|
|
14
14
|
csrf?: boolean | undefined
|
|
15
|
+
/** The language the page is written in, for its `<html lang>`, when it differs from `lang` in prunelle.config.ts. */
|
|
16
|
+
lang?: string | undefined
|
|
17
|
+
/** How long this route's request may stay silent before the connection closes, in seconds or a duration string (`'5m'`), `0` for no limit; the server's is 30 s. */
|
|
18
|
+
idleTimeout?: number | string | undefined
|
|
15
19
|
GET?: (ctx: RequestContext) => Response | Promise<Response>
|
|
16
20
|
POST?: (ctx: RequestContext) => Response | Promise<Response>
|
|
17
21
|
PUT?: (ctx: RequestContext) => Response | Promise<Response>
|
package/src/server/rate-limit.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
171
|
-
const head = halves[0] === '' ? [] : halves[0]!.split(':')
|
|
172
|
-
const tail = halves[1] ? halves[1].split(':') : []
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
const zeros = halves.length === 2 ? 8 - head.length -
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
-
|
|
364
|
-
if (
|
|
365
|
-
const
|
|
366
|
-
if (
|
|
367
|
-
|
|
368
|
-
|
|
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,14 +24,14 @@ 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'
|
|
31
31
|
import { allowedMethodsHeader, hasPublicFavicon, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
|
|
32
32
|
import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
|
|
33
33
|
import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
|
|
34
|
-
import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, routeCacheKey, serveCachedHit, trackPrivateReads, withCacheControl } from './route-cache'
|
|
34
|
+
import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, parseCacheDuration, routeCacheKey, serveCachedHit, trackPrivateReads, withCacheControl } from './route-cache'
|
|
35
35
|
import { Router } from './router'
|
|
36
36
|
import { createFastStaticPageHandler, methodNotAllowed } from './routing'
|
|
37
37
|
import { styleHashesOf } from './security'
|
|
@@ -60,13 +60,20 @@ export interface CompiledRoute {
|
|
|
60
60
|
/** Options every document of this route shares; a request adds its body, head and islands. */
|
|
61
61
|
doc: DocumentOptions
|
|
62
62
|
headStyleHashes: string[]
|
|
63
|
+
/** The route's `export const idleTimeout` in whole seconds, as `server.timeout()` takes it. */
|
|
64
|
+
idleTimeout: number | undefined
|
|
63
65
|
}
|
|
64
66
|
|
|
65
|
-
function
|
|
67
|
+
function routeIdleTimeout(value: unknown): number | undefined {
|
|
68
|
+
const ms = value === undefined ? undefined : parseCacheDuration(value, true)
|
|
69
|
+
return ms === undefined ? undefined : Math.ceil(ms / 1000)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function routeDocument(manifest: BuildManifest, entry: RouteManifestEntry, mod: LoadedPageModule, lang: string, alwaysLoadRuntime: boolean, navigation: DocumentOptions['navigation'], hasFavicon: boolean): DocumentOptions {
|
|
66
73
|
return {
|
|
67
74
|
body: '',
|
|
68
75
|
headTags: mergedHeadTags(manifest, entry),
|
|
69
|
-
lang,
|
|
76
|
+
lang: typeof mod.lang === 'string' ? mod.lang : lang,
|
|
70
77
|
runtimeScript: manifest.runtimeScript,
|
|
71
78
|
chunkImports: manifest.chunkImports,
|
|
72
79
|
alwaysLoadRuntime,
|
|
@@ -104,18 +111,19 @@ export function compileRouteTable(options: RouteTableOptions): { router: Router<
|
|
|
104
111
|
const dirMiddlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
|
|
105
112
|
const hasLoad = Boolean(entry.hasLoad && typeof mod.load === 'function')
|
|
106
113
|
const dynamic = entry.path.includes(':') || entry.path.includes('*')
|
|
107
|
-
const doc = routeDocument(manifest, entry, lang, alwaysLoadRuntime, navigation, hasFavicon)
|
|
114
|
+
const doc = routeDocument(manifest, entry, mod, lang, alwaysLoadRuntime, navigation, hasFavicon)
|
|
115
|
+
const idleTimeout = routeIdleTimeout(mod.idleTimeout)
|
|
108
116
|
|
|
109
117
|
// Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, no route cache, and no intercepting plugin hook
|
|
110
118
|
const canFastPath = middlewaresFor(entry.path, hasLoad ? 'dynamic' : 'static').length === 0
|
|
111
119
|
&& !pluginIntercepts(entry.path) && !dynamic
|
|
112
120
|
&& dirMiddlewares.length === 0 && !entry.usesRenderContext && entry.cache === undefined
|
|
113
|
-
&& typeof mod.default === 'function' && mod.GET === undefined
|
|
121
|
+
&& typeof mod.default === 'function' && mod.GET === undefined && idleTimeout === undefined
|
|
114
122
|
if (canFastPath)
|
|
115
123
|
fastStaticPages.set(entry.path, createFastStaticPageHandler({ ...fast, entry, mod, layouts, doc, reviveScript: manifest.reviveScript, hasIslands: entry.islandChunks.length > 0, hasLoad }))
|
|
116
124
|
|
|
117
125
|
const routeEntry = entry.cache !== undefined && dirMiddlewares.length > 0 ? { ...entry, cache: { ...entry.cache, cacheControl: GATED_ROUTE_CACHE_CONTROL } } : entry
|
|
118
|
-
router.add(entry.path, { entry: routeEntry, mod, layouts, dirMiddlewares, middlewares: [...middlewaresFor(entry.path), ...dirMiddlewares], dynamic, doc, headStyleHashes: headTagStyleHashes(doc.headTags) })
|
|
126
|
+
router.add(entry.path, { entry: routeEntry, mod, layouts, dirMiddlewares, middlewares: [...middlewaresFor(entry.path), ...dirMiddlewares], dynamic, doc, headStyleHashes: headTagStyleHashes(doc.headTags), idleTimeout })
|
|
119
127
|
}
|
|
120
128
|
return { router, fastStaticPages }
|
|
121
129
|
}
|
|
@@ -182,7 +190,7 @@ async function renderPageDocument(
|
|
|
182
190
|
pageProps: Record<string, unknown>,
|
|
183
191
|
ctx: RequestContext,
|
|
184
192
|
hasFlash: boolean,
|
|
185
|
-
|
|
193
|
+
setIdleTimeout?: (seconds: number) => void,
|
|
186
194
|
timing?: DevTiming,
|
|
187
195
|
privateTracker?: PrivateReadTracker,
|
|
188
196
|
): Promise<RenderedPageOutput> {
|
|
@@ -192,7 +200,11 @@ async function renderPageDocument(
|
|
|
192
200
|
const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, privateTracker?.ctx ?? ctx))
|
|
193
201
|
if (hasFlash)
|
|
194
202
|
ctx.cookies.delete(ACTION_ERROR_COOKIE)
|
|
195
|
-
const
|
|
203
|
+
// A route's `export const lang` names the language it is written in, so a plugin head hook such as i18n's cannot replace it.
|
|
204
|
+
const pageLang = typeof route.mod.lang === 'string' ? route.mod.lang : undefined
|
|
205
|
+
const resolvedHead = await deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
|
|
206
|
+
const docHead = pageLang === undefined ? resolvedHead : { ...resolvedHead, lang: pageLang, htmlAttrs: { ...resolvedHead.htmlAttrs, lang: pageLang } }
|
|
207
|
+
rctx.headFlushed = true
|
|
196
208
|
const renderedIslands = resolveRenderedIslands(rctx, body)
|
|
197
209
|
const isStreamed = rctx.pending.length > 0
|
|
198
210
|
const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
|
|
@@ -206,9 +218,12 @@ async function renderPageDocument(
|
|
|
206
218
|
if (ctx.request.method === 'HEAD') {
|
|
207
219
|
rctx.aborted = true
|
|
208
220
|
endTimer(timing, 'stream', streamStart)
|
|
209
|
-
|
|
221
|
+
const headers = withRegionVary(deps.htmlHeaders(hasIslands, true, true, trustedStyleHashes), hasRegions)
|
|
222
|
+
if (deps.compressCache !== undefined)
|
|
223
|
+
headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
|
|
224
|
+
return { kind: 'stream', response: markCompressionHandled(new Response(null, { status: 200, headers })) }
|
|
210
225
|
}
|
|
211
|
-
|
|
226
|
+
setIdleTimeout?.(0)
|
|
212
227
|
const docShell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
|
|
213
228
|
const shell = deps.hasHtmlTransformers ? await deps.applyHtmlTransforms(docShell, ctx.url, ctx.request, ctx) : docShell
|
|
214
229
|
const streamStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docShell, shell))
|
|
@@ -259,6 +274,10 @@ async function revalidateCompiledRoute(
|
|
|
259
274
|
nonCacheable = true
|
|
260
275
|
return new Response(null, { status: 404 })
|
|
261
276
|
}
|
|
277
|
+
if (error instanceof Response) {
|
|
278
|
+
void error.body?.cancel().catch(() => undefined)
|
|
279
|
+
throw new Error(`prunelle: load() threw a Response (HTTP ${error.status}) instead of returning it; return the Response from load() instead.`)
|
|
280
|
+
}
|
|
262
281
|
throw error
|
|
263
282
|
}
|
|
264
283
|
if (isNotFound(data) || data instanceof Response) {
|
|
@@ -298,6 +317,10 @@ async function runCompiledRouteLoad(
|
|
|
298
317
|
catch (error) {
|
|
299
318
|
if (isNotFound(error))
|
|
300
319
|
return { kind: 'response', response: await deps.buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file) }
|
|
320
|
+
if (error instanceof Response) {
|
|
321
|
+
void error.body?.cancel().catch(() => undefined)
|
|
322
|
+
throw new Error(`prunelle: load() threw a Response (HTTP ${error.status}) instead of returning it; return the Response from load() instead.`)
|
|
323
|
+
}
|
|
301
324
|
throw error
|
|
302
325
|
}
|
|
303
326
|
endTimer(timing, 'load', loadStart)
|
|
@@ -338,12 +361,14 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
|
|
|
338
361
|
route: CompiledRoute,
|
|
339
362
|
ctx: RequestContext,
|
|
340
363
|
cookieStore: CookieStore,
|
|
341
|
-
|
|
364
|
+
setIdleTimeout?: (seconds: number) => void,
|
|
342
365
|
staticPath?: string,
|
|
343
366
|
timing?: DevTiming,
|
|
344
367
|
middlewares: readonly Middleware[] = route.middlewares,
|
|
345
368
|
): Promise<Response> {
|
|
346
369
|
const { entry, mod, doc } = route
|
|
370
|
+
if (route.idleTimeout !== undefined)
|
|
371
|
+
setIdleTimeout?.(route.idleTimeout)
|
|
347
372
|
const isRegion = hasRegionHeader(ctx.request)
|
|
348
373
|
|
|
349
374
|
const early = await resolvePrerenderedOrApi(deps, route, ctx, isRegion, staticPath)
|
|
@@ -400,7 +425,7 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
|
|
|
400
425
|
)
|
|
401
426
|
}
|
|
402
427
|
|
|
403
|
-
const rendered = await renderPageDocument(deps, route, loaded.data, pageProps, ctx, hasFlash,
|
|
428
|
+
const rendered = await renderPageDocument(deps, route, loaded.data, pageProps, ctx, hasFlash, setIdleTimeout, timing, privateTracker)
|
|
404
429
|
if (rendered.kind === 'stream')
|
|
405
430
|
return rendered.response
|
|
406
431
|
if (privateTracker?.didReadPrivate())
|
package/src/server/router.ts
CHANGED
|
@@ -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
|
|
207
|
-
const refused = (k: number): boolean => path.encoded?.has(k) === true ||
|
|
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 ?
|
|
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 += '<'
|
|
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
|
-
|
|
262
|
+
|
|
263
|
+
const tagEnd = findTagEndOffset(html, pos)
|
|
264
|
+
if (tagEnd === -1) {
|
|
254
265
|
out += '<'
|
|
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
|
|
282
|
-
|
|
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
|
|
package/src/server/security.ts
CHANGED
|
@@ -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. */
|
|
@@ -20,8 +20,8 @@ export interface ServeHandlerSources {
|
|
|
20
20
|
healthPath?: string | undefined
|
|
21
21
|
healthHandler?: ((request: Request, requestId?: string) => Response | Promise<Response>) | undefined
|
|
22
22
|
resolveRequestId?: RequestIdResolver | undefined
|
|
23
|
-
/** Answers through the app's whole pipeline,
|
|
24
|
-
runRequest: (req: Request, remoteIp: string | undefined,
|
|
23
|
+
/** Answers through the app's whole pipeline, `setIdleTimeout` setting the request's idle timeout in seconds: 0 for a long-lived stream, or a route's `export const idleTimeout`. */
|
|
24
|
+
runRequest: (req: Request, remoteIp: string | undefined, setIdleTimeout: (seconds: number) => void) => Promise<Response>
|
|
25
25
|
runFast: (handler: FastHandler, req: Request, remoteIp: string | undefined) => Response | Promise<Response>
|
|
26
26
|
notifyError: NotifyError
|
|
27
27
|
serverError: () => Response
|
|
@@ -38,7 +38,7 @@ export const isPlainRead = (request: Request): boolean => isRead(request) && !ha
|
|
|
38
38
|
export function serveHandlers(server: () => PrunelleServer | undefined, sources: ServeHandlerSources) {
|
|
39
39
|
const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone } = sources
|
|
40
40
|
const ipOf = (req: Request) => server()?.requestIP(req)?.address
|
|
41
|
-
const fetchReq = (req: Request) => runRequest(req, ipOf(req),
|
|
41
|
+
const fetchReq = (req: Request) => runRequest(req, ipOf(req), seconds => server()?.timeout(req, seconds))
|
|
42
42
|
// A file that fails to open answers here, where the request is known: gone since the build is a 404, anything else is reported with it.
|
|
43
43
|
const serveFile = async (req: Request, file: ServedFile): Promise<Response> => {
|
|
44
44
|
const reqId = resolveRequestId?.(req)
|
package/src/server/start.ts
CHANGED
|
@@ -30,7 +30,7 @@ export async function startServer(options: StartOptions): Promise<{ app: Prunell
|
|
|
30
30
|
let current = first.app
|
|
31
31
|
const server = current.serve(options.port, options.hostname)
|
|
32
32
|
const app: PrunelleApp = {
|
|
33
|
-
handle: async (request, remoteIp,
|
|
33
|
+
handle: async (request, remoteIp, setIdleTimeout) => current.handle(request, remoteIp, setIdleTimeout),
|
|
34
34
|
serve: () => server,
|
|
35
35
|
closeStreams: async () => current.closeStreams?.(),
|
|
36
36
|
dispose: async () => {
|
|
@@ -73,7 +73,7 @@ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleAp
|
|
|
73
73
|
catch {
|
|
74
74
|
return new Response('Service Unavailable', { status: 503, headers: { ...current().securityHeaders, 'content-type': 'text/plain; charset=utf-8' } })
|
|
75
75
|
}
|
|
76
|
-
return target.handle(request, server.requestIP(request)?.address,
|
|
76
|
+
return target.handle(request, server.requestIP(request)?.address, seconds => server.timeout(request, seconds))
|
|
77
77
|
},
|
|
78
78
|
})
|
|
79
79
|
}
|
package/src/server/static-dir.ts
CHANGED
|
@@ -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
|
|
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 =
|
|
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
|
package/src/server/stream.ts
CHANGED
|
@@ -150,8 +150,8 @@ function safeClose(controller: ReadableStreamDefaultController<Uint8Array>): boo
|
|
|
150
150
|
}
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
-
function trackEventStream(res: Response, active: Set<() => void>,
|
|
154
|
-
|
|
153
|
+
function trackEventStream(res: Response, active: Set<() => void>, setIdleTimeout?: (seconds: number) => void): Response {
|
|
154
|
+
setIdleTimeout?.(0)
|
|
155
155
|
if (res.body === null)
|
|
156
156
|
return res
|
|
157
157
|
const reader = res.body.getReader()
|
|
@@ -206,7 +206,7 @@ function trackEventStream(res: Response, active: Set<() => void>, disableTimeout
|
|
|
206
206
|
}
|
|
207
207
|
|
|
208
208
|
export interface StreamTracker {
|
|
209
|
-
track: (res: Response,
|
|
209
|
+
track: (res: Response, setIdleTimeout?: (seconds: number) => void) => Response
|
|
210
210
|
/** Registers a streamed page's way to end early; the returned function drops it once the page is done. */
|
|
211
211
|
trackPage: (end: () => void) => () => void
|
|
212
212
|
closeAll: () => Promise<void>
|
|
@@ -217,7 +217,7 @@ export function createStreamTracker(): StreamTracker {
|
|
|
217
217
|
const active = new Set<() => void>()
|
|
218
218
|
const pages = new Set<() => void>()
|
|
219
219
|
return {
|
|
220
|
-
track: (res,
|
|
220
|
+
track: (res, setIdleTimeout) => trackEventStream(res, active, setIdleTimeout),
|
|
221
221
|
trackPage: (end) => {
|
|
222
222
|
pages.add(end)
|
|
223
223
|
return () => { pages.delete(end) }
|
|
@@ -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
|
|
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>`
|