@timber-js/app 0.2.0-alpha.218 → 0.2.0-alpha.219
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/agent-skill.md +5 -5
- package/dist/_chunks/{actions-CUh3cClk.js → actions-BwkmAYXq.js} +8 -1
- package/dist/_chunks/{actions-CUh3cClk.js.map → actions-BwkmAYXq.js.map} +1 -1
- package/dist/client/form.d.ts +34 -37
- package/dist/client/form.d.ts.map +1 -1
- package/dist/client/index.d.ts +3 -3
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +40 -75
- package/dist/client/index.js.map +1 -1
- package/dist/client/{use-form-field.d.ts → use-field-state.d.ts} +10 -7
- package/dist/client/use-field-state.d.ts.map +1 -0
- package/dist/config-types.d.ts +15 -18
- package/dist/config-types.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/plugins/shims.d.ts.map +1 -1
- package/dist/server/action-client.d.ts +11 -172
- package/dist/server/action-client.d.ts.map +1 -1
- package/dist/server/action-handler.d.ts +0 -7
- package/dist/server/action-handler.d.ts.map +1 -1
- package/dist/server/action-schema.d.ts +126 -0
- package/dist/server/action-schema.d.ts.map +1 -0
- package/dist/server/action-types.d.ts +108 -0
- package/dist/server/action-types.d.ts.map +1 -0
- package/dist/server/form-data.d.ts +7 -0
- package/dist/server/form-data.d.ts.map +1 -1
- package/dist/server/index.d.ts +3 -2
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +511 -148
- package/dist/server/index.js.map +1 -1
- package/dist/server/internal.js +1 -1
- package/dist/server/rsc-entry/action-dispatcher.d.ts +0 -3
- package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/schema-introspection.d.ts +68 -0
- package/dist/server/schema-introspection.d.ts.map +1 -0
- package/dist/server/sensitive-fields.d.ts +40 -26
- package/dist/server/sensitive-fields.d.ts.map +1 -1
- package/docs/api/31-api-client.mdx +19 -18
- package/docs/api/34-api-config.mdx +1 -1
- package/docs/learn/08-forms-and-actions.mdx +57 -23
- package/package.json +1 -1
- package/src/client/form.tsx +57 -108
- package/src/client/index.ts +3 -3
- package/src/client/{use-form-field.ts → use-field-state.ts} +20 -8
- package/src/config-types.ts +15 -18
- package/src/plugins/shims.ts +0 -1
- package/src/server/action-client.ts +82 -307
- package/src/server/action-handler.ts +1 -42
- package/src/server/action-schema.ts +203 -0
- package/src/server/action-types.ts +145 -0
- package/src/server/form-data.ts +7 -0
- package/src/server/index.ts +5 -3
- package/src/server/rsc-entry/action-dispatcher.ts +0 -4
- package/src/server/rsc-entry/index.ts +1 -2
- package/src/server/schema-introspection.ts +393 -0
- package/src/server/sensitive-fields.ts +115 -58
- package/dist/client/use-form-field.d.ts.map +0 -1
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/shared/redirect-type.ts","../../src/server/sensitive-fields.ts","../../src/server/action-client.ts"],"sourcesContent":["/**\n * Next.js redirect type discriminator.\n *\n * Provided for API compatibility with libraries that import `RedirectType`\n * from `next/navigation`. In timber, `redirect()` always uses `replace`\n * semantics (no history entry for the redirect itself).\n *\n * Lives in shared/ (isomorphic) so both the server primitives and the\n * client-only next/navigation shim export the same definition without the\n * client shim pulling in server code.\n */\nexport const RedirectType = {\n push: 'push',\n replace: 'replace',\n} as const;\n\nexport type RedirectTypeValue = (typeof RedirectType)[keyof typeof RedirectType];\n","/**\n * Sensitive field stripping — removes password/token/CVV-style fields\n * from form values before they are echoed back to the client as\n * `submittedValues` for form repopulation.\n *\n * Applied to both action paths:\n * - With-JS action path: `createActionClient()` in `action-client.ts`\n * - No-JS form POST path: `handleFormAction()` in `action-handler.ts`\n *\n * Why: on a validation failure, timber echoes submitted form values back so\n * the user doesn't have to re-type everything. Without filtering, plaintext\n * passwords / credit-card numbers / TOTP codes would travel through the RSC\n * stream (with-JS) or land in the HTML as `defaultValue` attributes (no-JS)\n * — ending up in browser history, proxy logs, disk caches, and the\n * back-forward cache.\n *\n * Safe by default: the built-in deny-list is applied unconditionally unless\n * the user explicitly opts out via `forms.stripSensitiveFields: false` in\n * `timber.config.ts` or per-action via `createActionClient({ stripSensitiveFields: false })`.\n *\n * See design/08-forms-and-actions.md §\"Validation errors\"\n * See design/13-security.md §\"Sensitive field stripping\"\n * See TIM-816\n */\n\nimport { isDebug } from './debug.ts';\n\n// ─── Public types ────────────────────────────────────────────────────────\n\n/**\n * How to strip sensitive fields from `submittedValues`.\n *\n * - `true` / `undefined` — use the built-in deny-list (default, safe).\n * - `false` — do not strip anything (dev convenience; never do this in prod).\n * - `string[]` — additional field names to strip, merged with the built-in list.\n * - `(name) => boolean` — custom predicate, fully replaces the built-in list.\n * Return `true` to strip, `false` to keep. The `name` argument is the raw\n * (un-normalized) field name as it appeared in the submitted form.\n */\nexport type SensitiveFieldsOption = boolean | readonly string[] | ((name: string) => boolean);\n\n// ─── Built-in deny-list ──────────────────────────────────────────────────\n\n/**\n * Substring patterns matched against the normalized field name.\n * Normalization = lowercase + strip `_` and `-`.\n *\n * Any field whose normalized name *contains* one of these strings is\n * considered sensitive. Entries like `currentPassword`, `passwordConfirmation`,\n * and `user.password` all match via the `password` substring.\n */\nconst BUILTIN_SUBSTRING_PATTERNS: readonly string[] = [\n 'password',\n 'passwd',\n 'pwd',\n 'secret',\n 'apikey',\n 'accesstoken',\n 'refreshtoken',\n 'cvv',\n 'cvc',\n 'cardnumber',\n 'cardcvc',\n 'ssn',\n 'socialsecuritynumber',\n 'otp',\n 'totp',\n 'mfacode',\n 'twofactorcode',\n 'privatekey',\n];\n\n/**\n * Exact matches against the normalized field name. These are field names that\n * are too short or too common to substring-match safely. e.g. `token` alone\n * would match `csrfToken`, which is not sensitive — so `token` is exact-only,\n * while legitimate token fields are covered by `accesstoken` / `refreshtoken`.\n */\nconst BUILTIN_EXACT_PATTERNS: readonly string[] = ['token'];\n\n/**\n * Normalize a field name for deny-list comparison.\n * Lowercases the string and strips `_` and `-` so camelCase, snake_case, and\n * kebab-case variants all compare equal (`api_key` / `apiKey` / `api-key` →\n * `apikey`).\n */\nfunction normalize(name: string): string {\n let out = '';\n for (let i = 0; i < name.length; i++) {\n const ch = name.charCodeAt(i);\n if (ch === 0x5f /* _ */ || ch === 0x2d /* - */) continue;\n // A-Z → a-z\n if (ch >= 0x41 && ch <= 0x5a) {\n out += String.fromCharCode(ch + 32);\n } else {\n out += name[i];\n }\n }\n return out;\n}\n\n/**\n * Check whether a name matches the built-in deny-list (with optional extras).\n * Extras are merged into the substring pattern list after normalization.\n */\nfunction isBuiltinSensitive(name: string, extras?: readonly string[]): boolean {\n const normalized = normalize(name);\n if (BUILTIN_EXACT_PATTERNS.includes(normalized)) return true;\n for (const pattern of BUILTIN_SUBSTRING_PATTERNS) {\n if (normalized.includes(pattern)) return true;\n }\n if (extras && extras.length > 0) {\n for (const extra of extras) {\n const normExtra = normalize(extra);\n if (normExtra.length === 0) continue;\n if (normalized.includes(normExtra)) return true;\n }\n }\n return false;\n}\n\n// ─── Predicate resolution ────────────────────────────────────────────────\n\n/**\n * A resolved predicate: `null` means \"don't strip anything\" (the option was\n * explicitly `false`). Otherwise a function from raw field name → boolean.\n */\nexport type ResolvedSensitivePredicate = ((name: string) => boolean) | null;\n\n/**\n * Resolve a `SensitiveFieldsOption` into a concrete predicate.\n * Precedence: per-action > global > built-in default.\n *\n * - Per-action `undefined` → fall back to global.\n * - Global `undefined` → use built-in list.\n * - Either level set to `false` → disable stripping entirely (returns `null`).\n * - `true` → built-in list.\n * - `string[]` → built-in ∪ extras.\n * - function → custom, replaces the built-in list entirely.\n */\nexport function resolveSensitivePredicate(\n perAction: SensitiveFieldsOption | undefined,\n global: SensitiveFieldsOption | undefined\n): ResolvedSensitivePredicate {\n const chosen = perAction !== undefined ? perAction : global;\n\n if (chosen === false) return null;\n if (chosen === undefined || chosen === true) {\n return (name) => isBuiltinSensitive(name);\n }\n if (typeof chosen === 'function') {\n return chosen;\n }\n // Array of extra names merged with the built-in list.\n const extras = chosen;\n return (name) => isBuiltinSensitive(name, extras);\n}\n\n// ─── Module-level global config ──────────────────────────────────────────\n\nlet globalConfig: SensitiveFieldsOption | undefined;\n\n/**\n * Set the global `forms.stripSensitiveFields` config from `timber.config.ts`.\n * Called once at startup from `rsc-entry`.\n */\nexport function setGlobalSensitiveFieldsConfig(option: SensitiveFieldsOption | undefined): void {\n globalConfig = option;\n}\n\n/** Read the global `forms.stripSensitiveFields` config. */\nexport function getGlobalSensitiveFieldsConfig(): SensitiveFieldsOption | undefined {\n return globalConfig;\n}\n\n// ─── Stripping ───────────────────────────────────────────────────────────\n\n// One warning per field name per process — prevents log spam when a form is\n// submitted many times in dev mode.\nconst warnedFields = new Set<string>();\n\nfunction warnStripped(name: string): void {\n if (!isDebug()) return;\n if (warnedFields.has(name)) return;\n warnedFields.add(name);\n console.warn(\n `[timber] stripped sensitive field \"${name}\" from submittedValues. ` +\n `Override via forms.stripSensitiveFields in timber.config.ts.`\n );\n}\n\n/**\n * Walk an object (recursively) and return a copy with every key matching\n * `predicate` removed. Nested objects like `{ user: { password: '...' } }`\n * are handled — `user.password` is stripped while other `user.*` fields remain.\n *\n * - Arrays are walked element-wise (object entries inside arrays are cleaned).\n * - Non-plain values (strings, numbers, Files, Dates, etc.) are returned as-is.\n * - When a stripped key is encountered, it is omitted from the result entirely\n * — we do NOT set it to an empty string, because that would overwrite a\n * valid `defaultValue` the form author might have set.\n */\nexport function stripSensitiveFields<T>(value: T, predicate: ResolvedSensitivePredicate): T {\n // Null predicate = stripping disabled entirely.\n if (predicate === null) return value;\n if (value === null || value === undefined) return value;\n if (typeof value !== 'object') return value;\n if (value instanceof File || value instanceof Date) return value;\n\n if (Array.isArray(value)) {\n return value.map((item) => stripSensitiveFields(item, predicate)) as unknown as T;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {\n if (predicate(key)) {\n warnStripped(key);\n continue;\n }\n result[key] = stripSensitiveFields(nested, predicate);\n }\n return result as unknown as T;\n}\n\n// ─── Test helpers ────────────────────────────────────────────────────────\n\n/** Reset the \"warned once\" cache. Exposed for tests. */\nexport function __resetSensitiveFieldsWarnings(): void {\n warnedFields.clear();\n}\n","/**\n * createActionClient — typed middleware and schema validation for server actions.\n *\n * Inspired by next-safe-action. Provides a builder API:\n * createActionClient({ middleware }) → .schema(z.object(...)) → .action(fn)\n *\n * The resulting action function satisfies both:\n * 1. Direct call: action(input) → Promise<ActionResult>\n * 2. React useActionState: (prevState, formData) => Promise<ActionResult>\n *\n * See design/08-forms-and-actions.md §\"Middleware and Server Actions\"\n */\n\n// ─── ActionError ─────────────────────────────────────────────────────────\n\n/**\n * Typed error class for server actions. Carries a string code and optional data.\n * When thrown from middleware or the action body, the action short-circuits and\n * the client receives `result.serverError`.\n *\n * In production, unexpected errors (non-ActionError) return `{ code: 'INTERNAL_ERROR' }`\n * with no message. In dev, `data.message` is included.\n */\nexport class ActionError<TCode extends string = string> extends Error {\n readonly code: TCode;\n readonly data: Record<string, unknown> | undefined;\n\n constructor(code: TCode, data?: Record<string, unknown>) {\n super(`ActionError: ${code}`);\n this.name = 'ActionError';\n this.code = code;\n this.data = data;\n }\n}\n\n// ─── Standard Schema ──────────────────────────────────────────────────────\n\n/**\n * Standard Schema v1 interface (subset).\n * Zod ≥3.24, Valibot ≥1.0, and ArkType all implement this.\n * See https://github.com/standard-schema/standard-schema\n *\n * We use permissive types here to accept all compliant libraries without\n * requiring exact structural matches on issues/path shapes.\n */\ninterface StandardSchemaV1<Output = unknown> {\n readonly '~standard': {\n readonly validate: (\n value: unknown\n ) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;\n };\n}\n\ntype StandardSchemaResult<Output> =\n | { value: Output; issues?: undefined }\n | { value?: undefined; issues: ReadonlyArray<StandardSchemaIssue> };\n\ninterface StandardSchemaIssue {\n message: string;\n path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;\n}\n\n/** Check if a schema implements the Standard Schema protocol. */\nfunction isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n '~standard' in schema &&\n typeof (schema as StandardSchemaV1)['~standard'].validate === 'function'\n );\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────\n\n/**\n * Minimal schema interface — compatible with Zod, Valibot, ArkType, etc.\n *\n * Accepts either:\n * - Standard Schema (preferred): any object with `~standard.validate()`\n * - Legacy parse interface: objects with `.parse()` / `.safeParse()`\n *\n * At runtime, Standard Schema is detected via `~standard` property and\n * takes priority over the legacy interface.\n */\nexport type ActionSchema<T = unknown> = StandardSchemaV1<T> | LegacyActionSchema<T>;\n\n/** Legacy schema interface with .parse() / .safeParse(). */\ninterface LegacyActionSchema<T = unknown> {\n 'parse'(data: unknown): T;\n 'safeParse'?(data: unknown): { success: true; data: T } | { success: false; error: SchemaError };\n // Exclude Standard Schema objects from matching this interface\n '~standard'?: never;\n}\n\n/** Schema validation error shape (for legacy .safeParse()/.parse() interface). */\nexport interface SchemaError {\n issues?: Array<{ path?: Array<string | number>; message: string }>;\n flatten?(): { fieldErrors: Record<string, string[]> };\n}\n\n/** Flattened validation errors keyed by field name. */\nexport type ValidationErrors = Record<string, string[]>;\n\n/** Middleware function: returns context to merge into the action body's ctx. */\nexport type ActionMiddleware<TCtx = Record<string, unknown>> = () => Promise<TCtx> | TCtx;\n\n/** The result type returned to the client. */\nexport type ActionResult<TData = unknown> =\n | { data: TData; validationErrors?: never; serverError?: never; submittedValues?: never }\n | {\n data?: never;\n validationErrors: ValidationErrors;\n serverError?: never;\n /** Raw input values on validation failure — for repopulating form fields. */\n submittedValues?: Record<string, unknown>;\n }\n | {\n data?: never;\n validationErrors?: never;\n serverError: { code: string; data?: Record<string, unknown> };\n /**\n * The submitted form, when the input was FormData — for repopulating\n * form fields, which React resets after the action (TIM-1573).\n */\n submittedValues?: Record<string, unknown>;\n };\n\n/** Context passed to the action body. */\nexport interface ActionContext<TCtx, TInput> {\n ctx: TCtx;\n input: TInput;\n}\n\n// ─── Builder ─────────────────────────────────────────────────────────────\n\ninterface ActionClientConfig<TCtx> {\n middleware?: ActionMiddleware<TCtx> | ActionMiddleware<Record<string, unknown>>[];\n /** Max file size in bytes. Files exceeding this are rejected with validation errors. */\n fileSizeLimit?: number;\n /**\n * Override the sensitive-field deny-list for this action client.\n * See `SensitiveFieldsOption` in `./sensitive-fields.ts`. Per-action config\n * takes precedence over the global `forms.stripSensitiveFields` option in\n * `timber.config.ts`. See design/08-forms-and-actions.md and TIM-816.\n */\n stripSensitiveFields?: SensitiveFieldsOption;\n}\n\n/** Intermediate builder returned by createActionClient(). */\nexport interface ActionBuilder<TCtx> {\n /** Declare the input schema. Validation errors are returned typed. */\n schema<TInput>(schema: ActionSchema<TInput>): ActionBuilderWithSchema<TCtx, TInput>;\n /** Define the action body without input validation. */\n action<TData>(\n fn: (ctx: ActionContext<TCtx, undefined>) => Promise<TData>\n ): ActionFn<TData, undefined>;\n}\n\n/** Builder after .schema() has been called. */\nexport interface ActionBuilderWithSchema<TCtx, TInput> {\n /** Define the action body with validated input. */\n action<TData>(fn: (ctx: ActionContext<TCtx, TInput>) => Promise<TData>): ActionFn<TData, TInput>;\n}\n\n/**\n * The final action function. Callable three ways:\n * - Direct: action(input) → Promise<ActionResult<TData>>\n * - React useActionState: action(prevState, payload) → Promise<ActionResult<TData>>,\n * where payload is the submitted FormData or the value dispatch was called with\n * - React <form action={fn}>: action(formData) → void (return value ignored by React)\n *\n * The third overload exists purely for type compatibility with React's\n * `<form action>` prop, which expects `(formData: FormData) => void`.\n * At runtime the function still returns Promise<ActionResult>, but React\n * discards it. This lets validated actions be passed directly to forms\n * without casts.\n */\n/**\n * Map schema output keys to `string | undefined` for form-facing APIs.\n * HTML form values are always strings, and fields can be absent.\n * Gives autocomplete for field names without lying about value types.\n */\nexport type InputHint<T> =\n T extends Record<string, unknown> ? { [K in keyof T]: string | undefined } : T;\n\n/**\n * ActionFn — the callable returned by `createActionClient().action()`.\n *\n * Generic order: `<TData, TInput>` — TData first for backward compatibility.\n * Previously ActionFn had a single `<TData>` generic, so existing code like\n * `ActionFn<MyResult>` must still work with TData in the first position.\n * See TIM-797.\n */\nexport type ActionFn<TData = unknown, TInput = unknown> = {\n /** <form action={fn}> compatibility — React discards the return value. */\n (formData: FormData): void;\n /** Direct call: action(input) — optional when TInput is undefined/unknown (no-schema actions). */\n (\n ...args: undefined extends TInput ? [input?: TInput] : [input: TInput]\n ): Promise<ActionResult<TData>>;\n /**\n * React useActionState: action(prevState, payload). The payload is the\n * submitted FormData, or whatever the hook's dispatch was called with.\n */\n (prevState: ActionResult<TData> | null, payload: TInput | FormData): Promise<ActionResult<TData>>;\n};\n\n// ─── Implementation ──────────────────────────────────────────────────────\n\n/**\n * Run middleware array or single function. Returns merged context.\n */\nasync function runActionMiddleware<TCtx>(\n middleware: ActionMiddleware<TCtx> | ActionMiddleware<Record<string, unknown>>[] | undefined\n): Promise<TCtx> {\n if (!middleware) {\n return {} as TCtx;\n }\n\n if (Array.isArray(middleware)) {\n let merged = {} as Record<string, unknown>;\n for (const mw of middleware) {\n const result = await mw();\n merged = { ...merged, ...result };\n }\n return merged as TCtx;\n }\n\n return await middleware();\n}\n\n// Re-export parseFormData for use throughout the framework\nimport { parseFormData } from './form-data.ts';\nimport { formatSize } from '../utils/format.ts';\nimport { isDebug, isDevMode } from './debug.ts';\nimport { isDenySignal, isRedirectSignal } from './signal-identity.ts';\nimport {\n stripSensitiveFields,\n resolveSensitivePredicate,\n getGlobalSensitiveFieldsConfig,\n type SensitiveFieldsOption,\n} from './sensitive-fields.ts';\n\n/**\n * Extract validation errors from a schema error.\n * Supports Zod's flatten() and generic issues array.\n */\nfunction extractValidationErrors(error: SchemaError): ValidationErrors {\n // Zod-style flatten\n if (typeof error.flatten === 'function') {\n return error.flatten().fieldErrors;\n }\n\n // Generic issues array\n if (error.issues) {\n const errors: ValidationErrors = {};\n for (const issue of error.issues) {\n const path = issue.path?.join('.') ?? '_root';\n if (!errors[path]) errors[path] = [];\n errors[path].push(issue.message);\n }\n return errors;\n }\n\n return { _root: ['Validation failed'] };\n}\n\n/**\n * Extract validation errors from Standard Schema issues.\n */\nfunction extractStandardSchemaErrors(issues: ReadonlyArray<StandardSchemaIssue>): ValidationErrors {\n const errors: ValidationErrors = {};\n for (const issue of issues) {\n const path =\n issue.path\n ?.map((p) => {\n // Standard Schema path items can be { key: ... } objects or bare PropertyKey values\n if (typeof p === 'object' && p !== null && 'key' in p) return String(p.key);\n return String(p);\n })\n .join('.') ?? '_root';\n if (!errors[path]) errors[path] = [];\n errors[path].push(issue.message);\n }\n return Object.keys(errors).length > 0 ? errors : { _root: ['Validation failed'] };\n}\n\n/**\n * Wrap unexpected errors into a safe server error result.\n * ActionError → typed result. Other errors → INTERNAL_ERROR (no leak).\n *\n * `createActionClient` actions only. A raw `'use server'` function that\n * throws is rejected on the client instead (action-handler.ts).\n */\nexport function handleActionError(error: unknown): {\n serverError: { code: string; data?: Record<string, unknown> };\n} {\n if (error instanceof ActionError) {\n return {\n serverError: {\n code: error.code,\n ...(error.data ? { data: error.data } : {}),\n },\n };\n }\n\n // In dev, include the message for debugging.\n // Uses isDevMode() — NOT isDebug() — because this data is sent to the\n // browser. TIMBER_DEBUG must never cause error messages to leak to clients.\n // See design/13-security.md principle 4: \"Errors don't leak.\"\n const devMode = isDevMode();\n return {\n serverError: {\n code: 'INTERNAL_ERROR',\n ...(devMode && error instanceof Error ? { data: { message: error.message } } : {}),\n },\n };\n}\n\n/**\n * Create a typed action client with middleware and schema validation.\n *\n * @example\n * ```ts\n * const action = createActionClient({\n * middleware: async () => {\n * const user = await getUser()\n * if (!user) throw new ActionError('UNAUTHORIZED')\n * return { user }\n * },\n * })\n *\n * export const createTodo = action\n * .schema(z.object({ title: z.string().min(1) }))\n * .action(async ({ input, ctx }) => {\n * await db.todos.create({ ...input, userId: ctx.user.id })\n * })\n * ```\n */\nexport function createActionClient<TCtx = Record<string, never>>(\n config: ActionClientConfig<TCtx> = {}\n): ActionBuilder<TCtx> {\n function buildAction<TInput, TData>(\n schema: ActionSchema<TInput> | undefined,\n fn: (ctx: ActionContext<TCtx, TInput>) => Promise<TData>\n ): ActionFn<TData, TInput> {\n async function actionHandler(...args: unknown[]): Promise<ActionResult<TData>> {\n // The input is the last argument in every call shape: `(input)`,\n // `(formData)`, `(prevState, payload)` from useActionState's\n // dispatch, `(initialState, formData)` on the no-JS path (Fizz binds\n // the initial state into the form, and decodeAction binds the\n // FormData after it), and `(...bound, prevState, payload)` for an\n // action with bound arguments. Nothing before it is input:\n // `prevState` comes from the client, so it is never read.\n const last = args.at(-1);\n const form = last instanceof FormData ? parseFormData(last) : undefined;\n\n // Resolve the sensitive-field stripping predicate once per invocation.\n // Precedence: per-action (config.stripSensitiveFields) > global\n // (forms.stripSensitiveFields from timber.config.ts) > built-in deny-list.\n // See TIM-816.\n const sensitivePredicate = resolveSensitivePredicate(\n config.stripSensitiveFields,\n getGlobalSensitiveFieldsConfig()\n );\n\n // A \"safe-to-echo\" copy of the input. Files are stripped (can't\n // serialize, shouldn't echo back) and sensitive fields (passwords,\n // tokens, CVV, etc.) are removed before they would land in the RSC\n // payload → client form `defaultValue` → DOM.\n const echo = (value: unknown): Record<string, unknown> | undefined => {\n const withoutFiles = stripFiles(value);\n if (withoutFiles === undefined) return undefined;\n return stripSensitiveFields(withoutFiles, sensitivePredicate);\n };\n\n try {\n // Run middleware\n const ctx = await runActionMiddleware(config.middleware);\n\n // Without a schema the action receives the FormData itself. Checks\n // and echoes read the parsed form: a FormData has no own entries.\n const rawInput: unknown = schema && form ? form : last;\n const submitted: unknown = form ?? rawInput;\n const buildSubmittedValues = () => echo(submitted);\n\n // Validate file sizes before schema validation.\n if (config.fileSizeLimit !== undefined && submitted && typeof submitted === 'object') {\n const fileSizeErrors = validateFileSizes(\n submitted as Record<string, unknown>,\n config.fileSizeLimit\n );\n if (fileSizeErrors) {\n return { validationErrors: fileSizeErrors, submittedValues: buildSubmittedValues() };\n }\n }\n\n // Capture submitted values for repopulation on validation failure.\n const submittedValues = schema ? buildSubmittedValues() : undefined;\n\n // Validate with schema if provided\n let input: TInput;\n if (schema) {\n if (isStandardSchema(schema)) {\n // Standard Schema protocol (Zod ≥3.24, Valibot ≥1.0, ArkType)\n const result = schema['~standard'].validate(rawInput);\n if (result instanceof Promise) {\n throw new Error(\n '[timber] createActionClient: schema returned a Promise — only sync schemas are supported.'\n );\n }\n if (result.issues) {\n const validationErrors = extractStandardSchemaErrors(result.issues);\n logValidationFailure(validationErrors);\n return { validationErrors, submittedValues };\n }\n input = result.value;\n } else if (typeof schema.safeParse === 'function') {\n const result = schema.safeParse(rawInput);\n if (!result.success) {\n const validationErrors = extractValidationErrors(result.error);\n logValidationFailure(validationErrors);\n return { validationErrors, submittedValues };\n }\n input = result.data;\n } else {\n try {\n input = schema.parse(rawInput);\n } catch (parseError) {\n const validationErrors = extractValidationErrors(parseError as SchemaError);\n logValidationFailure(validationErrors);\n return { validationErrors, submittedValues };\n }\n }\n } else {\n input = rawInput as TInput;\n }\n\n // Execute the action body\n const data = await fn({ ctx, input });\n return { data };\n } catch (error) {\n // Re-throw redirect/deny signals — these are control flow, not errors.\n // They must propagate to executeAction() which converts them to proper\n // HTTP responses (302 redirect, 4xx deny). Catching them here would\n // wrap them as INTERNAL_ERROR and break redirect()/redirectExternal()/deny().\n if (isRedirectSignal(error) || isDenySignal(error)) {\n throw error;\n }\n // A `serverError` echoes the form like a validation failure does.\n // React resets the form after the action, and a form whose defaults\n // fell back to page data would lose what the user typed (TIM-1573).\n const result = handleActionError(error);\n const submittedValues = form && echo(form);\n return submittedValues ? { ...result, submittedValues } : result;\n }\n }\n\n return actionHandler as ActionFn<TData, TInput>;\n }\n\n return {\n schema<TInput>(schema: ActionSchema<TInput>) {\n return {\n action<TData>(\n fn: (ctx: ActionContext<TCtx, TInput>) => Promise<TData>\n ): ActionFn<TData, TInput> {\n return buildAction(schema, fn);\n },\n };\n },\n action<TData>(\n fn: (ctx: ActionContext<TCtx, undefined>) => Promise<TData>\n ): ActionFn<TData, undefined> {\n return buildAction(undefined, fn as (ctx: ActionContext<TCtx, unknown>) => Promise<TData>);\n },\n };\n}\n\n// ─── validated() ────────────────────────────────────────────────────────\n\n/**\n * Convenience wrapper for the common case: validate input, run handler.\n * No middleware needed.\n *\n * @example\n * ```ts\n * 'use server'\n * import { validated } from '@timber-js/app/server'\n * import { z } from 'zod'\n *\n * export const createTodo = validated(\n * z.object({ title: z.string().min(1) }),\n * async (input) => {\n * await db.todos.create(input)\n * }\n * )\n * ```\n */\nexport function validated<TInput, TData>(\n schema: ActionSchema<TInput>,\n handler: (input: TInput) => Promise<TData>\n): ActionFn<TData, TInput> {\n return createActionClient()\n .schema(schema)\n .action(async ({ input }) => handler(input));\n}\n\n// ─── Helpers ────────────────────────────────────────────────────────────\n\n/**\n * Log validation failures in dev mode so developers can see what went wrong.\n * In production, validation errors are only returned to the client.\n */\nfunction logValidationFailure(errors: ValidationErrors): void {\n const isDev = isDebug();\n if (!isDev) return;\n\n const fields = Object.entries(errors)\n .map(([field, messages]) => ` ${field}: ${messages.join(', ')}`)\n .join('\\n');\n console.warn(`[timber] action schema validation failed:\\n${fields}`);\n}\n\n/**\n * Validate that all File objects in the input are within the size limit.\n * Returns validation errors keyed by field name, or null if all files are ok.\n * Keys are dot paths (`rows.0.file`), the form a field name and a Standard\n * Schema error use, so `getFieldError` finds a file in a list.\n */\nfunction validateFileSizes(input: Record<string, unknown>, limit: number): ValidationErrors | null {\n const limitKb = Math.round(limit / 1024);\n const limitLabel =\n limit >= 1024 * 1024 ? `${Math.round(limit / (1024 * 1024))}MB` : `${limitKb}KB`;\n\n const errors: ValidationErrors = {};\n\n function walk(obj: Record<string, unknown>, prefix: string): void {\n for (const [key, value] of Object.entries(obj)) {\n const path = prefix ? `${prefix}.${key}` : key;\n if (value instanceof File && value.size > limit) {\n errors[path] = [\n `File \"${value.name}\" (${formatSize(value.size)}) exceeds the ${limitLabel} limit`,\n ];\n } else if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const item = value[i];\n const itemPath = `${path}.${i}`;\n if (item instanceof File && item.size > limit) {\n (errors[itemPath] ??= []).push(\n `File \"${item.name}\" (${formatSize(item.size)}) exceeds the ${limitLabel} limit`\n );\n } else if (typeof item === 'object' && item !== null && !(item instanceof File)) {\n walk(item as Record<string, unknown>, itemPath);\n }\n }\n } else if (typeof value === 'object' && value !== null && !(value instanceof File)) {\n walk(value as Record<string, unknown>, path);\n }\n }\n }\n\n walk(input, '');\n return Object.keys(errors).length > 0 ? errors : null;\n}\n\n/**\n * Strip File objects from a value, returning a copy safe for serialization.\n * File objects can't be serialized and shouldn't be echoed back.\n *\n * Mirrors `parseFormData`'s output: objects and arrays at any depth, arrays\n * of arrays included. A File in an array becomes `undefined` rather than\n * being removed, so `rows.2` still names the third element (TIM-1573).\n */\nfunction stripFiles(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== 'object' || value instanceof File) return undefined;\n return stripFilesFrom(value) as Record<string, unknown>;\n}\n\nfunction stripFilesFrom(value: unknown): unknown {\n if (value instanceof File) return undefined;\n if (Array.isArray(value)) return value.map(stripFilesFrom);\n if (typeof value !== 'object' || value === null) return value;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n if (!(v instanceof File)) result[k] = stripFilesFrom(v);\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,IAAa,eAAe;CAC1B,MAAM;CACN,SAAS;AACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACqCA,IAAM,6BAAgD;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,IAAM,yBAA4C,CAAC,OAAO;;;;;;;AAQ1D,SAAS,UAAU,MAAsB;CACvC,IAAI,MAAM;CACV,KAAK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AQ,CACb,SAAS,MAAM,KAAK,KAAK,WAAW,MAAM,IAAI,EAAE,gBAAgB,WAAW,OAC7E;QACK,IAAI,MAAM,QAAQ,KAAK,GAC5B,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;IACrC,MAAM,OAAO,MAAM;IACnB,MAAM,WAAW,GAAG,KAAK,GAAG;IAC5B,IAAI,gBAAgB,QAAQ,KAAK,OAAO,OACtC,CAAC,OAAO,cAAc,CAAC,EAAA,CAAG,KACxB,SAAS,KAAK,KAAK,KAAK,WAAW,KAAK,IAAI,EAAE,gBAAgB,WAAW,OAC3E;SACK,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,EAAE,gBAAgB,OACxE,KAAK,MAAiC,QAAQ;GAElD;QACK,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,EAAE,iBAAiB,OAC3E,KAAK,OAAkC,IAAI;EAE/C;CACF;CAEA,KAAK,OAAO,EAAE;CACd,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,IAAI,SAAS;AACnD;;;;;;;;;AAUA,SAAS,WAAW,OAAqD;CACvE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,iBAAiB,MAAM,OAAO,KAAA;CACjF,OAAO,eAAe,KAAK;AAC7B;AAEA,SAAS,eAAe,OAAyB;CAC/C,IAAI,iBAAiB,MAAM,OAAO,KAAA;CAClC,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,cAAc;CACzD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,KAAK,GACvC,IAAI,EAAE,aAAa,OAAO,OAAO,KAAK,eAAe,CAAC;CAExD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["normalize"],"sources":["../../src/shared/redirect-type.ts","../../src/server/sensitive-fields.ts","../../src/server/action-schema.ts","../../src/server/schema-introspection.ts","../../src/server/action-client.ts"],"sourcesContent":["/**\n * Next.js redirect type discriminator.\n *\n * Provided for API compatibility with libraries that import `RedirectType`\n * from `next/navigation`. In timber, `redirect()` always uses `replace`\n * semantics (no history entry for the redirect itself).\n *\n * Lives in shared/ (isomorphic) so both the server primitives and the\n * client-only next/navigation shim export the same definition without the\n * client shim pulling in server code.\n */\nexport const RedirectType = {\n push: 'push',\n replace: 'replace',\n} as const;\n\nexport type RedirectTypeValue = (typeof RedirectType)[keyof typeof RedirectType];\n","/**\n * Sensitive field stripping — removes password/token/CVV-style fields from\n * the `submittedValues` a `createActionClient` action echoes back to the\n * client for form repopulation.\n *\n * **This is hygiene, not a security boundary.** `submittedValues` only ever\n * returns to the user who typed it, in the response to their own POST:\n *\n * - With JavaScript, it travels in the action's response, a non-cacheable\n * POST fetch. What remains is exposure to devtools, HAR exports and\n * TLS-inspecting proxies.\n * - Without JavaScript, it is rendered into the page's HTML as a field's\n * `defaultValue`: one uncached response, but one that view-source, the\n * back-forward cache and a shared machine can surface. OWASP advises not\n * pre-filling password fields for this reason.\n *\n * The main reason to strip is UX: a password or card field comes back empty\n * after a failed submit, as users expect.\n *\n * What is stripped: a field whose name matches the built-in deny-list (or the\n * configured option), and a field the action's schema marks sensitive with\n * `.meta({ sensitive: true })` (Valibot: `v.metadata({ sensitive: true })`),\n * at its exact path. The schema mark covers names the list misses\n * (`recoveryPhrase`) and always applies, even with the name list turned off.\n *\n * Only `createActionClient` strips, because only it builds `submittedValues`.\n * A raw `'use server'` action owns its return value: whatever it returns is\n * what the client gets, on both paths.\n *\n * See design/08-forms-and-actions.md §\"Sensitive field stripping\"\n * See design/13-security.md §\"Sensitive field stripping\"\n */\n\nimport { isDebug } from './debug.ts';\nimport type { FieldShape } from './schema-introspection.ts';\n\n// ─── Public types ────────────────────────────────────────────────────────\n\n/**\n * How to strip sensitive fields from `submittedValues`, by name.\n *\n * - `true` / `undefined` — use the built-in deny-list (default).\n * - `false` — strip no field by name. Fields the schema marks sensitive are\n * still stripped.\n * - `string[]` — additional field names to strip, merged with the built-in list.\n * - `(name) => boolean` — custom predicate, fully replaces the built-in list.\n * Return `true` to strip, `false` to keep. The `name` argument is the raw\n * (un-normalized) field name as it appeared in the submitted form.\n */\nexport type SensitiveFieldsOption = boolean | readonly string[] | ((name: string) => boolean);\n\n// ─── Built-in deny-list ──────────────────────────────────────────────────\n\n/**\n * Substring patterns matched against the normalized field name.\n * Normalization = lowercase + strip `_` and `-`.\n *\n * Any field whose normalized name *contains* one of these strings is\n * considered sensitive. Entries like `currentPassword`, `passwordConfirmation`,\n * and `user.password` all match via the `password` substring. Every pattern\n * here is long enough not to occur inside an ordinary word.\n */\nconst BUILTIN_SUBSTRING_PATTERNS: readonly string[] = [\n 'password',\n 'passwd',\n 'secret',\n 'apikey',\n 'accesstoken',\n 'refreshtoken',\n 'cardnumber',\n 'cardcvc',\n 'socialsecuritynumber',\n 'mfacode',\n 'twofactorcode',\n 'privatekey',\n];\n\n/**\n * Patterns matched at the start or end of a word of the field name. These are\n * short enough to occur inside ordinary words (`otp` in `footPath` and\n * `notpublic`, `ssn` in `class_number` and `classnumber`), so they must\n * begin or end a word: `otp`, `otpCode`, `otpcode`, `userotp`, `user_ssn`,\n * `SSNLast4`, `newpwd`, `cardcvv`.\n */\nconst BUILTIN_WORD_PATTERNS: readonly string[] = ['pwd', 'cvv', 'cvc', 'ssn', 'otp', 'totp'];\n\n/**\n * Exact matches against the normalized field name. These are field names that\n * are too short or too common to substring-match safely. e.g. `token` alone\n * would match `csrfToken`, which is not sensitive — so `token` is exact-only,\n * while legitimate token fields are covered by `accesstoken` / `refreshtoken`.\n */\nconst BUILTIN_EXACT_PATTERNS: readonly string[] = ['token'];\n\n/**\n * Normalize a field name for deny-list comparison.\n * Lowercases the string and strips `_` and `-` so camelCase, snake_case, and\n * kebab-case variants all compare equal (`api_key` / `apiKey` / `api-key` →\n * `apikey`).\n */\nfunction normalize(name: string): string {\n return name.replace(/[_-]/g, '').toLowerCase();\n}\n\n/**\n * Split a field name into lowercase words at anything that is not a letter\n * and at a lowercase-to-uppercase hump: `user_ssnLast4` → `user`, `ssn`,\n * `last`. An acronym stays joined to what follows it (`OTPcode` →\n * `otpcode`, `SSNLast` → `ssnlast`), which a start-of-word match still finds.\n */\nfunction words(name: string): string[] {\n return name\n .split(/[^A-Za-z]+|(?<=[a-z])(?=[A-Z])/)\n .filter(Boolean)\n .map((w) => w.toLowerCase());\n}\n\n/** Whether a short pattern begins or ends one of the name's words. */\nfunction hasWordPattern(name: string): boolean {\n return words(name).some((word) =>\n BUILTIN_WORD_PATTERNS.some((p) => word.startsWith(p) || word.endsWith(p))\n );\n}\n\n/**\n * Check whether a name matches the built-in deny-list (with optional extras).\n * Extras are merged into the substring pattern list after normalization.\n */\nfunction isBuiltinSensitive(name: string, extras?: readonly string[]): boolean {\n const normalized = normalize(name);\n if (BUILTIN_EXACT_PATTERNS.includes(normalized)) return true;\n for (const pattern of BUILTIN_SUBSTRING_PATTERNS) {\n if (normalized.includes(pattern)) return true;\n }\n if (hasWordPattern(name)) return true;\n if (extras && extras.length > 0) {\n for (const extra of extras) {\n const normExtra = normalize(extra);\n if (normExtra.length === 0) continue;\n if (normalized.includes(normExtra)) return true;\n }\n }\n return false;\n}\n\n// ─── Predicate resolution ────────────────────────────────────────────────\n\n/**\n * A resolved predicate: `null` means \"strip no field by name\" (the option was\n * explicitly `false`). Otherwise a function from raw field name → boolean.\n */\nexport type ResolvedSensitivePredicate = ((name: string) => boolean) | null;\n\n/**\n * Resolve a `SensitiveFieldsOption` into a concrete predicate.\n * Precedence: per-action > global > built-in default.\n *\n * - Per-action `undefined` → fall back to global.\n * - Global `undefined` → use built-in list.\n * - Either level set to `false` → no name matching (returns `null`).\n * - `true` → built-in list.\n * - `string[]` → built-in ∪ extras.\n * - function → custom, replaces the built-in list entirely.\n */\nexport function resolveSensitivePredicate(\n perAction: SensitiveFieldsOption | undefined,\n global: SensitiveFieldsOption | undefined\n): ResolvedSensitivePredicate {\n const chosen = perAction !== undefined ? perAction : global;\n\n if (chosen === false) return null;\n if (chosen === undefined || chosen === true) {\n return (name) => isBuiltinSensitive(name);\n }\n if (typeof chosen === 'function') {\n return chosen;\n }\n // Array of extra names merged with the built-in list.\n const extras = chosen;\n return (name) => isBuiltinSensitive(name, extras);\n}\n\n// ─── Module-level global config ──────────────────────────────────────────\n\nlet globalConfig: SensitiveFieldsOption | undefined;\n\n/**\n * Set the global `forms.stripSensitiveFields` config from `timber.config.ts`.\n * Called once at startup from `rsc-entry`.\n */\nexport function setGlobalSensitiveFieldsConfig(option: SensitiveFieldsOption | undefined): void {\n globalConfig = option;\n}\n\n/** Read the global `forms.stripSensitiveFields` config. */\nexport function getGlobalSensitiveFieldsConfig(): SensitiveFieldsOption | undefined {\n return globalConfig;\n}\n\n// ─── Stripping ───────────────────────────────────────────────────────────\n\n// One warning per field name per process — prevents log spam when a form is\n// submitted many times in dev mode.\nconst warnedFields = new Set<string>();\n\nfunction warnStripped(name: string, markedInSchema: boolean): void {\n if (!isDebug()) return;\n if (warnedFields.has(name)) return;\n warnedFields.add(name);\n console.warn(\n `[timber] stripped sensitive field \"${name}\" from submittedValues. ` +\n (markedInSchema\n ? `The action's schema marks it sensitive; remove the mark to echo it.`\n : `Override via forms.stripSensitiveFields in timber.config.ts.`)\n );\n}\n\n/**\n * Walk an object (recursively) and return a copy without its sensitive\n * fields: every key `predicate` matches, and every field `shape` (the\n * schema's declared shape) marks sensitive. Nested objects like\n * `{ user: { password: '...' } }` are handled — `user.password` is stripped\n * while other `user.*` fields remain.\n *\n * - Arrays are walked element-wise (object entries inside arrays are cleaned).\n * - Non-plain values (strings, numbers, Files, Dates, etc.) are returned as-is.\n * - When a stripped key is encountered, it is omitted from the result entirely\n * — we do NOT set it to an empty string, because that would overwrite a\n * valid `defaultValue` the form author might have set.\n */\nexport function stripSensitiveFields(\n value: Record<string, unknown>,\n predicate: ResolvedSensitivePredicate,\n shape?: FieldShape\n): Record<string, unknown> {\n if (predicate === null && !hasSensitive(shape)) return value;\n return stripFrom(value, predicate, shape) as Record<string, unknown>;\n}\n\nfunction stripFrom(\n value: unknown,\n predicate: ResolvedSensitivePredicate,\n shape: FieldShape | undefined\n): unknown {\n if (value === null || typeof value !== 'object') return value;\n if (value instanceof Blob || value instanceof Date) return value;\n\n if (Array.isArray(value)) {\n return value.map((item) => stripFrom(item, predicate, shape?.item));\n }\n\n // A list `parseFormData` kept as an object (an indexed list with a gap,\n // `keys.0` and `keys.2`): every value is an item.\n const indexed = shape?.item !== undefined && shape.properties === undefined;\n const result: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n const child = indexed ? shape.item : shape?.properties?.[key];\n if (child?.sensitive || predicate?.(key)) {\n warnStripped(key, child?.sensitive === true);\n continue;\n }\n result[key] = stripFrom(nested, predicate, child);\n }\n return result;\n}\n\n/** Whether `shape` marks any field at or below it sensitive. */\nfunction hasSensitive(shape: FieldShape | undefined): boolean {\n if (!shape) return false;\n if (shape.sensitive) return true;\n if (hasSensitive(shape.item)) return true;\n return Object.values(shape.properties ?? {}).some(hasSensitive);\n}\n\n// ─── Test helpers ────────────────────────────────────────────────────────\n\n/** The built-in patterns, for the docs drift test. */\nexport const __BUILTIN_SENSITIVE_PATTERNS: readonly string[] = [\n ...BUILTIN_SUBSTRING_PATTERNS,\n ...BUILTIN_WORD_PATTERNS,\n ...BUILTIN_EXACT_PATTERNS,\n];\n\n/** Reset the \"warned once\" cache. Exposed for tests. */\nexport function __resetSensitiveFieldsWarnings(): void {\n warnedFields.clear();\n}\n","/**\n * Action input schemas — the Standard Schema protocol (and the legacy\n * `.parse()` interface) as `createActionClient().schema()` accepts them, the\n * input/output types they carry, and running one against an action's input.\n *\n * See design/08-forms-and-actions.md §\"Validation Pattern\"\n */\n\nimport type { ValidationErrors } from './action-types.ts';\n\n// ─── Standard Schema ──────────────────────────────────────────────────────\n\n/**\n * Standard Schema v1 interface (subset).\n * Zod ≥3.24, Valibot ≥1.0, and ArkType all implement this.\n * See https://github.com/standard-schema/standard-schema\n *\n * `types` is the protocol's type-only carrier: a schema's input type (what a\n * caller passes, before coercion) and output type (what validation produces).\n * We use permissive types for issues and paths to accept all compliant\n * libraries without requiring exact structural matches on their shapes.\n */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': {\n readonly validate: (\n value: unknown\n ) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;\n readonly types?: { readonly input: Input; readonly output: Output } | undefined;\n };\n}\n\ntype StandardSchemaResult<Output> =\n | { value: Output; issues?: undefined }\n | { value?: undefined; issues: ReadonlyArray<StandardSchemaIssue> };\n\ninterface StandardSchemaIssue {\n message: string;\n path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;\n}\n\n/** Check if a schema implements the Standard Schema protocol. */\nexport function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n '~standard' in schema &&\n typeof (schema as StandardSchemaV1)['~standard'].validate === 'function'\n );\n}\n\n// ─── Schema types ─────────────────────────────────────────────────────────\n\n/**\n * Minimal schema interface — compatible with Zod, Valibot, ArkType, etc.\n *\n * Accepts either:\n * - Standard Schema (preferred): any object with `~standard.validate()`\n * - Legacy parse interface: objects with `.parse()` / `.safeParse()`\n *\n * At runtime, Standard Schema is detected via `~standard` property and\n * takes priority over the legacy interface.\n */\nexport type ActionSchema<T = unknown> = StandardSchemaV1<unknown, T> | LegacyActionSchema<T>;\n\n/** Legacy schema interface with .parse() / .safeParse(). */\ninterface LegacyActionSchema<T = unknown> {\n 'parse'(data: unknown): T;\n 'safeParse'?(data: unknown): { success: true; data: T } | { success: false; error: SchemaError };\n // Exclude Standard Schema objects from matching this interface\n '~standard'?: never;\n}\n\n/** Schema validation error shape (for legacy .safeParse()/.parse() interface). */\nexport interface SchemaError {\n issues?: Array<{ path?: Array<string | number>; message: string }>;\n flatten?(): { fieldErrors: Record<string, string[]> };\n}\n\n/**\n * What a validated action's body receives: the schema's output, after\n * coercion and defaults.\n */\nexport type SchemaOutput<S> = S extends { readonly '~standard': infer Std }\n ? DeclaredType<Std, 'output', ValidatedValue<S>>\n : S extends LegacyActionSchema<infer T>\n ? T\n : never;\n\n/**\n * The value a Standard Schema's `validate` produces on success, for a schema\n * that declares no `types`. Only the success branch has a required `value`.\n */\ntype ValidatedValue<S> = S extends {\n readonly '~standard': { readonly validate: (value: unknown) => infer R };\n}\n ? SuccessValue<Awaited<R>>\n : never;\n\n/** Distributes over the result union, keeping the members with a value. */\ntype SuccessValue<R> = R extends { value: infer O } ? O : never;\n\n/**\n * What a caller passes a validated action: the schema's input, before\n * coercion. A schema that declares no `types` (a hand-written Standard\n * Schema, a legacy `.parse()` schema) has one type for both.\n */\nexport type SchemaInput<S> = S extends { readonly '~standard': infer Std }\n ? DeclaredType<Std, 'input', SchemaOutput<S>>\n : SchemaOutput<S>;\n\n/**\n * `Std.types[K]` when the schema declares `types` (Zod, Valibot, ArkType do),\n * else `Fallback`. Read by key, because `types` is optional in the protocol.\n */\ntype DeclaredType<Std, K extends 'input' | 'output', Fallback> = 'types' extends keyof Std\n ? NonNullable<Std['types' & keyof Std]> extends { readonly [P in K]: infer T }\n ? T\n : Fallback\n : Fallback;\n\n// ─── Validation ───────────────────────────────────────────────────────────\n\n/** The outcome of running an action's schema over its input. */\nexport type SchemaValidation<T> =\n | { ok: true; value: T }\n | { ok: false; validationErrors: ValidationErrors };\n\n/**\n * Validate `input` with `schema`, through Standard Schema when the schema\n * implements it, and through `.safeParse()` / `.parse()` otherwise. Only\n * synchronous Standard Schema validation is supported.\n */\nexport function validateWithSchema<T>(\n schema: ActionSchema<T>,\n input: unknown\n): SchemaValidation<T> {\n if (isStandardSchema(schema)) {\n const result = schema['~standard'].validate(input);\n if (result instanceof Promise) {\n throw new Error(\n '[timber] createActionClient: schema returned a Promise — only sync schemas are supported.'\n );\n }\n if (result.issues) {\n return { ok: false, validationErrors: extractStandardSchemaErrors(result.issues) };\n }\n return { ok: true, value: result.value };\n }\n if (typeof schema.safeParse === 'function') {\n const result = schema.safeParse(input);\n if (!result.success) {\n return { ok: false, validationErrors: extractValidationErrors(result.error) };\n }\n return { ok: true, value: result.data };\n }\n try {\n return { ok: true, value: schema.parse(input) };\n } catch (parseError) {\n return { ok: false, validationErrors: extractValidationErrors(parseError as SchemaError) };\n }\n}\n\n/**\n * Extract validation errors from a schema error.\n * Supports Zod's flatten() and generic issues array.\n */\nfunction extractValidationErrors(error: SchemaError): ValidationErrors {\n // Zod-style flatten\n if (typeof error.flatten === 'function') {\n return error.flatten().fieldErrors;\n }\n\n // Generic issues array\n if (error.issues) {\n const errors: Record<string, string[]> = {};\n for (const issue of error.issues) {\n const path = issue.path?.join('.') ?? '_root';\n (errors[path] ??= []).push(issue.message);\n }\n return errors;\n }\n\n return { _root: ['Validation failed'] };\n}\n\n/**\n * Extract validation errors from Standard Schema issues.\n */\nfunction extractStandardSchemaErrors(issues: ReadonlyArray<StandardSchemaIssue>): ValidationErrors {\n const errors: Record<string, string[]> = {};\n for (const issue of issues) {\n const path =\n issue.path\n ?.map((p) => {\n // Standard Schema path items can be { key: ... } objects or bare PropertyKey values\n if (typeof p === 'object' && p !== null && 'key' in p) return String(p.key);\n return String(p);\n })\n .join('.') ?? '_root';\n (errors[path] ??= []).push(issue.message);\n }\n return Object.keys(errors).length > 0 ? errors : { _root: ['Validation failed'] };\n}\n","/**\n * Schema introspection — the shape of an action's input as its schema\n * declares it: which fields are lists, which may be absent, and which the\n * schema marks sensitive.\n *\n * Standard Schema v1 has no introspection API, so this feature-detects what\n * the libraries expose:\n *\n * - **Zod 4**: its schema tree (`_zod.def`, documented for library authors),\n * with `.meta()` for marks and `_zod.optin` for fields that may be absent.\n * Not Zod's JSON Schema: that describes a `z.preprocess(fn, z.array(…))`\n * field as the inner array, and wrapping a scalar before `fn` runs would\n * hand a comma-splitting preprocessor `['a,b']`. A preprocessed field is\n * its author's to read, so it has no shape here.\n * - **Valibot**: its schema objects (`entries`, `item`, `wrapped`, `options`),\n * with `v.metadata({ sensitive: true })` read from the pipe.\n * - **Standard JSON Schema** (`~standard.jsonSchema.input()`) for any other\n * library that implements it, such as ArkType, whose\n * `.configure({ sensitive: true })` lands in the JSON Schema node.\n *\n * Any other schema (a legacy `.parse()` schema, Zod 3, a hand-written\n * Standard Schema) has no shape: its form input is not normalized and only\n * the name deny-list strips its echo.\n *\n * A union merges its branches: a field is sensitive if any branch marks it,\n * and a list only if every branch declares it one. An intersection merges\n * its parts, which all apply: a list or sensitive if any part says so.\n *\n * `createActionClient` computes the shape once per action and keeps it on the\n * action's closure. It is used twice, by `normalizeListFields` (before\n * validation, and for `submittedValues`) and by `stripSensitiveFields`.\n *\n * See design/08-forms-and-actions.md §\"The Form Model\" and\n * §\"Sensitive field stripping\".\n */\n\nimport { isStandardSchema } from './action-schema.ts';\n\n/** The declared shape of one field (or of the whole input). */\nexport interface FieldShape {\n /** The field holds items of this shape (a list, possibly not in every union branch). */\n item?: FieldShape;\n /** Every declaration of the field is a list: normalize its form value to an array. */\n list?: boolean;\n /** The field is an object; these are its properties' shapes. */\n properties?: Record<string, FieldShape>;\n /** The field may be absent (`.optional()`, a default, a missing union branch). */\n optional?: boolean;\n /** The schema marks the field sensitive (`.meta({ sensitive: true })`). */\n sensitive?: boolean;\n}\n\n/**\n * The shape of `schema`'s input, or `undefined` when the schema library\n * exposes nothing to read it from.\n */\nexport function introspectSchema(schema: unknown): FieldShape | undefined {\n if (!isStandardSchema(schema)) return undefined;\n const standard: Record<string, unknown> = schema['~standard'];\n if (standard.vendor === 'zod' && isRecord(schema) && isRecord(schema._zod)) {\n return fromZod(schema, new Set());\n }\n if (standard.vendor === 'valibot') return fromValibot(schema, new Set());\n\n const jsonSchema = standard.jsonSchema;\n if (!isRecord(jsonSchema) || typeof jsonSchema.input !== 'function') return undefined;\n let root: unknown;\n try {\n root = jsonSchema.input({ target: 'draft-2020-12' });\n } catch {\n return undefined;\n }\n return isRecord(root) ? fromJsonSchema(root, root, new Set()) : undefined;\n}\n\n// ─── Zod 4 ───────────────────────────────────────────────────────────────\n\n/** Zod wrappers whose `innerType` is the field's real type. */\nconst ZOD_WRAPPERS = new Set([\n 'optional',\n 'nullable',\n 'default',\n 'prefault',\n 'nonoptional',\n 'readonly',\n 'catch',\n]);\n\nfunction fromZod(schema: unknown, seen: Set<unknown>): FieldShape | undefined {\n if (!isRecord(schema) || seen.has(schema) || !isRecord(schema._zod)) return undefined;\n const inner = new Set(seen).add(schema);\n const def = schema._zod.def;\n if (!isRecord(def)) return undefined;\n const marks = withMarks(schema._zod.optin === 'optional', zodSensitive(schema));\n\n switch (def.type) {\n case 'object': {\n if (!isRecord(def.shape)) return marks(undefined);\n const properties: Record<string, FieldShape> = {};\n for (const [key, child] of Object.entries(def.shape)) {\n const shape = fromZod(child, inner);\n if (shape) properties[key] = shape;\n }\n return marks({ properties });\n }\n case 'array':\n return marks({ item: fromZod(def.element, inner) ?? {}, list: true });\n case 'union':\n return marks(mergeAll(asList(def.options).map((option) => fromZod(option, inner))));\n case 'intersection':\n return marks(intersectAll([fromZod(def.left, inner), fromZod(def.right, inner)]));\n case 'pipe':\n // `z.preprocess(fn, …)` is a pipe from a transform: its author reads\n // the raw value. Any other pipe takes its input side's shape.\n if (isRecord(def.in) && isRecord(def.in._zod) && isRecord(def.in._zod.def)) {\n if (def.in._zod.def.type === 'transform') return marks(undefined);\n }\n return marks(fromZod(def.in, inner));\n default:\n if (typeof def.type === 'string' && ZOD_WRAPPERS.has(def.type)) {\n return marks(fromZod(def.innerType, inner));\n }\n return marks(undefined);\n }\n}\n\n/** `.meta()` read back: Zod returns the schema's registered metadata. */\nfunction zodSensitive(schema: Record<string, unknown>): boolean {\n if (typeof schema.meta !== 'function') return false;\n try {\n const meta: unknown = schema.meta();\n return isRecord(meta) && meta.sensitive === true;\n } catch {\n return false;\n }\n}\n\n// ─── Valibot ─────────────────────────────────────────────────────────────\n\n/** Valibot wrappers whose `wrapped` schema is the field's real type. */\nconst VALIBOT_WRAPPERS = new Set([\n 'optional',\n 'exact_optional',\n 'nullable',\n 'nullish',\n 'undefinedable',\n 'non_optional',\n 'non_nullable',\n 'non_nullish',\n]);\n\n/** Valibot wrappers that let the field be absent. */\nconst VALIBOT_OPTIONAL = new Set(['optional', 'exact_optional', 'nullish', 'undefinedable']);\n\nconst VALIBOT_OBJECTS = new Set(['object', 'loose_object', 'strict_object', 'object_with_rest']);\n\nfunction fromValibot(schema: unknown, seen: Set<unknown>): FieldShape | undefined {\n if (!isRecord(schema) || seen.has(schema)) return undefined;\n const inner = new Set(seen).add(schema);\n const sensitive =\n Array.isArray(schema.pipe) &&\n schema.pipe.some(\n (action) =>\n isRecord(action) &&\n action.kind === 'metadata' &&\n isRecord(action.metadata) &&\n action.metadata.sensitive === true\n );\n\n const type = schema.type;\n const marks = withMarks(typeof type === 'string' && VALIBOT_OPTIONAL.has(type), sensitive);\n if (typeof type !== 'string') return marks(undefined);\n if (VALIBOT_WRAPPERS.has(type)) return marks(fromValibot(schema.wrapped, inner));\n if (type === 'array') return marks({ item: fromValibot(schema.item, inner) ?? {}, list: true });\n if (type === 'union' || type === 'variant') {\n return marks(mergeAll(asList(schema.options).map((option) => fromValibot(option, inner))));\n }\n if (type === 'intersect') {\n return marks(intersectAll(asList(schema.options).map((option) => fromValibot(option, inner))));\n }\n if (VALIBOT_OBJECTS.has(type) && isRecord(schema.entries)) {\n const properties: Record<string, FieldShape> = {};\n for (const [key, child] of Object.entries(schema.entries)) {\n const shape = fromValibot(child, inner);\n if (shape) properties[key] = shape;\n }\n return marks({ properties });\n }\n return marks(undefined);\n}\n\n// ─── Standard JSON Schema ────────────────────────────────────────────────\n\nfunction fromJsonSchema(\n node: Record<string, unknown>,\n root: Record<string, unknown>,\n refs: Set<string>\n): FieldShape | undefined {\n const marks = withMarks(false, node.sensitive === true);\n const ref = node.$ref;\n if (typeof ref === 'string') {\n // A recursive schema: stop at a ref already being expanded on this path.\n if (refs.has(ref)) return marks(undefined);\n const target = resolveRef(root, ref);\n if (!target) return marks(undefined);\n return marks(fromJsonSchema(target, root, new Set(refs).add(ref)));\n }\n\n const branches = node.anyOf ?? node.oneOf;\n if (Array.isArray(branches)) {\n const shapes = branches\n .filter((b): b is Record<string, unknown> => isRecord(b) && b.type !== 'null')\n .map((b) => fromJsonSchema(b, root, refs));\n return marks(mergeAll(shapes));\n }\n\n if (Array.isArray(node.allOf)) {\n const parts = node.allOf.filter(isRecord).map((part) => fromJsonSchema(part, root, refs));\n return marks(intersectAll(parts));\n }\n\n const types = Array.isArray(node.type) ? node.type : [node.type];\n if (types.includes('array') && isRecord(node.items)) {\n return marks({ item: fromJsonSchema(node.items, root, refs) ?? {}, list: true });\n }\n if (isRecord(node.properties)) {\n const required = new Set(asList(node.required));\n const properties: Record<string, FieldShape> = {};\n for (const [key, child] of Object.entries(node.properties)) {\n const shape = isRecord(child) ? fromJsonSchema(child, root, refs) : undefined;\n if (shape) properties[key] = required.has(key) ? shape : { ...shape, optional: true };\n }\n return marks({ properties });\n }\n return marks(undefined);\n}\n\n/** Resolve a local `#/$defs/...` or `#/definitions/...` reference. */\nfunction resolveRef(\n root: Record<string, unknown>,\n ref: string\n): Record<string, unknown> | undefined {\n if (!ref.startsWith('#/')) return undefined;\n let node: unknown = root;\n for (const segment of ref.slice(2).split('/')) {\n if (!isRecord(node)) return undefined;\n node = node[segment.replaceAll('~1', '/').replaceAll('~0', '~')];\n }\n return isRecord(node) ? node : undefined;\n}\n\n// ─── Unions ──────────────────────────────────────────────────────────────\n\n/**\n * One shape for the branches of a union. A field is sensitive if any branch\n * marks it, a list only if every branch declares it one, and optional if any\n * branch lacks it. A branch with no shape makes nothing a list, but its\n * siblings' marks still apply.\n */\nfunction mergeAll(shapes: (FieldShape | undefined)[]): FieldShape | undefined {\n if (shapes.length === 0) return undefined;\n return shapes.reduce<FieldShape | undefined>(\n (merged, shape, i) => (i === 0 ? (shape ?? {}) : merge(merged ?? {}, shape ?? {})),\n undefined\n );\n}\n\nfunction merge(a: FieldShape, b: FieldShape): FieldShape {\n const out: FieldShape = {};\n if (a.sensitive || b.sensitive) out.sensitive = true;\n if (a.optional || b.optional) out.optional = true;\n if (a.list && b.list) out.list = true;\n if (a.item || b.item) out.item = merge(a.item ?? {}, b.item ?? {});\n if (a.properties || b.properties) {\n const properties: Record<string, FieldShape> = {};\n const keys = new Set([...Object.keys(a.properties ?? {}), ...Object.keys(b.properties ?? {})]);\n for (const key of keys) {\n const left = a.properties?.[key];\n const right = b.properties?.[key];\n // Present in one branch only: absent whenever the other is chosen.\n properties[key] = left && right ? merge(left, right) : { ...(left ?? right), optional: true };\n }\n out.properties = properties;\n }\n return out;\n}\n\n// ─── Intersections ──────────────────────────────────────────────────────\n\n/**\n * One shape for the parts of an intersection, which all apply: a field is a\n * list or sensitive if any part says so, and optional only if every part\n * that declares it lets it be absent.\n */\nfunction intersectAll(shapes: (FieldShape | undefined)[]): FieldShape | undefined {\n const present = shapes.filter((shape): shape is FieldShape => shape !== undefined);\n if (present.length === 0) return undefined;\n return present.reduce(intersect);\n}\n\nfunction intersect(a: FieldShape, b: FieldShape): FieldShape {\n const out: FieldShape = {};\n if (a.sensitive || b.sensitive) out.sensitive = true;\n if (a.optional && b.optional) out.optional = true;\n if (a.list || b.list) out.list = true;\n if (a.item || b.item) out.item = intersect(a.item ?? {}, b.item ?? {});\n if (a.properties || b.properties) {\n const properties: Record<string, FieldShape> = {};\n const keys = new Set([...Object.keys(a.properties ?? {}), ...Object.keys(b.properties ?? {})]);\n for (const key of keys) {\n const left = a.properties?.[key];\n const right = b.properties?.[key];\n properties[key] = left && right ? intersect(left, right) : (left ?? right ?? {});\n }\n out.properties = properties;\n }\n return out;\n}\n\n// ─── List normalization ──────────────────────────────────────────────────\n\n/**\n * Give every field the schema declares as a list the same shape whatever its\n * count. `parseFormData` reads a repeated name as an array, a single value as\n * a scalar, and an absent name not at all; here a scalar becomes `[value]`,\n * and an absent or blank required list becomes `[]` (blanks are dropped from\n * a list, as `parseFormData` drops them from a repeated name). An optional\n * list that was not submitted (or was one blank) is absent, so `.optional()` still means\n * \"not sent\". Lists inside lists and objects are normalized too. An object\n * where a list is declared (an indexed list with a gap) is left for the\n * schema to reject.\n *\n * Returns a copy; the input is not written to.\n */\nexport function normalizeListFields(\n values: Record<string, unknown>,\n shape: FieldShape | undefined\n): Record<string, unknown> {\n if (!shape) return values;\n return normalize(values, shape) as Record<string, unknown>;\n}\n\nfunction normalize(value: unknown, shape: FieldShape): unknown {\n if (shape.list && shape.item) {\n if (value === undefined || value === '') return shape.optional ? undefined : [];\n if (isPlainObject(value)) return value;\n const list = Array.isArray(value) ? value : [value];\n const item = shape.item;\n return list.map((v) => normalize(v, item));\n }\n if (shape.properties && isPlainObject(value)) {\n const out: Record<string, unknown> = { ...value };\n for (const [key, child] of Object.entries(shape.properties)) {\n // Only own keys: `out.constructor` would read Object.prototype's.\n const current = Object.hasOwn(out, key) ? out[key] : undefined;\n if (key === '__proto__') continue;\n const normalized = normalize(current, child);\n if (normalized === undefined) delete out[key];\n else out[key] = normalized;\n }\n return out;\n }\n return value;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────\n\n/** Apply a node's own marks to the shape read from what it wraps. */\nfunction withMarks(\n optional: boolean,\n sensitive: boolean\n): (shape: FieldShape | undefined) => FieldShape | undefined {\n return (shape) => {\n if (!optional && !sensitive) return shape;\n return {\n ...shape,\n ...(optional ? { optional: true } : {}),\n ...(sensitive ? { sensitive: true } : {}),\n };\n };\n}\n\nfunction asList(value: unknown): unknown[] {\n return Array.isArray(value) ? value : [];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && !Array.isArray(value) && !(value instanceof Blob);\n}\n","/**\n * createActionClient — typed middleware and schema validation for server actions.\n *\n * Inspired by next-safe-action. Provides a builder API:\n * createActionClient({ middleware }) → .schema(z.object(...)) → .action(fn)\n *\n * The resulting action function satisfies both:\n * 1. Direct call: action(input) → Promise<ActionResult>\n * 2. React useActionState: (prevState, formData) => Promise<ActionResult>\n *\n * Types live in `action-types.ts`, schema handling in `action-schema.ts`, and\n * the schema's declared shape (list fields, sensitive fields) in\n * `schema-introspection.ts`.\n *\n * See design/08-forms-and-actions.md §\"Middleware and Server Actions\"\n */\n\nimport { parseFormData } from './form-data.ts';\nimport { formatSize } from '../utils/format.ts';\nimport { isDebug, isDevMode } from './debug.ts';\nimport { isDenySignal, isRedirectSignal } from './signal-identity.ts';\nimport {\n stripSensitiveFields,\n resolveSensitivePredicate,\n getGlobalSensitiveFieldsConfig,\n type SensitiveFieldsOption,\n} from './sensitive-fields.ts';\nimport {\n validateWithSchema,\n type ActionSchema,\n type SchemaInput,\n type SchemaOutput,\n} from './action-schema.ts';\nimport { introspectSchema, normalizeListFields, type FieldShape } from './schema-introspection.ts';\nimport type {\n ActionBuilder,\n ActionContext,\n ActionFn,\n ActionMiddleware,\n ActionResult,\n ActionServerError,\n ValidationErrors,\n} from './action-types.ts';\n\n// ─── ActionError ─────────────────────────────────────────────────────────\n\n/**\n * Typed error class for server actions. Carries a string code and optional data.\n * When thrown from middleware or the action body, the action short-circuits and\n * the client receives `result.serverError`.\n *\n * In production, unexpected errors (non-ActionError) return `{ code: 'INTERNAL_ERROR' }`\n * with no message. In dev, `data.message` is included.\n */\nexport class ActionError<TCode extends string = string> extends Error {\n readonly code: TCode;\n readonly data: Record<string, unknown> | undefined;\n\n constructor(code: TCode, data?: Record<string, unknown>) {\n super(`ActionError: ${code}`);\n this.name = 'ActionError';\n this.code = code;\n this.data = data;\n }\n}\n\n// ─── Config ──────────────────────────────────────────────────────────────\n\ninterface ActionClientConfig<TCtx> {\n middleware?: ActionMiddleware<TCtx> | ActionMiddleware<Record<string, unknown>>[];\n /** Max file size in bytes. Files exceeding this are rejected with validation errors. */\n fileSizeLimit?: number;\n /**\n * Override the sensitive-field name deny-list for this action client.\n * See `SensitiveFieldsOption` in `./sensitive-fields.ts`. Per-client config\n * takes precedence over the global `forms.stripSensitiveFields` option in\n * `timber.config.ts`. Fields the schema marks `.meta({ sensitive: true })`\n * are stripped whatever this says. See design/08-forms-and-actions.md.\n */\n stripSensitiveFields?: SensitiveFieldsOption;\n}\n\n// ─── Implementation ──────────────────────────────────────────────────────\n\n/**\n * Run middleware array or single function. Returns merged context.\n */\nasync function runActionMiddleware<TCtx>(\n middleware: ActionMiddleware<TCtx> | ActionMiddleware<Record<string, unknown>>[] | undefined\n): Promise<TCtx> {\n if (!middleware) {\n return {} as TCtx;\n }\n\n if (Array.isArray(middleware)) {\n let merged = {} as Record<string, unknown>;\n for (const mw of middleware) {\n const result = await mw();\n merged = { ...merged, ...result };\n }\n return merged as TCtx;\n }\n\n return await middleware();\n}\n\n/**\n * Wrap unexpected errors into a safe server error result.\n * ActionError → typed result. Other errors → INTERNAL_ERROR (no leak).\n *\n * `createActionClient` actions only. A raw `'use server'` function that\n * throws is rejected on the client instead (action-handler.ts).\n */\nexport function handleActionError(error: unknown): { serverError: ActionServerError } {\n if (error instanceof ActionError) {\n return {\n serverError: {\n code: error.code,\n ...(error.data ? { data: error.data } : {}),\n },\n };\n }\n\n // In dev, include the message for debugging.\n // Uses isDevMode() — NOT isDebug() — because this data is sent to the\n // browser. TIMBER_DEBUG must never cause error messages to leak to clients.\n // See design/13-security.md principle 4: \"Errors don't leak.\"\n const devMode = isDevMode();\n return {\n serverError: {\n code: 'INTERNAL_ERROR',\n ...(devMode && error instanceof Error ? { data: { message: error.message } } : {}),\n },\n };\n}\n\n/**\n * Create a typed action client with middleware and schema validation.\n *\n * @example\n * ```ts\n * const action = createActionClient({\n * middleware: async () => {\n * const user = await getUser()\n * if (!user) throw new ActionError('UNAUTHORIZED')\n * return { user }\n * },\n * })\n *\n * export const createTodo = action\n * .schema(z.object({ title: z.string().min(1) }))\n * .action(async ({ input, ctx }) => {\n * await db.todos.create({ ...input, userId: ctx.user.id })\n * })\n * ```\n */\nexport function createActionClient<TCtx = Record<string, never>>(\n config: ActionClientConfig<TCtx> = {}\n): ActionBuilder<TCtx> {\n function buildAction<TInput, TOutput, TData>(\n schema: ActionSchema | undefined,\n fn: (ctx: ActionContext<TCtx, TOutput>) => Promise<TData>\n ): ActionFn<TData, TInput> {\n // The schema's declared shape, read once per action on its first call:\n // which fields are lists, and which are marked sensitive.\n let shape: FieldShape | undefined;\n let introspected = false;\n const getShape = (): FieldShape | undefined => {\n if (!introspected) {\n shape = introspectSchema(schema);\n introspected = true;\n }\n return shape;\n };\n\n async function actionHandler(...args: unknown[]): Promise<ActionResult<TData>> {\n // The input is the last argument in every call shape: `(input)`,\n // `(formData)`, `(prevState, payload)` from useActionState's\n // dispatch, `(initialState, formData)` on the no-JS path (Fizz binds\n // the initial state into the form, and decodeAction binds the\n // FormData after it), and `(...bound, prevState, payload)` for an\n // action with bound arguments. Nothing before it is input:\n // `prevState` comes from the client, so it is never read.\n const last = args.at(-1);\n // A form's list fields take the shape the schema declares whatever\n // their count, both for validation and for `submittedValues`.\n const form =\n last instanceof FormData ? normalizeListFields(parseFormData(last), getShape()) : undefined;\n\n // Precedence: per-client (config.stripSensitiveFields) > global\n // (forms.stripSensitiveFields from timber.config.ts) > built-in deny-list.\n const sensitivePredicate = resolveSensitivePredicate(\n config.stripSensitiveFields,\n getGlobalSensitiveFieldsConfig()\n );\n\n // A \"safe-to-echo\" copy of the input. Files are stripped (can't\n // serialize, shouldn't echo back) and sensitive fields (passwords,\n // tokens, CVV, schema-marked fields) are removed before they would\n // land in the RSC payload → client form `defaultValue` → DOM.\n const echo = (value: unknown): Record<string, unknown> | undefined => {\n const withoutFiles = stripFiles(value);\n if (withoutFiles === undefined) return undefined;\n return stripSensitiveFields(withoutFiles, sensitivePredicate, getShape());\n };\n\n try {\n // Run middleware\n const ctx = await runActionMiddleware(config.middleware);\n\n // Without a schema the action receives the FormData itself. Checks\n // and echoes read the parsed form: a FormData has no own entries.\n const rawInput: unknown = schema && form ? form : last;\n const submitted: unknown = form ?? rawInput;\n\n // Validate file sizes before schema validation.\n if (config.fileSizeLimit !== undefined && submitted && typeof submitted === 'object') {\n const fileSizeErrors = validateFileSizes(\n submitted as Record<string, unknown>,\n config.fileSizeLimit\n );\n if (fileSizeErrors) {\n return { validationErrors: fileSizeErrors, submittedValues: echo(submitted) };\n }\n }\n\n let input: unknown = rawInput;\n if (schema) {\n const validation = validateWithSchema(schema, rawInput);\n if (!validation.ok) {\n logValidationFailure(validation.validationErrors);\n return {\n validationErrors: validation.validationErrors,\n submittedValues: echo(submitted),\n };\n }\n input = validation.value;\n }\n\n // Execute the action body. `input` is the schema's output, or the\n // raw input when there is no schema (TOutput is `undefined` then).\n const data = await fn({ ctx, input: input as TOutput });\n return { data };\n } catch (error) {\n // Re-throw redirect/deny signals — these are control flow, not errors.\n // They must propagate to executeAction() which converts them to proper\n // HTTP responses (302 redirect, 4xx deny). Catching them here would\n // wrap them as INTERNAL_ERROR and break redirect()/redirectExternal()/deny().\n if (isRedirectSignal(error) || isDenySignal(error)) {\n throw error;\n }\n // A `serverError` echoes the form like a validation failure does.\n // React resets the form after the action, and a form whose defaults\n // fell back to page data would lose what the user typed (TIM-1573).\n const result = handleActionError(error);\n const submittedValues = form && echo(form);\n return submittedValues ? { ...result, submittedValues } : result;\n }\n }\n\n // One implementation serves every overload of `ActionFn`, which\n // TypeScript cannot check a single function against.\n return actionHandler as ActionFn<TData, TInput>;\n }\n\n return {\n schema<S extends ActionSchema>(schema: S) {\n return {\n action<TData>(\n fn: (ctx: ActionContext<TCtx, SchemaOutput<S>>) => Promise<TData>\n ): ActionFn<TData, SchemaInput<S>> {\n return buildAction(schema, fn);\n },\n };\n },\n action<TData>(\n fn: (ctx: ActionContext<TCtx, undefined>) => Promise<TData>\n ): ActionFn<TData, undefined> {\n return buildAction(undefined, fn);\n },\n };\n}\n\n// ─── Helpers ────────────────────────────────────────────────────────────\n\n/**\n * Log validation failures in dev mode so developers can see what went wrong.\n * In production, validation errors are only returned to the client.\n */\nfunction logValidationFailure(errors: ValidationErrors): void {\n const isDev = isDebug();\n if (!isDev) return;\n\n const fields = Object.entries(errors)\n .map(([field, messages]) => ` ${field}: ${(messages ?? []).join(', ')}`)\n .join('\\n');\n console.warn(`[timber] action schema validation failed:\\n${fields}`);\n}\n\n/**\n * Validate that all File objects in the input are within the size limit.\n * Returns validation errors keyed by field name, or null if all files are ok.\n * Keys are dot paths (`rows.0.file`), the form a field name and a Standard\n * Schema error use, so `errors.field()` finds a file in a list.\n */\nfunction validateFileSizes(input: Record<string, unknown>, limit: number): ValidationErrors | null {\n const limitKb = Math.round(limit / 1024);\n const limitLabel =\n limit >= 1024 * 1024 ? `${Math.round(limit / (1024 * 1024))}MB` : `${limitKb}KB`;\n\n const errors: Record<string, string[]> = {};\n\n function walk(obj: Record<string, unknown>, prefix: string): void {\n for (const [key, value] of Object.entries(obj)) {\n const path = prefix ? `${prefix}.${key}` : key;\n if (value instanceof File && value.size > limit) {\n errors[path] = [\n `File \"${value.name}\" (${formatSize(value.size)}) exceeds the ${limitLabel} limit`,\n ];\n } else if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const item = value[i];\n const itemPath = `${path}.${i}`;\n if (item instanceof File && item.size > limit) {\n (errors[itemPath] ??= []).push(\n `File \"${item.name}\" (${formatSize(item.size)}) exceeds the ${limitLabel} limit`\n );\n } else if (typeof item === 'object' && item !== null && !(item instanceof File)) {\n walk(item as Record<string, unknown>, itemPath);\n }\n }\n } else if (typeof value === 'object' && value !== null && !(value instanceof File)) {\n walk(value as Record<string, unknown>, path);\n }\n }\n }\n\n walk(input, '');\n return Object.keys(errors).length > 0 ? errors : null;\n}\n\n/**\n * Strip File objects from a value, returning a copy safe for serialization.\n * File objects can't be serialized and shouldn't be echoed back.\n *\n * Mirrors `parseFormData`'s output: objects and arrays at any depth, arrays\n * of arrays included. A File in an array becomes `undefined` rather than\n * being removed, so `rows.2` still names the third element (TIM-1573).\n */\nfunction stripFiles(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== 'object' || value instanceof File) return undefined;\n return stripFilesFrom(value) as Record<string, unknown>;\n}\n\nfunction stripFilesFrom(value: unknown): unknown {\n if (value instanceof File) return undefined;\n if (Array.isArray(value)) return value.map(stripFilesFrom);\n if (typeof value !== 'object' || value === null) return value;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n if (!(v instanceof File)) result[k] = stripFilesFrom(v);\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,IAAa,eAAe;CAC1B,MAAM;CACN,SAAS;AACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACgDA,IAAM,6BAAgD;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;AASA,IAAM,wBAA2C;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;;;;;;;AAQ3F,IAAM,yBAA4C,CAAC,OAAO;;;;;;;AAQ1D,SAASA,YAAU,MAAsB;CACvC,OAAO,KAAK,QAAQ,SAAS,EAAE,CAAC,CAAC,YAAY;AAC/C;;;;;;;AAQA,SAAS,MAAM,MAAwB;CACrC,OAAO,KACJ,MAAM,gCAAgC,CAAC,CACvC,OAAO,OAAO,CAAC,CACf,KAAK,MAAM,EAAE,YAAY,CAAC;AAC/B;;AAGA,SAAS,eAAe,MAAuB;CAC7C,OAAO,MAAM,IAAI,CAAC,CAAC,MAAM,SACvB,sBAAsB,MAAM,MAAM,KAAK,WAAW,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAC1E;AACF;;;;;AAMA,SAAS,mBAAmB,MAAc,QAAqC;CAC7E,MAAM,aAAaA,YAAU,IAAI;CACjC,IAAI,uBAAuB,SAAS,UAAU,GAAG,OAAO;CACxD,KAAK,MAAM,WAAW,4BACpB,IAAI,WAAW,SAAS,OAAO,GAAG,OAAO;CAE3C,IAAI,eAAe,IAAI,GAAG,OAAO;CACjC,IAAI,UAAU,OAAO,SAA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AK,GACvC,IAAI,EAAE,aAAa,OAAO,OAAO,KAAK,eAAe,CAAC;CAExD,OAAO;AACT"}
|
package/dist/server/internal.js
CHANGED
|
@@ -8,7 +8,7 @@ import { i as requestContextAls, n as prebuiltCaptureAls, o as timingAls, t as e
|
|
|
8
8
|
import { C as isRedirectSignal, F as withSpan, M as replaceTraceId, N as runWithTraceId, O as generateTraceId, P as setSpanAttribute, S as isDenySignal, _ as setLogger, a as logMiddlewareError, c as logRenderError, d as logRouteError, f as logRouteSetupError, g as logWaitUntilUnsupported, h as logWaitUntilRejected, j as getTraceId, k as getOtelTraceId, l as logRequestCompleted, m as logSwrRefetchFailed, n as logCacheMiss, o as logMiddlewareShortCircuit, p as logSlowRequest, r as logCsrfRejected, s as logProxyError, t as getLogger, u as logRequestReceived, v as swallow, w as isDebug, x as isControlFlowSignal } from "../_chunks/logger-CbLdcy-W.js";
|
|
9
9
|
import { i as collectRouteModulepreloads, n as collectRouteCss, r as collectRouteFonts } from "../_chunks/build-manifest-DWppEdLB.js";
|
|
10
10
|
import { i as isRscCacheKeyShape, n as RSC_KEY_PARAM, r as appVisibleSearch, s as rscCacheKey, t as RSC_KEY_HEADERS } from "../_chunks/rsc-cache-key-ClUiXQnK.js";
|
|
11
|
-
import { C as setMutableCookieContext, S as setMatchedSegmentPath, T as runOutsideReactCacheScope, b as markResponseFlushed, f as getCookie, g as getHeader, h as applyRequestHeaderOverlay, i as coerce, m as getSetCookieHeaders, o as DenySignal, s as RedirectSignal, t as executeAction, v as getSearchParams, w as setSegmentParams, x as runWithRequestContext, y as getSegmentParams } from "../_chunks/actions-
|
|
11
|
+
import { C as setMutableCookieContext, S as setMatchedSegmentPath, T as runOutsideReactCacheScope, b as markResponseFlushed, f as getCookie, g as getHeader, h as applyRequestHeaderOverlay, i as coerce, m as getSetCookieHeaders, o as DenySignal, s as RedirectSignal, t as executeAction, v as getSearchParams, w as setSegmentParams, x as runWithRequestContext, y as getSegmentParams } from "../_chunks/actions-BwkmAYXq.js";
|
|
12
12
|
import { a as getManifestEntry, b as wasInvalidatedSince, c as lookupPrebuiltPayload, d as checkVersionSkew, i as storeOverlayEntry, l as setPrebuiltPayloadSource, n as lookupOverlay, o as hasPrebuiltPayloadSource, r as overlayKey, s as isParamIndependent, u as applyReloadHeaders, v as currentInvalidationEpoch, x as getWaitUntil, y as lastInvalidationEpochFor } from "../_chunks/cache-api-LA3sBpUS.js";
|
|
13
13
|
import { n as createSingleflight } from "../_chunks/singleflight-BeVMMKi0.js";
|
|
14
14
|
import { n as toBracketKey } from "../_chunks/resolve-schema-CBR6Lm4i.js";
|
|
@@ -22,7 +22,6 @@
|
|
|
22
22
|
import type { BodyLimitsConfig } from '../body-limits.ts';
|
|
23
23
|
import type { CsrfConfig } from '../csrf.ts';
|
|
24
24
|
import type { PipelineReentry, RouteMatcher } from '../pipeline.ts';
|
|
25
|
-
import type { SensitiveFieldsOption } from '../sensitive-fields.ts';
|
|
26
25
|
import type { RevalidateRenderer } from '../actions.ts';
|
|
27
26
|
/**
|
|
28
27
|
* Build a `RevalidateRenderer` for a specific request.
|
|
@@ -40,8 +39,6 @@ export interface ActionDispatcherDeps {
|
|
|
40
39
|
csrfConfig: CsrfConfig;
|
|
41
40
|
/** Body size limits forwarded to `handleActionRequest`. */
|
|
42
41
|
bodyLimits?: BodyLimitsConfig['limits'];
|
|
43
|
-
/** Sensitive-field deny-list forwarded to `handleActionRequest`. */
|
|
44
|
-
sensitiveFields?: SensitiveFieldsOption;
|
|
45
42
|
/** Per-request factory that builds a `RevalidateRenderer`. */
|
|
46
43
|
buildRevalidateRenderer: RevalidateRendererFactory;
|
|
47
44
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"action-dispatcher.d.ts","sourceRoot":"","sources":["../../../src/server/rsc-entry/action-dispatcher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEpE,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"action-dispatcher.d.ts","sourceRoot":"","sources":["../../../src/server/rsc-entry/action-dispatcher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEpE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAIxD;;;;;;;;GAQG;AACH,MAAM,MAAM,yBAAyB,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK,kBAAkB,CAAC;AAE7E,yEAAyE;AACzE,MAAM,WAAW,oBAAoB;IACnC,6EAA6E;IAC7E,UAAU,EAAE,UAAU,CAAC;IACvB,2DAA2D;IAC3D,UAAU,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,CAAC;IACxC,8DAA8D;IAC9D,uBAAuB,EAAE,yBAAyB,CAAC;IACnD;;;;;;OAMG;IACH,UAAU,EAAE,YAAY,CAAC;CAC1B;AAID;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,oBAAoB,GACzB,CACD,GAAG,EAAE,OAAO,EACZ,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,KAAK,OAAO,CAAC,QAAQ,CAAC,KACnE,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAgE5B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/rsc-entry/index.ts"],"names":[],"mappings":"AA0CA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AA8ClE;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI,CAEjD;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/rsc-entry/index.ts"],"names":[],"mappings":"AA0CA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AA8ClE;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI,CAEjD;AAgVD,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAInE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAK1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAItE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,OAAO,wBAAwB,EAAE,cAAc,GACvD,OAAO,CAAC,OAAO,wBAAwB,EAAE,cAAc,CAAC,CAE1D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,OAAO,wBAAwB,EAAE,uBAAuB,GAChE,OAAO,CAAC,OAAO,wBAAwB,EAAE,uBAAuB,CAAC,CAQnE;8BAwCoB,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema introspection — the shape of an action's input as its schema
|
|
3
|
+
* declares it: which fields are lists, which may be absent, and which the
|
|
4
|
+
* schema marks sensitive.
|
|
5
|
+
*
|
|
6
|
+
* Standard Schema v1 has no introspection API, so this feature-detects what
|
|
7
|
+
* the libraries expose:
|
|
8
|
+
*
|
|
9
|
+
* - **Zod 4**: its schema tree (`_zod.def`, documented for library authors),
|
|
10
|
+
* with `.meta()` for marks and `_zod.optin` for fields that may be absent.
|
|
11
|
+
* Not Zod's JSON Schema: that describes a `z.preprocess(fn, z.array(…))`
|
|
12
|
+
* field as the inner array, and wrapping a scalar before `fn` runs would
|
|
13
|
+
* hand a comma-splitting preprocessor `['a,b']`. A preprocessed field is
|
|
14
|
+
* its author's to read, so it has no shape here.
|
|
15
|
+
* - **Valibot**: its schema objects (`entries`, `item`, `wrapped`, `options`),
|
|
16
|
+
* with `v.metadata({ sensitive: true })` read from the pipe.
|
|
17
|
+
* - **Standard JSON Schema** (`~standard.jsonSchema.input()`) for any other
|
|
18
|
+
* library that implements it, such as ArkType, whose
|
|
19
|
+
* `.configure({ sensitive: true })` lands in the JSON Schema node.
|
|
20
|
+
*
|
|
21
|
+
* Any other schema (a legacy `.parse()` schema, Zod 3, a hand-written
|
|
22
|
+
* Standard Schema) has no shape: its form input is not normalized and only
|
|
23
|
+
* the name deny-list strips its echo.
|
|
24
|
+
*
|
|
25
|
+
* A union merges its branches: a field is sensitive if any branch marks it,
|
|
26
|
+
* and a list only if every branch declares it one. An intersection merges
|
|
27
|
+
* its parts, which all apply: a list or sensitive if any part says so.
|
|
28
|
+
*
|
|
29
|
+
* `createActionClient` computes the shape once per action and keeps it on the
|
|
30
|
+
* action's closure. It is used twice, by `normalizeListFields` (before
|
|
31
|
+
* validation, and for `submittedValues`) and by `stripSensitiveFields`.
|
|
32
|
+
*
|
|
33
|
+
* See design/08-forms-and-actions.md §"The Form Model" and
|
|
34
|
+
* §"Sensitive field stripping".
|
|
35
|
+
*/
|
|
36
|
+
/** The declared shape of one field (or of the whole input). */
|
|
37
|
+
export interface FieldShape {
|
|
38
|
+
/** The field holds items of this shape (a list, possibly not in every union branch). */
|
|
39
|
+
item?: FieldShape;
|
|
40
|
+
/** Every declaration of the field is a list: normalize its form value to an array. */
|
|
41
|
+
list?: boolean;
|
|
42
|
+
/** The field is an object; these are its properties' shapes. */
|
|
43
|
+
properties?: Record<string, FieldShape>;
|
|
44
|
+
/** The field may be absent (`.optional()`, a default, a missing union branch). */
|
|
45
|
+
optional?: boolean;
|
|
46
|
+
/** The schema marks the field sensitive (`.meta({ sensitive: true })`). */
|
|
47
|
+
sensitive?: boolean;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The shape of `schema`'s input, or `undefined` when the schema library
|
|
51
|
+
* exposes nothing to read it from.
|
|
52
|
+
*/
|
|
53
|
+
export declare function introspectSchema(schema: unknown): FieldShape | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* Give every field the schema declares as a list the same shape whatever its
|
|
56
|
+
* count. `parseFormData` reads a repeated name as an array, a single value as
|
|
57
|
+
* a scalar, and an absent name not at all; here a scalar becomes `[value]`,
|
|
58
|
+
* and an absent or blank required list becomes `[]` (blanks are dropped from
|
|
59
|
+
* a list, as `parseFormData` drops them from a repeated name). An optional
|
|
60
|
+
* list that was not submitted (or was one blank) is absent, so `.optional()` still means
|
|
61
|
+
* "not sent". Lists inside lists and objects are normalized too. An object
|
|
62
|
+
* where a list is declared (an indexed list with a gap) is left for the
|
|
63
|
+
* schema to reject.
|
|
64
|
+
*
|
|
65
|
+
* Returns a copy; the input is not written to.
|
|
66
|
+
*/
|
|
67
|
+
export declare function normalizeListFields(values: Record<string, unknown>, shape: FieldShape | undefined): Record<string, unknown>;
|
|
68
|
+
//# sourceMappingURL=schema-introspection.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-introspection.d.ts","sourceRoot":"","sources":["../../src/server/schema-introspection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAIH,+DAA+D;AAC/D,MAAM,WAAW,UAAU;IACzB,wFAAwF;IACxF,IAAI,CAAC,EAAE,UAAU,CAAC;IAClB,sFAAsF;IACtF,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,gEAAgE;IAChE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACxC,kFAAkF;IAClF,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,2EAA2E;IAC3E,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,OAAO,GAAG,UAAU,GAAG,SAAS,CAiBxE;AAwPD;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,KAAK,EAAE,UAAU,GAAG,SAAS,GAC5B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAGzB"}
|
|
@@ -1,32 +1,42 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Sensitive field stripping — removes password/token/CVV-style fields
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Sensitive field stripping — removes password/token/CVV-style fields from
|
|
3
|
+
* the `submittedValues` a `createActionClient` action echoes back to the
|
|
4
|
+
* client for form repopulation.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* - No-JS form POST path: `handleFormAction()` in `action-handler.ts`
|
|
6
|
+
* **This is hygiene, not a security boundary.** `submittedValues` only ever
|
|
7
|
+
* returns to the user who typed it, in the response to their own POST:
|
|
9
8
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
9
|
+
* - With JavaScript, it travels in the action's response, a non-cacheable
|
|
10
|
+
* POST fetch. What remains is exposure to devtools, HAR exports and
|
|
11
|
+
* TLS-inspecting proxies.
|
|
12
|
+
* - Without JavaScript, it is rendered into the page's HTML as a field's
|
|
13
|
+
* `defaultValue`: one uncached response, but one that view-source, the
|
|
14
|
+
* back-forward cache and a shared machine can surface. OWASP advises not
|
|
15
|
+
* pre-filling password fields for this reason.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
* `timber.config.ts` or per-action via `createActionClient({ stripSensitiveFields: false })`.
|
|
17
|
+
* The main reason to strip is UX: a password or card field comes back empty
|
|
18
|
+
* after a failed submit, as users expect.
|
|
20
19
|
*
|
|
21
|
-
*
|
|
20
|
+
* What is stripped: a field whose name matches the built-in deny-list (or the
|
|
21
|
+
* configured option), and a field the action's schema marks sensitive with
|
|
22
|
+
* `.meta({ sensitive: true })` (Valibot: `v.metadata({ sensitive: true })`),
|
|
23
|
+
* at its exact path. The schema mark covers names the list misses
|
|
24
|
+
* (`recoveryPhrase`) and always applies, even with the name list turned off.
|
|
25
|
+
*
|
|
26
|
+
* Only `createActionClient` strips, because only it builds `submittedValues`.
|
|
27
|
+
* A raw `'use server'` action owns its return value: whatever it returns is
|
|
28
|
+
* what the client gets, on both paths.
|
|
29
|
+
*
|
|
30
|
+
* See design/08-forms-and-actions.md §"Sensitive field stripping"
|
|
22
31
|
* See design/13-security.md §"Sensitive field stripping"
|
|
23
|
-
* See TIM-816
|
|
24
32
|
*/
|
|
33
|
+
import type { FieldShape } from './schema-introspection.ts';
|
|
25
34
|
/**
|
|
26
|
-
* How to strip sensitive fields from `submittedValues
|
|
35
|
+
* How to strip sensitive fields from `submittedValues`, by name.
|
|
27
36
|
*
|
|
28
|
-
* - `true` / `undefined` — use the built-in deny-list (default
|
|
29
|
-
* - `false` —
|
|
37
|
+
* - `true` / `undefined` — use the built-in deny-list (default).
|
|
38
|
+
* - `false` — strip no field by name. Fields the schema marks sensitive are
|
|
39
|
+
* still stripped.
|
|
30
40
|
* - `string[]` — additional field names to strip, merged with the built-in list.
|
|
31
41
|
* - `(name) => boolean` — custom predicate, fully replaces the built-in list.
|
|
32
42
|
* Return `true` to strip, `false` to keep. The `name` argument is the raw
|
|
@@ -34,7 +44,7 @@
|
|
|
34
44
|
*/
|
|
35
45
|
export type SensitiveFieldsOption = boolean | readonly string[] | ((name: string) => boolean);
|
|
36
46
|
/**
|
|
37
|
-
* A resolved predicate: `null` means "
|
|
47
|
+
* A resolved predicate: `null` means "strip no field by name" (the option was
|
|
38
48
|
* explicitly `false`). Otherwise a function from raw field name → boolean.
|
|
39
49
|
*/
|
|
40
50
|
export type ResolvedSensitivePredicate = ((name: string) => boolean) | null;
|
|
@@ -44,7 +54,7 @@ export type ResolvedSensitivePredicate = ((name: string) => boolean) | null;
|
|
|
44
54
|
*
|
|
45
55
|
* - Per-action `undefined` → fall back to global.
|
|
46
56
|
* - Global `undefined` → use built-in list.
|
|
47
|
-
* - Either level set to `false` →
|
|
57
|
+
* - Either level set to `false` → no name matching (returns `null`).
|
|
48
58
|
* - `true` → built-in list.
|
|
49
59
|
* - `string[]` → built-in ∪ extras.
|
|
50
60
|
* - function → custom, replaces the built-in list entirely.
|
|
@@ -58,9 +68,11 @@ export declare function setGlobalSensitiveFieldsConfig(option: SensitiveFieldsOp
|
|
|
58
68
|
/** Read the global `forms.stripSensitiveFields` config. */
|
|
59
69
|
export declare function getGlobalSensitiveFieldsConfig(): SensitiveFieldsOption | undefined;
|
|
60
70
|
/**
|
|
61
|
-
* Walk an object (recursively) and return a copy
|
|
62
|
-
* `predicate`
|
|
63
|
-
*
|
|
71
|
+
* Walk an object (recursively) and return a copy without its sensitive
|
|
72
|
+
* fields: every key `predicate` matches, and every field `shape` (the
|
|
73
|
+
* schema's declared shape) marks sensitive. Nested objects like
|
|
74
|
+
* `{ user: { password: '...' } }` are handled — `user.password` is stripped
|
|
75
|
+
* while other `user.*` fields remain.
|
|
64
76
|
*
|
|
65
77
|
* - Arrays are walked element-wise (object entries inside arrays are cleaned).
|
|
66
78
|
* - Non-plain values (strings, numbers, Files, Dates, etc.) are returned as-is.
|
|
@@ -68,7 +80,9 @@ export declare function getGlobalSensitiveFieldsConfig(): SensitiveFieldsOption
|
|
|
68
80
|
* — we do NOT set it to an empty string, because that would overwrite a
|
|
69
81
|
* valid `defaultValue` the form author might have set.
|
|
70
82
|
*/
|
|
71
|
-
export declare function stripSensitiveFields
|
|
83
|
+
export declare function stripSensitiveFields(value: Record<string, unknown>, predicate: ResolvedSensitivePredicate, shape?: FieldShape): Record<string, unknown>;
|
|
84
|
+
/** The built-in patterns, for the docs drift test. */
|
|
85
|
+
export declare const __BUILTIN_SENSITIVE_PATTERNS: readonly string[];
|
|
72
86
|
/** Reset the "warned once" cache. Exposed for tests. */
|
|
73
87
|
export declare function __resetSensitiveFieldsWarnings(): void;
|
|
74
88
|
//# sourceMappingURL=sensitive-fields.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sensitive-fields.d.ts","sourceRoot":"","sources":["../../src/server/sensitive-fields.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"sensitive-fields.d.ts","sourceRoot":"","sources":["../../src/server/sensitive-fields.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAGH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAI5D;;;;;;;;;;GAUG;AACH,MAAM,MAAM,qBAAqB,GAAG,OAAO,GAAG,SAAS,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;AAkG9F;;;GAGG;AACH,MAAM,MAAM,0BAA0B,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,IAAI,CAAC;AAE5E;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CACvC,SAAS,EAAE,qBAAqB,GAAG,SAAS,EAC5C,MAAM,EAAE,qBAAqB,GAAG,SAAS,GACxC,0BAA0B,CAa5B;AAMD;;;GAGG;AACH,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,qBAAqB,GAAG,SAAS,GAAG,IAAI,CAE9F;AAED,2DAA2D;AAC3D,wBAAgB,8BAA8B,IAAI,qBAAqB,GAAG,SAAS,CAElF;AAoBD;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC9B,SAAS,EAAE,0BAA0B,EACrC,KAAK,CAAC,EAAE,UAAU,GACjB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAGzB;AAuCD,sDAAsD;AACtD,eAAO,MAAM,4BAA4B,EAAE,SAAS,MAAM,EAIzD,CAAC;AAEF,wDAAwD;AACxD,wBAAgB,8BAA8B,IAAI,IAAI,CAErD"}
|
|
@@ -123,51 +123,52 @@ const params = useSegmentParams(); // Partial<AllSegmentParams>
|
|
|
123
123
|
|
|
124
124
|
## Form Hooks
|
|
125
125
|
|
|
126
|
-
Forms use React's own `useActionState`, imported from `react`. An action built with `createActionClient` passes to it directly: `result` is typed from the action, and the dispatch accepts the submitted `FormData` or the schema's input.
|
|
126
|
+
Forms use React's own `useActionState`, imported from `react`. An action built with `createActionClient` passes to it directly: `result` is typed from the action, and the dispatch accepts the submitted `FormData` or the schema's input. For a call that isn't a form submit, such as a delete button, dispatch inside a transition: `startTransition(() => dispatch({ id }))`.
|
|
127
127
|
|
|
128
|
-
### `
|
|
128
|
+
### `readFormErrors(result)`
|
|
129
129
|
|
|
130
130
|
Reads the errors out of an action result. `_root` validation errors are form-level; every other key is a field.
|
|
131
131
|
|
|
132
132
|
```tsx
|
|
133
133
|
import { useActionState } from 'react';
|
|
134
|
-
import {
|
|
134
|
+
import { readFormErrors } from '@timber-js/app/client';
|
|
135
135
|
|
|
136
136
|
const [result, action, isPending] = useActionState(createTodo, null);
|
|
137
|
-
const errors =
|
|
137
|
+
const errors = readFormErrors(result);
|
|
138
138
|
|
|
139
|
+
errors.field('title'); // string | null: the first error for the field
|
|
140
|
+
errors.form; // string[]: form-level errors
|
|
141
|
+
errors.server; // { code, data? } | null
|
|
139
142
|
errors.hasErrors; // boolean
|
|
140
|
-
errors.fieldErrors; // Record<string, string[]>
|
|
141
|
-
errors.formErrors; // string[]
|
|
142
|
-
errors.serverError; // { code, data? } | null
|
|
143
|
-
errors.getFieldError('title'); // string | null
|
|
144
143
|
```
|
|
145
144
|
|
|
146
|
-
|
|
145
|
+
`errors.field()` is typed from the action's schema: it takes the dot paths of the schema's input, such as `'title'` or `'sets.0.name'`, so a misspelled field name is a type error. An action without a schema accepts any name.
|
|
146
|
+
|
|
147
|
+
### `useFieldState(defaultValue)`
|
|
147
148
|
|
|
148
149
|
State for a form field that needs JavaScript, such as a combobox or a chip list, that follows the form's reset like a native input with a `defaultValue`. React resets a form after every action, so use this instead of `useState` for any field inside a form. See [Keeping What the User Typed](/docs/forms-and-actions#keeping-what-the-user-typed).
|
|
149
150
|
|
|
150
151
|
```tsx
|
|
151
|
-
import {
|
|
152
|
+
import { useFieldState } from '@timber-js/app/client';
|
|
152
153
|
|
|
153
154
|
// draft = toDraft(result?.submittedValues ?? post): the form's defaults
|
|
154
|
-
const [tags, setTags, ref] =
|
|
155
|
+
const [tags, setTags, ref] = useFieldState(draft.tags);
|
|
155
156
|
|
|
156
157
|
<div ref={ref}>
|
|
157
|
-
|
|
158
|
+
{tags.map((tag) => (
|
|
159
|
+
<input key={tag} type="hidden" name="tags" value={tag} />
|
|
160
|
+
))}
|
|
158
161
|
<TagPicker value={tags} onChange={setTags} />
|
|
159
|
-
</div
|
|
162
|
+
</div>;
|
|
160
163
|
```
|
|
161
164
|
|
|
162
165
|
- `value`: `defaultValue` until `setValue` is called, then the edit. An unedited field follows a new `defaultValue`.
|
|
163
166
|
- `setValue`: like a `useState` setter; accepts a value or an updater.
|
|
164
|
-
- `ref`: attach to any element inside the `<form
|
|
165
|
-
|
|
166
|
-
An edit dispatches a bubbling `change` event from the `ref` element, so a native `change` listener on the form sees it. React's `onChange` prop does not: it only reports inputs, selects and textareas. Render the value into the form data yourself, usually with a hidden input.
|
|
167
|
+
- `ref`: attach to any element inside the `<form>`, or to the `<form>` itself. When the form resets, the edit is dropped and `value` is `defaultValue` again, unless the form cancels the `reset` event.
|
|
167
168
|
|
|
168
|
-
|
|
169
|
+
An edit dispatches a bubbling `change` event from the `ref` element, so a native `change` listener on the form sees it. React's `onChange` prop does not: it only reports inputs, selects and textareas. Render the value into the form data yourself, usually with hidden inputs. A list can be one hidden input per item: a `createActionClient` action reads none, one or many values as a list when its schema declares one.
|
|
169
170
|
|
|
170
|
-
|
|
171
|
+
With the `ref` on the `<form>`, the hook can sit above the form and hold the whole draft as one object, for a preview outside the form. See [Where form state lives](/docs/forms-and-actions#where-form-state-lives).
|
|
171
172
|
|
|
172
173
|
## Utilities
|
|
173
174
|
|
|
@@ -153,7 +153,7 @@ limits: {
|
|
|
153
153
|
- **Type:** `boolean | string[]`
|
|
154
154
|
- **Default:** `true`
|
|
155
155
|
|
|
156
|
-
Strip sensitive fields (passwords, tokens, CVV, SSN, etc.) from the `submittedValues`
|
|
156
|
+
Strip sensitive fields (passwords, tokens, CVV, SSN, etc.) from the `submittedValues` a `createActionClient` action echoes back when it fails. `true` uses the built-in deny-list; an array adds extra field names to the built-in list; `false` turns off matching by name (fields the schema marks `.meta({ sensitive: true })` are still stripped). A client's own `stripSensitiveFields` option overrides this. See [Advanced Forms](/docs/advanced-forms#sensitive-field-stripping) for the full pattern list.
|
|
157
157
|
|
|
158
158
|
### `pageExtensions`
|
|
159
159
|
|