-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrule-validator.ts
More file actions
870 lines (811 loc) · 34.9 KB
/
Copy pathrule-validator.ts
File metadata and controls
870 lines (811 loc) · 34.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Validation-Rule Evaluator (ADR-0020)
*
* Where `record-validator.ts` checks field *shape* (types, lengths, option
* membership), this module enforces the object-level **business rules**
* declared in `ObjectSchema.validations` — the discriminated union of
* `state_machine`, `cross_field`, `script`, … rules.
*
* Until ADR-0020 these rules were pure declaration: nothing on the write
* path ever read `objectSchema.validations`, so a `state_machine` rule that
* said "an account can't jump from churned straight back to prospect"
* silently allowed exactly that. This evaluator closes that gap.
*
* ## What runs here
*
* - `state_machine` — the headline guardrail. On update, if the state field
* changed and the new value is not in `transitions[oldValue]`, the write
* is rejected. Needs the **prior** record (see plumbing note below). On
* insert, if the rule declares `initialStates`, the created value must be one
* of them (the FSM entry point, #3165); otherwise insert is a no-op.
* - `script` / `cross_field` — CEL predicates. If the predicate evaluates
* TRUE the rule is violated. These share the prior-record gap with
* `state_machine` (a PATCH carries only changed fields), so they are
* evaluated against the *merged* record `{ ...previous, ...patch }`.
* - `format` — a single field's value against a regex and/or a named format
* (`email` / `url` / `phone` / `json`). Only runs when the write touches
* the field and the value is non-empty (emptiness is the field-shape
* validator's job, not the format rule's).
* - `json_schema` — a JSON field validated against a JSON Schema via ajv.
* - `conditional` — evaluates the `when` CEL predicate and then recurses into
* `then` (true) or `otherwise` (false). The nested rule's violation message
* is surfaced; the *outer* conditional's `severity` decides whether it
* blocks (so `when`-gated guards can be advisory as a unit).
*
* Every variant declared by `ValidationRuleSchema` is enforced here — the
* schema deliberately excludes anything that would need I/O or a handler model
* (uniqueness → DB index, async → form layer, custom → lifecycle hook). The
* engine invokes this evaluator on insert, single-id update, and — per matched
* row — multi-row (`multi: true`) update (#3106), so no declared rule is a
* silent no-op on the write path. The `events` enum admits only `insert`/`update`
* to match: `delete` carries no record payload to validate, so it was removed
* from the spec rather than advertised-but-unenforced (#3184). Guard deletions
* with a `beforeDelete` lifecycle hook instead.
*
* ## Execution-control semantics (from `BaseValidationSchema`)
*
* - `active: false` → rule skipped entirely.
* - `events` → rule only runs for the matching write context
* (`insert` / `update`). `delete` is not a write
* payload context here.
* - `priority` → rules evaluated low-number-first (stable).
* - `severity` → only `error` blocks the write. `warning` / `info`
* are logged (best-effort) and never throw.
*
* ## Fail-open for *broken* rules, fail-closed for *violated* rules
*
* A CEL predicate that cannot be evaluated (parse error, references an
* unbound variable, …) is a broken rule, not a violated one — it is logged
* and skipped rather than bricking every write to the object. A predicate
* that evaluates cleanly to "violated", or a transition that is definitively
* illegal, is fail-closed (the write is rejected).
*
* ## Prior-record plumbing
*
* `state_machine` and the field-spanning predicates are meaningful only with
* the record's prior state. The engine fetches it once (see
* `engine.update`) and threads it in via `opts.previous`. On `insert` there
* is no prior state, so `state_machine`'s TRANSITION check is a no-op — but its
* `initialStates` entry-point check (#3165) does run against the created value.
* On a
* multi-row update the engine reads the row-scoped match set (the same AST the
* write binds, shared with the `readonlyWhen` bulk strip) and calls the
* evaluator once per matched row — one payload, N priors (#3106).
*/
import { ExpressionEngine } from '@objectstack/formula';
import type { Expression } from '@objectstack/spec';
import Ajv, { type ValidateFunction } from 'ajv';
import { ValidationError, type FieldValidationError } from './record-validator.js';
type Mode = 'insert' | 'update';
interface BaseRule {
type: string;
name: string;
message: string;
active?: boolean;
events?: Array<'insert' | 'update'>;
priority?: number;
severity?: 'error' | 'warning' | 'info';
}
interface StateMachineRule extends BaseRule {
type: 'state_machine';
field: string;
transitions: Record<string, string[]>;
/** States a record may be CREATED in (#3165). When set, an insert whose state
* field value is outside this list is rejected — the FSM entry point. */
initialStates?: string[];
}
interface PredicateRule extends BaseRule {
type: 'script' | 'cross_field';
condition: string | Expression;
fields?: string[];
}
interface FormatRule extends BaseRule {
type: 'format';
field: string;
regex?: string;
format?: 'email' | 'url' | 'phone' | 'json';
}
interface JsonSchemaRule extends BaseRule {
type: 'json_schema';
field: string;
schema: Record<string, unknown>;
}
interface ConditionalRule extends BaseRule {
type: 'conditional';
when: string | Expression;
then: BaseRule;
otherwise?: BaseRule;
}
/**
* Context threaded through every rule evaluation. `data` is the raw incoming
* write (a PATCH on update); `merged` overlays it on the prior record so a
* predicate referencing an unchanged field still sees its persisted value.
* Field-scoped rules (`state_machine`, `format`, `json_schema`) key off `data`
* to decide whether the write actually touched their field.
*/
interface RuleContext {
data: Record<string, unknown>;
merged: Record<string, unknown>;
previous: Record<string, unknown> | undefined;
mode: Mode;
logger: EvaluateRulesOptions['logger'];
}
/**
* Shared ajv instance. `strict: false` tolerates author-written JSON Schemas
* that use vendor keywords; `compile` results are memoised per schema object
* (see `jsonSchemaCache`) so we don't recompile on every write.
*/
const ajv = new Ajv({ allErrors: true, strict: false });
const jsonSchemaCache = new WeakMap<object, ValidateFunction>();
export interface EvaluateRulesOptions {
/** Prior persisted record (update only). Absent on insert. */
previous?: Record<string, unknown> | null;
/** Optional logger for non-blocking diagnostics (broken rules, warnings). */
logger?: { warn?: (msg: string, meta?: any) => void };
/**
* The acting user (ADR-0068 EvalUser shape), surfaced to per-option
* `visibleWhen` predicates as `current_user` so role/context-gated options can
* be enforced server-side (objectui#2284). Absent on system/unauthenticated
* writes — role predicates then reference an unbound `current_user`, fault,
* and fail-open (see {@link evaluateOptionVisibility}).
*/
currentUser?: { id?: string; roles?: string[]; organizationId?: string | null; [k: string]: unknown } | null;
}
/**
* Returns true when the object declares at least one validation rule whose
* correct evaluation needs the prior record (so the engine knows whether the
* extra fetch on the update path is worth it).
*/
export function needsPriorRecord(
objectSchema: { validations?: unknown[]; fields?: Record<string, ConditionalFieldDef> } | undefined | null,
): boolean {
const rules = objectSchema?.validations;
const ruleNeeds = Array.isArray(rules) && rules.some((r) => ruleNeedsPrior(r));
return !!(ruleNeeds || fieldsNeedPrior(objectSchema?.fields));
}
/**
* Strip fields whose `readonlyWhen` CEL predicate is TRUE for the (merged)
* record from an UPDATE payload — the field is locked, so an incoming change is
* ignored (the persisted value is kept) rather than rejected. Returns the same
* object when nothing is locked, else a shallow copy with the locked keys
* removed. A broken predicate is fail-open (the change is allowed through).
*/
export function stripReadonlyWhenFields(
objectSchema: { fields?: Record<string, ConditionalFieldDef> } | undefined | null,
data: Record<string, unknown> | undefined | null,
previous: Record<string, unknown> | undefined | null,
logger?: EvaluateRulesOptions['logger'],
): Record<string, unknown> | undefined | null {
const fields = objectSchema?.fields;
if (!fields || !data) return data;
const merged = { ...(previous ?? {}), ...data };
let result = data;
for (const [name, def] of Object.entries(fields)) {
if (!def?.readonlyWhen || !(name in data)) continue;
if (isReadonlyWhenLocked(def, merged, previous ?? undefined, name, logger)) {
if (result === data) result = { ...data };
delete (result as Record<string, unknown>)[name];
logger?.warn?.(`Field '${name}' is read-only (readonlyWhen) — ignoring incoming change`);
}
}
return result;
}
/**
* Evaluate one field's `readonlyWhen` predicate against a (merged) record.
* TRUE ⇒ the field is locked for that record and the incoming change must be
* dropped. A broken predicate is fail-open (returns `false` — the change is
* allowed through), matching the strip's historical behaviour. Shared by the
* single-id ({@link stripReadonlyWhenFields}) and bulk
* ({@link stripReadonlyWhenFieldsMulti}) strips.
*/
function isReadonlyWhenLocked(
def: ConditionalFieldDef,
merged: Record<string, unknown>,
previous: Record<string, unknown> | undefined,
name: string,
logger?: EvaluateRulesOptions['logger'],
): boolean {
const res = ExpressionEngine.evaluate<boolean>(toExpression(def.readonlyWhen!), {
record: merged,
previous,
});
if (!res.ok) {
logger?.warn?.(`readonlyWhen for '${name}' failed to evaluate — change allowed through`);
return false;
}
return res.value === true;
}
/**
* True when the UPDATE payload writes at least one field that declares a
* `readonlyWhen` predicate. A cheap gate the engine uses to decide whether the
* bulk update path must fetch its matched rows for
* {@link stripReadonlyWhenFieldsMulti} — no `readonlyWhen` field in the payload
* ⇒ no fetch, no cost.
*/
export function hasReadonlyWhenInPayload(
objectSchema: { fields?: Record<string, ConditionalFieldDef> } | undefined | null,
data: Record<string, unknown> | undefined | null,
): boolean {
const fields = objectSchema?.fields;
if (!fields || !data) return false;
for (const [name, def] of Object.entries(fields)) {
if (def?.readonlyWhen && name in data) return true;
}
return false;
}
/**
* Multi-row counterpart of {@link stripReadonlyWhenFields} (#3042). A bulk
* `updateMany` applies ONE payload to every matched row, but `readonlyWhen` is a
* PER-ROW predicate — a single merged prior is not enough. Given the matched
* rows' prior state (the engine reads them with the SAME row-scoped AST the
* write binds — one query), a `readonlyWhen` field is dropped from the batch
* when its predicate is TRUE for AT LEAST ONE matched row: a bulk write cannot
* lock the field for some rows and write it for others, so a field locked in any
* target row is fail-safe-dropped for all (narrow the `where` to reach the rows
* where it is unlocked). A field NO matched row locks is written normally — a
* legitimate bulk edit of an unlocked conditional field is unaffected. A broken
* predicate is fail-open for that row. INSERT is exempt (update path only),
* symmetric with the single-id strip.
*
* Returns the same object when nothing is stripped, else a shallow copy with the
* locked keys removed.
*/
export function stripReadonlyWhenFieldsMulti(
objectSchema: { fields?: Record<string, ConditionalFieldDef> } | undefined | null,
data: Record<string, unknown> | undefined | null,
priorRows: ReadonlyArray<Record<string, unknown>> | undefined | null,
logger?: EvaluateRulesOptions['logger'],
): Record<string, unknown> | undefined | null {
const fields = objectSchema?.fields;
if (!fields || !data) return data;
const rows = priorRows ?? [];
let result = data;
for (const [name, def] of Object.entries(fields)) {
if (!def?.readonlyWhen || !(name in data)) continue;
const lockedInSomeRow = rows.some((row) =>
isReadonlyWhenLocked(def, { ...(row ?? {}), ...data }, row ?? undefined, name, logger),
);
if (lockedInSomeRow) {
if (result === data) result = { ...data };
delete (result as Record<string, unknown>)[name];
logger?.warn?.(
`Field '${name}' is read-only (readonlyWhen) in ≥1 matched row — ignoring incoming change on bulk update`,
);
}
}
return result;
}
/**
* Strip CALLER-SUPPLIED writes to statically `readonly: true` fields from an
* UPDATE payload (#2948). Unlike `readonlyWhen` (conditional, handled above), a
* static `readonly` field was never enforced on the server write path: the
* record validator only SKIPS it from validation, so a user-context update
* could overwrite audit stamps, provenance, or any other read-only column. We
* STRIP the change (symmetric with `readonlyWhen`) rather than reject it, for
* compatibility.
*
* Two guards keep every legitimate write intact:
* - `suppliedKeys` — only keys the CALLER sent are candidates. Server stamps
* applied by beforeUpdate hooks or write middleware (e.g. `updated_by` /
* `updated_at`, plugin.ts) land in `data` but are NOT in `suppliedKeys`, so
* they survive. A caller that *explicitly* forges e.g. `updated_by` simply
* has it dropped for that request (the last-modified stamp is left unchanged
* — safe).
* - system context — the caller passes this strip only for NON-system writes;
* system-context writes (import, seed replay, approvals, lifecycle hooks —
* all `isSystem: true`) legitimately set read-only columns and skip it.
*
* Returns the same object when nothing is stripped, else a shallow copy with the
* offending keys removed.
*/
export function stripReadonlyFields(
objectSchema: { fields?: Record<string, ConditionalFieldDef> } | undefined | null,
data: Record<string, unknown> | undefined | null,
suppliedKeys: ReadonlySet<string>,
logger?: EvaluateRulesOptions['logger'],
): Record<string, unknown> | undefined | null {
const fields = objectSchema?.fields;
if (!fields || !data) return data;
let result = data;
for (const [name, def] of Object.entries(fields)) {
if (!def?.readonly) continue;
if (!(name in (result as Record<string, unknown>))) continue;
if (!suppliedKeys.has(name)) continue; // server-stamped, not caller-supplied — keep
if (result === data) result = { ...data };
delete (result as Record<string, unknown>)[name];
logger?.warn?.(`Field '${name}' is read-only — ignoring incoming change (#2948)`);
}
return result;
}
/**
* A rule needs the prior record if it reasons about the transition or compares
* against unchanged fields (`state_machine` / `cross_field` / `script`), or if
* it is a `conditional` whose branches (or `when`) recursively do. `format` and
* `json_schema` only inspect the incoming value, so they never need it.
*/
function ruleNeedsPrior(r: unknown): boolean {
if (r == null || typeof r !== 'object') return false;
const type = (r as BaseRule).type;
if (type === 'state_machine' || type === 'cross_field' || type === 'script') {
return true;
}
if (type === 'conditional') {
const c = r as ConditionalRule;
// `when` is evaluated against the merged record; the branches may need prior
// state. Be conservative and fetch if either branch does.
return ruleNeedsPrior(c.then) || ruleNeedsPrior(c.otherwise);
}
return false;
}
/** Field-level conditional rules (B2): a field is required / read-only when its
* CEL predicate is TRUE over the record. */
interface ConditionalFieldOption {
value?: unknown;
/** Per-option visibility predicate (CEL) — objectui#2284. */
visibleWhen?: string | Expression;
}
interface ConditionalFieldDef {
requiredWhen?: string | Expression;
conditionalRequired?: string | Expression; // back-compat alias of requiredWhen
readonlyWhen?: string | Expression;
/** Static, unconditional read-only flag (`field.readonly`). #2948. */
readonly?: boolean;
/** Field type — scopes per-option `visibleWhen` enforcement to choice fields. */
type?: string;
/** select/multiselect/radio/checkboxes options; an option may gate itself with `visibleWhen`. */
options?: Array<ConditionalFieldOption | null | undefined>;
}
/**
* Choice fields whose picked value(s) are drawn from `options`. Includes the
* multi-value `checkboxes` (its client widget cascades identically to
* `multiselect`, objectui#2715) so its gated options are enforced server-side too.
*/
const CHOICE_FIELD_TYPES = new Set(['select', 'multiselect', 'radio', 'checkboxes']);
/** True when a choice field carries at least one option gated by `visibleWhen`. */
function fieldHasOptionVisibility(def: ConditionalFieldDef | undefined | null): boolean {
if (!def || !CHOICE_FIELD_TYPES.has(String(def.type))) return false;
return Array.isArray(def.options) && def.options.some((o) => o != null && o.visibleWhen != null);
}
function isMissing(v: unknown): boolean {
return v === undefined || v === null || (typeof v === 'string' && v.trim() === '');
}
/** True when any field declares a conditional rule that needs the merged/prior
* record to evaluate (so the engine fetches `previous` on update). Per-option
* `visibleWhen` counts too — a cascade predicate can reference an unchanged
* sibling that only `previous` supplies (objectui#2284). */
function fieldsNeedPrior(fields: Record<string, ConditionalFieldDef> | undefined): boolean {
if (!fields) return false;
return Object.values(fields).some(
(f) => f && (f.requiredWhen || f.conditionalRequired || f.readonlyWhen || fieldHasOptionVisibility(f)),
);
}
/** Normalize an author-time ExpressionInput into the canonical envelope. */
function toExpression(cond: string | Expression): Expression {
return typeof cond === 'string' ? { dialect: 'cel', source: cond } : cond;
}
/**
* Per-option authorization / cascade enforcement (objectui#2284).
*
* A `select` / `multiselect` / `radio` / `checkboxes` option may gate itself with
* a `visibleWhen` CEL predicate, evaluated against the live record + `current_user`
* (the same predicate the client uses to hide the option). Client-side hiding is
* UX, not a security boundary — a caller can still submit a hidden value — so on
* write we re-evaluate the predicate for the *picked* value(s) and reject any
* that resolve cleanly to FALSE. This enforces both role/context gating
* (`'admin' in current_user.positions`) and cascade integrity (`record.country ==
* 'cn'`), server-side.
*
* Only WRITTEN fields are checked — an unchanged persisted value is left alone.
* A predicate that can't be evaluated (missing referenced field, unbound
* `current_user` on a system write) is **fail-open** (logged, allowed), matching
* every other field rule here: a broken cascade predicate must never brick a
* write. Authorization gating therefore depends on the engine binding
* `current_user` on authenticated writes.
*/
function evaluateOptionVisibility(
fields: Record<string, ConditionalFieldDef> | undefined,
data: Record<string, unknown>,
merged: Record<string, unknown>,
previous: Record<string, unknown> | undefined,
currentUser: EvaluateRulesOptions['currentUser'],
errors: FieldValidationError[],
logger: EvaluateRulesOptions['logger'],
): void {
if (!fields) return;
const user = (currentUser ?? undefined) as any;
for (const [name, def] of Object.entries(fields)) {
if (!fieldHasOptionVisibility(def) || !(name in data)) continue;
const raw = data[name];
if (raw === undefined || raw === null || raw === '') continue;
const picked = Array.isArray(raw) ? raw : [raw];
for (const value of picked) {
// Match by string form, mirroring the enum validator (record-validator
// compares `String(...)`). A numeric option value sent/stored as a string
// (or vice-versa) must still hit its gate, not silently fail-open.
const opt = def.options!.find((o) => o != null && String(o.value) === String(value));
// Unknown value (not in options) or an ungated option → nothing to enforce
// here; an out-of-set value is the enum validator's concern, not ours.
if (!opt || opt.visibleWhen == null) continue;
const res = ExpressionEngine.evaluate<boolean>(toExpression(opt.visibleWhen), {
record: merged,
previous,
user,
});
if (!res.ok) {
logger?.warn?.(
`option visibleWhen for '${name}=${String(value)}' failed to evaluate — allowed through`,
);
continue; // fail-open
}
if (res.value === false) {
errors.push({
field: name,
code: 'invalid_option',
message: `${name}: option '${String(value)}' is not available`,
});
}
}
}
}
/**
* Evaluate an object's declared validation rules against an incoming write.
*
* Throws `ValidationError` (the same envelope `validateRecord` uses, so REST
* surfaces a single `400 VALIDATION_FAILED`) when one or more `error`-severity
* rules are violated. Returns void otherwise.
*/
export function evaluateValidationRules(
objectSchema: { validations?: unknown[]; fields?: Record<string, ConditionalFieldDef> } | undefined | null,
data: Record<string, unknown> | undefined | null,
mode: Mode,
opts: EvaluateRulesOptions = {},
): void {
if (!data) return;
const rules = objectSchema?.validations;
const hasRules = Array.isArray(rules) && rules.length > 0;
const fields = objectSchema?.fields;
const hasFieldRules = fieldsNeedPrior(fields);
if (!hasRules && !hasFieldRules) return;
const previous = opts.previous ?? undefined;
// Merged view used by predicate rules: prior state overlaid with the PATCH,
// so a rule referencing an unchanged field still sees its persisted value.
const merged: Record<string, unknown> = { ...(previous ?? {}), ...data };
// #1871 — on INSERT, a field omitted entirely from the payload is absent from
// the record, so a `record.x == null` predicate sees a missing CEL key (which
// does not equal null) and silently can't match. Default declared-but-absent
// fields to null so an omitted optional reads as null — matching an explicit
// `null` and the UPDATE path (where the prior record already supplies them).
if (mode === 'insert' && fields) {
for (const name of Object.keys(fields)) {
if (!(name in merged)) merged[name] = null;
}
}
const ctx: RuleContext = { data, merged, previous, mode, logger: opts.logger };
const errors: FieldValidationError[] = [];
// Field-level conditional rules (B2): a field whose `requiredWhen`
// (or its `conditionalRequired` alias) predicate is TRUE over the merged
// record must have a value — enforced server-side so the rule can't be
// bypassed. (`readonlyWhen` is handled by stripReadonlyWhenFields on the
// write path, not here.) A broken predicate is fail-open (logged, skipped).
if (hasFieldRules && fields) {
for (const [name, def] of Object.entries(fields)) {
const pred = def?.requiredWhen ?? def?.conditionalRequired;
if (!pred) continue;
const res = ExpressionEngine.evaluate<boolean>(toExpression(pred), { record: merged, previous });
if (!res.ok) {
opts.logger?.warn?.(`requiredWhen for '${name}' failed to evaluate — skipped`);
continue;
}
if (res.value === true && isMissing(merged[name])) {
errors.push({ field: name, code: 'required', message: `${name} is required` });
}
}
}
// Per-option authorization / cascade gating (objectui#2284): reject a written
// choice value whose option `visibleWhen` resolves cleanly to FALSE against the
// merged record + `current_user`. Complements the client-side hiding, which is
// not a security boundary.
evaluateOptionVisibility(fields, data, merged, previous, opts.currentUser, errors, opts.logger);
const ordered = (hasRules ? rules! : [])
.filter((r): r is BaseRule => r != null && typeof r === 'object')
.filter((r) => r.active !== false)
.filter((r) => {
const events = r.events ?? ['insert', 'update'];
return events.includes(mode);
})
.sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100));
for (const rule of ordered) {
let violation: FieldValidationError | null = null;
try {
violation = evaluateRule(rule, ctx);
} catch (err) {
// Defensive: a broken rule must never brick a write.
opts.logger?.warn?.(`Validation rule '${rule.name}' threw — skipped`, err);
continue;
}
if (!violation) continue;
const severity = rule.severity ?? 'error';
if (severity === 'error') {
errors.push(violation);
} else {
opts.logger?.warn?.(
`Validation rule '${rule.name}' (${severity}): ${violation.message}`,
);
}
}
if (errors.length > 0) throw new ValidationError(errors);
}
/**
* Dispatch a single rule to its checker, returning the violation (or null).
* Shared by the top-level loop and by `checkConditional`, which recurses into
* its `then` / `otherwise` branch. Unknown types return null — but the schema
* (`ValidationRuleSchema`) only admits the types handled below, so in practice
* every declared rule is covered.
*/
function evaluateRule(rule: BaseRule, ctx: RuleContext): FieldValidationError | null {
switch (rule.type) {
case 'state_machine':
return checkStateMachine(rule as StateMachineRule, ctx.mode, ctx.data, ctx.previous);
case 'script':
case 'cross_field':
return checkPredicate(rule as PredicateRule, ctx.merged, ctx.previous, ctx.logger);
case 'format':
return checkFormat(rule as FormatRule, ctx.data, ctx.logger);
case 'json_schema':
return checkJsonSchema(rule as JsonSchemaRule, ctx.data, ctx.logger);
case 'conditional':
return checkConditional(rule as ConditionalRule, ctx);
default:
return null;
}
}
/**
* State-machine check.
*
* On UPDATE (with a prior record): if the state field changed, the new value
* must appear in `transitions[oldValue]`. Lenient where it cannot reason (no
* prior record, unchanged value, or a prior state with no declared transitions)
* so it never blocks legitimate or legacy data.
*
* On INSERT: if the rule declares `initialStates` (#3165), the state field's
* (defaulted) value must be one of them — the FSM entry point, since a `select`
* field alone permits ANY declared option as an initial value (a record could
* otherwise be born already `approved`). Absent `initialStates`, insert is a
* no-op (legacy behavior); a missing/empty value is left to required-validation.
*/
function checkStateMachine(
rule: StateMachineRule,
mode: Mode,
data: Record<string, unknown>,
previous: Record<string, unknown> | undefined,
): FieldValidationError | null {
if (mode === 'insert') {
const initial = rule.initialStates;
if (!Array.isArray(initial) || initial.length === 0) return null; // no initial-state contract → legacy no-op
if (!(rule.field in data)) return null; // absent → required-validation's job
const value = data[rule.field];
if (value === undefined || value === null || value === '') return null; // empty → not an initial state to check
if (!initial.includes(String(value))) {
return {
field: rule.field,
code: 'invalid_initial_state',
message:
rule.message ||
`Invalid initial state for ${rule.field}: ${String(value)} (allowed: ${initial.join(', ')})`,
};
}
return null;
}
if (!previous) return null;
// The PATCH didn't touch the state field → no transition to validate.
if (!(rule.field in data)) return null;
const from = previous[rule.field];
const to = data[rule.field];
// No change, or clearing the value → nothing to enforce.
if (from === to || to === undefined || to === null) return null;
const fromKey = String(from);
const allowed = rule.transitions[fromKey];
// Prior state not described by the FSM (legacy / external write) — cannot
// reason about its legal targets, so don't block.
if (!Array.isArray(allowed)) return null;
if (!allowed.includes(String(to))) {
return {
field: rule.field,
code: 'invalid_transition',
message:
rule.message ||
`Invalid transition for ${rule.field}: ${fromKey} → ${String(to)}`,
};
}
return null;
}
/**
* CEL predicate check (`script` / `cross_field`). The predicate expresses the
* *failure* condition: if it evaluates TRUE the rule is violated. An
* un-evaluable predicate is treated as a broken rule (logged, skipped).
*/
function checkPredicate(
rule: PredicateRule,
record: Record<string, unknown>,
previous: Record<string, unknown> | undefined,
logger: EvaluateRulesOptions['logger'],
): FieldValidationError | null {
const expr = toExpression(rule.condition);
const result = ExpressionEngine.evaluate<boolean>(expr, {
record,
previous: previous ?? undefined,
});
if (!result.ok) {
logger?.warn?.(
`Validation rule '${rule.name}' predicate failed to evaluate (${result.error.kind}: ${result.error.message}) — skipped`,
);
return null;
}
if (result.value === true) {
return {
field: rule.fields?.[0] ?? '_record',
code: 'rule_violation',
message: rule.message,
};
}
return null;
}
// Linear-time email check. Domain labels exclude '.', so the quantifiers on
// either side of each '.' can't overlap — this avoids the polynomial
// backtracking (ReDoS) of the naive `[^\s@]+\.[^\s@]+` shape while still
// requiring a local part, an '@', and a dotted domain.
const EMAIL_RE = /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/;
// Lenient phone matcher: optional leading +, then 7–20 digits with spaces,
// dashes, dots and parens allowed as separators. Intentionally permissive —
// strict national formats belong in a `regex`.
const PHONE_RE = /^\+?[\d\s().-]{7,20}$/;
/**
* Format check (`format`). Validates a single field's value against an optional
* `regex` and/or a named `format`. Only runs when the write touches the field
* (mirrors `state_machine`) and the value is non-empty — requiredness and
* type-shape are the field-level validator's job, so an absent/blank value is
* not a *format* violation. A malformed `regex` is a broken rule (logged,
* fail-open), not a violation.
*/
function checkFormat(
rule: FormatRule,
data: Record<string, unknown>,
logger: EvaluateRulesOptions['logger'],
): FieldValidationError | null {
if (!(rule.field in data)) return null;
const value = data[rule.field];
if (value === null || value === undefined || value === '') return null;
const str = String(value);
if (rule.regex) {
let re: RegExp;
try {
re = new RegExp(rule.regex);
} catch {
logger?.warn?.(`Validation rule '${rule.name}' has an invalid regex — skipped`);
return null;
}
if (!re.test(str)) return formatViolation(rule);
}
if (rule.format && !matchesNamedFormat(rule.format, str)) {
return formatViolation(rule);
}
return null;
}
function matchesNamedFormat(format: FormatRule['format'], str: string): boolean {
switch (format) {
case 'email':
return EMAIL_RE.test(str);
case 'phone':
return PHONE_RE.test(str);
case 'url':
try {
// eslint-disable-next-line no-new
new URL(str);
return true;
} catch {
return false;
}
case 'json':
try {
JSON.parse(str);
return true;
} catch {
return false;
}
default:
return true;
}
}
function formatViolation(rule: FormatRule): FieldValidationError {
return { field: rule.field, code: 'invalid_format', message: rule.message };
}
/**
* JSON Schema check (`json_schema`). Validates a JSON field against the rule's
* schema via ajv. The field value may be a parsed object or a JSON string (a
* string that fails to parse is itself a violation). Only runs when the write
* touches the field and the value is non-null. A schema ajv cannot compile is a
* broken rule (logged, fail-open).
*/
function checkJsonSchema(
rule: JsonSchemaRule,
data: Record<string, unknown>,
logger: EvaluateRulesOptions['logger'],
): FieldValidationError | null {
if (!(rule.field in data)) return null;
let value = data[rule.field];
if (value === null || value === undefined) return null;
if (typeof value === 'string') {
try {
value = JSON.parse(value);
} catch {
return { field: rule.field, code: 'invalid_json', message: rule.message };
}
}
let validate = jsonSchemaCache.get(rule.schema);
if (!validate) {
try {
validate = ajv.compile(rule.schema);
} catch (err) {
logger?.warn?.(
`Validation rule '${rule.name}' has an uncompilable JSON Schema — skipped`,
err,
);
return null;
}
jsonSchemaCache.set(rule.schema, validate);
}
if (!validate(value)) {
return { field: rule.field, code: 'json_schema_violation', message: rule.message };
}
return null;
}
/**
* Conditional check (`conditional`). Evaluates the `when` predicate against the
* merged record, then recurses into `then` (true) or `otherwise` (false) via
* `evaluateRule`. An un-evaluable `when` is a broken rule (logged, fail-open).
* The nested rule supplies the violation (field/code/message); the *outer*
* conditional's `severity` governs whether it blocks (handled by the caller).
*/
function checkConditional(
rule: ConditionalRule,
ctx: RuleContext,
): FieldValidationError | null {
const result = ExpressionEngine.evaluate<boolean>(toExpression(rule.when), {
record: ctx.merged,
previous: ctx.previous ?? undefined,
});
if (!result.ok) {
ctx.logger?.warn?.(
`Validation rule '${rule.name}' when-predicate failed to evaluate (${result.error.kind}: ${result.error.message}) — skipped`,
);
return null;
}
const branch = result.value === true ? rule.then : rule.otherwise;
if (!branch || branch.active === false) return null;
return evaluateRule(branch, ctx);
}
/**
* Introspection helper (ADR-0020 D3.3): given an object's schema, a state
* field, and a current state, return the legal next states declared by the
* matching `state_machine` rule. Returns `null` when no such rule exists (so
* callers can distinguish "no FSM governs this field" from "a dead-end state
* with zero outgoing transitions", which returns `[]`).
*/
export function legalNextStates(
objectSchema: { validations?: unknown[] } | undefined | null,
field: string,
currentState: string,
): string[] | null {
const rules = objectSchema?.validations;
if (!Array.isArray(rules)) return null;
const rule = rules.find(
(r): r is StateMachineRule =>
r != null &&
typeof r === 'object' &&
(r as BaseRule).type === 'state_machine' &&
(r as StateMachineRule).field === field,
);
if (!rule) return null;
return rule.transitions[currentState] ?? [];
}