@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1
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/attrs.ts +35 -0
- package/src/build/bundle.ts +442 -0
- package/src/build/compile.ts +20 -11
- package/src/build/files.ts +136 -0
- package/src/build/graph.ts +158 -0
- package/src/build/index.ts +231 -1296
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +224 -0
- package/src/build/plugin-host.ts +184 -0
- package/src/build/prerender.ts +93 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +58 -0
- package/src/build/routes.ts +135 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +228 -114
- package/src/cli/index.ts +298 -79
- package/src/cli/new.ts +67 -35
- package/src/compiler/analyze.ts +666 -91
- package/src/compiler/dom.ts +822 -629
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +164 -21
- package/src/compiler/shared.ts +442 -0
- package/src/compiler/ssr.ts +390 -324
- package/src/context.ts +120 -0
- package/src/dev/index.ts +291 -76
- package/src/dom/action.ts +23 -13
- package/src/dom/extras.ts +157 -84
- package/src/dom/index.ts +154 -33
- package/src/dom/island.ts +117 -39
- package/src/dom/loop.ts +34 -21
- package/src/index.ts +2 -1
- package/src/jsx-runtime.ts +11 -0
- package/src/plugins/context.ts +57 -0
- package/src/plugins/index.ts +120 -17
- package/src/reactivity/index.ts +250 -157
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +37 -12
- package/src/server/action.ts +217 -74
- package/src/server/compress.ts +155 -56
- package/src/server/cookies.ts +59 -22
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +201 -33
- package/src/server/index.ts +964 -737
- package/src/server/loader.ts +120 -0
- package/src/server/router.ts +27 -8
- package/src/server/security.ts +87 -39
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +96 -10
- package/src/ssr/index.ts +225 -56
- package/src/style.ts +33 -0
- package/src/test/index.ts +5 -0
- package/src/unrenderable.ts +35 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// Filesystem server loader: reads `dist/manifest.json` (or falls back to `--static` dir server) and loads built modules.
|
|
2
|
+
|
|
3
|
+
import type { BuildManifest } from '../build/index'
|
|
4
|
+
import type { EmbeddedBody, KayApp, ServerOptions } from './http'
|
|
5
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
6
|
+
import { join, resolve } from 'node:path'
|
|
7
|
+
import { loadConfig, pickRuntimeConfig } from '../plugins/index'
|
|
8
|
+
import { createServerFromEmbedded } from './index'
|
|
9
|
+
import { createStaticDirServer } from './static-dir'
|
|
10
|
+
|
|
11
|
+
let serverLoadSeq = 0
|
|
12
|
+
|
|
13
|
+
export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
14
|
+
const root = resolve(options.root)
|
|
15
|
+
const fileConfig = await loadConfig(root)
|
|
16
|
+
const plugins = options.plugins ?? fileConfig.plugins ?? []
|
|
17
|
+
const outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
|
|
18
|
+
const clientDir = join(outDir, 'client')
|
|
19
|
+
const manifestPath = join(outDir, 'manifest.json')
|
|
20
|
+
const securityOpt = options.security ?? fileConfig.security
|
|
21
|
+
const trustProxy = options.trustProxy ?? fileConfig.trustProxy ?? false
|
|
22
|
+
const maxRequestBodySize = options.maxRequestBodySize ?? fileConfig.maxRequestBodySize
|
|
23
|
+
const isDev = options.dev ?? (process.env.KAY_DEV === '1')
|
|
24
|
+
|
|
25
|
+
if (!existsSync(manifestPath)) {
|
|
26
|
+
if (existsSync(outDir) && readdirSync(outDir).length > 0) {
|
|
27
|
+
return createStaticDirServer(
|
|
28
|
+
outDir,
|
|
29
|
+
options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
|
|
30
|
+
securityOpt,
|
|
31
|
+
(options.compress ?? fileConfig.compress) !== false,
|
|
32
|
+
trustProxy,
|
|
33
|
+
isDev,
|
|
34
|
+
)
|
|
35
|
+
}
|
|
36
|
+
throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
|
|
40
|
+
const modules: Record<string, unknown> = {}
|
|
41
|
+
const assets: Record<string, EmbeddedBody> = {}
|
|
42
|
+
const publicAssets: Record<string, EmbeddedBody> = {}
|
|
43
|
+
const publicEtags: Record<string, string> = {}
|
|
44
|
+
const prerenderedFiles: Record<string, string> = {}
|
|
45
|
+
const srcPublicDir = resolve(root, fileConfig.publicDir ?? 'public')
|
|
46
|
+
|
|
47
|
+
// Store file paths only (zero-copy Bun.file() serving, zero startup RAM bloat!)
|
|
48
|
+
for (const rel of manifest.assets) {
|
|
49
|
+
const abs = join(clientDir, rel)
|
|
50
|
+
if (existsSync(abs)) {
|
|
51
|
+
assets[rel] = abs
|
|
52
|
+
if (existsSync(`${abs}.br`))
|
|
53
|
+
assets[`${rel}.br`] = `${abs}.br`
|
|
54
|
+
if (existsSync(`${abs}.gz`))
|
|
55
|
+
assets[`${rel}.gz`] = `${abs}.gz`
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
for (const rel of manifest.publicFiles ?? []) {
|
|
60
|
+
const outAbs = join(outDir, 'public', rel)
|
|
61
|
+
const abs = existsSync(outAbs) ? outAbs : join(srcPublicDir, rel)
|
|
62
|
+
if (existsSync(abs)) {
|
|
63
|
+
publicAssets[rel] = abs
|
|
64
|
+
const st = statSync(abs)
|
|
65
|
+
publicEtags[rel] = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const loadStamp = `${Date.now()}-${++serverLoadSeq}`
|
|
70
|
+
const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${loadStamp}`))
|
|
71
|
+
const loadMod = async (rel: string) => {
|
|
72
|
+
if (!(rel in modules))
|
|
73
|
+
modules[rel] = await importModule(join(outDir, rel))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
for (const r of manifest.routes) {
|
|
77
|
+
await loadMod(r.file)
|
|
78
|
+
for (const l of r.layouts) await loadMod(l)
|
|
79
|
+
for (const m of r.middlewares) await loadMod(m)
|
|
80
|
+
if (r.prerendered) {
|
|
81
|
+
for (const relHtml of Object.values(r.prerendered)) {
|
|
82
|
+
const abs = join(outDir, relHtml)
|
|
83
|
+
if (existsSync(abs))
|
|
84
|
+
prerenderedFiles[relHtml] = abs
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (manifest.errorFile) await loadMod(manifest.errorFile)
|
|
89
|
+
if (manifest.notFoundFile) await loadMod(manifest.notFoundFile)
|
|
90
|
+
for (const a of manifest.actions) {
|
|
91
|
+
await loadMod(a.file)
|
|
92
|
+
for (const m of a.middlewares) await loadMod(m)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const runtimeConfig = pickRuntimeConfig(fileConfig)
|
|
96
|
+
return createServerFromEmbedded({
|
|
97
|
+
...runtimeConfig,
|
|
98
|
+
manifest,
|
|
99
|
+
modules,
|
|
100
|
+
assets,
|
|
101
|
+
publicAssets,
|
|
102
|
+
publicEtags,
|
|
103
|
+
prerendered: {},
|
|
104
|
+
prerenderedFiles,
|
|
105
|
+
root,
|
|
106
|
+
outDir,
|
|
107
|
+
publicDir: join(outDir, 'public'),
|
|
108
|
+
assetPrefix: options.assetPrefix ?? fileConfig.assetPrefix,
|
|
109
|
+
lang: options.lang ?? fileConfig.lang,
|
|
110
|
+
security: securityOpt,
|
|
111
|
+
trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
|
|
112
|
+
trustProxy,
|
|
113
|
+
maxRequestBodySize,
|
|
114
|
+
streamTimeout: options.streamTimeout ?? fileConfig.streamTimeout,
|
|
115
|
+
compress: options.compress ?? fileConfig.compress,
|
|
116
|
+
dev: isDev,
|
|
117
|
+
onError: options.onError ?? fileConfig.onError,
|
|
118
|
+
plugins,
|
|
119
|
+
})
|
|
120
|
+
}
|
package/src/server/router.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// File-based route matcher: static > [param] > [...catchall] priority sorting + param extraction.
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
const ENCODED_SLASH_RE = /%2f/i
|
|
4
|
+
|
|
5
|
+
interface RoutePattern<T> {
|
|
4
6
|
path: string
|
|
5
7
|
segments: string[]
|
|
6
8
|
isStatic: boolean
|
|
@@ -14,8 +16,13 @@ export interface RouteMatch<T> {
|
|
|
14
16
|
params: Record<string, string>
|
|
15
17
|
}
|
|
16
18
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
+
function normalizePath(path: string): string {
|
|
20
|
+
return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
|
|
24
|
+
const norm = normalizePath(path)
|
|
25
|
+
const clean = norm === '/' ? '' : norm.replace(/^\/|\/$/g, '')
|
|
19
26
|
const segments = clean === '' ? [] : clean.split('/')
|
|
20
27
|
let isStatic = true
|
|
21
28
|
let hasCatchAll = false
|
|
@@ -37,7 +44,7 @@ export function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
|
|
|
37
44
|
}
|
|
38
45
|
}
|
|
39
46
|
|
|
40
|
-
return { path, segments, isStatic, hasCatchAll, score, data }
|
|
47
|
+
return { path: norm, segments, isStatic, hasCatchAll, score, data }
|
|
41
48
|
}
|
|
42
49
|
|
|
43
50
|
export class Router<T> {
|
|
@@ -47,21 +54,28 @@ export class Router<T> {
|
|
|
47
54
|
add(path: string, data: T): void {
|
|
48
55
|
const compiled = compileRoutePattern(path, data)
|
|
49
56
|
if (compiled.isStatic) {
|
|
50
|
-
this.#staticRoutes.set(path, data)
|
|
57
|
+
this.#staticRoutes.set(compiled.path, data)
|
|
51
58
|
}
|
|
52
59
|
else {
|
|
53
|
-
this.#dynamicRoutes.
|
|
60
|
+
const existing = this.#dynamicRoutes.findIndex(r => r.path === compiled.path)
|
|
61
|
+
if (existing !== -1)
|
|
62
|
+
this.#dynamicRoutes[existing] = compiled
|
|
63
|
+
else
|
|
64
|
+
this.#dynamicRoutes.push(compiled)
|
|
54
65
|
this.#dynamicRoutes.sort((a, b) => b.score - a.score || b.segments.length - a.segments.length)
|
|
55
66
|
}
|
|
56
67
|
}
|
|
57
68
|
|
|
58
69
|
match(pathname: string): RouteMatch<T> | undefined {
|
|
59
|
-
const norm =
|
|
70
|
+
const norm = normalizePath(pathname)
|
|
60
71
|
|
|
61
72
|
const exact = this.#staticRoutes.get(norm)
|
|
62
73
|
if (exact !== undefined)
|
|
63
74
|
return { data: exact, params: {} }
|
|
64
75
|
|
|
76
|
+
if (this.#dynamicRoutes.length === 0)
|
|
77
|
+
return undefined
|
|
78
|
+
|
|
65
79
|
const parts = norm === '/' ? [] : norm.slice(1).split('/')
|
|
66
80
|
|
|
67
81
|
for (let i = 0; i < this.#dynamicRoutes.length; i++) {
|
|
@@ -84,7 +98,12 @@ export class Router<T> {
|
|
|
84
98
|
break
|
|
85
99
|
}
|
|
86
100
|
else if (seg.startsWith(':')) {
|
|
87
|
-
|
|
101
|
+
const rawSeg = parts[j]!
|
|
102
|
+
if (ENCODED_SLASH_RE.test(rawSeg)) {
|
|
103
|
+
matched = false
|
|
104
|
+
break
|
|
105
|
+
}
|
|
106
|
+
params[seg.slice(1)] = decodeSegment(rawSeg)
|
|
88
107
|
}
|
|
89
108
|
else if (seg !== parts[j]) {
|
|
90
109
|
matched = false
|
package/src/server/security.ts
CHANGED
|
@@ -56,7 +56,11 @@ export function withCspHashes(
|
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
addHashes('style-src', styleHashes)
|
|
59
|
+
if (directives.has('style-src-elem'))
|
|
60
|
+
addHashes('style-src-elem', styleHashes)
|
|
59
61
|
addHashes('script-src', scriptHashes)
|
|
62
|
+
if (directives.has('script-src-elem'))
|
|
63
|
+
addHashes('script-src-elem', scriptHashes)
|
|
60
64
|
|
|
61
65
|
return order.map((name) => {
|
|
62
66
|
const tokens = directives.get(name)!
|
|
@@ -64,55 +68,95 @@ export function withCspHashes(
|
|
|
64
68
|
}).join('; ')
|
|
65
69
|
}
|
|
66
70
|
|
|
71
|
+
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'"
|
|
72
|
+
export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
|
|
73
|
+
export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
|
|
74
|
+
|
|
67
75
|
export interface SecurityHeadersOptions {
|
|
68
76
|
frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
|
|
69
77
|
referrerPolicy?: string | false | undefined
|
|
70
78
|
contentTypeOptions?: boolean | undefined
|
|
71
|
-
|
|
79
|
+
permissionsPolicy?: string | false | undefined
|
|
80
|
+
csp?: string | false | undefined
|
|
81
|
+
hsts?: string | boolean | undefined
|
|
72
82
|
}
|
|
73
83
|
|
|
74
84
|
const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
|
75
85
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
86
|
+
/** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
|
|
87
|
+
export type TrustProxy = boolean | number
|
|
88
|
+
|
|
89
|
+
function proxyHops(trustProxy: TrustProxy): number {
|
|
90
|
+
return trustProxy === true ? 1 : trustProxy === false ? 0 : Math.max(0, Math.floor(trustProxy))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Proxies append to X-Forwarded-*, so only the entries the trusted hops wrote count: the one `hops` from the right.
|
|
94
|
+
function forwardedValue(request: Request, header: string, trustProxy: TrustProxy): string | undefined {
|
|
95
|
+
const hops = proxyHops(trustProxy)
|
|
96
|
+
if (hops === 0)
|
|
97
|
+
return undefined
|
|
98
|
+
const entries = (request.headers.get(header) ?? '').split(',').map(e => e.trim()).filter(e => e !== '')
|
|
99
|
+
return entries[Math.max(0, entries.length - hops)]
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function forwardedOrigin(request: Request, trustProxy: TrustProxy): string | undefined {
|
|
103
|
+
const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)
|
|
104
|
+
const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim()
|
|
105
|
+
if (!proto || !host)
|
|
106
|
+
return undefined
|
|
107
|
+
try {
|
|
108
|
+
return new URL(`${proto}://${host}`).origin
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return undefined
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Returns true when the request arrived over HTTPS (directly, or via X-Forwarded-Proto when `trustProxy` is true). */
|
|
116
|
+
export function isHttpsRequest(request: Request, trustProxy: TrustProxy = false): boolean {
|
|
117
|
+
return request.url.startsWith('https:')
|
|
118
|
+
|| forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase() === 'https'
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Extracts the client IP from the trusted proxies' headers, or falls back to the direct socket IP. */
|
|
122
|
+
export function getClientIp(request: Request, trustProxy: TrustProxy = false, remoteIp?: string): string | undefined {
|
|
123
|
+
if (proxyHops(trustProxy) > 0) {
|
|
124
|
+
const forwarded = forwardedValue(request, 'x-forwarded-for', trustProxy)
|
|
125
|
+
if (forwarded)
|
|
126
|
+
return forwarded
|
|
127
|
+
const realIp = request.headers.get('x-real-ip')?.trim()
|
|
128
|
+
if (realIp)
|
|
129
|
+
return realIp
|
|
88
130
|
}
|
|
89
|
-
return
|
|
131
|
+
return remoteIp || undefined
|
|
90
132
|
}
|
|
91
133
|
|
|
92
|
-
/** Returns true when `origin` matches the request's direct
|
|
134
|
+
/** Returns true when `origin` matches the request's direct (or trusted forwarded) origin or `trustedOrigins`. */
|
|
93
135
|
export function isTrustedOrigin(
|
|
94
136
|
origin: string,
|
|
95
137
|
request: Request,
|
|
96
138
|
trustedOrigins?: ReadonlySet<string>,
|
|
139
|
+
trustProxy: TrustProxy = false,
|
|
97
140
|
): boolean {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|| (forwardedOrigin !== undefined && origin === forwardedOrigin)
|
|
141
|
+
return origin === new URL(request.url).origin
|
|
142
|
+
|| origin === forwardedOrigin(request, trustProxy)
|
|
101
143
|
|| trustedOrigins?.has(origin) === true
|
|
102
144
|
}
|
|
103
145
|
|
|
104
146
|
/** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
|
|
105
|
-
export function verifyOrigin(
|
|
147
|
+
export function verifyOrigin(
|
|
148
|
+
request: Request,
|
|
149
|
+
trustedOrigins?: ReadonlySet<string>,
|
|
150
|
+
trustProxy: TrustProxy = false,
|
|
151
|
+
): { ok: true } | { ok: false, reason: string } {
|
|
106
152
|
if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
|
|
107
153
|
return { ok: true }
|
|
108
154
|
|
|
109
|
-
const { expectedOrigin, forwardedOrigin } = requestOrigins(request)
|
|
110
155
|
const origin = request.headers.get('origin')
|
|
111
|
-
|
|
112
156
|
if (origin !== null) {
|
|
113
|
-
if (
|
|
157
|
+
if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy))
|
|
114
158
|
return { ok: true }
|
|
115
|
-
return { ok: false, reason: `Cross-site request blocked: origin ${origin}
|
|
159
|
+
return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}` }
|
|
116
160
|
}
|
|
117
161
|
|
|
118
162
|
const fetchSite = request.headers.get('sec-fetch-site')
|
|
@@ -122,6 +166,22 @@ export function verifyOrigin(request: Request, trustedOrigins?: ReadonlySet<stri
|
|
|
122
166
|
return { ok: true }
|
|
123
167
|
}
|
|
124
168
|
|
|
169
|
+
export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
|
|
170
|
+
if (options === false)
|
|
171
|
+
return undefined
|
|
172
|
+
if (options?.csp === false)
|
|
173
|
+
return undefined
|
|
174
|
+
return options?.csp ?? DEFAULT_CSP
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function resolveHstsValue(options: SecurityHeadersOptions | false | undefined): string | undefined {
|
|
178
|
+
if (options === false)
|
|
179
|
+
return undefined
|
|
180
|
+
if (options?.hsts === false)
|
|
181
|
+
return undefined
|
|
182
|
+
return typeof options?.hsts === 'string' ? options.hsts : DEFAULT_HSTS
|
|
183
|
+
}
|
|
184
|
+
|
|
125
185
|
export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined): readonly [string, string][] {
|
|
126
186
|
if (options === false)
|
|
127
187
|
return []
|
|
@@ -133,21 +193,9 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
|
|
|
133
193
|
entries.push(['x-frame-options', opts.frameOptions ?? 'SAMEORIGIN'])
|
|
134
194
|
if (opts.referrerPolicy !== false)
|
|
135
195
|
entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
|
|
136
|
-
if (opts.
|
|
137
|
-
entries.push(['
|
|
196
|
+
if (opts.permissionsPolicy !== false)
|
|
197
|
+
entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
|
|
198
|
+
if (opts.csp !== false)
|
|
199
|
+
entries.push(['content-security-policy', opts.csp ?? DEFAULT_CSP])
|
|
138
200
|
return entries
|
|
139
201
|
}
|
|
140
|
-
|
|
141
|
-
export function applySecurityHeaders(headers: Headers, options: SecurityHeadersOptions = {}): void {
|
|
142
|
-
if ((options.contentTypeOptions ?? true) && !headers.has('x-content-type-options'))
|
|
143
|
-
headers.set('x-content-type-options', 'nosniff')
|
|
144
|
-
|
|
145
|
-
if (options.frameOptions !== false && !headers.has('x-frame-options'))
|
|
146
|
-
headers.set('x-frame-options', options.frameOptions ?? 'SAMEORIGIN')
|
|
147
|
-
|
|
148
|
-
if (options.referrerPolicy !== false && !headers.has('referrer-policy'))
|
|
149
|
-
headers.set('referrer-policy', options.referrerPolicy ?? 'strict-origin-when-cross-origin')
|
|
150
|
-
|
|
151
|
-
if (options.csp !== undefined && !headers.has('content-security-policy'))
|
|
152
|
-
headers.set('content-security-policy', options.csp)
|
|
153
|
-
}
|
|
@@ -36,21 +36,52 @@ export interface ValidationSuccess<T> {
|
|
|
36
36
|
|
|
37
37
|
export type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure
|
|
38
38
|
|
|
39
|
+
export function formatIssuePath(issue: StandardSchemaIssue): string {
|
|
40
|
+
if (!issue.path || issue.path.length === 0)
|
|
41
|
+
return ''
|
|
42
|
+
return issue.path
|
|
43
|
+
.map(seg => (typeof seg === 'object' && seg !== null && 'key' in seg ? String(seg.key) : String(seg)))
|
|
44
|
+
.join('.')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function formatSchemaIssues(issues: ReadonlyArray<StandardSchemaIssue>): string {
|
|
48
|
+
return issues
|
|
49
|
+
.map((issue) => {
|
|
50
|
+
const path = formatIssuePath(issue)
|
|
51
|
+
return path ? `${path}: ${issue.message}` : issue.message
|
|
52
|
+
})
|
|
53
|
+
.join('; ')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function buildValidationFailure(issues: ReadonlyArray<StandardSchemaIssue>): ValidationFailure {
|
|
57
|
+
const fieldErrors: Record<string, string> = {}
|
|
58
|
+
for (const issue of issues) {
|
|
59
|
+
const key = formatIssuePath(issue)
|
|
60
|
+
if (!Object.hasOwn(fieldErrors, key))
|
|
61
|
+
Object.defineProperty(fieldErrors, key, { value: issue.message, enumerable: true, writable: true, configurable: true })
|
|
62
|
+
}
|
|
63
|
+
return { ok: false, issues, fieldErrors }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function validateSchemaSync<S extends StandardSchemaV1>(
|
|
67
|
+
schema: S,
|
|
68
|
+
input: unknown,
|
|
69
|
+
asyncErrorMessage = 'kay: synchronous Standard Schema validator required',
|
|
70
|
+
): ValidationResult<InferOutput<S>> {
|
|
71
|
+
const res = schema['~standard'].validate(input)
|
|
72
|
+
if (res instanceof Promise)
|
|
73
|
+
throw new TypeError(asyncErrorMessage)
|
|
74
|
+
if (res.issues && res.issues.length > 0)
|
|
75
|
+
return buildValidationFailure(res.issues)
|
|
76
|
+
return { ok: true, value: (res as { value: InferOutput<S> }).value }
|
|
77
|
+
}
|
|
78
|
+
|
|
39
79
|
export async function validateSchema<S extends StandardSchemaV1>(
|
|
40
80
|
schema: S,
|
|
41
81
|
input: unknown,
|
|
42
82
|
): Promise<ValidationResult<InferOutput<S>>> {
|
|
43
83
|
const res = await schema['~standard'].validate(input)
|
|
44
|
-
if (res.issues && res.issues.length > 0)
|
|
45
|
-
|
|
46
|
-
for (const issue of res.issues) {
|
|
47
|
-
const key = issue.path && issue.path.length > 0
|
|
48
|
-
? issue.path.map(seg => (typeof seg === 'object' && seg !== null && 'key' in seg ? String(seg.key) : String(seg))).join('.')
|
|
49
|
-
: ''
|
|
50
|
-
if (!(key in fieldErrors))
|
|
51
|
-
fieldErrors[key] = issue.message
|
|
52
|
-
}
|
|
53
|
-
return { ok: false, issues: res.issues, fieldErrors }
|
|
54
|
-
}
|
|
84
|
+
if (res.issues && res.issues.length > 0)
|
|
85
|
+
return buildValidationFailure(res.issues)
|
|
55
86
|
return { ok: true, value: (res as { value: InferOutput<S> }).value }
|
|
56
87
|
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Standalone `--static` directory server (used when `outDir` holds exported HTML without `manifest.json`).
|
|
2
|
+
|
|
3
|
+
import type { Stats } from 'node:fs'
|
|
4
|
+
import type { KayApp } from './http'
|
|
5
|
+
import type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
6
|
+
import { existsSync, statSync } from 'node:fs'
|
|
7
|
+
import { extname, join, resolve } from 'node:path'
|
|
8
|
+
import { CompressionCache, isCompressibleType, maybeCompressResponse, pickPrecompressedEncoding, toWeakEtag } from './compress'
|
|
9
|
+
import { applyHstsHeader, etagMatches, MIME } from './http'
|
|
10
|
+
import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
|
|
11
|
+
|
|
12
|
+
const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
|
|
13
|
+
|
|
14
|
+
export function createStaticDirServer(
|
|
15
|
+
outDir: string,
|
|
16
|
+
assetPrefix: string,
|
|
17
|
+
security: SecurityHeadersOptions | false | undefined,
|
|
18
|
+
compressEnabled: boolean,
|
|
19
|
+
trustProxy: TrustProxy,
|
|
20
|
+
isDev = false,
|
|
21
|
+
): KayApp {
|
|
22
|
+
const cleanPrefix = `${assetPrefix.replace(/\/$/, '')}/`
|
|
23
|
+
const absRoot = resolve(outDir)
|
|
24
|
+
const compressCache = compressEnabled ? new CompressionCache() : undefined
|
|
25
|
+
const securityEntries = buildSecurityHeaderEntries(security)
|
|
26
|
+
const baseCsp = resolveCspPolicy(security)
|
|
27
|
+
const htmlCsp = baseCsp !== undefined ? withCspHashes(baseCsp, { styleHashes: [KAY_ISLAND_STYLE_HASH] }) : undefined
|
|
28
|
+
const htmlSecurityEntries: [string, string][] = securityEntries.map(([k, v]) =>
|
|
29
|
+
k === 'content-security-policy' && htmlCsp !== undefined ? [k, htmlCsp] : [k, v],
|
|
30
|
+
)
|
|
31
|
+
const hstsValue = resolveHstsValue(security)
|
|
32
|
+
const withHsts = (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev)
|
|
33
|
+
|
|
34
|
+
function statFile(abs: string): Stats | undefined {
|
|
35
|
+
try {
|
|
36
|
+
const st = statSync(abs, { throwIfNoEntry: false })
|
|
37
|
+
return st?.isFile() ? st : undefined
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return undefined
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function resolveStaticFile(pathname: string): { path: string, st: Stats } | undefined {
|
|
45
|
+
let decoded: string
|
|
46
|
+
try {
|
|
47
|
+
decoded = decodeURIComponent(pathname)
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return undefined
|
|
51
|
+
}
|
|
52
|
+
if (decoded.includes('\0'))
|
|
53
|
+
return undefined
|
|
54
|
+
const rel = decoded.replace(/^\/+/, '').replace(/\/+$/, '')
|
|
55
|
+
const candidates = rel === ''
|
|
56
|
+
? ['index.html']
|
|
57
|
+
: [rel, `${rel}.html`, `${rel}/index.html`]
|
|
58
|
+
for (const c of candidates) {
|
|
59
|
+
const abs = resolve(absRoot, c)
|
|
60
|
+
if (abs !== absRoot && !abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
|
|
61
|
+
continue
|
|
62
|
+
const st = statFile(abs)
|
|
63
|
+
if (st !== undefined)
|
|
64
|
+
return { path: abs, st }
|
|
65
|
+
}
|
|
66
|
+
return undefined
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const initHeaders = (isHtml = false): Headers => new Headers((isHtml ? htmlSecurityEntries : securityEntries) as [string, string][])
|
|
70
|
+
|
|
71
|
+
const handle = async (req: Request): Promise<Response> => {
|
|
72
|
+
if (!isRead(req)) {
|
|
73
|
+
const headers = initHeaders()
|
|
74
|
+
headers.set('allow', 'GET, HEAD')
|
|
75
|
+
return withHsts(new Response('Method Not Allowed', { status: 405, headers }), req)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const url = new URL(req.url)
|
|
79
|
+
const found = resolveStaticFile(url.pathname)
|
|
80
|
+
if (found === undefined) {
|
|
81
|
+
const notFoundPath = join(absRoot, '404.html')
|
|
82
|
+
if (statFile(notFoundPath) !== undefined) {
|
|
83
|
+
const headers = initHeaders(true)
|
|
84
|
+
headers.set('content-type', 'text/html; charset=utf-8')
|
|
85
|
+
return withHsts(new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers }), req)
|
|
86
|
+
}
|
|
87
|
+
return withHsts(new Response('Not Found', { status: 404, headers: initHeaders() }), req)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const { path: filePath, st } = found
|
|
91
|
+
const ext = extname(filePath).toLowerCase()
|
|
92
|
+
const mime = MIME[ext] ?? 'application/octet-stream'
|
|
93
|
+
const isHtml = ext === '.html' || ext === '.htm'
|
|
94
|
+
const etag = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
|
|
95
|
+
const isImmutable = url.pathname.startsWith(cleanPrefix)
|
|
96
|
+
const headers = initHeaders(isHtml)
|
|
97
|
+
headers.set('content-type', mime)
|
|
98
|
+
headers.set('cache-control', isImmutable ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate')
|
|
99
|
+
headers.set('etag', etag)
|
|
100
|
+
|
|
101
|
+
const hasBr = compressEnabled && existsSync(`${filePath}.br`)
|
|
102
|
+
const hasGz = compressEnabled && existsSync(`${filePath}.gz`)
|
|
103
|
+
if (hasBr || hasGz || (compressEnabled && isCompressibleType(mime)))
|
|
104
|
+
headers.set('vary', 'Accept-Encoding')
|
|
105
|
+
|
|
106
|
+
if (etagMatches(req.headers.get('if-none-match'), etag))
|
|
107
|
+
return withHsts(new Response(null, { status: 304, headers }), req)
|
|
108
|
+
|
|
109
|
+
if (compressEnabled && req.method !== 'HEAD' && (hasBr || hasGz)) {
|
|
110
|
+
const preEnc = pickPrecompressedEncoding(req.headers.get('accept-encoding'), { br: hasBr, gz: hasGz })
|
|
111
|
+
if (preEnc !== undefined) {
|
|
112
|
+
headers.set('content-encoding', preEnc)
|
|
113
|
+
headers.set('etag', toWeakEtag(etag))
|
|
114
|
+
return withHsts(new Response(Bun.file(`${filePath}.${preEnc === 'br' ? 'br' : 'gz'}`), { status: 200, headers }), req)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
headers.set('content-length', String(st.size))
|
|
119
|
+
const res = new Response(req.method === 'HEAD' ? null : Bun.file(filePath), { status: 200, headers })
|
|
120
|
+
if (!compressEnabled || req.method === 'HEAD')
|
|
121
|
+
return withHsts(res, req)
|
|
122
|
+
return withHsts(await maybeCompressResponse(res, req, compressCache), req)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
handle,
|
|
127
|
+
serve(port = 3000, hostname = '127.0.0.1') {
|
|
128
|
+
return Bun.serve({
|
|
129
|
+
port,
|
|
130
|
+
hostname,
|
|
131
|
+
idleTimeout: 30,
|
|
132
|
+
development: false,
|
|
133
|
+
fetch: handle,
|
|
134
|
+
error() {
|
|
135
|
+
return new Response('Internal Server Error', {
|
|
136
|
+
status: 500,
|
|
137
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', ...Object.fromEntries(securityEntries) },
|
|
138
|
+
})
|
|
139
|
+
},
|
|
140
|
+
})
|
|
141
|
+
},
|
|
142
|
+
async dispose() {},
|
|
143
|
+
}
|
|
144
|
+
}
|