@kayjs/kay 2.0.0-alpha.0 → 2.0.0-alpha.5
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/build/index.ts +68 -3
- package/src/cli/new.ts +5 -4
- package/src/compiler/dom.ts +7 -6
- package/src/compiler/ssr.ts +36 -4
- package/src/server/action.ts +9 -3
- package/src/server/index.ts +6 -3
- package/src/server/security.ts +29 -5
- package/src/ssr/index.ts +21 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kayjs/kay",
|
|
3
|
-
"version": "2.0.0-alpha.
|
|
3
|
+
"version": "2.0.0-alpha.5",
|
|
4
4
|
"description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://kayjs.kaynooo.fr",
|
package/src/build/index.ts
CHANGED
|
@@ -7,7 +7,8 @@ import type { BunPlugin } from 'bun'
|
|
|
7
7
|
import type { IslandBinding, ModuleAnalysis } from '../compiler/index'
|
|
8
8
|
import type { BuildPluginContext, KayPlugin } from '../plugins/index'
|
|
9
9
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
10
|
-
import { basename, dirname, extname, join, relative, resolve } from 'node:path'
|
|
10
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
11
|
+
import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
|
|
11
12
|
import { analyzeModule, compileDom, compileSsr } from '../compiler/index'
|
|
12
13
|
import { loadConfig } from '../plugins/index'
|
|
13
14
|
import { actionHash } from '../server/action'
|
|
@@ -85,10 +86,22 @@ export function resolveKaySpecifier(specifier: string): string | undefined {
|
|
|
85
86
|
return join(KAY_SRC_ROOT, 'ssr/index.ts')
|
|
86
87
|
if (specifier === 'kay/server' || specifier === '@kayjs/kay/server')
|
|
87
88
|
return join(KAY_SRC_ROOT, 'server/index.ts')
|
|
89
|
+
if (specifier === 'kay/compiler' || specifier === '@kayjs/kay/compiler')
|
|
90
|
+
return join(KAY_SRC_ROOT, 'compiler/index.ts')
|
|
91
|
+
if (specifier === 'kay/build' || specifier === '@kayjs/kay/build')
|
|
92
|
+
return join(KAY_SRC_ROOT, 'build/index.ts')
|
|
93
|
+
if (specifier === 'kay/dev' || specifier === '@kayjs/kay/dev')
|
|
94
|
+
return join(KAY_SRC_ROOT, 'dev/index.ts')
|
|
88
95
|
if (specifier === 'kay/test' || specifier === '@kayjs/kay/test')
|
|
89
96
|
return join(KAY_SRC_ROOT, 'test/index.ts')
|
|
90
|
-
if (
|
|
97
|
+
if (
|
|
98
|
+
specifier === 'kay/jsx-runtime'
|
|
99
|
+
|| specifier === 'kay/jsx-dev-runtime'
|
|
100
|
+
|| specifier === '@kayjs/kay/jsx-runtime'
|
|
101
|
+
|| specifier === '@kayjs/kay/jsx-dev-runtime'
|
|
102
|
+
) {
|
|
91
103
|
return join(KAY_SRC_ROOT, 'jsx-runtime.ts')
|
|
104
|
+
}
|
|
92
105
|
return undefined
|
|
93
106
|
}
|
|
94
107
|
|
|
@@ -508,13 +521,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
508
521
|
const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles]
|
|
509
522
|
const serverRoot = standaloneActionFiles.length > 0 ? root : routesDir
|
|
510
523
|
|
|
524
|
+
const relOut = relative(root, outDir)
|
|
525
|
+
const outDirOutsideRoot = relOut !== '' && (relOut.startsWith('..') || isAbsolute(relOut))
|
|
526
|
+
const EXTERNAL_KAY_SUBPATHS = new Set([
|
|
527
|
+
'kay/build',
|
|
528
|
+
'@kayjs/kay/build',
|
|
529
|
+
'kay/compiler',
|
|
530
|
+
'@kayjs/kay/compiler',
|
|
531
|
+
'kay/dev',
|
|
532
|
+
'@kayjs/kay/dev',
|
|
533
|
+
'kay/test',
|
|
534
|
+
'@kayjs/kay/test',
|
|
535
|
+
])
|
|
536
|
+
|
|
511
537
|
const runServerBuild = async (): Promise<void> => {
|
|
512
538
|
const serverPlugin: BunPlugin = {
|
|
513
539
|
name: 'kay-v2-server',
|
|
514
540
|
setup(b) {
|
|
515
541
|
b.onResolve({ filter: /^(?:@kayjs\/)?kay(?:\/.*)?$/ }, (args) => {
|
|
516
542
|
const resolved = resolveKaySpecifier(args.path)
|
|
517
|
-
|
|
543
|
+
if (resolved === undefined)
|
|
544
|
+
return undefined
|
|
545
|
+
return EXTERNAL_KAY_SUBPATHS.has(args.path) ? { path: resolved, external: true } : { path: resolved }
|
|
518
546
|
})
|
|
519
547
|
b.onResolve({ filter: /^@kayjs\// }, (args) => {
|
|
520
548
|
try {
|
|
@@ -524,6 +552,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
524
552
|
return undefined
|
|
525
553
|
}
|
|
526
554
|
})
|
|
555
|
+
if (outDirOutsideRoot) {
|
|
556
|
+
b.onResolve({ filter: /^[^./]/ }, (args) => {
|
|
557
|
+
if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || isAbsolute(args.path))
|
|
558
|
+
return undefined
|
|
559
|
+
let resolved: string | undefined
|
|
560
|
+
try {
|
|
561
|
+
resolved = Bun.resolveSync(args.path, args.resolveDir || root)
|
|
562
|
+
}
|
|
563
|
+
catch {
|
|
564
|
+
try {
|
|
565
|
+
resolved = Bun.resolveSync(args.path, root)
|
|
566
|
+
}
|
|
567
|
+
catch {
|
|
568
|
+
return undefined
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
const isInsideNodeModules = resolved.includes('/node_modules/') || resolved.includes('\\node_modules\\')
|
|
572
|
+
const relToRoot = relative(root, resolved)
|
|
573
|
+
const isLocalSource = !isInsideNodeModules && !relToRoot.startsWith('..') && !isAbsolute(relToRoot)
|
|
574
|
+
return isLocalSource ? undefined : { path: resolved, external: true }
|
|
575
|
+
})
|
|
576
|
+
}
|
|
527
577
|
b.onLoad({ filter: /\.tsx$/ }, (args) => {
|
|
528
578
|
const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
|
|
529
579
|
const analysis = analyses.get(args.path)
|
|
@@ -850,6 +900,21 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
850
900
|
mkdirSync(dirname(dst), { recursive: true })
|
|
851
901
|
writeFileSync(dst, readFileSync(join(outDir, 'public', rel)))
|
|
852
902
|
}
|
|
903
|
+
// Emit precompressed .br and .gz sidecars for compressible static files (>= 128 B)
|
|
904
|
+
const COMPRESSIBLE = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest'])
|
|
905
|
+
for (const abs of walkAllFiles(prerenderDir)) {
|
|
906
|
+
if (!COMPRESSIBLE.has(extname(abs).toLowerCase()))
|
|
907
|
+
continue
|
|
908
|
+
const raw = readFileSync(abs)
|
|
909
|
+
if (raw.byteLength < 128)
|
|
910
|
+
continue
|
|
911
|
+
const br = brotliCompressSync(raw, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 6 } })
|
|
912
|
+
if (br.byteLength < raw.byteLength)
|
|
913
|
+
writeFileSync(`${abs}.br`, br)
|
|
914
|
+
const gz = Bun.gzipSync(raw, { level: 9 })
|
|
915
|
+
if (gz.byteLength < raw.byteLength)
|
|
916
|
+
writeFileSync(`${abs}.gz`, gz)
|
|
917
|
+
}
|
|
853
918
|
}
|
|
854
919
|
|
|
855
920
|
writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
|
package/src/cli/new.ts
CHANGED
|
@@ -15,7 +15,7 @@ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}
|
|
|
15
15
|
const root = resolve(targetDir)
|
|
16
16
|
const name = basename(root).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'kay-app'
|
|
17
17
|
const template: ScaffoldTemplate = options.template ?? 'minimal'
|
|
18
|
-
const kayVersion = options.kayVersion ?? '^2.0.0-alpha.
|
|
18
|
+
const kayVersion = options.kayVersion ?? '^2.0.0-alpha.5'
|
|
19
19
|
|
|
20
20
|
if (existsSync(root) && readdirSync(root).length > 0 && !options.force)
|
|
21
21
|
throw new Error(`kay new: directory "${root}" is not empty (pass --force to overwrite)`)
|
|
@@ -150,11 +150,12 @@ export function GET(ctx: RequestContext) {
|
|
|
150
150
|
return ctx.json({ ok: true, runtime: 'bun' })
|
|
151
151
|
}
|
|
152
152
|
`
|
|
153
|
-
files['src/actions/greet.ts'] = `import {
|
|
153
|
+
files['src/actions/greet.ts'] = `import type { StandardSchemaV1 } from 'kay/server'
|
|
154
|
+
import { action } from 'kay/server'
|
|
154
155
|
|
|
155
|
-
const nameSchema = {
|
|
156
|
+
const nameSchema: StandardSchemaV1<{ name: string }> = {
|
|
156
157
|
'~standard': {
|
|
157
|
-
version: 1
|
|
158
|
+
version: 1,
|
|
158
159
|
vendor: 'kay',
|
|
159
160
|
validate(raw: unknown) {
|
|
160
161
|
const name = String((raw as { name?: unknown })?.name ?? '').trim()
|
package/src/compiler/dom.ts
CHANGED
|
@@ -254,6 +254,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
254
254
|
hasNestedJsx = true
|
|
255
255
|
return false
|
|
256
256
|
}
|
|
257
|
+
return undefined
|
|
257
258
|
})
|
|
258
259
|
if (!hasNestedJsx)
|
|
259
260
|
return rewriteFreeIdentifiers(code, node, scopeRewrites)
|
|
@@ -268,6 +269,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
268
269
|
sub.replace(child.start - offset, child.end - offset, compileRootJsx(child, scopeRewrites))
|
|
269
270
|
return false
|
|
270
271
|
}
|
|
272
|
+
return undefined
|
|
271
273
|
})
|
|
272
274
|
|
|
273
275
|
// Also rewrite non-JSX free identifiers by applying identifier rewrites on non-JSX spans
|
|
@@ -374,12 +376,6 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
374
376
|
}
|
|
375
377
|
|
|
376
378
|
function compileElementTree(rootEl: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
|
|
377
|
-
interface NodeRef {
|
|
378
|
-
varName: string
|
|
379
|
-
parentVar: string
|
|
380
|
-
childIndex: number
|
|
381
|
-
}
|
|
382
|
-
|
|
383
379
|
const ops: string[] = []
|
|
384
380
|
const rootVar = freshVar('_e')
|
|
385
381
|
const childRefs = new Map<string, string>() // "parentVar:index" -> varName
|
|
@@ -843,6 +839,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
843
839
|
fnHasJsx = true
|
|
844
840
|
return false
|
|
845
841
|
}
|
|
842
|
+
return undefined
|
|
846
843
|
})
|
|
847
844
|
if (!fnHasJsx)
|
|
848
845
|
return
|
|
@@ -888,6 +885,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
888
885
|
stmtHasJsx = true
|
|
889
886
|
return false
|
|
890
887
|
}
|
|
888
|
+
return undefined
|
|
891
889
|
})
|
|
892
890
|
if (!stmtHasJsx) {
|
|
893
891
|
const active = new Map<string, string>()
|
|
@@ -904,6 +902,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
904
902
|
editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
|
|
905
903
|
return false
|
|
906
904
|
}
|
|
905
|
+
return undefined
|
|
907
906
|
})
|
|
908
907
|
}
|
|
909
908
|
if (stmt.type === 'VariableDeclaration') {
|
|
@@ -918,6 +917,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
918
917
|
editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
|
|
919
918
|
return false
|
|
920
919
|
}
|
|
920
|
+
return undefined
|
|
921
921
|
})
|
|
922
922
|
}
|
|
923
923
|
}
|
|
@@ -931,6 +931,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
931
931
|
editor.replace(node.start, node.end, compileRootJsx(node, new Map()))
|
|
932
932
|
return false
|
|
933
933
|
}
|
|
934
|
+
return undefined
|
|
934
935
|
})
|
|
935
936
|
|
|
936
937
|
// Emit imports, hoisted templates, and delegated events
|
package/src/compiler/ssr.ts
CHANGED
|
@@ -9,6 +9,14 @@ export function escapeStaticText(str: string): string {
|
|
|
9
9
|
return str.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
const RAW_TEXT_ELEMENTS = new Set(['style', 'script'])
|
|
13
|
+
const CLOSE_STYLE_RE = /<\/(style)/gi
|
|
14
|
+
const CLOSE_SCRIPT_RE = /<\/(script)/gi
|
|
15
|
+
|
|
16
|
+
function escapeRawText(str: string, tag: 'style' | 'script'): string {
|
|
17
|
+
return str.replace(tag === 'script' ? CLOSE_SCRIPT_RE : CLOSE_STYLE_RE, '<\\/$1')
|
|
18
|
+
}
|
|
19
|
+
|
|
12
20
|
const VOID_ELEMENTS = new Set([
|
|
13
21
|
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
|
|
14
22
|
'link', 'meta', 'param', 'source', 'track', 'wbr',
|
|
@@ -171,6 +179,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
171
179
|
hasNestedJsx = true
|
|
172
180
|
return false
|
|
173
181
|
}
|
|
182
|
+
return undefined
|
|
174
183
|
})
|
|
175
184
|
if (!hasNestedJsx)
|
|
176
185
|
return code.slice(node.start, node.end)
|
|
@@ -182,6 +191,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
182
191
|
sub.replace(child.start - offset, child.end - offset, compileRootJsx(child))
|
|
183
192
|
return false
|
|
184
193
|
}
|
|
194
|
+
return undefined
|
|
185
195
|
})
|
|
186
196
|
return sub.toString()
|
|
187
197
|
}
|
|
@@ -253,7 +263,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
253
263
|
if (innerHtmlExpr !== undefined)
|
|
254
264
|
parts.pushExpr(innerHtmlExpr)
|
|
255
265
|
else
|
|
256
|
-
emitChildrenIntoBuffer(node.children as AstNode[], bufVar, parts, flushParts, pushStmt)
|
|
266
|
+
emitChildrenIntoBuffer(node.children as AstNode[], bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
|
|
257
267
|
parts.pushStatic(`</${tag}>`)
|
|
258
268
|
}
|
|
259
269
|
|
|
@@ -263,6 +273,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
263
273
|
parts: StringParts,
|
|
264
274
|
flushParts: () => void,
|
|
265
275
|
pushStmt: (stmt: string) => void,
|
|
276
|
+
rawTextTag?: 'style' | 'script',
|
|
266
277
|
): void {
|
|
267
278
|
const meaningful = children.filter((c) => {
|
|
268
279
|
if (c.type === 'JSXText')
|
|
@@ -277,7 +288,8 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
277
288
|
const child = meaningful[i]!
|
|
278
289
|
const isLast = i === meaningful.length - 1
|
|
279
290
|
if (child.type === 'JSXText') {
|
|
280
|
-
|
|
291
|
+
const text = cleanJsxText(child.value as string)
|
|
292
|
+
parts.pushStatic(rawTextTag !== undefined ? escapeRawText(text, rawTextTag) : text)
|
|
281
293
|
}
|
|
282
294
|
else if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
|
|
283
295
|
emitIntoBuffer(child, bufVar, parts, flushParts, pushStmt)
|
|
@@ -285,9 +297,28 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
285
297
|
else if (child.type === 'JSXExpressionContainer') {
|
|
286
298
|
const expr = child.expression as AstNode
|
|
287
299
|
|
|
288
|
-
// Fold static string literal expressions like `{' '}` directly into static text
|
|
300
|
+
// Fold static string literal expressions like `{' '}` or `<style>{':root { ... }'}</style>` directly into static text
|
|
289
301
|
if (expr.type === 'Literal' && typeof expr.value === 'string') {
|
|
290
|
-
parts.pushStatic(escapeStaticText(expr.value))
|
|
302
|
+
parts.pushStatic(rawTextTag !== undefined ? escapeRawText(expr.value, rawTextTag) : escapeStaticText(expr.value))
|
|
303
|
+
continue
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Fold static no-substitution template literals inside `<style>`/`<script>` directly into raw text
|
|
307
|
+
if (
|
|
308
|
+
rawTextTag !== undefined
|
|
309
|
+
&& expr.type === 'TemplateLiteral'
|
|
310
|
+
&& (expr.expressions as AstNode[]).length === 0
|
|
311
|
+
&& (expr.quasis as AstNode[]).length === 1
|
|
312
|
+
) {
|
|
313
|
+
const cooked = expr.quasis[0]?.value?.cooked
|
|
314
|
+
if (typeof cooked === 'string') {
|
|
315
|
+
parts.pushStatic(escapeRawText(cooked, rawTextTag))
|
|
316
|
+
continue
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
if (rawTextTag !== undefined) {
|
|
321
|
+
parts.pushExpr(`${use('ssrRawText')}(${JSON.stringify(rawTextTag)}, ${compileSubExpression(expr)})`)
|
|
291
322
|
continue
|
|
292
323
|
}
|
|
293
324
|
|
|
@@ -549,6 +580,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
549
580
|
editor.replace(node.start, node.end, compileRootJsx(node))
|
|
550
581
|
return false
|
|
551
582
|
}
|
|
583
|
+
return undefined
|
|
552
584
|
})
|
|
553
585
|
|
|
554
586
|
if (used.size > 0) {
|
package/src/server/action.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import type { Cookies } from './cookies'
|
|
4
4
|
import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
|
|
5
|
-
import { verifyOrigin } from './security'
|
|
5
|
+
import { isTrustedOrigin, verifyOrigin } from './security'
|
|
6
6
|
import { validateSchema } from './standard-schema'
|
|
7
7
|
|
|
8
8
|
export interface ActionContext {
|
|
@@ -141,8 +141,14 @@ export async function executeAction(
|
|
|
141
141
|
if (!wantsJson) {
|
|
142
142
|
const referer = request.headers.get('referer')
|
|
143
143
|
if (referer) {
|
|
144
|
-
|
|
145
|
-
|
|
144
|
+
let refUrl: URL | undefined
|
|
145
|
+
try {
|
|
146
|
+
refUrl = new URL(referer)
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
refUrl = undefined
|
|
150
|
+
}
|
|
151
|
+
if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins))
|
|
146
152
|
return Response.redirect(refUrl.href, 303)
|
|
147
153
|
}
|
|
148
154
|
}
|
package/src/server/index.ts
CHANGED
|
@@ -559,9 +559,12 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
559
559
|
'etag': pub.etag,
|
|
560
560
|
'cache-control': pubCache,
|
|
561
561
|
}
|
|
562
|
-
routes[path] =
|
|
563
|
-
|
|
564
|
-
|
|
562
|
+
routes[path] = (req: Request) => {
|
|
563
|
+
if (req.headers.get('if-none-match') === pub.etag)
|
|
564
|
+
return new Response(null, { status: 304, headers: { 'etag': pub.etag, 'cache-control': pubCache } })
|
|
565
|
+
const body = typeof pub.body === 'string' ? Bun.file(pub.body) : pub.body
|
|
566
|
+
return new Response(req.method === 'HEAD' ? null : body, { status: 200, headers })
|
|
567
|
+
}
|
|
565
568
|
}
|
|
566
569
|
}
|
|
567
570
|
|
package/src/server/security.ts
CHANGED
|
@@ -9,16 +9,40 @@ export interface SecurityHeadersOptions {
|
|
|
9
9
|
|
|
10
10
|
const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
|
11
11
|
|
|
12
|
+
function requestOrigins(request: Request): { expectedOrigin: string, forwardedOrigin: string | undefined } {
|
|
13
|
+
const expectedOrigin = new URL(request.url).origin
|
|
14
|
+
const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim()
|
|
15
|
+
const fwdHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() || request.headers.get('host')?.trim()
|
|
16
|
+
let forwardedOrigin: string | undefined
|
|
17
|
+
if (fwdProto && fwdHost) {
|
|
18
|
+
try {
|
|
19
|
+
forwardedOrigin = new URL(`${fwdProto}://${fwdHost}`).origin
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
forwardedOrigin = `${fwdProto}://${fwdHost}`
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return { expectedOrigin, forwardedOrigin }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Returns true when `origin` matches the request's direct/forwarded origin or `trustedOrigins`. */
|
|
29
|
+
export function isTrustedOrigin(
|
|
30
|
+
origin: string,
|
|
31
|
+
request: Request,
|
|
32
|
+
trustedOrigins?: ReadonlySet<string>,
|
|
33
|
+
): boolean {
|
|
34
|
+
const { expectedOrigin, forwardedOrigin } = requestOrigins(request)
|
|
35
|
+
return origin === expectedOrigin
|
|
36
|
+
|| (forwardedOrigin !== undefined && origin === forwardedOrigin)
|
|
37
|
+
|| trustedOrigins?.has(origin) === true
|
|
38
|
+
}
|
|
39
|
+
|
|
12
40
|
/** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
|
|
13
41
|
export function verifyOrigin(request: Request, trustedOrigins?: ReadonlySet<string>): { ok: true } | { ok: false, reason: string } {
|
|
14
42
|
if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
|
|
15
43
|
return { ok: true }
|
|
16
44
|
|
|
17
|
-
const
|
|
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
|
|
45
|
+
const { expectedOrigin, forwardedOrigin } = requestOrigins(request)
|
|
22
46
|
const origin = request.headers.get('origin')
|
|
23
47
|
|
|
24
48
|
if (origin !== null) {
|
package/src/ssr/index.ts
CHANGED
|
@@ -42,6 +42,27 @@ export function ssrRaw(value: unknown): string {
|
|
|
42
42
|
return String(value)
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
const CLOSE_STYLE_RE = /<\/(style)/gi
|
|
46
|
+
const CLOSE_SCRIPT_RE = /<\/(script)/gi
|
|
47
|
+
|
|
48
|
+
/** Emits raw text inside `<style>` or `<script>` without HTML entity escaping, neutralizing only its closing tag. */
|
|
49
|
+
export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
|
|
50
|
+
if (value == null || typeof value === 'boolean')
|
|
51
|
+
return ''
|
|
52
|
+
if (Array.isArray(value)) {
|
|
53
|
+
let out = ''
|
|
54
|
+
for (let i = 0; i < value.length; i++)
|
|
55
|
+
out += ssrRawText(tag, value[i])
|
|
56
|
+
return out
|
|
57
|
+
}
|
|
58
|
+
const str = typeof value === 'string'
|
|
59
|
+
? value
|
|
60
|
+
: typeof value === 'object' && '__html' in value
|
|
61
|
+
? String((value as Html).__html)
|
|
62
|
+
: String(value)
|
|
63
|
+
return str.replace(tag === 'script' ? CLOSE_SCRIPT_RE : CLOSE_STYLE_RE, '<\\/$1')
|
|
64
|
+
}
|
|
65
|
+
|
|
45
66
|
export function escAttr(value: unknown): string {
|
|
46
67
|
const str = String(value)
|
|
47
68
|
if (bunEscape !== undefined)
|