@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.2
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 +615 -0
- package/src/build/compile.ts +32 -19
- package/src/build/files.ts +174 -0
- package/src/build/graph.ts +223 -0
- package/src/build/index.ts +255 -1461
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +227 -0
- package/src/build/plugin-host.ts +186 -0
- package/src/build/prerender.ts +94 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +51 -0
- package/src/build/routes.ts +163 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +300 -129
- package/src/cli/index.ts +297 -94
- package/src/cli/new.ts +58 -38
- package/src/compiler/analyze.ts +723 -93
- package/src/compiler/dom.ts +848 -762
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +172 -23
- package/src/compiler/shared.ts +485 -0
- package/src/compiler/ssr.ts +331 -342
- package/src/context.ts +120 -0
- package/src/dev/index.ts +358 -76
- package/src/dom/action.ts +114 -14
- package/src/dom/extras.ts +121 -83
- package/src/dom/index.ts +122 -80
- package/src/dom/island.ts +71 -36
- package/src/dom/loop.ts +28 -20
- package/src/index.ts +5 -1
- package/src/jsx-runtime.ts +432 -93
- package/src/plugins/context.ts +83 -0
- package/src/plugins/index.ts +285 -23
- package/src/reactivity/index.ts +237 -213
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +36 -11
- package/src/server/action.ts +157 -79
- package/src/server/compress.ts +197 -104
- package/src/server/cookies.ts +46 -16
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +189 -77
- package/src/server/index.ts +1024 -878
- package/src/server/loader.ts +138 -0
- package/src/server/router.ts +69 -26
- package/src/server/security.ts +50 -58
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +95 -10
- package/src/ssr/index.ts +167 -66
- package/src/style.ts +33 -0
- package/src/test/index.ts +5 -15
- package/src/unrenderable.ts +35 -0
|
@@ -0,0 +1,138 @@
|
|
|
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 { KayConfig } from '../plugins/index'
|
|
5
|
+
import type { EmbeddedBody, KayApp, ServerOptions } from './http'
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
7
|
+
import { join, resolve } from 'node:path'
|
|
8
|
+
import { loadConfig, resolveServerConfig } from '../plugins/index'
|
|
9
|
+
import { createServerFromEmbedded } from './index'
|
|
10
|
+
import { createStaticDirServer } from './static-dir'
|
|
11
|
+
|
|
12
|
+
let serverLoadSeq = 0
|
|
13
|
+
|
|
14
|
+
export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
15
|
+
const root = resolve(options.root)
|
|
16
|
+
const loadStamp = `${Date.now()}-${++serverLoadSeq}`
|
|
17
|
+
const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${loadStamp}`))
|
|
18
|
+
const isDev = options.dev ?? (process.env.KAY_DEV === '1')
|
|
19
|
+
|
|
20
|
+
// When a bundled `manifest.configFile` exists and plugins were not explicitly overridden,
|
|
21
|
+
// load the bundled config module so it shares the exact same chunk instances as routes & actions.
|
|
22
|
+
const initialOutDir = resolve(root, options.outDir ?? 'dist')
|
|
23
|
+
const initialManifestPath = join(initialOutDir, 'manifest.json')
|
|
24
|
+
let fileConfig: KayConfig
|
|
25
|
+
let outDir: string
|
|
26
|
+
let manifest: BuildManifest
|
|
27
|
+
|
|
28
|
+
if (options.plugins === undefined && existsSync(initialManifestPath)) {
|
|
29
|
+
outDir = initialOutDir
|
|
30
|
+
manifest = JSON.parse(readFileSync(initialManifestPath, 'utf8')) as BuildManifest
|
|
31
|
+
if (manifest.configFile !== undefined) {
|
|
32
|
+
const cfgMod = await importModule(join(outDir, manifest.configFile))
|
|
33
|
+
const loaded = (cfgMod.default ?? cfgMod) as KayConfig | undefined
|
|
34
|
+
fileConfig = loaded !== undefined && typeof loaded === 'object' ? loaded : {}
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
fileConfig = await loadConfig(root)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
fileConfig = await loadConfig(root)
|
|
42
|
+
outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
|
|
43
|
+
const manifestPath = join(outDir, 'manifest.json')
|
|
44
|
+
if (!existsSync(manifestPath)) {
|
|
45
|
+
const securityOpt = options.security ?? fileConfig.security
|
|
46
|
+
const trustProxy = options.trustProxy ?? fileConfig.trustProxy ?? false
|
|
47
|
+
if (existsSync(outDir) && readdirSync(outDir).length > 0) {
|
|
48
|
+
return createStaticDirServer(
|
|
49
|
+
outDir,
|
|
50
|
+
options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
|
|
51
|
+
securityOpt,
|
|
52
|
+
(options.compress ?? fileConfig.compress) !== false,
|
|
53
|
+
trustProxy,
|
|
54
|
+
isDev,
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
|
|
58
|
+
}
|
|
59
|
+
manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
|
|
60
|
+
if (options.plugins === undefined && manifest.configFile !== undefined) {
|
|
61
|
+
const cfgMod = await importModule(join(outDir, manifest.configFile))
|
|
62
|
+
const loaded = (cfgMod.default ?? cfgMod) as KayConfig | undefined
|
|
63
|
+
if (loaded !== undefined && typeof loaded === 'object')
|
|
64
|
+
fileConfig = loaded
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const runtimeConfig = resolveServerConfig(fileConfig, options)
|
|
69
|
+
const clientDir = join(outDir, 'client')
|
|
70
|
+
|
|
71
|
+
const modules: Record<string, unknown> = {}
|
|
72
|
+
const assets: Record<string, EmbeddedBody> = {}
|
|
73
|
+
const publicAssets: Record<string, EmbeddedBody> = {}
|
|
74
|
+
const publicEtags: Record<string, string> = {}
|
|
75
|
+
const prerenderedFiles: Record<string, string> = {}
|
|
76
|
+
const srcPublicDir = resolve(root, fileConfig.publicDir ?? 'public')
|
|
77
|
+
|
|
78
|
+
// Store file paths only (zero-copy Bun.file() serving, zero startup RAM bloat!)
|
|
79
|
+
for (const rel of manifest.assets) {
|
|
80
|
+
const abs = join(clientDir, rel)
|
|
81
|
+
if (existsSync(abs)) {
|
|
82
|
+
assets[rel] = abs
|
|
83
|
+
if (existsSync(`${abs}.br`))
|
|
84
|
+
assets[`${rel}.br`] = `${abs}.br`
|
|
85
|
+
if (existsSync(`${abs}.gz`))
|
|
86
|
+
assets[`${rel}.gz`] = `${abs}.gz`
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
for (const rel of manifest.publicFiles ?? []) {
|
|
91
|
+
const outAbs = join(outDir, 'public', rel)
|
|
92
|
+
const abs = existsSync(outAbs) ? outAbs : join(srcPublicDir, rel)
|
|
93
|
+
if (existsSync(abs)) {
|
|
94
|
+
publicAssets[rel] = abs
|
|
95
|
+
const st = statSync(abs)
|
|
96
|
+
publicEtags[rel] = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const loadMod = async (rel: string) => {
|
|
101
|
+
if (!(rel in modules))
|
|
102
|
+
modules[rel] = await importModule(join(outDir, rel))
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
for (const r of manifest.routes) {
|
|
106
|
+
await loadMod(r.file)
|
|
107
|
+
for (const l of r.layouts) await loadMod(l)
|
|
108
|
+
for (const m of r.middlewares) await loadMod(m)
|
|
109
|
+
if (r.prerendered) {
|
|
110
|
+
for (const relHtml of Object.values(r.prerendered)) {
|
|
111
|
+
const abs = join(outDir, relHtml)
|
|
112
|
+
if (existsSync(abs))
|
|
113
|
+
prerenderedFiles[relHtml] = abs
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (manifest.rootLayoutFile) await loadMod(manifest.rootLayoutFile)
|
|
118
|
+
if (manifest.errorFile) await loadMod(manifest.errorFile)
|
|
119
|
+
if (manifest.notFoundFile) await loadMod(manifest.notFoundFile)
|
|
120
|
+
for (const a of manifest.actions) {
|
|
121
|
+
await loadMod(a.file)
|
|
122
|
+
for (const m of a.middlewares) await loadMod(m)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return createServerFromEmbedded({
|
|
126
|
+
...runtimeConfig,
|
|
127
|
+
manifest,
|
|
128
|
+
modules,
|
|
129
|
+
assets,
|
|
130
|
+
publicAssets,
|
|
131
|
+
publicEtags,
|
|
132
|
+
prerenderedFiles,
|
|
133
|
+
root,
|
|
134
|
+
outDir,
|
|
135
|
+
publicDir: join(outDir, 'public'),
|
|
136
|
+
dev: isDev,
|
|
137
|
+
})
|
|
138
|
+
}
|
package/src/server/router.ts
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
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
|
+
const enum SegmentKind {
|
|
6
|
+
Static = 0,
|
|
7
|
+
Param = 1,
|
|
8
|
+
CatchAll = 2,
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface CompiledSegment {
|
|
12
|
+
kind: SegmentKind
|
|
13
|
+
/** Exact literal for Static, parameter name for Param/CatchAll. */
|
|
14
|
+
value: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface RoutePattern<T> {
|
|
4
18
|
path: string
|
|
5
|
-
segments:
|
|
19
|
+
segments: CompiledSegment[]
|
|
6
20
|
isStatic: boolean
|
|
7
21
|
hasCatchAll: boolean
|
|
8
22
|
score: number
|
|
@@ -14,57 +28,80 @@ export interface RouteMatch<T> {
|
|
|
14
28
|
params: Record<string, string>
|
|
15
29
|
}
|
|
16
30
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
31
|
+
function normalizePath(path: string): string {
|
|
32
|
+
return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
|
|
36
|
+
const norm = normalizePath(path)
|
|
37
|
+
const clean = norm === '/' ? '' : norm.replace(/^\/|\/$/g, '')
|
|
38
|
+
const rawSegments = clean === '' ? [] : clean.split('/')
|
|
39
|
+
const segments: CompiledSegment[] = []
|
|
20
40
|
let isStatic = true
|
|
21
41
|
let hasCatchAll = false
|
|
22
42
|
let score = 0
|
|
23
43
|
|
|
24
|
-
for (let i = 0; i <
|
|
25
|
-
const seg =
|
|
44
|
+
for (let i = 0; i < rawSegments.length; i++) {
|
|
45
|
+
const seg = rawSegments[i]!
|
|
26
46
|
if (seg.startsWith('*')) {
|
|
27
47
|
isStatic = false
|
|
28
48
|
hasCatchAll = true
|
|
29
49
|
score += 1
|
|
50
|
+
segments.push({ kind: SegmentKind.CatchAll, value: seg.slice(1) || 'rest' })
|
|
30
51
|
}
|
|
31
52
|
else if (seg.startsWith(':')) {
|
|
32
53
|
isStatic = false
|
|
33
54
|
score += 10
|
|
55
|
+
segments.push({ kind: SegmentKind.Param, value: seg.slice(1) })
|
|
34
56
|
}
|
|
35
57
|
else {
|
|
36
58
|
score += 100
|
|
59
|
+
segments.push({ kind: SegmentKind.Static, value: seg })
|
|
37
60
|
}
|
|
38
61
|
}
|
|
39
62
|
|
|
40
|
-
return { path, segments, isStatic, hasCatchAll, score, data }
|
|
63
|
+
return { path: norm, segments, isStatic, hasCatchAll, score, data }
|
|
41
64
|
}
|
|
42
65
|
|
|
43
66
|
export class Router<T> {
|
|
44
67
|
readonly #staticRoutes = new Map<string, T>()
|
|
45
68
|
readonly #dynamicRoutes: RoutePattern<T>[] = []
|
|
69
|
+
#sorted = true
|
|
46
70
|
|
|
47
71
|
add(path: string, data: T): void {
|
|
48
72
|
const compiled = compileRoutePattern(path, data)
|
|
49
73
|
if (compiled.isStatic) {
|
|
50
|
-
this.#staticRoutes.set(path, data)
|
|
74
|
+
this.#staticRoutes.set(compiled.path, data)
|
|
51
75
|
}
|
|
52
76
|
else {
|
|
53
|
-
this.#dynamicRoutes.
|
|
54
|
-
|
|
77
|
+
const existing = this.#dynamicRoutes.findIndex(r => r.path === compiled.path)
|
|
78
|
+
if (existing !== -1)
|
|
79
|
+
this.#dynamicRoutes[existing] = compiled
|
|
80
|
+
else
|
|
81
|
+
this.#dynamicRoutes.push(compiled)
|
|
82
|
+
this.#sorted = false
|
|
55
83
|
}
|
|
56
84
|
}
|
|
57
85
|
|
|
58
86
|
match(pathname: string): RouteMatch<T> | undefined {
|
|
59
|
-
const norm =
|
|
87
|
+
const norm = normalizePath(pathname)
|
|
60
88
|
|
|
61
89
|
const exact = this.#staticRoutes.get(norm)
|
|
62
90
|
if (exact !== undefined)
|
|
63
91
|
return { data: exact, params: {} }
|
|
64
92
|
|
|
93
|
+
const dynLen = this.#dynamicRoutes.length
|
|
94
|
+
if (dynLen === 0)
|
|
95
|
+
return undefined
|
|
96
|
+
|
|
97
|
+
if (!this.#sorted) {
|
|
98
|
+
this.#dynamicRoutes.sort((a, b) => b.score - a.score || b.segments.length - a.segments.length)
|
|
99
|
+
this.#sorted = true
|
|
100
|
+
}
|
|
101
|
+
|
|
65
102
|
const parts = norm === '/' ? [] : norm.slice(1).split('/')
|
|
66
103
|
|
|
67
|
-
for (let i = 0; i <
|
|
104
|
+
for (let i = 0; i < dynLen; i++) {
|
|
68
105
|
const route = this.#dynamicRoutes[i]!
|
|
69
106
|
const segs = route.segments
|
|
70
107
|
|
|
@@ -73,32 +110,38 @@ export class Router<T> {
|
|
|
73
110
|
if (route.hasCatchAll && parts.length < segs.length - 1)
|
|
74
111
|
continue
|
|
75
112
|
|
|
76
|
-
const params: Record<string, string> = {}
|
|
77
113
|
let matched = true
|
|
78
|
-
|
|
79
114
|
for (let j = 0; j < segs.length; j++) {
|
|
80
115
|
const seg = segs[j]!
|
|
81
|
-
if (seg.
|
|
82
|
-
const name = seg.slice(1) || 'rest'
|
|
83
|
-
params[name] = parts.slice(j).map(decodeSegment).join('/')
|
|
116
|
+
if (seg.kind === SegmentKind.CatchAll)
|
|
84
117
|
break
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
const rawSeg = parts[j]!
|
|
88
|
-
if (/%2f/i.test(rawSeg)) {
|
|
118
|
+
if (seg.kind === SegmentKind.Param) {
|
|
119
|
+
if (ENCODED_SLASH_RE.test(parts[j]!)) {
|
|
89
120
|
matched = false
|
|
90
121
|
break
|
|
91
122
|
}
|
|
92
|
-
params[seg.slice(1)] = decodeSegment(rawSeg)
|
|
93
123
|
}
|
|
94
|
-
else if (seg !== parts[j]) {
|
|
124
|
+
else if (seg.value !== parts[j]) {
|
|
95
125
|
matched = false
|
|
96
126
|
break
|
|
97
127
|
}
|
|
98
128
|
}
|
|
99
129
|
|
|
100
|
-
if (matched)
|
|
101
|
-
|
|
130
|
+
if (!matched)
|
|
131
|
+
continue
|
|
132
|
+
|
|
133
|
+
// Allocate and decode params only for the winning route.
|
|
134
|
+
const params: Record<string, string> = {}
|
|
135
|
+
for (let j = 0; j < segs.length; j++) {
|
|
136
|
+
const seg = segs[j]!
|
|
137
|
+
if (seg.kind === SegmentKind.CatchAll) {
|
|
138
|
+
params[seg.value] = parts.slice(j).map(decodeSegment).join('/')
|
|
139
|
+
break
|
|
140
|
+
}
|
|
141
|
+
if (seg.kind === SegmentKind.Param)
|
|
142
|
+
params[seg.value] = decodeSegment(parts[j]!)
|
|
143
|
+
}
|
|
144
|
+
return { data: route.data, params }
|
|
102
145
|
}
|
|
103
146
|
|
|
104
147
|
return undefined
|
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)!
|
|
@@ -66,59 +70,60 @@ export function withCspHashes(
|
|
|
66
70
|
|
|
67
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'"
|
|
68
72
|
export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
|
|
73
|
+
export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
|
|
69
74
|
|
|
70
75
|
export interface SecurityHeadersOptions {
|
|
71
76
|
frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
|
|
72
77
|
referrerPolicy?: string | false | undefined
|
|
73
78
|
contentTypeOptions?: boolean | undefined
|
|
79
|
+
permissionsPolicy?: string | false | undefined
|
|
74
80
|
csp?: string | false | undefined
|
|
75
81
|
hsts?: string | boolean | undefined
|
|
76
82
|
}
|
|
77
83
|
|
|
78
84
|
const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
|
79
85
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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
|
-
}
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
return { expectedOrigin, forwardedOrigin }
|
|
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))
|
|
96
91
|
}
|
|
97
92
|
|
|
98
|
-
|
|
99
|
-
|
|
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
|
|
100
107
|
try {
|
|
101
|
-
|
|
102
|
-
return true
|
|
108
|
+
return new URL(`${proto}://${host}`).origin
|
|
103
109
|
}
|
|
104
|
-
catch {
|
|
105
|
-
|
|
106
|
-
const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase()
|
|
107
|
-
if (fwdProto === 'https')
|
|
108
|
-
return true
|
|
110
|
+
catch {
|
|
111
|
+
return undefined
|
|
109
112
|
}
|
|
110
|
-
return false
|
|
111
113
|
}
|
|
112
114
|
|
|
113
|
-
/**
|
|
114
|
-
export function
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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
|
|
122
127
|
const realIp = request.headers.get('x-real-ip')?.trim()
|
|
123
128
|
if (realIp)
|
|
124
129
|
return realIp
|
|
@@ -131,11 +136,11 @@ export function isTrustedOrigin(
|
|
|
131
136
|
origin: string,
|
|
132
137
|
request: Request,
|
|
133
138
|
trustedOrigins?: ReadonlySet<string>,
|
|
134
|
-
trustProxy = false,
|
|
139
|
+
trustProxy: TrustProxy = false,
|
|
140
|
+
requestUrl?: URL,
|
|
135
141
|
): boolean {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|| (forwardedOrigin !== undefined && origin === forwardedOrigin)
|
|
142
|
+
return origin === (requestUrl?.origin ?? new URL(request.url).origin)
|
|
143
|
+
|| origin === forwardedOrigin(request, trustProxy)
|
|
139
144
|
|| trustedOrigins?.has(origin) === true
|
|
140
145
|
}
|
|
141
146
|
|
|
@@ -143,18 +148,17 @@ export function isTrustedOrigin(
|
|
|
143
148
|
export function verifyOrigin(
|
|
144
149
|
request: Request,
|
|
145
150
|
trustedOrigins?: ReadonlySet<string>,
|
|
146
|
-
trustProxy = false,
|
|
151
|
+
trustProxy: TrustProxy = false,
|
|
152
|
+
requestUrl?: URL,
|
|
147
153
|
): { ok: true } | { ok: false, reason: string } {
|
|
148
154
|
if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
|
|
149
155
|
return { ok: true }
|
|
150
156
|
|
|
151
|
-
const { expectedOrigin, forwardedOrigin } = requestOrigins(request, trustProxy)
|
|
152
157
|
const origin = request.headers.get('origin')
|
|
153
|
-
|
|
154
158
|
if (origin !== null) {
|
|
155
|
-
if (
|
|
159
|
+
if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy, requestUrl))
|
|
156
160
|
return { ok: true }
|
|
157
|
-
return { ok: false, reason: `Cross-site request blocked: origin ${origin}
|
|
161
|
+
return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}` }
|
|
158
162
|
}
|
|
159
163
|
|
|
160
164
|
const fetchSite = request.headers.get('sec-fetch-site')
|
|
@@ -191,21 +195,9 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
|
|
|
191
195
|
entries.push(['x-frame-options', opts.frameOptions ?? 'SAMEORIGIN'])
|
|
192
196
|
if (opts.referrerPolicy !== false)
|
|
193
197
|
entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
|
|
198
|
+
if (opts.permissionsPolicy !== false)
|
|
199
|
+
entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
|
|
194
200
|
if (opts.csp !== false)
|
|
195
201
|
entries.push(['content-security-policy', opts.csp ?? DEFAULT_CSP])
|
|
196
202
|
return entries
|
|
197
203
|
}
|
|
198
|
-
|
|
199
|
-
export function applySecurityHeaders(headers: Headers, options: SecurityHeadersOptions = {}): void {
|
|
200
|
-
if ((options.contentTypeOptions ?? true) && !headers.has('x-content-type-options'))
|
|
201
|
-
headers.set('x-content-type-options', 'nosniff')
|
|
202
|
-
|
|
203
|
-
if (options.frameOptions !== false && !headers.has('x-frame-options'))
|
|
204
|
-
headers.set('x-frame-options', options.frameOptions ?? 'SAMEORIGIN')
|
|
205
|
-
|
|
206
|
-
if (options.referrerPolicy !== false && !headers.has('referrer-policy'))
|
|
207
|
-
headers.set('referrer-policy', options.referrerPolicy ?? 'strict-origin-when-cross-origin')
|
|
208
|
-
|
|
209
|
-
if (options.csp !== false && !headers.has('content-security-policy'))
|
|
210
|
-
headers.set('content-security-policy', options.csp ?? DEFAULT_CSP)
|
|
211
|
-
}
|
|
@@ -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
|
}
|