@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.3
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 +617 -0
- package/src/build/compile.ts +27 -51
- package/src/build/files.ts +174 -0
- package/src/build/graph.ts +223 -0
- package/src/build/index.ts +272 -1466
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +229 -0
- package/src/build/plugin-host.ts +186 -0
- package/src/build/prerender.ts +102 -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/server-entry.ts +38 -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 +339 -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/config.ts +49 -0
- package/src/plugins/context.ts +61 -0
- package/src/plugins/index.ts +10 -123
- package/src/plugins/load.ts +38 -0
- package/src/plugins/order.ts +107 -0
- package/src/plugins/services.ts +23 -0
- package/src/plugins/types.ts +197 -0
- 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-registry.ts +72 -0
- package/src/server/action.ts +157 -79
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +182 -0
- package/src/server/compress.ts +197 -104
- package/src/server/cookies.ts +46 -16
- package/src/server/document.ts +192 -0
- package/src/server/env.ts +18 -13
- package/src/server/errors.ts +123 -0
- package/src/server/http.ts +203 -77
- package/src/server/index.ts +420 -973
- package/src/server/loader.ts +113 -0
- package/src/server/page.ts +107 -0
- package/src/server/plugin-host.ts +167 -0
- package/src/server/router.ts +69 -26
- package/src/server/security.ts +90 -59
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +163 -0
- package/src/server/stream.ts +94 -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 +24 -18
- package/src/unrenderable.ts +35 -0
package/src/server/security.ts
CHANGED
|
@@ -12,6 +12,45 @@ export const KAY_ISLAND_STYLE_HASH = cspSha256(KAY_ISLAND_STYLE)
|
|
|
12
12
|
export const KAY_SUSPENSE_STYLE_HASH = cspSha256(KAY_SUSPENSE_STYLE)
|
|
13
13
|
export const KAY_STREAM_SCRIPT_HASH = cspSha256(KAY_STREAM_SCRIPT)
|
|
14
14
|
|
|
15
|
+
const STYLE_HASH_CACHE_SIZE = 256
|
|
16
|
+
const styleHashCache = new Map<string, string>()
|
|
17
|
+
|
|
18
|
+
// Hashes stay cached by content, so a layout's fixed block costs one SHA-256 per process; past the cap a new block is hashed each time.
|
|
19
|
+
function styleHash(content: string): string {
|
|
20
|
+
let hash = styleHashCache.get(content)
|
|
21
|
+
if (hash === undefined) {
|
|
22
|
+
hash = cspSha256(content)
|
|
23
|
+
if (styleHashCache.size < STYLE_HASH_CACHE_SIZE)
|
|
24
|
+
styleHashCache.set(content, hash)
|
|
25
|
+
}
|
|
26
|
+
return hash
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// A regex finds the next tag ~10x faster than `indexOf('<style')`, which stalls on every `<span` and `<strong` of a large page.
|
|
30
|
+
const STYLE_OPEN_RE = /<style[\s>/]/g
|
|
31
|
+
|
|
32
|
+
/** CSP hashes of the app's own `<style>` blocks in `html`, leaving out kay's island and Suspense styles (hashed apart). */
|
|
33
|
+
export function inlineStyleHashes(html: string): string[] {
|
|
34
|
+
const hashes: string[] = []
|
|
35
|
+
STYLE_OPEN_RE.lastIndex = 0
|
|
36
|
+
let open = STYLE_OPEN_RE.exec(html)
|
|
37
|
+
while (open !== null) {
|
|
38
|
+
const tagEnd = html.indexOf('>', open.index)
|
|
39
|
+
const close = tagEnd === -1 ? -1 : html.indexOf('</style', tagEnd)
|
|
40
|
+
if (close === -1)
|
|
41
|
+
break
|
|
42
|
+
const content = html.slice(tagEnd + 1, close)
|
|
43
|
+
if (content !== KAY_ISLAND_STYLE && content !== KAY_SUSPENSE_STYLE) {
|
|
44
|
+
const hash = styleHash(content)
|
|
45
|
+
if (!hashes.includes(hash))
|
|
46
|
+
hashes.push(hash)
|
|
47
|
+
}
|
|
48
|
+
STYLE_OPEN_RE.lastIndex = close
|
|
49
|
+
open = STYLE_OPEN_RE.exec(html)
|
|
50
|
+
}
|
|
51
|
+
return hashes
|
|
52
|
+
}
|
|
53
|
+
|
|
15
54
|
/** Augments a Content-Security-Policy header with exact SHA-256 hashes (no `'unsafe-inline'` required). */
|
|
16
55
|
export function withCspHashes(
|
|
17
56
|
csp: string,
|
|
@@ -56,7 +95,11 @@ export function withCspHashes(
|
|
|
56
95
|
}
|
|
57
96
|
|
|
58
97
|
addHashes('style-src', styleHashes)
|
|
98
|
+
if (directives.has('style-src-elem'))
|
|
99
|
+
addHashes('style-src-elem', styleHashes)
|
|
59
100
|
addHashes('script-src', scriptHashes)
|
|
101
|
+
if (directives.has('script-src-elem'))
|
|
102
|
+
addHashes('script-src-elem', scriptHashes)
|
|
60
103
|
|
|
61
104
|
return order.map((name) => {
|
|
62
105
|
const tokens = directives.get(name)!
|
|
@@ -64,61 +107,62 @@ export function withCspHashes(
|
|
|
64
107
|
}).join('; ')
|
|
65
108
|
}
|
|
66
109
|
|
|
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'"
|
|
110
|
+
export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'"
|
|
68
111
|
export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
|
|
112
|
+
export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
|
|
69
113
|
|
|
70
114
|
export interface SecurityHeadersOptions {
|
|
71
115
|
frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
|
|
72
116
|
referrerPolicy?: string | false | undefined
|
|
73
117
|
contentTypeOptions?: boolean | undefined
|
|
118
|
+
permissionsPolicy?: string | false | undefined
|
|
74
119
|
csp?: string | false | undefined
|
|
75
120
|
hsts?: string | boolean | undefined
|
|
76
121
|
}
|
|
77
122
|
|
|
78
123
|
const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
|
79
124
|
|
|
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 }
|
|
125
|
+
/** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
|
|
126
|
+
export type TrustProxy = boolean | number
|
|
127
|
+
|
|
128
|
+
function proxyHops(trustProxy: TrustProxy): number {
|
|
129
|
+
return trustProxy === true ? 1 : trustProxy === false ? 0 : Math.max(0, Math.floor(trustProxy))
|
|
96
130
|
}
|
|
97
131
|
|
|
98
|
-
|
|
99
|
-
|
|
132
|
+
// Proxies append to X-Forwarded-*, so only the entries the trusted hops wrote count: the one `hops` from the right.
|
|
133
|
+
function forwardedValue(request: Request, header: string, trustProxy: TrustProxy): string | undefined {
|
|
134
|
+
const hops = proxyHops(trustProxy)
|
|
135
|
+
if (hops === 0)
|
|
136
|
+
return undefined
|
|
137
|
+
const entries = (request.headers.get(header) ?? '').split(',').map(e => e.trim()).filter(e => e !== '')
|
|
138
|
+
return entries[Math.max(0, entries.length - hops)]
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function forwardedOrigin(request: Request, trustProxy: TrustProxy): string | undefined {
|
|
142
|
+
const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)
|
|
143
|
+
const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim()
|
|
144
|
+
if (!proto || !host)
|
|
145
|
+
return undefined
|
|
100
146
|
try {
|
|
101
|
-
|
|
102
|
-
return true
|
|
147
|
+
return new URL(`${proto}://${host}`).origin
|
|
103
148
|
}
|
|
104
|
-
catch {
|
|
105
|
-
|
|
106
|
-
const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase()
|
|
107
|
-
if (fwdProto === 'https')
|
|
108
|
-
return true
|
|
149
|
+
catch {
|
|
150
|
+
return undefined
|
|
109
151
|
}
|
|
110
|
-
return false
|
|
111
152
|
}
|
|
112
153
|
|
|
113
|
-
/**
|
|
114
|
-
export function
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
154
|
+
/** Returns true when the request arrived over HTTPS (directly, or via X-Forwarded-Proto when `trustProxy` is true). */
|
|
155
|
+
export function isHttpsRequest(request: Request, trustProxy: TrustProxy = false): boolean {
|
|
156
|
+
return request.url.startsWith('https:')
|
|
157
|
+
|| forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase() === 'https'
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Extracts the client IP from the trusted proxies' headers, or falls back to the direct socket IP. */
|
|
161
|
+
export function getClientIp(request: Request, trustProxy: TrustProxy = false, remoteIp?: string): string | undefined {
|
|
162
|
+
if (proxyHops(trustProxy) > 0) {
|
|
163
|
+
const forwarded = forwardedValue(request, 'x-forwarded-for', trustProxy)
|
|
164
|
+
if (forwarded)
|
|
165
|
+
return forwarded
|
|
122
166
|
const realIp = request.headers.get('x-real-ip')?.trim()
|
|
123
167
|
if (realIp)
|
|
124
168
|
return realIp
|
|
@@ -131,11 +175,11 @@ export function isTrustedOrigin(
|
|
|
131
175
|
origin: string,
|
|
132
176
|
request: Request,
|
|
133
177
|
trustedOrigins?: ReadonlySet<string>,
|
|
134
|
-
trustProxy = false,
|
|
178
|
+
trustProxy: TrustProxy = false,
|
|
179
|
+
requestUrl?: URL,
|
|
135
180
|
): boolean {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|| (forwardedOrigin !== undefined && origin === forwardedOrigin)
|
|
181
|
+
return origin === (requestUrl?.origin ?? new URL(request.url).origin)
|
|
182
|
+
|| origin === forwardedOrigin(request, trustProxy)
|
|
139
183
|
|| trustedOrigins?.has(origin) === true
|
|
140
184
|
}
|
|
141
185
|
|
|
@@ -143,18 +187,17 @@ export function isTrustedOrigin(
|
|
|
143
187
|
export function verifyOrigin(
|
|
144
188
|
request: Request,
|
|
145
189
|
trustedOrigins?: ReadonlySet<string>,
|
|
146
|
-
trustProxy = false,
|
|
190
|
+
trustProxy: TrustProxy = false,
|
|
191
|
+
requestUrl?: URL,
|
|
147
192
|
): { ok: true } | { ok: false, reason: string } {
|
|
148
193
|
if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
|
|
149
194
|
return { ok: true }
|
|
150
195
|
|
|
151
|
-
const { expectedOrigin, forwardedOrigin } = requestOrigins(request, trustProxy)
|
|
152
196
|
const origin = request.headers.get('origin')
|
|
153
|
-
|
|
154
197
|
if (origin !== null) {
|
|
155
|
-
if (
|
|
198
|
+
if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy, requestUrl))
|
|
156
199
|
return { ok: true }
|
|
157
|
-
return { ok: false, reason: `Cross-site request blocked: origin ${origin}
|
|
200
|
+
return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}` }
|
|
158
201
|
}
|
|
159
202
|
|
|
160
203
|
const fetchSite = request.headers.get('sec-fetch-site')
|
|
@@ -191,21 +234,9 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
|
|
|
191
234
|
entries.push(['x-frame-options', opts.frameOptions ?? 'SAMEORIGIN'])
|
|
192
235
|
if (opts.referrerPolicy !== false)
|
|
193
236
|
entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
|
|
237
|
+
if (opts.permissionsPolicy !== false)
|
|
238
|
+
entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
|
|
194
239
|
if (opts.csp !== false)
|
|
195
240
|
entries.push(['content-security-policy', opts.csp ?? DEFAULT_CSP])
|
|
196
241
|
return entries
|
|
197
242
|
}
|
|
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
|
}
|
|
@@ -0,0 +1,163 @@
|
|
|
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, inlineStyleHashes, 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
|
+
// An exported page's CSP gains the hashes of its own `<style>` blocks, read once per file version.
|
|
72
|
+
const pageCsp = new Map<string, { etag: string, csp: string }>()
|
|
73
|
+
async function setPageCsp(headers: Headers, filePath: string, etag: string): Promise<void> {
|
|
74
|
+
if (htmlCsp === undefined)
|
|
75
|
+
return
|
|
76
|
+
let cached = pageCsp.get(filePath)
|
|
77
|
+
if (cached?.etag !== etag) {
|
|
78
|
+
const styleHashes = inlineStyleHashes(await Bun.file(filePath).text())
|
|
79
|
+
cached = { etag, csp: withCspHashes(htmlCsp, { styleHashes }) }
|
|
80
|
+
pageCsp.set(filePath, cached)
|
|
81
|
+
}
|
|
82
|
+
headers.set('content-security-policy', cached.csp)
|
|
83
|
+
}
|
|
84
|
+
const fileEtag = (st: Stats): string => `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
|
|
85
|
+
|
|
86
|
+
const handle = async (req: Request): Promise<Response> => {
|
|
87
|
+
if (!isRead(req)) {
|
|
88
|
+
const headers = initHeaders()
|
|
89
|
+
headers.set('allow', 'GET, HEAD')
|
|
90
|
+
return withHsts(new Response('Method Not Allowed', { status: 405, headers }), req)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const url = new URL(req.url)
|
|
94
|
+
const found = resolveStaticFile(url.pathname)
|
|
95
|
+
if (found === undefined) {
|
|
96
|
+
const notFoundPath = join(absRoot, '404.html')
|
|
97
|
+
const notFoundStat = statFile(notFoundPath)
|
|
98
|
+
if (notFoundStat !== undefined) {
|
|
99
|
+
const headers = initHeaders(true)
|
|
100
|
+
headers.set('content-type', 'text/html; charset=utf-8')
|
|
101
|
+
await setPageCsp(headers, notFoundPath, fileEtag(notFoundStat))
|
|
102
|
+
return withHsts(new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers }), req)
|
|
103
|
+
}
|
|
104
|
+
return withHsts(new Response('Not Found', { status: 404, headers: initHeaders() }), req)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const { path: filePath, st } = found
|
|
108
|
+
const ext = extname(filePath).toLowerCase()
|
|
109
|
+
const mime = MIME[ext] ?? 'application/octet-stream'
|
|
110
|
+
const isHtml = ext === '.html' || ext === '.htm'
|
|
111
|
+
const etag = fileEtag(st)
|
|
112
|
+
const isImmutable = url.pathname.startsWith(cleanPrefix)
|
|
113
|
+
const headers = initHeaders(isHtml)
|
|
114
|
+
headers.set('content-type', mime)
|
|
115
|
+
headers.set('cache-control', isImmutable ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate')
|
|
116
|
+
headers.set('etag', etag)
|
|
117
|
+
if (isHtml)
|
|
118
|
+
await setPageCsp(headers, filePath, etag)
|
|
119
|
+
|
|
120
|
+
const hasBr = compressEnabled && existsSync(`${filePath}.br`)
|
|
121
|
+
const hasGz = compressEnabled && existsSync(`${filePath}.gz`)
|
|
122
|
+
if (hasBr || hasGz || (compressEnabled && isCompressibleType(mime)))
|
|
123
|
+
headers.set('vary', 'Accept-Encoding')
|
|
124
|
+
|
|
125
|
+
if (etagMatches(req.headers.get('if-none-match'), etag))
|
|
126
|
+
return withHsts(new Response(null, { status: 304, headers }), req)
|
|
127
|
+
|
|
128
|
+
if (compressEnabled && req.method !== 'HEAD' && (hasBr || hasGz)) {
|
|
129
|
+
const preEnc = pickPrecompressedEncoding(req.headers.get('accept-encoding'), { br: hasBr, gz: hasGz })
|
|
130
|
+
if (preEnc !== undefined) {
|
|
131
|
+
headers.set('content-encoding', preEnc)
|
|
132
|
+
headers.set('etag', toWeakEtag(etag))
|
|
133
|
+
return withHsts(new Response(Bun.file(`${filePath}.${preEnc === 'br' ? 'br' : 'gz'}`), { status: 200, headers }), req)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
headers.set('content-length', String(st.size))
|
|
138
|
+
const res = new Response(req.method === 'HEAD' ? null : Bun.file(filePath), { status: 200, headers })
|
|
139
|
+
if (!compressEnabled || req.method === 'HEAD')
|
|
140
|
+
return withHsts(res, req)
|
|
141
|
+
return withHsts(await maybeCompressResponse(res, req, compressCache), req)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
handle,
|
|
146
|
+
serve(port = 3000, hostname = '127.0.0.1') {
|
|
147
|
+
return Bun.serve({
|
|
148
|
+
port,
|
|
149
|
+
hostname,
|
|
150
|
+
idleTimeout: 30,
|
|
151
|
+
development: false,
|
|
152
|
+
fetch: handle,
|
|
153
|
+
error() {
|
|
154
|
+
return new Response('Internal Server Error', {
|
|
155
|
+
status: 500,
|
|
156
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', ...Object.fromEntries(securityEntries) },
|
|
157
|
+
})
|
|
158
|
+
},
|
|
159
|
+
})
|
|
160
|
+
},
|
|
161
|
+
async dispose() {},
|
|
162
|
+
}
|
|
163
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// A page with pending `<Suspense>` boundaries: its document flushes first, then each boundary as a script once it resolves or times out.
|
|
2
|
+
|
|
3
|
+
import type { PendingChunk, RenderContext, SettledChunk } from '../ssr/context'
|
|
4
|
+
import { streamChunkScript } from '../ssr/context'
|
|
5
|
+
|
|
6
|
+
const textEncoder = new TextEncoder()
|
|
7
|
+
// Where a streamed page's document splits: everything before it flushes first, resolved boundaries go in between.
|
|
8
|
+
export const STREAM_TAIL_MARK = '<!--kay:stream-tail-->'
|
|
9
|
+
|
|
10
|
+
async function settleWithin(chunk: PendingChunk, deadlineMs: number, signal: AbortSignal): Promise<SettledChunk | undefined> {
|
|
11
|
+
if (signal.aborted)
|
|
12
|
+
return undefined
|
|
13
|
+
const remaining = Math.max(0, deadlineMs - Date.now())
|
|
14
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
15
|
+
const abortedOrTimedOut = new Promise<SettledChunk | undefined>((resolve) => {
|
|
16
|
+
const onAbort = () => resolve(undefined)
|
|
17
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
18
|
+
timer = setTimeout(() => {
|
|
19
|
+
signal.removeEventListener('abort', onAbort)
|
|
20
|
+
const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${remaining} ms`)
|
|
21
|
+
resolve({ html: chunk.renderError(error), error })
|
|
22
|
+
}, remaining)
|
|
23
|
+
})
|
|
24
|
+
try {
|
|
25
|
+
return await Promise.race([chunk.settled, abortedOrTimedOut])
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
clearTimeout(timer)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Streams `shell` (a document holding `STREAM_TAIL_MARK`), with every boundary of `rctx` flushed before its tail. */
|
|
33
|
+
export function streamDocument(shell: string, rctx: RenderContext, streamTimeout: number, onBoundaryError: (error: unknown) => void): ReadableStream<Uint8Array> {
|
|
34
|
+
let splitAt = shell.lastIndexOf(STREAM_TAIL_MARK)
|
|
35
|
+
let tailOffset = STREAM_TAIL_MARK.length
|
|
36
|
+
if (splitAt === -1) {
|
|
37
|
+
splitAt = shell.lastIndexOf('</body>')
|
|
38
|
+
tailOffset = 0
|
|
39
|
+
}
|
|
40
|
+
const openingHtml = splitAt === -1 ? shell : shell.slice(0, splitAt)
|
|
41
|
+
const tailHtml = splitAt === -1 ? '' : shell.slice(splitAt + tailOffset)
|
|
42
|
+
|
|
43
|
+
const abortCtrl = new AbortController()
|
|
44
|
+
let closed = false
|
|
45
|
+
const deadline = Date.now() + streamTimeout
|
|
46
|
+
|
|
47
|
+
const safeEnqueue = (controller: ReadableStreamDefaultController<Uint8Array>, data: Uint8Array): void => {
|
|
48
|
+
if (closed || abortCtrl.signal.aborted)
|
|
49
|
+
return
|
|
50
|
+
try {
|
|
51
|
+
controller.enqueue(data)
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
closed = true
|
|
55
|
+
abortCtrl.abort()
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return new ReadableStream<Uint8Array>({
|
|
60
|
+
async start(controller) {
|
|
61
|
+
safeEnqueue(controller, textEncoder.encode(openingHtml))
|
|
62
|
+
// A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
|
|
63
|
+
let flushed = 0
|
|
64
|
+
const flushPending = async (): Promise<void> => {
|
|
65
|
+
if (closed || abortCtrl.signal.aborted)
|
|
66
|
+
return
|
|
67
|
+
const chunks = rctx.pending.slice(flushed)
|
|
68
|
+
flushed = rctx.pending.length
|
|
69
|
+
await Promise.all(chunks.map(async (chunk) => {
|
|
70
|
+
const settled = await settleWithin(chunk, deadline, abortCtrl.signal)
|
|
71
|
+
if (settled === undefined || closed || abortCtrl.signal.aborted)
|
|
72
|
+
return
|
|
73
|
+
if ('error' in settled)
|
|
74
|
+
onBoundaryError(settled.error)
|
|
75
|
+
safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, settled.html)))
|
|
76
|
+
await flushPending()
|
|
77
|
+
}))
|
|
78
|
+
}
|
|
79
|
+
await flushPending()
|
|
80
|
+
if (!closed && !abortCtrl.signal.aborted) {
|
|
81
|
+
safeEnqueue(controller, textEncoder.encode(tailHtml))
|
|
82
|
+
closed = true
|
|
83
|
+
try {
|
|
84
|
+
controller.close()
|
|
85
|
+
}
|
|
86
|
+
catch {}
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
cancel() {
|
|
90
|
+
closed = true
|
|
91
|
+
abortCtrl.abort()
|
|
92
|
+
},
|
|
93
|
+
})
|
|
94
|
+
}
|