@kayjs/kay 2.0.0-alpha.4 → 2.0.0-alpha.6

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.
@@ -1,4 +1,68 @@
1
- // Built-in security basics: CSRF/Origin verification on state-changing requests + safe default headers.
1
+ // Built-in security basics: CSRF/Origin verification on state-changing requests + safe default headers + strict CSP hashes.
2
+
3
+ import { KAY_STREAM_SCRIPT } from '../ssr/context'
4
+ import { KAY_ISLAND_STYLE, KAY_SUSPENSE_STYLE } from '../ssr/index'
5
+
6
+ function cspSha256(content: string): string {
7
+ const digest = new Bun.CryptoHasher('sha256').update(content).digest('base64')
8
+ return `'sha256-${digest}'`
9
+ }
10
+
11
+ export const KAY_ISLAND_STYLE_HASH = cspSha256(KAY_ISLAND_STYLE)
12
+ export const KAY_SUSPENSE_STYLE_HASH = cspSha256(KAY_SUSPENSE_STYLE)
13
+ export const KAY_STREAM_SCRIPT_HASH = cspSha256(KAY_STREAM_SCRIPT)
14
+
15
+ /** Augments a Content-Security-Policy header with exact SHA-256 hashes (no `'unsafe-inline'` required). */
16
+ export function withCspHashes(
17
+ csp: string,
18
+ opts: { styleHashes?: readonly string[], scriptHashes?: readonly string[] },
19
+ ): string {
20
+ const styleHashes = opts.styleHashes ?? []
21
+ const scriptHashes = opts.scriptHashes ?? []
22
+ if (styleHashes.length === 0 && scriptHashes.length === 0)
23
+ return csp
24
+
25
+ const rawParts = csp.split(';').map(s => s.trim()).filter(Boolean)
26
+ const directives = new Map<string, string[]>()
27
+ const order: string[] = []
28
+ for (const part of rawParts) {
29
+ const tokens = part.split(/\s+/)
30
+ const name = tokens[0]!.toLowerCase()
31
+ if (!directives.has(name)) {
32
+ order.push(name)
33
+ directives.set(name, tokens.slice(1))
34
+ }
35
+ }
36
+
37
+ const defaultSrc = directives.get('default-src') ?? ["'self'"]
38
+ const addHashes = (dirName: string, hashes: readonly string[]) => {
39
+ if (hashes.length === 0)
40
+ return
41
+ let tokens = directives.get(dirName)
42
+ if (tokens === undefined) {
43
+ tokens = [...defaultSrc]
44
+ directives.set(dirName, tokens)
45
+ order.push(dirName)
46
+ }
47
+ if (tokens.includes("'unsafe-inline'"))
48
+ return
49
+ const noneIdx = tokens.indexOf("'none'")
50
+ if (noneIdx !== -1)
51
+ tokens.splice(noneIdx, 1)
52
+ for (const h of hashes) {
53
+ if (!tokens.includes(h))
54
+ tokens.push(h)
55
+ }
56
+ }
57
+
58
+ addHashes('style-src', styleHashes)
59
+ addHashes('script-src', scriptHashes)
60
+
61
+ return order.map((name) => {
62
+ const tokens = directives.get(name)!
63
+ return tokens.length > 0 ? `${name} ${tokens.join(' ')}` : name
64
+ }).join('; ')
65
+ }
2
66
 
3
67
  export interface SecurityHeadersOptions {
4
68
  frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
@@ -9,16 +73,40 @@ export interface SecurityHeadersOptions {
9
73
 
10
74
  const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
11
75
 
76
+ function requestOrigins(request: Request): { expectedOrigin: string, forwardedOrigin: string | undefined } {
77
+ 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
+ let forwardedOrigin: string | undefined
81
+ if (fwdProto && fwdHost) {
82
+ try {
83
+ forwardedOrigin = new URL(`${fwdProto}://${fwdHost}`).origin
84
+ }
85
+ catch {
86
+ forwardedOrigin = `${fwdProto}://${fwdHost}`
87
+ }
88
+ }
89
+ return { expectedOrigin, forwardedOrigin }
90
+ }
91
+
92
+ /** Returns true when `origin` matches the request's direct/forwarded origin or `trustedOrigins`. */
93
+ export function isTrustedOrigin(
94
+ origin: string,
95
+ request: Request,
96
+ trustedOrigins?: ReadonlySet<string>,
97
+ ): boolean {
98
+ const { expectedOrigin, forwardedOrigin } = requestOrigins(request)
99
+ return origin === expectedOrigin
100
+ || (forwardedOrigin !== undefined && origin === forwardedOrigin)
101
+ || trustedOrigins?.has(origin) === true
102
+ }
103
+
12
104
  /** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
13
105
  export function verifyOrigin(request: Request, trustedOrigins?: ReadonlySet<string>): { ok: true } | { ok: false, reason: string } {
14
106
  if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
15
107
  return { ok: true }
16
108
 
17
- const url = new URL(request.url)
18
- const expectedOrigin = url.origin
19
- const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim()
20
- const fwdHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() || request.headers.get('host')?.trim()
21
- const forwardedOrigin = fwdProto && fwdHost ? `${fwdProto}://${fwdHost}` : undefined
109
+ const { expectedOrigin, forwardedOrigin } = requestOrigins(request)
22
110
  const origin = request.headers.get('origin')
23
111
 
24
112
  if (origin !== null) {
@@ -34,6 +122,22 @@ export function verifyOrigin(request: Request, trustedOrigins?: ReadonlySet<stri
34
122
  return { ok: true }
35
123
  }
36
124
 
125
+ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined): readonly [string, string][] {
126
+ if (options === false)
127
+ return []
128
+ const opts = options ?? {}
129
+ const entries: [string, string][] = []
130
+ if (opts.contentTypeOptions ?? true)
131
+ entries.push(['x-content-type-options', 'nosniff'])
132
+ if (opts.frameOptions !== false)
133
+ entries.push(['x-frame-options', opts.frameOptions ?? 'SAMEORIGIN'])
134
+ if (opts.referrerPolicy !== false)
135
+ entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
136
+ if (opts.csp !== undefined)
137
+ entries.push(['content-security-policy', opts.csp])
138
+ return entries
139
+ }
140
+
37
141
  export function applySecurityHeaders(headers: Headers, options: SecurityHeadersOptions = {}): void {
38
142
  if ((options.contentTypeOptions ?? true) && !headers.has('x-content-type-options'))
39
143
  headers.set('x-content-type-options', 'nosniff')
@@ -81,9 +81,12 @@ export function Suspense(props: { fallback?: KayChild, children?: KayChild | Pro
81
81
  })
82
82
 
83
83
  const fallbackHtml = ssrChild(props.fallback)
84
- return raw(`<div id="k-s-${id}" style="display:contents">${fallbackHtml}</div>`)
84
+ return raw(`<kay-s id="k-s-${id}">${fallbackHtml}</kay-s>`)
85
85
  }
86
86
 
87
+ /** Fixed streaming swap bootstrap (constant content -> deterministic SHA-256 CSP hash, zero per-chunk inline scripts). */
88
+ export const KAY_STREAM_SCRIPT = `(()=>{const w=n=>{if(n.nodeType===1&&n.tagName==='TEMPLATE'&&n.dataset.ks){const s=document.getElementById('k-s-'+n.dataset.ks);if(s){s.replaceWith(n.content);n.remove()}}};const o=new MutationObserver(ms=>{for(const m of ms)for(const n of m.addedNodes)w(n)});o.observe(document.documentElement,{childList:true,subtree:true});document.addEventListener('DOMContentLoaded',()=>{document.querySelectorAll('template[data-ks]').forEach(w);o.disconnect()},{once:true})})()`
89
+
87
90
  export function streamChunkScript(id: number, resolvedHtml: string): string {
88
- return `<template id="k-p-${id}">${resolvedHtml}</template><script>(()=>{let s=document.getElementById("k-s-${id}"),t=document.getElementById("k-p-${id}");if(s&&t){s.replaceWith(t.content);t.remove()}document.currentScript?.remove()})()</script>`
91
+ return `<template data-ks="${id}">${resolvedHtml}</template>`
89
92
  }
package/src/ssr/index.ts CHANGED
@@ -1,6 +1,10 @@
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'
5
+
6
+ export const KAY_ISLAND_STYLE = 'kay-island,kay-slot{display:contents}'
7
+ export const KAY_SUSPENSE_STYLE = 'kay-s{display:contents}'
4
8
 
5
9
  const ESC_TEXT = /[&<>]/
6
10
  const ESC_ATTR = /[&"<>]/
@@ -42,6 +46,27 @@ export function ssrRaw(value: unknown): string {
42
46
  return String(value)
43
47
  }
44
48
 
49
+ const CLOSE_STYLE_RE = /<\/(style)/gi
50
+ const CLOSE_SCRIPT_RE = /<\/(script)/gi
51
+
52
+ /** Emits raw text inside `<style>` or `<script>` without HTML entity escaping, neutralizing only its closing tag. */
53
+ export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
54
+ if (value == null || typeof value === 'boolean')
55
+ return ''
56
+ if (Array.isArray(value)) {
57
+ let out = ''
58
+ for (let i = 0; i < value.length; i++)
59
+ out += ssrRawText(tag, value[i])
60
+ return out
61
+ }
62
+ const str = typeof value === 'string'
63
+ ? value
64
+ : typeof value === 'object' && '__html' in value
65
+ ? String((value as Html).__html)
66
+ : String(value)
67
+ return str.replace(tag === 'script' ? CLOSE_SCRIPT_RE : CLOSE_STYLE_RE, '<\\/$1')
68
+ }
69
+
45
70
  export function escAttr(value: unknown): string {
46
71
  const str = String(value)
47
72
  if (bunEscape !== undefined)
@@ -131,6 +156,25 @@ export function ssrChild(value: KayChild): string {
131
156
  return esc(String(value))
132
157
  }
133
158
 
159
+ function serializeIslandProps(props: Record<string, unknown>): string {
160
+ return JSON.stringify(props, function (this: Record<string, unknown>, key: string, value: unknown) {
161
+ const orig = key !== '' && this != null && typeof this === 'object' ? this[key] : value
162
+ if (orig instanceof Date)
163
+ return { __k: 'D', v: orig.toISOString() }
164
+ if (orig instanceof Set)
165
+ return { __k: 'S', v: [...orig] }
166
+ if (orig instanceof Map)
167
+ return { __k: 'M', v: [...orig.entries()] }
168
+ if (orig instanceof URL)
169
+ return { __k: 'U', v: orig.href }
170
+ if (orig instanceof RegExp)
171
+ return { __k: 'R', v: [orig.source, orig.flags] }
172
+ if (typeof orig === 'bigint')
173
+ return { __k: 'B', v: orig.toString() }
174
+ return value
175
+ })
176
+ }
177
+
134
178
  export function ssrIsland(
135
179
  _id: string,
136
180
  chunk: string,
@@ -139,7 +183,7 @@ export function ssrIsland(
139
183
  hydrate?: HydrateStrategy,
140
184
  ): string {
141
185
  const propsAttr = Object.keys(props).length > 0
142
- ? ` p="${escAttr(JSON.stringify(props))}"`
186
+ ? ` p="${escAttr(serializeIslandProps(props))}"`
143
187
  : ''
144
188
  const hydrateAttr = hydrate !== undefined && hydrate !== 'load'
145
189
  ? ` h="${escAttr(hydrate)}"`
@@ -159,10 +203,11 @@ export interface DocumentOptions {
159
203
  preloadChunks?: Iterable<string> | undefined
160
204
  styles?: Iterable<string> | undefined
161
205
  hasIslands?: boolean | undefined
206
+ hasSuspense?: boolean | undefined
162
207
  }
163
208
 
164
209
  export function renderDocument(options: DocumentOptions): string {
165
- const { body, head = '', headTags, lang = 'en', runtimeScript, alwaysLoadRuntime, preloadChunks, styles, hasIslands } = options
210
+ const { body, head = '', headTags, lang = 'en', runtimeScript, alwaysLoadRuntime, preloadChunks, styles, hasIslands, hasSuspense } = options
166
211
  let headExtra = head
167
212
 
168
213
  if (headTags !== undefined) {
@@ -176,13 +221,16 @@ export function renderDocument(options: DocumentOptions): string {
176
221
  }
177
222
 
178
223
  if (hasIslands) {
179
- headExtra += '<style>kay-island,kay-slot{display:contents}</style>'
224
+ headExtra += `<style>${KAY_ISLAND_STYLE}</style>`
180
225
  if (preloadChunks !== undefined) {
181
226
  for (const href of preloadChunks)
182
227
  headExtra += `<link rel="modulepreload" href="${escAttr(href)}">`
183
228
  }
184
229
  }
185
230
 
231
+ if (hasSuspense)
232
+ headExtra += `<style>${KAY_SUSPENSE_STYLE}</style><script>${KAY_STREAM_SCRIPT}</script>`
233
+
186
234
  if (runtimeScript !== undefined && (hasIslands || alwaysLoadRuntime))
187
235
  headExtra += `<script type="module" src="${escAttr(runtimeScript)}"></script>`
188
236