Repository navigation
Expand file tree
/
Copy pathsharing-rule-service.ts
More file actions
2539 lines (2432 loc) · 123 KB
/
Copy pathsharing-rule-service.ts
File metadata and controls
2539 lines (2432 loc) · 123 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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import type {
ISharingRuleService,
DefineSharingRuleInput,
SharingRuleRow,
SharingRuleEvaluationResult,
ShareAccessLevel,
SharingRuleRecipientType,
} from '@objectstack/spec/contracts';
// [#7136] The full `resolveAuthzContext` envelope — what `ISharingRuleService`
// has declared for every one of these context parameters since commit aa4b90d9a (the
// full-envelope ruling: no per-site subset contracts).
import type { ExecutionContext } from '@objectstack/spec/kernel';
// [#15981] The built-in platform-operator position NAME is deliberately NOT
// imported here any more. It used to spell the second half of
// {@link SharingRuleService.hasPlatformAuthority}, and reading it as authority
// became an escalation channel once `positions[]` started carrying ADR-0057 D4
// `sys_user_position` names; that predicate now reads the ADR-0095 rung.
// [ADR-0131 D3, ADR-0126 §4] The activation ledger a position's deactivation is
// read from — the table the authorization resolver reads it from, by name.
import { METADATA_ACTIVATION_TABLE } from '@objectstack/core';
// [#14754] The engine's organization refusal for a system write on a
// tenant-scoped object (#8844). The runtime check is a `code` compare, which is
// the convention that refusal itself documents ("a caller that catches it
// identifies it by `code`") so the check survives the package boundary where
// two copies of that module can exist — `instanceof` is unsound across the dual
// build and fails SILENTLY, as a catch that never fires.
//
// [#14936] The recognizer and the code are taken FROM the engine rather than
// re-spelled here. The engine publishes both precisely so a consumer can
// perform the compare without authoring the string itself: a local literal is a
// second spelling that can drift from what the engine throws, and it acquires a
// `check:error-code-provenance` stamp site in this package for a code this
// package only ever RECOGNISES.
import {
isSystemWriteOrganizationRequiredError,
SYSTEM_WRITE_ORGANIZATION_REQUIRED_CODE,
} from '@objectstack/objectql';
import type { SharingEngine } from './sharing-service.js';
import type { SharingService } from './sharing-service.js';
import { isInternalRecipientRefusal } from './sharing-service.js';
import { normalizeAccessLevel, normalizeStoredAccessLevel } from './access-level.js';
import { parseCriteria, isMatchAllCriteria, MATCH_ALL_CRITERIA_MESSAGE } from './rule-criteria.js';
import { TeamGraphService, teamHasMember } from './team-graph.js';
import { PositionGraphService } from './position-graph.js';
import { BusinessUnitGraphService } from './business-unit-graph.js';
import type { DeclaredSharingRule, DeclaredSharingRuleSource } from './declared-sharing-rules.js';
/**
* System-elevated context for the rule evaluator's own reconcile writes.
*
* [#7136] Typed as the full envelope so it is passed AS ITSELF. It used to be
* declared `as const` and forced through an `as any` at all 10 of its context
* call sites — an erasure on an enforcement input, which switches checking off
* for the whole argument, not just for the readonly-array mismatch that
* provoked it.
*/
const SYSTEM_CTX: ExecutionContext = { isSystem: true, positions: [], permissions: [] };
/** The organization object, whose registration tells a lean embedding from a deployment with organizations. */
const ORGANIZATION_OBJECT = 'sys_organization';
/**
* [ADR-0131 D6 regime C] The `sys_metadata_activation.metadata_type` a declared
* sharing rule's switch is recorded under — its registry type.
*/
export const SHARING_RULE_ACTIVATION_TYPE = 'sharing_rule';
/**
* [#15072] The `FieldSchema.name` machine-name grammar, as `packages/spec`
* spells it inline (`data/field.zod.ts`; `shared/identifiers.zod.ts` records
* that object and field names are bound there and by no exported schema). A
* `field` recipient's `recipient_id` is a field NAME and is held to it at the
* authoring seams that never run the spec parse — see
* {@link SharingRuleService.defineRule}.
*/
export const FIELD_NAME_GRAMMAR = /^[a-z_][a-z0-9_]*$/;
/**
* [#15072] The user ids a record's user-typed column names.
*
* Exactly the stored shapes a user-valued field has: one id (a scalar) or,
* with `multiple: true`, an array of ids — the drivers hydrate a multi-value
* column back to an array before a row reaches an `engine.find` caller, so a
* string here is one id, never JSON to be parsed (a driver handing back an
* unhydrated column would be the driver's defect, and a parse here would
* fossilise it into a second contract — AGENTS.md PD #12). Everything else —
* `null`, an empty string, an empty array, an object — names NOBODY: fail-
* closed, executor-contract point 3 (never a match-all principal, never a
* fallback to the owner). Duplicates collapse: a column naming one user twice
* grants once.
*/
function usersNamedBy(raw: unknown): string[] {
const out = new Set<string>();
const add = (v: unknown): void => {
if (typeof v !== 'string' && typeof v !== 'number') return;
const id = String(v).trim();
if (id) out.add(id);
};
if (Array.isArray(raw)) for (const v of raw) add(v);
else add(raw);
return [...out];
}
/**
* [#15072] Does this declared field hold USERS? The two spellings the spec
* has for a user-valued column: the `user` type (its target is fixed to
* `sys_user` by the type — `Field.user()` takes no target), and a `lookup` /
* `master_detail` whose `reference` is `sys_user` (the same pair
* `defaultValue: 'current_user'` is accepted on, `data/field.zod.ts`).
*/
function fieldHoldsUsers(def: unknown): boolean {
if (!def || typeof def !== 'object') return false;
const d = def as { type?: unknown; reference?: unknown };
if (d.type === 'user') return true;
return (d.type === 'lookup' || d.type === 'master_detail') && d.reference === 'sys_user';
}
function uid(prefix: string): string {
const g: any = globalThis as any;
if (g.crypto?.randomUUID) return `${prefix}_${g.crypto.randomUUID()}`;
return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
}
function rowFromRule(row: any): SharingRuleRow {
return {
id: row.id,
organization_id: row.organization_id ?? null,
name: row.name,
label: row.label,
description: row.description ?? null,
object_name: row.object_name,
criteria: parseCriteria(row.criteria_json),
recipient_type: row.recipient_type as SharingRuleRecipientType,
recipient_id: row.recipient_id,
// Projected through the normaliser, not cast: a rule row stored before
// `full` was retired (#3865) must report the level it actually enforces.
// This also makes reconciliation self-healing — a `full` rule now differs
// from its `full` share rows, so the next pass re-grants them as `edit`.
access_level: normalizeStoredAccessLevel(row.access_level),
active: row.active !== false,
managed_by: row.managed_by ?? null,
customized: row.customized === true,
created_at: row.created_at ?? undefined,
updated_at: row.updated_at ?? undefined,
};
}
/**
* [ADR-0131 D2/D8] The one scope a declared rule is served in under `single`:
* the deployment. A typed marker, never an organization id and never NULL —
* "no organization" is not a state (D1), and no layer has a NULL arm (D8).
*/
const DEPLOYMENT_WIDE_SCOPE: unique symbol = Symbol('sharing-rule.deployment-wide');
/** [ADR-0131 D2] Where a declared rule is served: the deployment, or one organization. */
type DeclaredRuleScope = string | typeof DEPLOYMENT_WIDE_SCOPE;
/**
* [ADR-0131 D2] A declared rule's projection that sweeps the deployment — the
* typed marker that replaced the organization-less (`organization_id: null`)
* projection, in the shape of the declared webhooks' `deploymentWide` (the
* epic's ruling A on the walled shape of a declared webhook, record
* 6278609968). It carries no `organization_id` at all. The marker itself is
* declared on the spec contract (`SharingRuleRow.deploymentWide`); this type
* narrows it to present.
*/
export interface DeploymentWideSharingRule extends SharingRuleRow {
readonly deploymentWide: true;
}
/**
* Does `rule` sweep the whole deployment? Only a declared rule's `single`
* projection does ({@link projectDeclaredRule}); a stored row is never one,
* because {@link rowFromRule} builds its fields one by one and the marker is
* not a column.
*/
export function isDeploymentWideSharingRule(rule: SharingRuleRow): rule is DeploymentWideSharingRule {
return (rule as Partial<DeploymentWideSharingRule>).deploymentWide === true && isDeclaredSharingRule(rule);
}
/**
* [ADR-0131 D2] A DECLARED rule as the rule set serves it: the declaration
* (read from the registry, {@link DeclaredSharingRuleSource}) projected into
* the runtime row shape for ONE scope. It is not a row: nothing is written for
* it.
*
* A declaration is deployment-wide under every posture — every organization
* runs the same code (D2). How it is SERVED follows the wall:
*
* - under `single`, ONE projection marked {@link DeploymentWideSharingRule}:
* its criteria sweep carries no tenant, which is the predicate D8 computes
* there (none), and each grant is stamped with its record's organization;
* - under a wall, one projection PER ORGANIZATION, stamped with it: the sweep
* runs inside that organization's one predicate, recipients expand inside
* it, and its grants carry it. A deployment-wide sweep under a wall would
* be a second predicate beside Layer 0's, which D8 forbids.
*
* Its `id` is its NAME. That is what its grants carry as
* `sys_record_share.source_id` (ruling β item 5 (c) on the C3 epic: the
* ownership ceremony rewrites a declared-rule mirror's grants from the mirror
* row's id to the rule's name before it deletes the mirror), so every
* reconcile below reads and writes a declared rule's grants by name with no
* second code path. An organization-authored rule keeps its row id.
*/
function projectDeclaredRule(rule: DeclaredSharingRule, scope: DeclaredRuleScope): SharingRuleRow {
return {
id: rule.name,
...(scope === DEPLOYMENT_WIDE_SCOPE ? { deploymentWide: true } : { organization_id: scope }),
name: rule.name,
label: rule.label,
description: rule.description,
object_name: rule.object,
criteria: rule.criteria,
recipient_type: rule.recipientType,
recipient_id: rule.recipientId,
access_level: normalizeStoredAccessLevel(rule.accessLevel),
active: rule.active,
managed_by: 'package',
customized: false,
};
}
/**
* Is `rule` a declared rule's projection ({@link projectDeclaredRule}) rather
* than a `sys_sharing_rule` row? A row's id is minted (`srule_…`, or the data
* API's), never its name, and `managed_by` is readonly to every non-system
* writer — so the pair cannot be forged by an author.
*/
export function isDeclaredSharingRule(rule: Pick<SharingRuleRow, 'id' | 'name' | 'managed_by'>): boolean {
return rule.managed_by === 'package' && rule.id === rule.name;
}
/**
* [ADR-0131 D6 regime C — ruling A on the declared sharing rules] A
* `sys_sharing_rule` row — new, or renamed — that would take a declared rule's
* name.
*
* A declared sharing rule is read-only and clonable: it is customised by a
* CLONE under a new name, with the declared rule switched off through the
* activation ledger ({@link SharingRuleService.reconcileDeclaredRuleActivation}).
* Same-name shadowing is retired, so no write may take a declared rule's name
* — Setup's New, a script, an AI tool, `POST /api/v1/sharing/rules` — and every
* such write is refused before it lands.
*
* `code` + `status` are the declared envelope the `/data` door and the
* sharing-rule routes answer at its own status (409 `RESOURCE_CONFLICT`, the
* catalogue's code for a 409 — `HttpStatusErrorCodeMap`): the name is taken by
* an existing rule, which is a conflict, not a missing capability.
*/
export class DeclaredSharingRuleNameConflictError extends Error {
readonly code = 'RESOURCE_CONFLICT';
readonly status = 409;
/** The declared (vendor) rule whose name the write would take. */
readonly rule: string;
constructor(rule: Pick<DeclaredSharingRule, 'name' | 'object'>, write: 'create' | 'rename') {
super(
`sharing rule '${rule.name}' is declared by the application (on object '${rule.object}'), so ` +
(write === 'create' ? 'a new rule cannot take its name' : 'no rule can be renamed to it') +
`. Declared rules are read-only: to customise '${rule.name}', create your own rule under another name and ` +
`switch the declared one off (POST /api/v1/security/_activation/sharing_rule/${rule.name} with ` +
'{ "enabled": false }).',
);
this.name = 'DeclaredSharingRuleNameConflictError';
this.rule = rule.name;
}
}
/** Package id of {@link bindDeclaredRuleNameGuard}'s hooks. */
export const DECLARED_RULE_NAME_GUARD_PACKAGE = 'plugin-sharing:declared-rule-name-guard';
/**
* [ADR-0131 D6 regime C] Bind the guard above on `sys_sharing_rule` writes that do not
* come through {@link SharingRuleService.defineRule}: the `/data` door Setup's
* New and its edit form write through, scripts, imports. An insert of a
* declared name is refused, and so is an update that CHANGES `name` onto one;
* an update that leaves the name alone (a customised copy's `active` switch)
* passes.
*
* System writes pass: `defineRule` writes under the system context after making
* the same check itself, and the remaining system writers are the platform's
* own machinery (the ownership ceremony, migrations).
*/
export function bindDeclaredRuleNameGuard(
engine: {
registerHook(event: string, handler: (ctx: any) => any, options?: Record<string, any>): void;
unregisterHooksByPackage?(packageId: string): number;
},
rules: Pick<SharingRuleService, 'declaredRuleNamed'>,
): void {
engine.unregisterHooksByPackage?.(DECLARED_RULE_NAME_GUARD_PACKAGE);
const guard = (insert: boolean) => async (ctx: any) => {
if ((ctx?.session as any)?.isSystem) return;
const data = ctx?.input?.data;
if (!data || typeof data !== 'object' || Array.isArray(data)) return;
if (typeof data.name !== 'string') return;
// An update is a rename only against its pre-image (`ctx.previous`, the
// `HookContext` contract both update shapes bind before `beforeUpdate`): a
// full-form save re-sends the name it already has.
if (!insert) {
const previous = ctx?.previous as Record<string, unknown> | undefined;
if (!previous || typeof previous !== 'object' || data.name === previous.name) return;
}
const declared = await rules.declaredRuleNamed(data.name);
if (declared) throw new DeclaredSharingRuleNameConflictError(declared, insert ? 'create' : 'rename');
};
const opts = { object: 'sys_sharing_rule', packageId: DECLARED_RULE_NAME_GUARD_PACKAGE, priority: 100 };
engine.registerHook('beforeInsert', guard(true), opts);
engine.registerHook('beforeUpdate', guard(false), opts);
}
/** Package id of {@link bindSharingRuleActivationReconcile}'s hooks. */
export const SHARING_RULE_ACTIVATION_RECONCILE_PACKAGE = 'plugin-sharing:sharing-rule-activation-reconcile';
/**
* [ADR-0131 D6 regime C] Reconcile a declared rule's grants when its
* activation-ledger row is written: the `sys_metadata_activation` write the
* activation door (`POST /security/_activation/sharing_rule/:name`) makes is
* followed, in the same request, by
* {@link SharingRuleService.reconcileDeclaredRuleActivation} — off revokes
* every grant carrying the rule's name, on re-derives them. A failure is the
* write's failure: it reaches the door, which answers it, rather than leaving a
* switched-off rule's grants standing behind a successful flip.
*/
export function bindSharingRuleActivationReconcile(
engine: {
registerHook(event: string, handler: (ctx: any) => any, options?: Record<string, any>): void;
unregisterHooksByPackage?(packageId: string): number;
},
rules: Pick<SharingRuleService, 'reconcileDeclaredRuleActivation'>,
): void {
engine.unregisterHooksByPackage?.(SHARING_RULE_ACTIVATION_RECONCILE_PACKAGE);
const handler = async (ctx: any) => {
// The update patch carries `{ id, active, package_id }`; type and name come
// from the pre-image (`ctx.previous`), an insert's from the row itself.
const row = { ...(ctx?.previous ?? {}), ...(ctx?.result ?? ctx?.input?.data ?? {}) };
if (row.metadata_type !== SHARING_RULE_ACTIVATION_TYPE || typeof row.name !== 'string' || !row.name) return;
await rules.reconcileDeclaredRuleActivation(row.name);
};
for (const event of ['afterInsert', 'afterUpdate', 'afterDelete']) {
engine.registerHook(event, handler, {
object: METADATA_ACTIVATION_TABLE,
packageId: SHARING_RULE_ACTIVATION_RECONCILE_PACKAGE,
priority: 200,
});
}
}
/**
* The `sys_record_share` rows a rule's grants are: `source: 'rule'` plus the
* rule's id. A declared rule served under a wall is one projection per
* organization, all carrying the rule's name, so its grants are told apart by
* the organization each one is stamped with — the rule's own, which the grant
* write threads ({@link SharingRuleService.criteriaContext}). Without it one
* organization's reconcile would read every other organization's grants of
* the same rule as its own stale rows, and revoke them.
*/
function ruleGrantScope(rule: SharingRuleRow): Record<string, unknown> {
const where: Record<string, unknown> = { source: 'rule', source_id: rule.id };
if (isDeclaredSharingRule(rule) && !isDeploymentWideSharingRule(rule)) where.organization_id = rule.organization_id;
return where;
}
/** Name order, as `listRules` has always answered. */
function byName(a: SharingRuleRow, b: SharingRuleRow): number {
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
}
/**
* [#14754] What one reconcile pass did, plus the grants the engine's
* organization rule REFUSED in it.
*
* [#14969] The NARROWING is the point, not a lag. `@objectstack/spec` declares
* `grantsRefused?: number` on {@link SharingRuleEvaluationResult} itself, and
* declares it OPTIONAL on purpose: an `ISharingRuleService` implementation that
* does not count refusals leaves the key ABSENT, and absent is not `0`. This
* implementation always counts them, so it REQUIRES the key — a legal covariant
* narrowing, and the reason a caller holding this type never has to decide
* whether an unset key means "no grant was refused" or "this implementation
* does not report refusals". Consumers typed against the spec contract are
* unaffected; for them the key stays optional. The required form is what this
* package's own pins assert and what the evaluate route puts on the wire — it
* answers this service's return value unfiltered.
*
* ⛔ `grantsRefused > 0` is NOT "the pass failed". It is the pass reporting that
* it met a record it cannot grant on (an organization-less record under a
* walled posture) and CONTINUED — which is the whole point: the remaining
* grants and, above all, the stale-row revocations still ran.
*/
export interface SharingRuleReconcilePassResult extends SharingRuleEvaluationResult {
/** Grants the engine's organization rule refused; each one is also logged. */
grantsRefused: number;
/**
* [#25549] One line, present only when the pass skipped recipients: the rule
* is anchored on a public object, where a share reaches an `external` member
* of the record's organization only, so no row was written for the internal
* recipients it expands to, nor for any recipient on a record whose
* organization could not be resolved. The count is in the pass's log line.
*/
note?: string;
}
/** What one attempted grant of a pass came to. */
type RuleGrantOutcome = 'granted' | 'refused' | 'internal';
/** [#25549] The pass's one-line note when it skipped internal recipients. */
function internalHalfNote(object: string): string {
return `"${object}" has a public sharing model: rows were written only for external members of each record's `
+ 'organization; none for the other recipients this rule expands to (internal members already reach its '
+ 'records, and a record whose organization could not be resolved admits no recipient)';
}
export interface SharingRuleServiceOptions {
engine: SharingEngine;
sharing: SharingService;
/**
* [ADR-0131 D2] Where DECLARED rules are read — the registry
* (`createDeclaredSharingRuleSource`). Absent, the rule set is the
* `sys_sharing_rule` rows alone.
*/
declaredRules?: DeclaredSharingRuleSource;
logger?: {
info?: (msg: any, ...rest: any[]) => void;
/**
* The GUARANTEED fallback channel (#9754, ruled on #10556). `error` stays
* optional — hosts do inject reduced sinks — so `warn` is where a
* durability report lands when `error` is absent, and a fallback that may
* itself be missing is not a fallback. Call sites keep the
* `logger?.warn?.(…)` spelling as the backstop for hosts the TYPE cannot
* reach; `SweepLogger` in plugin-email's `outbox-sweep.ts` carries the full
* reasoning and the measurement.
*
* ⚠️ This member is REQUIRED, and `SharingRuleServiceOptions` is PUBLICLY EXPORTED
* from this package's `index.ts` — so a host passing `{ info, error }`
* compiled before this landed and does not after. That break is declared,
* shipped `minor`, and named in the changeset (maintainer ruling
* 2026-08-24, #10556 limb (c)).
*/
warn: (msg: any, ...rest: any[]) => void;
error?: (msg: any, ...rest: any[]) => void;
debug?: (msg: any, ...rest: any[]) => void;
};
}
/**
* [commit 04d03c3a0] Memo for the catalogue reads a recipient expansion adds, scoped to
* ONE evaluator pass.
*
* The lifetime is the whole design. It is the same lifetime the graph services
* already document for their own `cache` option ("shared cache across one
* evaluator pass"), and it is deliberately NOT a field on the service: this
* service instance lives as long as the plugin, so a memo hung there would
* outlive the pass and make a deactivation take effect late — a second defect
* in the shape of a fix for the first. Created at the public entry, threaded
* down, discarded with the pass.
*/
type RuleEvaluationPass = {
/** Position activation verdicts (the activation ledger), keyed by position name. */
positionActive?: Map<string, boolean>;
};
/** [#15072] One grant a rule DESIRES on a whole-rule pass: a (record, user) pair. */
interface DesiredGrant {
record_id: string;
recipient_id: string;
}
/**
* [#15072] Everything a whole-rule pass wants to exist, keyed
* `${record_id}::${recipient_id}`, plus the two counts the evaluation result
* reports. Built per recipient kind by {@link SharingRuleService.desiredGrantsForRule}
* so that `reconcile` diffs pairs without knowing whether the recipient was
* resolved once per rule or once per record.
*/
interface DesiredGrantSet {
desired: Map<string, DesiredGrant>;
matchedRecords: number;
expandedUsers: number;
}
/**
* Default {@link ISharingRuleService} implementation.
*
* Stores rule definitions in `sys_sharing_rule` and materialises grants
* as `sys_record_share` rows with `source='rule'` and `source_id={ruleId}`
* so reconcile can diff old grants vs fresh evaluation results without
* touching manual / team-derived shares.
*/
export class SharingRuleService implements ISharingRuleService {
private readonly engine: SharingEngine;
private readonly sharing: SharingService;
private readonly logger?: SharingRuleServiceOptions['logger'];
/**
* [#3929 follow-up] Inert (criteria-less) rules seen this process, for
* once-per-rule warn dedup + the boot aggregate. Pre-dedup the evaluator
* warned on EVERY pass — findMatchingRecords per evaluation AND
* recordMatches per reconciled write — so one legacy row could dominate a
* deployment's log. The enforcement is unchanged (such a rule still
* matches NOTHING); only the repetition is gone.
*/
private readonly inertRuleSeen = new Set<string>();
/**
* [#14547] Business-unit rules seen expanding to NOBODY this process — the
* same once-per-rule dedup {@link inertRuleSeen} carries, for the same
* reason: the reconcilers call {@link expandRecipient} on every matched
* write, so an undeduped warn would let one misconfigured rule dominate a
* deployment's log.
*/
private readonly emptyUnitExpansionSeen = new Set<string>();
/**
* [#15072] `field` rules already warned about this process, keyed by cause
* — the same once-per-rule dedup {@link inertRuleSeen} and
* {@link emptyUnitExpansionSeen} carry, for the same reason: the per-record
* path runs on every write of the shared object.
*/
private readonly fieldRuleWarned = new Set<string>();
/** [ADR-0131 D2] Where declared rules are read. */
private readonly declaredSource?: DeclaredSharingRuleSource;
/**
* [ADR-0131 D2] The scopes a declared rule is served in: the deployment
* under `single` (one {@link DeploymentWideSharingRule} projection), every
* organization under a wall. Set by the plugin from the posture
* ({@link setDeclaredRuleScopes}).
*
* `null` is UNKNOWN — the organizations could not be read
* ({@link setDeclaredRuleScopesUnknown}). It is a state of its own, never an
* empty list: an empty list would read as "no organization serves this
* rule", and the orphaned-grant sweep would revoke every declared rule's
* grants on that reading. Unknown serves no declared rule and revokes none.
*/
private declaredScopes: ReadonlyArray<DeclaredRuleScope> | null = [DEPLOYMENT_WIDE_SCOPE];
/** [ADR-0131 D2] The held-back sweep under unknown scopes says so once per process. */
private unknownScopesSweepWarned = false;
/** [ADR-0131 D6 regime C] The declaration-over-row conflicts already reported, `name::scope`. */
private readonly declarationOverRowReported = new Set<string>();
/** [ADR-0131 D1/D8] Stored rules refused for carrying no organization, reported once each. */
private readonly organizationlessRuleReported = new Set<string>();
constructor(opts: SharingRuleServiceOptions) {
this.engine = opts.engine;
this.sharing = opts.sharing;
this.logger = opts.logger;
this.declaredSource = opts.declaredRules;
}
/**
* [ADR-0131 D2] Serve declared rules in these scopes — the deployment under
* `single`, the organizations under a wall. The same passes the retired
* seeder made, as reads instead of rows: one deployment-wide pass under
* `single`, one per organization under a wall (#10103).
*
* `null` is how the plugin's posture read (`resolveDeclaredRuleScopes`)
* spells `single`. It is translated here, at the one door, into the
* deployment-wide scope, so no NULL travels past this line.
*/
setDeclaredRuleScopes(scopes: ReadonlyArray<string | null>): void {
this.declaredScopes = [...new Set(scopes.map((s): DeclaredRuleScope => (s === null ? DEPLOYMENT_WIDE_SCOPE : s)))];
}
/**
* [ADR-0131 D2] The scopes are UNKNOWN — the organizations could not be
* enumerated. No declared rule is served anywhere (an incomplete scope set
* would grant in some organizations and not others), and
* {@link sweepOrphanedRuleGrants} revokes no declared rule's grant: a read
* that failed is never a revocation. The next boot that reads the
* organizations serves them again.
*/
setDeclaredRuleScopesUnknown(): void {
this.declaredScopes = null;
}
/**
* [ADR-0131 D2] An organization created after boot is served from its
* creation on. Under unknown scopes it stays unknown: one organization known
* is not the set.
*/
addDeclaredRuleScope(organizationId: string): void {
const scopes = this.declaredScopes;
if (!organizationId || scopes === null || scopes.includes(DEPLOYMENT_WIDE_SCOPE) || scopes.includes(organizationId)) {
return;
}
this.declaredScopes = [...scopes, organizationId];
}
/**
* [ADR-0111 D6] The sharing-rule surface is tenant-wide sharing
* ADMINISTRATION — a rule is an org-wide grant generator, and `evaluate`
* triggers materialisation, so every verb (list/get included) requires the
* `manage_sharing` capability. Enforced HERE, not at the route, so every
* caller is covered (#3902's widened finding: any signed-in user could
* define a broad-criteria rule naming themself and evaluate it into
* org-wide `sys_record_share` grants). `manage_platform_settings` is
* honoured as the legacy gate the Setup sharing pages used before
* `manage_sharing` existed. System contexts (boot seeding, hooks, backfills,
* the REST-independent plugin machinery) bypass.
*/
private assertCanManageRules(context: ExecutionContext): void {
if (context?.isSystem) return;
const caps = Array.isArray(context?.systemPermissions) ? context.systemPermissions : [];
if (!caps.includes('manage_sharing') && !caps.includes('manage_platform_settings')) {
throw new Error(
'PERMISSION_DENIED: sharing-rule administration requires the manage_sharing capability (ADR-0111 D6)',
);
}
// [#8158] Holding the capability is not enough: an org-scoped capability
// needs an organization to be scoped BY. See
// {@link assertResolvableAdminScope}.
this.assertResolvableAdminScope(context);
}
/**
* The organization this caller operates in — the ONE spelling of that read.
*
* [#7136] Only the `tenantId` half is a declared field of the envelope;
* `organizationId` is not a field of `ExecutionContext` at all (its history
* is #5858 / `check:org-identifier`, and #7070 explicitly held it out of the
* envelope work), so it stays cast. The asymmetry is the visible marker of
* which of the two names the contract actually knows.
*
* [#8158] Was open-coded at three call sites (`listRules`, `getRule`,
* `defineRule`), with `findRuleRowByName` taking `getRule`'s result as a
* parameter. Three copies of a security-relevant read is how the fall-open
* below stayed invisible: each site could see "no org id", none could see
* whether that meant "system" or "authenticated caller who never selected
* one".
*/
private callerOrgId(context: ExecutionContext): string | undefined {
return ((context as any)?.organizationId ?? context?.tenantId) || undefined;
}
/**
* [#8158] PLATFORM authority — the two spellings, one predicate.
*
* Both spellings are accepted because they are two independent channels by
* which the same unscoped `admin_full_access` grant reaches an
* `ExecutionContext` (a `scope: 'platform'` capability on
* `systemPermissions`; the ADR-0095 posture RUNG): a context built by the
* shared authz resolver carries both, a hand-built one may carry only one,
* so accepting either is the fail-safe reading.
*
* It decides whether an org-less caller may read across tenants. Its other
* question — may this caller DELETE a platform-global (`organization_id =
* null`) rule (#7795) — retired with that rule class (ADR-0131 D1/D2): a
* stored rule belongs to the organization that authored it, and a declared
* rule is code, which no caller deletes.
*
* ⛔ [#15981] The second spelling is the RUNG, never
* `positions.includes(BUILTIN_IDENTITY_PLATFORM_ADMIN)`. The two stopped
* being the same channel when `positions[]` became the security axis: it
* carries ADR-0057 D4 `sys_user_position` names, that table is `apiEnabled`
* with unconstrained `position` values, and `resolveUserAuthzGrants` §4
* pushes a minted row's name straight onto the array. `resolve-authz-context.ts`
* states the rule at `hasPlatformAdminStanding`, and
* `grants.posture === 'PLATFORM_ADMIN'` is byte-for-byte what that predicate
* returns — the unscoped `admin_full_access` evidence, which is what this
* doc block meant by the built-in position all along.
*
* Driven, not argued: with the minted row present and only the ORG-scoped
* `manage_sharing` capability held, the old read admitted an org-less caller
* to every tenant's rules through {@link listRules}. See
* `sharing-rule-positions-name-authority.test.ts`.
*/
private hasPlatformAuthority(context: ExecutionContext): boolean {
const caps = Array.isArray(context?.systemPermissions) ? context.systemPermissions : [];
if (caps.includes('manage_platform_settings')) return true;
return context?.posture === 'PLATFORM_ADMIN';
}
/**
* [#8158] Refuse an authenticated, non-platform caller whose session
* resolves NO organization — the sharing-rule surface's fall-open.
*
* ## The defect
*
* {@link adminOrgScope} used to answer the unfiltered `where` for any caller
* with no org id (`if (!orgId) return where`). That branch exists for
* {@link SYSTEM_CTX} — boot seeding, hooks, backfills — which legitimately
* reads every tenant's rows. But it was reached on the ABSENCE OF AN ORG ID,
* never on system-ness, and {@link assertCanManageRules} admits any caller
* holding the org-scoped `manage_sharing` capability. So an authenticated,
* non-system caller arriving with neither `organizationId` nor `tenantId`
* got the system read scope: {@link listRules} returned EVERY organization's
* rules, {@link getRule} resolved any of them by id or name, and
* {@link evaluateRule} reached those rows too — a cross-tenant WRITE, since
* it reconciles `sys_record_share` grants. Same class #7761 closed for the
* by-id branch, through a different door: there the filter was missing, here
* it was skipped.
*
* ## That context is reachable (measured, not inferred)
*
* `resolveAuthzContext` derives the tenant from the session's active
* organization and stamps it only when truthy, and
* `resolveUserAuthzGrants` resolves an org-SCOPED permission-set grant
* whenever the caller has no active org to compare it against
* (`!(org && tenantId && org !== tenantId)`). A user holding an org-scoped
* `manage_sharing` grant with no `sys_member` row — a multi-org deployment
* (the membership reconciler binds nobody there), an `invite-only`
* deployment, a user removed from their org, an SSO JIT user pending
* placement — therefore logs in, resolves the capability, and carries no
* tenant. Driven end to end over HTTP in
* `packages/qa/dogfood/test/sharing-rule-org-less-caller.dogfood.test.ts`:
* before this guard that session listed both tenants' rules.
*
* ## Refuse, rather than answer empty
*
* Both are fail-closed; the difference is what the caller is told. An empty
* list is the #7676 shape — `{data: []}` over rules that exist and are
* actively granting access, which reads as "this deployment has no sharing
* rules" and sends the operator to look for the wrong bug. A 403 states the
* actual condition and its remedy. `manage_sharing` is declared
* `scope: 'org'` in the spec's capability registry: with no organization
* resolved there is no scope in which it grants anything, so the honest
* answer is a refusal, not an answer.
*
* Asserted in {@link assertCanManageRules}, which every verb already calls
* first — so `defineRule` is covered too, and an org-less caller can no
* longer write a rule with no organization of its own (the engine stamps or
* refuses such a write, ADR-0131 D9).
*
* ## Two classes keep the unfiltered read, deliberately
*
* - **System contexts** (`isSystem`) — the branch's original and only
* intended reason: boot seeding, the reconcile hooks, the backfills.
* - **Platform operators** — `manage_platform_settings` or the
* `platform_admin` position ({@link hasPlatformAuthority}). Their
* cross-tenant read is what the Setup sharing pages are (the capability
* is `scope: 'platform'`, and those pages are documented platform-only in
* plugin-security's default permission sets), and they hold platform
* authority whether or not an organization is selected. Refusing them
* would be a functional regression dressed as a security fix — a
* single-tenant deployment before its default org is bootstrapped, or one
* running `autoDefaultOrganization: false`, has a platform admin with no
* active organization and nothing else wrong with it.
*/
private assertResolvableAdminScope(context: ExecutionContext): void {
if (this.callerOrgId(context)) return;
if (this.hasPlatformAuthority(context)) return;
throw new Error(
'PERMISSION_DENIED: sharing-rule administration requires an active organization — this ' +
'session carries none. manage_sharing is an ORG-scoped capability (ADR-0111 D6), so with ' +
'no organization resolved there is no tenant whose rules it authorizes, and answering ' +
'unscoped would expose every tenant’s rules. Select an active organization and ' +
'retry. Platform operators (manage_platform_settings or the platform_admin position) and ' +
'system contexts are unaffected.',
);
}
async defineRule(input: DefineSharingRuleInput, context: ExecutionContext): Promise<SharingRuleRow> {
this.assertCanManageRules(context);
if (!input.name) throw new Error('VALIDATION_FAILED: name is required');
if (!input.label) throw new Error('VALIDATION_FAILED: label is required');
if (!input.object) throw new Error('VALIDATION_FAILED: object is required');
if (!input.recipientType) throw new Error('VALIDATION_FAILED: recipientType is required');
if (!input.recipientId) throw new Error('VALIDATION_FAILED: recipientId is required');
// [#15072] A `field` recipient's `recipientId` is a FIELD NAME, not a
// principal id, and is held to the grammar `sharedWith.value` meets at
// parse (`ShareRecipientType` `field`, `sharing.zod.ts`): the
// `FieldSchema.name` machine-name shape. Refused HERE as well because this
// entry — the REST `POST /sharing/rules` body and programmatic authoring —
// never runs the spec schema, so without it a dotted path
// (`owner.manager_id`: a graph walk spelled as a value, the shape the
// ruling's ⛔ on a `manager` member refuses) would reach the executor and
// share with nobody in silence.
if (input.recipientType === 'field' && !FIELD_NAME_GRAMMAR.test(String(input.recipientId))) {
throw new Error(
"VALIDATION_FAILED: recipientId must name a user-typed field on the object when recipientType is 'field' " +
`(got ${JSON.stringify(input.recipientId)}) — a snake_case field name, not a principal id and not a dotted path`,
);
}
// [#3896] `criteria` is as required as the fields above — and for a
// sharper reason. Omitting `recipientId` yields a rule that shares with
// nobody; omitting `criteria` used to yield one that shares EVERYTHING
// (stored as `criteria_json: null`, evaluated as the empty filter `{}`
// against SYSTEM_CTX). `SharingRuleSchema` has always forbidden that
// shape — "never seeded as a permissive match-all (ADR-0049)" — but this
// entry, which `POST {basePath}/sharing/rules` plucks its body into, never
// ran the schema, so a missing / null / misspelled (`criterias`) key
// sailed through with a 201 and no warning.
if (isMatchAllCriteria(input.criteria)) {
throw new Error(`VALIDATION_FAILED: ${MATCH_ALL_CRITERIA_MESSAGE}`);
}
// [#7136 / #8158] One spelling of this read for the whole service — see
// {@link callerOrgId}. Only a system context or a platform operator
// reaches this line without an org id (`assertCanManageRules` above
// refuses the authenticated org-less caller). Their insert carries no
// organization, and the engine stamps it with the derivable one under
// `single` or refuses it under a wall (ADR-0131 D9) — it never lands NULL.
const orgId = this.callerOrgId(context) ?? null;
const now = new Date().toISOString();
// Authoring path — `full` normalises to `edit`, anything unrecognised is a
// loud VALIDATION_FAILED alongside the required-field checks above (#3865).
const accessLevel: ShareAccessLevel = normalizeAccessLevel(input.accessLevel, 'read');
const active = input.active !== false;
const criteriaJson = input.criteria == null
? null
: (typeof input.criteria === 'string' ? input.criteria : JSON.stringify(input.criteria));
const existing = await this.engine.find('sys_sharing_rule', {
where: orgId ? { name: input.name, organization_id: orgId } : { name: input.name },
limit: 1,
context: SYSTEM_CTX,
});
// [#2909 P0/T1] Seed mode: a package/platform managedBy marks this call
// as a seed rather than an admin/programmatic authoring path. Its one
// caller here was the boot seeder, retired by ADR-0131 D2 — declared rules
// are read from the registry now ({@link declaredRules}); the contract's
// `managedBy` input keeps its meaning for any other caller. sys_sharing_rule is
// RECORD-AUTHORITATIVE (ADR-0094 addendum): the declared metadata is a
// seed, not a live override, so the seeder must never clobber a row the
// admin owns or has customized — most importantly an admin's
// `active: false` on an over-sharing rule must survive redeploys.
const seedMode = input.managedBy === 'package' || input.managedBy === 'platform';
if (Array.isArray(existing) && existing[0]) {
const row: any = existing[0];
if (seedMode) {
if (row.managed_by === 'admin') {
// Name collision with a tenant-authored rule — the admin's row wins.
this.logger?.warn?.('[sharing-rule] declared rule name collides with an admin-authored rule — seed skipped', {
rule: input.name,
});
return rowFromRule(row);
}
if (row.customized === true) {
// Admin edited/deactivated this seeded rule — never resurrect it.
return rowFromRule(row);
}
}
const patch: any = {
id: row.id,
label: input.label,
description: input.description ?? null,
object_name: input.object,
criteria_json: criteriaJson,
recipient_type: input.recipientType,
recipient_id: input.recipientId,
access_level: accessLevel,
active,
updated_at: now,
// Seed mode adopts pristine/legacy (pre-provenance) rows so future
// boots recognize them; non-seed calls never touch provenance.
...(seedMode ? { managed_by: input.managedBy } : {}),
};
await this.engine.update('sys_sharing_rule', patch, { context: SYSTEM_CTX });
return rowFromRule({ ...row, ...patch });
}
// [ADR-0131 D6 regime C] No row holds this name in the caller's scope, so
// the write creates one — and no row may take a declared rule's name.
const declared = await this.declaredRuleNamed(input.name);
if (declared) throw new DeclaredSharingRuleNameConflictError(declared, 'create');
const newRow: any = {
id: uid('srule'),
organization_id: orgId,
name: input.name,
label: input.label,
description: input.description ?? null,
object_name: input.object,
criteria_json: criteriaJson,
recipient_type: input.recipientType,
recipient_id: input.recipientId,
access_level: accessLevel,
active,
managed_by: input.managedBy ?? 'admin',
customized: false,
created_at: now,
updated_at: now,
};
await this.engine.insert('sys_sharing_rule', newRow, { context: SYSTEM_CTX });
return rowFromRule(newRow);
}
/**
* Tenant scope for a sharing-rule ADMIN read: the caller's OWN organization.
*
* [ADR-0131 D1/D8] This was "this org ∪ platform-global" (#7676): a
* `$or` with an `organization_id = null` arm, because the retired boot
* seeder (`bootstrapDeclaredSharingRules`) defined declared rules under the
* system context and so stamped them with no organization, and a strict
* equality made those rows invisible to the admin API while enforcement
* kept reading them. Both halves of that reason are gone: declared rules are
* read from the registry and never written (D2, {@link declaredRules}, which
* serves them beside the rows below), and the organization-ownership
* ceremony attributes every stored row before the deployment is certified
* (D10), after which a write with no organization is stamped or refused
* (D9). No layer keeps a NULL arm (D8), so this one is an equality.
*
* ⚠️ {@link defineRule}'s existence lookup is the same equality, and must
* stay one: it decides UPSERT-or-insert, so a wider lookup would let one
* organization's admin overwrite a row another organization reads.
*
* [#7761] It IS applied to {@link getRule}'s by-**id** branch. Unfiltered,
* that branch let an org admin resolve — and, through {@link deleteRule},
* destroy — another organization's rule from its id alone.
*
* [#8158] Takes the CONTEXT, not a bare org id. The unfiltered branch is
* for a system context (and, since #8158, a platform operator) — a fact
* only the context carries. Handed an org id alone, this function could not
* tell "boot seeding" from "an authenticated caller who never selected an
* organization" and answered unfiltered to both;
* {@link assertResolvableAdminScope} is where that distinction now lives,
* and this signature is what stops a future call site from re-conflating
* them.
*/
private adminOrgScope(where: Record<string, unknown>, context: ExecutionContext): Record<string, unknown> {
const orgId = this.callerOrgId(context);
if (!orgId) return where; // system context / platform operator — asserted upstream
return { ...where, organization_id: orgId };
}
async listRules(
filter: { object?: string; activeOnly?: boolean },
context: ExecutionContext,
): Promise<SharingRuleRow[]> {
this.assertCanManageRules(context); // [ADR-0111 D6]
const where: any = {};
if (filter.object) where.object_name = filter.object;
if (filter.activeOnly) where.active = true;
const rows = await this.engine.find('sys_sharing_rule', {
where: this.adminOrgScope(where, context),
orderBy: [{ field: 'name', order: 'asc' }],
limit: 1000,
context: SYSTEM_CTX,
});
const stored = Array.isArray(rows) ? rows.map(rowFromRule) : [];
// [ADR-0131 D2] The declared rules, read from the registry — every
// enforcement path (the record hooks, the object and boot reconciles, the
// business-unit recompute, the rebind) lists through here.
const declared = await this.declaredRules(context, filter);
return declared.length === 0 ? stored : [...stored, ...declared].sort(byName);
}
/**
* [ADR-0131 D2] The declared rules this caller's scope serves, projected
* ({@link projectDeclaredRule}) — the retired seeder's passes, read instead
* of written.
*
* A declaration is NOT served in a scope where a `sys_sharing_rule` row
* holds its name — the row the seeder's upsert would have found there: under
* `single` a row of that name in any organization, under a wall that
* organization's row of that name. Such a row is an organization's own rule
* of that name, a seeded copy an administrator customized, or a seeded copy
* the ownership ceremony has not deleted yet; it answers for the name, as it
* did while the seeder ran (an admin-authored or customized row was never
* overwritten), and the declaration does not ALSO grant beside it.
*/
private async declaredRules(
context: ExecutionContext,
filter: { object?: string; activeOnly?: boolean; name?: string },
): Promise<SharingRuleRow[]> {
if (!this.declaredSource) return [];
let rules = await this.declaredSource.list();
if (filter.object) rules = rules.filter((r) => r.object === filter.object);
if (filter.activeOnly) rules = rules.filter((r) => r.active);
if (filter.name !== undefined) rules = rules.filter((r) => r.name === filter.name);
const scopes = this.declaredScopesFor(context);
if (rules.length === 0 || scopes.length === 0) return [];
// [ADR-0131 D6 regime C] A declared rule the activation ledger switches off
// is served nowhere: the row is deployment-level, so it covers every scope.
const off = await this.readSwitchedOffDeclaredRules();
if (off.size > 0) rules = rules.filter((r) => !off.has(r.name));
if (rules.length === 0) return [];
const single = this.declaredScopes?.includes(DEPLOYMENT_WIDE_SCOPE) === true;
const holders = await this.engine.find('sys_sharing_rule', {
where: { name: { $in: rules.map((r) => r.name) } },
fields: ['name', 'organization_id'],
limit: 100000,
context: SYSTEM_CTX,
});
const held = new Set<string>();
for (const row of (Array.isArray(holders) ? holders : []) as any[]) {
held.add(single ? String(row.name) : `${String(row.name)}::${String(row.organization_id)}`);
}
const out: SharingRuleRow[] = [];
for (const scope of scopes) {
for (const rule of rules) {
if (held.has(single ? rule.name : `${rule.name}::${String(scope)}`)) {
this.reportDeclarationOverAuthoredRow(rule, scope);
continue;
}
out.push(projectDeclaredRule(rule, scope));
}
}
return out;
}
/**
* [ADR-0131 D6 regime C] A declaration whose name a `sys_sharing_rule` row
* already holds in a scope — a package upgrade that ships a rule an
* organization authored under the same name, or a copy customised before
* same-name shadowing was retired. The row is never made an overlay of the
* declaration: it is that organization's own rule and answers as itself. The
* declaration is NOT served in that scope beside it — serving both would
* re-grant what a customised copy switched off — and that is said loudly,
* once per name and scope per process, with the remedy.