@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.
@@ -84,7 +84,12 @@ export class Router<T> {
84
84
  break
85
85
  }
86
86
  else if (seg.startsWith(':')) {
87
- params[seg.slice(1)] = decodeSegment(parts[j]!)
87
+ const rawSeg = parts[j]!
88
+ if (/%2f/i.test(rawSeg)) {
89
+ matched = false
90
+ break
91
+ }
92
+ params[seg.slice(1)] = decodeSegment(rawSeg)
88
93
  }
89
94
  else if (seg !== parts[j]) {
90
95
  matched = false
@@ -64,49 +64,91 @@ export function withCspHashes(
64
64
  }).join('; ')
65
65
  }
66
66
 
67
+ export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'"
68
+ export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
69
+
67
70
  export interface SecurityHeadersOptions {
68
71
  frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
69
72
  referrerPolicy?: string | false | undefined
70
73
  contentTypeOptions?: boolean | undefined
71
- csp?: string | undefined
74
+ csp?: string | false | undefined
75
+ hsts?: string | boolean | undefined
72
76
  }
73
77
 
74
78
  const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
75
79
 
76
- function requestOrigins(request: Request): { expectedOrigin: string, forwardedOrigin: string | undefined } {
80
+ function requestOrigins(request: Request, trustProxy = false): { expectedOrigin: string, forwardedOrigin: string | undefined } {
77
81
  const expectedOrigin = new URL(request.url).origin
78
- const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim()
79
- const fwdHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() || request.headers.get('host')?.trim()
80
82
  let forwardedOrigin: string | undefined
81
- if (fwdProto && fwdHost) {
82
- try {
83
- forwardedOrigin = new URL(`${fwdProto}://${fwdHost}`).origin
84
- }
85
- catch {
86
- forwardedOrigin = `${fwdProto}://${fwdHost}`
83
+ if (trustProxy) {
84
+ const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim()
85
+ const fwdHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() || request.headers.get('host')?.trim()
86
+ if (fwdProto && fwdHost) {
87
+ try {
88
+ forwardedOrigin = new URL(`${fwdProto}://${fwdHost}`).origin
89
+ }
90
+ catch {
91
+ forwardedOrigin = `${fwdProto}://${fwdHost}`
92
+ }
87
93
  }
88
94
  }
89
95
  return { expectedOrigin, forwardedOrigin }
90
96
  }
91
97
 
92
- /** Returns true when `origin` matches the request's direct/forwarded origin or `trustedOrigins`. */
98
+ /** Returns true when the request arrived over HTTPS (directly, or via X-Forwarded-Proto when `trustProxy` is true). */
99
+ export function isHttpsRequest(request: Request, trustProxy = false): boolean {
100
+ try {
101
+ if (new URL(request.url).protocol === 'https:')
102
+ return true
103
+ }
104
+ catch {}
105
+ if (trustProxy) {
106
+ const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase()
107
+ if (fwdProto === 'https')
108
+ return true
109
+ }
110
+ return false
111
+ }
112
+
113
+ /** Extracts the client IP from proxy headers (only when `trustProxy` is true) or falls back to the direct socket IP. */
114
+ export function getClientIp(request: Request, trustProxy = false, remoteIp?: string): string | undefined {
115
+ if (trustProxy) {
116
+ const xff = request.headers.get('x-forwarded-for')
117
+ if (xff) {
118
+ const first = xff.split(',')[0]?.trim()
119
+ if (first)
120
+ return first
121
+ }
122
+ const realIp = request.headers.get('x-real-ip')?.trim()
123
+ if (realIp)
124
+ return realIp
125
+ }
126
+ return remoteIp || undefined
127
+ }
128
+
129
+ /** Returns true when `origin` matches the request's direct (or trusted forwarded) origin or `trustedOrigins`. */
93
130
  export function isTrustedOrigin(
94
131
  origin: string,
95
132
  request: Request,
96
133
  trustedOrigins?: ReadonlySet<string>,
134
+ trustProxy = false,
97
135
  ): boolean {
98
- const { expectedOrigin, forwardedOrigin } = requestOrigins(request)
136
+ const { expectedOrigin, forwardedOrigin } = requestOrigins(request, trustProxy)
99
137
  return origin === expectedOrigin
100
138
  || (forwardedOrigin !== undefined && origin === forwardedOrigin)
101
139
  || trustedOrigins?.has(origin) === true
102
140
  }
103
141
 
104
142
  /** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
105
- export function verifyOrigin(request: Request, trustedOrigins?: ReadonlySet<string>): { ok: true } | { ok: false, reason: string } {
143
+ export function verifyOrigin(
144
+ request: Request,
145
+ trustedOrigins?: ReadonlySet<string>,
146
+ trustProxy = false,
147
+ ): { ok: true } | { ok: false, reason: string } {
106
148
  if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
107
149
  return { ok: true }
108
150
 
109
- const { expectedOrigin, forwardedOrigin } = requestOrigins(request)
151
+ const { expectedOrigin, forwardedOrigin } = requestOrigins(request, trustProxy)
110
152
  const origin = request.headers.get('origin')
111
153
 
112
154
  if (origin !== null) {
@@ -122,6 +164,22 @@ export function verifyOrigin(request: Request, trustedOrigins?: ReadonlySet<stri
122
164
  return { ok: true }
123
165
  }
124
166
 
167
+ export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
168
+ if (options === false)
169
+ return undefined
170
+ if (options?.csp === false)
171
+ return undefined
172
+ return options?.csp ?? DEFAULT_CSP
173
+ }
174
+
175
+ export function resolveHstsValue(options: SecurityHeadersOptions | false | undefined): string | undefined {
176
+ if (options === false)
177
+ return undefined
178
+ if (options?.hsts === false)
179
+ return undefined
180
+ return typeof options?.hsts === 'string' ? options.hsts : DEFAULT_HSTS
181
+ }
182
+
125
183
  export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined): readonly [string, string][] {
126
184
  if (options === false)
127
185
  return []
@@ -133,8 +191,8 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
133
191
  entries.push(['x-frame-options', opts.frameOptions ?? 'SAMEORIGIN'])
134
192
  if (opts.referrerPolicy !== false)
135
193
  entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
136
- if (opts.csp !== undefined)
137
- entries.push(['content-security-policy', opts.csp])
194
+ if (opts.csp !== false)
195
+ entries.push(['content-security-policy', opts.csp ?? DEFAULT_CSP])
138
196
  return entries
139
197
  }
140
198
 
@@ -148,6 +206,6 @@ export function applySecurityHeaders(headers: Headers, options: SecurityHeadersO
148
206
  if (options.referrerPolicy !== false && !headers.has('referrer-policy'))
149
207
  headers.set('referrer-policy', options.referrerPolicy ?? 'strict-origin-when-cross-origin')
150
208
 
151
- if (options.csp !== undefined && !headers.has('content-security-policy'))
152
- headers.set('content-security-policy', options.csp)
209
+ if (options.csp !== false && !headers.has('content-security-policy'))
210
+ headers.set('content-security-policy', options.csp ?? DEFAULT_CSP)
153
211
  }
@@ -15,13 +15,14 @@ export interface RenderContext {
15
15
  title: string | undefined
16
16
  pending: PendingChunk[]
17
17
  nextId: number
18
+ islandDepth: number
18
19
  }
19
20
 
20
21
  const STORAGE_KEY = Symbol.for('kay.render.storage')
21
22
  const renderStorage: AsyncLocalStorage<RenderContext> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderContext> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RenderContext>())
22
23
 
23
24
  export function createRenderContext(): RenderContext {
24
- return { headParts: [], title: undefined, pending: [], nextId: 0 }
25
+ return { headParts: [], title: undefined, pending: [], nextId: 0, islandDepth: 0 }
25
26
  }
26
27
 
27
28
  export function runWithRenderContext<T>(ctx: RenderContext, fn: () => T): T {
package/src/ssr/index.ts CHANGED
@@ -1,11 +1,17 @@
1
1
  // Kay v2 SSR runtime: flat string concatenation with fast-path escaping and zero-overhead islands.
2
2
 
3
3
  import type { Html, HydrateStrategy, KayChild } from '../jsx-runtime'
4
- import { KAY_STREAM_SCRIPT } from './context'
4
+ import { currentRenderContext, KAY_STREAM_SCRIPT } from './context'
5
5
 
6
6
  export const KAY_ISLAND_STYLE = 'kay-island,kay-slot{display:contents}'
7
7
  export const KAY_SUSPENSE_STYLE = 'kay-s{display:contents}'
8
8
 
9
+ export const RAW_HTML = Symbol.for('kay.html')
10
+
11
+ function isRawHtml(value: unknown): value is Html {
12
+ return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[RAW_HTML] === true && '__html' in value
13
+ }
14
+
9
15
  const ESC_TEXT = /[&<>]/
10
16
  const ESC_ATTR = /[&"<>]/
11
17
  const bunEscape = typeof Bun !== 'undefined' && typeof Bun.escapeHTML === 'function' ? Bun.escapeHTML : undefined
@@ -22,8 +28,8 @@ export function esc(value: unknown): string {
22
28
  return String(value)
23
29
  if (value == null || typeof value === 'boolean')
24
30
  return ''
25
- if (typeof value === 'object' && '__html' in value)
26
- return (value as Html).__html
31
+ if (isRawHtml(value))
32
+ return value.__html
27
33
  if (Array.isArray(value)) {
28
34
  let out = ''
29
35
  for (let i = 0; i < value.length; i++)
@@ -41,15 +47,15 @@ export function esc(value: unknown): string {
41
47
  export function ssrRaw(value: unknown): string {
42
48
  if (value == null || value === false)
43
49
  return ''
44
- if (typeof value === 'object' && '__html' in value)
45
- return String((value as Html).__html)
50
+ if (isRawHtml(value))
51
+ return String(value.__html)
46
52
  return String(value)
47
53
  }
48
54
 
49
55
  const CLOSE_STYLE_RE = /<\/(style)/gi
50
- const CLOSE_SCRIPT_RE = /<\/(script)/gi
56
+ const SCRIPT_UNSAFE_RE = /<(\/script|script|!--)/gi
51
57
 
52
- /** Emits raw text inside `<style>` or `<script>` without HTML entity escaping, neutralizing only its closing tag. */
58
+ /** Emits raw text inside `<style>` or `<script>` without HTML entity escaping, neutralizing dangerous script/style sequences. */
53
59
  export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
54
60
  if (value == null || typeof value === 'boolean')
55
61
  return ''
@@ -61,10 +67,14 @@ export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
61
67
  }
62
68
  const str = typeof value === 'string'
63
69
  ? value
64
- : typeof value === 'object' && '__html' in value
65
- ? String((value as Html).__html)
70
+ : isRawHtml(value)
71
+ ? String(value.__html)
66
72
  : String(value)
67
- return str.replace(tag === 'script' ? CLOSE_SCRIPT_RE : CLOSE_STYLE_RE, '<\\/$1')
73
+ if (tag === 'script') {
74
+ return str.replace(SCRIPT_UNSAFE_RE, (_, body: string) =>
75
+ body.charCodeAt(0) === 47 ? `<\\${body}` : `\\u003c${body}`)
76
+ }
77
+ return str.replace(CLOSE_STYLE_RE, '<\\/$1')
68
78
  }
69
79
 
70
80
  export function escAttr(value: unknown): string {
@@ -81,14 +91,42 @@ export function escAttr(value: unknown): string {
81
91
  }
82
92
 
83
93
  export function raw(html: string): Html {
84
- return { __html: html }
94
+ return { __html: html, [RAW_HTML]: true } as Html
95
+ }
96
+
97
+ const VALID_ATTR_NAME = /^[A-Za-z_:][-\w:.]*$/
98
+ const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'xlink:href'])
99
+ const UNSAFE_URL_RE = /^(?:javascript|vbscript):/i
100
+ const STRING_BOOL_ATTRS = new Set(['draggable', 'spellcheck', 'contenteditable'])
101
+
102
+ function isBlockedAttr(name: string): boolean {
103
+ if (!VALID_ATTR_NAME.test(name))
104
+ return true
105
+ const lower = name.toLowerCase()
106
+ return lower.startsWith('on') || lower === 'innerhtml' || lower === 'srcdoc'
107
+ }
108
+
109
+ function isStringBoolAttr(name: string): boolean {
110
+ const lower = name.toLowerCase()
111
+ return lower.startsWith('aria-') || STRING_BOOL_ATTRS.has(lower)
112
+ }
113
+
114
+ function isUnsafeUrlAttr(name: string, value: unknown): boolean {
115
+ if (!URL_ATTRS.has(name.toLowerCase()))
116
+ return false
117
+ return UNSAFE_URL_RE.test(String(value).replace(/[\u0000-\u0020]+/g, ''))
85
118
  }
86
119
 
87
120
  export function ssrAttr(name: string, value: unknown): string {
88
- if (value == null || value === false)
121
+ if (value == null || isBlockedAttr(name))
122
+ return ''
123
+ if (typeof value === 'boolean') {
124
+ if (isStringBoolAttr(name))
125
+ return ` ${name}="${value ? 'true' : 'false'}"`
126
+ return value ? ` ${name}` : ''
127
+ }
128
+ if (isUnsafeUrlAttr(name, value))
89
129
  return ''
90
- if (value === true)
91
- return ` ${name}`
92
130
  return ` ${name}="${escAttr(value)}"`
93
131
  }
94
132
 
@@ -108,16 +146,16 @@ export function ssrStyle(value: unknown): string {
108
146
  return ''
109
147
  }
110
148
 
111
- const SPREAD_EVENT_RE = /^on[A-Z]/
112
-
113
149
  export function ssrSpread(props: Record<string, unknown> | null | undefined): string {
114
150
  if (props == null || typeof props !== 'object')
115
151
  return ''
116
152
  let out = ''
117
153
  for (const [rawKey, value] of Object.entries(props)) {
118
- if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children' || SPREAD_EVENT_RE.test(rawKey))
154
+ if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
119
155
  continue
120
156
  const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
157
+ if (isBlockedAttr(name))
158
+ continue
121
159
  out += name === 'style' ? ssrStyle(value) : ssrAttr(name, value)
122
160
  }
123
161
  return out
@@ -145,8 +183,8 @@ export function ssrChild(value: KayChild): string {
145
183
  return String(value)
146
184
  if (value == null || typeof value === 'boolean')
147
185
  return ''
148
- if (typeof value === 'object' && '__html' in value)
149
- return (value as Html).__html
186
+ if (isRawHtml(value))
187
+ return value.__html
150
188
  if (Array.isArray(value)) {
151
189
  let out = ''
152
190
  for (let i = 0; i < value.length; i++)
@@ -175,6 +213,33 @@ function serializeIslandProps(props: Record<string, unknown>): string {
175
213
  })
176
214
  }
177
215
 
216
+ let fallbackIslandDepth = 0
217
+
218
+ function getIslandDepth(): number {
219
+ const ctx = currentRenderContext()
220
+ return ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth
221
+ }
222
+
223
+ export function ssrInIsland(render: () => string): string {
224
+ const ctx = currentRenderContext()
225
+ if (ctx !== undefined) {
226
+ ctx.islandDepth++
227
+ try {
228
+ return render()
229
+ }
230
+ finally {
231
+ ctx.islandDepth--
232
+ }
233
+ }
234
+ fallbackIslandDepth++
235
+ try {
236
+ return render()
237
+ }
238
+ finally {
239
+ fallbackIslandDepth--
240
+ }
241
+ }
242
+
178
243
  export function ssrIsland(
179
244
  _id: string,
180
245
  chunk: string,
@@ -182,13 +247,16 @@ export function ssrIsland(
182
247
  props: Record<string, unknown>,
183
248
  hydrate?: HydrateStrategy,
184
249
  ): string {
250
+ if (getIslandDepth() > 0)
251
+ return render()
252
+
185
253
  const propsAttr = Object.keys(props).length > 0
186
254
  ? ` p="${escAttr(serializeIslandProps(props))}"`
187
255
  : ''
188
256
  const hydrateAttr = hydrate !== undefined && hydrate !== 'load'
189
257
  ? ` h="${escAttr(hydrate)}"`
190
258
  : ''
191
- const inner = hydrate === 'client' ? '' : render()
259
+ const inner = hydrate === 'client' ? '' : ssrInIsland(render)
192
260
 
193
261
  return `<kay-island c="${escAttr(chunk)}"${propsAttr}${hydrateAttr}>${inner}</kay-island>`
194
262
  }
package/src/test/index.ts CHANGED
@@ -10,6 +10,8 @@ export interface TestAppOptions extends Omit<BuildOptions, 'compile' | 'static'>
10
10
  lang?: string | undefined
11
11
  security?: ServerOptions['security']
12
12
  trustedOrigins?: string[] | undefined
13
+ trustProxy?: boolean | undefined
14
+ maxRequestBodySize?: number | undefined
13
15
  }
14
16
 
15
17
  export interface TestApp {
@@ -40,6 +42,8 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
40
42
  lang: options.lang,
41
43
  security: options.security,
42
44
  trustedOrigins: options.trustedOrigins,
45
+ trustProxy: options.trustProxy,
46
+ maxRequestBodySize: options.maxRequestBodySize,
43
47
  plugins: options.plugins,
44
48
  })
45
49