prunelle 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/llms.txt +48 -43
- package/package.json +4 -1
- package/src/a11y/declaration.ts +106 -72
- package/src/a11y/index.ts +59 -39
- package/src/a11y/rgaa-map.ts +95 -49
- package/src/build/bundle.ts +8 -4
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-plugin.ts +3 -1
- package/src/build/compile.ts +2 -1
- package/src/build/ecoindex.ts +25 -16
- package/src/build/files.ts +6 -0
- package/src/build/first-load.ts +83 -11
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +61 -18
- package/src/build/island-promote.ts +250 -0
- package/src/build/islands.ts +12 -201
- package/src/build/manifest.ts +4 -125
- package/src/build/plugin-host.ts +21 -8
- package/src/build/precompress.ts +1 -1
- package/src/build/prerender.ts +97 -44
- package/src/build/reach.ts +136 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +25 -3
- package/src/build/static-headers.ts +93 -0
- package/src/build/static.ts +2 -0
- package/src/cli/check-forms.ts +97 -48
- package/src/cli/check-imports.ts +25 -0
- package/src/cli/check-links.ts +2 -2
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +37 -7
- package/src/cli/commands.ts +35 -7
- package/src/cli/docs.ts +4 -3
- package/src/cli/inspect.ts +2 -1
- package/src/cli/mcp-tools.ts +7 -5
- package/src/cli/mcp.ts +1 -1
- package/src/cli/new.ts +14 -3
- package/src/cli/render.ts +14 -19
- package/src/cli/upgrade.ts +22 -5
- package/src/compiler/analyze.ts +27 -5
- package/src/compiler/cacheability.ts +2 -2
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +110 -4
- package/src/compiler/compliance-urls.ts +146 -0
- package/src/compiler/compliance.ts +168 -116
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +19 -1
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/shared.ts +2 -2
- package/src/compiler/ssr.ts +2 -2
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +90 -64
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +17 -7
- package/src/dev/open-editor.ts +36 -12
- package/src/dev/protocol.ts +2 -0
- package/src/dev/supervisor.ts +8 -0
- package/src/dev/watchers.ts +27 -2
- package/src/dom/action.ts +4 -1
- package/src/dom/extras.ts +1 -2
- package/src/dom/index.ts +28 -6
- package/src/dom/island.ts +22 -10
- package/src/dom/loop.ts +60 -27
- package/src/eco/declaration.ts +257 -0
- package/src/eco/index.ts +65 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +44 -1
- package/src/plugins/load.ts +4 -3
- package/src/plugins/public.ts +2 -2
- package/src/plugins/services.ts +3 -0
- package/src/plugins/types.ts +17 -2
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +38 -37
- package/src/server/action.ts +11 -127
- package/src/server/app-secret.ts +63 -0
- package/src/server/compress.ts +5 -1
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +3 -1
- package/src/server/form-schema.ts +1 -1
- package/src/server/health.ts +46 -15
- package/src/server/http.ts +56 -8
- package/src/server/index.ts +59 -30
- package/src/server/loader.ts +10 -2
- package/src/server/plugin-host.ts +3 -1
- package/src/server/public.ts +4 -3
- package/src/server/rate-limit.ts +52 -9
- package/src/server/route-cache.ts +26 -4
- package/src/server/route-table.ts +7 -3
- package/src/server/routing.ts +3 -87
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +73 -22
- package/src/server/serve-handlers.ts +14 -4
- package/src/server/start.ts +1 -1
- package/src/server/static-dir.ts +31 -5
- package/src/server/stream.ts +28 -6
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +20 -4
- package/src/ssr/index.ts +18 -0
- package/src/ssr/navigation.ts +2 -2
- package/src/style.ts +64 -1
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/src/routes/legal.tsx +10 -1
- 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/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +1 -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
|
@@ -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
|
+
}
|
|
@@ -2,21 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
import type { ActionContext } from './action'
|
|
4
4
|
import type { RateLimit } from './rate-limit'
|
|
5
|
+
import { getAppContext } from '../plugins/context'
|
|
6
|
+
import { appSecret, deriveKey, safeEqual } from './app-secret'
|
|
5
7
|
import { nodeEnv } from './env'
|
|
6
8
|
import { assertRateLimit } from './rate-limit'
|
|
7
9
|
|
|
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
10
|
export const DEFAULT_HONEYPOT_FIELD = '_pru_hp'
|
|
18
11
|
export const FORM_TIMESTAMP_FIELD = '_pru_ts'
|
|
19
|
-
|
|
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'
|
|
20
16
|
|
|
21
17
|
export interface ActionProtectOptions {
|
|
22
18
|
/** Sliding-window rate limit for submissions to this action. */
|
|
@@ -27,27 +23,17 @@ export interface ActionProtectOptions {
|
|
|
27
23
|
minTime?: number | undefined
|
|
28
24
|
}
|
|
29
25
|
|
|
30
|
-
const EPHEMERAL_SECRET_KEY = Symbol.for('pru.form.secret')
|
|
31
26
|
const DIGITS_RE = /^\d+$/
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
if (
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
|
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')
|
|
51
37
|
}
|
|
52
38
|
|
|
53
39
|
function timestampPayload(ts: string, actionUrl: string): string {
|
|
@@ -82,16 +68,18 @@ export function assertActionProtect(protect: ActionProtectOptions): void {
|
|
|
82
68
|
throw new Error(`prunelle: protect.minTime of an action is ${String(protect.minTime)}; give a non-negative number of milliseconds.`)
|
|
83
69
|
if (typeof protect.honeypot === 'string' && protect.honeypot.trim() === '')
|
|
84
70
|
throw new Error('prunelle: protect.honeypot of an action must be a non-empty field name.')
|
|
71
|
+
if (protect.minTime !== undefined)
|
|
72
|
+
warnEphemeralSecret()
|
|
85
73
|
}
|
|
86
74
|
|
|
87
75
|
/** Creates an HMAC-SHA256 signed timestamp token (`<timestampMs>.<signatureHex>`), optionally bound to `actionUrl`. */
|
|
88
76
|
export function signFormTimestamp(timestampMs = Date.now(), actionUrl = ''): string {
|
|
89
77
|
const ts = String(Math.trunc(timestampMs))
|
|
90
|
-
const sig =
|
|
78
|
+
const sig = timestampSignature(timestampPayload(ts, actionUrl))
|
|
91
79
|
return `${ts}.${sig}`
|
|
92
80
|
}
|
|
93
81
|
|
|
94
|
-
/** Verifies an HMAC-signed `_pru_ts` token against `minTimeMs`, the
|
|
82
|
+
/** Verifies an HMAC-signed `_pru_ts` token against `minTimeMs`, the two-hour expiry window, and optional `actionUrl`. */
|
|
95
83
|
export function verifyFormTimestamp(
|
|
96
84
|
token: unknown,
|
|
97
85
|
minTimeMs: number,
|
|
@@ -107,8 +95,8 @@ export function verifyFormTimestamp(
|
|
|
107
95
|
const sig = token.slice(dot + 1)
|
|
108
96
|
if (!DIGITS_RE.test(tsStr))
|
|
109
97
|
return { ok: false, reason: 'Invalid form timestamp' }
|
|
110
|
-
const expected =
|
|
111
|
-
if (!
|
|
98
|
+
const expected = timestampSignature(timestampPayload(tsStr, actionUrl))
|
|
99
|
+
if (!safeEqual(sig, expected))
|
|
112
100
|
return { ok: false, reason: 'Invalid form timestamp' }
|
|
113
101
|
const ts = Number(tsStr)
|
|
114
102
|
if (!Number.isFinite(ts))
|
|
@@ -149,6 +137,16 @@ export function stripProtectFields(protect: ActionProtectOptions | undefined, ra
|
|
|
149
137
|
return Object.fromEntries(entries)
|
|
150
138
|
}
|
|
151
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
|
+
|
|
152
150
|
/** Verifies honeypot and signed timestamp protections and returns the body with internal fields stripped. */
|
|
153
151
|
export function verifyActionProtection(
|
|
154
152
|
protect: ActionProtectOptions | undefined,
|
|
@@ -170,15 +168,18 @@ export function verifyActionProtection(
|
|
|
170
168
|
|
|
171
169
|
if (hpField !== undefined && obj !== undefined && Object.hasOwn(obj, hpField)) {
|
|
172
170
|
if (isNonEmptyFieldValue(obj[hpField]))
|
|
173
|
-
return { ok: false, error:
|
|
171
|
+
return { ok: false, error: REJECTED, cleanedBody }
|
|
174
172
|
}
|
|
175
173
|
|
|
176
174
|
if (minTime !== undefined) {
|
|
177
175
|
const rawTs = obj !== undefined && Object.hasOwn(obj, FORM_TIMESTAMP_FIELD) ? obj[FORM_TIMESTAMP_FIELD] : undefined
|
|
178
176
|
const token = Array.isArray(rawTs) ? rawTs[0] : rawTs
|
|
179
177
|
const tsResult = verifyFormTimestamp(token, minTime, now, actionUrl)
|
|
180
|
-
if (!tsResult.ok)
|
|
181
|
-
|
|
178
|
+
if (!tsResult.ok) {
|
|
179
|
+
if (token === undefined)
|
|
180
|
+
warnNoTimestamp(actionUrl)
|
|
181
|
+
return { ok: false, error: REJECTED, cleanedBody }
|
|
182
|
+
}
|
|
182
183
|
}
|
|
183
184
|
|
|
184
185
|
return { ok: true, cleanedBody }
|
package/src/server/action.ts
CHANGED
|
@@ -2,17 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
import type { ActionProtectOptions } from './action-protect'
|
|
4
4
|
import type { Cookies } from './cookies'
|
|
5
|
+
import type { RequestContext } from './http'
|
|
5
6
|
import type { PrunelleLocals } from './index'
|
|
6
7
|
import type { RateLimit, RateLimiter } from './rate-limit'
|
|
7
8
|
import type { TrustProxy } from './security'
|
|
8
9
|
import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
|
|
10
|
+
import { ACTION_ERROR_COOKIE, buildActionErrorFlash, flashAllowlist } from './action-flash'
|
|
9
11
|
import { assertActionProtect, needsProtectBody, verifyActionProtection } from './action-protect'
|
|
10
|
-
import { wantsJson } from './http'
|
|
12
|
+
import { isExternalRedirect, wantsJson } from './http'
|
|
11
13
|
import { assertRateLimit, hitFor, tooManyRequests } from './rate-limit'
|
|
12
14
|
import { currentRequest } from './request-scope'
|
|
13
15
|
import { isTrustedOrigin } from './security'
|
|
14
16
|
import { validateSchema } from './standard-schema'
|
|
15
17
|
|
|
18
|
+
export { ACTION_ERROR_COOKIE, hydrateActionErrorFlash } from './action-flash'
|
|
16
19
|
export type { ActionProtectOptions } from './action-protect'
|
|
17
20
|
|
|
18
21
|
declare module './index' {
|
|
@@ -21,71 +24,6 @@ declare module './index' {
|
|
|
21
24
|
}
|
|
22
25
|
}
|
|
23
26
|
|
|
24
|
-
export const ACTION_ERROR_COOKIE = '__pru_action_err'
|
|
25
|
-
|
|
26
|
-
const MAX_FLASH_COOKIE_BYTES = 3500
|
|
27
|
-
const MAX_FLASH_FIELD_CHARS = 512
|
|
28
|
-
// Substrings that are unambiguously sensitive even inside compound identifiers.
|
|
29
|
-
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
|
|
30
|
-
// Short acronyms/words matched only on token boundaries (after camelCase/punctuation/accent normalization) to avoid false positives like `subscribe`, `article`, `souvenir`, or `description`.
|
|
31
|
-
const SENSITIVE_TOKEN_RE = /\b(?:mot de passe|mdp|pwd|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
|
|
32
|
-
|
|
33
|
-
function isSensitiveField(name: string): boolean {
|
|
34
|
-
const normalized = name
|
|
35
|
-
.normalize('NFD')
|
|
36
|
-
.replace(/[\u0300-\u036f]/g, '')
|
|
37
|
-
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
38
|
-
.replace(/[^a-zA-Z0-9]+/g, ' ')
|
|
39
|
-
.trim()
|
|
40
|
-
return SENSITIVE_SUBSTRING_RE.test(normalized) || SENSITIVE_TOKEN_RE.test(normalized)
|
|
41
|
-
}
|
|
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
|
-
|
|
75
|
-
/** Hydrates `ctx.locals.actionError` from `__pru_action_err` without clearing the cookie yet; returns true when the cookie was present. */
|
|
76
|
-
export function hydrateActionErrorFlash(ctx: Pick<ActionContext, 'cookies' | 'locals'>): boolean {
|
|
77
|
-
const rawFlash = ctx.cookies.get(ACTION_ERROR_COOKIE)
|
|
78
|
-
if (rawFlash === undefined)
|
|
79
|
-
return false
|
|
80
|
-
try {
|
|
81
|
-
const parsed = parseActionErrorFlash(JSON.parse(rawFlash))
|
|
82
|
-
if (parsed !== undefined)
|
|
83
|
-
ctx.locals.actionError = parsed
|
|
84
|
-
}
|
|
85
|
-
catch {}
|
|
86
|
-
return true
|
|
87
|
-
}
|
|
88
|
-
|
|
89
27
|
/** Converts 3xx action/middleware redirects into a 204 + `x-pru-redirect` header for `actionStub` (`x-pru-action: 1`), preventing double-fetch and cross-origin CORS failures in browsers. */
|
|
90
28
|
export function finishActionRedirect(res: Response, request: Request): Response {
|
|
91
29
|
if (request.headers.get('x-pru-action') !== '1' || res.status < 300 || res.status >= 400)
|
|
@@ -97,11 +35,14 @@ export function finishActionRedirect(res: Response, request: Request): Response
|
|
|
97
35
|
for (const cookie of res.headers.getSetCookie())
|
|
98
36
|
headers.append('set-cookie', cookie)
|
|
99
37
|
headers.set('x-pru-redirect', location)
|
|
38
|
+
// The call from an island follows a target on another site only when the app said it chose it.
|
|
39
|
+
if (isExternalRedirect(res))
|
|
40
|
+
headers.set('x-pru-redirect-external', '1')
|
|
100
41
|
return new Response(null, { status: 204, headers })
|
|
101
42
|
}
|
|
102
43
|
|
|
103
44
|
export interface ActionOptions {
|
|
104
|
-
/**
|
|
45
|
+
/** The form fields an error puts back in the form, in place of the fields the schema declares (minus anything that reads as a secret); a schema with no JSON Schema output declares none, so list them here. */
|
|
105
46
|
flashFields?: readonly string[] | undefined
|
|
106
47
|
/** 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. */
|
|
107
48
|
rateLimit?: RateLimit<ActionContext> | undefined
|
|
@@ -126,7 +67,7 @@ export interface ActionContext {
|
|
|
126
67
|
cookies: Cookies
|
|
127
68
|
locals: PrunelleLocals
|
|
128
69
|
ip?: string | undefined
|
|
129
|
-
redirect:
|
|
70
|
+
redirect: RequestContext['redirect']
|
|
130
71
|
deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
|
|
131
72
|
}
|
|
132
73
|
|
|
@@ -321,64 +262,6 @@ async function retryWithFormArrays(schema: StandardSchemaV1, body: Record<string
|
|
|
321
262
|
return kept.length === wrapped.length ? second : validateSchema(schema, retried)
|
|
322
263
|
}
|
|
323
264
|
|
|
324
|
-
function encodedFlashSize(flash: ActionErrorFlash): number {
|
|
325
|
-
return Buffer.byteLength(encodeURIComponent(JSON.stringify(flash)), 'utf8')
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
function buildActionErrorFlash(
|
|
329
|
-
actionUrl: string,
|
|
330
|
-
error: string,
|
|
331
|
-
fieldErrors: Record<string, string> | undefined,
|
|
332
|
-
rawBody: unknown,
|
|
333
|
-
flashFields?: readonly string[],
|
|
334
|
-
): string {
|
|
335
|
-
const trimmedError = error.length > 256 ? error.slice(0, 256) : error
|
|
336
|
-
const base: ActionErrorFlash = {
|
|
337
|
-
action: actionUrl,
|
|
338
|
-
error: trimmedError,
|
|
339
|
-
}
|
|
340
|
-
if (fieldErrors !== undefined) {
|
|
341
|
-
const safeErrors: Record<string, string> = Object.create(null)
|
|
342
|
-
base.fieldErrors = safeErrors
|
|
343
|
-
for (const [k, msg] of Object.entries(fieldErrors)) {
|
|
344
|
-
const trimmed = msg.length > 256 ? msg.slice(0, 256) : msg
|
|
345
|
-
safeErrors[k] = trimmed
|
|
346
|
-
if (encodedFlashSize(base) > MAX_FLASH_COOKIE_BYTES) {
|
|
347
|
-
delete safeErrors[k]
|
|
348
|
-
break
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
const allowSet = flashFields !== undefined ? new Set(flashFields) : undefined
|
|
354
|
-
const values: Record<string, string> = Object.create(null)
|
|
355
|
-
if (rawBody !== null && typeof rawBody === 'object') {
|
|
356
|
-
for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
|
|
357
|
-
if (typeof v !== 'string' || v.length > MAX_FLASH_FIELD_CHARS)
|
|
358
|
-
continue
|
|
359
|
-
if (allowSet !== undefined) {
|
|
360
|
-
if (!allowSet.has(k))
|
|
361
|
-
continue
|
|
362
|
-
}
|
|
363
|
-
else if (isSensitiveField(k)) {
|
|
364
|
-
continue
|
|
365
|
-
}
|
|
366
|
-
values[k] = v
|
|
367
|
-
const candidate: ActionErrorFlash = { ...base, values }
|
|
368
|
-
if (encodedFlashSize(candidate) > MAX_FLASH_COOKIE_BYTES) {
|
|
369
|
-
delete values[k]
|
|
370
|
-
break
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
const finalFlash: ActionErrorFlash = {
|
|
376
|
-
...base,
|
|
377
|
-
...(Object.keys(values).length > 0 ? { values } : {}),
|
|
378
|
-
}
|
|
379
|
-
return JSON.stringify(finalFlash)
|
|
380
|
-
}
|
|
381
|
-
|
|
382
265
|
/** Programmatic action invocation with Standard Schema validation (used by `ServerPluginAPI.invokeAction` inside middleware chains). */
|
|
383
266
|
export async function invokeActionCore<I, O>(
|
|
384
267
|
act: ServerAction<I, O>,
|
|
@@ -442,10 +325,11 @@ export async function executeAction(
|
|
|
442
325
|
const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy, ctx.url)
|
|
443
326
|
if (back === undefined)
|
|
444
327
|
return undefined
|
|
445
|
-
ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, error, fieldErrors, rawBody, act
|
|
328
|
+
ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, error, fieldErrors, rawBody, flashAllowlist(act)), {
|
|
446
329
|
httpOnly: true,
|
|
447
330
|
sameSite: 'lax',
|
|
448
331
|
maxAge: 60,
|
|
332
|
+
category: 'essential',
|
|
449
333
|
})
|
|
450
334
|
return new Response(null, { status: 303, headers: { location: back.href } })
|
|
451
335
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// The app's signing secret, and one key per purpose derived from it with HKDF so a token made for one use never verifies for another.
|
|
2
|
+
// HMAC goes through Bun.CryptoHasher, never `node:crypto`, which would add 2 MB to the server's RSS.
|
|
3
|
+
|
|
4
|
+
const EPHEMERAL_SECRET_KEY = Symbol.for('pru.form.secret')
|
|
5
|
+
const keyCache = new Map<string, Buffer>()
|
|
6
|
+
|
|
7
|
+
const hmac = (key: string | Buffer, data: string | Buffer): Buffer => new Bun.CryptoHasher('sha256', key).update(data).digest()
|
|
8
|
+
|
|
9
|
+
/** The configured secret (`PRUNELLE_FORM_SECRET`, then `AUTH_SECRET`), or one random per process that dies with it. */
|
|
10
|
+
export function appSecret(): { secret: string, ephemeral: boolean } {
|
|
11
|
+
const configured = process.env.PRUNELLE_FORM_SECRET || process.env.AUTH_SECRET
|
|
12
|
+
if (configured)
|
|
13
|
+
return { secret: configured, ephemeral: false }
|
|
14
|
+
const g = globalThis as Record<symbol, string | undefined>
|
|
15
|
+
let secret = g[EPHEMERAL_SECRET_KEY]
|
|
16
|
+
if (secret === undefined) {
|
|
17
|
+
secret = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('hex')
|
|
18
|
+
g[EPHEMERAL_SECRET_KEY] = secret
|
|
19
|
+
}
|
|
20
|
+
return { secret, ephemeral: true }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A 32-byte key for `purpose` (`"form-timestamp"`, `"action-flash"`), HKDF-SHA256 (RFC 5869) of the app secret with `"prunelle"` as salt and the purpose as `info`. */
|
|
24
|
+
export function deriveKey(purpose: string): Buffer {
|
|
25
|
+
const { secret } = appSecret()
|
|
26
|
+
const id = `${purpose}\0${secret}`
|
|
27
|
+
let key = keyCache.get(id)
|
|
28
|
+
if (key === undefined) {
|
|
29
|
+
// One SHA-256 block is the 32 bytes asked for, so the expand step is its first round alone.
|
|
30
|
+
key = hmac(hmac('prunelle', secret), Buffer.concat([Buffer.from(purpose), Buffer.of(1)]))
|
|
31
|
+
if (keyCache.size > 16)
|
|
32
|
+
keyCache.clear()
|
|
33
|
+
keyCache.set(id, key)
|
|
34
|
+
}
|
|
35
|
+
return key
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Compares two secrets (tokens, MACs, OAuth states) in constant time: both are hashed first, so neither their content nor their length shows in the timing.
|
|
40
|
+
* The digests are XORed byte by byte rather than passed to `node:crypto`.
|
|
41
|
+
*/
|
|
42
|
+
export function safeEqual(a: string, b: string): boolean {
|
|
43
|
+
const x = new Bun.CryptoHasher('sha256').update(a).digest()
|
|
44
|
+
const y = new Bun.CryptoHasher('sha256').update(b).digest()
|
|
45
|
+
let diff = 0
|
|
46
|
+
for (let i = 0; i < x.length; i++)
|
|
47
|
+
diff |= x[i]! ^ y[i]!
|
|
48
|
+
return diff === 0
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** `<signature>.<payload>`: the payload as is, behind the HMAC-SHA256 (base64url) of it under the key for `purpose`. */
|
|
52
|
+
export function signPayload(purpose: string, payload: string): string {
|
|
53
|
+
return `${hmac(deriveKey(purpose), payload).toString('base64url')}.${payload}`
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The payload of a `signPayload` value, or undefined when it is not one or its signature does not match. */
|
|
57
|
+
export function verifyPayload(purpose: string, signed: string): string | undefined {
|
|
58
|
+
const dot = signed.indexOf('.')
|
|
59
|
+
if (dot <= 0)
|
|
60
|
+
return undefined
|
|
61
|
+
const payload = signed.slice(dot + 1)
|
|
62
|
+
return safeEqual(signed.slice(0, dot), hmac(deriveKey(purpose), payload).toString('base64url')) ? payload : undefined
|
|
63
|
+
}
|
package/src/server/compress.ts
CHANGED
|
@@ -17,6 +17,9 @@ const COMPRESSIBLE_EXACT = new Set([
|
|
|
17
17
|
'application/atom+xml',
|
|
18
18
|
'application/wasm',
|
|
19
19
|
'image/svg+xml',
|
|
20
|
+
'image/x-icon',
|
|
21
|
+
'font/ttf',
|
|
22
|
+
'font/otf',
|
|
20
23
|
])
|
|
21
24
|
|
|
22
25
|
export function isCompressibleType(contentType: string | null | undefined): boolean {
|
|
@@ -380,7 +383,8 @@ export function compressedHtmlResponse(
|
|
|
380
383
|
if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
|
|
381
384
|
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
382
385
|
if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
|
|
383
|
-
|
|
386
|
+
// SHA-256 of the page, so two pages never share a kept body: a 64-bit hash could be made to collide by a page that renders the query string.
|
|
387
|
+
const staticKey = reuse ? `s:${new Bun.CryptoHasher('sha256').update(html).digest('base64url')}` : undefined
|
|
384
388
|
let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
|
|
385
389
|
if (compressed === undefined)
|
|
386
390
|
compressed = cache.compress(html, enc, staticKey)
|