prunelle 0.6.0 → 0.7.0
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 +15 -14
- 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 +57 -18
- package/src/build/island-promote.ts +229 -0
- package/src/build/islands.ts +9 -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 +19 -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 +33 -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 +26 -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 +145 -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 +52 -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 +26 -0
- package/src/dev/index.ts +12 -5
- package/src/dev/open-editor.ts +15 -11
- 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 +13 -2
- package/src/dom/island.ts +22 -10
- package/src/dom/loop.ts +25 -16
- 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 +16 -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 +47 -7
- package/src/server/index.ts +52 -30
- package/src/server/loader.ts +6 -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 +71 -20
- package/src/server/serve-handlers.ts +14 -4
- package/src/server/start.ts +1 -1
- package/src/server/static-dir.ts +27 -4
- 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 +32 -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
package/src/jsx-runtime.ts
CHANGED
|
@@ -35,11 +35,11 @@ export function Fragment(props: { children?: PrunelleChild }): PrunelleChild {
|
|
|
35
35
|
return props.children
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
//
|
|
38
|
+
// Only a component call reaches this: prunelle's compiler turns every element into HTML or DOM calls, so an element here means the file skipped it.
|
|
39
39
|
export function jsx(tag: unknown, props: Record<string, unknown>): PrunelleChild | Promise<PrunelleChild> {
|
|
40
40
|
if (typeof tag === 'function')
|
|
41
41
|
return (tag as Component)(props)
|
|
42
|
-
|
|
42
|
+
throw new Error(`prunelle: <${String(tag)}> reached the JSX runtime, so this file was not compiled by prunelle: run it with prunelle dev, build or prunelle/test, and check that nothing else (a bundler, a test runner, a tsconfig \`jsxImportSource\`) compiles the TSX first.`)
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
export const jsxs = jsx
|
package/src/plugins/config.ts
CHANGED
|
@@ -16,7 +16,7 @@ export function pickRuntimeConfig(config: PrunelleConfig | undefined): ServerRun
|
|
|
16
16
|
|
|
17
17
|
// Typed as records so that a key added to the config types without being listed here fails the typecheck.
|
|
18
18
|
const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, routeCache: true, healthCheck: true, onError: true, plugins: true }
|
|
19
|
-
const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true, autoPrerender: true }
|
|
19
|
+
const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true, autoPrerender: true, budget: true }
|
|
20
20
|
const RUNTIME_CONFIG_KEYS = Object.keys(RUNTIME_KEYS) as (keyof ServerRuntimeConfig)[]
|
|
21
21
|
const CONFIG_KEYS = [...RUNTIME_CONFIG_KEYS, ...Object.keys(BUILD_KEYS)]
|
|
22
22
|
|
package/src/plugins/context.ts
CHANGED
|
@@ -61,6 +61,21 @@ export function runWithAppContext<T>(ctx: AppRuntimeContext, fn: () => T): T {
|
|
|
61
61
|
return appStorage.run(ctx, fn)
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
// Bun does not carry an AsyncLocalStorage store into the top level of a module imported inside `run()` (1.4.5), so the context of a config being imported is also kept here.
|
|
65
|
+
let importing: AppRuntimeContext | undefined
|
|
66
|
+
|
|
67
|
+
/** Imports with `ctx` as the app context, the imported modules' top-level code included. */
|
|
68
|
+
export async function importWithAppContext<T>(ctx: AppRuntimeContext, load: () => Promise<T>): Promise<T> {
|
|
69
|
+
const outer = importing
|
|
70
|
+
importing = ctx
|
|
71
|
+
try {
|
|
72
|
+
return await runWithAppContext(ctx, load)
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
importing = outer
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
64
79
|
export function getAppContext(): AppRuntimeContext | undefined {
|
|
65
|
-
return appStorage.getStore()
|
|
80
|
+
return appStorage.getStore() ?? importing
|
|
66
81
|
}
|
package/src/plugins/load.ts
CHANGED
|
@@ -6,7 +6,8 @@ import { AsyncLocalStorage } from 'node:async_hooks'
|
|
|
6
6
|
import { existsSync, readFileSync } from 'node:fs'
|
|
7
7
|
import { join, relative, resolve, sep } from 'node:path'
|
|
8
8
|
import { assertKnownConfigKeys } from './config'
|
|
9
|
-
import {
|
|
9
|
+
import { devFromEnv } from '../server/env'
|
|
10
|
+
import { createAppContext, getAppContext, importWithAppContext } from './context'
|
|
10
11
|
|
|
11
12
|
let configReloadSeq = 0
|
|
12
13
|
const PRUNELLE_SRC_DIR = resolve(import.meta.dir, '..')
|
|
@@ -43,7 +44,7 @@ export async function loadConfig(
|
|
|
43
44
|
if (!existsSync(configPath))
|
|
44
45
|
return {}
|
|
45
46
|
const active = options?.appContext ?? getAppContext()
|
|
46
|
-
const isDev = options?.dev ?? active?.dev ?? (
|
|
47
|
+
const isDev = options?.dev ?? active?.dev ?? devFromEnv()
|
|
47
48
|
const resolvedNodeEnv = options?.nodeEnv ?? active?.nodeEnv
|
|
48
49
|
const isFresh = options?.fresh ?? (freshConfigStorage.getStore() === true)
|
|
49
50
|
if (isFresh)
|
|
@@ -61,7 +62,7 @@ export async function loadConfig(
|
|
|
61
62
|
})
|
|
62
63
|
let mod: { default?: PrunelleConfig }
|
|
63
64
|
try {
|
|
64
|
-
mod = await
|
|
65
|
+
mod = await importWithAppContext(ctx, () => import(spec)) as { default?: PrunelleConfig }
|
|
65
66
|
}
|
|
66
67
|
catch (error) {
|
|
67
68
|
// Several syntax errors arrive together; the first one names the line to fix.
|
package/src/plugins/public.ts
CHANGED
|
@@ -8,8 +8,8 @@ export type { FirstLoad, Locate } from '../build/first-load'
|
|
|
8
8
|
export { brotliSize } from '../build/precompress'
|
|
9
9
|
export { minifyCss } from '../build/style-bundles'
|
|
10
10
|
export { defineConfig, definePlugin } from './config'
|
|
11
|
-
export { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, JOBS_SERVICE,
|
|
11
|
+
export { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, JOBS_SERVICE, serviceKey, UI_KUI_LAYER_SERVICE, WEB_MANIFEST_SERVICE } from './services'
|
|
12
12
|
export type { AccessedContentEntry, ActiveI18nConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, JobsEnqueueOptions, JobsQueueOptions, JobsService, ServiceKey, WebManifestIcon, WebManifestInfo } from './services'
|
|
13
13
|
export type { ComplianceConfig, ComplianceRule } from '../compiler/compliance'
|
|
14
14
|
export type { ConsentConfig } from '../server/consent'
|
|
15
|
-
export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
|
|
15
|
+
export type { BudgetConfig, BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
|
package/src/plugins/services.ts
CHANGED
|
@@ -23,6 +23,9 @@ export interface ActiveI18nConfig {
|
|
|
23
23
|
|
|
24
24
|
export const I18N_CONFIG_SERVICE = serviceKey<ActiveI18nConfig>('prunelle.i18n.config')
|
|
25
25
|
|
|
26
|
+
/** Set by `@prunellejs/ui` when it emits its grammar layer, so `@prunellejs/tailwind` places the `kui` layer between its base and utilities layers. */
|
|
27
|
+
export const UI_KUI_LAYER_SERVICE = serviceKey<boolean>('prunelle.ui.kuiLayer')
|
|
28
|
+
|
|
26
29
|
export interface ContentImageResult {
|
|
27
30
|
src: string
|
|
28
31
|
srcset?: string | undefined
|
package/src/plugins/types.ts
CHANGED
|
@@ -84,6 +84,8 @@ export interface FinalizeBuildContext {
|
|
|
84
84
|
export interface CheckPluginContext {
|
|
85
85
|
readonly root: string
|
|
86
86
|
readonly routesDir: string
|
|
87
|
+
/** The app's own static folder (`publicDir`, `public/` by default), as `prunelle check` resolved it. */
|
|
88
|
+
readonly publicDir?: string | undefined
|
|
87
89
|
/** Report a validation error from `prunelle check`. */
|
|
88
90
|
error(message: string): void
|
|
89
91
|
/** Report what may be intended but usually is not; `prunelle check --strict` fails on it. */
|
|
@@ -98,6 +100,8 @@ export interface RequiresPluginContext {
|
|
|
98
100
|
readonly root: string
|
|
99
101
|
/** `PrunelleConfig.site`, when the app sets it. */
|
|
100
102
|
readonly site: string | undefined
|
|
103
|
+
/** The categories `consent.categories` declares, `essential` left out; empty when the app declares none. */
|
|
104
|
+
readonly consentCategories: readonly string[]
|
|
101
105
|
}
|
|
102
106
|
|
|
103
107
|
export interface PluginRouteOptions {
|
|
@@ -132,6 +136,8 @@ export interface ServerPluginAPI {
|
|
|
132
136
|
readonly assetPrefix: string
|
|
133
137
|
readonly site?: string | undefined
|
|
134
138
|
readonly dev: boolean
|
|
139
|
+
/** True when `prunelle dev --host` binds an address other machines reach (`0.0.0.0`, a LAN address): a dev-only route that writes or reveals data then needs a guard. */
|
|
140
|
+
readonly devExposed: boolean
|
|
135
141
|
/** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
|
|
136
142
|
readonly trustProxy: TrustProxy
|
|
137
143
|
readonly trustedOrigins: readonly string[]
|
|
@@ -141,7 +147,7 @@ export interface ServerPluginAPI {
|
|
|
141
147
|
use(middleware: Middleware, options?: MiddlewareOptions): void
|
|
142
148
|
/** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
|
|
143
149
|
route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
|
|
144
|
-
/** A limiter counting in this server's store, for limits a route option cannot express (per account, per email): `hit(key)` returns 0, or the seconds to wait. */
|
|
150
|
+
/** A limiter counting in this server's store, for limits a route option cannot express (per account, per email): `hit(key)` returns 0, or the seconds to wait, and `peek(key)` answers the same without counting. */
|
|
145
151
|
rateLimiter(limit: Pick<RateLimit, 'max' | 'windowMs'>): RateLimiter
|
|
146
152
|
/** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
|
|
147
153
|
rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
|
|
@@ -198,7 +204,7 @@ export interface PrunellePlugin {
|
|
|
198
204
|
/** Code transform run during client & server compilation (`.ts` and `.tsx`). */
|
|
199
205
|
transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
|
|
200
206
|
/** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
|
|
201
|
-
bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
|
|
207
|
+
bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget, lang?: string | undefined }) => BunPlugin[]) | undefined
|
|
202
208
|
/** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
|
|
203
209
|
css?: string[] | undefined
|
|
204
210
|
/** Mutate `<html lang>`, `htmlAttrs`, `<title>`, or append tags to `<head>` before core renders the document once. */
|
|
@@ -260,4 +266,13 @@ export interface PrunelleConfig extends ServerRuntimeConfig {
|
|
|
260
266
|
compliance?: ComplianceConfig | undefined
|
|
261
267
|
/** Automatically prerender static pages that read nothing from the request or clock (and have no middleware or `cache` export). */
|
|
262
268
|
autoPrerender?: boolean | undefined
|
|
269
|
+
/** Page weight caps `prunelle build` fails on: bytes, or a size like `'40kb'`. */
|
|
270
|
+
budget?: BudgetConfig | undefined
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export interface BudgetConfig {
|
|
274
|
+
/** Eager JS per route, gzipped (`--max-js` overrides it for one run). */
|
|
275
|
+
js?: number | string | undefined
|
|
276
|
+
/** What a first visit downloads, brotli: the stylesheets, scripts and fonts, and on a prerendered page its HTML and every image. */
|
|
277
|
+
firstLoad?: number | string | undefined
|
|
263
278
|
}
|
|
@@ -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
|
}
|