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.
- package/LICENSE +21 -0
- package/llms.txt +48 -43
- package/package.json +4 -1
- package/src/a11y/declaration.ts +106 -72
- package/src/a11y/index.ts +59 -39
- package/src/a11y/rgaa-map.ts +95 -49
- package/src/build/bundle.ts +8 -4
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-plugin.ts +3 -1
- package/src/build/compile.ts +2 -1
- package/src/build/ecoindex.ts +25 -16
- package/src/build/files.ts +6 -0
- package/src/build/first-load.ts +83 -11
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +61 -18
- package/src/build/island-promote.ts +250 -0
- package/src/build/islands.ts +12 -201
- package/src/build/manifest.ts +4 -125
- package/src/build/plugin-host.ts +21 -8
- package/src/build/precompress.ts +1 -1
- package/src/build/prerender.ts +97 -44
- package/src/build/reach.ts +136 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +25 -3
- package/src/build/static-headers.ts +93 -0
- package/src/build/static.ts +2 -0
- package/src/cli/check-forms.ts +97 -48
- package/src/cli/check-imports.ts +25 -0
- package/src/cli/check-links.ts +2 -2
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +37 -7
- package/src/cli/commands.ts +35 -7
- package/src/cli/docs.ts +4 -3
- package/src/cli/inspect.ts +2 -1
- package/src/cli/mcp-tools.ts +7 -5
- package/src/cli/mcp.ts +1 -1
- package/src/cli/new.ts +14 -3
- package/src/cli/render.ts +14 -19
- package/src/cli/upgrade.ts +22 -5
- package/src/compiler/analyze.ts +27 -5
- package/src/compiler/cacheability.ts +2 -2
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +110 -4
- package/src/compiler/compliance-urls.ts +146 -0
- package/src/compiler/compliance.ts +168 -116
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +19 -1
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/shared.ts +2 -2
- package/src/compiler/ssr.ts +2 -2
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +90 -64
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +17 -7
- package/src/dev/open-editor.ts +36 -12
- package/src/dev/protocol.ts +2 -0
- package/src/dev/supervisor.ts +8 -0
- package/src/dev/watchers.ts +27 -2
- package/src/dom/action.ts +4 -1
- package/src/dom/extras.ts +1 -2
- package/src/dom/index.ts +28 -6
- package/src/dom/island.ts +22 -10
- package/src/dom/loop.ts +60 -27
- package/src/eco/declaration.ts +257 -0
- package/src/eco/index.ts +65 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +44 -1
- package/src/plugins/load.ts +4 -3
- package/src/plugins/public.ts +2 -2
- package/src/plugins/services.ts +3 -0
- package/src/plugins/types.ts +17 -2
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +38 -37
- package/src/server/action.ts +11 -127
- package/src/server/app-secret.ts +63 -0
- package/src/server/compress.ts +5 -1
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +3 -1
- package/src/server/form-schema.ts +1 -1
- package/src/server/health.ts +46 -15
- package/src/server/http.ts +56 -8
- package/src/server/index.ts +59 -30
- package/src/server/loader.ts +10 -2
- package/src/server/plugin-host.ts +3 -1
- package/src/server/public.ts +4 -3
- package/src/server/rate-limit.ts +52 -9
- package/src/server/route-cache.ts +26 -4
- package/src/server/route-table.ts +7 -3
- package/src/server/routing.ts +3 -87
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +73 -22
- package/src/server/serve-handlers.ts +14 -4
- package/src/server/start.ts +1 -1
- package/src/server/static-dir.ts +31 -5
- package/src/server/stream.ts +28 -6
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +20 -4
- package/src/ssr/index.ts +18 -0
- package/src/ssr/navigation.ts +2 -2
- package/src/style.ts +64 -1
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/src/routes/legal.tsx +10 -1
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +1 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
package/src/server/index.ts
CHANGED
|
@@ -13,12 +13,14 @@ import type { NotifyError } from './errors'
|
|
|
13
13
|
import type { DevTiming } from './health'
|
|
14
14
|
import type { DeniedInfo, EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
|
|
15
15
|
import type { RateLimiter, RateLimitStore } from './rate-limit'
|
|
16
|
+
export { rateLimitKey } from './rate-limit'
|
|
17
|
+
export { sanitizeMarkdownHtml } from './sanitize-html'
|
|
16
18
|
import type { LoadedMiddlewareModule } from './page'
|
|
17
19
|
import type { ServerPluginHost } from './plugin-host'
|
|
18
20
|
import type { RequestPath } from './request-path'
|
|
19
21
|
import type { CompiledRoute } from './route-table'
|
|
20
22
|
import type { FastHandler } from './routing'
|
|
21
|
-
import type { TrustProxy } from './security'
|
|
23
|
+
import type { OriginRefusal, TrustProxy } from './security'
|
|
22
24
|
import { join } from 'node:path'
|
|
23
25
|
import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
24
26
|
import { createNavigation } from '../ssr/navigation'
|
|
@@ -27,6 +29,7 @@ import { createActionRegistry } from './action-registry'
|
|
|
27
29
|
import { createAssets } from './assets'
|
|
28
30
|
import { CompressionCache, maybeCompressResponse } from './compress'
|
|
29
31
|
import { normalizeConsentConfig } from './consent'
|
|
32
|
+
import { devFromEnv, nodeEnv } from './env'
|
|
30
33
|
import { createDocumentHooks, createHtmlHeaders, withPluginHtmlCsp } from './document'
|
|
31
34
|
import { createErrorNotifier, createFallbackPages, devErrorResponse } from './errors'
|
|
32
35
|
import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, formatServerTiming, runTimedChain, withRequestId } from './health'
|
|
@@ -42,7 +45,7 @@ import { createRouteCache } from './route-cache'
|
|
|
42
45
|
import { compileRouteTable, createCompiledRouteRenderer, routeMethodHandler } from './route-table'
|
|
43
46
|
import { actionRoutePrefix, createAncestorMiddlewareLookup, inferRoutesServerPrefix, methodNotAllowed } from './routing'
|
|
44
47
|
import { isPlainRead, isRead, serveHandlers } from './serve-handlers'
|
|
45
|
-
import { buildSecurityHeaderEntries, resolveHstsValue, verifyOrigin } from './security'
|
|
48
|
+
import { buildSecurityHeaderEntries, isLoopbackHost, logOriginHint, resolveHstsValue, verifyOrigin } from './security'
|
|
46
49
|
import { createStreamTracker } from './stream'
|
|
47
50
|
|
|
48
51
|
/**
|
|
@@ -60,14 +63,14 @@ export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEn
|
|
|
60
63
|
export type { CompressionEncoding, PrecompressedEncoding } from './compress'
|
|
61
64
|
export type { RequestConsent } from './consent'
|
|
62
65
|
export type { CookieOptions, Cookies } from './cookies'
|
|
63
|
-
export { defineEnv, nodeEnv } from './env'
|
|
66
|
+
export { defineEnv, devFromEnv, nodeEnv } from './env'
|
|
64
67
|
export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from './health'
|
|
65
68
|
export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
|
|
66
69
|
export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, ServerOptions, StatusPageProps } from './http'
|
|
67
70
|
export { createServer } from './loader'
|
|
68
71
|
export { buildRouteCacheSpec, createRouteCache, formatCacheSpec, parseCacheDuration, RouteCache } from './route-cache'
|
|
69
72
|
export type { CachedRouteEntry, RouteCacheOptions, RouteCacheSpec } from './route-cache'
|
|
70
|
-
export { DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isTrustedOrigin, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
|
|
73
|
+
export { DEFAULT_COOP, DEFAULT_CORP, DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isLoopbackHost, isTrustedOrigin, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
|
|
71
74
|
export type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
72
75
|
export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
|
|
73
76
|
export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
|
|
@@ -133,8 +136,10 @@ function createRequestGuards(
|
|
|
133
136
|
maxRequestBodySize: number,
|
|
134
137
|
finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response,
|
|
135
138
|
) {
|
|
136
|
-
const refuseCrossSite = (request: Request,
|
|
137
|
-
|
|
139
|
+
const refuseCrossSite = (request: Request, check: OriginRefusal, cookieStore?: CookieStore, requestId?: string): Response => {
|
|
140
|
+
logOriginHint(check.hint)
|
|
141
|
+
return finish(Response.json({ ok: false, status: 403, error: check.reason }, { status: 403 }), request, cookieStore, requestId)
|
|
142
|
+
}
|
|
138
143
|
|
|
139
144
|
const checkBodyLimit = async (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string): Promise<Request | Response> => {
|
|
140
145
|
if (bodyLimited)
|
|
@@ -156,10 +161,11 @@ interface ActionDispatcherDeps {
|
|
|
156
161
|
rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
|
|
157
162
|
trustedOrigins: Set<string> | undefined
|
|
158
163
|
trustProxy: TrustProxy
|
|
164
|
+
httpsSite: boolean
|
|
159
165
|
consent: NormalizedConsentConfig | undefined
|
|
160
166
|
rateLimits: RateLimitStore
|
|
161
167
|
isDev: boolean
|
|
162
|
-
refuseCrossSite: (request: Request,
|
|
168
|
+
refuseCrossSite: (request: Request, check: OriginRefusal, cookieStore?: CookieStore, requestId?: string) => Response
|
|
163
169
|
checkBodyLimit: (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string) => Promise<Request | Response>
|
|
164
170
|
finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
|
|
165
171
|
notifyError: NotifyError
|
|
@@ -167,7 +173,7 @@ interface ActionDispatcherDeps {
|
|
|
167
173
|
}
|
|
168
174
|
|
|
169
175
|
function createActionDispatcher(deps: ActionDispatcherDeps) {
|
|
170
|
-
const { actions, rewrites, trustedOrigins, trustProxy, consent, rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
|
|
176
|
+
const { actions, rewrites, trustedOrigins, trustProxy, httpsSite, consent, rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
|
|
171
177
|
const limiters = new WeakMap<RegisteredAction['act'], RateLimiter>()
|
|
172
178
|
const limiterFor = (act: RegisteredAction['act']): RateLimiter | undefined => {
|
|
173
179
|
if (act.rateLimit === undefined)
|
|
@@ -194,14 +200,14 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
|
|
|
194
200
|
if (actionHandler !== undefined) {
|
|
195
201
|
const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
|
|
196
202
|
if (!originCheck.ok)
|
|
197
|
-
return refuseCrossSite(request, originCheck
|
|
203
|
+
return refuseCrossSite(request, originCheck, existing?.cookieStore, requestId)
|
|
198
204
|
const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore, requestId)
|
|
199
205
|
if (checked instanceof Response)
|
|
200
206
|
return checked
|
|
201
207
|
req = checked
|
|
202
208
|
}
|
|
203
209
|
const { act, middlewares } = registeredAction
|
|
204
|
-
const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, remoteIp, url, consent, requestId })
|
|
210
|
+
const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
|
|
205
211
|
ctx.request = req
|
|
206
212
|
if (existing === undefined && rewrites.length > 0) {
|
|
207
213
|
for (const rewrite of rewrites)
|
|
@@ -284,6 +290,36 @@ function createNotFoundRenderer(deps: NotFoundRendererDeps) {
|
|
|
284
290
|
}
|
|
285
291
|
}
|
|
286
292
|
|
|
293
|
+
/** The security headers every response carries, and the helpers that put them on a response built without them. */
|
|
294
|
+
function createSecurityResponders(
|
|
295
|
+
security: EmbeddedServerConfig['security'],
|
|
296
|
+
trustProxy: TrustProxy,
|
|
297
|
+
isDev: boolean,
|
|
298
|
+
site: string | undefined,
|
|
299
|
+
explicitNodeEnv: string | undefined,
|
|
300
|
+
) {
|
|
301
|
+
const resolvedNodeEnv = explicitNodeEnv ?? nodeEnv()
|
|
302
|
+
// An https `site` says the app is served over https, whatever a proxy the server does not trust leaves in the request.
|
|
303
|
+
const httpsSite = !isDev && resolvedNodeEnv !== 'development' && resolvedNodeEnv !== 'test' && site?.startsWith('https://') === true
|
|
304
|
+
const securityEntries = buildSecurityHeaderEntries(security)
|
|
305
|
+
const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
|
|
306
|
+
const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
|
|
307
|
+
const hstsValue = resolveHstsValue(security)
|
|
308
|
+
// Every response passes here, so it is where a production server first sees it runs behind a proxy it does not trust.
|
|
309
|
+
let proxyChecked = trustProxy !== false || isDev || resolvedNodeEnv !== 'production'
|
|
310
|
+
const withHsts = (res: Response, request: Request): Response => {
|
|
311
|
+
if (!proxyChecked && request.headers.has('x-forwarded-proto')) {
|
|
312
|
+
proxyChecked = true
|
|
313
|
+
console.warn('prunelle: a request came through a proxy (it carries x-forwarded-proto) but trustProxy is off, so ctx.ip and rate limits see the proxy\'s address and https is known from site alone: set trustProxy in prunelle.config.ts to the proxy the server runs behind.')
|
|
314
|
+
}
|
|
315
|
+
return applyHstsHeader(res, request, hstsValue, trustProxy, isDev, explicitNodeEnv, httpsSite)
|
|
316
|
+
}
|
|
317
|
+
// The one way out of every response not built with the security headers already in place.
|
|
318
|
+
const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
|
|
319
|
+
withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
|
|
320
|
+
return { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError: makeServerError(securityRecord), fileGone: makeFileGone(securityRecord) }
|
|
321
|
+
}
|
|
322
|
+
|
|
287
323
|
export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<PrunelleApp> {
|
|
288
324
|
const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, prerenderedEtags = {}, lang = 'en', security } = config
|
|
289
325
|
const plugins = resolvePlugins(config.plugins)
|
|
@@ -295,7 +331,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
295
331
|
const consent = normalizeConsentConfig(config.consent)
|
|
296
332
|
const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
|
|
297
333
|
const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
|
|
298
|
-
const isDev = config.dev ?? (
|
|
334
|
+
const isDev = config.dev ?? devFromEnv()
|
|
299
335
|
const serverRoot = config.root ?? process.cwd()
|
|
300
336
|
const serverOutDir = config.outDir ?? join(serverRoot, 'dist')
|
|
301
337
|
const serverPublicDir = config.publicDir ?? join(serverOutDir, 'public')
|
|
@@ -306,17 +342,8 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
306
342
|
const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
|
|
307
343
|
const { hasHeadHooks, hasHtmlTransformers, resolveDocumentHead, applyHtmlTransforms } = document
|
|
308
344
|
|
|
309
|
-
const
|
|
310
|
-
const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
|
|
311
|
-
const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
|
|
312
|
-
const hstsValue = resolveHstsValue(security)
|
|
313
|
-
const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy, isDev)
|
|
314
|
-
// The one way out of every response not built with the security headers already in place.
|
|
315
|
-
const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
|
|
316
|
-
withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
|
|
345
|
+
const { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError, fileGone } = createSecurityResponders(security, trustProxy, isDev, site, config.nodeEnv ?? parentAppCtx?.nodeEnv)
|
|
317
346
|
const resolveRequestId = createRequestIdResolver(trustProxy)
|
|
318
|
-
const serverError = makeServerError(securityRecord)
|
|
319
|
-
const fileGone = makeFileGone(securityRecord)
|
|
320
347
|
const navigation = createNavigation(config.navigation)
|
|
321
348
|
const htmlHeaders = createHtmlHeaders(security, securityRecord, navigation, plugins)
|
|
322
349
|
const streams = createStreamTracker()
|
|
@@ -353,6 +380,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
353
380
|
assetPrefix,
|
|
354
381
|
site,
|
|
355
382
|
dev: isDev,
|
|
383
|
+
devExposed: config.devHost !== undefined && !isLoopbackHost(config.devHost),
|
|
356
384
|
trustProxy,
|
|
357
385
|
trustedOriginsList,
|
|
358
386
|
trustedOrigins,
|
|
@@ -375,7 +403,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
375
403
|
let renderCompiledRoute: ReturnType<typeof createCompiledRouteRenderer>
|
|
376
404
|
let dispatchAction: ReturnType<typeof createActionDispatcher>
|
|
377
405
|
try {
|
|
378
|
-
healthHandler = createHealthHandler({ checks: collectHealthChecks(config.healthCheck, pluginHost.healthChecks), securityRecord, withHsts, resolveRequestId })
|
|
406
|
+
healthHandler = createHealthHandler({ checks: collectHealthChecks(config.healthCheck, pluginHost.healthChecks), securityRecord, withHsts, resolveRequestId, exposeErrors: isDev })
|
|
379
407
|
const routesPrefix = inferRoutesServerPrefix(manifest)
|
|
380
408
|
const paramMatchers = resolveParamMatchers(manifest.paramMatchers, modules)
|
|
381
409
|
const routePathByFile = new Map(manifest.routes.map(r => [r.file, r.path]))
|
|
@@ -389,20 +417,21 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
389
417
|
;({ router, fastStaticPages } = compileRouteTable({
|
|
390
418
|
manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, middlewaresFor,
|
|
391
419
|
pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
|
|
392
|
-
fast: { trustProxy, consent, htmlHeaders, compressCache,
|
|
420
|
+
fast: { trustProxy, httpsSite, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
|
|
393
421
|
}))
|
|
394
422
|
const collected = files.collectPrerendered(manifest.routes, {
|
|
395
423
|
prerendered, prerenderedFiles, prerenderedEtags,
|
|
396
424
|
// The route's region script is what sends `x-pru-region`, so a page without one never varies on it.
|
|
397
|
-
|
|
425
|
+
// no-cache, not public: an app middleware may gate the page, and its ETag still spares a revisit the download.
|
|
426
|
+
htmlHeaders: (route, urlPath) => ({ 'cache-control': 'no-cache', ...withRegionVary(htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true) }),
|
|
398
427
|
isFast: nativePrerenderedCheck({ site, rewrites: pluginHost.rewrites, pluginRouter, router, actions, middlewaresForPaths, trustProxy, consent }),
|
|
399
428
|
})
|
|
400
429
|
fastPrerenderedMap = collected.fast
|
|
401
430
|
renderCompiledRoute = createCompiledRouteRenderer({
|
|
402
|
-
manifest, prerenderedMap: collected.all, serveFile, buildNotFoundResponse: fallbacks.buildNotFoundResponse, htmlHeaders, resolveDocumentHead, applyHtmlTransforms, hasHtmlTransformers, streamTimeout, compressCache, routeCache, notifyError, actions, rewrites: pluginHost.rewrites, trustProxy, consent, resolveRequestId, serverAppCtx,
|
|
431
|
+
manifest, prerenderedMap: collected.all, serveFile, buildNotFoundResponse: fallbacks.buildNotFoundResponse, htmlHeaders, resolveDocumentHead, applyHtmlTransforms, hasHtmlTransformers, streamTimeout, streams, compressCache, routeCache, notifyError, actions, rewrites: pluginHost.rewrites, trustProxy, consent, resolveRequestId, serverAppCtx,
|
|
403
432
|
})
|
|
404
433
|
dispatchAction = createActionDispatcher({
|
|
405
|
-
actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
|
|
434
|
+
actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, httpsSite, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
|
|
406
435
|
})
|
|
407
436
|
}
|
|
408
437
|
catch (error) {
|
|
@@ -448,7 +477,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
448
477
|
}
|
|
449
478
|
|
|
450
479
|
// 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
|
|
451
|
-
const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent, requestId })
|
|
480
|
+
const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
|
|
452
481
|
const timing = createTiming(isDev)
|
|
453
482
|
|
|
454
483
|
// Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
|
|
@@ -480,7 +509,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
480
509
|
if (routeDef.csrf) {
|
|
481
510
|
const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
|
|
482
511
|
if (!originCheck.ok)
|
|
483
|
-
return refuseCrossSite(request, originCheck
|
|
512
|
+
return refuseCrossSite(request, originCheck, cookieStore, requestId)
|
|
484
513
|
}
|
|
485
514
|
const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
|
|
486
515
|
if (checked instanceof Response)
|
|
@@ -535,7 +564,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
535
564
|
if (route.mod.csrf !== false) {
|
|
536
565
|
const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
|
|
537
566
|
if (!originCheck.ok)
|
|
538
|
-
return refuseCrossSite(request, originCheck
|
|
567
|
+
return refuseCrossSite(request, originCheck, cookieStore, requestId)
|
|
539
568
|
}
|
|
540
569
|
const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
|
|
541
570
|
if (checked instanceof Response)
|
|
@@ -582,5 +611,5 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
582
611
|
const reloadInto = (server: PrunelleServer): void => {
|
|
583
612
|
server.reload(handlers(() => server))
|
|
584
613
|
}
|
|
585
|
-
return { handle, serve, reloadInto, inject: serverAppCtx.inject, closeStreams: streams.closeAll, dispose: async () => { await streams.closeAll(); await pluginHost.dispose() } }
|
|
614
|
+
return { handle, serve, reloadInto, inject: serverAppCtx.inject, closeStreams: streams.closeAll, securityHeaders: securityRecord, dispose: async () => { await streams.closeAll(); await pluginHost.dispose() } }
|
|
586
615
|
}
|
package/src/server/loader.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
|
7
7
|
import { join, resolve } from 'node:path'
|
|
8
8
|
import { SERVER_ENTRY_FILE } from '../build/server-entry'
|
|
9
9
|
import { loadConfig, resolveServerConfig } from '../plugins/index'
|
|
10
|
+
import { devFromEnv } from './env'
|
|
10
11
|
import { createStaticDirServer } from './static-dir'
|
|
11
12
|
|
|
12
13
|
let serverLoadSeq = 0
|
|
@@ -70,7 +71,8 @@ export async function startBuiltApp(options: ServerOptions): Promise<{ app: Prun
|
|
|
70
71
|
root,
|
|
71
72
|
outDir,
|
|
72
73
|
publicDir: join(outDir, 'public'),
|
|
73
|
-
dev: options.dev ?? (
|
|
74
|
+
dev: options.dev ?? devFromEnv(),
|
|
75
|
+
devHost: options.devHost,
|
|
74
76
|
nodeEnv: options.nodeEnv,
|
|
75
77
|
errorSink: options.errorSink,
|
|
76
78
|
prerender: options.prerender,
|
|
@@ -108,16 +110,22 @@ async function loadServerEntry(options: ServerOptions): Promise<BuiltOutput> {
|
|
|
108
110
|
|
|
109
111
|
async function serveStaticDir(options: ServerOptions, root: string, outDir: string): Promise<PrunelleApp> {
|
|
110
112
|
const config = await loadConfig(root, { dev: options.dev, nodeEnv: options.nodeEnv })
|
|
113
|
+
const site = (options.site ?? config.site)?.replace(/\/$/, '') || undefined
|
|
114
|
+
const isDev = options.dev ?? devFromEnv()
|
|
111
115
|
return createStaticDirServer(
|
|
112
116
|
outDir,
|
|
113
117
|
options.assetPrefix ?? config.assetPrefix ?? '/_pru',
|
|
114
118
|
options.security ?? config.security,
|
|
115
119
|
(options.compress ?? config.compress) !== false,
|
|
116
120
|
options.trustProxy ?? config.trustProxy ?? false,
|
|
117
|
-
|
|
121
|
+
isDev,
|
|
118
122
|
{
|
|
119
123
|
navigation: options.navigation ?? config.navigation,
|
|
120
124
|
plugins: options.plugins ?? config.plugins,
|
|
125
|
+
onError: options.onError ?? config.onError,
|
|
126
|
+
errorSink: options.errorSink,
|
|
127
|
+
httpsSite: !isDev && site?.startsWith('https://') === true,
|
|
128
|
+
nodeEnv: options.nodeEnv,
|
|
121
129
|
},
|
|
122
130
|
)
|
|
123
131
|
}
|
|
@@ -45,6 +45,7 @@ export interface ServerPluginHostOptions {
|
|
|
45
45
|
assetPrefix: string
|
|
46
46
|
site: string | undefined
|
|
47
47
|
dev: boolean
|
|
48
|
+
devExposed: boolean
|
|
48
49
|
trustProxy: TrustProxy
|
|
49
50
|
trustedOriginsList: readonly string[]
|
|
50
51
|
trustedOrigins: Set<string> | undefined
|
|
@@ -214,7 +215,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
|
214
215
|
|
|
215
216
|
if (config.prerender !== true || config.static === true) {
|
|
216
217
|
const production = !options.dev && (appCtx.nodeEnv ?? process.env.NODE_ENV) === 'production'
|
|
217
|
-
await runWithAppContext(appCtx, () => enforceRequirements(plugins, { root: options.root, site: options.site }, production))
|
|
218
|
+
await runWithAppContext(appCtx, () => enforceRequirements(plugins, { root: options.root, site: options.site, consentCategories: consentConfig?.categories ?? [] }, production))
|
|
218
219
|
}
|
|
219
220
|
for (const plugin of plugins) {
|
|
220
221
|
if (plugin.server !== undefined) {
|
|
@@ -224,6 +225,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
|
224
225
|
assetPrefix: options.assetPrefix,
|
|
225
226
|
site: options.site,
|
|
226
227
|
dev: options.dev,
|
|
228
|
+
devExposed: options.devExposed,
|
|
227
229
|
trustProxy,
|
|
228
230
|
trustedOrigins: options.trustedOriginsList,
|
|
229
231
|
config: readonlyRuntimeConfig,
|
package/src/server/public.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
export { action, getActionError } from './action'
|
|
4
4
|
export type { ActionContext, ActionErrorFlash, ActionOptions, ActionProtectOptions, ActionResult, ServerAction } from './action'
|
|
5
|
+
export { safeEqual } from './app-secret'
|
|
5
6
|
export type { ConsentConfig, RequestConsent } from './consent'
|
|
6
7
|
export type { CookieOptions, Cookies } from './cookies'
|
|
7
8
|
export { defineEnv, nodeEnv } from './env'
|
|
@@ -9,11 +10,11 @@ export { notFound, wantsJson } from './http'
|
|
|
9
10
|
export type { ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
|
|
10
11
|
export type { PrunelleLocals } from './index'
|
|
11
12
|
export { createServer } from './loader'
|
|
12
|
-
export { createRateLimitStore } from './rate-limit'
|
|
13
|
+
export { createRateLimitStore, rateLimitAddress } from './rate-limit'
|
|
13
14
|
export type { RateLimit, RateLimiter, RateLimitStore, RateLimitStoreOptions } from './rate-limit'
|
|
14
15
|
export { readStringFields } from './request-body'
|
|
15
|
-
export { DEFAULT_CSP, extendCsp, getClientIp, isHttpsRequest, isTrustedOrigin,
|
|
16
|
+
export { DEFAULT_CSP, extendCsp, getClientIp, isHttpsRequest, isTrustedOrigin, safeRedirect, verifyOrigin } from './security'
|
|
16
17
|
export type { CspDirectives, SecurityHeadersOptions, TrustProxy } from './security'
|
|
17
18
|
export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
|
|
18
19
|
export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
|
|
19
|
-
export { esc, escAttr, escJson, raw } from '../ssr/index'
|
|
20
|
+
export { esc, escAttr, escJson, escXml, raw } from '../ssr/index'
|
package/src/server/rate-limit.ts
CHANGED
|
@@ -14,6 +14,8 @@ export interface RateLimit<Ctx extends { ip?: string | undefined } = { ip?: stri
|
|
|
14
14
|
export interface RateLimiter {
|
|
15
15
|
/** Counts a request from `key` and returns 0; past the limit, counts nothing and returns the whole seconds until the next request would pass. */
|
|
16
16
|
hit(key: string): number
|
|
17
|
+
/** The seconds `hit(key)` would answer, counting nothing: 0 while `key` is under the limit. */
|
|
18
|
+
peek(key: string): number
|
|
17
19
|
}
|
|
18
20
|
|
|
19
21
|
export interface RateLimitStore {
|
|
@@ -57,6 +59,10 @@ export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateL
|
|
|
57
59
|
let totalKeys = 0
|
|
58
60
|
let timer: ReturnType<typeof setInterval> | undefined
|
|
59
61
|
|
|
62
|
+
function secondsUntilFree(hits: readonly number[], max: number, windowMs: number, now: number): number {
|
|
63
|
+
return Math.max(1, Math.ceil((hits[hits.length - max]! + windowMs - now) / 1000))
|
|
64
|
+
}
|
|
65
|
+
|
|
60
66
|
function trim(bucket: Bucket, hits: number[], now: number): void {
|
|
61
67
|
const cutoff = now - bucket.windowMs
|
|
62
68
|
let stale = 0
|
|
@@ -115,12 +121,20 @@ export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateL
|
|
|
115
121
|
}
|
|
116
122
|
bucket.entries.set(key, hits)
|
|
117
123
|
if (hits.length >= max)
|
|
118
|
-
return
|
|
124
|
+
return secondsUntilFree(hits, max, windowMs, now)
|
|
119
125
|
hits.push(now)
|
|
120
126
|
bucket.hitCount++
|
|
121
127
|
evict(bucket)
|
|
122
128
|
return 0
|
|
123
129
|
},
|
|
130
|
+
peek(key) {
|
|
131
|
+
const hits = bucket.entries.get(key)
|
|
132
|
+
if (hits === undefined)
|
|
133
|
+
return 0
|
|
134
|
+
const now = Date.now()
|
|
135
|
+
trim(bucket, hits, now)
|
|
136
|
+
return hits.length >= max ? secondsUntilFree(hits, max, windowMs, now) : 0
|
|
137
|
+
},
|
|
124
138
|
}
|
|
125
139
|
},
|
|
126
140
|
sweep,
|
|
@@ -139,18 +153,47 @@ export function tooManyRequests(retryAfter: number): Response {
|
|
|
139
153
|
return Response.json({ ok: false, status: 429, error: 'Too many requests' }, { status: 429, headers: { 'retry-after': String(retryAfter) } })
|
|
140
154
|
}
|
|
141
155
|
|
|
142
|
-
|
|
156
|
+
// One warning per limit declaration, so a test or a second server does not inherit another's silence.
|
|
157
|
+
const warnedMissingIp = new WeakSet<object>()
|
|
158
|
+
|
|
159
|
+
const BRACKETED_RE = /^\[([^\]]+)\](?::\d+)?$/
|
|
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
|
|
162
|
+
const HEXTET_RE = /^[\da-f]{1,4}$/i
|
|
163
|
+
|
|
164
|
+
/** 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
|
+
export function rateLimitAddress(ip: string): string {
|
|
166
|
+
const bare = BRACKETED_RE.exec(ip)?.[1] ?? IPV4_PORT_RE.exec(ip)?.[1] ?? ip
|
|
167
|
+
const addr = MAPPED_IPV4_RE.exec(bare)?.[1] ?? bare
|
|
168
|
+
const halves = addr.split('::')
|
|
169
|
+
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`
|
|
180
|
+
}
|
|
143
181
|
|
|
144
|
-
/**
|
|
145
|
-
export function
|
|
182
|
+
/** 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. */
|
|
183
|
+
export function rateLimitKey<Ctx extends { ip?: string | undefined }>(limit: RateLimit<Ctx>, ctx: Ctx): string {
|
|
146
184
|
const custom = limit.key?.(ctx)
|
|
147
185
|
if (custom !== undefined)
|
|
148
|
-
return
|
|
186
|
+
return `k:${custom}`
|
|
149
187
|
if (ctx.ip !== undefined && ctx.ip !== '')
|
|
150
|
-
return
|
|
151
|
-
if (!warnedMissingIp && nodeEnv() === 'production') {
|
|
152
|
-
warnedMissingIp
|
|
188
|
+
return `ip:${rateLimitAddress(ctx.ip)}`
|
|
189
|
+
if (!warnedMissingIp.has(limit) && nodeEnv() === 'production') {
|
|
190
|
+
warnedMissingIp.add(limit)
|
|
153
191
|
console.warn('prunelle: rateLimit ran with no client IP (ctx.ip is undefined); configure trustProxy in prunelle.config.ts or pass remoteIp to app.handle() so callers do not share one fallback bucket.')
|
|
154
192
|
}
|
|
155
|
-
return
|
|
193
|
+
return 'ip:unknown'
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Counts `ctx` against `limiter` under `rateLimitKey`; returns 0 or the seconds to wait. */
|
|
197
|
+
export function hitFor<Ctx extends { ip?: string | undefined }>(limiter: RateLimiter, limit: RateLimit<Ctx>, ctx: Ctx): number {
|
|
198
|
+
return limiter.hit(rateLimitKey(limit, ctx))
|
|
156
199
|
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import type { CompressionCache, CompressionEncoding } from './compress'
|
|
4
4
|
import { ACTION_ERROR_COOKIE } from './action'
|
|
5
5
|
import { markCompressionHandled, mergeVaryValue, pickEncoding } from './compress'
|
|
6
|
+
import { etagMatches } from './http'
|
|
6
7
|
import { hasRegionHeader } from './region'
|
|
7
8
|
|
|
8
9
|
export interface RouteCacheSpec {
|
|
@@ -30,6 +31,8 @@ export interface RouteCacheSingleflightResult {
|
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
export interface CachedRouteEntry {
|
|
34
|
+
/** The key it is stored under, so a holder can tell whether it is still the stored entry. */
|
|
35
|
+
key: string
|
|
33
36
|
html: string
|
|
34
37
|
bytes: number
|
|
35
38
|
headers: Record<string, string>
|
|
@@ -37,6 +40,8 @@ export interface CachedRouteEntry {
|
|
|
37
40
|
freshUntil: number
|
|
38
41
|
staleUntil: number
|
|
39
42
|
spec: RouteCacheSpec
|
|
43
|
+
/** Weak validator of `html`, so a revisit can get a 304. */
|
|
44
|
+
etag: string
|
|
40
45
|
compressed: Partial<Record<CompressionEncoding, Uint8Array<ArrayBuffer> | null>>
|
|
41
46
|
}
|
|
42
47
|
|
|
@@ -49,6 +54,9 @@ const DEFAULT_MAX_BYTES = 32 * 1024 * 1024
|
|
|
49
54
|
const DEFAULT_FAILURE_COOLDOWN_MS = 5_000
|
|
50
55
|
const MIN_COMPRESS_BYTES = 256
|
|
51
56
|
const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i
|
|
57
|
+
// Campaign and click identifiers: they change who is counted, never what the page shows.
|
|
58
|
+
const TRACKING_PARAM_RE = /^(?:utm_.+|gclid|gbraid|wbraid|dclid|fbclid|msclkid|mc_cid|mc_eid)$/
|
|
59
|
+
const TRACKING_SEARCH_RE = /[?&](?:utm_|gclid=|gbraid=|wbraid=|dclid=|fbclid=|msclkid=|mc_cid=|mc_eid=)/
|
|
52
60
|
|
|
53
61
|
const UNIT_MS: Record<string, number> = {
|
|
54
62
|
ms: 1,
|
|
@@ -95,6 +103,9 @@ export function formatCacheDuration(ms: number): string {
|
|
|
95
103
|
return `${ms}ms`
|
|
96
104
|
}
|
|
97
105
|
|
|
106
|
+
/** The `Cache-Control` of a cached route under an app `_middleware.ts`: the middleware may gate it, so only the server's own cache, behind the middleware, keeps the render. */
|
|
107
|
+
export const GATED_ROUTE_CACHE_CONTROL = 'private, no-cache'
|
|
108
|
+
|
|
98
109
|
/** Builds a normalized `RouteCacheSpec` with its `Cache-Control` header value. */
|
|
99
110
|
export function buildRouteCacheSpec(maxAgeMs: number, swrMs: number = maxAgeMs): RouteCacheSpec {
|
|
100
111
|
const maxAgeSec = Math.max(1, Math.round(maxAgeMs / 1000))
|
|
@@ -119,9 +130,16 @@ export function withCacheControl(headers: Record<string, string>, cacheControl:
|
|
|
119
130
|
return { ...headers, 'cache-control': cacheControl }
|
|
120
131
|
}
|
|
121
132
|
|
|
122
|
-
/** Builds a host-scoped cache key so multi-domain deployments never poison one host from another. */
|
|
133
|
+
/** Builds a host-scoped cache key so multi-domain deployments never poison one host from another; tracking parameters are left out, so a campaign link reuses the page. */
|
|
123
134
|
export function routeCacheKey(url: URL): string {
|
|
124
|
-
|
|
135
|
+
if (!TRACKING_SEARCH_RE.test(url.search))
|
|
136
|
+
return `${url.host}${url.pathname}${url.search}`
|
|
137
|
+
const kept = [...url.searchParams].filter(([name]) => !TRACKING_PARAM_RE.test(name))
|
|
138
|
+
return `${url.host}${url.pathname}${kept.length === 0 ? '' : `?${new URLSearchParams(kept)}`}`
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function weakEtagOf(html: string): string {
|
|
142
|
+
return `W/"${Bun.hash(html).toString(36)}"`
|
|
125
143
|
}
|
|
126
144
|
|
|
127
145
|
/** Whether a request is eligible to read from or populate the shared route cache. */
|
|
@@ -232,6 +250,7 @@ export class RouteCache {
|
|
|
232
250
|
this.#map.delete(key)
|
|
233
251
|
}
|
|
234
252
|
const entry: CachedRouteEntry = {
|
|
253
|
+
key,
|
|
235
254
|
html,
|
|
236
255
|
bytes: rawBytes,
|
|
237
256
|
headers,
|
|
@@ -239,6 +258,7 @@ export class RouteCache {
|
|
|
239
258
|
freshUntil: now + spec.maxAgeMs,
|
|
240
259
|
staleUntil: now + spec.maxAgeMs + spec.swrMs,
|
|
241
260
|
spec,
|
|
261
|
+
etag: weakEtagOf(html),
|
|
242
262
|
compressed: {},
|
|
243
263
|
}
|
|
244
264
|
this.#map.set(key, entry)
|
|
@@ -322,11 +342,13 @@ export class RouteCache {
|
|
|
322
342
|
age?: string,
|
|
323
343
|
serverTiming?: string,
|
|
324
344
|
): Response {
|
|
325
|
-
const headers: Record<string, string> = { ...baseHeaders, 'x-request-id': requestId }
|
|
345
|
+
const headers: Record<string, string> = { ...baseHeaders, 'x-request-id': requestId, 'etag': entry?.etag ?? weakEtagOf(html) }
|
|
326
346
|
if (age !== undefined)
|
|
327
347
|
headers.age = age
|
|
328
348
|
if (serverTiming !== undefined)
|
|
329
349
|
headers['server-timing'] = serverTiming
|
|
350
|
+
if (etagMatches(request.headers.get('if-none-match'), headers.etag!))
|
|
351
|
+
return markCompressionHandled(new Response(null, { status: 304, headers }))
|
|
330
352
|
|
|
331
353
|
if (compressCache !== undefined) {
|
|
332
354
|
headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
|
|
@@ -355,7 +377,7 @@ export class RouteCache {
|
|
|
355
377
|
if (buf === null) {
|
|
356
378
|
entry.compressed[enc] = null
|
|
357
379
|
}
|
|
358
|
-
else if (entry.bytes + buf.byteLength <= this.#maxBytes) {
|
|
380
|
+
else if (this.#map.get(entry.key) === entry && entry.bytes + buf.byteLength <= this.#maxBytes) {
|
|
359
381
|
entry.compressed[enc] = buf
|
|
360
382
|
entry.bytes += buf.byteLength
|
|
361
383
|
this.#totalBytes += buf.byteLength
|
|
@@ -19,6 +19,7 @@ import type { RequestKind } from './plugin-host'
|
|
|
19
19
|
import type { RouteCache, RouteCacheSingleflightResult, RouteCacheSpec } from './route-cache'
|
|
20
20
|
import type { FastHandler, FastStaticPageOptions } from './routing'
|
|
21
21
|
import type { TrustProxy } from './security'
|
|
22
|
+
import type { StreamTracker } from './stream'
|
|
22
23
|
import { runWithAppContext } from '../plugins/index'
|
|
23
24
|
import { createRenderContext, runWithRenderContext } from '../ssr/context'
|
|
24
25
|
import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
|
|
@@ -30,7 +31,7 @@ import { isNotFound, makeRequestContext, runChain } from './http'
|
|
|
30
31
|
import { allowedMethodsHeader, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
|
|
31
32
|
import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
|
|
32
33
|
import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
|
|
33
|
-
import { isCacheableRequest, routeCacheKey, serveCachedHit, withCacheControl } from './route-cache'
|
|
34
|
+
import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, routeCacheKey, serveCachedHit, withCacheControl } from './route-cache'
|
|
34
35
|
import { Router } from './router'
|
|
35
36
|
import { createFastStaticPageHandler, methodNotAllowed } from './routing'
|
|
36
37
|
import { styleHashesOf } from './security'
|
|
@@ -110,7 +111,8 @@ export function compileRouteTable(options: RouteTableOptions): { router: Router<
|
|
|
110
111
|
if (canFastPath)
|
|
111
112
|
fastStaticPages.set(entry.path, createFastStaticPageHandler({ ...fast, entry, mod, layouts, doc, reviveScript: manifest.reviveScript, hasIslands: entry.islandChunks.length > 0, hasLoad }))
|
|
112
113
|
|
|
113
|
-
|
|
114
|
+
const routeEntry = entry.cache !== undefined && dirMiddlewares.length > 0 ? { ...entry, cache: { ...entry.cache, cacheControl: GATED_ROUTE_CACHE_CONTROL } } : entry
|
|
115
|
+
router.add(entry.path, { entry: routeEntry, mod, layouts, dirMiddlewares, middlewares: [...middlewaresFor(entry.path), ...dirMiddlewares], dynamic, doc, headStyleHashes: headTagStyleHashes(doc.headTags) })
|
|
114
116
|
}
|
|
115
117
|
return { router, fastStaticPages }
|
|
116
118
|
}
|
|
@@ -153,6 +155,8 @@ export interface CompiledRouteRendererDeps {
|
|
|
153
155
|
applyHtmlTransforms: DocumentHooks['applyHtmlTransforms']
|
|
154
156
|
hasHtmlTransformers: boolean
|
|
155
157
|
streamTimeout: number
|
|
158
|
+
/** Where a streamed page registers, so shutdown can end it. */
|
|
159
|
+
streams?: Pick<StreamTracker, 'trackPage'> | undefined
|
|
156
160
|
compressCache: CompressionCache | undefined
|
|
157
161
|
routeCache: RouteCache | undefined
|
|
158
162
|
notifyError: NotifyError
|
|
@@ -207,7 +211,7 @@ async function renderPageDocument(
|
|
|
207
211
|
rctx.headersFlushed = true
|
|
208
212
|
endTimer(timing, 'stream', streamStart)
|
|
209
213
|
const transformChunk = deps.hasHtmlTransformers ? (html: string) => deps.applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined
|
|
210
|
-
const response = await compressedHtmlStream(streamDocument(shell, rctx, deps.streamTimeout, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId), transformChunk), 200, withRegionVary(deps.htmlHeaders(hasIslands, true, true, streamStyleHashes), hasRegions), ctx.request, deps.compressCache)
|
|
214
|
+
const response = await compressedHtmlStream(streamDocument(shell, rctx, deps.streamTimeout, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId), transformChunk, deps.streams), 200, withRegionVary(deps.htmlHeaders(hasIslands, true, true, streamStyleHashes), hasRegions), ctx.request, deps.compressCache)
|
|
211
215
|
return { kind: 'stream', response }
|
|
212
216
|
}
|
|
213
217
|
|