prunelle 0.1.1 → 0.5.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/llms.txt +23 -19
- package/package.json +8 -2
- package/src/a11y/declaration.ts +335 -0
- package/src/a11y/index.ts +446 -0
- package/src/a11y/rgaa-map.ts +184 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +80 -36
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +8 -4
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +11 -9
- package/src/build/ecoindex.ts +229 -0
- package/src/build/index.ts +174 -108
- package/src/build/islands.ts +2 -2
- package/src/build/manifest.ts +66 -5
- package/src/build/output.ts +2 -2
- package/src/build/plugin-host.ts +91 -33
- package/src/build/precompress.ts +15 -2
- package/src/build/prerender.ts +128 -46
- package/src/build/report.ts +23 -2
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static.ts +137 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +561 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check.ts +75 -20
- package/src/cli/commands.ts +85 -4
- package/src/cli/docs.ts +402 -0
- package/src/cli/inspect.ts +103 -14
- package/src/cli/mcp-tools.ts +490 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +2 -2
- package/src/cli/render.ts +421 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +137 -16
- package/src/compiler/analyze.ts +42 -9
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability.ts +636 -0
- package/src/compiler/compliance-rgaa.ts +508 -0
- package/src/compiler/compliance.ts +241 -289
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +167 -57
- package/src/compiler/mistakes.ts +4 -1
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +40 -12
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +218 -87
- package/src/dev/error-log.ts +151 -0
- package/src/dev/index.ts +84 -34
- package/src/dev/open-editor.ts +204 -0
- package/src/dev/protocol.ts +1 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +42 -25
- package/src/dev/watchers.ts +47 -11
- package/src/dom/action.ts +43 -20
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +28 -12
- package/src/dom/index.ts +26 -8
- package/src/dom/island.ts +35 -28
- package/src/dom/loop.ts +10 -9
- package/src/plugins/config.ts +8 -7
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +26 -7
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +5 -2
- package/src/plugins/services.ts +62 -0
- package/src/plugins/types.ts +32 -0
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +45 -13
- package/src/server/action-protect.ts +198 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +82 -27
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +91 -9
- package/src/server/document.ts +25 -10
- package/src/server/errors.ts +303 -65
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +128 -31
- package/src/server/index.ts +230 -260
- package/src/server/loader.ts +5 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +123 -88
- package/src/server/public.ts +3 -3
- package/src/server/rate-limit.ts +58 -35
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +423 -0
- package/src/server/route-table.ts +339 -8
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +196 -63
- package/src/server/security.ts +208 -32
- package/src/server/serve-handlers.ts +21 -7
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +61 -8
- package/src/server/stream.ts +41 -22
- package/src/ssr/context.ts +85 -3
- package/src/ssr/index.ts +130 -3
- package/src/ssr/region.ts +31 -19
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +5 -0
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/index.tsx +4 -0
- package/ts-plugin.cjs +4277 -0
package/src/server/loader.ts
CHANGED
|
@@ -74,6 +74,7 @@ export async function startBuiltApp(options: ServerOptions): Promise<{ app: Prun
|
|
|
74
74
|
nodeEnv: options.nodeEnv,
|
|
75
75
|
errorSink: options.errorSink,
|
|
76
76
|
prerender: options.prerender,
|
|
77
|
+
static: options.static,
|
|
77
78
|
})
|
|
78
79
|
return { app, outDir, entry }
|
|
79
80
|
}
|
|
@@ -114,5 +115,9 @@ async function serveStaticDir(options: ServerOptions, root: string, outDir: stri
|
|
|
114
115
|
(options.compress ?? config.compress) !== false,
|
|
115
116
|
options.trustProxy ?? config.trustProxy ?? false,
|
|
116
117
|
options.dev ?? (process.env.PRUNELLE_DEV === '1'),
|
|
118
|
+
{
|
|
119
|
+
navigation: options.navigation ?? config.navigation,
|
|
120
|
+
plugins: options.plugins ?? config.plugins,
|
|
121
|
+
},
|
|
117
122
|
)
|
|
118
123
|
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Route parameter matchers (built-in `integer`, `uuid`, `slug` and app-defined `src/params/<name>.ts`) and shared route-pattern segment parsing.
|
|
2
|
+
|
|
3
|
+
export type ParamMatcher = (value: string) => boolean
|
|
4
|
+
export type ParamMatcherMap = Readonly<Record<string, ParamMatcher>>
|
|
5
|
+
|
|
6
|
+
const INTEGER_RE = /^\d+$/
|
|
7
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
8
|
+
const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
9
|
+
|
|
10
|
+
export const BUILTIN_PARAM_MATCHERS: ParamMatcherMap = {
|
|
11
|
+
integer: value => INTEGER_RE.test(value),
|
|
12
|
+
uuid: value => UUID_RE.test(value),
|
|
13
|
+
slug: value => SLUG_RE.test(value),
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const BUILTIN_PARAM_MATCHER_NAMES = ['integer', 'uuid', 'slug'] as const
|
|
17
|
+
|
|
18
|
+
export function isBuiltinMatcher(name: string): boolean {
|
|
19
|
+
return Object.hasOwn(BUILTIN_PARAM_MATCHERS, name)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Extracts a matcher function from an app param matcher module (`export function match` or `export default`). */
|
|
23
|
+
export function extractMatcherFn(mod: unknown): ParamMatcher | undefined {
|
|
24
|
+
if (typeof mod === 'function')
|
|
25
|
+
return mod as ParamMatcher
|
|
26
|
+
if (mod !== null && typeof mod === 'object') {
|
|
27
|
+
const rec = mod as Record<string, unknown>
|
|
28
|
+
if (typeof rec.match === 'function')
|
|
29
|
+
return rec.match as ParamMatcher
|
|
30
|
+
if (typeof rec.default === 'function')
|
|
31
|
+
return rec.default as ParamMatcher
|
|
32
|
+
}
|
|
33
|
+
return undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Merges built-in matchers with app matchers listed in the build manifest. */
|
|
37
|
+
export function resolveParamMatchers(
|
|
38
|
+
manifestMatchers: Readonly<Record<string, string>> | undefined,
|
|
39
|
+
modules: Readonly<Record<string, unknown>>,
|
|
40
|
+
): ParamMatcherMap {
|
|
41
|
+
if (manifestMatchers === undefined)
|
|
42
|
+
return BUILTIN_PARAM_MATCHERS
|
|
43
|
+
const merged: Record<string, ParamMatcher> = { ...BUILTIN_PARAM_MATCHERS }
|
|
44
|
+
for (const [name, modKey] of Object.entries(manifestMatchers)) {
|
|
45
|
+
const fn = extractMatcherFn(modules[modKey])
|
|
46
|
+
if (fn !== undefined)
|
|
47
|
+
merged[name] = fn
|
|
48
|
+
}
|
|
49
|
+
return merged
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ParsedPatternSegment {
|
|
53
|
+
kind: 'static' | 'param' | 'optional' | 'catchall'
|
|
54
|
+
/** Exact literal for static, parameter name for param/optional/catchall. */
|
|
55
|
+
value: string
|
|
56
|
+
matcherName?: string | undefined
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function splitNameAndMatcher(spec: string, fallbackName?: string): { name: string, matcherName?: string | undefined } {
|
|
60
|
+
const eq = spec.indexOf('=')
|
|
61
|
+
if (eq === -1)
|
|
62
|
+
return { name: spec || fallbackName || '' }
|
|
63
|
+
const name = spec.slice(0, eq) || fallbackName || ''
|
|
64
|
+
const matcherName = spec.slice(eq + 1)
|
|
65
|
+
return matcherName.length > 0 ? { name, matcherName } : { name }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Parses one segment of a compiled route pattern (`about`, `:id`, `:id=integer`, `:lang?`, `:page=integer?`, `*rest`, `*path=slug`). */
|
|
69
|
+
export function parsePatternSegment(seg: string): ParsedPatternSegment {
|
|
70
|
+
if (seg.startsWith('*')) {
|
|
71
|
+
const { name, matcherName } = splitNameAndMatcher(seg.slice(1), 'rest')
|
|
72
|
+
return { kind: 'catchall', value: name, matcherName }
|
|
73
|
+
}
|
|
74
|
+
if (seg.startsWith(':')) {
|
|
75
|
+
const body = seg.slice(1)
|
|
76
|
+
const optional = body.endsWith('?')
|
|
77
|
+
const spec = optional ? body.slice(0, -1) : body
|
|
78
|
+
const { name, matcherName } = splitNameAndMatcher(spec)
|
|
79
|
+
return { kind: optional ? 'optional' : 'param', value: name, matcherName }
|
|
80
|
+
}
|
|
81
|
+
return { kind: 'static', value: seg }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Lists every param matcher reference in a compiled route pattern (e.g. `'/users/:id=integer'` -> `[{ param: 'id', matcher: 'integer' }]`). */
|
|
85
|
+
export function extractPatternMatchers(routePath: string): { param: string, matcher: string }[] {
|
|
86
|
+
const result: { param: string, matcher: string }[] = []
|
|
87
|
+
if (!routePath.includes('='))
|
|
88
|
+
return result
|
|
89
|
+
for (const seg of routePath.split('/')) {
|
|
90
|
+
if (seg === '')
|
|
91
|
+
continue
|
|
92
|
+
const parsed = parsePatternSegment(seg)
|
|
93
|
+
if (parsed.matcherName !== undefined)
|
|
94
|
+
result.push({ param: parsed.value, matcher: parsed.matcherName })
|
|
95
|
+
}
|
|
96
|
+
return result
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Lists optional parameter names in a compiled route pattern (e.g. `'/:lang?/about'` -> `['lang']`). */
|
|
100
|
+
export function extractOptionalParams(routePath: string): string[] {
|
|
101
|
+
const result: string[] = []
|
|
102
|
+
if (!routePath.includes('?'))
|
|
103
|
+
return result
|
|
104
|
+
for (const seg of routePath.split('/')) {
|
|
105
|
+
if (seg === '')
|
|
106
|
+
continue
|
|
107
|
+
const parsed = parsePatternSegment(seg)
|
|
108
|
+
if (parsed.kind === 'optional')
|
|
109
|
+
result.push(parsed.value)
|
|
110
|
+
}
|
|
111
|
+
return result
|
|
112
|
+
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import type { BuildManifest } from '../build/index'
|
|
4
4
|
import type { AppRuntimeContext } from '../plugins/context'
|
|
5
5
|
import type { PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerPluginAPI } from '../plugins/index'
|
|
6
|
+
import type { HealthCheckEntry } from './health'
|
|
6
7
|
import type { EmbeddedServerConfig, Middleware, RequestContext } from './http'
|
|
7
8
|
|
|
8
9
|
import type { TrustProxy } from './security'
|
|
@@ -10,6 +11,8 @@ import { runWithAppContext } from '../plugins/context'
|
|
|
10
11
|
import { enforceRequirements } from '../plugins/requires'
|
|
11
12
|
import { normalizeConsentConfig, registerConsentRoute } from './consent'
|
|
12
13
|
import { assertRateLimit, createRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
|
|
14
|
+
import type { RequestPath } from './request-path'
|
|
15
|
+
import type { RouteMatch } from './router'
|
|
13
16
|
import { Router } from './router'
|
|
14
17
|
|
|
15
18
|
export interface PluginRouteDef {
|
|
@@ -18,6 +21,8 @@ export interface PluginRouteDef {
|
|
|
18
21
|
csrf: boolean
|
|
19
22
|
trustedOrigins: Set<string> | undefined
|
|
20
23
|
trustProxy: TrustProxy
|
|
24
|
+
/** The catch-all takes an encoded separator for this method (`PluginRouteOptions.encodedSlashes`). */
|
|
25
|
+
encodedSlashes: boolean
|
|
21
26
|
}
|
|
22
27
|
|
|
23
28
|
interface ScopedMiddleware {
|
|
@@ -59,6 +64,14 @@ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string,
|
|
|
59
64
|
return normPath === normScope || normPath.startsWith(`${normScope}/`)
|
|
60
65
|
}
|
|
61
66
|
|
|
67
|
+
/** The methods of `match` that may answer `path`: for a path with an encoded separator, only those that set `encodedSlashes`; none left is no match. */
|
|
68
|
+
export function takesEncoded(match: RouteMatch<Map<string, PluginRouteDef>> | undefined, path: RequestPath): RouteMatch<Map<string, PluginRouteDef>> | undefined {
|
|
69
|
+
if (match === undefined || path.encoded === undefined || path.encoded.size === 0)
|
|
70
|
+
return match
|
|
71
|
+
const data = new Map([...match.data].filter(([, def]) => def.encodedSlashes))
|
|
72
|
+
return data.size === 0 ? undefined : { data, params: match.params }
|
|
73
|
+
}
|
|
74
|
+
|
|
62
75
|
export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
|
|
63
76
|
const allowed = new Set<string>()
|
|
64
77
|
for (const m of methods.keys()) {
|
|
@@ -71,11 +84,49 @@ export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRo
|
|
|
71
84
|
return [...allowed].join(', ')
|
|
72
85
|
}
|
|
73
86
|
|
|
87
|
+
function assertRouteFree(pluginName: string, upperMethod: string, normPath: string, byMethod: ReadonlyMap<string, PluginRouteDef>): void {
|
|
88
|
+
const directConflict = byMethod.get(upperMethod)
|
|
89
|
+
if (directConflict !== undefined)
|
|
90
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with "${directConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
91
|
+
if (upperMethod === 'ALL' && byMethod.size > 0) {
|
|
92
|
+
const [existingMethod, existingDef] = byMethod.entries().next().value!
|
|
93
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ALL ${normPath}, which collides with ${existingMethod} ${normPath} from "${existingDef.plugin}". Mount one of the plugins on a different path.`)
|
|
94
|
+
}
|
|
95
|
+
const allConflict = byMethod.get('ALL')
|
|
96
|
+
if (allConflict !== undefined)
|
|
97
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with ALL ${normPath} from "${allConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function createMiddlewareLookup(scopedMiddlewares: readonly ScopedMiddleware[]) {
|
|
101
|
+
const allMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
|
|
102
|
+
const hasPathScopedMiddlewares = scopedMiddlewares.some(m => !isKindScope(m.scope))
|
|
103
|
+
// With no path-scoped middleware the list depends on the kind alone, so it is worked out once per kind.
|
|
104
|
+
const byKind: Record<RequestKind, readonly Middleware[]> = {
|
|
105
|
+
prerendered: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'prerendered')).map(m => m.mw),
|
|
106
|
+
static: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'static')).map(m => m.mw),
|
|
107
|
+
dynamic: allMiddlewares,
|
|
108
|
+
}
|
|
109
|
+
const middlewaresFor = (path: string, kind: RequestKind = 'dynamic'): readonly Middleware[] => {
|
|
110
|
+
if (!hasPathScopedMiddlewares)
|
|
111
|
+
return byKind[kind]
|
|
112
|
+
return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, kind)).map(m => m.mw)
|
|
113
|
+
}
|
|
114
|
+
const middlewaresForPaths = (paths: readonly string[], kind: RequestKind = 'dynamic'): readonly Middleware[] => {
|
|
115
|
+
if (!hasPathScopedMiddlewares)
|
|
116
|
+
return byKind[kind]
|
|
117
|
+
return scopedMiddlewares
|
|
118
|
+
.filter(m => paths.some(path => middlewareAppliesToPath(m.scope, path, kind)))
|
|
119
|
+
.map(m => m.mw)
|
|
120
|
+
}
|
|
121
|
+
return { allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths }
|
|
122
|
+
}
|
|
123
|
+
|
|
74
124
|
export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
75
125
|
const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
|
|
76
126
|
// The counters of every limited route and action of this server, dropped with it.
|
|
77
127
|
const rateLimits = createRateLimitStore()
|
|
78
128
|
const scopedMiddlewares: ScopedMiddleware[] = []
|
|
129
|
+
const healthChecks: HealthCheckEntry[] = []
|
|
79
130
|
const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
|
|
80
131
|
const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
|
|
81
132
|
const router = new Router<Map<string, PluginRouteDef>>()
|
|
@@ -89,25 +140,20 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
|
89
140
|
): void => {
|
|
90
141
|
const upperMethod = method.toUpperCase()
|
|
91
142
|
const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
143
|
+
const encodedSlashes = routeOptions?.encodedSlashes === true
|
|
144
|
+
if (encodedSlashes && !normPath.split('/').some(seg => seg.startsWith('*')))
|
|
145
|
+
throw new Error(`prunelle: plugin "${pluginName}" set encodedSlashes on ${upperMethod} ${normPath}, which has no catch-all: only a \`*name\` segment takes an encoded /, so end the path with one, or drop the option.`)
|
|
92
146
|
let byMethod = routeEntries.get(normPath)
|
|
93
147
|
if (byMethod === undefined) {
|
|
94
148
|
byMethod = new Map()
|
|
95
149
|
routeEntries.set(normPath, byMethod)
|
|
96
|
-
router.add(normPath, byMethod)
|
|
150
|
+
router.add(normPath, byMethod, { encodedSlashes })
|
|
97
151
|
}
|
|
98
152
|
else {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
if (upperMethod === 'ALL' && byMethod.size > 0) {
|
|
104
|
-
const [existingMethod, existingDef] = byMethod.entries().next().value!
|
|
105
|
-
throw new Error(`prunelle: plugin "${pluginName}" registered ALL ${normPath}, which collides with ${existingMethod} ${normPath} from "${existingDef.plugin}". Mount one of the plugins on a different path.`)
|
|
106
|
-
}
|
|
107
|
-
const allConflict = byMethod.get('ALL')
|
|
108
|
-
if (allConflict !== undefined) {
|
|
109
|
-
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with ALL ${normPath} from "${allConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
110
|
-
}
|
|
153
|
+
assertRouteFree(pluginName, upperMethod, normPath, byMethod)
|
|
154
|
+
// The path matches encoded separators once any method takes them; takesEncoded still refuses them to the others.
|
|
155
|
+
if (encodedSlashes)
|
|
156
|
+
router.add(normPath, byMethod, { encodedSlashes })
|
|
111
157
|
}
|
|
112
158
|
let routeTrustedOrigins = trustedOrigins
|
|
113
159
|
if (routeOptions?.trustedOrigins !== undefined && routeOptions.trustedOrigins.length > 0) {
|
|
@@ -129,12 +175,25 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
|
129
175
|
csrf: routeOptions?.csrf ?? true,
|
|
130
176
|
trustedOrigins: routeTrustedOrigins,
|
|
131
177
|
trustProxy: routeOptions?.trustProxy ?? trustProxy,
|
|
178
|
+
encodedSlashes,
|
|
132
179
|
})
|
|
133
180
|
}
|
|
134
181
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
182
|
+
let disposed = false
|
|
183
|
+
async function dispose(): Promise<void> {
|
|
184
|
+
if (disposed)
|
|
185
|
+
return
|
|
186
|
+
disposed = true
|
|
187
|
+
rateLimits.close()
|
|
188
|
+
for (const { plugin, hook } of shutdownHooks) {
|
|
189
|
+
try {
|
|
190
|
+
await hook()
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
console.error(`prunelle: the onShutdown hook of ${plugin} threw; the other hooks still run.`, error)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
138
197
|
|
|
139
198
|
const {
|
|
140
199
|
manifest: _m,
|
|
@@ -148,83 +207,59 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
|
148
207
|
} = config as EmbeddedServerConfig & Record<string, unknown>
|
|
149
208
|
const readonlyRuntimeConfig: Readonly<Record<string, unknown>> = Object.freeze({ ...forwardedConfig })
|
|
150
209
|
|
|
151
|
-
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
for (const plugin of plugins) {
|
|
156
|
-
if (plugin.server !== undefined) {
|
|
157
|
-
const pluginApi: ServerPluginAPI = {
|
|
158
|
-
root: options.root,
|
|
159
|
-
outDir: options.outDir,
|
|
160
|
-
assetPrefix: options.assetPrefix,
|
|
161
|
-
site: options.site,
|
|
162
|
-
dev: options.dev,
|
|
163
|
-
trustProxy,
|
|
164
|
-
trustedOrigins: options.trustedOriginsList,
|
|
165
|
-
config: readonlyRuntimeConfig,
|
|
166
|
-
use(mw: Middleware, middlewareOptions?: MiddlewareOptions) {
|
|
167
|
-
scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
|
|
168
|
-
},
|
|
169
|
-
route: registerRouteFor(plugin.name),
|
|
170
|
-
rateLimiter(limit) {
|
|
171
|
-
assertRateLimit(limit, `the rateLimiter of "${plugin.name}"`)
|
|
172
|
-
return rateLimits.limiter(limit)
|
|
173
|
-
},
|
|
174
|
-
rewrite(fn) {
|
|
175
|
-
rewrites.push(fn)
|
|
176
|
-
},
|
|
177
|
-
provide: appCtx.provide,
|
|
178
|
-
inject: appCtx.inject,
|
|
179
|
-
getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
|
|
180
|
-
return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
|
|
181
|
-
},
|
|
182
|
-
onShutdown(fn) {
|
|
183
|
-
shutdownHooks.push({ plugin: plugin.name, hook: fn })
|
|
184
|
-
},
|
|
185
|
-
}
|
|
186
|
-
await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
const allMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
|
|
191
|
-
const hasPathScopedMiddlewares = scopedMiddlewares.some(m => !isKindScope(m.scope))
|
|
192
|
-
// With no path-scoped middleware the list depends on the kind alone, so it is worked out once per kind.
|
|
193
|
-
const byKind: Record<RequestKind, readonly Middleware[]> = {
|
|
194
|
-
prerendered: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'prerendered')).map(m => m.mw),
|
|
195
|
-
static: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'static')).map(m => m.mw),
|
|
196
|
-
dynamic: allMiddlewares,
|
|
197
|
-
}
|
|
198
|
-
const middlewaresFor = (path: string, kind: RequestKind = 'dynamic'): readonly Middleware[] => {
|
|
199
|
-
if (!hasPathScopedMiddlewares)
|
|
200
|
-
return byKind[kind]
|
|
201
|
-
return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, kind)).map(m => m.mw)
|
|
202
|
-
}
|
|
203
|
-
const middlewaresForPaths = (paths: readonly string[], kind: RequestKind = 'dynamic'): readonly Middleware[] => {
|
|
204
|
-
if (!hasPathScopedMiddlewares)
|
|
205
|
-
return byKind[kind]
|
|
206
|
-
return scopedMiddlewares
|
|
207
|
-
.filter(m => paths.some(path => middlewareAppliesToPath(m.scope, path, kind)))
|
|
208
|
-
.map(m => m.mw)
|
|
209
|
-
}
|
|
210
|
+
try {
|
|
211
|
+
const consentConfig = normalizeConsentConfig(config.consent)
|
|
212
|
+
if (consentConfig !== undefined)
|
|
213
|
+
registerConsentRoute(registerRouteFor('pru:consent'), consentConfig, trustedOrigins, trustProxy)
|
|
210
214
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
215
|
+
if (config.prerender !== true || config.static === true) {
|
|
216
|
+
const production = !options.dev && (appCtx.nodeEnv ?? process.env.NODE_ENV) === 'production'
|
|
217
|
+
await runWithAppContext(appCtx, () => enforceRequirements(plugins, { root: options.root, site: options.site }, production))
|
|
218
|
+
}
|
|
219
|
+
for (const plugin of plugins) {
|
|
220
|
+
if (plugin.server !== undefined) {
|
|
221
|
+
const pluginApi: ServerPluginAPI = {
|
|
222
|
+
root: options.root,
|
|
223
|
+
outDir: options.outDir,
|
|
224
|
+
assetPrefix: options.assetPrefix,
|
|
225
|
+
site: options.site,
|
|
226
|
+
dev: options.dev,
|
|
227
|
+
trustProxy,
|
|
228
|
+
trustedOrigins: options.trustedOriginsList,
|
|
229
|
+
config: readonlyRuntimeConfig,
|
|
230
|
+
use(mw: Middleware, middlewareOptions?: MiddlewareOptions) {
|
|
231
|
+
scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
|
|
232
|
+
},
|
|
233
|
+
route: registerRouteFor(plugin.name),
|
|
234
|
+
rateLimiter(limit) {
|
|
235
|
+
assertRateLimit(limit, `the rateLimiter of "${plugin.name}"`)
|
|
236
|
+
return rateLimits.limiter(limit)
|
|
237
|
+
},
|
|
238
|
+
rewrite(fn) {
|
|
239
|
+
rewrites.push(fn)
|
|
240
|
+
},
|
|
241
|
+
provide: appCtx.provide,
|
|
242
|
+
inject: appCtx.inject,
|
|
243
|
+
getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
|
|
244
|
+
return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
|
|
245
|
+
},
|
|
246
|
+
healthCheck(name, fn) {
|
|
247
|
+
healthChecks.push({ name, fn })
|
|
248
|
+
},
|
|
249
|
+
onShutdown(fn) {
|
|
250
|
+
shutdownHooks.push({ plugin: plugin.name, hook: fn })
|
|
251
|
+
},
|
|
252
|
+
}
|
|
253
|
+
await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
|
|
223
254
|
}
|
|
224
255
|
}
|
|
225
256
|
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
await dispose()
|
|
259
|
+
throw error
|
|
260
|
+
}
|
|
226
261
|
|
|
227
|
-
return { router, rewrites,
|
|
262
|
+
return { router, rewrites, healthChecks, ...createMiddlewareLookup(scopedMiddlewares), rateLimits, dispose }
|
|
228
263
|
}
|
|
229
264
|
|
|
230
265
|
export type ServerPluginHost = Awaited<ReturnType<typeof createServerPluginHost>>
|
package/src/server/public.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// `prunelle/server`: what an app's routes, actions and middleware use, and `createServer` to run a built app inside another program. Anything not listed here stays internal.
|
|
2
2
|
|
|
3
3
|
export { action, getActionError } from './action'
|
|
4
|
-
export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
|
|
4
|
+
export type { ActionContext, ActionErrorFlash, ActionOptions, ActionProtectOptions, ActionResult, ServerAction } from './action'
|
|
5
5
|
export type { ConsentConfig, RequestConsent } from './consent'
|
|
6
6
|
export type { CookieOptions, Cookies } from './cookies'
|
|
7
7
|
export { defineEnv, nodeEnv } from './env'
|
|
@@ -12,8 +12,8 @@ export { createServer } from './loader'
|
|
|
12
12
|
export { createRateLimitStore } from './rate-limit'
|
|
13
13
|
export type { RateLimit, RateLimiter, RateLimitStore, RateLimitStoreOptions } from './rate-limit'
|
|
14
14
|
export { readStringFields } from './request-body'
|
|
15
|
-
export { getClientIp, isHttpsRequest, isTrustedOrigin, safeEqual, safeRedirect, verifyOrigin } from './security'
|
|
16
|
-
export type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
15
|
+
export { DEFAULT_CSP, extendCsp, getClientIp, isHttpsRequest, isTrustedOrigin, safeEqual, safeRedirect, verifyOrigin } from './security'
|
|
16
|
+
export type { CspDirectives, SecurityHeadersOptions, TrustProxy } from './security'
|
|
17
17
|
export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
|
|
18
18
|
export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
|
|
19
19
|
export { esc, escAttr, escJson, raw } from '../ssr/index'
|
package/src/server/rate-limit.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// How often a client may call a plugin route or an action: a sliding window per key, in one store per server bounded in keys and hits.
|
|
2
2
|
|
|
3
|
+
import { nodeEnv } from './env'
|
|
4
|
+
|
|
3
5
|
export interface RateLimit<Ctx extends { ip?: string | undefined } = { ip?: string | undefined }> {
|
|
4
6
|
/** Requests a key may make per window. */
|
|
5
7
|
max: number
|
|
@@ -31,9 +33,10 @@ export interface RateLimitStoreOptions {
|
|
|
31
33
|
maxHits?: number | undefined
|
|
32
34
|
}
|
|
33
35
|
|
|
34
|
-
interface
|
|
35
|
-
|
|
36
|
-
windowMs: number
|
|
36
|
+
interface Bucket {
|
|
37
|
+
readonly entries: Map<string, number[]>
|
|
38
|
+
readonly windowMs: number
|
|
39
|
+
hitCount: number
|
|
37
40
|
}
|
|
38
41
|
|
|
39
42
|
const SWEEP_MS = 60_000
|
|
@@ -49,47 +52,51 @@ export function assertRateLimit(limit: Pick<RateLimit, 'max' | 'windowMs'>, wher
|
|
|
49
52
|
export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateLimitStore {
|
|
50
53
|
const maxKeys = Math.max(1, options.maxKeys ?? 10_000)
|
|
51
54
|
const maxHits = Math.max(1, options.maxHits ?? 1_000_000)
|
|
52
|
-
//
|
|
53
|
-
const
|
|
54
|
-
let
|
|
55
|
-
let nextId = 0
|
|
55
|
+
// Each limiter owns a bounded LRU map so flooding one endpoint cannot evict keys from another.
|
|
56
|
+
const buckets: Bucket[] = []
|
|
57
|
+
let totalKeys = 0
|
|
56
58
|
let timer: ReturnType<typeof setInterval> | undefined
|
|
57
59
|
|
|
58
|
-
function trim(
|
|
59
|
-
const cutoff = now -
|
|
60
|
+
function trim(bucket: Bucket, hits: number[], now: number): void {
|
|
61
|
+
const cutoff = now - bucket.windowMs
|
|
60
62
|
let stale = 0
|
|
61
|
-
while (stale <
|
|
63
|
+
while (stale < hits.length && hits[stale]! <= cutoff)
|
|
62
64
|
stale++
|
|
63
65
|
if (stale > 0) {
|
|
64
|
-
|
|
65
|
-
hitCount -= stale
|
|
66
|
+
hits.splice(0, stale)
|
|
67
|
+
bucket.hitCount -= stale
|
|
66
68
|
}
|
|
67
69
|
}
|
|
68
70
|
|
|
69
71
|
function sweep(now = Date.now()): number {
|
|
70
72
|
let removed = 0
|
|
71
|
-
for (const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
73
|
+
for (const bucket of buckets) {
|
|
74
|
+
for (const [key, hits] of bucket.entries) {
|
|
75
|
+
trim(bucket, hits, now)
|
|
76
|
+
if (hits.length === 0) {
|
|
77
|
+
bucket.entries.delete(key)
|
|
78
|
+
totalKeys--
|
|
79
|
+
removed++
|
|
80
|
+
}
|
|
76
81
|
}
|
|
77
82
|
}
|
|
78
83
|
return removed
|
|
79
84
|
}
|
|
80
85
|
|
|
81
|
-
function evict(): void {
|
|
82
|
-
while (entries.size > maxKeys || hitCount > maxHits) {
|
|
83
|
-
const [key,
|
|
84
|
-
entries.delete(key)
|
|
85
|
-
hitCount -=
|
|
86
|
+
function evict(bucket: Bucket): void {
|
|
87
|
+
while (bucket.entries.size > maxKeys || bucket.hitCount > maxHits) {
|
|
88
|
+
const [key, hits] = bucket.entries.entries().next().value!
|
|
89
|
+
bucket.entries.delete(key)
|
|
90
|
+
bucket.hitCount -= hits.length
|
|
91
|
+
totalKeys--
|
|
86
92
|
}
|
|
87
93
|
}
|
|
88
94
|
|
|
89
95
|
return {
|
|
90
96
|
limiter(limit) {
|
|
91
97
|
const { max, windowMs } = limit
|
|
92
|
-
const
|
|
98
|
+
const bucket: Bucket = { entries: new Map(), windowMs, hitCount: 0 }
|
|
99
|
+
buckets.push(bucket)
|
|
93
100
|
if (timer === undefined) {
|
|
94
101
|
timer = setInterval(sweep, SWEEP_MS)
|
|
95
102
|
timer.unref()
|
|
@@ -97,23 +104,28 @@ export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateL
|
|
|
97
104
|
return {
|
|
98
105
|
hit(key) {
|
|
99
106
|
const now = Date.now()
|
|
100
|
-
const
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
107
|
+
const existing = bucket.entries.get(key)
|
|
108
|
+
const hits = existing ?? []
|
|
109
|
+
if (existing !== undefined) {
|
|
110
|
+
trim(bucket, hits, now)
|
|
111
|
+
bucket.entries.delete(key)
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
totalKeys++
|
|
115
|
+
}
|
|
116
|
+
bucket.entries.set(key, hits)
|
|
117
|
+
if (hits.length >= max)
|
|
118
|
+
return Math.max(1, Math.ceil((hits[hits.length - max]! + windowMs - now) / 1000))
|
|
119
|
+
hits.push(now)
|
|
120
|
+
bucket.hitCount++
|
|
121
|
+
evict(bucket)
|
|
110
122
|
return 0
|
|
111
123
|
},
|
|
112
124
|
}
|
|
113
125
|
},
|
|
114
126
|
sweep,
|
|
115
127
|
get size() {
|
|
116
|
-
return
|
|
128
|
+
return totalKeys
|
|
117
129
|
},
|
|
118
130
|
close() {
|
|
119
131
|
clearInterval(timer)
|
|
@@ -127,7 +139,18 @@ export function tooManyRequests(retryAfter: number): Response {
|
|
|
127
139
|
return Response.json({ ok: false, status: 429, error: 'Too many requests' }, { status: 429, headers: { 'retry-after': String(retryAfter) } })
|
|
128
140
|
}
|
|
129
141
|
|
|
142
|
+
let warnedMissingIp = false
|
|
143
|
+
|
|
130
144
|
/** Counts `ctx` against `limiter` by the limit's key, else the client address; returns 0 or the seconds to wait. */
|
|
131
145
|
export function hitFor<Ctx extends { ip?: string | undefined }>(limiter: RateLimiter, limit: RateLimit<Ctx>, ctx: Ctx): number {
|
|
132
|
-
|
|
146
|
+
const custom = limit.key?.(ctx)
|
|
147
|
+
if (custom !== undefined)
|
|
148
|
+
return limiter.hit(`k:${custom}`)
|
|
149
|
+
if (ctx.ip !== undefined && ctx.ip !== '')
|
|
150
|
+
return limiter.hit(`ip:${ctx.ip}`)
|
|
151
|
+
if (!warnedMissingIp && nodeEnv() === 'production') {
|
|
152
|
+
warnedMissingIp = true
|
|
153
|
+
console.warn('prunelle: rateLimit ran with no client IP (ctx.ip is undefined); configure trustProxy in prunelle.config.ts or pass remoteIp to app.handle() so callers do not share one fallback bucket.')
|
|
154
|
+
}
|
|
155
|
+
return limiter.hit('ip:unknown')
|
|
133
156
|
}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export async function readStringFields(request: Request): Promise<Record<string, string>> {
|
|
9
9
|
const fields: Record<string, string> = Object.create(null)
|
|
10
|
-
const contentType = request.headers.get('content-type') ?? ''
|
|
10
|
+
const contentType = (request.headers.get('content-type') ?? '').toLowerCase()
|
|
11
11
|
if (contentType.includes('application/json')) {
|
|
12
12
|
const raw: unknown = await request.json()
|
|
13
13
|
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|