@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,8 +7,8 @@
7
7
 
8
8
  import type { BuildManifest, RouteManifestEntry } from '../build/index'
9
9
  import type { Html, HydrateStrategy } from '../jsx-runtime'
10
- import type { KayPlugin, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
11
- import type { ActionContext, ServerAction } from './action'
10
+ import type { KayPlugin, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
11
+ import type { ActionContext, ActionErrorFlash, ServerAction } from './action'
12
12
  import type { CookieStore } from './cookies'
13
13
  import type { EmbeddedBody, EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
14
14
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
@@ -17,28 +17,29 @@ import { loadConfig } from '../plugins/index'
17
17
  import { createRenderContext, renderCollectedHead, runWithRenderContext, streamChunkScript } from '../ssr/context'
18
18
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
19
19
  import { ACTION_ERROR_COOKIE, executeAction, isServerAction } from './action'
20
- import type { ActionErrorFlash } from './action'
21
- import { CompressionCache, compressedHtmlResponse, isCompressibleType, maybeCompressResponse, pickEncoding } from './compress'
22
- import { extractRenderedIslands, finalizeResponse, makeRequestContext, MIME } from './http'
20
+ import { CompressionCache, compressedHtmlResponse, isCompressibleType, maybeCompressResponse, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
21
+ import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, extractRenderedIslands, finalizeResponse, makeRequestContext, MIME } from './http'
23
22
  import { Router } from './router'
24
- import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, withCspHashes } from './security'
23
+ import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, resolveHstsValue, verifyOrigin, withCspHashes } from './security'
25
24
 
26
25
  export { defineConfig, definePlugin, loadConfig } from '../plugins/index'
27
- export type { BuildPluginContext, CheckPluginContext, KayConfig, KayPlugin, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
26
+ export type { BuildPluginContext, CheckPluginContext, KayConfig, KayPlugin, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI } from '../plugins/index'
28
27
  export { action, getActionError } from './action'
29
- export type { ActionContext, ActionErrorFlash, ActionResult, ServerAction } from './action'
30
- export { CompressionCache, isCompressibleType, pickEncoding } from './compress'
31
- export type { CompressionEncoding } from './compress'
28
+ export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
29
+ export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
30
+ export type { CompressionEncoding, PrecompressedEncoding } from './compress'
32
31
  export type { CookieOptions, Cookies } from './cookies'
33
32
  export { defineEnv } from './env'
33
+ export { DEFAULT_MAX_REQUEST_BODY_SIZE } from './http'
34
34
  export type { EmbeddedServerConfig, KayApp, Middleware, RequestContext, ServerOptions } from './http'
35
- export { KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
35
+ export { DEFAULT_CSP, DEFAULT_HSTS, getClientIp, isHttpsRequest, isTrustedOrigin, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
36
36
  export type { SecurityHeadersOptions } from './security'
37
37
  export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
38
38
 
39
39
  interface LoadedPageModule {
40
40
  default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
41
41
  load?: (ctx: RequestContext) => unknown | Promise<unknown>
42
+ csrf?: boolean | undefined
42
43
  GET?: (ctx: RequestContext) => Response | Promise<Response>
43
44
  POST?: (ctx: RequestContext) => Response | Promise<Response>
44
45
  PUT?: (ctx: RequestContext) => Response | Promise<Response>
@@ -67,6 +68,8 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
67
68
  const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered, prerenderedFiles = {}, lang = 'en', security, plugins = [] } = config
68
69
  const assetPrefix = (config.assetPrefix ?? '/_kay').replace(/\/$/, '')
69
70
  const trustedOrigins = config.trustedOrigins ? new Set(config.trustedOrigins) : undefined
71
+ const trustProxy = config.trustProxy === true
72
+ const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
70
73
  const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
71
74
  const htmlTransformers = plugins
72
75
  .map(p => p.transformHtml)
@@ -78,11 +81,18 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
78
81
  const [k, v] = securityEntries[i]!
79
82
  securityRecord[k] = v
80
83
  }
84
+ const nosniffEnabled = security !== false && (security?.contentTypeOptions ?? true)
85
+ const hstsValue = resolveHstsValue(security)
86
+ const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy)
87
+
81
88
  const htmlBaseHeaders: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
82
- const baseCsp = security !== false ? security?.csp : undefined
83
- const makeHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> => {
89
+ const baseCsp = resolveCspPolicy(security)
90
+ const makeHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean): Record<string, string> => {
91
+ const base = isDynamic
92
+ ? { ...htmlBaseHeaders, 'cache-control': 'private' }
93
+ : htmlBaseHeaders
84
94
  if (baseCsp === undefined || (!hasIslands && !hasSuspense))
85
- return htmlBaseHeaders
95
+ return base
86
96
  const styleHashes: string[] = []
87
97
  const scriptHashes: string[] = []
88
98
  if (hasIslands)
@@ -91,37 +101,51 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
91
101
  styleHashes.push(KAY_SUSPENSE_STYLE_HASH)
92
102
  scriptHashes.push(KAY_STREAM_SCRIPT_HASH)
93
103
  }
94
- return { ...htmlBaseHeaders, 'content-security-policy': withCspHashes(baseCsp, { styleHashes, scriptHashes }) }
104
+ return { ...base, 'content-security-policy': withCspHashes(baseCsp, { styleHashes, scriptHashes }) }
95
105
  }
96
- const htmlHeadersPlain = makeHtmlHeaders(false, false)
97
- const htmlHeadersIslands = makeHtmlHeaders(true, false)
98
- const htmlHeadersSuspense = makeHtmlHeaders(false, true)
99
- const htmlHeadersBoth = makeHtmlHeaders(true, true)
106
+ const htmlHeadersPlain = makeHtmlHeaders(false, false, false)
107
+ const htmlHeadersIslands = makeHtmlHeaders(true, false, false)
108
+ const htmlHeadersSuspense = makeHtmlHeaders(false, true, false)
109
+ const htmlHeadersBoth = makeHtmlHeaders(true, true, false)
100
110
  const selectHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> =>
101
111
  hasIslands
102
112
  ? (hasSuspense ? htmlHeadersBoth : htmlHeadersIslands)
103
113
  : (hasSuspense ? htmlHeadersSuspense : htmlHeadersPlain)
114
+
115
+ const dynHeadersPlain = makeHtmlHeaders(false, false, true)
116
+ const dynHeadersIslands = makeHtmlHeaders(true, false, true)
117
+ const dynHeadersSuspense = makeHtmlHeaders(false, true, true)
118
+ const dynHeadersBoth = makeHtmlHeaders(true, true, true)
119
+ const selectDynamicHtmlHeaders = (hasIslands: boolean, hasSuspense: boolean): Record<string, string> =>
120
+ hasIslands
121
+ ? (hasSuspense ? dynHeadersBoth : dynHeadersIslands)
122
+ : (hasSuspense ? dynHeadersSuspense : dynHeadersPlain)
123
+
104
124
  const compressEnabled = config.compress ?? (process.env.KAY_DEV !== '1')
105
125
  const compressCache = compressEnabled ? new CompressionCache() : undefined
106
126
 
107
127
  // Collect plugin server hooks (supports both sync and async plugin setup)
128
+ interface PluginRouteDef {
129
+ handler: (ctx: RequestContext) => Response | Promise<Response>
130
+ csrf: boolean
131
+ }
108
132
  const globalMiddlewares: Middleware[] = []
109
133
  const pluginRewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
110
- const pluginRouter = new Router<Map<string, (ctx: RequestContext) => Response | Promise<Response>>>()
111
- const pluginRouteEntries = new Map<string, Map<string, (ctx: RequestContext) => Response | Promise<Response>>>()
134
+ const pluginRouter = new Router<Map<string, PluginRouteDef>>()
135
+ const pluginRouteEntries = new Map<string, Map<string, PluginRouteDef>>()
112
136
 
113
137
  const pluginApi: ServerPluginAPI = {
114
138
  use(mw) {
115
139
  globalMiddlewares.push(mw)
116
140
  },
117
- route(method, path, handler) {
141
+ route(method, path, handler, options?: PluginRouteOptions) {
118
142
  let byMethod = pluginRouteEntries.get(path)
119
143
  if (byMethod === undefined) {
120
144
  byMethod = new Map()
121
145
  pluginRouteEntries.set(path, byMethod)
122
146
  pluginRouter.add(path, byMethod)
123
147
  }
124
- byMethod.set(method.toUpperCase(), handler)
148
+ byMethod.set(method.toUpperCase(), { handler, csrf: options?.csrf ?? true })
125
149
  },
126
150
  rewrite(fn) {
127
151
  pluginRewrites.push(fn)
@@ -137,9 +161,11 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
137
161
  const hasPluginRewrites = pluginRewrites.length > 0
138
162
  const hasHtmlTransformers = htmlTransformers.length > 0
139
163
 
140
- // Hashed build asset table (immutable cache + optional lazy compression)
164
+ // Hashed build asset table (immutable cache + precompressed .br/.gz sidecars + optional lazy compression)
141
165
  interface AssetEntry {
142
166
  body: EmbeddedBody
167
+ br?: EmbeddedBody | undefined
168
+ gz?: EmbeddedBody | undefined
143
169
  type: string
144
170
  compressible: boolean
145
171
  headers: Record<string, string>
@@ -147,16 +173,20 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
147
173
  }
148
174
  const assetMap = new Map<string, AssetEntry>()
149
175
  for (const [rel, body] of Object.entries(assets)) {
176
+ const brSidecar = assets[`${rel}.br`] ?? (typeof body === 'string' && existsSync(`${body}.br`) ? `${body}.br` : undefined)
177
+ const gzSidecar = assets[`${rel}.gz`] ?? (typeof body === 'string' && existsSync(`${body}.gz`) ? `${body}.gz` : undefined)
150
178
  const type = MIME[extname(rel).toLowerCase()] ?? 'application/octet-stream'
151
179
  const compressible = isCompressibleType(type)
152
180
  const headers: Record<string, string> = {
153
181
  'content-type': type,
154
182
  'cache-control': 'public, max-age=31536000, immutable',
183
+ ...(nosniffEnabled ? { 'x-content-type-options': 'nosniff' } : {}),
155
184
  }
156
- const varyHeaders: Record<string, string> = compressible && compressCache !== undefined
185
+ const canVary = (compressible && compressCache !== undefined) || brSidecar !== undefined || gzSidecar !== undefined
186
+ const varyHeaders: Record<string, string> = canVary
157
187
  ? { ...headers, vary: 'Accept-Encoding' }
158
188
  : headers
159
- assetMap.set(`${assetPrefix}/${rel}`, { body, type, compressible, headers, varyHeaders })
189
+ assetMap.set(`${assetPrefix}/${rel}`, { body, br: brSidecar, gz: gzSidecar, type, compressible, headers, varyHeaders })
160
190
  }
161
191
 
162
192
  // Static public/ file table (ETag + 304 + zero-copy Bun.file + optional lazy compression)
@@ -192,7 +222,22 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
192
222
 
193
223
  async function serveAsset(request: Request, pathname: string, asset: AssetEntry): Promise<Response> {
194
224
  if (request.method === 'HEAD')
195
- return new Response(null, { status: 200, headers: asset.varyHeaders })
225
+ return withHsts(new Response(null, { status: 200, headers: asset.varyHeaders }), request)
226
+
227
+ // Serve precompressed .br / .gz sidecars directly without on-the-fly recompression
228
+ if (compressEnabled && (asset.br !== undefined || asset.gz !== undefined)) {
229
+ const preEnc = pickPrecompressedEncoding(request.headers.get('accept-encoding'), {
230
+ br: asset.br !== undefined,
231
+ gz: asset.gz !== undefined,
232
+ })
233
+ if (preEnc !== undefined) {
234
+ const sidecar = preEnc === 'br' ? asset.br! : asset.gz!
235
+ const headers: Record<string, string> = { ...asset.headers, 'content-encoding': preEnc, 'vary': 'Accept-Encoding' }
236
+ if (headers.etag !== undefined)
237
+ headers.etag = toWeakEtag(headers.etag)
238
+ return withHsts(new Response(toResponseBody(sidecar), { status: 200, headers }), request)
239
+ }
240
+ }
196
241
 
197
242
  if (compressCache !== undefined && asset.compressible) {
198
243
  const enc = pickEncoding(request.headers.get('accept-encoding'))
@@ -205,34 +250,35 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
205
250
  : asset.body
206
251
  compressed = compressCache.compress(rawBytes, enc, `a:${pathname}`)
207
252
  if (compressed === undefined)
208
- return new Response(rawBytes, { status: 200, headers: asset.varyHeaders })
253
+ return withHsts(new Response(rawBytes, { status: 200, headers: asset.varyHeaders }), request)
209
254
  }
210
- return new Response(compressed, {
255
+ return withHsts(new Response(compressed, {
211
256
  status: 200,
212
257
  headers: { ...asset.headers, 'content-encoding': enc, vary: 'Accept-Encoding' },
213
- })
258
+ }), request)
214
259
  }
215
260
  }
216
261
 
217
- return new Response(toResponseBody(asset.body), { status: 200, headers: asset.varyHeaders })
262
+ return withHsts(new Response(toResponseBody(asset.body), { status: 200, headers: asset.varyHeaders }), request)
218
263
  }
219
264
 
220
265
  async function servePublic(request: Request, pathname: string, pub: PublicEntry): Promise<Response> {
221
266
  const cacheControl = process.env.KAY_DEV === '1' ? 'no-cache' : 'public, max-age=3600'
222
267
  const hasVary = pub.compressible && compressCache !== undefined
268
+ const nosniffHeader: Record<string, string> = nosniffEnabled ? { 'x-content-type-options': 'nosniff' } : {}
223
269
  if (request.headers.get('if-none-match') === pub.etag) {
224
270
  const h: Record<string, string> = hasVary
225
- ? { 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding' }
226
- : { 'etag': pub.etag, 'cache-control': cacheControl }
227
- return new Response(null, { status: 304, headers: h })
271
+ ? { 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding', ...nosniffHeader }
272
+ : { 'etag': pub.etag, 'cache-control': cacheControl, ...nosniffHeader }
273
+ return withHsts(new Response(null, { status: 304, headers: h }), request)
228
274
  }
229
275
 
230
276
  const baseHeaders: Record<string, string> = hasVary
231
- ? { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding' }
232
- : { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl }
277
+ ? { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl, 'vary': 'Accept-Encoding', ...nosniffHeader }
278
+ : { 'content-type': pub.type, 'etag': pub.etag, 'cache-control': cacheControl, ...nosniffHeader }
233
279
 
234
280
  if (request.method === 'HEAD')
235
- return new Response(null, { status: 200, headers: baseHeaders })
281
+ return withHsts(new Response(null, { status: 200, headers: baseHeaders }), request)
236
282
 
237
283
  if (hasVary) {
238
284
  const enc = pickEncoding(request.headers.get('accept-encoding'))
@@ -245,16 +291,16 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
245
291
  : pub.body
246
292
  compressed = compressCache.compress(rawBytes, enc, staticKey)
247
293
  if (compressed === undefined)
248
- return new Response(rawBytes, { status: 200, headers: baseHeaders })
294
+ return withHsts(new Response(rawBytes, { status: 200, headers: baseHeaders }), request)
249
295
  }
250
- return new Response(compressed, {
296
+ return withHsts(new Response(compressed, {
251
297
  status: 200,
252
- headers: { ...baseHeaders, 'content-encoding': enc },
253
- })
298
+ headers: { ...baseHeaders, 'etag': toWeakEtag(pub.etag), 'content-encoding': enc },
299
+ }), request)
254
300
  }
255
301
  }
256
302
 
257
- return new Response(toResponseBody(pub.body), { status: 200, headers: baseHeaders })
303
+ return withHsts(new Response(toResponseBody(pub.body), { status: 200, headers: baseHeaders }), request)
258
304
  }
259
305
 
260
306
  async function servePrerendered(request: Request, pathname: string, pre: PrerenderEntry): Promise<Response> {
@@ -264,7 +310,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
264
310
  : base
265
311
 
266
312
  if (request.method === 'HEAD')
267
- return new Response(null, { status: 200, headers })
313
+ return withHsts(new Response(null, { status: 200, headers }), request)
268
314
 
269
315
  if (compressCache !== undefined) {
270
316
  const enc = pickEncoding(request.headers.get('accept-encoding'))
@@ -277,17 +323,17 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
277
323
  : textEncoder.encode(pre.html)
278
324
  compressed = compressCache.compress(rawBytes, enc, staticKey)
279
325
  if (compressed === undefined)
280
- return new Response(rawBytes, { status: 200, headers })
326
+ return withHsts(new Response(rawBytes, { status: 200, headers }), request)
281
327
  }
282
- return new Response(compressed, {
328
+ return withHsts(new Response(compressed, {
283
329
  status: 200,
284
330
  headers: { ...headers, 'content-encoding': enc },
285
- })
331
+ }), request)
286
332
  }
287
333
  }
288
334
 
289
335
  const body = pre.kind === 'file' ? Bun.file(pre.path) : pre.html
290
- return new Response(body, { status: 200, headers })
336
+ return withHsts(new Response(body, { status: 200, headers }), request)
291
337
  }
292
338
 
293
339
  // Register server actions and assign their live URLs
@@ -333,13 +379,13 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
333
379
  mod: LoadedPageModule
334
380
  layouts: LoadedLayoutModule[]
335
381
  middlewares: Middleware[]
336
- fastHandler: ((req: Request) => Response | Promise<Response>) | undefined
382
+ fastHandler: ((req: Request, remoteIp?: string) => Response | Promise<Response>) | undefined
337
383
  docPrefix: string
338
384
  docSuffix: string
339
385
  }
340
386
 
341
387
  const router = new Router<CompiledRoute>()
342
- const fastStaticPages = new Map<string, (req: Request) => Response | Promise<Response>>()
388
+ const fastStaticPages = new Map<string, (req: Request, remoteIp?: string) => Response | Promise<Response>>()
343
389
 
344
390
  for (const entry of manifest.routes) {
345
391
  const mod = modules[entry.file] as LoadedPageModule
@@ -377,20 +423,20 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
377
423
  && typeof mod.default === 'function'
378
424
  && mod.GET === undefined
379
425
 
380
- let fastHandler: ((req: Request) => Response | Promise<Response>) | undefined
426
+ let fastHandler: ((req: Request, remoteIp?: string) => Response | Promise<Response>) | undefined
381
427
  if (canFastPath) {
382
428
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
383
- const fastHeaders = selectHtmlHeaders(hasIslands, false)
429
+ const fastHeaders = selectDynamicHtmlHeaders(hasIslands, false)
384
430
 
385
- fastHandler = (request: Request): Response | Promise<Response> => {
431
+ fastHandler = (request: Request, remoteIp?: string): Response | Promise<Response> => {
386
432
  const handleErr = (error: unknown): Promise<Response> => {
387
433
  notifyError(error, request, 'route')
388
- return renderError(error, makeRequestContext(request, {}).cookieStore, new URL(request.url))
434
+ return renderError(error, makeRequestContext(request, {}, { trustProxy, remoteIp }).cookieStore, new URL(request.url), request)
389
435
  }
390
436
  try {
391
437
  const reqUrl = new URL(request.url)
392
438
  const respondHtml = (body: string): Response =>
393
- compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache)
439
+ withHsts(compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache), request)
394
440
 
395
441
  const wrapLayouts = (inner: string): Response | Promise<Response> => {
396
442
  if (layouts.length === 0)
@@ -433,13 +479,13 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
433
479
  }
434
480
 
435
481
  if (entry.hasLoad && typeof mod.load === 'function') {
436
- const { ctx, cookieStore } = makeRequestContext(request, {})
482
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp })
437
483
  const finish = (res: Response | Promise<Response>): Response | Promise<Response> => {
438
484
  if (!cookieStore.hasChanges)
439
- return res
485
+ return res instanceof Promise ? res.then(r => withHsts(r, request), handleErr) : withHsts(res, request)
440
486
  if (res instanceof Promise)
441
- return res.then(r => finalizeResponse(r, cookieStore, securityEntries), handleErr)
442
- return finalizeResponse(res, cookieStore, securityEntries)
487
+ return res.then(r => withHsts(finalizeResponse(r, cookieStore, securityEntries), request), handleErr)
488
+ return withHsts(finalizeResponse(res, cookieStore, securityEntries), request)
443
489
  }
444
490
  const loaded = mod.load(ctx)
445
491
  if (loaded instanceof Promise) {
@@ -464,20 +510,31 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
464
510
  router.add(entry.path, { entry, mod, layouts, middlewares, fastHandler, docPrefix, docSuffix })
465
511
  }
466
512
 
467
- async function renderCompiledRoute(route: CompiledRoute, ctx: RequestContext): Promise<Response> {
513
+ async function renderCompiledRoute(
514
+ route: CompiledRoute,
515
+ ctx: RequestContext,
516
+ disableTimeout?: () => void,
517
+ ): Promise<Response> {
468
518
  const { entry, mod, layouts } = route
469
519
 
470
520
  // Serve prerendered HTML after middlewares have passed (when route had middlewares)
471
521
  if (ctx.request.method === 'GET' || ctx.request.method === 'HEAD') {
472
- const pre = prerenderedMap.get(ctx.url.pathname)
522
+ const rawPath = ctx.url.pathname
523
+ const normPath = rawPath.length > 1 && rawPath.endsWith('/') ? rawPath.slice(0, -1) : rawPath
524
+ const pre = prerenderedMap.get(rawPath) ?? prerenderedMap.get(normPath)
473
525
  if (pre !== undefined)
474
- return servePrerendered(ctx.request, ctx.url.pathname, pre)
526
+ return servePrerendered(ctx.request, rawPath, pre)
527
+ // Prerendered dynamic route: unlisted param returns 404 (never falls back to SSR)
528
+ if (entry.prerender === true && entry.prerendered !== undefined && (entry.path.includes(':') || entry.path.includes('*')))
529
+ return buildNotFoundResponse(ctx.url)
475
530
  }
476
531
 
477
532
  // API route (.ts exporting GET/POST/etc.)
478
533
  const methodHandler = mod[ctx.request.method]
479
534
  if (typeof methodHandler === 'function') {
480
535
  const res = await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
536
+ if ((res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream'))
537
+ disableTimeout?.()
481
538
  return maybeCompressResponse(res, ctx.request, compressCache)
482
539
  }
483
540
 
@@ -527,6 +584,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
527
584
 
528
585
  // Streaming SSR path when <Suspense> boundaries are pending (never buffered for compression)!
529
586
  if (rctx.pending.length > 0) {
587
+ disableTimeout?.()
530
588
  const shell = renderDocument({
531
589
  body: '\0',
532
590
  head: collectedHead,
@@ -557,7 +615,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
557
615
  },
558
616
  })
559
617
 
560
- return new Response(stream, { status: 200, headers: { ...selectHtmlHeaders(hasIslands, true) } })
618
+ return new Response(stream, { status: 200, headers: { ...selectDynamicHtmlHeaders(hasIslands, true) } })
561
619
  }
562
620
 
563
621
  let html = renderDocument({
@@ -575,201 +633,299 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
575
633
  for (let i = 0; i < htmlTransformers.length; i++)
576
634
  html = await htmlTransformers[i]!(html, ctx)
577
635
 
578
- return compressedHtmlResponse(html, 200, selectHtmlHeaders(hasIslands, false), ctx.request, compressCache)
636
+ return compressedHtmlResponse(html, 200, selectDynamicHtmlHeaders(hasIslands, false), ctx.request, compressCache)
579
637
  }
580
638
 
581
639
  const rootLayoutFile = manifest.routes.find(r => r.layouts.length > 0)?.layouts[0]
582
640
  const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LoadedLayoutModule | undefined : undefined
583
641
  const fallbackStyles = manifest.globalStyles ?? manifest.styles
584
642
 
585
- async function renderError(error: unknown, cookieStore: CookieStore, url?: URL): Promise<Response> {
643
+ async function buildErrorResponse(error: unknown, url?: URL): Promise<Response> {
586
644
  if (errorMod !== undefined) {
587
- const rctx = createRenderContext()
588
- const body = await runWithRenderContext(rctx, async () => {
589
- let inner = ssrChild(await errorMod.default({ error }) as Html)
590
- if (rootLayoutMod !== undefined)
591
- inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/500'), params: {}, locals: {} }) as Html)
592
- return inner
593
- })
594
- const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
595
- return finalizeResponse(new Response(html, { status: 500, headers: { 'content-type': 'text/html; charset=utf-8' } }), cookieStore, securityEntries)
645
+ try {
646
+ const rctx = createRenderContext()
647
+ const body = await runWithRenderContext(rctx, async () => {
648
+ let inner = ssrChild(await errorMod.default({ error }) as Html)
649
+ if (rootLayoutMod !== undefined)
650
+ inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/500'), params: {}, locals: {} }) as Html)
651
+ return inner
652
+ })
653
+ const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
654
+ return new Response(html, { status: 500, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'private' } })
655
+ }
656
+ catch {}
596
657
  }
597
- return finalizeResponse(new Response('Internal Server Error', { status: 500 }), cookieStore, securityEntries)
658
+ return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
659
+ }
660
+
661
+ async function renderError(error: unknown, cookieStore: CookieStore, url?: URL, request?: Request): Promise<Response> {
662
+ const base = finalizeResponse(await buildErrorResponse(error, url), cookieStore, securityEntries)
663
+ return request !== undefined ? withHsts(base, request) : base
598
664
  }
599
665
 
600
- async function renderNotFound(cookieStore: CookieStore, url?: URL): Promise<Response> {
666
+ async function buildNotFoundResponse(url?: URL): Promise<Response> {
601
667
  const notFoundFn = notFoundMod?.default
602
668
  if (notFoundFn !== undefined) {
603
- const rctx = createRenderContext()
604
- const body = await runWithRenderContext(rctx, async () => {
605
- let inner = ssrChild(await notFoundFn({}) as Html)
606
- if (rootLayoutMod !== undefined)
607
- inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/404'), params: {}, locals: {} }) as Html)
608
- return inner
609
- })
610
- const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
611
- return finalizeResponse(new Response(html, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }), cookieStore, securityEntries)
612
- }
613
- return finalizeResponse(new Response('Not Found', { status: 404 }), cookieStore, securityEntries)
614
- }
615
-
616
- async function handle(request: Request): Promise<Response> {
617
- const pathname = new URL(request.url).pathname
618
-
619
- // 1. Static client assets
620
- if (request.method === 'GET' || request.method === 'HEAD') {
621
- const asset = assetMap.get(pathname)
622
- if (asset !== undefined)
623
- return serveAsset(request, pathname, asset)
624
- }
625
-
626
- // 1b. Static public/ files (no-cache in dev so edits/plugins never get stuck in browser cache)
627
- if (request.method === 'GET' || request.method === 'HEAD') {
628
- const pub = publicMap.get(pathname)
629
- if (pub !== undefined)
630
- return servePublic(request, pathname, pub)
631
- }
632
-
633
- // 2. Server actions (POST /_kay/action/<id>): global plugin middlewares, then the _middleware.ts chain of the action's folder
634
- if (request.method === 'POST') {
635
- const handler = actionHandlers.get(pathname)
636
- if (handler !== undefined) {
637
- const { act, middlewares } = handler
638
- const { ctx, cookieStore } = makeRequestContext(request, {})
639
- const runAction = async (): Promise<Response> => {
640
- const actionCtx: ActionContext = {
641
- request: ctx.request,
642
- url: ctx.url,
643
- params: ctx.params,
644
- cookies: ctx.cookies,
645
- locals: ctx.locals,
646
- redirect: ctx.redirect,
647
- deny: ctx.deny,
669
+ try {
670
+ const rctx = createRenderContext()
671
+ const body = await runWithRenderContext(rctx, async () => {
672
+ let inner = ssrChild(await notFoundFn({}) as Html)
673
+ if (rootLayoutMod !== undefined)
674
+ inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: url ?? new URL('http://localhost/404'), params: {}, locals: {} }) as Html)
675
+ return inner
676
+ })
677
+ const html = renderDocument({ body, head: renderCollectedHead(rctx), headTags: manifest.headTags, styles: fallbackStyles, runtimeScript: manifest.runtimeScript, alwaysLoadRuntime, lang })
678
+ return new Response(html, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'private' } })
679
+ }
680
+ catch {}
681
+ }
682
+ return new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } })
683
+ }
684
+
685
+ async function renderNotFound(cookieStore: CookieStore, url?: URL, request?: Request): Promise<Response> {
686
+ const base = finalizeResponse(await buildNotFoundResponse(url), cookieStore, securityEntries)
687
+ return request !== undefined ? withHsts(base, request) : base
688
+ }
689
+
690
+ function requestWantsJson(request: Request): boolean {
691
+ return (request.headers.get('accept') ?? '').includes('application/json')
692
+ || (request.headers.get('content-type') ?? '').includes('application/json')
693
+ }
694
+
695
+ async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void): Promise<Response> {
696
+ try {
697
+ const pathname = new URL(request.url).pathname
698
+
699
+ // 1. Static client assets
700
+ if (request.method === 'GET' || request.method === 'HEAD') {
701
+ const asset = assetMap.get(pathname)
702
+ if (asset !== undefined)
703
+ return serveAsset(request, pathname, asset)
704
+ }
705
+
706
+ // 1b. Static public/ files (no-cache in dev so edits/plugins never get stuck in browser cache)
707
+ if (request.method === 'GET' || request.method === 'HEAD') {
708
+ const pub = publicMap.get(pathname)
709
+ if (pub !== undefined)
710
+ return servePublic(request, pathname, pub)
711
+ }
712
+
713
+ // Enforce request body size cap before actions, plugin routes, and API routes
714
+ const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
715
+ if (!bounded.ok) {
716
+ const res413 = requestWantsJson(request)
717
+ ? Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
718
+ : new Response('Payload Too Large', { status: 413, headers: { 'content-type': 'text/plain; charset=utf-8' } })
719
+ return withHsts(finalizeResponse(res413, makeRequestContext(request, {}, { trustProxy, remoteIp }).cookieStore, securityEntries), request)
720
+ }
721
+ const req = bounded.request
722
+
723
+ // 2. Server actions (POST /_kay/action/<id>): global plugin middlewares, then the _middleware.ts chain of the action's folder
724
+ if (req.method === 'POST') {
725
+ const handler = actionHandlers.get(pathname)
726
+ if (handler !== undefined) {
727
+ const { act, middlewares } = handler
728
+ const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp })
729
+ const runAction = async (): Promise<Response> => {
730
+ const actionCtx: ActionContext = {
731
+ request: ctx.request,
732
+ url: ctx.url,
733
+ params: ctx.params,
734
+ cookies: ctx.cookies,
735
+ locals: ctx.locals,
736
+ ip: ctx.ip,
737
+ redirect: ctx.redirect,
738
+ deny: ctx.deny,
739
+ }
740
+ return executeAction(act, req, actionCtx, trustedOrigins, trustProxy, maxRequestBodySize)
741
+ }
742
+ let index = -1
743
+ const dispatch = async (i: number): Promise<Response> => {
744
+ if (i <= index)
745
+ throw new Error('kay: middleware called next() multiple times')
746
+ index = i
747
+ if (i < middlewares.length)
748
+ return middlewares[i]!(ctx, () => dispatch(i + 1))
749
+ return runAction()
750
+ }
751
+ try {
752
+ const res = await dispatch(0)
753
+ return withHsts(finalizeResponse(res, cookieStore, securityEntries), req)
754
+ }
755
+ catch (error) {
756
+ notifyError(error, req, 'action')
757
+ if (requestWantsJson(req)) {
758
+ return withHsts(
759
+ finalizeResponse(
760
+ Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }),
761
+ cookieStore,
762
+ securityEntries,
763
+ ),
764
+ req,
765
+ )
766
+ }
767
+ return renderError(error, cookieStore, ctx.url, req)
648
768
  }
649
- return executeAction(act, request, actionCtx, trustedOrigins)
650
- }
651
- let index = -1
652
- const dispatch = async (i: number): Promise<Response> => {
653
- if (i <= index)
654
- throw new Error('kay: middleware called next() multiple times')
655
- index = i
656
- if (i < middlewares.length)
657
- return middlewares[i]!(ctx, () => dispatch(i + 1))
658
- return runAction()
659
- }
660
- try {
661
- const res = await dispatch(0)
662
- return finalizeResponse(res, cookieStore, securityEntries)
663
- }
664
- catch (error) {
665
- notifyError(error, request, 'action')
666
- return renderError(error, cookieStore, ctx.url)
667
769
  }
668
770
  }
669
- }
670
771
 
671
- const hasActionErrorFlash = (request.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
772
+ const hasActionErrorFlash = (req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
672
773
 
673
- // 3. Prerendered static HTML (safe even when plugins add routes or build-time transformHtml!)
674
- if (!hasActionErrorFlash && (request.method === 'GET' || request.method === 'HEAD')) {
675
- const pre = fastPrerenderedMap.get(pathname)
676
- if (pre !== undefined)
677
- return servePrerendered(request, pathname, pre)
678
- }
774
+ // 3. Prerendered static HTML (safe even when plugins add routes or build-time transformHtml!)
775
+ if (!hasActionErrorFlash && (req.method === 'GET' || req.method === 'HEAD')) {
776
+ const pre = fastPrerenderedMap.get(pathname)
777
+ if (pre !== undefined)
778
+ return servePrerendered(req, pathname, pre)
779
+ }
679
780
 
680
- // 4. Ultra-fast static route path
681
- if (!hasActionErrorFlash && (request.method === 'GET' || request.method === 'HEAD')) {
682
- const fast = fastStaticPages.get(pathname)
683
- if (fast !== undefined)
684
- return fast(request)
685
- }
781
+ // 4. Ultra-fast static route path
782
+ if (!hasActionErrorFlash && (req.method === 'GET' || req.method === 'HEAD')) {
783
+ const fast = fastStaticPages.get(pathname)
784
+ if (fast !== undefined)
785
+ return fast(req, remoteIp)
786
+ }
686
787
 
687
- // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
688
- const { ctx, cookieStore } = makeRequestContext(request, {})
788
+ // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
789
+ const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp })
689
790
 
690
- // Hydrate & clear one-shot progressive form validation flash cookie
691
- if (hasActionErrorFlash && request.method === 'GET') {
692
- const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
693
- if (rawFlash !== undefined) {
694
- try {
695
- ctx.locals.actionError = JSON.parse(rawFlash) as ActionErrorFlash
791
+ // Hydrate & clear one-shot progressive form validation flash cookie
792
+ if (hasActionErrorFlash && req.method === 'GET') {
793
+ const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
794
+ if (rawFlash !== undefined) {
795
+ try {
796
+ ctx.locals.actionError = JSON.parse(rawFlash) as ActionErrorFlash
797
+ }
798
+ catch {}
799
+ ctx.cookies.delete(ACTION_ERROR_COOKIE)
696
800
  }
697
- catch {}
698
- ctx.cookies.delete(ACTION_ERROR_COOKIE)
699
801
  }
700
- }
701
802
 
702
- // Apply plugin URL rewrites (e.g. @kayjs/i18n stripping /fr prefix and setting ctx.locals.locale)
703
- let effectivePath = pathname
704
- for (let i = 0; i < pluginRewrites.length; i++) {
705
- const nextPath = pluginRewrites[i]!(effectivePath, ctx)
706
- if (nextPath !== undefined)
707
- effectivePath = nextPath
708
- }
803
+ // Apply plugin URL rewrites (e.g. @kayjs/i18n stripping /fr prefix and setting ctx.locals.locale)
804
+ let effectivePath = pathname
805
+ for (let i = 0; i < pluginRewrites.length; i++) {
806
+ const nextPath = pluginRewrites[i]!(effectivePath, ctx)
807
+ if (nextPath !== undefined)
808
+ effectivePath = nextPath
809
+ }
709
810
 
710
- // Check custom plugin routes first (e.g. GET /sitemap.xml, POST /auth/callback, GET /api/board)
711
- // Run global plugin middlewares so ctx.locals (e.g. auth user/session) is available in plugin routes too.
712
- const pluginMatch = pluginRouter.match(effectivePath)
713
- if (pluginMatch !== undefined) {
714
- const methodHandler = pluginMatch.data.get(request.method.toUpperCase()) ?? pluginMatch.data.get('ALL')
715
- if (methodHandler !== undefined) {
716
- ctx.params = pluginMatch.params
717
- let res: Response
718
- try {
719
- if (globalMiddlewares.length === 0) {
720
- res = await methodHandler(ctx)
811
+ // Check custom plugin routes first (e.g. GET /sitemap.xml, POST /auth/callback, GET /api/board)
812
+ // Run global plugin middlewares so ctx.locals (e.g. auth user/session) is available in plugin routes too.
813
+ const pluginMatch = pluginRouter.match(effectivePath)
814
+ if (pluginMatch !== undefined) {
815
+ const routeDef = pluginMatch.data.get(req.method.toUpperCase()) ?? pluginMatch.data.get('ALL')
816
+ if (routeDef !== undefined) {
817
+ if (routeDef.csrf) {
818
+ const originCheck = verifyOrigin(req, trustedOrigins, trustProxy)
819
+ if (!originCheck.ok) {
820
+ return withHsts(
821
+ finalizeResponse(
822
+ Response.json({ ok: false, status: 403, error: originCheck.reason }, { status: 403 }),
823
+ cookieStore,
824
+ securityEntries,
825
+ ),
826
+ req,
827
+ )
828
+ }
721
829
  }
722
- else {
723
- let index = -1
724
- const dispatch = async (i: number): Promise<Response> => {
725
- if (i <= index)
726
- throw new Error('kay: middleware called next() multiple times')
727
- index = i
728
- if (i < globalMiddlewares.length)
729
- return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
730
- return methodHandler(ctx)
830
+ ctx.params = pluginMatch.params
831
+ let res: Response
832
+ try {
833
+ if (globalMiddlewares.length === 0) {
834
+ res = await routeDef.handler(ctx)
835
+ }
836
+ else {
837
+ let index = -1
838
+ const dispatch = async (i: number): Promise<Response> => {
839
+ if (i <= index)
840
+ throw new Error('kay: middleware called next() multiple times')
841
+ index = i
842
+ if (i < globalMiddlewares.length)
843
+ return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
844
+ return routeDef.handler(ctx)
845
+ }
846
+ res = await dispatch(0)
731
847
  }
732
- res = await dispatch(0)
848
+ if ((res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream'))
849
+ disableTimeout?.()
850
+ return withHsts(finalizeResponse(await maybeCompressResponse(res, req, compressCache), cookieStore, securityEntries), req)
851
+ }
852
+ catch (error) {
853
+ notifyError(error, req, 'plugin')
854
+ return renderError(error, cookieStore, ctx.url, req)
733
855
  }
734
- return finalizeResponse(await maybeCompressResponse(res, request, compressCache), cookieStore, securityEntries)
735
- }
736
- catch (error) {
737
- notifyError(error, request, 'plugin')
738
- return renderError(error, cookieStore, ctx.url)
739
856
  }
740
857
  }
741
- }
742
858
 
743
- const matched = router.match(effectivePath)
744
- if (matched === undefined)
745
- return renderNotFound(cookieStore, ctx.url)
859
+ const matched = router.match(effectivePath)
860
+ if (matched === undefined)
861
+ return renderNotFound(cookieStore, ctx.url, req)
862
+
863
+ ctx.params = matched.params
864
+ const route = matched.data
865
+
866
+ // CSRF verification for file-based API routes on unsafe methods (opt out via `export const csrf = false`)
867
+ if (typeof route.mod[req.method] === 'function' && route.mod.csrf !== false) {
868
+ const originCheck = verifyOrigin(req, trustedOrigins, trustProxy)
869
+ if (!originCheck.ok) {
870
+ return withHsts(
871
+ finalizeResponse(
872
+ Response.json({ ok: false, status: 403, error: originCheck.reason }, { status: 403 }),
873
+ cookieStore,
874
+ securityEntries,
875
+ ),
876
+ req,
877
+ )
878
+ }
879
+ }
746
880
 
747
- ctx.params = matched.params
748
- const route = matched.data
749
- const allMiddlewares = globalMiddlewares.length > 0
750
- ? [...globalMiddlewares, ...route.middlewares]
751
- : route.middlewares
881
+ const allMiddlewares = globalMiddlewares.length > 0
882
+ ? [...globalMiddlewares, ...route.middlewares]
883
+ : route.middlewares
752
884
 
753
- try {
754
- let index = -1
755
- const dispatch = async (i: number): Promise<Response> => {
756
- if (i <= index)
757
- throw new Error('kay: middleware called next() multiple times')
758
- index = i
759
- if (i < allMiddlewares.length)
760
- return allMiddlewares[i]!(ctx, () => dispatch(i + 1))
761
- return renderCompiledRoute(route, ctx)
885
+ try {
886
+ let index = -1
887
+ const dispatch = async (i: number): Promise<Response> => {
888
+ if (i <= index)
889
+ throw new Error('kay: middleware called next() multiple times')
890
+ index = i
891
+ if (i < allMiddlewares.length)
892
+ return allMiddlewares[i]!(ctx, () => dispatch(i + 1))
893
+ return renderCompiledRoute(route, ctx, disableTimeout)
894
+ }
895
+ const res = await dispatch(0)
896
+ if ((res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream'))
897
+ disableTimeout?.()
898
+ return withHsts(finalizeResponse(res, cookieStore, securityEntries), req)
899
+ }
900
+ catch (error) {
901
+ notifyError(error, req, 'route')
902
+ return renderError(error, cookieStore, ctx.url, req)
762
903
  }
763
- const res = await dispatch(0)
764
- return finalizeResponse(res, cookieStore, securityEntries)
765
904
  }
766
905
  catch (error) {
767
906
  notifyError(error, request, 'route')
768
- return renderError(error, cookieStore, ctx.url)
907
+ return withHsts(
908
+ new Response('Internal Server Error', {
909
+ status: 500,
910
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
911
+ }),
912
+ request,
913
+ )
769
914
  }
770
915
  }
771
916
 
772
- function serve(port = 3000, hostname?: string) {
917
+ function handle(request: Request, remoteIp?: string): Promise<Response> {
918
+ return handleInternal(request, remoteIp)
919
+ }
920
+
921
+ function serve(port = 3000, hostname = '127.0.0.1') {
922
+ let srvRef: ReturnType<typeof Bun.serve> | undefined
923
+ const fetchReq = (req: Request) => handleInternal(
924
+ req,
925
+ srvRef?.requestIP(req)?.address,
926
+ srvRef ? () => srvRef!.timeout(req, 0) : undefined,
927
+ )
928
+
773
929
  const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
774
930
 
775
931
  for (const [path, asset] of assetMap)
@@ -784,25 +940,35 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
784
940
  if (!(path in routes)) {
785
941
  routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
786
942
  ? servePrerendered(req, path, pre)
787
- : handle(req)
943
+ : fetchReq(req)
788
944
  }
789
945
  }
790
946
 
791
947
  for (const [path, handler] of fastStaticPages) {
792
948
  if (!(path in routes)) {
793
949
  routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
794
- ? handler(req)
795
- : handle(req)
950
+ ? handler(req, srvRef?.requestIP(req)?.address)
951
+ : fetchReq(req)
796
952
  }
797
953
  }
798
954
 
799
- return Bun.serve({
955
+ srvRef = Bun.serve({
800
956
  port,
801
- ...(hostname ? { hostname } : {}),
802
- idleTimeout: 0,
957
+ hostname,
958
+ idleTimeout: 30,
959
+ maxRequestBodySize,
960
+ development: false,
803
961
  routes,
804
- fetch: handle,
962
+ fetch: fetchReq,
963
+ error(err) {
964
+ notifyError(err, new Request('http://localhost/'), 'route')
965
+ return new Response('Internal Server Error', {
966
+ status: 500,
967
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
968
+ })
969
+ },
805
970
  })
971
+ return srvRef
806
972
  }
807
973
 
808
974
  return { handle, serve }
@@ -813,10 +979,16 @@ function createStaticDirServer(
813
979
  assetPrefix: string,
814
980
  securityEntries: readonly [string, string][],
815
981
  compressEnabled: boolean,
982
+ hstsValue: string | undefined,
983
+ trustProxy: boolean,
816
984
  ): KayApp {
817
985
  const cleanPrefix = `${assetPrefix.replace(/\/$/, '')}/`
818
986
  const absRoot = resolve(outDir)
819
987
  const compressCache = compressEnabled ? new CompressionCache() : undefined
988
+ const securityRecord: Record<string, string> = {}
989
+ for (let i = 0; i < securityEntries.length; i++)
990
+ securityRecord[securityEntries[i]![0]] = securityEntries[i]![1]
991
+ const withHsts = (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy)
820
992
 
821
993
  function resolveStaticFile(pathname: string): string | undefined {
822
994
  let decoded: string
@@ -849,7 +1021,7 @@ function createStaticDirServer(
849
1021
 
850
1022
  const handle = async (req: Request): Promise<Response> => {
851
1023
  if (req.method !== 'GET' && req.method !== 'HEAD')
852
- return new Response('Method Not Allowed', { status: 405 })
1024
+ return withHsts(new Response('Method Not Allowed', { status: 405, headers: initHeaders() }), req)
853
1025
 
854
1026
  const url = new URL(req.url)
855
1027
  const filePath = resolveStaticFile(url.pathname)
@@ -858,9 +1030,9 @@ function createStaticDirServer(
858
1030
  if (existsSync(notFoundPath) && statSync(notFoundPath).isFile()) {
859
1031
  const headers = initHeaders()
860
1032
  headers.set('content-type', 'text/html; charset=utf-8')
861
- return new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers })
1033
+ return withHsts(new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers }), req)
862
1034
  }
863
- return new Response('Not Found', { status: 404 })
1035
+ return withHsts(new Response('Not Found', { status: 404, headers: initHeaders() }), req)
864
1036
  }
865
1037
 
866
1038
  const st = statSync(filePath)
@@ -873,18 +1045,45 @@ function createStaticDirServer(
873
1045
  headers.set('etag', etag)
874
1046
 
875
1047
  if (req.headers.get('if-none-match') === etag)
876
- return new Response(null, { status: 304, headers })
1048
+ return withHsts(new Response(null, { status: 304, headers }), req)
1049
+
1050
+ if (compressEnabled && req.method !== 'HEAD') {
1051
+ const hasBr = existsSync(`${filePath}.br`)
1052
+ const hasGz = existsSync(`${filePath}.gz`)
1053
+ if (hasBr || hasGz) {
1054
+ const preEnc = pickPrecompressedEncoding(req.headers.get('accept-encoding'), { br: hasBr, gz: hasGz })
1055
+ if (preEnc !== undefined) {
1056
+ headers.set('content-encoding', preEnc)
1057
+ headers.set('vary', 'Accept-Encoding')
1058
+ headers.set('etag', toWeakEtag(etag))
1059
+ return withHsts(new Response(Bun.file(`${filePath}.${preEnc === 'br' ? 'br' : 'gz'}`), { status: 200, headers }), req)
1060
+ }
1061
+ }
1062
+ }
877
1063
 
1064
+ headers.set('content-length', String(st.size))
878
1065
  const res = new Response(req.method === 'HEAD' ? null : Bun.file(filePath), { status: 200, headers })
879
1066
  if (!compressEnabled || req.method === 'HEAD')
880
- return res
881
- return maybeCompressResponse(res, req, compressCache)
1067
+ return withHsts(res, req)
1068
+ return withHsts(await maybeCompressResponse(res, req, compressCache), req)
882
1069
  }
883
1070
 
884
1071
  return {
885
1072
  handle,
886
- serve(port = 3000) {
887
- return Bun.serve({ port, fetch: handle })
1073
+ serve(port = 3000, hostname = '127.0.0.1') {
1074
+ return Bun.serve({
1075
+ port,
1076
+ hostname,
1077
+ idleTimeout: 30,
1078
+ development: false,
1079
+ fetch: handle,
1080
+ error() {
1081
+ return new Response('Internal Server Error', {
1082
+ status: 500,
1083
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
1084
+ })
1085
+ },
1086
+ })
888
1087
  },
889
1088
  }
890
1089
  }
@@ -896,16 +1095,20 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
896
1095
  const outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
897
1096
  const clientDir = join(outDir, 'client')
898
1097
  const manifestPath = join(outDir, 'manifest.json')
1098
+ const securityOpt = options.security ?? fileConfig.security
1099
+ const trustProxy = (options.trustProxy ?? fileConfig.trustProxy) === true
1100
+ const maxRequestBodySize = options.maxRequestBodySize ?? fileConfig.maxRequestBodySize
899
1101
 
900
1102
  if (!existsSync(manifestPath)) {
901
1103
  if (existsSync(outDir) && readdirSync(outDir).length > 0) {
902
- const securityOpt = options.security ?? fileConfig.security
903
1104
  const securityEntries = securityOpt === false ? [] : buildSecurityHeaderEntries(securityOpt ?? {})
904
1105
  return createStaticDirServer(
905
1106
  outDir,
906
1107
  options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
907
1108
  securityEntries,
908
1109
  (options.compress ?? fileConfig.compress) !== false,
1110
+ resolveHstsValue(securityOpt),
1111
+ trustProxy,
909
1112
  )
910
1113
  }
911
1114
  throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
@@ -922,8 +1125,13 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
922
1125
  // Store file paths only (zero-copy Bun.file() serving, zero startup RAM bloat!)
923
1126
  for (const rel of manifest.assets) {
924
1127
  const abs = join(clientDir, rel)
925
- if (existsSync(abs))
1128
+ if (existsSync(abs)) {
926
1129
  assets[rel] = abs
1130
+ if (existsSync(`${abs}.br`))
1131
+ assets[`${rel}.br`] = `${abs}.br`
1132
+ if (existsSync(`${abs}.gz`))
1133
+ assets[`${rel}.gz`] = `${abs}.gz`
1134
+ }
927
1135
  }
928
1136
 
929
1137
  for (const rel of manifest.publicFiles ?? []) {
@@ -971,8 +1179,10 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
971
1179
  prerenderedFiles,
972
1180
  assetPrefix: options.assetPrefix ?? fileConfig.assetPrefix,
973
1181
  lang: options.lang ?? fileConfig.lang,
974
- security: options.security ?? fileConfig.security,
1182
+ security: securityOpt,
975
1183
  trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
1184
+ trustProxy,
1185
+ maxRequestBodySize,
976
1186
  compress: options.compress ?? fileConfig.compress,
977
1187
  onError: options.onError ?? fileConfig.onError,
978
1188
  plugins,