@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.
@@ -2,6 +2,7 @@
2
2
  // Never imports `node:zlib` so server RSS stays minimal.
3
3
 
4
4
  export type CompressionEncoding = 'zstd' | 'gzip'
5
+ export type PrecompressedEncoding = 'br' | 'gzip'
5
6
 
6
7
  export const MIN_COMPRESS_BYTES = 256
7
8
  const DEFAULT_MAX_CACHE_BYTES = 2 * 1024 * 1024
@@ -76,6 +77,73 @@ export function pickEncoding(acceptEncoding: string | null): CompressionEncoding
76
77
  return zstdQ >= gzipQ ? 'zstd' : 'gzip'
77
78
  }
78
79
 
80
+ export function pickPrecompressedEncoding(
81
+ acceptEncoding: string | null,
82
+ available: { br?: boolean, gz?: boolean },
83
+ ): PrecompressedEncoding | undefined {
84
+ if (!acceptEncoding || (!available.br && !available.gz))
85
+ return undefined
86
+
87
+ if (!acceptEncoding.includes(';')) {
88
+ const lower = acceptEncoding.toLowerCase()
89
+ if (available.br && hasToken(lower, 'br'))
90
+ return 'br'
91
+ if (available.gz && hasToken(lower, 'gzip'))
92
+ return 'gzip'
93
+ return undefined
94
+ }
95
+
96
+ let brQ = -1
97
+ let gzipQ = -1
98
+ const parts = acceptEncoding.split(',')
99
+ for (let i = 0; i < parts.length; i++) {
100
+ const part = parts[i]!.trim()
101
+ if (!part)
102
+ continue
103
+ const semi = part.indexOf(';')
104
+ const name = (semi === -1 ? part : part.slice(0, semi)).trim().toLowerCase()
105
+ if (name !== 'br' && name !== 'gzip')
106
+ continue
107
+ let q = 1
108
+ if (semi !== -1) {
109
+ const m = /;\s*q\s*=\s*([0-9.]+)/i.exec(part.slice(semi))
110
+ if (m !== null) {
111
+ const parsed = Number(m[1])
112
+ if (!Number.isNaN(parsed))
113
+ q = parsed
114
+ }
115
+ }
116
+ if (name === 'br')
117
+ brQ = q
118
+ else
119
+ gzipQ = q
120
+ }
121
+
122
+ const effBr = available.br ? brQ : -1
123
+ const effGz = available.gz ? gzipQ : -1
124
+ if (effBr <= 0 && effGz <= 0)
125
+ return undefined
126
+ return effBr >= effGz ? 'br' : 'gzip'
127
+ }
128
+
129
+ export function toWeakEtag(etag: string): string {
130
+ return etag.startsWith('W/') || etag.startsWith('w/') ? etag : `W/${etag}`
131
+ }
132
+
133
+ function hasNoTransform(cacheControl: string | null | undefined): boolean {
134
+ return Boolean(cacheControl && /\bno-transform\b/i.test(cacheControl))
135
+ }
136
+
137
+ function isStreamingBody(res: Response): boolean {
138
+ // Check transfer-encoding or Bun's unmaterialized ReadableStream representation BEFORE touching `res.body`.
139
+ const te = res.headers.get('transfer-encoding')
140
+ if (te && te.toLowerCase().includes('chunked'))
141
+ return true
142
+ if (typeof Bun !== 'undefined')
143
+ return Bun.inspect(res).includes('ReadableStream {')
144
+ return true
145
+ }
146
+
79
147
  function hasToken(haystack: string, token: string): boolean {
80
148
  let idx = haystack.indexOf(token)
81
149
  while (idx !== -1) {
@@ -170,7 +238,8 @@ export function compressedHtmlResponse(
170
238
  request: Request,
171
239
  cache: CompressionCache | undefined,
172
240
  ): Response {
173
- if (cache !== undefined && request.method !== 'HEAD') {
241
+ const noTransform = hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
242
+ if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
174
243
  const enc = pickEncoding(request.headers.get('accept-encoding'))
175
244
  if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
176
245
  const staticKey = `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}`
@@ -180,16 +249,17 @@ export function compressedHtmlResponse(
180
249
  compressed = cache.compress(bytes, enc, staticKey)
181
250
  }
182
251
  if (compressed !== undefined) {
183
- return new Response(compressed, {
184
- status,
185
- headers: { ...baseHeaders, 'content-encoding': enc, 'vary': 'Accept-Encoding' },
186
- })
252
+ const headers: Record<string, string> = { ...baseHeaders, 'content-encoding': enc, 'vary': 'Accept-Encoding' }
253
+ const etag = headers.etag ?? headers.ETag
254
+ if (etag !== undefined)
255
+ headers.etag = toWeakEtag(etag)
256
+ return new Response(compressed, { status, headers })
187
257
  }
188
258
  }
189
259
  }
190
260
  return new Response(request.method === 'HEAD' ? null : html, {
191
261
  status,
192
- headers: cache !== undefined ? { ...baseHeaders, vary: 'Accept-Encoding' } : baseHeaders,
262
+ headers: cache !== undefined && !noTransform ? { ...baseHeaders, vary: 'Accept-Encoding' } : baseHeaders,
193
263
  })
194
264
  }
195
265
 
@@ -200,13 +270,20 @@ export async function maybeCompressResponse(
200
270
  ): Promise<Response> {
201
271
  if (cache === undefined)
202
272
  return res
203
- if (res.status === 204 || res.status === 304 || (res.status >= 300 && res.status < 400))
273
+ if (res.status === 204 || res.status === 206 || res.status === 304 || (res.status >= 300 && res.status < 400))
204
274
  return res
205
275
  if (res.headers.has('content-encoding'))
206
276
  return res
277
+ if (hasNoTransform(res.headers.get('cache-control')))
278
+ return res
207
279
  if (!isCompressibleType(res.headers.get('content-type')))
208
280
  return res
209
281
 
282
+ const cl = res.headers.get('content-length')
283
+ // Never buffer streaming responses that have no Content-Length (e.g. chunked streams, ReadableStream)
284
+ if (cl === null && isStreamingBody(res))
285
+ return res
286
+
210
287
  const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
211
288
  if (enc === undefined) {
212
289
  try {
@@ -216,7 +293,6 @@ export async function maybeCompressResponse(
216
293
  return res
217
294
  }
218
295
 
219
- const cl = res.headers.get('content-length')
220
296
  if (cl !== null && Number(cl) < MIN_COMPRESS_BYTES) {
221
297
  try {
222
298
  appendVaryAcceptEncoding(res.headers)
@@ -237,5 +313,8 @@ export async function maybeCompressResponse(
237
313
 
238
314
  headers.set('content-encoding', enc)
239
315
  headers.delete('content-length')
316
+ const etag = headers.get('etag')
317
+ if (etag !== null)
318
+ headers.set('etag', toWeakEtag(etag))
240
319
  return new Response(compressed, { status: res.status, statusText: res.statusText, headers })
241
320
  }
@@ -13,7 +13,7 @@ export interface CookieOptions {
13
13
  export interface Cookies {
14
14
  get(name: string): string | undefined
15
15
  set(name: string, value: string, options?: CookieOptions): void
16
- delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void
16
+ delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void
17
17
  all(): Record<string, string>
18
18
  }
19
19
 
@@ -39,7 +39,12 @@ export function parseCookieHeader(header: string | null): Map<string, string> {
39
39
  return map
40
40
  }
41
41
 
42
- function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {
42
+ function serializeCookie(name: string, value: string, options: CookieOptions = {}, defaultSecure = false): string {
43
+ const secure = options.secure ?? defaultSecure
44
+ const sameSite = options.sameSite ?? 'lax'
45
+ if (sameSite === 'none' && !secure)
46
+ throw new Error(`kay: Cookie "${name}" with sameSite: "none" requires secure: true`)
47
+
43
48
  let out = `${name}=${encodeURIComponent(value)}`
44
49
  out += `; Path=${options.path ?? '/'}`
45
50
  if (options.domain !== undefined)
@@ -50,9 +55,8 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
50
55
  out += `; Expires=${options.expires.toUTCString()}`
51
56
  if (options.httpOnly ?? true)
52
57
  out += '; HttpOnly'
53
- if (options.secure)
58
+ if (secure)
54
59
  out += '; Secure'
55
- const sameSite = options.sameSite ?? 'lax'
56
60
  out += `; SameSite=${sameSite[0]!.toUpperCase()}${sameSite.slice(1)}`
57
61
  return out
58
62
  }
@@ -60,9 +64,11 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
60
64
  export class CookieStore implements Cookies {
61
65
  readonly #values: Map<string, string>
62
66
  readonly #headers: string[] = []
67
+ readonly #isHttps: boolean
63
68
 
64
- constructor(cookieHeader: string | null) {
69
+ constructor(cookieHeader: string | null, isHttps = false) {
65
70
  this.#values = parseCookieHeader(cookieHeader)
71
+ this.#isHttps = isHttps
66
72
  }
67
73
 
68
74
  get(name: string): string | undefined {
@@ -70,13 +76,14 @@ export class CookieStore implements Cookies {
70
76
  }
71
77
 
72
78
  set(name: string, value: string, options?: CookieOptions): void {
79
+ const serialized = serializeCookie(name, value, options, this.#isHttps)
73
80
  this.#values.set(name, value)
74
- this.#headers.push(serializeCookie(name, value, options))
81
+ this.#headers.push(serialized)
75
82
  }
76
83
 
77
- delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void {
84
+ delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void {
78
85
  this.#values.delete(name)
79
- this.#headers.push(serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }))
86
+ this.#headers.push(serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
80
87
  }
81
88
 
82
89
  all(): Record<string, string> {
@@ -5,7 +5,9 @@ import type { KayPlugin, ServerErrorInfo } from '../plugins/index'
5
5
  import type { Cookies } from './cookies'
6
6
  import type { SecurityHeadersOptions } from './security'
7
7
  import { CookieStore } from './cookies'
8
- import { buildSecurityHeaderEntries } from './security'
8
+ import { buildSecurityHeaderEntries, getClientIp, isHttpsRequest } from './security'
9
+
10
+ export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
9
11
 
10
12
  export interface ServerOptions {
11
13
  root: string
@@ -15,6 +17,8 @@ export interface ServerOptions {
15
17
  lang?: string | undefined
16
18
  security?: SecurityHeadersOptions | false | undefined
17
19
  trustedOrigins?: string[] | undefined
20
+ trustProxy?: boolean | undefined
21
+ maxRequestBodySize?: number | undefined
18
22
  compress?: boolean | undefined
19
23
  onError?: ((info: ServerErrorInfo) => void) | undefined
20
24
  plugins?: KayPlugin[] | undefined
@@ -26,6 +30,7 @@ export interface RequestContext {
26
30
  params: Record<string, string>
27
31
  cookies: Cookies
28
32
  locals: Record<string, unknown>
33
+ ip?: string | undefined
29
34
  json: (data: unknown, init?: ResponseInit) => Response
30
35
  text: (body: string, init?: ResponseInit) => Response
31
36
  redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
@@ -35,7 +40,7 @@ export interface RequestContext {
35
40
  export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) => Response | Promise<Response>
36
41
 
37
42
  export interface KayApp {
38
- handle: (request: Request) => Promise<Response>
43
+ handle: (request: Request, remoteIp?: string) => Promise<Response>
39
44
  serve: (port?: number, hostname?: string) => ReturnType<typeof Bun.serve>
40
45
  }
41
46
 
@@ -53,6 +58,8 @@ export interface EmbeddedServerConfig {
53
58
  lang?: string | undefined
54
59
  security?: SecurityHeadersOptions | false | undefined
55
60
  trustedOrigins?: string[] | undefined
61
+ trustProxy?: boolean | undefined
62
+ maxRequestBodySize?: number | undefined
56
63
  compress?: boolean | undefined
57
64
  onError?: ((info: ServerErrorInfo) => void) | undefined
58
65
  plugins?: KayPlugin[] | undefined
@@ -102,23 +109,131 @@ export function extractRenderedIslands(html: string): { hasIslands: boolean, eag
102
109
  return { hasIslands, eagerChunks: [...eager] }
103
110
  }
104
111
 
105
- export function makeRequestContext(request: Request, params: Record<string, string>): { ctx: RequestContext, cookieStore: CookieStore } {
112
+ export interface RequestContextOptions {
113
+ trustProxy?: boolean | undefined
114
+ remoteIp?: string | undefined
115
+ }
116
+
117
+ export function makeRequestContext(
118
+ request: Request,
119
+ params: Record<string, string>,
120
+ opts?: RequestContextOptions,
121
+ ): { ctx: RequestContext, cookieStore: CookieStore } {
106
122
  const url = new URL(request.url)
107
- const cookieStore = new CookieStore(request.headers.get('cookie'))
123
+ const trustProxy = opts?.trustProxy === true
124
+ const isHttps = isHttpsRequest(request, trustProxy)
125
+ const cookieStore = new CookieStore(request.headers.get('cookie'), isHttps)
126
+ const ip = getClientIp(request, trustProxy, opts?.remoteIp)
108
127
  const ctx: RequestContext = {
109
128
  request,
110
129
  url,
111
130
  params,
112
131
  cookies: cookieStore,
113
132
  locals: {},
114
- json: (data, init) => Response.json(data, init),
115
- text: (body, init) => new Response(body, { ...init, headers: { 'content-type': 'text/plain; charset=utf-8', ...init?.headers } }),
133
+ ip,
134
+ json: (data, init) => {
135
+ const payload = JSON.stringify(data)
136
+ const headers = new Headers(init?.headers)
137
+ if (!headers.has('content-type'))
138
+ headers.set('content-type', 'application/json; charset=utf-8')
139
+ if (!headers.has('content-length'))
140
+ headers.set('content-length', String(Buffer.byteLength(payload, 'utf8')))
141
+ return new Response(payload, { ...init, headers })
142
+ },
143
+ text: (body, init) => {
144
+ const headers = new Headers(init?.headers)
145
+ if (!headers.has('content-type'))
146
+ headers.set('content-type', 'text/plain; charset=utf-8')
147
+ if (!headers.has('content-length'))
148
+ headers.set('content-length', String(Buffer.byteLength(body, 'utf8')))
149
+ return new Response(body, { ...init, headers })
150
+ },
116
151
  redirect: (location, status = 302) => new Response(null, { status, headers: { location } }),
117
152
  deny: (status, message, fieldErrors) => Response.json({ ok: false, status, error: message, fieldErrors }, { status }),
118
153
  }
119
154
  return { ctx, cookieStore }
120
155
  }
121
156
 
157
+ /** Enforces `maxBytes` on incoming request bodies (both Content-Length and streaming body reads). */
158
+ export async function enforceRequestBodyLimit(
159
+ request: Request,
160
+ maxBytes: number,
161
+ ): Promise<{ ok: true, request: Request } | { ok: false }> {
162
+ if (request.method === 'GET' || request.method === 'HEAD' || !Number.isFinite(maxBytes) || maxBytes <= 0)
163
+ return { ok: true, request }
164
+
165
+ const clHeader = request.headers.get('content-length')
166
+ if (clHeader !== null) {
167
+ const cl = Number(clHeader)
168
+ if (Number.isFinite(cl) && cl > maxBytes)
169
+ return { ok: false }
170
+ }
171
+
172
+ // Capture headers BEFORE accessing request.body so Bun preserves FormData multipart boundaries.
173
+ const headers = new Headers(request.headers)
174
+ const body = request.body
175
+ if (body === null)
176
+ return { ok: true, request }
177
+
178
+ const reader = body.getReader()
179
+ const chunks: Uint8Array[] = []
180
+ let total = 0
181
+ try {
182
+ while (true) {
183
+ const { done, value } = await reader.read()
184
+ if (done)
185
+ break
186
+ total += value.byteLength
187
+ if (total > maxBytes) {
188
+ await reader.cancel().catch(() => {})
189
+ return { ok: false }
190
+ }
191
+ chunks.push(value)
192
+ }
193
+ }
194
+ finally {
195
+ reader.releaseLock()
196
+ }
197
+
198
+ const combined = new Uint8Array(total)
199
+ let offset = 0
200
+ for (let i = 0; i < chunks.length; i++) {
201
+ const chunk = chunks[i]!
202
+ combined.set(chunk, offset)
203
+ offset += chunk.byteLength
204
+ }
205
+
206
+ return {
207
+ ok: true,
208
+ request: new Request(request.url, {
209
+ method: request.method,
210
+ headers,
211
+ body: combined,
212
+ }),
213
+ }
214
+ }
215
+
216
+ export function applyHstsHeader(
217
+ res: Response,
218
+ request: Request,
219
+ hstsValue: string | undefined,
220
+ trustProxy: boolean,
221
+ ): Response {
222
+ if (hstsValue === undefined || process.env.NODE_ENV !== 'production' || !isHttpsRequest(request, trustProxy))
223
+ return res
224
+ if (res.headers.has('strict-transport-security'))
225
+ return res
226
+ try {
227
+ res.headers.set('strict-transport-security', hstsValue)
228
+ return res
229
+ }
230
+ catch {
231
+ const headers = new Headers(res.headers)
232
+ headers.set('strict-transport-security', hstsValue)
233
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
234
+ }
235
+ }
236
+
122
237
  export function finalizeResponse(
123
238
  res: Response,
124
239
  cookieStore: CookieStore,