Repository navigation
Expand file tree
/
Copy patheffective-object-permissions.ts
More file actions
964 lines (931 loc) · 50 KB
/
Copy patheffective-object-permissions.ts
File metadata and controls
964 lines (931 loc) · 50 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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* The EFFECTIVE object-permission map — object name -> `EffectiveObjectPermission`
* — computed from a subject's resolved permission sets. ONE function, two
* consumers:
*
* - `/auth/me/permissions` (`@objectstack/plugin-hono-server`) serves it as the
* `objects` slot of its response;
* - `ISecurityService.getEffectiveObjectPermissions` (`@objectstack/plugin-security`)
* returns it, and the engine hands it to `current_user.can(object, verb)` as
* `EvalContext.permissions` (#18783).
*
* ## Why here, and why ONE function
*
* The contract member's docblock requires the two to be byte-for-byte the same
* answer, "computed once rather than twice": the second consumer (`can()`)
* cannot tell a wrong map from a right one — an entry the map omits reads as
* "no grant", indistinguishable from a measured denial. A second copy of this
* merge would be exactly the hand-built map `@objectstack/formula`'s
* `toEvalPermissions` names as a confident silent denial waiting to happen.
*
* It lives in `@objectstack/core` because both consumers already depend on this
* package and on nothing else they share: `plugin-hono-server` must never take a
* runtime dependency on `plugin-security` (it is optional in the stacks those
* endpoints serve), and `plugin-security` has no business importing a transport.
* The folds below used to live in `plugin-hono-server`'s
* `current-user-endpoints.ts`, which still re-exports them under the same names.
*
* Every function here is PURE over its inputs (the map is mutated in place and
* returned; nothing else is read or written) — the set RESOLUTION is the
* caller's, from the one resolver `ISecurityService.resolvePermissionSetsForContext`.
*/
import {
resolveEffectiveApiMethods,
effectiveOperationsArray,
canServeApiOperation,
type ApiOperation,
type EnableLike,
} from '@objectstack/spec/data';
import { objectPermissionGrants, type EffectiveObjectPermission } from '@objectstack/spec/security';
/**
* Does the `'*'` entry carry the super-user READ bypass?
*
* ONE reading of that question for this whole file — {@link foldSuperUserWildcardGrants}
* asks it of each set to decide which wildcards it folds (and the standalone
* {@link foldWildcardSuperUser} of the merged map), and
* {@link seedSuperUserRestrictedObjects} asks it to decide whom it seeds for, so
* the seed can never materialise an entry for a principal the fold leaves false.
* It is the same bypass the server itself applies: `PermissionEvaluator`'s
* `wildcardSuperUser()` treats `viewAllRecords` and `modifyAllRecords` alike for
* read (`allowRead` short-circuits on either), and only the modify bit reaches
* the write axis.
*/
function wildcardGrantsSuperRead(objects: Record<string, any>): boolean {
const wild = objects?.['*'];
return wild?.viewAllRecords === true || wild?.modifyAllRecords === true;
}
/**
* Fold the `'*'` wildcard super-user grant into every per-object entry of a
* `/me/permissions` `objects` map, mutating it in place.
*
* The endpoint merges each resolved permission set's explicit `objects` entries
* most-permissively per key, but treats `'*'` and named objects as independent
* keys — so a wildcard "Modify/View All Data" grant is never propagated into a
* per-object entry another set explicitly denied. That makes the client's
* per-object FLS STRICTER than the server's actual enforcement
* (`PermissionEvaluator.checkObjectPermission`, which returns allow as soon as
* ANY set grants — including via the `'*'` modifyAll/viewAll super-user bypass,
* with no deny-wins). The mismatch surfaces for a platform admin
* (`admin_full_access` `'*': {modifyAllRecords}`) who ALSO holds
* `organization_admin` (which denies writes on identity tables): the client
* would see `sys_user.allowEdit:false` and disable a form the server accepts
* (verified: `PATCH /data/sys_user {name}` → 200). ADR-0124 D1 makes the
* server the authoritative gate, and D4 makes this direction explicit: what
* the client is told must be derived from the server's actual effective
* enforcement, never from an independent reading of the declarations.
*
* The super-user grant covers private/managed objects on the server, so the
* read and write bypass reach every entry here.
*
* [#20136] ⛔ NOT a step of {@link buildEffectiveObjectPermissions}, and not
* what the effective map is built from. It reads the MERGED wildcard, and a
* merged map no longer says which set names which object, so no fold over it
* alone can match the server. The map's super-user fold is
* {@link foldSuperUserWildcardGrants}, which reads each set on its own. This
* helper stays exported, body unchanged, for the callers of the released
* `@objectstack/plugin-hono-server` export of the same name. Against
* `PermissionEvaluator.checkObjectPermission` its answer is:
* - BROADER where the super-user set itself names the object narrower:
* `resolveObjectPermission` answers that set with its explicit entry, so
* the walled `organization_admin` would be granted edit on `sys_position`
* here and is refused it by the server;
* - BROADER on create: `allowCreate` is pulled on the write bypass, which the
* spec's `objectPermissionGrants` gives no create cell;
* - NARROWER on `transfer` and on a super-user wildcard's own plain bits,
* which it never sets.
* Build a map with {@link buildEffectiveObjectPermissions}, never with this.
*/
export function foldWildcardSuperUser(objects: Record<string, any>): void {
const wild = objects?.['*'];
if (!wild) return;
const superRead = wildcardGrantsSuperRead(objects);
const superWrite = wild.modifyAllRecords === true;
if (!superRead && !superWrite) return;
for (const [obj, acc] of Object.entries(objects) as Array<[string, any]>) {
if (obj === '*' || !acc) continue;
if (superRead) acc.allowRead = true;
if (superWrite) {
acc.allowEdit = true;
acc.allowCreate = true;
acc.allowDelete = true;
}
}
}
/**
* [#20134] The super-user fold: each set's SUPER-USER `'*'` puts every bit it
* grants on each entry that set does not name, mutating the map in place.
* Runs after the seed (so every registered object has an entry) and BEFORE the
* managed-write clamp.
*
* Without it the map held only the four bits {@link foldWildcardSuperUser}
* pulls, so `current_user.can(object, 'transfer')` answered `false` for
* `admin_full_access` and the walled `organization_admin` on every object
* where `PermissionEvaluator.checkObjectPermission('transfer', …)` answers
* `true` through `modifyAllRecords`, and a super-read wildcard lost its own
* plain bits (`'*': { viewAllRecords, allowEdit }` read only).
*
* [#20136] And it is the WHOLE super-user fold: the merged
* {@link foldWildcardSuperUser} no longer runs before it. That pass put the
* merged bypass on every entry, the ones a super-user set names itself
* included, and pulled `allowCreate` on `modifyAllRecords` alone, so the map
* granted cells the server refuses — edit on `sys_position` for the walled
* `organization_admin`, create for a `'*': { modifyAllRecords: true }`, read on
* an entry a super-user set names as `{}`. Every bit that pass set that the
* server grants, this one sets too, per set.
*
* The bits are DERIVED, not listed: for each grant bit, the spec's
* `objectPermissionGrants` — the one fold `checkObjectPermission` itself asks
* — is read on the set's wildcard. For a super-user wildcard its read cell is
* always `true`, so its export cell is exactly the wildcard's own
* `allowExport`, the grant half the evaluator's export conjunction reads.
*
* Exactly as broad as `resolveObjectPermission`, never broader:
* - a set that names the object contributes nothing here: for that set the
* explicit entry is the whole answer, and the merge already carries it;
* - a super-user wildcard covers a private object as much as a public one,
* so no posture is read;
* - only `true` bits are set — a bit the wildcard does not grant is left
* as the other passes left it.
*
* A plain wildcard is {@link materializePlainWildcardCoverage}'s, and a map
* holding no super-user wildcard leaves this pass without a single write.
*/
function foldSuperUserWildcardGrants(
objects: Record<string, any>,
sets: ReadonlyArray<EffectiveObjectPermissionsInputSet | null | undefined>,
): void {
const superWildcards: Array<{ named: Record<string, unknown>; bits: readonly GrantBit[] }> = [];
for (const ps of sets) {
const named = ps?.objects as Record<string, unknown> | null | undefined;
const wild = named?.['*'] as Record<string, unknown> | null | undefined;
if (!named || !wild || typeof wild !== 'object') continue;
// The file's one reading of "is this a super-user wildcard?", asked of the set.
if (!wildcardGrantsSuperRead(named)) continue;
const bits = GRANT_BITS.filter((bit) => objectPermissionGrants(wild as EffectiveObjectPermission, bit));
superWildcards.push({ named, bits });
}
if (superWildcards.length === 0) return;
for (const [obj, acc] of Object.entries(objects) as Array<[string, any]>) {
if (obj === '*' || !acc) continue;
for (const { named, bits } of superWildcards) {
// `resolveObjectPermission`'s own test: a set's explicit entry, when it
// has one, is that set's whole answer for the object.
if (named[obj]) continue;
for (const bit of bits) {
if (acc[bit] !== true) acc[bit] = true;
}
}
}
}
/** Minimal schema shape the managed-write clamp needs. */
export interface ManagedSchemaLike {
managedBy?: string;
userActions?: {
// create/edit/delete all accept the object form
// ({ enabled, visibleWhen, disabledWhen }) — #2614 gave it to the row
// pair, #7692 to `create`. Only the object-level `enabled` matters
// here: the predicates are UI gating, not a permission grant.
create?: boolean | { enabled?: boolean };
edit?: boolean | { enabled?: boolean };
delete?: boolean | { enabled?: boolean };
} | null;
}
/** True only when a userActions flag (bare boolean or object form) explicitly opts the write in. */
function isWriteOptedIn(v: boolean | { enabled?: boolean } | undefined | null): boolean {
return v === true || (typeof v === 'object' && v !== null && v.enabled === true);
}
/**
* Buckets whose user-context generic writes are guarded fail-closed at the
* engine: `better-auth` by plugin-auth's identity write guard (ADR-0092 D2),
* `engine-owned` / `append-only` by plugin-security's engine-owned write guard
* (ADR-0103). `config` / `platform` / `system-data` have no such guard — their
* permission-set result stands.
*
* `system` was listed here until #3355 renamed it to the writable-default
* `system-data`, which joins `config` / `platform` on the unclamped side. That
* matters more here than it looks: this clamp reads `userActions` DIRECTLY rather
* than the resolved affordances, so clamping a bucket whose members legitimately
* dropped their now-redundant `userActions` block would report `allowEdit: false`
* for tables the engine happily writes — the exact false-NEGATIVE this function
* exists to avoid, merely inverted.
*/
const GUARDED_WRITE_BUCKETS: ReadonlySet<string> = new Set(['better-auth', 'engine-owned', 'append-only']);
/**
* Re-clamp a `/me/permissions` `objects` map by the SECOND server-side
* enforcement layer that permission sets don't model: the engine write guards.
* They fail-closed reject USER-CONTEXT insert/update/delete on every managed
* object whose resolved affordances forbid the verb — `better-auth`
* (ADR-0092 D2) and `engine-owned`/`append-only` (ADR-0103) — except where the
* object opted the write affordance in via `userActions.{create,edit,delete}`
* (e.g. sys_user opens `edit` for its profile fields).
*
* Without this clamp, the super-user fold ({@link foldSuperUserWildcardGrants})
* would report `allowEdit:true`
* for a platform admin on tables the guard actually blocks (sys_member,
* sys_automation_run, …) — a false-POSITIVE that mirrors, inverted, the
* false-negative the fold fixes. The real effective answer for a user-context
* caller is `permission-set grant ∩ guard policy`, and the guard policy for a
* guarded object is exactly its resolved CRUD affordance. `config`/`platform`/`system-data`
* objects are NOT clamped — no guard covers them, so their permission-set result
* stands (an admin CAN write them via the data API, and the hint must not
* under-report that).
*/
export function clampManagedObjectWrites(
objects: Record<string, any>,
schemaOf: (objectName: string) => ManagedSchemaLike | undefined,
): void {
for (const [obj, acc] of Object.entries(objects) as Array<[string, any]>) {
if (obj === '*' || !acc) continue;
const schema = schemaOf(obj);
if (!schema?.managedBy || !GUARDED_WRITE_BUCKETS.has(schema.managedBy)) continue;
const ua = schema.userActions ?? {};
if (!isWriteOptedIn(ua.edit)) acc.allowEdit = false;
// `create` reads through the same opt-in helper as edit/delete since
// #7692 widened it to the object form — a bare `ua.create !== true`
// would clamp away a legitimate `{ enabled: true, visibleWhen: … }`.
if (!isWriteOptedIn(ua.create)) acc.allowCreate = false;
if (!isWriteOptedIn(ua.delete)) acc.allowDelete = false;
}
}
/** The API-exposure-relevant slice of a registered object schema. */
export interface ApiExposureSchemaLike {
name?: string;
enable?: EnableLike | null;
}
/**
* The posture slice of a registered object schema: whether a plain `'*'` grant
* covers it at all. `access.default === 'private'` keeps a wildcard carrying no
* super-user bypass bit off the object — ADR-0066 D2, read exactly as
* `PermissionEvaluator` reads it (`access?.default === 'private'`; anything else
* is public).
*/
export interface ObjectAccessPostureLike {
name?: string;
/**
* The registered schema's own `access` block, passed through as it is. Typed
* `unknown` so that any schema a caller already hands over still type-checks;
* the one read is `access.default === 'private'`.
*/
access?: unknown;
}
/** `access.default === 'private'` off a registered schema — the evaluator's own test. */
function isPrivatePosture(schema: ObjectAccessPostureLike | null | undefined): boolean {
const access = schema?.access;
return typeof access === 'object' && access !== null && (access as { default?: unknown }).default === 'private';
}
/** The `allow*` bits {@link objectPermissionGrants} reads, i.e. every bit a `can()` verb resolves to. */
const GRANT_BITS = ['allowRead', 'allowCreate', 'allowEdit', 'allowDelete', 'allowTransfer', 'allowExport'] as const;
type GrantBit = (typeof GRANT_BITS)[number];
const GRANT_BIT_SET: ReadonlySet<string> = new Set(GRANT_BITS);
/** Does the entry grant any verb on its own? (`objectPermissionGrants` over every verb target.) */
function grantsAnyVerb(entry: Record<string, unknown>): boolean {
return GRANT_BITS.some((bit) => objectPermissionGrants(entry as EffectiveObjectPermission, bit));
}
/**
* [#20083] Materialise every PLAIN `'*'` grant — a wildcard carrying neither
* super-user bypass bit — onto the registered objects it covers, mutating the
* map in place. Runs after the merge and the super-user seed (an entry the
* seed placed only gains grants here, and keeps its place), BEFORE the fold.
*
* The merge above folds each set's EXPLICIT entries and keeps `'*'` as a key of
* its own, but the server does not stop there: `PermissionEvaluator`'s
* `resolveObjectPermission` answers, PER SET, with that set's explicit entry
* for the object when it has one, and otherwise with its `'*'` — for a public
* object always, for a private one only when the wildcard is a super-user
* grant. So a set whose plain wildcard covers an object contributes that
* wildcard to the object, and `checkObjectPermission` allows as soon as ANY
* set's contribution grants. Without this pass the map held no entry for an
* object reached only that way, and `current_user.can()` — which reads an absent
* entry as "no grant" — answered `false` for a wall-less org admin
* (`organization_admin_no_bypass`) on every app object the server lets them
* write; and it held a narrower entry wherever one set named the object and
* another covered it by its wildcard.
*
* Exactly as broad as that resolution, never broader:
* - only REGISTERED objects are covered — the server refuses an object whose
* posture it cannot resolve, whatever the wildcard says;
* - a set that names the object explicitly contributes nothing here: for
* that set the explicit entry is the whole answer, and the merge already
* carries it;
* - a `private` object takes nothing from a plain wildcard;
* - only `true` bits are merged — the grants every `can()` verb reads. A
* wildcard's `false` or unset bit grants nothing, and depth keys
* (`readScope`/`writeScope`) are not grants;
* - an object the pass would ADD but whose entry grants no verb on its own is
* left out: an absent entry and an all-`false` one read the same.
*
* A super-user wildcard is NOT materialised here: {@link seedSuperUserRestrictedObjects}
* and {@link foldSuperUserWildcardGrants} carry it, and this pass leaves their answer
* byte-for-byte as it was for every subject holding no plain wildcard.
*/
function materializePlainWildcardCoverage(
objects: Record<string, any>,
sets: ReadonlyArray<EffectiveObjectPermissionsInputSet | null | undefined>,
allSchemas: readonly (ApiExposureSchemaLike & ObjectAccessPostureLike)[],
): void {
const plainWildcards: Array<{ named: Record<string, unknown>; wild: Record<string, unknown> }> = [];
for (const ps of sets) {
const named = ps?.objects as Record<string, unknown> | null | undefined;
const wild = named?.['*'] as Record<string, unknown> | null | undefined;
if (!named || !wild || typeof wild !== 'object') continue;
if (wild.viewAllRecords === true || wild.modifyAllRecords === true) continue;
if (!GRANT_BITS.some((bit) => wild[bit] === true)) continue;
plainWildcards.push({ named, wild });
}
if (plainWildcards.length === 0) return;
for (const schema of allSchemas) {
const name = schema?.name;
if (!name || name === '*') continue;
if (isPrivatePosture(schema)) continue;
const had = Object.prototype.hasOwnProperty.call(objects, name);
const acc: Record<string, unknown> = had ? objects[name] : {};
let touched = false;
for (const { named, wild } of plainWildcards) {
// `resolveObjectPermission`'s own test: a set's explicit entry, when it
// has one, is that set's whole answer for the object.
if (named[name]) continue;
// The wildcard's own key order, so an entry this pass adds reads like
// every other entry the map carries.
for (const [bit, value] of Object.entries(wild)) {
if (value === true && GRANT_BIT_SET.has(bit) && acc[bit] !== true) {
acc[bit] = true;
touched = true;
}
}
}
if (!had && touched && grantsAnyVerb(acc)) objects[name] = acc;
}
}
/**
* [#3391] Seed false-initialized per-object entries for a wildcard SUPER-USER,
* for every registered object the merged map does not already carry.
*
* A super-user's grant is usually the `'*'` wildcard, not explicit per-object
* entries — so the objects it reaches never appear in the merged `objects` map.
* Seeding a `{allow*: false}` entry lets {@link foldSuperUserWildcardGrants}
* pull its grants true and lets
* {@link annotateEffectiveApiOperations} attach the effective operation set
* where the object narrows it. Runs BEFORE the fold.
*
* [#18990] Admitted by {@link wildcardGrantsSuperRead} — the READ bypass, so
* BOTH super-user classes are seeded, and a plain wildcard grant carrying
* neither bypass bit still is not — [#20083] its coverage is
* {@link materializePlainWildcardCoverage}'s, which puts the wildcard's own
* grants on the objects it covers. This pass used to be guarded to
* `modifyAllRecords` alone, on the reading that materializing a `false` entry
* for a viewAll-only caller would flip the client's `check('edit')` from
* "undefined → default-allow" to "explicit false → deny". It does flip it, and
* that flip is the POINT: the seed only ever touches objects with no explicit
* entry (`objects[name]` below), and on those a viewAll-only principal really
* can only read — so "explicit false" for edit is what is TRUE about it, while
* the silence it replaces left the client rendering write and Export
* affordances the server answers `403`. `allowRead` is pulled true by the same
* fold for the same reason: `viewAllRecords` is a read bypass server-side too
* (`PermissionEvaluator.checkObjectPermission`), so the entry is exactly as
* broad as real enforcement, never broader.
*
* [#18931] An unrestricted object whose `export` the export axis withholds is
* seeded too: annotate iterates existing entries only, so without an entry
* `/me/permissions` stayed silent for exactly the population #8681 created — a
* wildcard-only admin holding no `allowExport` — the client's `apiOperations`
* was `undefined`, its default-allow path rendered an Export button, and the
* click was refused `403 EXPORT_NOT_PERMITTED`.
*
* [#20134] And so is EVERY other registered object absent from the map — the
* name keeps its #3391 origin, the scope does not. The pass used to skip an
* unrestricted object whose `export` stays allowed, the one object that needs
* no `apiOperations` annotation. But the entry is not only the annotation's
* carrier: `current_user.can()` reads the map entry by entry and an absent one
* as "no grant", so a super-user wildcard that also carries `allowExport` left
* every such object reading `false` for every verb the server lets that
* principal perform. The entry is the truth the #18990 ruling asks for — every
* object a principal can reach gets one — and annotate keeps its own skip:
* an entry seeded for an unrestricted, export-allowed object carries no
* `apiOperations`, so the client's default-allow path for the operation set is
* exactly as it was.
*/
export function seedSuperUserRestrictedObjects(
objects: Record<string, any>,
allSchemas: readonly ApiExposureSchemaLike[],
): void {
if (!wildcardGrantsSuperRead(objects)) return;
// A super-user wildcard covers every registered object, private ones
// included (`PermissionEvaluator`'s `resolveObjectPermission`), so every
// registered object the merge left absent gets an entry.
for (const schema of allSchemas) {
const name = schema?.name;
if (!name || name === '*' || objects[name]) continue;
objects[name] = { allowCreate: false, allowRead: false, allowEdit: false, allowDelete: false };
}
}
/**
* [#3391] Annotate each per-object `/me/permissions` entry with the SERVER's
* effective API operation set (`apiOperations`), mutating the map in place.
*
* This is the single "effective" channel the frontend consumes — it renders the
* operations the server hands down here, never the raw `apiMethods` whitelist.
* An object is annotated whenever its effective set is narrower than the
* client's default-allow assumption (a `deny-all` object gets an empty array;
* [#3544] an unrestricted object gets one too whenever the export axis withholds
* `export`). Only an unrestricted object that keeps its full closure gets
* nothing, because for it default-allow is already the right answer. Runs AFTER
* fold + clamp so the annotation sits alongside the final CRUD affordances, and
* {@link seedSuperUserRestrictedObjects} applies the same predicate so a
* wildcard-only principal has an entry here to annotate ([#18931]).
*
* [#20135] The set is what the REST door SERVES this subject, read through the
* door's own two questions rather than a second spelling of either:
*
* - the OBJECT half is `canServeApiOperation` — the boolean face of the
* spec's `apiExposureDenialReason`, the one function
* `@objectstack/rest`'s `enforceApiAccess` turns into its 404 / 405. It
* judges `enable.apiEnabled === false` FIRST and for every operation, so an
* API-disabled object is annotated `[]`: the door answers
* `404 OBJECT_API_DISABLED` for every verb, whatever `apiMethods` says, and
* an entry left without an annotation would send the client down its
* default-allow path — every operation offered, every one refused. The
* entry itself stays: `apiEnabled` closes the API, not data access, and the
* map's CRUD bits are what `current_user.can()` reads on the server;
* - the USER half is the export door's own conjunction on this entry,
* `objectPermissionGrants(entry, 'allowExport')` — read ∧ an opt-in export
* grant. By the time this pass runs every set's `'*'` has been put on the
* entries it covers for THAT set and posture (plain coverage, then the
* per-set super-user fold), so the entry already is
* `PermissionEvaluator.checkObjectPermission('export', …, { isPrivate })`'s
* answer. It used to fall back to the MERGED `'*'` export bit, which covers
* what no single set covers: a private object reached only through a plain
* `'*': { allowExport: true }` (a plain wildcard never covers a private
* object), and an object the exporting set itself names without the grant.
* Both were annotated `export` and answered `403 EXPORT_NOT_PERMITTED`.
*
* Which entries carry the annotation is unchanged in rule: only an
* unrestricted object that keeps its whole closure — every operation served,
* `export` included — gets none.
*
* [#30370] With `isExternalWriteForbidden`, an object whose external write
* gate is closed (ADR-0015 §5.3 Gate 3) is served without every write
* operation ({@link EXTERNAL_WRITE_GATED_OPERATIONS}): the data plane refuses
* each one `403 EXTERNAL_WRITE_FORBIDDEN` whatever the permission sets say,
* and such an object is always annotated, since the client's default-allow
* path would offer every write. Without it, the answer is what it was.
*/
export function annotateEffectiveApiOperations(
objects: Record<string, any>,
schemaOf: (objectName: string) => ApiExposureSchemaLike | undefined,
isExternalWriteForbidden?: (objectName: string) => boolean,
): void {
for (const [obj, acc] of Object.entries(objects) as Array<[string, any]>) {
if (obj === '*' || !acc) continue;
const schema = schemaOf(obj);
if (!schema) continue; // schema missing → no annotation (client falls back)
const enable = schema.enable ?? undefined;
// [#3544] User-level export axis: `export` derives from `list ∧ this
// grant`. OPT-IN — only an explicit `true` allows export; unset and
// `false` both withhold it, and the super-user bits do NOT imply it.
// [#20135] Read off THIS entry, as the export door reads it (see above).
const userExportAllowed = objectPermissionGrants(acc as EffectiveObjectPermission, 'allowExport');
const eff = resolveEffectiveApiMethods(enable, { userExportAllowed });
const closure = effectiveOperationsArray(eff);
// [#20135] Only what the door itself admits: `apiEnabled: false` empties
// the set; any other `enable` leaves the closure as it is.
// [#30370] And only what the external write gate admits: a closed gate
// refuses every write operation on the data plane.
const writeForbidden = isExternalWriteForbidden?.(obj) === true;
const served = closure.filter((operation) =>
canServeApiOperation(enable, operation)
&& !(writeForbidden && EXTERNAL_WRITE_GATED_OPERATIONS.has(operation)));
// Annotate when the object tightens via `apiMethods`, when the export
// axis removes `export` from an otherwise-open object (so the client
// hides the Export button), OR when the door serves less than the closure
// (an API-disabled object, or [#30370] a closed external write gate). An
// unrestricted object with every operation still served needs no
// annotation — the client keeps its default-allow path.
if (eff.mode === 'unrestricted' && userExportAllowed && served.length === closure.length) continue;
acc.apiOperations = served;
}
}
/**
* [#30370] The effective API operations that WRITE a row — every one the
* external write gate (ADR-0015 §5.3 Gate 3, objectql `assertWriteAllowed`)
* refuses on an object whose gate is closed: the three primitives it judges
* (`insert` is `create`), and every derived operation built on them —
* `upsert` (create ∧ update), `bulk` (batched create / update / delete),
* `import` (create ∨ update), and `restore` / `purge`, which never derive
* today but write when they do. The read operations (`get`, `list`,
* `aggregate`, `history`, `search`, `export`) are untouched: the gate judges
* writes only.
*/
const EXTERNAL_WRITE_GATED_OPERATIONS: ReadonlySet<ApiOperation> = new Set<ApiOperation>([
'create', 'update', 'delete', 'upsert', 'bulk', 'import', 'restore', 'purge',
]);
/**
* [#30370] Re-clamp the map by the THIRD server-side enforcement layer
* permission sets do not model: the external write gate (ADR-0015 §5.3
* Gate 3). On an object whose gate is closed, objectql refuses every insert,
* update and delete `403 EXTERNAL_WRITE_FORBIDDEN` for every caller — no
* permission set, super-user bypass included, opens it — so the entry grants
* no write: `allowCreate`, `allowEdit`, `allowDelete` and `allowTransfer`
* (an owner change is an update) are `false`.
*
* `modifyAllRecords` is a write grant too: the spec's `objectPermissionGrants`
* answers edit, delete and transfer `true` on it alone, so an entry keeping it
* would still answer `current_user.can(object, 'edit')` `true`. It is lowered
* to `viewAllRecords`, the read half it implies, so the entry keeps exactly
* the read it had.
*
* An object the map does not mention already grants nothing, and is left out.
*/
function clampExternalReadOnlyWrites(objects: Record<string, any>, forbidden: ReadonlySet<string>): void {
if (forbidden.size === 0) return;
for (const [obj, acc] of Object.entries(objects) as Array<[string, any]>) {
if (obj === '*' || !acc || !forbidden.has(obj)) continue;
acc.allowCreate = false;
acc.allowEdit = false;
acc.allowDelete = false;
acc.allowTransfer = false;
if (acc.modifyAllRecords === true) {
acc.modifyAllRecords = false;
acc.viewAllRecords = true;
}
}
}
/**
* [#30370] The {@link EffectiveObjectPermissionsSchemaSource.isExternalWriteForbidden}
* accessor over an engine: its `isExternalWriteForbidden`, the verdict objectql's
* own write gate (`assertWriteAllowed`) reads before it refuses a write
* `403 EXTERNAL_WRITE_FORBIDDEN`. That member is not on the contract's engine
* view, so it is asked when present; an engine without it forbids nothing.
* Both builders of the map (`/auth/me/permissions` and
* `ISecurityService.getEffectiveObjectPermissions`) hand over this one reading.
*/
export function engineExternalWriteForbidden(engine: unknown): (objectName: string) => boolean {
return (objectName) => {
const predicate = (engine as { isExternalWriteForbidden?: unknown } | null | undefined)?.isExternalWriteForbidden;
return typeof predicate === 'function' && predicate.call(engine, objectName) === true;
};
}
/**
* The schema reads {@link buildEffectiveObjectPermissions} needs, as accessors
* over whatever engine the caller holds. Every accessor is optional and every
* read is GUARDED: a registry that throws, or an engine that is not wired at
* all, degrades the annotations exactly as `/auth/me/permissions` always has
* (no seed, no clamp, no `apiOperations`) — it never drops the map.
*/
export interface EffectiveObjectPermissionsSchemaSource {
/**
* Every registered object schema — read by the plain-wildcard coverage
* (`name` and `access.default`, [#20083]) and by the super-user seed (`name`
* and `enable`). Hand over the registered schemas themselves: an entry whose
* `access` is missing reads as public, exactly as it does to the server.
*/
allSchemas?: () => readonly (ApiExposureSchemaLike & ObjectAccessPostureLike)[] | null | undefined;
/** One object's schema — read by the managed-write clamp and the `apiOperations` annotation. */
schemaOf?: (objectName: string) => (ManagedSchemaLike & ApiExposureSchemaLike) | null | undefined;
/**
* [#28877] Whether `objectName` is an object whose OWNING package is
* disabled — the engine registry's `isObjectPackageDisabled`, the predicate
* the data plane asks before it answers `404 OBJECT_PACKAGE_DISABLED`. Hand
* over that predicate itself, never a second reading of the package state:
* the map must leave out exactly the objects the data plane refuses.
*/
isObjectPackageDisabled?: (objectName: string) => boolean;
/**
* [#30370] Whether the external write gate (ADR-0015 §5.3 Gate 3) is closed
* on `objectName` — the engine's `isExternalWriteForbidden`, the verdict its
* own `assertWriteAllowed` refuses a write on. Hand over that predicate
* itself ({@link engineExternalWriteForbidden}), never a second reading of
* the datasource definitions: the map must withhold exactly the writes the
* data plane refuses.
*/
isExternalWriteForbidden?: (objectName: string) => boolean;
/** Where a failed seed / annotation pass is reported. */
logger?: { warn?: (message: string, meta?: Record<string, unknown>) => void };
}
/**
* [#28877] The {@link EffectiveObjectPermissionsSchemaSource.isObjectPackageDisabled}
* accessor over an engine registry: its `isObjectPackageDisabled`, the predicate
* `SchemaRegistry` answers and the data plane asks before it refuses an object
* `404 OBJECT_PACKAGE_DISABLED`. That member is not on the contract's registry
* view, so it is asked when present; a registry without it disables nothing.
* Both builders of the map (`/auth/me/permissions` and
* `ISecurityService.getEffectiveObjectPermissions`) hand over this one reading.
*/
export function registryObjectPackageDisabled(registry: unknown): (objectName: string) => boolean {
return (objectName) => {
const predicate = (registry as { isObjectPackageDisabled?: unknown } | null | undefined)?.isObjectPackageDisabled;
return typeof predicate === 'function' && predicate.call(registry, objectName) === true;
};
}
/**
* [#28877] Leave out of the map every object whose owning package is disabled
* (#28117 ruling A: a disabled package is hidden, and refused on the data
* plane). The data plane answers such an object `404 OBJECT_PACKAGE_DISABLED`
* for every verb, so an entry granting it would tell the console, and
* `current_user.can(object, verb)`, a grant no request can use; an object the
* map does not mention answers `can()` false. Re-enabling the package brings
* the entries back on the next build: nothing is cached here.
*
* Runs LAST, over the entries every earlier step placed: an explicit grant, a
* super-user seed, a plain wildcard's coverage. The `'*'` entry itself is not
* an object and is kept.
*/
function omitDisabledPackageObjects(
objects: Record<string, any>,
isObjectPackageDisabled: ((objectName: string) => boolean) | undefined,
): void {
if (typeof isObjectPackageDisabled !== 'function') return;
// Judged in full before anything is removed, so a predicate that throws
// midway leaves the map whole rather than half-pruned.
const disabled = Object.keys(objects).filter((name) => name !== '*' && isObjectPackageDisabled(name) === true);
for (const name of disabled) delete objects[name];
}
/** One resolved permission set, as far as this merge reads it. */
export interface EffectiveObjectPermissionsInputSet {
objects?: Record<string, unknown> | null;
}
/**
* [#18783] The effective object-permission map for a subject whose permission
* sets are `sets` — the `objects` slot of `/auth/me/permissions` and the answer
* of `ISecurityService.getEffectiveObjectPermissions`, from this ONE function.
*
* In order:
*
* 1. the most-permissive merge of every set's explicit `objects` entries —
* same semantics as `PermissionEvaluator.getFieldPermissions`, for ALL
* objects in one pass (`'*'` is merged as an ordinary key);
* 2. {@link seedSuperUserRestrictedObjects} — guarded: a failure is reported
* and the map is kept;
* 3. {@link materializePlainWildcardCoverage} — [#20083] each set's plain
* `'*'` onto the registered objects it covers for that set, so the map is
* as broad as `checkObjectPermission` there; guarded like (2);
* 4. {@link foldSuperUserWildcardGrants} — [#20134] each set's super-user
* `'*'` onto the entries it covers for that set, every bit it grants;
* [#20136] and nothing more: the merged {@link foldWildcardSuperUser} is
* not a step, so an entry a super-user set names itself keeps that set's
* explicit answer, and `modifyAllRecords` alone grants no create;
* 5. {@link clampManagedObjectWrites};
* 6. {@link clampExternalReadOnlyWrites} — [#30370] an object whose external
* write gate is closed grants no write, as the data plane refuses every
* one; the verdict is judged for every entry before anything is clamped,
* and a predicate that throws is reported and clamps nothing (guarded
* like (2));
* 7. {@link annotateEffectiveApiOperations} — guarded like (2); [#30370] it
* reads the same verdicts, so a closed gate's object is served no write
* operation;
* 8. {@link omitDisabledPackageObjects} — [#28877] an object whose owning
* package is disabled is left out, as the data plane refuses it; guarded
* like (2).
*
* Every entry is a FRESH object: nothing in the returned map aliases a
* permission set, so a caller may freeze or serialise it freely.
*
* It throws only where the merge itself cannot read a set (an `objects` value
* that is not an object) — the set RESOLUTION, and its failure stance, stay
* with the caller.
*/
export function buildEffectiveObjectPermissions(
sets: ReadonlyArray<EffectiveObjectPermissionsInputSet | null | undefined>,
source: EffectiveObjectPermissionsSchemaSource = {},
): Record<string, EffectiveObjectPermission> {
const objects: Record<string, any> = {};
for (const ps of sets) {
if (!ps?.objects) continue;
for (const [obj, perm] of Object.entries(ps.objects)) {
const acc = objects[obj] ?? {};
for (const [k, v] of Object.entries(perm as any)) {
if (v === true) acc[k] = true;
else if (acc[k] === undefined) acc[k] = v;
}
objects[obj] = acc;
}
}
const schemaOf = (name: string): (ManagedSchemaLike & ApiExposureSchemaLike) | undefined => {
try { return source.schemaOf?.(name) ?? undefined; } catch { return undefined; }
};
const allSchemas = (() => {
try { return source.allSchemas?.() ?? []; } catch { return [] as ApiExposureSchemaLike[]; }
})();
// [#3391] For a wildcard super-user — [#18990] either bypass bit, not
// modify-all alone — seed [#20134] every registered object absent from the
// merged map, so the folds pull what they pull and annotate can attach the
// effective apiOperations where the object narrows them. Guarded — a failure
// here must never drop the whole map.
try {
seedSuperUserRestrictedObjects(objects, allSchemas);
} catch (e: any) {
source.logger?.warn?.('[effective-permissions] apiOperations seed failed', { err: e?.message });
}
// [#20083] A plain `'*'` covers every registered public object its set does
// not name — per set, as the server resolves it. After the seed, so an entry
// the seed already placed keeps its place in the map and only gains grants.
// Guarded like the seed.
try {
materializePlainWildcardCoverage(objects, sets, allSchemas);
} catch (e: any) {
source.logger?.warn?.('[effective-permissions] plain-wildcard coverage failed', { err: e?.message });
}
// Make the per-object map reflect the server's ACTUAL effective enforcement
// = permission-set grant ∩ identity write guard (ADR-0057 D10, cited as an
// attribution, #9628) ∩ [#30370] external write gate (ADR-0015 §5.3): (1) fold each set's `'*'` super-user grant into every
// entry that set does not name, so an admin's wildcard is not shadowed by
// another set's explicit deny — [#20134] every bit it grants, `transfer` and
// its own plain bits included; [#20136] per set only, never the merged
// bypass, which would also override the super-user set's OWN narrower entry;
// (2) re-clamp guarded managed objects by their write affordance; (3)
// [#30370] re-clamp objects whose external write gate is closed.
foldSuperUserWildcardGrants(objects, sets);
clampManagedObjectWrites(objects, schemaOf);
// [#30370] Judged in full before anything is clamped, so a predicate that
// throws midway clamps nothing rather than half the map — and the
// annotation below reads these same verdicts, never a second asking.
let externalWriteForbidden: ReadonlySet<string> = new Set();
const isForbidden = source.isExternalWriteForbidden;
if (typeof isForbidden === 'function') {
try {
externalWriteForbidden = new Set(Object.keys(objects).filter((name) => name !== '*' && isForbidden(name) === true));
} catch (e: any) {
source.logger?.warn?.('[effective-permissions] external write gate read failed', { err: e?.message });
}
}
clampExternalReadOnlyWrites(objects, externalWriteForbidden);
// [#3391] Annotate the per-object effective API operation set. Guarded: on
// failure `apiOperations` is simply omitted and a client falls back to its
// default-allow behaviour.
try {
annotateEffectiveApiOperations(objects, schemaOf, (name) => externalWriteForbidden.has(name));
} catch (e: any) {
source.logger?.warn?.('[effective-permissions] apiOperations annotate failed', { err: e?.message });
}
// [#28877] Last: a disabled package's objects leave the map. Guarded like the
// seed: a predicate that throws leaves the map as the earlier steps built it.
try {
omitDisabledPackageObjects(objects, source.isObjectPackageDisabled);
} catch (e: any) {
source.logger?.warn?.('[effective-permissions] disabled-package omission failed', { err: e?.message });
}
return objects as Record<string, EffectiveObjectPermission>;
}
// ---------------------------------------------------------------------------
// [Ruling of record 6408558941, letter A — ADR-0066 ⑧ note of 2026-10-26]
// The `fields` slot, and the ONE reading of how a field-permission entry votes.
// ---------------------------------------------------------------------------
/**
* One field-permission entry as every merge reads it — the parsed
* `FieldPermission` of `@objectstack/spec/security`, or the stored shape a
* resolver hands back, which may carry the keys unparsed.
*/
export interface FieldPermissionEntryLike {
readable?: boolean;
editable?: boolean;
/** The row condition (`FieldPermissionSchema.when`); absent, the entry votes on every row. */
when?: string;
}
/**
* What a reader knows about an entry's row condition on the row it is judging:
*
* - `matched` — the row satisfies the condition, or the entry carries none:
* the entry votes as declared;
* - `unmatched` — the row does not satisfy it: the entry is ABSENT, as if
* the set had not declared the field;
* - `unjudged` — no row can be judged (a reader that holds no row, a predicate
* update with no row address, a stored row the caller cannot read, a
* condition that does not resolve for the request): the entry is judged as
* its LOCK — it votes its read bit as declared and contributes NO edit
* grant, so a reading made without the row is never wider than the gate's.
*/
export type FieldConditionVerdict = 'matched' | 'unmatched' | 'unjudged';
/**
* How one field-permission entry votes under `verdict` — the ONE reading of
* `FieldPermissionSchema.when` shared by `PermissionEvaluator.getFieldPermissions`
* (per object, with the write gate's row judge) and
* {@link buildEffectiveFieldPermissions} (every object, row-blind). `null` is
* "no vote": the entry is absent from the merge, which keeps the rule that only
* DECLARING sets vote exactly as it was for an entry without a condition.
*
* The read bit is row-blind by contract — the spec refuses `readable: false`
* beside a `when` — so it is taken as declared under every verdict; only the
* edit bit is withheld when the row is `unmatched` (absent) or `unjudged`
* (locked). Each bit is read as the merges always read it (`=== true`: a
* parsed entry carries the schema defaults, an unparsed one votes only what
* it spells), so an entry without a `when` votes byte-identically to before.
*/
export function fieldPermissionVote(
entry: FieldPermissionEntryLike,
verdict: FieldConditionVerdict,
): { readable: boolean; editable: boolean } | null {
if (entry.when === undefined) return { readable: entry.readable === true, editable: entry.editable === true };
if (verdict === 'unmatched') return null;
return { readable: entry.readable === true, editable: verdict === 'matched' && entry.editable === true };
}
/**
* [ADR-0066 D2 / ①] Does `set` hold the super-user ("View/Modify All Data")
* bypass on `objectName`? The ONE reading of that question:
* `PermissionEvaluator.superuserBypassSets` (`@objectstack/plugin-security`,
* the row-level bypass every RLS, sharing and explain consumer folds through)
* asks it per set, and so does the field merge's super-user vote below, so the
* two can never disagree about who is a super-user on an object.
*
* The set's own entry for the object answers when it has one; otherwise its
* `'*'` wildcard does (`resolveObjectPermission` in the evaluator: lookup, not
* merge). The private posture never changes the answer, because it withholds
* only a wildcard that carries NEITHER bit.
*
* - `view` — `viewAllRecords` OR `modifyAllRecords` (Modify All implies View All);
* - `modify` — `modifyAllRecords` only: View All never widens a write.
*/
export function holdsSuperuserBypass(
set: { objects?: Record<string, unknown> | null } | null | undefined,
objectName: string,
bit: 'view' | 'modify',
): boolean {
const objects = set?.objects;
if (!objects || typeof objects !== 'object') return false;
const op = (objects[objectName] || objects['*']) as
| { viewAllRecords?: unknown; modifyAllRecords?: unknown }
| null
| undefined;
if (!op || typeof op !== 'object') return false;
return bit === 'modify' ? Boolean(op.modifyAllRecords) : Boolean(op.viewAllRecords || op.modifyAllRecords);
}
/**
* [ADR-0066 D2 ⑧ as amended — ruling of record 6573563853, letter A] The
* super-user vote in the field merge: when any of `sets` holds the bypass on
* `objectName` ({@link holdsSuperuserBypass}), it votes on EVERY field of that
* object — `viewAllRecords` votes `readable: true`, `modifyAllRecords` votes
* `readable: true` and `editable: true`. `null` when no set holds it.
*
* A set that grants the object through its super-user bits but names no field
* used to cast no vote at all, so another set's `readable: false` hid the
* field from a platform admin who also held that set. Union without deny is
* otherwise unchanged: a caller who holds no super-user set on the object is
* narrowed by a declared mask as before. Applied to the fields the merge
* already holds an entry for; an absent field is unrestricted anyway.
*
* Both merges apply it after their declared-entry votes —
* `PermissionEvaluator.getFieldPermissions` per object and
* {@link buildEffectiveFieldPermissions} for every object.
*/
export function superuserFieldVote(
sets: ReadonlyArray<{ objects?: Record<string, unknown> | null } | null | undefined>,
objectName: string,
): { readable: true; editable: boolean } | null {
let read = false;
for (const ps of sets) {
if (holdsSuperuserBypass(ps, objectName, 'modify')) return { readable: true, editable: true };
if (!read && holdsSuperuserBypass(ps, objectName, 'view')) read = true;
}
return read ? { readable: true, editable: false } : null;
}
/** A resolved permission set, as far as the field merge reads it. */
export interface EffectiveFieldPermissionsInputSet {
fields?: Record<string, unknown> | null;
/** Read only for the super-user vote ({@link superuserFieldVote}). */
objects?: Record<string, unknown> | null;
}
/**
* The `fields` slot of `/auth/me/permissions`: the most-permissive merge of
* every set's `fields` entries, keyed `<object>.<field>` as authored, for ALL
* objects in one pass — the same vote per entry as
* `PermissionEvaluator.getFieldPermissions` takes per object, read through
* {@link fieldPermissionVote}. Row-blind by construction (the endpoint holds
* no row), so a row-conditioned entry is reported as its lock: a client reading
* this map never advertises an edit the write gate refuses, and may hide one it
* admits on the rows the condition does not name.
*
* A set holding the super-user bypass on an object then votes on every field
* of it ({@link superuserFieldVote}, ruling of record 6573563853).
*
* Every entry is a FRESH object, as {@link buildEffectiveObjectPermissions}'s are.
*/
export function buildEffectiveFieldPermissions(
sets: ReadonlyArray<EffectiveFieldPermissionsInputSet | null | undefined>,
): Record<string, { readable: boolean; editable: boolean }> {
const fields: Record<string, { readable: boolean; editable: boolean }> = {};
for (const ps of sets) {
if (!ps?.fields || typeof ps.fields !== 'object') continue;
for (const [key, entry] of Object.entries(ps.fields)) {
if (!entry || typeof entry !== 'object') continue;
const vote = fieldPermissionVote(entry as FieldPermissionEntryLike, 'unjudged');
if (!vote) continue;
const acc = fields[key] ?? { readable: false, editable: false };
if (vote.readable) acc.readable = true;
if (vote.editable) acc.editable = true;
fields[key] = acc;
}
}
// [Ruling of record 6573563853] The super-user vote, per object the map
// names — the same function `getFieldPermissions` applies per object.
const votes = new Map<string, ReturnType<typeof superuserFieldVote>>();
for (const [key, acc] of Object.entries(fields)) {
const dot = key.indexOf('.');
if (dot <= 0) continue;
const objectName = key.slice(0, dot);
if (!votes.has(objectName)) votes.set(objectName, superuserFieldVote(sets, objectName));
const vote = votes.get(objectName);
if (!vote) continue;
acc.readable = true;
if (vote.editable) acc.editable = true;
}
return fields;
}