prunelle 0.1.1 → 0.7.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/LICENSE +21 -0
- package/llms.txt +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +89 -41
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +15 -0
- package/src/build/first-load.ts +85 -14
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +225 -122
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +14 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +115 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +177 -39
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +48 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +139 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +101 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -22
- package/src/compiler/analyze.ts +87 -54
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +407 -352
- 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 +260 -81
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +60 -0
- 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 +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +94 -34
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +57 -40
- package/src/dom/index.ts +54 -14
- package/src/dom/island.ts +102 -68
- package/src/dom/loop.ts +66 -32
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +18 -12
- package/src/plugins/context.ts +44 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- 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 +64 -20
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +188 -152
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +308 -65
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +186 -39
- package/src/server/index.ts +272 -273
- package/src/server/loader.ts +15 -2
- package/src/server/page.ts +15 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +356 -11
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +279 -52
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/standard-schema.ts +17 -0
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +91 -12
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +106 -8
- package/src/ssr/index.ts +151 -4
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +40 -19
- package/src/style.ts +64 -1
- 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/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
- package/ts-plugin.cjs +4277 -0
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// The error flash a progressive form leaves behind: a signed 60 s cookie holding the error, the field errors and the values to put back in the form.
|
|
2
|
+
|
|
3
|
+
import type { ActionContext, ActionErrorFlash, ServerAction } from './action'
|
|
4
|
+
import { signPayload, verifyPayload } from './app-secret'
|
|
5
|
+
import { extractFormSchema, isRecord } from './form-schema'
|
|
6
|
+
|
|
7
|
+
export const ACTION_ERROR_COOKIE = '__pru_action_err'
|
|
8
|
+
|
|
9
|
+
const FLASH_PURPOSE = 'action-flash'
|
|
10
|
+
const MAX_FLASH_COOKIE_BYTES = 3500
|
|
11
|
+
const MAX_FLASH_FIELD_CHARS = 512
|
|
12
|
+
// Substrings that are unambiguously sensitive even inside compound identifiers.
|
|
13
|
+
const SENSITIVE_SUBSTRING_RE = /password|passwd|passphrase|passcode|motdepasse|secret|token|jeton|credit|debit|card|carte|iban|routing|account|compte|bank|banque|bancaire|securite|vitale|passeport|passport|fiscal|impot|crypto|sante|medical|health|biometr|credential|private|session|bearer|csrf|xsrf|naissance/i
|
|
14
|
+
// Short acronyms/words matched only on token boundaries (after camelCase/punctuation/accent normalization) to avoid false positives like `subscribe`, `article`, `souvenir`, or `description`.
|
|
15
|
+
const SENSITIVE_TOKEN_RE = /\b(?:mot de passe|mdp|pwd|pw|pswd|psw|pass|pin|cvv|cvc|csc|ccv|rib|bic|sepa|cb|nir|secu|insee|cni|siret|siren|permis|ssn|sin|nin|tin|pan|otp|totp|mfa|2fa|auth|key|cle|code|tax|jwt)\b/i
|
|
16
|
+
|
|
17
|
+
function isSensitiveField(name: string): boolean {
|
|
18
|
+
const normalized = name
|
|
19
|
+
.normalize('NFD')
|
|
20
|
+
.replace(/[\u0300-\u036F]/g, '')
|
|
21
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
22
|
+
.replace(/[^a-zA-Z0-9]+/g, ' ')
|
|
23
|
+
.trim()
|
|
24
|
+
return SENSITIVE_SUBSTRING_RE.test(normalized) || SENSITIVE_TOKEN_RE.test(normalized)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function parseStringRecord(raw: unknown): Record<string, string> | undefined {
|
|
28
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
29
|
+
return undefined
|
|
30
|
+
const out: Record<string, string> = Object.create(null)
|
|
31
|
+
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
|
|
32
|
+
if (typeof v !== 'string')
|
|
33
|
+
return undefined
|
|
34
|
+
out[k] = v
|
|
35
|
+
}
|
|
36
|
+
return out
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function parseActionErrorFlash(raw: unknown): ActionErrorFlash | undefined {
|
|
40
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
41
|
+
return undefined
|
|
42
|
+
const rec = raw as Record<string, unknown>
|
|
43
|
+
if (typeof rec.action !== 'string' || typeof rec.error !== 'string')
|
|
44
|
+
return undefined
|
|
45
|
+
const fieldErrors = rec.fieldErrors === undefined ? undefined : parseStringRecord(rec.fieldErrors)
|
|
46
|
+
if (rec.fieldErrors !== undefined && fieldErrors === undefined)
|
|
47
|
+
return undefined
|
|
48
|
+
const values = rec.values === undefined ? undefined : parseStringRecord(rec.values)
|
|
49
|
+
if (rec.values !== undefined && values === undefined)
|
|
50
|
+
return undefined
|
|
51
|
+
return {
|
|
52
|
+
action: rec.action,
|
|
53
|
+
error: rec.error,
|
|
54
|
+
...(fieldErrors !== undefined ? { fieldErrors } : {}),
|
|
55
|
+
...(values !== undefined ? { values } : {}),
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Hydrates `ctx.locals.actionError` from `__pru_action_err` without clearing the cookie yet; returns true when the cookie was present. A cookie whose signature does not match is ignored. */
|
|
60
|
+
export function hydrateActionErrorFlash(ctx: Pick<ActionContext, 'cookies' | 'locals'>): boolean {
|
|
61
|
+
const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
|
|
62
|
+
if (rawFlash === undefined)
|
|
63
|
+
return false
|
|
64
|
+
const payload = verifyPayload(FLASH_PURPOSE, rawFlash)
|
|
65
|
+
if (payload === undefined)
|
|
66
|
+
return true
|
|
67
|
+
let json: unknown
|
|
68
|
+
try {
|
|
69
|
+
json = JSON.parse(payload)
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return true
|
|
73
|
+
}
|
|
74
|
+
const parsed = parseActionErrorFlash(json)
|
|
75
|
+
if (parsed !== undefined)
|
|
76
|
+
ctx.locals.actionError = parsed
|
|
77
|
+
return true
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// A property the schema marks as a secret (`format: "password"`, `writeOnly`).
|
|
81
|
+
function isSecretProperty(jsonSchema: Record<string, unknown>, name: string): boolean {
|
|
82
|
+
const props = jsonSchema.properties
|
|
83
|
+
const prop = isRecord(props) ? props[name] : undefined
|
|
84
|
+
return isRecord(prop) && (prop.format === 'password' || prop.writeOnly === true)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const derivedFields = new WeakMap<object, ReadonlySet<string>>()
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The form fields an error may put back in the form: the action's `flashFields` when it lists them, else the fields its schema declares, minus anything that reads as a secret.
|
|
91
|
+
* A schema that cannot describe itself as JSON declares none, so such an action lists `flashFields` to get its form refilled.
|
|
92
|
+
*/
|
|
93
|
+
export function flashAllowlist(act: Pick<ServerAction<unknown, unknown>, 'schema' | 'flashFields'>): ReadonlySet<string> {
|
|
94
|
+
if (act.flashFields !== undefined)
|
|
95
|
+
return new Set(act.flashFields)
|
|
96
|
+
if (act.schema === undefined)
|
|
97
|
+
return new Set()
|
|
98
|
+
let names = derivedFields.get(act.schema)
|
|
99
|
+
if (names === undefined) {
|
|
100
|
+
const extracted = extractFormSchema(act.schema)
|
|
101
|
+
names = extracted.ok
|
|
102
|
+
? new Set([...extracted.fields.keys()].filter(name => !isSensitiveField(name) && !isSecretProperty(extracted.jsonSchema, name)))
|
|
103
|
+
: new Set()
|
|
104
|
+
derivedFields.set(act.schema, names)
|
|
105
|
+
}
|
|
106
|
+
return names
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function encodedFlashSize(flash: ActionErrorFlash): number {
|
|
110
|
+
return Buffer.byteLength(encodeURIComponent(JSON.stringify(flash)), 'utf8')
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The value of the flash cookie: the signed JSON of the error, its field errors, and the allowed fields of the body that fit under 3.5 KB. */
|
|
114
|
+
export function buildActionErrorFlash(
|
|
115
|
+
actionUrl: string,
|
|
116
|
+
error: string,
|
|
117
|
+
fieldErrors: Record<string, string> | undefined,
|
|
118
|
+
rawBody: unknown,
|
|
119
|
+
allowed: ReadonlySet<string>,
|
|
120
|
+
): string {
|
|
121
|
+
const trimmedError = error.length > 256 ? error.slice(0, 256) : error
|
|
122
|
+
const base: ActionErrorFlash = {
|
|
123
|
+
action: actionUrl,
|
|
124
|
+
error: trimmedError,
|
|
125
|
+
}
|
|
126
|
+
if (fieldErrors !== undefined) {
|
|
127
|
+
const safeErrors: Record<string, string> = Object.create(null)
|
|
128
|
+
base.fieldErrors = safeErrors
|
|
129
|
+
for (const [k, msg] of Object.entries(fieldErrors)) {
|
|
130
|
+
const trimmed = msg.length > 256 ? msg.slice(0, 256) : msg
|
|
131
|
+
safeErrors[k] = trimmed
|
|
132
|
+
if (encodedFlashSize(base) > MAX_FLASH_COOKIE_BYTES) {
|
|
133
|
+
delete safeErrors[k]
|
|
134
|
+
break
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const values: Record<string, string> = Object.create(null)
|
|
140
|
+
if (rawBody !== null && typeof rawBody === 'object') {
|
|
141
|
+
for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
|
|
142
|
+
if (typeof v !== 'string' || v.length > MAX_FLASH_FIELD_CHARS || !allowed.has(k))
|
|
143
|
+
continue
|
|
144
|
+
values[k] = v
|
|
145
|
+
const candidate: ActionErrorFlash = { ...base, values }
|
|
146
|
+
if (encodedFlashSize(candidate) > MAX_FLASH_COOKIE_BYTES) {
|
|
147
|
+
delete values[k]
|
|
148
|
+
break
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const finalFlash: ActionErrorFlash = {
|
|
154
|
+
...base,
|
|
155
|
+
...(Object.keys(values).length > 0 ? { values } : {}),
|
|
156
|
+
}
|
|
157
|
+
return signPayload(FLASH_PURPOSE, JSON.stringify(finalFlash))
|
|
158
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
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 { getAppContext } from '../plugins/context'
|
|
6
|
+
import { appSecret, deriveKey, safeEqual } from './app-secret'
|
|
7
|
+
import { nodeEnv } from './env'
|
|
8
|
+
import { assertRateLimit } from './rate-limit'
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_HONEYPOT_FIELD = '_pru_hp'
|
|
11
|
+
export const FORM_TIMESTAMP_FIELD = '_pru_ts'
|
|
12
|
+
/** A signed timestamp older than this is refused: a form left open longer is rendered again. */
|
|
13
|
+
export const MAX_FORM_AGE_MS = 2 * 60 * 60 * 1000
|
|
14
|
+
/** What every refusal says, whichever check failed, so a bot learns nothing about which one it tripped. */
|
|
15
|
+
const REJECTED = 'Submission rejected'
|
|
16
|
+
|
|
17
|
+
export interface ActionProtectOptions {
|
|
18
|
+
/** Sliding-window rate limit for submissions to this action. */
|
|
19
|
+
rateLimit?: RateLimit<ActionContext> | undefined
|
|
20
|
+
/** Hidden trap input name (`true` uses `_pru_hp`, or pass a custom field name). Non-empty values are rejected. */
|
|
21
|
+
honeypot?: boolean | string | undefined
|
|
22
|
+
/** Minimum elapsed milliseconds between SSR render and submit; enforced with an HMAC-signed `_pru_ts` token. */
|
|
23
|
+
minTime?: number | undefined
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const DIGITS_RE = /^\d+$/
|
|
27
|
+
const TIMESTAMP_PURPOSE = 'form-timestamp'
|
|
28
|
+
|
|
29
|
+
// At definition, so a deploy that signs with a per-process key says so at start, not on the first submit.
|
|
30
|
+
function warnEphemeralSecret(): void {
|
|
31
|
+
if (nodeEnv() === 'production' && appSecret().ephemeral)
|
|
32
|
+
console.warn('prunelle: protect.minTime is signing form timestamps with a key made at this start because PRUNELLE_FORM_SECRET and AUTH_SECRET are unset, so a restart or a second instance refuses every form already rendered: set PRUNELLE_FORM_SECRET to 32 random bytes or more.')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function timestampSignature(payload: string): string {
|
|
36
|
+
return new Bun.CryptoHasher('sha256', deriveKey(TIMESTAMP_PURPOSE)).update(payload).digest('hex')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function timestampPayload(ts: string, actionUrl: string): string {
|
|
40
|
+
return actionUrl !== '' ? `${ts}\0${actionUrl}` : ts
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function escapeAttrValue(value: string): string {
|
|
44
|
+
return value.replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<').replaceAll('>', '>')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Returns the configured honeypot field name, or `undefined` when honeypot is disabled. */
|
|
48
|
+
export function honeypotFieldName(protect: ActionProtectOptions | undefined): string | undefined {
|
|
49
|
+
if (protect?.honeypot === true)
|
|
50
|
+
return DEFAULT_HONEYPOT_FIELD
|
|
51
|
+
if (typeof protect?.honeypot === 'string') {
|
|
52
|
+
const trimmed = protect.honeypot.trim()
|
|
53
|
+
return trimmed !== '' ? trimmed : undefined
|
|
54
|
+
}
|
|
55
|
+
return undefined
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Whether `protect` requires reading the request body (honeypot or minTime). */
|
|
59
|
+
export function needsProtectBody(protect: ActionProtectOptions | undefined): boolean {
|
|
60
|
+
return honeypotFieldName(protect) !== undefined || protect?.minTime !== undefined
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Validates `ActionProtectOptions` eagerly when `action()` is defined. */
|
|
64
|
+
export function assertActionProtect(protect: ActionProtectOptions): void {
|
|
65
|
+
if (protect.rateLimit !== undefined)
|
|
66
|
+
assertRateLimit(protect.rateLimit, 'an action')
|
|
67
|
+
if (protect.minTime !== undefined && (!Number.isFinite(protect.minTime) || protect.minTime < 0))
|
|
68
|
+
throw new Error(`prunelle: protect.minTime of an action is ${String(protect.minTime)}; give a non-negative number of milliseconds.`)
|
|
69
|
+
if (typeof protect.honeypot === 'string' && protect.honeypot.trim() === '')
|
|
70
|
+
throw new Error('prunelle: protect.honeypot of an action must be a non-empty field name.')
|
|
71
|
+
if (protect.minTime !== undefined)
|
|
72
|
+
warnEphemeralSecret()
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Creates an HMAC-SHA256 signed timestamp token (`<timestampMs>.<signatureHex>`), optionally bound to `actionUrl`. */
|
|
76
|
+
export function signFormTimestamp(timestampMs = Date.now(), actionUrl = ''): string {
|
|
77
|
+
const ts = String(Math.trunc(timestampMs))
|
|
78
|
+
const sig = timestampSignature(timestampPayload(ts, actionUrl))
|
|
79
|
+
return `${ts}.${sig}`
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Verifies an HMAC-signed `_pru_ts` token against `minTimeMs`, the two-hour expiry window, and optional `actionUrl`. */
|
|
83
|
+
export function verifyFormTimestamp(
|
|
84
|
+
token: unknown,
|
|
85
|
+
minTimeMs: number,
|
|
86
|
+
now = Date.now(),
|
|
87
|
+
actionUrl = '',
|
|
88
|
+
): { ok: true } | { ok: false, reason: string } {
|
|
89
|
+
if (typeof token !== 'string')
|
|
90
|
+
return { ok: false, reason: 'Missing form timestamp' }
|
|
91
|
+
const dot = token.indexOf('.')
|
|
92
|
+
if (dot <= 0 || dot === token.length - 1)
|
|
93
|
+
return { ok: false, reason: 'Invalid form timestamp' }
|
|
94
|
+
const tsStr = token.slice(0, dot)
|
|
95
|
+
const sig = token.slice(dot + 1)
|
|
96
|
+
if (!DIGITS_RE.test(tsStr))
|
|
97
|
+
return { ok: false, reason: 'Invalid form timestamp' }
|
|
98
|
+
const expected = timestampSignature(timestampPayload(tsStr, actionUrl))
|
|
99
|
+
if (!safeEqual(sig, expected))
|
|
100
|
+
return { ok: false, reason: 'Invalid form timestamp' }
|
|
101
|
+
const ts = Number(tsStr)
|
|
102
|
+
if (!Number.isFinite(ts))
|
|
103
|
+
return { ok: false, reason: 'Invalid form timestamp' }
|
|
104
|
+
const elapsed = now - ts
|
|
105
|
+
if (elapsed < minTimeMs)
|
|
106
|
+
return { ok: false, reason: 'Form submitted too quickly' }
|
|
107
|
+
if (elapsed > MAX_FORM_AGE_MS)
|
|
108
|
+
return { ok: false, reason: 'Form submission expired' }
|
|
109
|
+
return { ok: true }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function isNonEmptyFieldValue(value: unknown): boolean {
|
|
113
|
+
if (Array.isArray(value))
|
|
114
|
+
return value.some(v => v !== '' && v != null)
|
|
115
|
+
return value !== '' && value != null
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Returns a shallow copy of `rawBody` with internal Prunelle protection fields removed. */
|
|
119
|
+
export function stripProtectFields(protect: ActionProtectOptions | undefined, rawBody: unknown): unknown {
|
|
120
|
+
if (protect === undefined || rawBody === null || typeof rawBody !== 'object' || Array.isArray(rawBody))
|
|
121
|
+
return rawBody
|
|
122
|
+
const hpField = honeypotFieldName(protect)
|
|
123
|
+
const hasMinTime = protect.minTime !== undefined
|
|
124
|
+
if (hpField === undefined && !hasMinTime)
|
|
125
|
+
return rawBody
|
|
126
|
+
const obj = rawBody as Record<string, unknown>
|
|
127
|
+
const dropHp = hpField !== undefined && Object.hasOwn(obj, hpField)
|
|
128
|
+
const dropTs = hasMinTime && Object.hasOwn(obj, FORM_TIMESTAMP_FIELD)
|
|
129
|
+
if (!dropHp && !dropTs)
|
|
130
|
+
return rawBody
|
|
131
|
+
const entries: [string, unknown][] = []
|
|
132
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
133
|
+
if ((dropHp && k === hpField) || (dropTs && k === FORM_TIMESTAMP_FIELD))
|
|
134
|
+
continue
|
|
135
|
+
entries.push([k, v])
|
|
136
|
+
}
|
|
137
|
+
return Object.fromEntries(entries)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const warnedNoTimestamp = new Set<string>()
|
|
141
|
+
|
|
142
|
+
// Once per action and process, in dev only: in production a submit without the token is a bot's, and only a developer can act on why.
|
|
143
|
+
function warnNoTimestamp(actionUrl: string): void {
|
|
144
|
+
if (warnedNoTimestamp.has(actionUrl) || getAppContext()?.dev !== true)
|
|
145
|
+
return
|
|
146
|
+
warnedNoTimestamp.add(actionUrl)
|
|
147
|
+
console.warn(`prunelle: the action at ${actionUrl} refused a submit with no signed ${FORM_TIMESTAMP_FIELD} timestamp, which protect.minTime requires: prunelle signs one only into a <form action={...}> rendered on the server, so a form an island renders in the browser (after a click, say) has none; render the form in the page's first render and hide it until needed, or drop minTime and rely on the honeypot and rateLimit.`)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Verifies honeypot and signed timestamp protections and returns the body with internal fields stripped. */
|
|
151
|
+
export function verifyActionProtection(
|
|
152
|
+
protect: ActionProtectOptions | undefined,
|
|
153
|
+
rawBody: unknown,
|
|
154
|
+
now = Date.now(),
|
|
155
|
+
actionUrl = '',
|
|
156
|
+
): { ok: true, cleanedBody: unknown } | { ok: false, error: string, cleanedBody: unknown } {
|
|
157
|
+
if (protect === undefined)
|
|
158
|
+
return { ok: true, cleanedBody: rawBody }
|
|
159
|
+
const hpField = honeypotFieldName(protect)
|
|
160
|
+
const minTime = protect.minTime
|
|
161
|
+
if (hpField === undefined && minTime === undefined)
|
|
162
|
+
return { ok: true, cleanedBody: rawBody }
|
|
163
|
+
|
|
164
|
+
const cleanedBody = stripProtectFields(protect, rawBody)
|
|
165
|
+
const obj = rawBody !== null && typeof rawBody === 'object' && !Array.isArray(rawBody)
|
|
166
|
+
? rawBody as Record<string, unknown>
|
|
167
|
+
: undefined
|
|
168
|
+
|
|
169
|
+
if (hpField !== undefined && obj !== undefined && Object.hasOwn(obj, hpField)) {
|
|
170
|
+
if (isNonEmptyFieldValue(obj[hpField]))
|
|
171
|
+
return { ok: false, error: REJECTED, cleanedBody }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (minTime !== undefined) {
|
|
175
|
+
const rawTs = obj !== undefined && Object.hasOwn(obj, FORM_TIMESTAMP_FIELD) ? obj[FORM_TIMESTAMP_FIELD] : undefined
|
|
176
|
+
const token = Array.isArray(rawTs) ? rawTs[0] : rawTs
|
|
177
|
+
const tsResult = verifyFormTimestamp(token, minTime, now, actionUrl)
|
|
178
|
+
if (!tsResult.ok) {
|
|
179
|
+
if (token === undefined)
|
|
180
|
+
warnNoTimestamp(actionUrl)
|
|
181
|
+
return { ok: false, error: REJECTED, cleanedBody }
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return { ok: true, cleanedBody }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Renders the SSR hidden protection inputs (visually hidden honeypot + signed timestamp) for `<form action={fn}>`. */
|
|
189
|
+
export function renderProtectFields(protect: ActionProtectOptions | undefined, actionUrl = ''): string {
|
|
190
|
+
if (protect === undefined)
|
|
191
|
+
return ''
|
|
192
|
+
let html = ''
|
|
193
|
+
const hp = honeypotFieldName(protect)
|
|
194
|
+
if (hp !== undefined)
|
|
195
|
+
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">`
|
|
196
|
+
if (protect.minTime !== undefined)
|
|
197
|
+
html += `<input type="hidden" name="${FORM_TIMESTAMP_FIELD}" value="${signFormTimestamp(undefined, actionUrl)}">`
|
|
198
|
+
return html
|
|
199
|
+
}
|
|
@@ -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>
|