@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.
Files changed (58) hide show
  1. package/agent-skill.md +5 -5
  2. package/dist/_chunks/{actions-CUh3cClk.js → actions-BwkmAYXq.js} +8 -1
  3. package/dist/_chunks/{actions-CUh3cClk.js.map → actions-BwkmAYXq.js.map} +1 -1
  4. package/dist/client/form.d.ts +34 -37
  5. package/dist/client/form.d.ts.map +1 -1
  6. package/dist/client/index.d.ts +3 -3
  7. package/dist/client/index.d.ts.map +1 -1
  8. package/dist/client/index.js +40 -75
  9. package/dist/client/index.js.map +1 -1
  10. package/dist/client/{use-form-field.d.ts → use-field-state.d.ts} +10 -7
  11. package/dist/client/use-field-state.d.ts.map +1 -0
  12. package/dist/config-types.d.ts +15 -18
  13. package/dist/config-types.d.ts.map +1 -1
  14. package/dist/index.js +0 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/plugins/shims.d.ts.map +1 -1
  17. package/dist/server/action-client.d.ts +11 -172
  18. package/dist/server/action-client.d.ts.map +1 -1
  19. package/dist/server/action-handler.d.ts +0 -7
  20. package/dist/server/action-handler.d.ts.map +1 -1
  21. package/dist/server/action-schema.d.ts +126 -0
  22. package/dist/server/action-schema.d.ts.map +1 -0
  23. package/dist/server/action-types.d.ts +108 -0
  24. package/dist/server/action-types.d.ts.map +1 -0
  25. package/dist/server/form-data.d.ts +7 -0
  26. package/dist/server/form-data.d.ts.map +1 -1
  27. package/dist/server/index.d.ts +3 -2
  28. package/dist/server/index.d.ts.map +1 -1
  29. package/dist/server/index.js +511 -148
  30. package/dist/server/index.js.map +1 -1
  31. package/dist/server/internal.js +1 -1
  32. package/dist/server/rsc-entry/action-dispatcher.d.ts +0 -3
  33. package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -1
  34. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  35. package/dist/server/schema-introspection.d.ts +68 -0
  36. package/dist/server/schema-introspection.d.ts.map +1 -0
  37. package/dist/server/sensitive-fields.d.ts +40 -26
  38. package/dist/server/sensitive-fields.d.ts.map +1 -1
  39. package/docs/api/31-api-client.mdx +19 -18
  40. package/docs/api/34-api-config.mdx +1 -1
  41. package/docs/learn/08-forms-and-actions.mdx +57 -23
  42. package/package.json +1 -1
  43. package/src/client/form.tsx +57 -108
  44. package/src/client/index.ts +3 -3
  45. package/src/client/{use-form-field.ts → use-field-state.ts} +20 -8
  46. package/src/config-types.ts +15 -18
  47. package/src/plugins/shims.ts +0 -1
  48. package/src/server/action-client.ts +82 -307
  49. package/src/server/action-handler.ts +1 -42
  50. package/src/server/action-schema.ts +203 -0
  51. package/src/server/action-types.ts +145 -0
  52. package/src/server/form-data.ts +7 -0
  53. package/src/server/index.ts +5 -3
  54. package/src/server/rsc-entry/action-dispatcher.ts +0 -4
  55. package/src/server/rsc-entry/index.ts +1 -2
  56. package/src/server/schema-introspection.ts +393 -0
  57. package/src/server/sensitive-fields.ts +115 -58
  58. package/dist/client/use-form-field.d.ts.map +0 -1
@@ -0,0 +1,393 @@
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
+
37
+ import { isStandardSchema } from './action-schema.ts';
38
+
39
+ /** The declared shape of one field (or of the whole input). */
40
+ export interface FieldShape {
41
+ /** The field holds items of this shape (a list, possibly not in every union branch). */
42
+ item?: FieldShape;
43
+ /** Every declaration of the field is a list: normalize its form value to an array. */
44
+ list?: boolean;
45
+ /** The field is an object; these are its properties' shapes. */
46
+ properties?: Record<string, FieldShape>;
47
+ /** The field may be absent (`.optional()`, a default, a missing union branch). */
48
+ optional?: boolean;
49
+ /** The schema marks the field sensitive (`.meta({ sensitive: true })`). */
50
+ sensitive?: boolean;
51
+ }
52
+
53
+ /**
54
+ * The shape of `schema`'s input, or `undefined` when the schema library
55
+ * exposes nothing to read it from.
56
+ */
57
+ export function introspectSchema(schema: unknown): FieldShape | undefined {
58
+ if (!isStandardSchema(schema)) return undefined;
59
+ const standard: Record<string, unknown> = schema['~standard'];
60
+ if (standard.vendor === 'zod' && isRecord(schema) && isRecord(schema._zod)) {
61
+ return fromZod(schema, new Set());
62
+ }
63
+ if (standard.vendor === 'valibot') return fromValibot(schema, new Set());
64
+
65
+ const jsonSchema = standard.jsonSchema;
66
+ if (!isRecord(jsonSchema) || typeof jsonSchema.input !== 'function') return undefined;
67
+ let root: unknown;
68
+ try {
69
+ root = jsonSchema.input({ target: 'draft-2020-12' });
70
+ } catch {
71
+ return undefined;
72
+ }
73
+ return isRecord(root) ? fromJsonSchema(root, root, new Set()) : undefined;
74
+ }
75
+
76
+ // ─── Zod 4 ───────────────────────────────────────────────────────────────
77
+
78
+ /** Zod wrappers whose `innerType` is the field's real type. */
79
+ const ZOD_WRAPPERS = new Set([
80
+ 'optional',
81
+ 'nullable',
82
+ 'default',
83
+ 'prefault',
84
+ 'nonoptional',
85
+ 'readonly',
86
+ 'catch',
87
+ ]);
88
+
89
+ function fromZod(schema: unknown, seen: Set<unknown>): FieldShape | undefined {
90
+ if (!isRecord(schema) || seen.has(schema) || !isRecord(schema._zod)) return undefined;
91
+ const inner = new Set(seen).add(schema);
92
+ const def = schema._zod.def;
93
+ if (!isRecord(def)) return undefined;
94
+ const marks = withMarks(schema._zod.optin === 'optional', zodSensitive(schema));
95
+
96
+ switch (def.type) {
97
+ case 'object': {
98
+ if (!isRecord(def.shape)) return marks(undefined);
99
+ const properties: Record<string, FieldShape> = {};
100
+ for (const [key, child] of Object.entries(def.shape)) {
101
+ const shape = fromZod(child, inner);
102
+ if (shape) properties[key] = shape;
103
+ }
104
+ return marks({ properties });
105
+ }
106
+ case 'array':
107
+ return marks({ item: fromZod(def.element, inner) ?? {}, list: true });
108
+ case 'union':
109
+ return marks(mergeAll(asList(def.options).map((option) => fromZod(option, inner))));
110
+ case 'intersection':
111
+ return marks(intersectAll([fromZod(def.left, inner), fromZod(def.right, inner)]));
112
+ case 'pipe':
113
+ // `z.preprocess(fn, …)` is a pipe from a transform: its author reads
114
+ // the raw value. Any other pipe takes its input side's shape.
115
+ if (isRecord(def.in) && isRecord(def.in._zod) && isRecord(def.in._zod.def)) {
116
+ if (def.in._zod.def.type === 'transform') return marks(undefined);
117
+ }
118
+ return marks(fromZod(def.in, inner));
119
+ default:
120
+ if (typeof def.type === 'string' && ZOD_WRAPPERS.has(def.type)) {
121
+ return marks(fromZod(def.innerType, inner));
122
+ }
123
+ return marks(undefined);
124
+ }
125
+ }
126
+
127
+ /** `.meta()` read back: Zod returns the schema's registered metadata. */
128
+ function zodSensitive(schema: Record<string, unknown>): boolean {
129
+ if (typeof schema.meta !== 'function') return false;
130
+ try {
131
+ const meta: unknown = schema.meta();
132
+ return isRecord(meta) && meta.sensitive === true;
133
+ } catch {
134
+ return false;
135
+ }
136
+ }
137
+
138
+ // ─── Valibot ─────────────────────────────────────────────────────────────
139
+
140
+ /** Valibot wrappers whose `wrapped` schema is the field's real type. */
141
+ const VALIBOT_WRAPPERS = new Set([
142
+ 'optional',
143
+ 'exact_optional',
144
+ 'nullable',
145
+ 'nullish',
146
+ 'undefinedable',
147
+ 'non_optional',
148
+ 'non_nullable',
149
+ 'non_nullish',
150
+ ]);
151
+
152
+ /** Valibot wrappers that let the field be absent. */
153
+ const VALIBOT_OPTIONAL = new Set(['optional', 'exact_optional', 'nullish', 'undefinedable']);
154
+
155
+ const VALIBOT_OBJECTS = new Set(['object', 'loose_object', 'strict_object', 'object_with_rest']);
156
+
157
+ function fromValibot(schema: unknown, seen: Set<unknown>): FieldShape | undefined {
158
+ if (!isRecord(schema) || seen.has(schema)) return undefined;
159
+ const inner = new Set(seen).add(schema);
160
+ const sensitive =
161
+ Array.isArray(schema.pipe) &&
162
+ schema.pipe.some(
163
+ (action) =>
164
+ isRecord(action) &&
165
+ action.kind === 'metadata' &&
166
+ isRecord(action.metadata) &&
167
+ action.metadata.sensitive === true
168
+ );
169
+
170
+ const type = schema.type;
171
+ const marks = withMarks(typeof type === 'string' && VALIBOT_OPTIONAL.has(type), sensitive);
172
+ if (typeof type !== 'string') return marks(undefined);
173
+ if (VALIBOT_WRAPPERS.has(type)) return marks(fromValibot(schema.wrapped, inner));
174
+ if (type === 'array') return marks({ item: fromValibot(schema.item, inner) ?? {}, list: true });
175
+ if (type === 'union' || type === 'variant') {
176
+ return marks(mergeAll(asList(schema.options).map((option) => fromValibot(option, inner))));
177
+ }
178
+ if (type === 'intersect') {
179
+ return marks(intersectAll(asList(schema.options).map((option) => fromValibot(option, inner))));
180
+ }
181
+ if (VALIBOT_OBJECTS.has(type) && isRecord(schema.entries)) {
182
+ const properties: Record<string, FieldShape> = {};
183
+ for (const [key, child] of Object.entries(schema.entries)) {
184
+ const shape = fromValibot(child, inner);
185
+ if (shape) properties[key] = shape;
186
+ }
187
+ return marks({ properties });
188
+ }
189
+ return marks(undefined);
190
+ }
191
+
192
+ // ─── Standard JSON Schema ────────────────────────────────────────────────
193
+
194
+ function fromJsonSchema(
195
+ node: Record<string, unknown>,
196
+ root: Record<string, unknown>,
197
+ refs: Set<string>
198
+ ): FieldShape | undefined {
199
+ const marks = withMarks(false, node.sensitive === true);
200
+ const ref = node.$ref;
201
+ if (typeof ref === 'string') {
202
+ // A recursive schema: stop at a ref already being expanded on this path.
203
+ if (refs.has(ref)) return marks(undefined);
204
+ const target = resolveRef(root, ref);
205
+ if (!target) return marks(undefined);
206
+ return marks(fromJsonSchema(target, root, new Set(refs).add(ref)));
207
+ }
208
+
209
+ const branches = node.anyOf ?? node.oneOf;
210
+ if (Array.isArray(branches)) {
211
+ const shapes = branches
212
+ .filter((b): b is Record<string, unknown> => isRecord(b) && b.type !== 'null')
213
+ .map((b) => fromJsonSchema(b, root, refs));
214
+ return marks(mergeAll(shapes));
215
+ }
216
+
217
+ if (Array.isArray(node.allOf)) {
218
+ const parts = node.allOf.filter(isRecord).map((part) => fromJsonSchema(part, root, refs));
219
+ return marks(intersectAll(parts));
220
+ }
221
+
222
+ const types = Array.isArray(node.type) ? node.type : [node.type];
223
+ if (types.includes('array') && isRecord(node.items)) {
224
+ return marks({ item: fromJsonSchema(node.items, root, refs) ?? {}, list: true });
225
+ }
226
+ if (isRecord(node.properties)) {
227
+ const required = new Set(asList(node.required));
228
+ const properties: Record<string, FieldShape> = {};
229
+ for (const [key, child] of Object.entries(node.properties)) {
230
+ const shape = isRecord(child) ? fromJsonSchema(child, root, refs) : undefined;
231
+ if (shape) properties[key] = required.has(key) ? shape : { ...shape, optional: true };
232
+ }
233
+ return marks({ properties });
234
+ }
235
+ return marks(undefined);
236
+ }
237
+
238
+ /** Resolve a local `#/$defs/...` or `#/definitions/...` reference. */
239
+ function resolveRef(
240
+ root: Record<string, unknown>,
241
+ ref: string
242
+ ): Record<string, unknown> | undefined {
243
+ if (!ref.startsWith('#/')) return undefined;
244
+ let node: unknown = root;
245
+ for (const segment of ref.slice(2).split('/')) {
246
+ if (!isRecord(node)) return undefined;
247
+ node = node[segment.replaceAll('~1', '/').replaceAll('~0', '~')];
248
+ }
249
+ return isRecord(node) ? node : undefined;
250
+ }
251
+
252
+ // ─── Unions ──────────────────────────────────────────────────────────────
253
+
254
+ /**
255
+ * One shape for the branches of a union. A field is sensitive if any branch
256
+ * marks it, a list only if every branch declares it one, and optional if any
257
+ * branch lacks it. A branch with no shape makes nothing a list, but its
258
+ * siblings' marks still apply.
259
+ */
260
+ function mergeAll(shapes: (FieldShape | undefined)[]): FieldShape | undefined {
261
+ if (shapes.length === 0) return undefined;
262
+ return shapes.reduce<FieldShape | undefined>(
263
+ (merged, shape, i) => (i === 0 ? (shape ?? {}) : merge(merged ?? {}, shape ?? {})),
264
+ undefined
265
+ );
266
+ }
267
+
268
+ function merge(a: FieldShape, b: FieldShape): FieldShape {
269
+ const out: FieldShape = {};
270
+ if (a.sensitive || b.sensitive) out.sensitive = true;
271
+ if (a.optional || b.optional) out.optional = true;
272
+ if (a.list && b.list) out.list = true;
273
+ if (a.item || b.item) out.item = merge(a.item ?? {}, b.item ?? {});
274
+ if (a.properties || b.properties) {
275
+ const properties: Record<string, FieldShape> = {};
276
+ const keys = new Set([...Object.keys(a.properties ?? {}), ...Object.keys(b.properties ?? {})]);
277
+ for (const key of keys) {
278
+ const left = a.properties?.[key];
279
+ const right = b.properties?.[key];
280
+ // Present in one branch only: absent whenever the other is chosen.
281
+ properties[key] = left && right ? merge(left, right) : { ...(left ?? right), optional: true };
282
+ }
283
+ out.properties = properties;
284
+ }
285
+ return out;
286
+ }
287
+
288
+ // ─── Intersections ──────────────────────────────────────────────────────
289
+
290
+ /**
291
+ * One shape for the parts of an intersection, which all apply: a field is a
292
+ * list or sensitive if any part says so, and optional only if every part
293
+ * that declares it lets it be absent.
294
+ */
295
+ function intersectAll(shapes: (FieldShape | undefined)[]): FieldShape | undefined {
296
+ const present = shapes.filter((shape): shape is FieldShape => shape !== undefined);
297
+ if (present.length === 0) return undefined;
298
+ return present.reduce(intersect);
299
+ }
300
+
301
+ function intersect(a: FieldShape, b: FieldShape): FieldShape {
302
+ const out: FieldShape = {};
303
+ if (a.sensitive || b.sensitive) out.sensitive = true;
304
+ if (a.optional && b.optional) out.optional = true;
305
+ if (a.list || b.list) out.list = true;
306
+ if (a.item || b.item) out.item = intersect(a.item ?? {}, b.item ?? {});
307
+ if (a.properties || b.properties) {
308
+ const properties: Record<string, FieldShape> = {};
309
+ const keys = new Set([...Object.keys(a.properties ?? {}), ...Object.keys(b.properties ?? {})]);
310
+ for (const key of keys) {
311
+ const left = a.properties?.[key];
312
+ const right = b.properties?.[key];
313
+ properties[key] = left && right ? intersect(left, right) : (left ?? right ?? {});
314
+ }
315
+ out.properties = properties;
316
+ }
317
+ return out;
318
+ }
319
+
320
+ // ─── List normalization ──────────────────────────────────────────────────
321
+
322
+ /**
323
+ * Give every field the schema declares as a list the same shape whatever its
324
+ * count. `parseFormData` reads a repeated name as an array, a single value as
325
+ * a scalar, and an absent name not at all; here a scalar becomes `[value]`,
326
+ * and an absent or blank required list becomes `[]` (blanks are dropped from
327
+ * a list, as `parseFormData` drops them from a repeated name). An optional
328
+ * list that was not submitted (or was one blank) is absent, so `.optional()` still means
329
+ * "not sent". Lists inside lists and objects are normalized too. An object
330
+ * where a list is declared (an indexed list with a gap) is left for the
331
+ * schema to reject.
332
+ *
333
+ * Returns a copy; the input is not written to.
334
+ */
335
+ export function normalizeListFields(
336
+ values: Record<string, unknown>,
337
+ shape: FieldShape | undefined
338
+ ): Record<string, unknown> {
339
+ if (!shape) return values;
340
+ return normalize(values, shape) as Record<string, unknown>;
341
+ }
342
+
343
+ function normalize(value: unknown, shape: FieldShape): unknown {
344
+ if (shape.list && shape.item) {
345
+ if (value === undefined || value === '') return shape.optional ? undefined : [];
346
+ if (isPlainObject(value)) return value;
347
+ const list = Array.isArray(value) ? value : [value];
348
+ const item = shape.item;
349
+ return list.map((v) => normalize(v, item));
350
+ }
351
+ if (shape.properties && isPlainObject(value)) {
352
+ const out: Record<string, unknown> = { ...value };
353
+ for (const [key, child] of Object.entries(shape.properties)) {
354
+ // Only own keys: `out.constructor` would read Object.prototype's.
355
+ const current = Object.hasOwn(out, key) ? out[key] : undefined;
356
+ if (key === '__proto__') continue;
357
+ const normalized = normalize(current, child);
358
+ if (normalized === undefined) delete out[key];
359
+ else out[key] = normalized;
360
+ }
361
+ return out;
362
+ }
363
+ return value;
364
+ }
365
+
366
+ // ─── Helpers ─────────────────────────────────────────────────────────────
367
+
368
+ /** Apply a node's own marks to the shape read from what it wraps. */
369
+ function withMarks(
370
+ optional: boolean,
371
+ sensitive: boolean
372
+ ): (shape: FieldShape | undefined) => FieldShape | undefined {
373
+ return (shape) => {
374
+ if (!optional && !sensitive) return shape;
375
+ return {
376
+ ...shape,
377
+ ...(optional ? { optional: true } : {}),
378
+ ...(sensitive ? { sensitive: true } : {}),
379
+ };
380
+ };
381
+ }
382
+
383
+ function asList(value: unknown): unknown[] {
384
+ return Array.isArray(value) ? value : [];
385
+ }
386
+
387
+ function isRecord(value: unknown): value is Record<string, unknown> {
388
+ return typeof value === 'object' && value !== null;
389
+ }
390
+
391
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
392
+ return isRecord(value) && !Array.isArray(value) && !(value instanceof Blob);
393
+ }
@@ -1,37 +1,47 @@
1
1
  /**
2
- * Sensitive field stripping — removes password/token/CVV-style fields
3
- * from form values before they are echoed back to the client as
4
- * `submittedValues` for form repopulation.
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
- * Applied to both action paths:
7
- * - With-JS action path: `createActionClient()` in `action-client.ts`
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
- * Why: on a validation failure, timber echoes submitted form values back so
11
- * the user doesn't have to re-type everything. Without filtering, plaintext
12
- * passwords / credit-card numbers / TOTP codes would travel through the RSC
13
- * stream (with-JS) or land in the HTML as `defaultValue` attributes (no-JS)
14
- * — ending up in browser history, proxy logs, disk caches, and the
15
- * back-forward cache.
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
- * Safe by default: the built-in deny-list is applied unconditionally unless
18
- * the user explicitly opts out via `forms.stripSensitiveFields: false` in
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
- * See design/08-forms-and-actions.md §"Validation errors"
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
  */
25
33
 
26
34
  import { isDebug } from './debug.ts';
35
+ import type { FieldShape } from './schema-introspection.ts';
27
36
 
28
37
  // ─── Public types ────────────────────────────────────────────────────────
29
38
 
30
39
  /**
31
- * How to strip sensitive fields from `submittedValues`.
40
+ * How to strip sensitive fields from `submittedValues`, by name.
32
41
  *
33
- * - `true` / `undefined` — use the built-in deny-list (default, safe).
34
- * - `false` — do not strip anything (dev convenience; never do this in prod).
42
+ * - `true` / `undefined` — use the built-in deny-list (default).
43
+ * - `false` — strip no field by name. Fields the schema marks sensitive are
44
+ * still stripped.
35
45
  * - `string[]` — additional field names to strip, merged with the built-in list.
36
46
  * - `(name) => boolean` — custom predicate, fully replaces the built-in list.
37
47
  * Return `true` to strip, `false` to keep. The `name` argument is the raw
@@ -47,29 +57,33 @@ export type SensitiveFieldsOption = boolean | readonly string[] | ((name: string
47
57
  *
48
58
  * Any field whose normalized name *contains* one of these strings is
49
59
  * considered sensitive. Entries like `currentPassword`, `passwordConfirmation`,
50
- * and `user.password` all match via the `password` substring.
60
+ * and `user.password` all match via the `password` substring. Every pattern
61
+ * here is long enough not to occur inside an ordinary word.
51
62
  */
52
63
  const BUILTIN_SUBSTRING_PATTERNS: readonly string[] = [
53
64
  'password',
54
65
  'passwd',
55
- 'pwd',
56
66
  'secret',
57
67
  'apikey',
58
68
  'accesstoken',
59
69
  'refreshtoken',
60
- 'cvv',
61
- 'cvc',
62
70
  'cardnumber',
63
71
  'cardcvc',
64
- 'ssn',
65
72
  'socialsecuritynumber',
66
- 'otp',
67
- 'totp',
68
73
  'mfacode',
69
74
  'twofactorcode',
70
75
  'privatekey',
71
76
  ];
72
77
 
78
+ /**
79
+ * Patterns matched at the start or end of a word of the field name. These are
80
+ * short enough to occur inside ordinary words (`otp` in `footPath` and
81
+ * `notpublic`, `ssn` in `class_number` and `classnumber`), so they must
82
+ * begin or end a word: `otp`, `otpCode`, `otpcode`, `userotp`, `user_ssn`,
83
+ * `SSNLast4`, `newpwd`, `cardcvv`.
84
+ */
85
+ const BUILTIN_WORD_PATTERNS: readonly string[] = ['pwd', 'cvv', 'cvc', 'ssn', 'otp', 'totp'];
86
+
73
87
  /**
74
88
  * Exact matches against the normalized field name. These are field names that
75
89
  * are too short or too common to substring-match safely. e.g. `token` alone
@@ -85,18 +99,27 @@ const BUILTIN_EXACT_PATTERNS: readonly string[] = ['token'];
85
99
  * `apikey`).
86
100
  */
87
101
  function normalize(name: string): string {
88
- let out = '';
89
- for (let i = 0; i < name.length; i++) {
90
- const ch = name.charCodeAt(i);
91
- if (ch === 0x5f /* _ */ || ch === 0x2d /* - */) continue;
92
- // A-Z → a-z
93
- if (ch >= 0x41 && ch <= 0x5a) {
94
- out += String.fromCharCode(ch + 32);
95
- } else {
96
- out += name[i];
97
- }
98
- }
99
- return out;
102
+ return name.replace(/[_-]/g, '').toLowerCase();
103
+ }
104
+
105
+ /**
106
+ * Split a field name into lowercase words at anything that is not a letter
107
+ * and at a lowercase-to-uppercase hump: `user_ssnLast4` → `user`, `ssn`,
108
+ * `last`. An acronym stays joined to what follows it (`OTPcode` →
109
+ * `otpcode`, `SSNLast` → `ssnlast`), which a start-of-word match still finds.
110
+ */
111
+ function words(name: string): string[] {
112
+ return name
113
+ .split(/[^A-Za-z]+|(?<=[a-z])(?=[A-Z])/)
114
+ .filter(Boolean)
115
+ .map((w) => w.toLowerCase());
116
+ }
117
+
118
+ /** Whether a short pattern begins or ends one of the name's words. */
119
+ function hasWordPattern(name: string): boolean {
120
+ return words(name).some((word) =>
121
+ BUILTIN_WORD_PATTERNS.some((p) => word.startsWith(p) || word.endsWith(p))
122
+ );
100
123
  }
101
124
 
102
125
  /**
@@ -109,6 +132,7 @@ function isBuiltinSensitive(name: string, extras?: readonly string[]): boolean {
109
132
  for (const pattern of BUILTIN_SUBSTRING_PATTERNS) {
110
133
  if (normalized.includes(pattern)) return true;
111
134
  }
135
+ if (hasWordPattern(name)) return true;
112
136
  if (extras && extras.length > 0) {
113
137
  for (const extra of extras) {
114
138
  const normExtra = normalize(extra);
@@ -122,7 +146,7 @@ function isBuiltinSensitive(name: string, extras?: readonly string[]): boolean {
122
146
  // ─── Predicate resolution ────────────────────────────────────────────────
123
147
 
124
148
  /**
125
- * A resolved predicate: `null` means "don't strip anything" (the option was
149
+ * A resolved predicate: `null` means "strip no field by name" (the option was
126
150
  * explicitly `false`). Otherwise a function from raw field name → boolean.
127
151
  */
128
152
  export type ResolvedSensitivePredicate = ((name: string) => boolean) | null;
@@ -133,7 +157,7 @@ export type ResolvedSensitivePredicate = ((name: string) => boolean) | null;
133
157
  *
134
158
  * - Per-action `undefined` → fall back to global.
135
159
  * - Global `undefined` → use built-in list.
136
- * - Either level set to `false` → disable stripping entirely (returns `null`).
160
+ * - Either level set to `false` → no name matching (returns `null`).
137
161
  * - `true` → built-in list.
138
162
  * - `string[]` → built-in ∪ extras.
139
163
  * - function → custom, replaces the built-in list entirely.
@@ -179,20 +203,24 @@ export function getGlobalSensitiveFieldsConfig(): SensitiveFieldsOption | undefi
179
203
  // submitted many times in dev mode.
180
204
  const warnedFields = new Set<string>();
181
205
 
182
- function warnStripped(name: string): void {
206
+ function warnStripped(name: string, markedInSchema: boolean): void {
183
207
  if (!isDebug()) return;
184
208
  if (warnedFields.has(name)) return;
185
209
  warnedFields.add(name);
186
210
  console.warn(
187
211
  `[timber] stripped sensitive field "${name}" from submittedValues. ` +
188
- `Override via forms.stripSensitiveFields in timber.config.ts.`
212
+ (markedInSchema
213
+ ? `The action's schema marks it sensitive; remove the mark to echo it.`
214
+ : `Override via forms.stripSensitiveFields in timber.config.ts.`)
189
215
  );
190
216
  }
191
217
 
192
218
  /**
193
- * Walk an object (recursively) and return a copy with every key matching
194
- * `predicate` removed. Nested objects like `{ user: { password: '...' } }`
195
- * are handled — `user.password` is stripped while other `user.*` fields remain.
219
+ * Walk an object (recursively) and return a copy without its sensitive
220
+ * fields: every key `predicate` matches, and every field `shape` (the
221
+ * schema's declared shape) marks sensitive. Nested objects like
222
+ * `{ user: { password: '...' } }` are handled — `user.password` is stripped
223
+ * while other `user.*` fields remain.
196
224
  *
197
225
  * - Arrays are walked element-wise (object entries inside arrays are cleaned).
198
226
  * - Non-plain values (strings, numbers, Files, Dates, etc.) are returned as-is.
@@ -200,30 +228,59 @@ function warnStripped(name: string): void {
200
228
  * — we do NOT set it to an empty string, because that would overwrite a
201
229
  * valid `defaultValue` the form author might have set.
202
230
  */
203
- export function stripSensitiveFields<T>(value: T, predicate: ResolvedSensitivePredicate): T {
204
- // Null predicate = stripping disabled entirely.
205
- if (predicate === null) return value;
206
- if (value === null || value === undefined) return value;
207
- if (typeof value !== 'object') return value;
208
- if (value instanceof File || value instanceof Date) return value;
231
+ export function stripSensitiveFields(
232
+ value: Record<string, unknown>,
233
+ predicate: ResolvedSensitivePredicate,
234
+ shape?: FieldShape
235
+ ): Record<string, unknown> {
236
+ if (predicate === null && !hasSensitive(shape)) return value;
237
+ return stripFrom(value, predicate, shape) as Record<string, unknown>;
238
+ }
239
+
240
+ function stripFrom(
241
+ value: unknown,
242
+ predicate: ResolvedSensitivePredicate,
243
+ shape: FieldShape | undefined
244
+ ): unknown {
245
+ if (value === null || typeof value !== 'object') return value;
246
+ if (value instanceof Blob || value instanceof Date) return value;
209
247
 
210
248
  if (Array.isArray(value)) {
211
- return value.map((item) => stripSensitiveFields(item, predicate)) as unknown as T;
249
+ return value.map((item) => stripFrom(item, predicate, shape?.item));
212
250
  }
213
251
 
252
+ // A list `parseFormData` kept as an object (an indexed list with a gap,
253
+ // `keys.0` and `keys.2`): every value is an item.
254
+ const indexed = shape?.item !== undefined && shape.properties === undefined;
214
255
  const result: Record<string, unknown> = {};
215
- for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
216
- if (predicate(key)) {
217
- warnStripped(key);
256
+ for (const [key, nested] of Object.entries(value)) {
257
+ const child = indexed ? shape.item : shape?.properties?.[key];
258
+ if (child?.sensitive || predicate?.(key)) {
259
+ warnStripped(key, child?.sensitive === true);
218
260
  continue;
219
261
  }
220
- result[key] = stripSensitiveFields(nested, predicate);
262
+ result[key] = stripFrom(nested, predicate, child);
221
263
  }
222
- return result as unknown as T;
264
+ return result;
265
+ }
266
+
267
+ /** Whether `shape` marks any field at or below it sensitive. */
268
+ function hasSensitive(shape: FieldShape | undefined): boolean {
269
+ if (!shape) return false;
270
+ if (shape.sensitive) return true;
271
+ if (hasSensitive(shape.item)) return true;
272
+ return Object.values(shape.properties ?? {}).some(hasSensitive);
223
273
  }
224
274
 
225
275
  // ─── Test helpers ────────────────────────────────────────────────────────
226
276
 
277
+ /** The built-in patterns, for the docs drift test. */
278
+ export const __BUILTIN_SENSITIVE_PATTERNS: readonly string[] = [
279
+ ...BUILTIN_SUBSTRING_PATTERNS,
280
+ ...BUILTIN_WORD_PATTERNS,
281
+ ...BUILTIN_EXACT_PATTERNS,
282
+ ];
283
+
227
284
  /** Reset the "warned once" cache. Exposed for tests. */
228
285
  export function __resetSensitiveFieldsWarnings(): void {
229
286
  warnedFields.clear();
@@ -1 +0,0 @@
1
- {"version":3,"file":"use-form-field.d.ts","sourceRoot":"","sources":["../../src/client/use-form-field.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAML,KAAK,QAAQ,EACb,KAAK,WAAW,EAChB,KAAK,cAAc,EACpB,MAAM,OAAO,CAAC;AAEf;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAC5B,YAAY,EAAE,CAAC,GACd,CAAC,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,WAAW,CAAC,WAAW,CAAC,CAAC,CAiFlF"}