@kayjs/kay 2.0.0-alpha.7 → 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.
- package/package.json +1 -1
- package/src/build/compile.ts +15 -3
- package/src/build/index.ts +301 -49
- package/src/cli/check.ts +41 -37
- package/src/cli/index.ts +27 -11
- package/src/cli/new.ts +24 -8
- package/src/compiler/dom.ts +153 -30
- package/src/compiler/server-only.ts +62 -0
- package/src/compiler/ssr.ts +101 -22
- package/src/dev/index.ts +26 -7
- package/src/dom/extras.ts +85 -43
- package/src/dom/index.ts +110 -17
- package/src/dom/island.ts +67 -24
- package/src/dom/loop.ts +6 -1
- package/src/plugins/index.ts +8 -1
- package/src/reactivity/index.ts +141 -40
- package/src/reactivity/store.ts +5 -1
- package/src/server/action.ts +98 -26
- package/src/server/compress.ts +87 -8
- package/src/server/cookies.ts +15 -8
- package/src/server/http.ts +121 -6
- package/src/server/index.ts +453 -242
- package/src/server/router.ts +6 -1
- package/src/server/security.ts +76 -18
- package/src/ssr/context.ts +2 -1
- package/src/ssr/index.ts +88 -20
- package/src/test/index.ts +4 -0
package/src/server/index.ts
CHANGED
|
@@ -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
|
|
21
|
-
import {
|
|
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
|
|
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
|
|
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 { ...
|
|
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, (
|
|
111
|
-
const pluginRouteEntries = new Map<string, Map<string, (
|
|
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
|
|
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,27 +323,28 @@ 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
|
|
294
|
-
const actionHandlers = new Map<string, ServerAction<unknown, unknown
|
|
340
|
+
const actionHandlers = new Map<string, { act: ServerAction<unknown, unknown>, middlewares: Middleware[] }>()
|
|
295
341
|
for (const entry of manifest.actions) {
|
|
296
342
|
const mod = modules[entry.file] as Record<string, unknown> | undefined
|
|
297
343
|
const act = mod?.[entry.exportName]
|
|
298
344
|
if (isServerAction(act)) {
|
|
299
345
|
;(act as { url: string }).url = entry.url
|
|
300
|
-
|
|
346
|
+
const middlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
|
|
347
|
+
actionHandlers.set(entry.url, { act, middlewares: [...globalMiddlewares, ...middlewares] })
|
|
301
348
|
}
|
|
302
349
|
}
|
|
303
350
|
|
|
@@ -332,13 +379,13 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
332
379
|
mod: LoadedPageModule
|
|
333
380
|
layouts: LoadedLayoutModule[]
|
|
334
381
|
middlewares: Middleware[]
|
|
335
|
-
fastHandler: ((req: Request) => Response | Promise<Response>) | undefined
|
|
382
|
+
fastHandler: ((req: Request, remoteIp?: string) => Response | Promise<Response>) | undefined
|
|
336
383
|
docPrefix: string
|
|
337
384
|
docSuffix: string
|
|
338
385
|
}
|
|
339
386
|
|
|
340
387
|
const router = new Router<CompiledRoute>()
|
|
341
|
-
const fastStaticPages = new Map<string, (req: Request) => Response | Promise<Response>>()
|
|
388
|
+
const fastStaticPages = new Map<string, (req: Request, remoteIp?: string) => Response | Promise<Response>>()
|
|
342
389
|
|
|
343
390
|
for (const entry of manifest.routes) {
|
|
344
391
|
const mod = modules[entry.file] as LoadedPageModule
|
|
@@ -376,20 +423,20 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
376
423
|
&& typeof mod.default === 'function'
|
|
377
424
|
&& mod.GET === undefined
|
|
378
425
|
|
|
379
|
-
let fastHandler: ((req: Request) => Response | Promise<Response>) | undefined
|
|
426
|
+
let fastHandler: ((req: Request, remoteIp?: string) => Response | Promise<Response>) | undefined
|
|
380
427
|
if (canFastPath) {
|
|
381
428
|
const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
|
|
382
|
-
const fastHeaders =
|
|
429
|
+
const fastHeaders = selectDynamicHtmlHeaders(hasIslands, false)
|
|
383
430
|
|
|
384
|
-
fastHandler = (request: Request): Response | Promise<Response> => {
|
|
431
|
+
fastHandler = (request: Request, remoteIp?: string): Response | Promise<Response> => {
|
|
385
432
|
const handleErr = (error: unknown): Promise<Response> => {
|
|
386
433
|
notifyError(error, request, 'route')
|
|
387
|
-
return renderError(error, makeRequestContext(request, {}).cookieStore, new URL(request.url))
|
|
434
|
+
return renderError(error, makeRequestContext(request, {}, { trustProxy, remoteIp }).cookieStore, new URL(request.url), request)
|
|
388
435
|
}
|
|
389
436
|
try {
|
|
390
437
|
const reqUrl = new URL(request.url)
|
|
391
438
|
const respondHtml = (body: string): Response =>
|
|
392
|
-
compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache)
|
|
439
|
+
withHsts(compressedHtmlResponse(docPrefix + body + docSuffix, 200, fastHeaders, request, compressCache), request)
|
|
393
440
|
|
|
394
441
|
const wrapLayouts = (inner: string): Response | Promise<Response> => {
|
|
395
442
|
if (layouts.length === 0)
|
|
@@ -432,13 +479,13 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
432
479
|
}
|
|
433
480
|
|
|
434
481
|
if (entry.hasLoad && typeof mod.load === 'function') {
|
|
435
|
-
const { ctx, cookieStore } = makeRequestContext(request, {})
|
|
482
|
+
const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp })
|
|
436
483
|
const finish = (res: Response | Promise<Response>): Response | Promise<Response> => {
|
|
437
484
|
if (!cookieStore.hasChanges)
|
|
438
|
-
return res
|
|
485
|
+
return res instanceof Promise ? res.then(r => withHsts(r, request), handleErr) : withHsts(res, request)
|
|
439
486
|
if (res instanceof Promise)
|
|
440
|
-
return res.then(r => finalizeResponse(r, cookieStore, securityEntries), handleErr)
|
|
441
|
-
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)
|
|
442
489
|
}
|
|
443
490
|
const loaded = mod.load(ctx)
|
|
444
491
|
if (loaded instanceof Promise) {
|
|
@@ -463,20 +510,31 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
463
510
|
router.add(entry.path, { entry, mod, layouts, middlewares, fastHandler, docPrefix, docSuffix })
|
|
464
511
|
}
|
|
465
512
|
|
|
466
|
-
async function renderCompiledRoute(
|
|
513
|
+
async function renderCompiledRoute(
|
|
514
|
+
route: CompiledRoute,
|
|
515
|
+
ctx: RequestContext,
|
|
516
|
+
disableTimeout?: () => void,
|
|
517
|
+
): Promise<Response> {
|
|
467
518
|
const { entry, mod, layouts } = route
|
|
468
519
|
|
|
469
520
|
// Serve prerendered HTML after middlewares have passed (when route had middlewares)
|
|
470
521
|
if (ctx.request.method === 'GET' || ctx.request.method === 'HEAD') {
|
|
471
|
-
const
|
|
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)
|
|
472
525
|
if (pre !== undefined)
|
|
473
|
-
return servePrerendered(ctx.request,
|
|
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)
|
|
474
530
|
}
|
|
475
531
|
|
|
476
532
|
// API route (.ts exporting GET/POST/etc.)
|
|
477
533
|
const methodHandler = mod[ctx.request.method]
|
|
478
534
|
if (typeof methodHandler === 'function') {
|
|
479
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?.()
|
|
480
538
|
return maybeCompressResponse(res, ctx.request, compressCache)
|
|
481
539
|
}
|
|
482
540
|
|
|
@@ -526,6 +584,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
526
584
|
|
|
527
585
|
// Streaming SSR path when <Suspense> boundaries are pending (never buffered for compression)!
|
|
528
586
|
if (rctx.pending.length > 0) {
|
|
587
|
+
disableTimeout?.()
|
|
529
588
|
const shell = renderDocument({
|
|
530
589
|
body: '\0',
|
|
531
590
|
head: collectedHead,
|
|
@@ -556,7 +615,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
556
615
|
},
|
|
557
616
|
})
|
|
558
617
|
|
|
559
|
-
return new Response(stream, { status: 200, headers: { ...
|
|
618
|
+
return new Response(stream, { status: 200, headers: { ...selectDynamicHtmlHeaders(hasIslands, true) } })
|
|
560
619
|
}
|
|
561
620
|
|
|
562
621
|
let html = renderDocument({
|
|
@@ -574,204 +633,299 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
574
633
|
for (let i = 0; i < htmlTransformers.length; i++)
|
|
575
634
|
html = await htmlTransformers[i]!(html, ctx)
|
|
576
635
|
|
|
577
|
-
return compressedHtmlResponse(html, 200,
|
|
636
|
+
return compressedHtmlResponse(html, 200, selectDynamicHtmlHeaders(hasIslands, false), ctx.request, compressCache)
|
|
578
637
|
}
|
|
579
638
|
|
|
580
639
|
const rootLayoutFile = manifest.routes.find(r => r.layouts.length > 0)?.layouts[0]
|
|
581
640
|
const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LoadedLayoutModule | undefined : undefined
|
|
582
641
|
const fallbackStyles = manifest.globalStyles ?? manifest.styles
|
|
583
642
|
|
|
584
|
-
async function
|
|
643
|
+
async function buildErrorResponse(error: unknown, url?: URL): Promise<Response> {
|
|
585
644
|
if (errorMod !== undefined) {
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
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 {}
|
|
595
657
|
}
|
|
596
|
-
return
|
|
658
|
+
return new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
597
659
|
}
|
|
598
660
|
|
|
599
|
-
async function
|
|
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
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
async function buildNotFoundResponse(url?: URL): Promise<Response> {
|
|
600
667
|
const notFoundFn = notFoundMod?.default
|
|
601
668
|
if (notFoundFn !== undefined) {
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
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)
|
|
646
768
|
}
|
|
647
|
-
return executeAction(act, request, actionCtx, trustedOrigins)
|
|
648
|
-
}
|
|
649
|
-
if (globalMiddlewares.length === 0) {
|
|
650
|
-
const res = await runAction()
|
|
651
|
-
return finalizeResponse(res, cookieStore, securityEntries)
|
|
652
|
-
}
|
|
653
|
-
let index = -1
|
|
654
|
-
const dispatch = async (i: number): Promise<Response> => {
|
|
655
|
-
if (i <= index)
|
|
656
|
-
throw new Error('kay: middleware called next() multiple times')
|
|
657
|
-
index = i
|
|
658
|
-
if (i < globalMiddlewares.length)
|
|
659
|
-
return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
|
|
660
|
-
return runAction()
|
|
661
|
-
}
|
|
662
|
-
try {
|
|
663
|
-
const res = await dispatch(0)
|
|
664
|
-
return finalizeResponse(res, cookieStore, securityEntries)
|
|
665
|
-
}
|
|
666
|
-
catch (error) {
|
|
667
|
-
notifyError(error, request, 'action')
|
|
668
|
-
return renderError(error, cookieStore, ctx.url)
|
|
669
769
|
}
|
|
670
770
|
}
|
|
671
|
-
}
|
|
672
771
|
|
|
673
|
-
|
|
772
|
+
const hasActionErrorFlash = (req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
|
|
674
773
|
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
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
|
+
}
|
|
681
780
|
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
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
|
+
}
|
|
688
787
|
|
|
689
|
-
|
|
690
|
-
|
|
788
|
+
// 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
|
|
789
|
+
const { ctx, cookieStore } = makeRequestContext(req, {}, { trustProxy, remoteIp })
|
|
691
790
|
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
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)
|
|
698
800
|
}
|
|
699
|
-
catch {}
|
|
700
|
-
ctx.cookies.delete(ACTION_ERROR_COOKIE)
|
|
701
801
|
}
|
|
702
|
-
}
|
|
703
802
|
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
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
|
+
}
|
|
711
810
|
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
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
|
+
}
|
|
723
829
|
}
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
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)
|
|
733
847
|
}
|
|
734
|
-
res
|
|
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)
|
|
735
855
|
}
|
|
736
|
-
return finalizeResponse(await maybeCompressResponse(res, request, compressCache), cookieStore, securityEntries)
|
|
737
|
-
}
|
|
738
|
-
catch (error) {
|
|
739
|
-
notifyError(error, request, 'plugin')
|
|
740
|
-
return renderError(error, cookieStore, ctx.url)
|
|
741
856
|
}
|
|
742
857
|
}
|
|
743
|
-
}
|
|
744
858
|
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
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
|
+
}
|
|
748
880
|
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
? [...globalMiddlewares, ...route.middlewares]
|
|
753
|
-
: route.middlewares
|
|
881
|
+
const allMiddlewares = globalMiddlewares.length > 0
|
|
882
|
+
? [...globalMiddlewares, ...route.middlewares]
|
|
883
|
+
: route.middlewares
|
|
754
884
|
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
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)
|
|
764
903
|
}
|
|
765
|
-
const res = await dispatch(0)
|
|
766
|
-
return finalizeResponse(res, cookieStore, securityEntries)
|
|
767
904
|
}
|
|
768
905
|
catch (error) {
|
|
769
906
|
notifyError(error, request, 'route')
|
|
770
|
-
return
|
|
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
|
+
)
|
|
771
914
|
}
|
|
772
915
|
}
|
|
773
916
|
|
|
774
|
-
function
|
|
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
|
+
|
|
775
929
|
const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
|
|
776
930
|
|
|
777
931
|
for (const [path, asset] of assetMap)
|
|
@@ -786,25 +940,35 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
786
940
|
if (!(path in routes)) {
|
|
787
941
|
routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
|
|
788
942
|
? servePrerendered(req, path, pre)
|
|
789
|
-
:
|
|
943
|
+
: fetchReq(req)
|
|
790
944
|
}
|
|
791
945
|
}
|
|
792
946
|
|
|
793
947
|
for (const [path, handler] of fastStaticPages) {
|
|
794
948
|
if (!(path in routes)) {
|
|
795
949
|
routes[path] = req => (req.method === 'GET' || req.method === 'HEAD') && !(req.headers.get('cookie') ?? '').includes(`${ACTION_ERROR_COOKIE}=`)
|
|
796
|
-
? handler(req)
|
|
797
|
-
:
|
|
950
|
+
? handler(req, srvRef?.requestIP(req)?.address)
|
|
951
|
+
: fetchReq(req)
|
|
798
952
|
}
|
|
799
953
|
}
|
|
800
954
|
|
|
801
|
-
|
|
955
|
+
srvRef = Bun.serve({
|
|
802
956
|
port,
|
|
803
|
-
|
|
804
|
-
idleTimeout:
|
|
957
|
+
hostname,
|
|
958
|
+
idleTimeout: 30,
|
|
959
|
+
maxRequestBodySize,
|
|
960
|
+
development: false,
|
|
805
961
|
routes,
|
|
806
|
-
fetch:
|
|
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
|
+
},
|
|
807
970
|
})
|
|
971
|
+
return srvRef
|
|
808
972
|
}
|
|
809
973
|
|
|
810
974
|
return { handle, serve }
|
|
@@ -815,10 +979,16 @@ function createStaticDirServer(
|
|
|
815
979
|
assetPrefix: string,
|
|
816
980
|
securityEntries: readonly [string, string][],
|
|
817
981
|
compressEnabled: boolean,
|
|
982
|
+
hstsValue: string | undefined,
|
|
983
|
+
trustProxy: boolean,
|
|
818
984
|
): KayApp {
|
|
819
985
|
const cleanPrefix = `${assetPrefix.replace(/\/$/, '')}/`
|
|
820
986
|
const absRoot = resolve(outDir)
|
|
821
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)
|
|
822
992
|
|
|
823
993
|
function resolveStaticFile(pathname: string): string | undefined {
|
|
824
994
|
let decoded: string
|
|
@@ -851,7 +1021,7 @@ function createStaticDirServer(
|
|
|
851
1021
|
|
|
852
1022
|
const handle = async (req: Request): Promise<Response> => {
|
|
853
1023
|
if (req.method !== 'GET' && req.method !== 'HEAD')
|
|
854
|
-
return new Response('Method Not Allowed', { status: 405 })
|
|
1024
|
+
return withHsts(new Response('Method Not Allowed', { status: 405, headers: initHeaders() }), req)
|
|
855
1025
|
|
|
856
1026
|
const url = new URL(req.url)
|
|
857
1027
|
const filePath = resolveStaticFile(url.pathname)
|
|
@@ -860,9 +1030,9 @@ function createStaticDirServer(
|
|
|
860
1030
|
if (existsSync(notFoundPath) && statSync(notFoundPath).isFile()) {
|
|
861
1031
|
const headers = initHeaders()
|
|
862
1032
|
headers.set('content-type', 'text/html; charset=utf-8')
|
|
863
|
-
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)
|
|
864
1034
|
}
|
|
865
|
-
return new Response('Not Found', { status: 404 })
|
|
1035
|
+
return withHsts(new Response('Not Found', { status: 404, headers: initHeaders() }), req)
|
|
866
1036
|
}
|
|
867
1037
|
|
|
868
1038
|
const st = statSync(filePath)
|
|
@@ -875,18 +1045,45 @@ function createStaticDirServer(
|
|
|
875
1045
|
headers.set('etag', etag)
|
|
876
1046
|
|
|
877
1047
|
if (req.headers.get('if-none-match') === etag)
|
|
878
|
-
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
|
+
}
|
|
879
1063
|
|
|
1064
|
+
headers.set('content-length', String(st.size))
|
|
880
1065
|
const res = new Response(req.method === 'HEAD' ? null : Bun.file(filePath), { status: 200, headers })
|
|
881
1066
|
if (!compressEnabled || req.method === 'HEAD')
|
|
882
|
-
return res
|
|
883
|
-
return maybeCompressResponse(res, req, compressCache)
|
|
1067
|
+
return withHsts(res, req)
|
|
1068
|
+
return withHsts(await maybeCompressResponse(res, req, compressCache), req)
|
|
884
1069
|
}
|
|
885
1070
|
|
|
886
1071
|
return {
|
|
887
1072
|
handle,
|
|
888
|
-
serve(port = 3000) {
|
|
889
|
-
return Bun.serve({
|
|
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
|
+
})
|
|
890
1087
|
},
|
|
891
1088
|
}
|
|
892
1089
|
}
|
|
@@ -898,16 +1095,20 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
898
1095
|
const outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
|
|
899
1096
|
const clientDir = join(outDir, 'client')
|
|
900
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
|
|
901
1101
|
|
|
902
1102
|
if (!existsSync(manifestPath)) {
|
|
903
1103
|
if (existsSync(outDir) && readdirSync(outDir).length > 0) {
|
|
904
|
-
const securityOpt = options.security ?? fileConfig.security
|
|
905
1104
|
const securityEntries = securityOpt === false ? [] : buildSecurityHeaderEntries(securityOpt ?? {})
|
|
906
1105
|
return createStaticDirServer(
|
|
907
1106
|
outDir,
|
|
908
1107
|
options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
|
|
909
1108
|
securityEntries,
|
|
910
1109
|
(options.compress ?? fileConfig.compress) !== false,
|
|
1110
|
+
resolveHstsValue(securityOpt),
|
|
1111
|
+
trustProxy,
|
|
911
1112
|
)
|
|
912
1113
|
}
|
|
913
1114
|
throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
|
|
@@ -924,8 +1125,13 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
924
1125
|
// Store file paths only (zero-copy Bun.file() serving, zero startup RAM bloat!)
|
|
925
1126
|
for (const rel of manifest.assets) {
|
|
926
1127
|
const abs = join(clientDir, rel)
|
|
927
|
-
if (existsSync(abs))
|
|
1128
|
+
if (existsSync(abs)) {
|
|
928
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
|
+
}
|
|
929
1135
|
}
|
|
930
1136
|
|
|
931
1137
|
for (const rel of manifest.publicFiles ?? []) {
|
|
@@ -958,7 +1164,10 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
958
1164
|
}
|
|
959
1165
|
if (manifest.errorFile) await loadMod(manifest.errorFile)
|
|
960
1166
|
if (manifest.notFoundFile) await loadMod(manifest.notFoundFile)
|
|
961
|
-
for (const a of manifest.actions)
|
|
1167
|
+
for (const a of manifest.actions) {
|
|
1168
|
+
await loadMod(a.file)
|
|
1169
|
+
for (const m of a.middlewares) await loadMod(m)
|
|
1170
|
+
}
|
|
962
1171
|
|
|
963
1172
|
return createServerFromEmbedded({
|
|
964
1173
|
manifest,
|
|
@@ -970,8 +1179,10 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
970
1179
|
prerenderedFiles,
|
|
971
1180
|
assetPrefix: options.assetPrefix ?? fileConfig.assetPrefix,
|
|
972
1181
|
lang: options.lang ?? fileConfig.lang,
|
|
973
|
-
security:
|
|
1182
|
+
security: securityOpt,
|
|
974
1183
|
trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
|
|
1184
|
+
trustProxy,
|
|
1185
|
+
maxRequestBodySize,
|
|
975
1186
|
compress: options.compress ?? fileConfig.compress,
|
|
976
1187
|
onError: options.onError ?? fileConfig.onError,
|
|
977
1188
|
plugins,
|