prunelle 0.7.0 → 0.7.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/build/ecoindex.ts +10 -2
- package/src/build/index.ts +4 -0
- package/src/build/island-promote.ts +23 -2
- package/src/build/islands.ts +6 -3
- package/src/build/report.ts +8 -2
- package/src/cli/check.ts +4 -0
- package/src/compiler/analyze.ts +4 -3
- package/src/compiler/compliance-urls.ts +4 -3
- package/src/compiler/props-body.ts +16 -8
- package/src/dev/host-check.ts +7 -1
- package/src/dev/index.ts +6 -3
- package/src/dev/open-editor.ts +22 -2
- package/src/dom/index.ts +15 -4
- package/src/dom/loop.ts +44 -20
- package/src/plugins/context.ts +34 -6
- package/src/server/http.ts +15 -7
- package/src/server/index.ts +12 -5
- package/src/server/loader.ts +5 -1
- package/src/server/security.ts +4 -4
- package/src/server/static-dir.ts +4 -1
- package/src/style.ts +42 -10
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prunelle",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.1",
|
|
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://prunelle.kaynooo.fr",
|
package/src/build/ecoindex.ts
CHANGED
|
@@ -26,6 +26,8 @@ export interface RouteEcoIndex {
|
|
|
26
26
|
/** Third-party requests, counted in `requests` but not in `weightBytes`. */
|
|
27
27
|
external?: number | undefined
|
|
28
28
|
url?: string | undefined
|
|
29
|
+
/** Heaviest prerendered URL when a sibling page weighs more than the lowest-EcoIndex page. */
|
|
30
|
+
heaviest?: { bytes: number, url: string } | undefined
|
|
29
31
|
}
|
|
30
32
|
|
|
31
33
|
// The EcoIndex as computed by its reference implementation, cnumr/ecoindex_python at 8833bb3 (components/ecoindex/compute/ecoindex.py, data/quantiles.py, data/grades.py): 20-quantile tables of DOM elements, HTTP requests and transfer size in KB of 1000.
|
|
@@ -200,8 +202,9 @@ export function measureRouteEcoIndex(route: RouteManifestEntry, options: { prere
|
|
|
200
202
|
if (route.prerendered === undefined)
|
|
201
203
|
return undefined
|
|
202
204
|
const entries = Object.entries(route.prerendered).sort(([a], [b]) => a.localeCompare(b))
|
|
203
|
-
let worst: Omit<RouteEcoIndex, 'url'> | undefined
|
|
205
|
+
let worst: Omit<RouteEcoIndex, 'url' | 'heaviest'> | undefined
|
|
204
206
|
let worstUrl: string | undefined
|
|
207
|
+
let heaviest: { bytes: number, url: string } | undefined
|
|
205
208
|
let measured = 0
|
|
206
209
|
|
|
207
210
|
for (const [url, relFile] of entries) {
|
|
@@ -222,9 +225,14 @@ export function measureRouteEcoIndex(route: RouteManifestEntry, options: { prere
|
|
|
222
225
|
worst = eco
|
|
223
226
|
worstUrl = url
|
|
224
227
|
}
|
|
228
|
+
if (heaviest === undefined || load.total > heaviest.bytes)
|
|
229
|
+
heaviest = { bytes: load.total, url }
|
|
225
230
|
}
|
|
226
231
|
|
|
227
232
|
if (worst === undefined || worstUrl === undefined)
|
|
228
233
|
return undefined
|
|
229
|
-
|
|
234
|
+
const result: RouteEcoIndex = measured > 1 || worstUrl !== route.path ? { ...worst, url: worstUrl } : { ...worst }
|
|
235
|
+
if (heaviest !== undefined && heaviest.bytes > worst.weightBytes)
|
|
236
|
+
result.heaviest = heaviest
|
|
237
|
+
return result
|
|
230
238
|
}
|
package/src/build/index.ts
CHANGED
|
@@ -259,6 +259,10 @@ function emitBuildWarnings(run: BuildRun, graph: ModuleGraph, routeFiles: readon
|
|
|
259
259
|
/** Plans the islands, then runs the rules `prunelle check` also runs on the whole graph: what server code renders wrong, and dynamic prerendered routes with no `paths()`. Throws them all at once, each placed with a code frame. */
|
|
260
260
|
function planCheckedIslands(root: string, routesDir: string, graph: ModuleGraph, pageFiles: string[], specialFiles: string[], isStatic: boolean): ReturnType<typeof planIslands> {
|
|
261
261
|
const islands = planIslands(graph, root, pageFiles, specialFiles)
|
|
262
|
+
for (const { file, warning } of islands.promotedWarnings) {
|
|
263
|
+
const rel = relPosix(root, file)
|
|
264
|
+
console.warn(formatDiagnostic(formatLoc(rel, graph.source(file), warning.start), warning.message.replaceAll(file, rel), 'warning'))
|
|
265
|
+
}
|
|
262
266
|
const placed: string[] = []
|
|
263
267
|
const place = (file: string, offset: number, message: string): void => {
|
|
264
268
|
const source = graph.source(file)
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
// Which modules run in the browser: following re-exports to the binding they name, and promoting what reads an interactive import.
|
|
2
2
|
|
|
3
3
|
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
4
|
+
import type { CompilerWarning } from '../compiler/mistakes'
|
|
4
5
|
import type { IslandIssue } from './islands'
|
|
5
6
|
import type { ModuleGraph } from './graph'
|
|
7
|
+
import { wholeLoadShippedWarning } from '../compiler/analyze'
|
|
6
8
|
import { withStateReads } from '../compiler/interactivity'
|
|
7
9
|
import { isInNodeModules, isTsFile } from './files'
|
|
8
10
|
|
|
@@ -120,16 +122,26 @@ function interactivityChanged(prev: ModuleAnalysis, next: { isInteractive: boole
|
|
|
120
122
|
/** An imported island a module reads as a value (`const D = Counter`, `{ C: Counter }`, `c={Counter}`), which makes what holds it an island. */
|
|
121
123
|
export interface IslandValueUse { file: string, offset: number, name: string }
|
|
122
124
|
|
|
125
|
+
/** A compiler warning that only applies once a module is promoted to an island across files. */
|
|
126
|
+
export interface PromotedWarning { file: string, warning: CompilerWarning }
|
|
127
|
+
|
|
123
128
|
const COMPONENT_NAME_RE = /^[A-Z]/
|
|
124
129
|
|
|
125
130
|
// The first place `analysis` reads `local` as a value, its bindings being in source order.
|
|
126
131
|
const firstValueRead = (analysis: ModuleAnalysis, local: string): number | undefined => analysis.bindings.map(b => b.valueRefs.get(local)).find(offset => offset !== undefined)
|
|
127
132
|
|
|
128
|
-
export function createPromoter(
|
|
133
|
+
export function createPromoter(
|
|
134
|
+
graph: ModuleGraph,
|
|
135
|
+
load: LoadModule,
|
|
136
|
+
issues: IslandIssue[],
|
|
137
|
+
valueUses: IslandValueUse[] = [],
|
|
138
|
+
promotedWarnings: PromotedWarning[] = [],
|
|
139
|
+
): { promoteAll: () => void, loadPromoted: LoadModule } {
|
|
129
140
|
const initialAsyncInteractive = new Set<string>()
|
|
130
141
|
const initialServerOnly = new Set<string>()
|
|
131
142
|
const reportedAsync = new Set<string>()
|
|
132
143
|
const reportedServerOnly = new Set<string>()
|
|
144
|
+
const reportedWholeLoad = new Set<string>()
|
|
133
145
|
|
|
134
146
|
const recordInitial = (file: string, a: ModuleAnalysis): void => {
|
|
135
147
|
if (a.hasAsyncDefault && a.exports.get('default')?.interactive === true)
|
|
@@ -197,7 +209,16 @@ export function createPromoter(graph: ModuleGraph, load: LoadModule, issues: Isl
|
|
|
197
209
|
if (!interactivityChanged(analysis, promoted))
|
|
198
210
|
return false
|
|
199
211
|
recordValueUses(file, analysis)
|
|
200
|
-
|
|
212
|
+
let nextWarnings = analysis.warnings
|
|
213
|
+
if (analysis.exports.get('default')?.interactive !== true && page?.interactive === true && analysis.hasLoadExport && analysis.defaultDataKeys === undefined && !analysis.exportedNames.includes('clientData') && !reportedWholeLoad.has(file)) {
|
|
214
|
+
reportedWholeLoad.add(file)
|
|
215
|
+
const defaultName = analysis.exportLocals.get('default')
|
|
216
|
+
const start = analysis.bindings.find(b => b.name === defaultName)?.start ?? page.offset ?? 0
|
|
217
|
+
const warning = wholeLoadShippedWarning(file, start)
|
|
218
|
+
promotedWarnings.push({ file, warning })
|
|
219
|
+
nextWarnings = [...analysis.warnings, warning]
|
|
220
|
+
}
|
|
221
|
+
graph.analyses.set(file, { ...analysis, ...promoted, warnings: nextWarnings })
|
|
201
222
|
return true
|
|
202
223
|
}
|
|
203
224
|
|
package/src/build/islands.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
4
4
|
import type { ServerOnlyInIsland } from '../compiler/interactivity'
|
|
5
5
|
import type { ModuleGraph } from './graph'
|
|
6
|
-
import type { IslandValueUse, LoadModule } from './island-promote'
|
|
6
|
+
import type { IslandValueUse, LoadModule, PromotedWarning } from './island-promote'
|
|
7
7
|
import { basename, extname } from 'node:path'
|
|
8
8
|
import { asyncInteractiveError } from '../compiler/analyze'
|
|
9
9
|
import { findCrossFileServerOnly } from '../compiler/interactivity'
|
|
@@ -57,6 +57,8 @@ export interface IslandPlan {
|
|
|
57
57
|
issues: IslandIssue[]
|
|
58
58
|
/** Imported islands read as values, each making what holds it an island (`prunelle check` warns). */
|
|
59
59
|
valueUses: IslandValueUse[]
|
|
60
|
+
/** Compiler warnings triggered once a route is promoted to an island across files. */
|
|
61
|
+
promotedWarnings: PromotedWarning[]
|
|
60
62
|
}
|
|
61
63
|
|
|
62
64
|
export interface AnalyzeIslandsOptions {
|
|
@@ -359,7 +361,8 @@ export function analyzeIslands(options: AnalyzeIslandsOptions): IslandPlan {
|
|
|
359
361
|
|
|
360
362
|
// A component or hook reading reactive state or calling an interactive hook runs in the browser too. The promoted analysis lives in this run's map only, so the cached one still reflects the file alone.
|
|
361
363
|
const valueUses: IslandValueUse[] = []
|
|
362
|
-
const
|
|
364
|
+
const promotedWarnings: PromotedWarning[] = []
|
|
365
|
+
const { promoteAll, loadPromoted } = createPromoter(graph, load, issues, valueUses, promotedWarnings)
|
|
363
366
|
promoteAll()
|
|
364
367
|
checkImportedBareSignals(graph, load, root, issues)
|
|
365
368
|
checkCrossFileServerOnlyTags(graph, load, issues)
|
|
@@ -400,7 +403,7 @@ export function analyzeIslands(options: AnalyzeIslandsOptions): IslandPlan {
|
|
|
400
403
|
}
|
|
401
404
|
|
|
402
405
|
const { reach, clientFiles, cssFiles } = walkIslandReach(graph, load, [...rootFiles], clientKeep, options.checkLeaks === true, issues)
|
|
403
|
-
return { targets, pageBindings, staticTags, cssFiles, reach, clientFiles, clientKeep, issues, valueUses }
|
|
406
|
+
return { targets, pageBindings, staticTags, cssFiles, reach, clientFiles, clientKeep, issues, valueUses, promotedWarnings }
|
|
404
407
|
}
|
|
405
408
|
|
|
406
409
|
function clientKeepOf(targets: Iterable<IslandTarget>, load: LoadModule): Map<string, Set<string>> {
|
package/src/build/report.ts
CHANGED
|
@@ -272,13 +272,19 @@ export function checkJsBudget(report: BundleReport, maxBytes: number, source = '
|
|
|
272
272
|
}
|
|
273
273
|
|
|
274
274
|
/** What a route's first visit downloads: its stylesheets, scripts and fonts, or, on a prerendered page, the heaviest page with its HTML and images. */
|
|
275
|
-
export const routeFirstLoad = (r: RouteBundleMetrics): number => Math.max(r.firstLoad, r.ecoIndex?.weightBytes ?? 0)
|
|
275
|
+
export const routeFirstLoad = (r: RouteBundleMetrics): number => Math.max(r.firstLoad, r.ecoIndex?.weightBytes ?? 0, r.ecoIndex?.heaviest?.bytes ?? 0)
|
|
276
276
|
|
|
277
277
|
/** Throws naming each route whose first load, brotli, is over `budget.firstLoad`. */
|
|
278
278
|
export function checkFirstLoadBudget(report: BundleReport, maxBytes: number): void {
|
|
279
279
|
const over = report.routes.filter(r => routeFirstLoad(r) > maxBytes)
|
|
280
280
|
if (over.length === 0)
|
|
281
281
|
return
|
|
282
|
-
const lines = over.map(r =>
|
|
282
|
+
const lines = over.map((r) => {
|
|
283
|
+
const bytes = routeFirstLoad(r)
|
|
284
|
+
const target = r.ecoIndex?.heaviest !== undefined && r.ecoIndex.heaviest.bytes >= r.firstLoad
|
|
285
|
+
? r.ecoIndex.heaviest.url
|
|
286
|
+
: r.ecoIndex?.url ?? r.path
|
|
287
|
+
return ` ${target} downloads ${kb(bytes)} on a first visit`
|
|
288
|
+
})
|
|
283
289
|
throw new Error(`prunelle build: first load over budget.firstLoad ${kb(maxBytes)} (brotli) on ${routeCount(over.length)}:\n${lines.join('\n')}\nResize or compress the heaviest images with @prunellejs/images, subset the fonts, defer islands, or raise budget.firstLoad in prunelle.config.ts.`)
|
|
284
290
|
}
|
package/src/cli/check.ts
CHANGED
|
@@ -326,6 +326,10 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
326
326
|
for (const issue of islands.issues)
|
|
327
327
|
errors.push(formatIslandIssue(issue, root, sources))
|
|
328
328
|
warnings.push(...islandValueWarnings(islands.valueUses, root, sources, compliance))
|
|
329
|
+
for (const { file, warning } of islands.promotedWarnings) {
|
|
330
|
+
if (shouldEmitWarning(warning, compliance, site))
|
|
331
|
+
warnings.push(formatDiagnostic(locOf(root, file, sources, warning.start), warning.message.replaceAll(file, relPosix(root, file)), 'warning'))
|
|
332
|
+
}
|
|
329
333
|
|
|
330
334
|
// 3b. Static guardrails: non-serializable island props, route exports, route conflicts, missing paths()
|
|
331
335
|
const seenRoutes = new Map<string, string>()
|
package/src/compiler/analyze.ts
CHANGED
|
@@ -598,7 +598,7 @@ export function getExprContext(analysis: ModuleAnalysis): ExprContext {
|
|
|
598
598
|
}
|
|
599
599
|
|
|
600
600
|
// An island page whose reads of `data` the compiler cannot follow ships the whole `load()` result, personal data it never shows included.
|
|
601
|
-
function wholeLoadShippedWarning(filename: string, start: number): CompilerWarning {
|
|
601
|
+
export function wholeLoadShippedWarning(filename: string, start: number): CompilerWarning {
|
|
602
602
|
return {
|
|
603
603
|
start,
|
|
604
604
|
message: `prunelle compiler: the island page in ${filename} uses \`data\` in a way the compiler cannot follow, so the whole load() result is sent to the browser: export \`clientData\` listing the keys the page reads (\`export const clientData = ['title']\`), or \`(data) => data\` to send all of it on purpose.`,
|
|
@@ -612,7 +612,6 @@ export function analyzeModule(filename: string, code: string, program: Program =
|
|
|
612
612
|
const loadNodes = loadDeclarations(program)
|
|
613
613
|
const body = scanBody(program, filename, code, imports, decls, warnings, new Set(loadNodes))
|
|
614
614
|
checkBareSignals(program, imports.signalCallees, filename)
|
|
615
|
-
checkBodyPropsDestructure(program, code, body.bindings, filename, warnings)
|
|
616
615
|
const jsxNodes = body.hasJsx ? computeJsxNodes(program) : new WeakSet<Node>()
|
|
617
616
|
if (body.hasJsx) {
|
|
618
617
|
checkCompliance(program, filename, code, warnings, tag => resolvePrunelleTag(tag, imports.imports))
|
|
@@ -625,6 +624,8 @@ export function analyzeModule(filename: string, code: string, program: Program =
|
|
|
625
624
|
}
|
|
626
625
|
const hasAsyncDefault = decls.hasAsyncDefault || (decls.defaultLocal !== undefined && decls.asyncLocals.has(decls.defaultLocal))
|
|
627
626
|
const interactivity = resolveInteractivity(body.bindings, decls.exportLocals)
|
|
627
|
+
if (body.hasJsx)
|
|
628
|
+
checkBodyPropsDestructure(program, code, interactivity.browserSpans, jsxNodes, filename, warnings)
|
|
628
629
|
const page = interactivity.exports.get('default')
|
|
629
630
|
if (hasAsyncDefault && page?.interactive === true)
|
|
630
631
|
guarded(page.offset ?? 0, () => { throw asyncInteractiveError(filename, page.reason, page.offset) })
|
|
@@ -633,7 +634,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
|
|
|
633
634
|
|
|
634
635
|
const cacheExport = parseCacheExport(program)
|
|
635
636
|
const hasLoadExport = decls.hasLoadExport || loadNodes.length > 0
|
|
636
|
-
const defaultDataKeys = page?.interactive === true ? analyzeDefaultDataKeys(program, decls.defaultLocal, decls.localInits) : undefined
|
|
637
|
+
const defaultDataKeys = page?.interactive === true || hasLoadExport ? analyzeDefaultDataKeys(program, decls.defaultLocal, decls.localInits) : undefined
|
|
637
638
|
if (page?.interactive === true && hasLoadExport && defaultDataKeys === undefined && !decls.exportedNames.includes('clientData'))
|
|
638
639
|
warnings.push(wholeLoadShippedWarning(filename, decls.localInits.get(decls.defaultLocal ?? '')?.start ?? page.offset ?? 0))
|
|
639
640
|
return {
|
|
@@ -127,17 +127,18 @@ function loadingAttrs(element: JSXElement, tag: string): Array<[string, JSXAttri
|
|
|
127
127
|
return out
|
|
128
128
|
}
|
|
129
129
|
|
|
130
|
-
/**
|
|
130
|
+
/** Distinct third-party origins each loading attribute of a plain element points at. */
|
|
131
131
|
export function thirdPartyLoads(element: JSXElement, tag: string): ThirdPartyLoad[] {
|
|
132
132
|
const out: ThirdPartyLoad[] = []
|
|
133
133
|
for (const [name, attr, urlsOf] of loadingAttrs(element, tag)) {
|
|
134
134
|
if (attr === undefined)
|
|
135
135
|
continue
|
|
136
|
+
const seen = new Set<string>()
|
|
136
137
|
for (const url of attrStrings(attr).flatMap(urlsOf)) {
|
|
137
138
|
const origin = thirdPartyOrigin(url)
|
|
138
|
-
if (origin !== undefined) {
|
|
139
|
+
if (origin !== undefined && !seen.has(origin)) {
|
|
140
|
+
seen.add(origin)
|
|
139
141
|
out.push({ attr: name, url, origin, start: attr.start })
|
|
140
|
-
break
|
|
141
142
|
}
|
|
142
143
|
}
|
|
143
144
|
}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
// Warns on `const { a } = props` in a component that runs in the browser: only a destructured parameter is rewritten to stay reactive, and a read of stable objects in the body can be meant.
|
|
2
2
|
|
|
3
3
|
import type { Function as FunctionNode, Node, Program } from 'oxc-parser'
|
|
4
|
-
import type { BindingFacts } from './interactivity'
|
|
5
4
|
import type { CompilerWarning } from './mistakes'
|
|
6
|
-
import { unwrapTsExpr } from './shared'
|
|
5
|
+
import { containsJsx, unwrapTsExpr } from './shared'
|
|
7
6
|
|
|
8
7
|
function isFunction(node: Node | null | undefined): node is FunctionNode {
|
|
9
8
|
return node !== null && node !== undefined && (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression')
|
|
@@ -28,14 +27,23 @@ function declaredFunctions(stmt: Node): FunctionNode[] {
|
|
|
28
27
|
}
|
|
29
28
|
|
|
30
29
|
/** Warns on a top-level statement of a browser component's body that destructures its first parameter, with the parameter form as the fix. */
|
|
31
|
-
export function checkBodyPropsDestructure(
|
|
32
|
-
|
|
30
|
+
export function checkBodyPropsDestructure(
|
|
31
|
+
program: Program,
|
|
32
|
+
code: string,
|
|
33
|
+
browserSpans: readonly [number, number][],
|
|
34
|
+
jsxNodes: WeakSet<Node>,
|
|
35
|
+
filename: string,
|
|
36
|
+
warnings: CompilerWarning[],
|
|
37
|
+
): void {
|
|
38
|
+
if (browserSpans.length === 0)
|
|
39
|
+
return
|
|
33
40
|
for (const stmt of program.body) {
|
|
34
|
-
if (!inBrowser.some(b => b.start >= stmt.start && b.end <= stmt.end))
|
|
35
|
-
continue
|
|
36
41
|
for (const fn of declaredFunctions(stmt)) {
|
|
37
|
-
|
|
38
|
-
|
|
42
|
+
if (!browserSpans.some(([s, e]) => fn.start >= s && fn.end <= e))
|
|
43
|
+
continue
|
|
44
|
+
const rawParam = fn.params[0]
|
|
45
|
+
const param = rawParam?.type === 'AssignmentPattern' ? rawParam.left : rawParam
|
|
46
|
+
if (param?.type !== 'Identifier' || fn.body?.type !== 'BlockStatement' || !containsJsx(fn.body, jsxNodes))
|
|
39
47
|
continue
|
|
40
48
|
for (const inner of fn.body.body) {
|
|
41
49
|
if (inner.type !== 'VariableDeclaration')
|
package/src/dev/host-check.ts
CHANGED
|
@@ -2,9 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
const LOOPBACK_NAMES = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
4
4
|
const IPV4_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/
|
|
5
|
+
const BAD_HOST_CHARS_RE = /[@/?#\\\s\u0000-\u001F\u007F]/
|
|
5
6
|
|
|
6
7
|
function hostnameOf(host: string): string | undefined {
|
|
7
|
-
|
|
8
|
+
if (host.length === 0 || BAD_HOST_CHARS_RE.test(host) || !URL.canParse(`http://${host}`))
|
|
9
|
+
return undefined
|
|
10
|
+
const parsed = new URL(`http://${host}`)
|
|
11
|
+
if (parsed.username !== '' || parsed.password !== '' || parsed.pathname !== '/' || parsed.search !== '' || parsed.hash !== '')
|
|
12
|
+
return undefined
|
|
13
|
+
return parsed.hostname
|
|
8
14
|
}
|
|
9
15
|
|
|
10
16
|
/** Refuses with `421` a request whose `Host` is not loopback, `*.localhost`, an IP address, the bound `hostname` or the host of one of `origins`. */
|
package/src/dev/index.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import type { Server } from 'bun'
|
|
5
5
|
import type { BuildCacheStats } from '../build/graph'
|
|
6
6
|
import type { PrunelleApp } from '../server/index'
|
|
7
|
+
import type { TrustProxy } from '../server/security'
|
|
7
8
|
import type { RecycleReason } from './protocol'
|
|
8
9
|
import type { PendingBuild } from './queue'
|
|
9
10
|
import { existsSync, readdirSync, rmSync } from 'node:fs'
|
|
@@ -79,6 +80,8 @@ async function handleAppFetch(
|
|
|
79
80
|
reloadAssets: ReturnType<typeof makeDevReloadAssets>
|
|
80
81
|
lastError: string | undefined
|
|
81
82
|
app: PrunelleApp | undefined
|
|
83
|
+
trustedOrigins: readonly string[] | undefined
|
|
84
|
+
trustProxy: TrustProxy | undefined
|
|
82
85
|
},
|
|
83
86
|
): Promise<Response> {
|
|
84
87
|
const refused = state.checkHost?.(request)
|
|
@@ -89,12 +92,12 @@ async function handleAppFetch(
|
|
|
89
92
|
srv.timeout(request, 0)
|
|
90
93
|
return state.hub.events(request)
|
|
91
94
|
}
|
|
95
|
+
const remoteIp = state.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
|
|
92
96
|
if (pathname === state.reloadAssets.openEditorPath)
|
|
93
|
-
return handleOpenEditorRequest(request, state.root)
|
|
97
|
+
return handleOpenEditorRequest(request, state.root, { trustedOrigins: state.trustedOrigins, trustProxy: state.trustProxy, remoteIp: remoteIp ?? '' })
|
|
94
98
|
if (state.lastError !== undefined)
|
|
95
99
|
return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
|
|
96
100
|
|
|
97
|
-
const remoteIp = state.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
|
|
98
101
|
const res = await state.app!.handle(request, remoteIp)
|
|
99
102
|
const ct = res.headers.get('content-type') ?? ''
|
|
100
103
|
const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
|
|
@@ -230,7 +233,7 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
230
233
|
options,
|
|
231
234
|
runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
|
|
232
235
|
initialCfg.port,
|
|
233
|
-
(request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, checkHost, hub, reloadAssets, lastError, app: current?.app }),
|
|
236
|
+
(request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, checkHost, hub, reloadAssets, lastError, app: current?.app, trustedOrigins: activeCfg.trustedOrigins, trustProxy: activeCfg.trustProxy }),
|
|
234
237
|
)
|
|
235
238
|
let stopPromise: Promise<void> | undefined
|
|
236
239
|
|
package/src/dev/open-editor.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Opens a project source file at `line:col` in `$PRUNELLE_EDITOR` or `$VISUAL` on Alt-click in `prunelle dev`.
|
|
2
2
|
|
|
3
|
+
import type { TrustProxy } from '../server/security'
|
|
3
4
|
import { existsSync, realpathSync } from 'node:fs'
|
|
4
5
|
import { relative, resolve } from 'node:path'
|
|
5
6
|
import { isInside } from '../build/is-inside'
|
|
@@ -136,6 +137,17 @@ export function buildEditorCommand(editorSpec: string, loc: { file: string, line
|
|
|
136
137
|
export interface OpenEditorOptions {
|
|
137
138
|
env?: Record<string, string | undefined> | undefined
|
|
138
139
|
spawn?: ((cmd: string[]) => void) | undefined
|
|
140
|
+
trustedOrigins?: ReadonlySet<string> | readonly string[] | undefined
|
|
141
|
+
trustProxy?: TrustProxy | undefined
|
|
142
|
+
remoteIp?: string | undefined
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const IPV4_LOOPBACK_RE = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
|
|
146
|
+
|
|
147
|
+
function isLoopbackIp(ip: string): boolean {
|
|
148
|
+
const bare = ip.trim().toLowerCase().replace(/^\[|\]$/g, '')
|
|
149
|
+
const unmapped = bare.startsWith('::ffff:') ? bare.slice(7) : bare
|
|
150
|
+
return unmapped === '::1' || unmapped === '0:0:0:0:0:0:0:1' || IPV4_LOOPBACK_RE.test(unmapped)
|
|
139
151
|
}
|
|
140
152
|
|
|
141
153
|
export function openInEditor(
|
|
@@ -184,10 +196,18 @@ export async function handleOpenEditorRequest(
|
|
|
184
196
|
): Promise<Response> {
|
|
185
197
|
if (request.method !== 'POST')
|
|
186
198
|
return Response.json({ ok: false, error: 'Method Not Allowed' }, { status: 405, headers: { allow: 'POST' } })
|
|
187
|
-
|
|
199
|
+
if (options?.remoteIp !== undefined && !isLoopbackIp(options.remoteIp))
|
|
200
|
+
return Response.json({ ok: false, error: 'Open-editor is only available from loopback addresses.' }, { status: 403 })
|
|
201
|
+
const trusted = options?.trustedOrigins === undefined
|
|
202
|
+
? undefined
|
|
203
|
+
: options.trustedOrigins instanceof Set
|
|
204
|
+
? options.trustedOrigins
|
|
205
|
+
: new Set(options.trustedOrigins)
|
|
206
|
+
const originCheck = verifyOrigin(request, trusted, options?.trustProxy ?? false)
|
|
188
207
|
if (!originCheck.ok)
|
|
189
208
|
return Response.json({ ok: false, error: originCheck.reason }, { status: 403 })
|
|
190
|
-
|
|
209
|
+
const mediaType = (request.headers.get('content-type') ?? '').split(';', 1)[0]!.trim().toLowerCase()
|
|
210
|
+
if (mediaType !== 'application/json')
|
|
191
211
|
return Response.json({ ok: false, error: 'Expected content-type: application/json.' }, { status: 415 })
|
|
192
212
|
|
|
193
213
|
let rawSrc = ''
|
package/src/dom/index.ts
CHANGED
|
@@ -8,6 +8,13 @@ export { effect } from '../reactivity/index'
|
|
|
8
8
|
let hydrating = false
|
|
9
9
|
let hydrateNode: Node | null = null
|
|
10
10
|
let hydrateRoot: Element | null = null
|
|
11
|
+
let mismatchHook: ((parent: Node, stale: Node, node: Node) => void) | null = null
|
|
12
|
+
|
|
13
|
+
export function setMismatchHook(fn: typeof mismatchHook): typeof mismatchHook {
|
|
14
|
+
const prev = mismatchHook
|
|
15
|
+
mismatchHook = fn
|
|
16
|
+
return prev
|
|
17
|
+
}
|
|
11
18
|
|
|
12
19
|
export function isRangeEnd(node: Node): boolean {
|
|
13
20
|
return node.nodeType === 8 && (node as Comment).data === 'k]'
|
|
@@ -126,14 +133,18 @@ export function template(html: string, isSvg?: boolean): () => Node {
|
|
|
126
133
|
node = null
|
|
127
134
|
if (process.env.NODE_ENV !== 'production' && node !== stale)
|
|
128
135
|
warnMismatch(stale, expectedTag!, node !== null)
|
|
136
|
+
const parent = stale.parentNode
|
|
129
137
|
if (node === null) {
|
|
130
138
|
hydrating = false
|
|
131
139
|
hydrateNode = null
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
140
|
+
node = clone()
|
|
141
|
+
parent?.replaceChild(node, stale)
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
hydrateNode = node.nextSibling
|
|
135
145
|
}
|
|
136
|
-
|
|
146
|
+
if (node !== stale && parent !== null)
|
|
147
|
+
mismatchHook?.(parent, stale, node)
|
|
137
148
|
return node
|
|
138
149
|
}
|
|
139
150
|
|
package/src/dom/loop.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import type { Owner, Signal } from '../reactivity/index'
|
|
5
5
|
import { createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, signal, untrack } from '../reactivity/index'
|
|
6
6
|
import { claimLoop } from './claim'
|
|
7
|
-
import { hydrateCursor, skipRange } from './index'
|
|
7
|
+
import { hydrateCursor, isRangeEnd, setMismatchHook, skipRange } from './index'
|
|
8
8
|
|
|
9
9
|
interface Row<T> {
|
|
10
10
|
key: unknown
|
|
@@ -83,16 +83,28 @@ function keepEnds<T>(rows: Row<T>[], start: number, oldEnd: number, newEnd: numb
|
|
|
83
83
|
type RenderRow<T> = (item: Signal<T>, index?: Signal<number>) => Node | DocumentFragment | null | undefined | boolean | string | number
|
|
84
84
|
|
|
85
85
|
|
|
86
|
+
function pushRange(out: Node[], from: Node | null, stop: Node | null): void {
|
|
87
|
+
for (let n = from; n !== null && n !== stop && !isRangeEnd(n); n = n.nextSibling)
|
|
88
|
+
out.push(n)
|
|
89
|
+
}
|
|
90
|
+
|
|
86
91
|
// While hydrating, a row that rendered no node of its own takes the server nodes the cursor moved over since `before`.
|
|
87
|
-
function adoptRowNodes<T>(
|
|
92
|
+
function adoptRowNodes<T>(
|
|
93
|
+
parent: Node,
|
|
94
|
+
marker: Node | null,
|
|
95
|
+
row: Row<T>,
|
|
96
|
+
before: Node | null,
|
|
97
|
+
prevSib: Node | null,
|
|
98
|
+
leftover: Node[],
|
|
99
|
+
fallbackEnd: Node | null,
|
|
100
|
+
): boolean {
|
|
88
101
|
const afterCursor = hydrateCursor()
|
|
89
102
|
if (row.node === null && before !== null && before !== afterCursor) {
|
|
90
103
|
const start = before.parentNode === parent ? before : prevSib !== null ? prevSib.nextSibling : parent.firstChild
|
|
91
104
|
const claimed: Node[] = []
|
|
92
|
-
for (let n: Node | null = start; n !== null && n !== afterCursor && n !== marker; n = n.nextSibling) {
|
|
93
|
-
if (
|
|
94
|
-
|
|
95
|
-
claimed.push(n)
|
|
105
|
+
for (let n: Node | null = start; n !== null && n !== afterCursor && n !== marker && n !== fallbackEnd && !isRangeEnd(n); n = n.nextSibling) {
|
|
106
|
+
if (!leftover.includes(n))
|
|
107
|
+
claimed.push(n)
|
|
96
108
|
}
|
|
97
109
|
if (claimed.length === 1) {
|
|
98
110
|
row.node = claimed[0]!
|
|
@@ -111,8 +123,7 @@ function adoptRowNodes<T>(parent: Node, marker: Node | null, row: Row<T>, before
|
|
|
111
123
|
|
|
112
124
|
// Server nodes no client row claimed (stepped over mid-list, or past the last row): the data changed between the render and hydration, so they would stay in the DOM outside `rows`. They are removed, and the island hears `pru:hydration-mismatch`.
|
|
113
125
|
function dropServerRows(parent: Node, leftover: Node[], from: Node | null, marker: Node | null, added: number): void {
|
|
114
|
-
|
|
115
|
-
leftover.push(n)
|
|
126
|
+
pushRange(leftover, from, marker)
|
|
116
127
|
if (leftover.length === 0 && added === 0)
|
|
117
128
|
return
|
|
118
129
|
if (process.env.NODE_ENV !== 'production')
|
|
@@ -129,21 +140,34 @@ function createRows<T>(parent: Node, marker: Node | null, items: readonly T[], n
|
|
|
129
140
|
let end: Node | null = null
|
|
130
141
|
const leftover: Node[] = []
|
|
131
142
|
let added = 0
|
|
143
|
+
let fallbackEnd: Node | null = null
|
|
132
144
|
if (claimLoop(parent, () => {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
if (before !== null && row.node !== null && row.node.parentNode === parent) {
|
|
139
|
-
for (let n: Node | null = before; n !== null && n !== row.node; n = n.nextSibling)
|
|
140
|
-
leftover.push(n)
|
|
141
|
-
}
|
|
142
|
-
if (adoptRowNodes(parent, marker, row, before, prevSib))
|
|
145
|
+
const prevHook = setMismatchHook((p, stale, target) => {
|
|
146
|
+
if (p !== parent)
|
|
147
|
+
return
|
|
148
|
+
if (stale.parentNode === null) {
|
|
149
|
+
leftover.push(stale)
|
|
143
150
|
added++
|
|
144
|
-
|
|
151
|
+
pushRange(leftover, fallbackEnd = target.nextSibling, marker)
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
pushRange(leftover, stale, target)
|
|
155
|
+
}
|
|
156
|
+
})
|
|
157
|
+
try {
|
|
158
|
+
for (let i = 0; i < items.length; i++) {
|
|
159
|
+
const before = hydrateCursor()
|
|
160
|
+
const prevSib = before?.previousSibling ?? null
|
|
161
|
+
const row = newRow(items[i]!, i)
|
|
162
|
+
if (adoptRowNodes(parent, marker, row, before, prevSib, leftover, fallbackEnd))
|
|
163
|
+
added++
|
|
164
|
+
created[i] = row
|
|
165
|
+
}
|
|
166
|
+
end = hydrateCursor()
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
setMismatchHook(prevHook)
|
|
145
170
|
}
|
|
146
|
-
end = hydrateCursor()
|
|
147
171
|
}, skip, startMarker)) {
|
|
148
172
|
dropServerRows(parent, leftover, end, marker, added)
|
|
149
173
|
return created
|
package/src/plugins/context.ts
CHANGED
|
@@ -62,20 +62,48 @@ export function runWithAppContext<T>(ctx: AppRuntimeContext, fn: () => T): T {
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
// Bun does not carry an AsyncLocalStorage store into the top level of a module imported inside `run()` (1.4.5), so the context of a config being imported is also kept here.
|
|
65
|
-
|
|
65
|
+
// Shared on `globalThis` alongside `appStorage` so dual module instances coordinate, and serialized across non-nested calls so out-of-order imports cannot leak `current`.
|
|
66
|
+
interface ImportFallbackState {
|
|
67
|
+
current: AppRuntimeContext | undefined
|
|
68
|
+
tail: Promise<void>
|
|
69
|
+
inImport: AsyncLocalStorage<boolean>
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const IMPORT_STATE_KEY = Symbol.for('pru.app.importState')
|
|
73
|
+
const importState: ImportFallbackState = (
|
|
74
|
+
(globalThis as Record<symbol, ImportFallbackState | undefined>)[IMPORT_STATE_KEY]
|
|
75
|
+
??= { current: undefined, tail: Promise.resolve(), inImport: new AsyncLocalStorage<boolean>() }
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
async function runImporting<T>(ctx: AppRuntimeContext, load: () => Promise<T>): Promise<T> {
|
|
79
|
+
const outer = importState.current
|
|
80
|
+
importState.current = ctx
|
|
81
|
+
try {
|
|
82
|
+
return await importState.inImport.run(true, () => runWithAppContext(ctx, load))
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
importState.current = outer
|
|
86
|
+
}
|
|
87
|
+
}
|
|
66
88
|
|
|
67
89
|
/** Imports with `ctx` as the app context, the imported modules' top-level code included. */
|
|
68
90
|
export async function importWithAppContext<T>(ctx: AppRuntimeContext, load: () => Promise<T>): Promise<T> {
|
|
69
|
-
|
|
70
|
-
|
|
91
|
+
if (importState.inImport.getStore() === true)
|
|
92
|
+
return runImporting(ctx, load)
|
|
93
|
+
const prev = importState.tail
|
|
94
|
+
let release!: () => void
|
|
95
|
+
importState.tail = new Promise<void>((resolve) => {
|
|
96
|
+
release = resolve
|
|
97
|
+
})
|
|
98
|
+
await prev
|
|
71
99
|
try {
|
|
72
|
-
return await
|
|
100
|
+
return await runImporting(ctx, load)
|
|
73
101
|
}
|
|
74
102
|
finally {
|
|
75
|
-
|
|
103
|
+
release()
|
|
76
104
|
}
|
|
77
105
|
}
|
|
78
106
|
|
|
79
107
|
export function getAppContext(): AppRuntimeContext | undefined {
|
|
80
|
-
return appStorage.getStore() ??
|
|
108
|
+
return appStorage.getStore() ?? importState.current
|
|
81
109
|
}
|
package/src/server/http.ts
CHANGED
|
@@ -13,7 +13,7 @@ import { nodeEnv } from './env'
|
|
|
13
13
|
import { resolveFallbackRequestId } from './health'
|
|
14
14
|
import { requestedRegion } from './region'
|
|
15
15
|
import { GATED_ROUTE_CACHE_CONTROL } from './route-cache'
|
|
16
|
-
import { getClientIp, isHttpsRequest } from './security'
|
|
16
|
+
import { expectedOrigin, getClientIp, isHttpsRequest } from './security'
|
|
17
17
|
|
|
18
18
|
export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
|
|
19
19
|
|
|
@@ -302,19 +302,27 @@ export function isExternalRedirect(res: Response): boolean {
|
|
|
302
302
|
return EXTERNAL_REDIRECTS.has(res)
|
|
303
303
|
}
|
|
304
304
|
|
|
305
|
-
|
|
305
|
+
const REDIRECT_CONTROL_CHAR_RE = /[\u0000-\u001F\u007F]/
|
|
306
|
+
const NON_HIERARCHICAL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:(?!\/\/)/i
|
|
307
|
+
|
|
308
|
+
function sameOrigin(location: string, baseOrigin: string): boolean {
|
|
309
|
+
if (baseOrigin === 'null' || REDIRECT_CONTROL_CHAR_RE.test(location) || NON_HIERARCHICAL_SCHEME_RE.test(location.trimStart()))
|
|
310
|
+
return false
|
|
306
311
|
try {
|
|
307
|
-
return new URL(location,
|
|
312
|
+
return new URL(location, baseOrigin).origin === baseOrigin
|
|
308
313
|
}
|
|
309
314
|
catch {
|
|
310
315
|
return false
|
|
311
316
|
}
|
|
312
317
|
}
|
|
313
318
|
|
|
314
|
-
const makeRedirect = (
|
|
319
|
+
const makeRedirect = (request: Request, trustProxy: TrustProxy, url: URL): RequestContext['redirect'] => (location, status = 302, options) => {
|
|
315
320
|
const external = options?.external === true
|
|
316
|
-
if (!external
|
|
317
|
-
|
|
321
|
+
if (!external) {
|
|
322
|
+
const baseOrigin = expectedOrigin(request, trustProxy, url)
|
|
323
|
+
if (!sameOrigin(location, baseOrigin))
|
|
324
|
+
throw new Error(`prunelle: ctx.redirect("${location}") leaves ${baseOrigin}: redirect to a path of this site, or pass { external: true } as the third argument when the app chose that address itself (never one read from the request, which makes an open redirect).`)
|
|
325
|
+
}
|
|
318
326
|
const res = new Response(null, { status, headers: { location } })
|
|
319
327
|
if (external)
|
|
320
328
|
EXTERNAL_REDIRECTS.add(res)
|
|
@@ -395,7 +403,7 @@ export function makeRequestContext(
|
|
|
395
403
|
},
|
|
396
404
|
json,
|
|
397
405
|
text,
|
|
398
|
-
redirect: makeRedirect(url),
|
|
406
|
+
redirect: makeRedirect(request, trustProxy, url),
|
|
399
407
|
deny,
|
|
400
408
|
}
|
|
401
409
|
return { ctx, cookieStore }
|
package/src/server/index.ts
CHANGED
|
@@ -291,21 +291,28 @@ function createNotFoundRenderer(deps: NotFoundRendererDeps) {
|
|
|
291
291
|
}
|
|
292
292
|
|
|
293
293
|
/** The security headers every response carries, and the helpers that put them on a response built without them. */
|
|
294
|
-
function createSecurityResponders(
|
|
294
|
+
function createSecurityResponders(
|
|
295
|
+
security: EmbeddedServerConfig['security'],
|
|
296
|
+
trustProxy: TrustProxy,
|
|
297
|
+
isDev: boolean,
|
|
298
|
+
site: string | undefined,
|
|
299
|
+
explicitNodeEnv: string | undefined,
|
|
300
|
+
) {
|
|
301
|
+
const resolvedNodeEnv = explicitNodeEnv ?? nodeEnv()
|
|
295
302
|
// An https `site` says the app is served over https, whatever a proxy the server does not trust leaves in the request.
|
|
296
|
-
const httpsSite = site?.startsWith('https://') === true
|
|
303
|
+
const httpsSite = !isDev && resolvedNodeEnv !== 'development' && resolvedNodeEnv !== 'test' && site?.startsWith('https://') === true
|
|
297
304
|
const securityEntries = buildSecurityHeaderEntries(security)
|
|
298
305
|
const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
|
|
299
306
|
const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
|
|
300
307
|
const hstsValue = resolveHstsValue(security)
|
|
301
308
|
// Every response passes here, so it is where a production server first sees it runs behind a proxy it does not trust.
|
|
302
|
-
let proxyChecked = trustProxy !== false || isDev ||
|
|
309
|
+
let proxyChecked = trustProxy !== false || isDev || resolvedNodeEnv !== 'production'
|
|
303
310
|
const withHsts = (res: Response, request: Request): Response => {
|
|
304
311
|
if (!proxyChecked && request.headers.has('x-forwarded-proto')) {
|
|
305
312
|
proxyChecked = true
|
|
306
313
|
console.warn('prunelle: a request came through a proxy (it carries x-forwarded-proto) but trustProxy is off, so ctx.ip and rate limits see the proxy\'s address and https is known from site alone: set trustProxy in prunelle.config.ts to the proxy the server runs behind.')
|
|
307
314
|
}
|
|
308
|
-
return applyHstsHeader(res, request, hstsValue, trustProxy, isDev,
|
|
315
|
+
return applyHstsHeader(res, request, hstsValue, trustProxy, isDev, explicitNodeEnv, httpsSite)
|
|
309
316
|
}
|
|
310
317
|
// The one way out of every response not built with the security headers already in place.
|
|
311
318
|
const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
|
|
@@ -335,7 +342,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
335
342
|
const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
|
|
336
343
|
const { hasHeadHooks, hasHtmlTransformers, resolveDocumentHead, applyHtmlTransforms } = document
|
|
337
344
|
|
|
338
|
-
const { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError, fileGone } = createSecurityResponders(security, trustProxy, isDev, site)
|
|
345
|
+
const { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError, fileGone } = createSecurityResponders(security, trustProxy, isDev, site, config.nodeEnv ?? parentAppCtx?.nodeEnv)
|
|
339
346
|
const resolveRequestId = createRequestIdResolver(trustProxy)
|
|
340
347
|
const navigation = createNavigation(config.navigation)
|
|
341
348
|
const htmlHeaders = createHtmlHeaders(security, securityRecord, navigation, plugins)
|
package/src/server/loader.ts
CHANGED
|
@@ -110,18 +110,22 @@ async function loadServerEntry(options: ServerOptions): Promise<BuiltOutput> {
|
|
|
110
110
|
|
|
111
111
|
async function serveStaticDir(options: ServerOptions, root: string, outDir: string): Promise<PrunelleApp> {
|
|
112
112
|
const config = await loadConfig(root, { dev: options.dev, nodeEnv: options.nodeEnv })
|
|
113
|
+
const site = (options.site ?? config.site)?.replace(/\/$/, '') || undefined
|
|
114
|
+
const isDev = options.dev ?? devFromEnv()
|
|
113
115
|
return createStaticDirServer(
|
|
114
116
|
outDir,
|
|
115
117
|
options.assetPrefix ?? config.assetPrefix ?? '/_pru',
|
|
116
118
|
options.security ?? config.security,
|
|
117
119
|
(options.compress ?? config.compress) !== false,
|
|
118
120
|
options.trustProxy ?? config.trustProxy ?? false,
|
|
119
|
-
|
|
121
|
+
isDev,
|
|
120
122
|
{
|
|
121
123
|
navigation: options.navigation ?? config.navigation,
|
|
122
124
|
plugins: options.plugins ?? config.plugins,
|
|
123
125
|
onError: options.onError ?? config.onError,
|
|
124
126
|
errorSink: options.errorSink,
|
|
127
|
+
httpsSite: !isDev && site?.startsWith('https://') === true,
|
|
128
|
+
nodeEnv: options.nodeEnv,
|
|
125
129
|
},
|
|
126
130
|
)
|
|
127
131
|
}
|
package/src/server/security.ts
CHANGED
|
@@ -366,11 +366,11 @@ function forwardedValue(request: Request, header: string, trustProxy: TrustProxy
|
|
|
366
366
|
return undefined
|
|
367
367
|
}
|
|
368
368
|
|
|
369
|
-
function forwardedOrigin(request: Request, trustProxy: TrustProxy): string | undefined {
|
|
369
|
+
function forwardedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?: URL): string | undefined {
|
|
370
370
|
const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase()
|
|
371
371
|
if (proto !== 'http' && proto !== 'https')
|
|
372
372
|
return undefined
|
|
373
|
-
const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim()
|
|
373
|
+
const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim() || (requestUrl ?? new URL(request.url)).host
|
|
374
374
|
if (!host)
|
|
375
375
|
return undefined
|
|
376
376
|
try {
|
|
@@ -430,8 +430,8 @@ export function isTrustedOrigin(
|
|
|
430
430
|
}
|
|
431
431
|
|
|
432
432
|
/** The origin this server takes the request to be on: the trusted forwarded one, else the one it was reached at. */
|
|
433
|
-
function expectedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?: URL): string {
|
|
434
|
-
return forwardedOrigin(request, trustProxy) ?? requestUrl?.origin ?? new URL(request.url).origin
|
|
433
|
+
export function expectedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?: URL): string {
|
|
434
|
+
return forwardedOrigin(request, trustProxy, requestUrl) ?? requestUrl?.origin ?? new URL(request.url).origin
|
|
435
435
|
}
|
|
436
436
|
|
|
437
437
|
/** Whether `origin` is the https twin of the http `expected` origin: the same host, so only the scheme can differ. */
|
package/src/server/static-dir.ts
CHANGED
|
@@ -34,6 +34,8 @@ export interface StaticDirExtraOptions {
|
|
|
34
34
|
/** The app's `onError` hook; plugin `onError` hooks run too. With no hook the error is logged. */
|
|
35
35
|
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
36
36
|
errorSink?: ((info: ServerErrorInfo) => void) | undefined
|
|
37
|
+
httpsSite?: boolean | undefined
|
|
38
|
+
nodeEnv?: string | undefined
|
|
37
39
|
}
|
|
38
40
|
|
|
39
41
|
function findNotFound(rel: string | undefined, byDir: ReadonlyMap<string, ServedFile>): ServedFile | undefined {
|
|
@@ -117,10 +119,11 @@ export function createStaticDirServer(
|
|
|
117
119
|
const htmlCsp = baseCsp !== undefined
|
|
118
120
|
? withCspHashes(baseCsp, { styleHashes: extraStyleHashes, scriptHashes: extraScriptHashes })
|
|
119
121
|
: undefined
|
|
122
|
+
const httpsSite = !isDev && extra?.httpsSite === true
|
|
120
123
|
const hstsValue = resolveHstsValue(security)
|
|
121
124
|
const withHsts = hstsValue === undefined || isDev
|
|
122
125
|
? (res: Response) => res
|
|
123
|
-
: (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev)
|
|
126
|
+
: (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev, extra?.nodeEnv, httpsSite)
|
|
124
127
|
const serveFileUnguarded = createFileServer({ compressEnabled, compressCache, withHsts })
|
|
125
128
|
const notifyError = createErrorNotifier(extra?.onError, plugins, { dev: isDev, sink: extra?.errorSink })
|
|
126
129
|
// A file that fails to open answers here, where the request is known: gone since the listing is a 404, anything else is reported.
|
package/src/style.ts
CHANGED
|
@@ -22,28 +22,60 @@ function cssName(key: string): string {
|
|
|
22
22
|
|
|
23
23
|
const PROPERTY_NAME = /^-{0,2}[a-z][\w-]*$/i
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
const NL = /[\n\r\f]/
|
|
26
|
+
const URL_FN = /(?:^|[^\w-])url$/i
|
|
27
|
+
// After `url(`, either a quoted string opener (group 1) or a valid unquoted `<url-token>` through `)` (disjoint branches: linear time).
|
|
28
|
+
const UNQUOTED_URL = /[ \t]*(?:(["'])|(?:\\[^\n\r\f]|[^"'(){}\u0000-\u0020\u007F\\])*[ \t]*\))/y
|
|
29
|
+
|
|
30
|
+
// Whether `value` stays one declaration value: a `;`, `{` or `}` outside quotes and parentheses, a comment, a raw newline, a trailing/newline escape, an unquoted bad-url, or a quote or parenthesis left open would end it and let the rest add declarations.
|
|
26
31
|
function isOneValue(value: string): boolean {
|
|
27
32
|
let depth = 0
|
|
28
33
|
let quote = ''
|
|
34
|
+
let esc = false
|
|
29
35
|
for (let i = 0; i < value.length; i++) {
|
|
30
36
|
const c = value[i]!
|
|
31
|
-
if (c === '\\')
|
|
32
|
-
i
|
|
33
|
-
|
|
37
|
+
if (c === '\\') {
|
|
38
|
+
if (++i >= value.length || NL.test(value[i]!))
|
|
39
|
+
return false
|
|
40
|
+
esc = true
|
|
41
|
+
}
|
|
42
|
+
else if (NL.test(c)) {
|
|
34
43
|
return false
|
|
35
|
-
|
|
44
|
+
}
|
|
45
|
+
else if (quote !== '') {
|
|
36
46
|
quote = c === quote ? '' : quote
|
|
37
|
-
|
|
47
|
+
}
|
|
48
|
+
else if (c === '"' || c === '\'') {
|
|
38
49
|
quote = c
|
|
39
|
-
|
|
50
|
+
esc = false
|
|
51
|
+
}
|
|
52
|
+
else if (c === '/' && value[i + 1] === '*') {
|
|
40
53
|
return false
|
|
41
|
-
|
|
54
|
+
}
|
|
55
|
+
else if (c === '(') {
|
|
56
|
+
const checkUrl = esc || URL_FN.test(value.slice(0, i))
|
|
57
|
+
esc = false
|
|
58
|
+
if (checkUrl) {
|
|
59
|
+
UNQUOTED_URL.lastIndex = i + 1
|
|
60
|
+
const m = UNQUOTED_URL.exec(value)
|
|
61
|
+
if (m === null || (m[1] === undefined && m[0].includes('/*')))
|
|
62
|
+
return false
|
|
63
|
+
if (m[1] === undefined) {
|
|
64
|
+
i = UNQUOTED_URL.lastIndex - 1
|
|
65
|
+
continue
|
|
66
|
+
}
|
|
67
|
+
}
|
|
42
68
|
depth++
|
|
43
|
-
|
|
69
|
+
}
|
|
70
|
+
else if (c === ')' && --depth < 0) {
|
|
44
71
|
return false
|
|
45
|
-
|
|
72
|
+
}
|
|
73
|
+
else if (depth === 0 && (c === ';' || c === '{' || c === '}')) {
|
|
46
74
|
return false
|
|
75
|
+
}
|
|
76
|
+
else if (',);{}'.includes(c)) {
|
|
77
|
+
esc = false
|
|
78
|
+
}
|
|
47
79
|
}
|
|
48
80
|
return quote === '' && depth === 0
|
|
49
81
|
}
|