prunelle 0.1.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +52 -5
- package/src/cli/commands.ts +86 -4
- package/src/cli/docs.ts +402 -0
- package/src/cli/inspect.ts +31 -2
- package/src/cli/mcp-tools.ts +480 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +2 -2
- package/src/cli/render.ts +261 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +137 -16
- package/src/compiler/analyze.ts +20 -6
- package/src/compiler/cacheability.ts +592 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +120 -221
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +12 -11
- package/src/compiler/expr-context.ts +167 -57
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +56 -17
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +216 -84
- 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 +4 -1
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +2 -2
- package/src/dom/island.ts +11 -10
- package/src/plugins/config.ts +4 -4
- package/src/plugins/index.ts +2 -2
- package/src/plugins/public.ts +5 -2
- package/src/plugins/services.ts +62 -0
- package/src/plugins/types.ts +32 -0
- 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/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 +120 -1
- package/src/ssr/region.ts +31 -19
- package/src/test/browser.ts +6 -0
- package/src/test/index.ts +17 -3
- package/src/ts-plugin/diagnostics.ts +378 -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
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// Built-in spam & abuse protection for public server actions: honeypot field + HMAC-signed render timestamp.
|
|
2
|
+
|
|
3
|
+
import type { ActionContext } from './action'
|
|
4
|
+
import type { RateLimit } from './rate-limit'
|
|
5
|
+
import { nodeEnv } from './env'
|
|
6
|
+
import { assertRateLimit } from './rate-limit'
|
|
7
|
+
|
|
8
|
+
function constantTimeEqual(a: string, b: string): boolean {
|
|
9
|
+
const x = new Bun.CryptoHasher('sha256').update(a).digest()
|
|
10
|
+
const y = new Bun.CryptoHasher('sha256').update(b).digest()
|
|
11
|
+
let diff = 0
|
|
12
|
+
for (let i = 0; i < x.length; i++)
|
|
13
|
+
diff |= x[i]! ^ y[i]!
|
|
14
|
+
return diff === 0
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_HONEYPOT_FIELD = '_pru_hp'
|
|
18
|
+
export const FORM_TIMESTAMP_FIELD = '_pru_ts'
|
|
19
|
+
export const MAX_FORM_AGE_MS = 24 * 60 * 60 * 1000
|
|
20
|
+
|
|
21
|
+
export interface ActionProtectOptions {
|
|
22
|
+
/** Sliding-window rate limit for submissions to this action. */
|
|
23
|
+
rateLimit?: RateLimit<ActionContext> | undefined
|
|
24
|
+
/** Hidden trap input name (`true` uses `_pru_hp`, or pass a custom field name). Non-empty values are rejected. */
|
|
25
|
+
honeypot?: boolean | string | undefined
|
|
26
|
+
/** Minimum elapsed milliseconds between SSR render and submit; enforced with an HMAC-signed `_pru_ts` token. */
|
|
27
|
+
minTime?: number | undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const EPHEMERAL_SECRET_KEY = Symbol.for('pru.form.secret')
|
|
31
|
+
const DIGITS_RE = /^\d+$/
|
|
32
|
+
let warnedEphemeralSecret = false
|
|
33
|
+
|
|
34
|
+
function formSecret(): string {
|
|
35
|
+
const configured = process.env.PRUNELLE_FORM_SECRET || process.env.AUTH_SECRET
|
|
36
|
+
if (configured)
|
|
37
|
+
return configured
|
|
38
|
+
if (!warnedEphemeralSecret && nodeEnv() === 'production') {
|
|
39
|
+
warnedEphemeralSecret = true
|
|
40
|
+
console.warn('prunelle: protect.minTime is using an ephemeral form secret because PRUNELLE_FORM_SECRET and AUTH_SECRET are unset; set PRUNELLE_FORM_SECRET in production so signed form timestamps survive restarts and work across instances.')
|
|
41
|
+
}
|
|
42
|
+
const g = globalThis as Record<symbol, string | undefined>
|
|
43
|
+
let secret = g[EPHEMERAL_SECRET_KEY]
|
|
44
|
+
if (secret === undefined) {
|
|
45
|
+
const bytes = new Uint8Array(32)
|
|
46
|
+
crypto.getRandomValues(bytes)
|
|
47
|
+
secret = Buffer.from(bytes).toString('hex')
|
|
48
|
+
g[EPHEMERAL_SECRET_KEY] = secret
|
|
49
|
+
}
|
|
50
|
+
return secret
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function timestampPayload(ts: string, actionUrl: string): string {
|
|
54
|
+
return actionUrl !== '' ? `${ts}\0${actionUrl}` : ts
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function escapeAttrValue(value: string): string {
|
|
58
|
+
return value.replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<').replaceAll('>', '>')
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Returns the configured honeypot field name, or `undefined` when honeypot is disabled. */
|
|
62
|
+
export function honeypotFieldName(protect: ActionProtectOptions | undefined): string | undefined {
|
|
63
|
+
if (protect?.honeypot === true)
|
|
64
|
+
return DEFAULT_HONEYPOT_FIELD
|
|
65
|
+
if (typeof protect?.honeypot === 'string') {
|
|
66
|
+
const trimmed = protect.honeypot.trim()
|
|
67
|
+
return trimmed !== '' ? trimmed : undefined
|
|
68
|
+
}
|
|
69
|
+
return undefined
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Whether `protect` requires reading the request body (honeypot or minTime). */
|
|
73
|
+
export function needsProtectBody(protect: ActionProtectOptions | undefined): boolean {
|
|
74
|
+
return honeypotFieldName(protect) !== undefined || protect?.minTime !== undefined
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Validates `ActionProtectOptions` eagerly when `action()` is defined. */
|
|
78
|
+
export function assertActionProtect(protect: ActionProtectOptions): void {
|
|
79
|
+
if (protect.rateLimit !== undefined)
|
|
80
|
+
assertRateLimit(protect.rateLimit, 'an action')
|
|
81
|
+
if (protect.minTime !== undefined && (!Number.isFinite(protect.minTime) || protect.minTime < 0))
|
|
82
|
+
throw new Error(`prunelle: protect.minTime of an action is ${String(protect.minTime)}; give a non-negative number of milliseconds.`)
|
|
83
|
+
if (typeof protect.honeypot === 'string' && protect.honeypot.trim() === '')
|
|
84
|
+
throw new Error('prunelle: protect.honeypot of an action must be a non-empty field name.')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Creates an HMAC-SHA256 signed timestamp token (`<timestampMs>.<signatureHex>`), optionally bound to `actionUrl`. */
|
|
88
|
+
export function signFormTimestamp(timestampMs = Date.now(), actionUrl = ''): string {
|
|
89
|
+
const ts = String(Math.trunc(timestampMs))
|
|
90
|
+
const sig = new Bun.CryptoHasher('sha256', formSecret()).update(timestampPayload(ts, actionUrl)).digest('hex')
|
|
91
|
+
return `${ts}.${sig}`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Verifies an HMAC-signed `_pru_ts` token against `minTimeMs`, the 24-hour expiry window, and optional `actionUrl`. */
|
|
95
|
+
export function verifyFormTimestamp(
|
|
96
|
+
token: unknown,
|
|
97
|
+
minTimeMs: number,
|
|
98
|
+
now = Date.now(),
|
|
99
|
+
actionUrl = '',
|
|
100
|
+
): { ok: true } | { ok: false, reason: string } {
|
|
101
|
+
if (typeof token !== 'string')
|
|
102
|
+
return { ok: false, reason: 'Missing form timestamp' }
|
|
103
|
+
const dot = token.indexOf('.')
|
|
104
|
+
if (dot <= 0 || dot === token.length - 1)
|
|
105
|
+
return { ok: false, reason: 'Invalid form timestamp' }
|
|
106
|
+
const tsStr = token.slice(0, dot)
|
|
107
|
+
const sig = token.slice(dot + 1)
|
|
108
|
+
if (!DIGITS_RE.test(tsStr))
|
|
109
|
+
return { ok: false, reason: 'Invalid form timestamp' }
|
|
110
|
+
const expected = new Bun.CryptoHasher('sha256', formSecret()).update(timestampPayload(tsStr, actionUrl)).digest('hex')
|
|
111
|
+
if (!constantTimeEqual(sig, expected))
|
|
112
|
+
return { ok: false, reason: 'Invalid form timestamp' }
|
|
113
|
+
const ts = Number(tsStr)
|
|
114
|
+
if (!Number.isFinite(ts))
|
|
115
|
+
return { ok: false, reason: 'Invalid form timestamp' }
|
|
116
|
+
const elapsed = now - ts
|
|
117
|
+
if (elapsed < minTimeMs)
|
|
118
|
+
return { ok: false, reason: 'Form submitted too quickly' }
|
|
119
|
+
if (elapsed > MAX_FORM_AGE_MS)
|
|
120
|
+
return { ok: false, reason: 'Form submission expired' }
|
|
121
|
+
return { ok: true }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function isNonEmptyFieldValue(value: unknown): boolean {
|
|
125
|
+
if (Array.isArray(value))
|
|
126
|
+
return value.some(v => v !== '' && v != null)
|
|
127
|
+
return value !== '' && value != null
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Returns a shallow copy of `rawBody` with internal Prunelle protection fields removed. */
|
|
131
|
+
export function stripProtectFields(protect: ActionProtectOptions | undefined, rawBody: unknown): unknown {
|
|
132
|
+
if (protect === undefined || rawBody === null || typeof rawBody !== 'object' || Array.isArray(rawBody))
|
|
133
|
+
return rawBody
|
|
134
|
+
const hpField = honeypotFieldName(protect)
|
|
135
|
+
const hasMinTime = protect.minTime !== undefined
|
|
136
|
+
if (hpField === undefined && !hasMinTime)
|
|
137
|
+
return rawBody
|
|
138
|
+
const obj = rawBody as Record<string, unknown>
|
|
139
|
+
const dropHp = hpField !== undefined && Object.hasOwn(obj, hpField)
|
|
140
|
+
const dropTs = hasMinTime && Object.hasOwn(obj, FORM_TIMESTAMP_FIELD)
|
|
141
|
+
if (!dropHp && !dropTs)
|
|
142
|
+
return rawBody
|
|
143
|
+
const entries: [string, unknown][] = []
|
|
144
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
145
|
+
if ((dropHp && k === hpField) || (dropTs && k === FORM_TIMESTAMP_FIELD))
|
|
146
|
+
continue
|
|
147
|
+
entries.push([k, v])
|
|
148
|
+
}
|
|
149
|
+
return Object.fromEntries(entries)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Verifies honeypot and signed timestamp protections and returns the body with internal fields stripped. */
|
|
153
|
+
export function verifyActionProtection(
|
|
154
|
+
protect: ActionProtectOptions | undefined,
|
|
155
|
+
rawBody: unknown,
|
|
156
|
+
now = Date.now(),
|
|
157
|
+
actionUrl = '',
|
|
158
|
+
): { ok: true, cleanedBody: unknown } | { ok: false, error: string, cleanedBody: unknown } {
|
|
159
|
+
if (protect === undefined)
|
|
160
|
+
return { ok: true, cleanedBody: rawBody }
|
|
161
|
+
const hpField = honeypotFieldName(protect)
|
|
162
|
+
const minTime = protect.minTime
|
|
163
|
+
if (hpField === undefined && minTime === undefined)
|
|
164
|
+
return { ok: true, cleanedBody: rawBody }
|
|
165
|
+
|
|
166
|
+
const cleanedBody = stripProtectFields(protect, rawBody)
|
|
167
|
+
const obj = rawBody !== null && typeof rawBody === 'object' && !Array.isArray(rawBody)
|
|
168
|
+
? rawBody as Record<string, unknown>
|
|
169
|
+
: undefined
|
|
170
|
+
|
|
171
|
+
if (hpField !== undefined && obj !== undefined && Object.hasOwn(obj, hpField)) {
|
|
172
|
+
if (isNonEmptyFieldValue(obj[hpField]))
|
|
173
|
+
return { ok: false, error: 'Submission rejected', cleanedBody }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (minTime !== undefined) {
|
|
177
|
+
const rawTs = obj !== undefined && Object.hasOwn(obj, FORM_TIMESTAMP_FIELD) ? obj[FORM_TIMESTAMP_FIELD] : undefined
|
|
178
|
+
const token = Array.isArray(rawTs) ? rawTs[0] : rawTs
|
|
179
|
+
const tsResult = verifyFormTimestamp(token, minTime, now, actionUrl)
|
|
180
|
+
if (!tsResult.ok)
|
|
181
|
+
return { ok: false, error: tsResult.reason, cleanedBody }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return { ok: true, cleanedBody }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Renders the SSR hidden protection inputs (visually hidden honeypot + signed timestamp) for `<form action={fn}>`. */
|
|
188
|
+
export function renderProtectFields(protect: ActionProtectOptions | undefined, actionUrl = ''): string {
|
|
189
|
+
if (protect === undefined)
|
|
190
|
+
return ''
|
|
191
|
+
let html = ''
|
|
192
|
+
const hp = honeypotFieldName(protect)
|
|
193
|
+
if (hp !== undefined)
|
|
194
|
+
html += `<input type="text" name="${escapeAttrValue(hp)}" value="" tabindex="-1" autocomplete="off" aria-hidden="true" style="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden">`
|
|
195
|
+
if (protect.minTime !== undefined)
|
|
196
|
+
html += `<input type="hidden" name="${FORM_TIMESTAMP_FIELD}" value="${signFormTimestamp(undefined, actionUrl)}">`
|
|
197
|
+
return html
|
|
198
|
+
}
|
|
@@ -39,7 +39,7 @@ export function createActionRegistry(): ActionRegistry {
|
|
|
39
39
|
if (actionResult !== undefined)
|
|
40
40
|
return actionResult
|
|
41
41
|
// A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
|
|
42
|
-
const ct = res.headers.get('content-type') ?? ''
|
|
42
|
+
const ct = (res.headers.get('content-type') ?? '').toLowerCase()
|
|
43
43
|
if (ct.includes('application/json')) {
|
|
44
44
|
try {
|
|
45
45
|
const body = await res.clone().json() as Record<string, unknown>
|
package/src/server/action.ts
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
// Unified server actions: works as both progressive <form action={fn} method="post"> and typed island RPC.
|
|
2
2
|
|
|
3
|
+
import type { ActionProtectOptions } from './action-protect'
|
|
3
4
|
import type { Cookies } from './cookies'
|
|
4
5
|
import type { PrunelleLocals } from './index'
|
|
5
6
|
import type { RateLimit, RateLimiter } from './rate-limit'
|
|
6
7
|
import type { TrustProxy } from './security'
|
|
7
8
|
import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
|
|
9
|
+
import { assertActionProtect, needsProtectBody, verifyActionProtection } from './action-protect'
|
|
8
10
|
import { wantsJson } from './http'
|
|
9
11
|
import { assertRateLimit, hitFor, tooManyRequests } from './rate-limit'
|
|
10
12
|
import { currentRequest } from './request-scope'
|
|
11
13
|
import { isTrustedOrigin } from './security'
|
|
12
14
|
import { validateSchema } from './standard-schema'
|
|
13
15
|
|
|
16
|
+
export type { ActionProtectOptions } from './action-protect'
|
|
17
|
+
|
|
14
18
|
declare module './index' {
|
|
15
19
|
interface PrunelleLocals {
|
|
16
20
|
actionError?: ActionErrorFlash | undefined
|
|
@@ -36,15 +40,47 @@ function isSensitiveField(name: string): boolean {
|
|
|
36
40
|
return SENSITIVE_SUBSTRING_RE.test(normalized) || SENSITIVE_TOKEN_RE.test(normalized)
|
|
37
41
|
}
|
|
38
42
|
|
|
43
|
+
function parseStringRecord(raw: unknown): Record<string, string> | undefined {
|
|
44
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
45
|
+
return undefined
|
|
46
|
+
const out: Record<string, string> = Object.create(null)
|
|
47
|
+
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
|
|
48
|
+
if (typeof v !== 'string')
|
|
49
|
+
return undefined
|
|
50
|
+
out[k] = v
|
|
51
|
+
}
|
|
52
|
+
return out
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function parseActionErrorFlash(raw: unknown): ActionErrorFlash | undefined {
|
|
56
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
57
|
+
return undefined
|
|
58
|
+
const rec = raw as Record<string, unknown>
|
|
59
|
+
if (typeof rec.action !== 'string' || typeof rec.error !== 'string')
|
|
60
|
+
return undefined
|
|
61
|
+
const fieldErrors = rec.fieldErrors === undefined ? undefined : parseStringRecord(rec.fieldErrors)
|
|
62
|
+
if (rec.fieldErrors !== undefined && fieldErrors === undefined)
|
|
63
|
+
return undefined
|
|
64
|
+
const values = rec.values === undefined ? undefined : parseStringRecord(rec.values)
|
|
65
|
+
if (rec.values !== undefined && values === undefined)
|
|
66
|
+
return undefined
|
|
67
|
+
return {
|
|
68
|
+
action: rec.action,
|
|
69
|
+
error: rec.error,
|
|
70
|
+
...(fieldErrors !== undefined ? { fieldErrors } : {}),
|
|
71
|
+
...(values !== undefined ? { values } : {}),
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
39
75
|
/** Hydrates `ctx.locals.actionError` from `__pru_action_err` without clearing the cookie yet; returns true when the cookie was present. */
|
|
40
76
|
export function hydrateActionErrorFlash(ctx: Pick<ActionContext, 'cookies' | 'locals'>): boolean {
|
|
41
77
|
const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
|
|
42
78
|
if (rawFlash === undefined)
|
|
43
79
|
return false
|
|
44
80
|
try {
|
|
45
|
-
const parsed
|
|
46
|
-
if (
|
|
47
|
-
ctx.locals.actionError = parsed
|
|
81
|
+
const parsed = parseActionErrorFlash(JSON.parse(rawFlash))
|
|
82
|
+
if (parsed !== undefined)
|
|
83
|
+
ctx.locals.actionError = parsed
|
|
48
84
|
}
|
|
49
85
|
catch {}
|
|
50
86
|
return true
|
|
@@ -69,6 +105,8 @@ export interface ActionOptions {
|
|
|
69
105
|
flashFields?: readonly string[] | undefined
|
|
70
106
|
/** How often one client may submit it: past `max` per `windowMs`, a call from script gets a 429 with `Retry-After` and a form comes back with the error. */
|
|
71
107
|
rateLimit?: RateLimit<ActionContext> | undefined
|
|
108
|
+
/** Public form spam & abuse protection: rate limit, hidden honeypot field, and minimum render-to-submit time. */
|
|
109
|
+
protect?: ActionProtectOptions | undefined
|
|
72
110
|
}
|
|
73
111
|
|
|
74
112
|
export interface ActionErrorFlash {
|
|
@@ -103,6 +141,7 @@ export interface ServerAction<Input, Output> {
|
|
|
103
141
|
readonly schema: StandardSchemaV1 | undefined
|
|
104
142
|
readonly flashFields: readonly string[] | undefined
|
|
105
143
|
readonly rateLimit: RateLimit<ActionContext> | undefined
|
|
144
|
+
readonly protect: ActionProtectOptions | undefined
|
|
106
145
|
readonly handler: (input: never, ctx: ActionContext) => Output | Response | Promise<Output | Response>
|
|
107
146
|
toString(): string
|
|
108
147
|
}
|
|
@@ -132,8 +171,11 @@ export function action(
|
|
|
132
171
|
? (maybeHandlerOrOpts as (input: never, ctx: ActionContext) => unknown)
|
|
133
172
|
: ((_input: never, ctx: ActionContext) => (schemaOrHandler as (c: ActionContext) => unknown)(ctx))
|
|
134
173
|
const options = hasSchema ? maybeOpts : (maybeHandlerOrOpts as ActionOptions | undefined)
|
|
135
|
-
if (options?.
|
|
136
|
-
|
|
174
|
+
if (options?.protect !== undefined)
|
|
175
|
+
assertActionProtect(options.protect)
|
|
176
|
+
const effectiveRateLimit = options?.protect?.rateLimit ?? options?.rateLimit
|
|
177
|
+
if (effectiveRateLimit !== undefined && options?.protect?.rateLimit === undefined)
|
|
178
|
+
assertRateLimit(effectiveRateLimit, 'an action')
|
|
137
179
|
|
|
138
180
|
const fn = (async (input: unknown) => {
|
|
139
181
|
const scope = currentRequest()
|
|
@@ -148,7 +190,8 @@ export function action(
|
|
|
148
190
|
__pruAction: { value: true, enumerable: false },
|
|
149
191
|
schema: { value: schema, enumerable: false },
|
|
150
192
|
flashFields: { value: options?.flashFields, enumerable: false },
|
|
151
|
-
rateLimit: { value:
|
|
193
|
+
rateLimit: { value: effectiveRateLimit, enumerable: false },
|
|
194
|
+
protect: { value: options?.protect, enumerable: false },
|
|
152
195
|
handler: { value: handler, enumerable: false },
|
|
153
196
|
url: { value: '', writable: true, enumerable: true },
|
|
154
197
|
toString: {
|
|
@@ -167,7 +210,7 @@ export function isServerAction(value: unknown): value is ServerAction<unknown, u
|
|
|
167
210
|
}
|
|
168
211
|
|
|
169
212
|
async function parseActionBody(boundedReq: Request): Promise<unknown> {
|
|
170
|
-
const contentType = boundedReq.headers.get('content-type') ?? ''
|
|
213
|
+
const contentType = (boundedReq.headers.get('content-type') ?? '').toLowerCase()
|
|
171
214
|
if (contentType.includes('application/json'))
|
|
172
215
|
return boundedReq.json()
|
|
173
216
|
|
|
@@ -193,7 +236,7 @@ async function parseActionBody(boundedReq: Request): Promise<unknown> {
|
|
|
193
236
|
}
|
|
194
237
|
|
|
195
238
|
function isJsonBody(request: Request): boolean {
|
|
196
|
-
return (request.headers.get('content-type') ?? '').includes('application/json')
|
|
239
|
+
return (request.headers.get('content-type') ?? '').toLowerCase().includes('application/json')
|
|
197
240
|
}
|
|
198
241
|
|
|
199
242
|
// The page a form came from, when its origin is one this server trusts: where a no-JS submit goes back to.
|
|
@@ -295,7 +338,7 @@ function buildActionErrorFlash(
|
|
|
295
338
|
error: trimmedError,
|
|
296
339
|
}
|
|
297
340
|
if (fieldErrors !== undefined) {
|
|
298
|
-
const safeErrors: Record<string, string> =
|
|
341
|
+
const safeErrors: Record<string, string> = Object.create(null)
|
|
299
342
|
base.fieldErrors = safeErrors
|
|
300
343
|
for (const [k, msg] of Object.entries(fieldErrors)) {
|
|
301
344
|
const trimmed = msg.length > 256 ? msg.slice(0, 256) : msg
|
|
@@ -308,7 +351,7 @@ function buildActionErrorFlash(
|
|
|
308
351
|
}
|
|
309
352
|
|
|
310
353
|
const allowSet = flashFields !== undefined ? new Set(flashFields) : undefined
|
|
311
|
-
const values: Record<string, string> =
|
|
354
|
+
const values: Record<string, string> = Object.create(null)
|
|
312
355
|
if (rawBody !== null && typeof rawBody === 'object') {
|
|
313
356
|
for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
|
|
314
357
|
if (typeof v !== 'string' || v.length > MAX_FLASH_FIELD_CHARS)
|
|
@@ -362,7 +405,7 @@ export async function invokeActionCore<I, O>(
|
|
|
362
405
|
if (result.status >= 300 && result.status < 400)
|
|
363
406
|
return { ok: true, data: result as unknown as O }
|
|
364
407
|
const ok = result.status >= 200 && result.status < 300
|
|
365
|
-
const ct = result.headers.get('content-type') ?? ''
|
|
408
|
+
const ct = (result.headers.get('content-type') ?? '').toLowerCase()
|
|
366
409
|
if (ct.includes('application/json')) {
|
|
367
410
|
try {
|
|
368
411
|
const body = await result.clone().json() as Record<string, unknown>
|
|
@@ -407,22 +450,44 @@ export async function executeAction(
|
|
|
407
450
|
return new Response(null, { status: 303, headers: { location: back.href } })
|
|
408
451
|
}
|
|
409
452
|
|
|
453
|
+
// Enforce rate limit before parsing bodies or running schema/protection checks so invalid floods cannot bypass throttling.
|
|
454
|
+
const retryAfter = limiter !== undefined && act.rateLimit !== undefined ? hitFor(limiter, act.rateLimit, ctx) : 0
|
|
455
|
+
if (retryAfter > 0) {
|
|
456
|
+
const redirected = flashAndRedirect('Too many requests', undefined, undefined)
|
|
457
|
+
if (redirected === undefined)
|
|
458
|
+
return tooManyRequests(retryAfter)
|
|
459
|
+
redirected.headers.set('retry-after', String(retryAfter))
|
|
460
|
+
return redirected
|
|
461
|
+
}
|
|
462
|
+
|
|
410
463
|
let rawBody: unknown
|
|
411
464
|
let input: unknown
|
|
412
|
-
|
|
465
|
+
const wantsBody = act.schema !== undefined || needsProtectBody(act.protect)
|
|
466
|
+
if (wantsBody) {
|
|
413
467
|
try {
|
|
414
468
|
rawBody = await parseActionBody(request)
|
|
415
469
|
}
|
|
416
470
|
catch {
|
|
417
471
|
return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
|
|
418
472
|
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const protectedBody = verifyActionProtection(act.protect, rawBody, Date.now(), act.url)
|
|
476
|
+
const cleanBody = protectedBody.cleanedBody
|
|
477
|
+
if (!protectedBody.ok) {
|
|
478
|
+
const redirected = flashAndRedirect(protectedBody.error, undefined, cleanBody)
|
|
479
|
+
if (redirected !== undefined)
|
|
480
|
+
return redirected
|
|
481
|
+
return Response.json({ ok: false, status: 400, error: protectedBody.error }, { status: 400 })
|
|
482
|
+
}
|
|
419
483
|
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
484
|
+
if (act.schema !== undefined) {
|
|
485
|
+
let checked = await validateSchema(act.schema, cleanBody)
|
|
486
|
+
if (!checked.ok && !isJsonBody(request) && cleanBody !== null && typeof cleanBody === 'object' && !Array.isArray(cleanBody))
|
|
487
|
+
checked = await retryWithFormArrays(act.schema, cleanBody as Record<string, unknown>, checked)
|
|
423
488
|
if (!checked.ok) {
|
|
424
489
|
// Zero-JS progressive HTML <form> submit: flash fieldErrors + safe submitted values (<4KB) and redirect 303 back to trusted Referer
|
|
425
|
-
const redirected = flashAndRedirect('Validation failed', checked.fieldErrors,
|
|
490
|
+
const redirected = flashAndRedirect('Validation failed', checked.fieldErrors, cleanBody)
|
|
426
491
|
if (redirected !== undefined)
|
|
427
492
|
return redirected
|
|
428
493
|
return Response.json(
|
|
@@ -433,16 +498,6 @@ export async function executeAction(
|
|
|
433
498
|
input = checked.value
|
|
434
499
|
}
|
|
435
500
|
|
|
436
|
-
// Counted once the body is read, so a refused form comes back with what was typed in it.
|
|
437
|
-
const retryAfter = limiter !== undefined && act.rateLimit !== undefined ? hitFor(limiter, act.rateLimit, ctx) : 0
|
|
438
|
-
if (retryAfter > 0) {
|
|
439
|
-
const redirected = flashAndRedirect('Too many requests', undefined, rawBody)
|
|
440
|
-
if (redirected === undefined)
|
|
441
|
-
return tooManyRequests(retryAfter)
|
|
442
|
-
redirected.headers.set('retry-after', String(retryAfter))
|
|
443
|
-
return redirected
|
|
444
|
-
}
|
|
445
|
-
|
|
446
501
|
// Track exact Response instances produced by `ctx.deny()` so zero-JS form submits flash & 303-redirect while custom Responses (redirects, downloads, custom JSON) pass through untouched.
|
|
447
502
|
let deniedResponses: Map<Response, { message: string, fieldErrors?: Record<string, string> | undefined }> | undefined
|
|
448
503
|
const actionCtx: ActionContext = Object.create(ctx, {
|
|
@@ -460,7 +515,7 @@ export async function executeAction(
|
|
|
460
515
|
if (result instanceof Response) {
|
|
461
516
|
const denied = deniedResponses?.get(result)
|
|
462
517
|
if (denied !== undefined) {
|
|
463
|
-
const redirected = flashAndRedirect(denied.message, denied.fieldErrors,
|
|
518
|
+
const redirected = flashAndRedirect(denied.message, denied.fieldErrors, cleanBody)
|
|
464
519
|
if (redirected !== undefined)
|
|
465
520
|
return redirected
|
|
466
521
|
}
|
package/src/server/assets.ts
CHANGED
|
@@ -34,6 +34,26 @@ export interface PrerenderedSources {
|
|
|
34
34
|
isFast: (urlPath: string, route: RouteManifestEntry) => boolean
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
const EXTRA_PRERENDER_MIME: Record<string, string> = {
|
|
38
|
+
'.htm': 'text/html; charset=utf-8',
|
|
39
|
+
'.rss': 'application/rss+xml; charset=utf-8',
|
|
40
|
+
'.atom': 'application/atom+xml; charset=utf-8',
|
|
41
|
+
'.ics': 'text/calendar; charset=utf-8',
|
|
42
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function prerenderedMime(ext: string, filePath: string | undefined): string {
|
|
46
|
+
const mapped = MIME[ext] ?? EXTRA_PRERENDER_MIME[ext]
|
|
47
|
+
if (mapped !== undefined)
|
|
48
|
+
return mapped
|
|
49
|
+
if (filePath !== undefined) {
|
|
50
|
+
const probed = Bun.file(filePath).type
|
|
51
|
+
if (probed && probed !== 'application/octet-stream')
|
|
52
|
+
return probed
|
|
53
|
+
}
|
|
54
|
+
return 'application/octet-stream'
|
|
55
|
+
}
|
|
56
|
+
|
|
37
57
|
const embedded = (body: EmbeddedBody): FileSource => typeof body === 'string' ? { path: body } : { bytes: body }
|
|
38
58
|
|
|
39
59
|
|
|
@@ -102,6 +122,12 @@ export function createAssets(options: AssetsOptions) {
|
|
|
102
122
|
}))
|
|
103
123
|
}
|
|
104
124
|
|
|
125
|
+
const nonHtmlSecurity: Record<string, string> = {}
|
|
126
|
+
for (const [k, v] of Object.entries(securityRecord)) {
|
|
127
|
+
if (k !== 'content-security-policy')
|
|
128
|
+
nonHtmlSecurity[k] = v
|
|
129
|
+
}
|
|
130
|
+
|
|
105
131
|
// Prerendered pages (zero-copy file paths preferred; raw HTML strings supported). `fast` holds those nothing may intercept.
|
|
106
132
|
function collectPrerendered(routes: readonly RouteManifestEntry[], sources: PrerenderedSources): { all: Map<string, ServedFile>, fast: Map<string, ServedFile> } {
|
|
107
133
|
const all = new Map<string, ServedFile>()
|
|
@@ -115,13 +141,19 @@ export function createAssets(options: AssetsOptions) {
|
|
|
115
141
|
const source: FileSource | undefined = filePath !== undefined ? { path: filePath } : html !== undefined ? { text: html } : undefined
|
|
116
142
|
if (source === undefined)
|
|
117
143
|
continue
|
|
144
|
+
const ext = extname(relHtml).toLowerCase()
|
|
145
|
+
const isHtml = ext === '.html' || ext === '.htm' || (ext === '' && html !== undefined)
|
|
118
146
|
const sidecars = sidecarsOf(sources.prerenderedFiles, relHtml)
|
|
147
|
+
const type = isHtml ? 'text/html; charset=utf-8' : prerenderedMime(ext, filePath)
|
|
148
|
+
const headers = isHtml
|
|
149
|
+
? sources.htmlHeaders(route, urlPath)
|
|
150
|
+
: { 'content-type': type, ...nonHtmlSecurity }
|
|
119
151
|
const entry = servedFile({
|
|
120
152
|
key: `pre:${urlPath}`,
|
|
121
153
|
source,
|
|
122
154
|
etag: sources.prerenderedEtags[relHtml],
|
|
123
|
-
headers
|
|
124
|
-
compressible: sidecars.br === undefined && sidecars.gz === undefined && compressCache !== undefined,
|
|
155
|
+
headers,
|
|
156
|
+
compressible: sidecars.br === undefined && sidecars.gz === undefined && (isHtml ? compressCache !== undefined : compressible(type)),
|
|
125
157
|
...sidecars,
|
|
126
158
|
})
|
|
127
159
|
all.set(urlPath, entry)
|
package/src/server/compress.ts
CHANGED
|
@@ -438,34 +438,111 @@ function zstdFrames(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array
|
|
|
438
438
|
}, { highWaterMark: 0 })
|
|
439
439
|
}
|
|
440
440
|
|
|
441
|
+
function tryCloseController(controller: ReadableStreamDefaultController<Uint8Array>): boolean {
|
|
442
|
+
try {
|
|
443
|
+
controller.close()
|
|
444
|
+
return true
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
return false
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function tryErrorController(controller: ReadableStreamDefaultController<Uint8Array>, error: unknown): boolean {
|
|
452
|
+
try {
|
|
453
|
+
controller.error(error)
|
|
454
|
+
return true
|
|
455
|
+
}
|
|
456
|
+
catch {
|
|
457
|
+
return false
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
441
461
|
/** One gzip stream flushed after each chunk: concatenated gzip members would stop a browser after the first. */
|
|
442
462
|
async function gzipFlushed(body: ReadableStream<Uint8Array>): Promise<ReadableStream<Uint8Array>> {
|
|
443
463
|
const { constants, createGzip } = await (zlib ??= import('node:zlib'))
|
|
444
464
|
const compressor = createGzip({ level: GZIP_PER_RESPONSE, flush: constants.Z_SYNC_FLUSH })
|
|
445
465
|
const reader = body.getReader()
|
|
466
|
+
let closed = false
|
|
446
467
|
let ended: Promise<void> | undefined
|
|
468
|
+
let resolveEnded: (() => void) | undefined
|
|
469
|
+
const markEnded = (): void => {
|
|
470
|
+
resolveEnded?.()
|
|
471
|
+
resolveEnded = undefined
|
|
472
|
+
}
|
|
447
473
|
return new ReadableStream<Uint8Array>({
|
|
448
474
|
start(controller) {
|
|
449
|
-
compressor.on('data', (chunk: Uint8Array) =>
|
|
450
|
-
|
|
451
|
-
|
|
475
|
+
compressor.on('data', (chunk: Uint8Array) => {
|
|
476
|
+
if (closed)
|
|
477
|
+
return
|
|
478
|
+
try {
|
|
479
|
+
controller.enqueue(chunk)
|
|
480
|
+
}
|
|
481
|
+
catch {
|
|
482
|
+
closed = true
|
|
483
|
+
markEnded()
|
|
484
|
+
compressor.destroy()
|
|
485
|
+
}
|
|
486
|
+
})
|
|
487
|
+
compressor.once('end', () => {
|
|
488
|
+
if (!closed) {
|
|
489
|
+
closed = true
|
|
490
|
+
tryCloseController(controller)
|
|
491
|
+
}
|
|
492
|
+
markEnded()
|
|
493
|
+
})
|
|
494
|
+
compressor.on('error', (error: unknown) => {
|
|
495
|
+
if (!closed) {
|
|
496
|
+
closed = true
|
|
497
|
+
tryErrorController(controller, error)
|
|
498
|
+
}
|
|
499
|
+
markEnded()
|
|
500
|
+
})
|
|
501
|
+
compressor.once('close', () => {
|
|
502
|
+
closed = true
|
|
503
|
+
markEnded()
|
|
504
|
+
})
|
|
452
505
|
},
|
|
453
506
|
async pull() {
|
|
507
|
+
if (closed)
|
|
508
|
+
return
|
|
454
509
|
if (ended !== undefined)
|
|
455
510
|
return ended
|
|
456
|
-
|
|
511
|
+
let next: Awaited<ReturnType<typeof reader.read>>
|
|
512
|
+
try {
|
|
513
|
+
next = await reader.read()
|
|
514
|
+
}
|
|
515
|
+
catch (error: unknown) {
|
|
516
|
+
closed = true
|
|
517
|
+
markEnded()
|
|
457
518
|
compressor.destroy()
|
|
458
519
|
throw error
|
|
459
|
-
}
|
|
520
|
+
}
|
|
521
|
+
if (closed)
|
|
522
|
+
return
|
|
460
523
|
if (next.done) {
|
|
461
|
-
|
|
524
|
+
if (compressor.readableEnded || compressor.destroyed) {
|
|
525
|
+
closed = true
|
|
526
|
+
return
|
|
527
|
+
}
|
|
528
|
+
ended = new Promise<void>((resolve) => {
|
|
529
|
+
resolveEnded = resolve
|
|
530
|
+
})
|
|
462
531
|
compressor.end()
|
|
463
532
|
return ended
|
|
464
533
|
}
|
|
465
534
|
// The compressor emits the flushed bytes before it calls back, so each chunk leaves before the next one is read.
|
|
466
|
-
await new Promise<void>((resolve, reject) =>
|
|
535
|
+
await new Promise<void>((resolve, reject) => {
|
|
536
|
+
if (closed || compressor.destroyed) {
|
|
537
|
+
resolve()
|
|
538
|
+
return
|
|
539
|
+
}
|
|
540
|
+
compressor.write(next.value, error => (error && !closed ? reject(error) : resolve()))
|
|
541
|
+
})
|
|
467
542
|
},
|
|
468
543
|
cancel(reason) {
|
|
544
|
+
closed = true
|
|
545
|
+
markEnded()
|
|
469
546
|
compressor.destroy()
|
|
470
547
|
return reader.cancel(reason)
|
|
471
548
|
},
|
|
@@ -512,11 +589,13 @@ export async function maybeCompressResponse(
|
|
|
512
589
|
return res
|
|
513
590
|
|
|
514
591
|
const cl = res.headers.get('content-length')
|
|
592
|
+
const clBytes = cl !== null && cl.trim() !== '' ? Number(cl) : Number.NaN
|
|
593
|
+
const hasValidCl = Number.isFinite(clBytes) && clBytes >= 0
|
|
515
594
|
const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
|
|
516
595
|
if (enc === undefined)
|
|
517
596
|
return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
|
|
518
597
|
|
|
519
|
-
if (
|
|
598
|
+
if (hasValidCl && clBytes < MIN_COMPRESS_BYTES)
|
|
520
599
|
return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
|
|
521
600
|
|
|
522
601
|
if (res.body === null)
|
|
@@ -538,8 +617,11 @@ export async function maybeCompressResponse(
|
|
|
538
617
|
return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
|
|
539
618
|
}
|
|
540
619
|
|
|
620
|
+
if (hasValidCl && clBytes > MAX_BUFFERED_PROBE_BYTES)
|
|
621
|
+
return isHtml(res) ? compressedStream(res, res.body, enc) : markCompressionHandled(tryAppendVaryAcceptEncoding(res))
|
|
622
|
+
|
|
541
623
|
let raw: Uint8Array<ArrayBuffer>
|
|
542
|
-
if (
|
|
624
|
+
if (hasValidCl) {
|
|
543
625
|
raw = new Uint8Array(await res.arrayBuffer())
|
|
544
626
|
}
|
|
545
627
|
else {
|