@cullet/erp-core 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/KIT_CONTEXT.md +5 -3
  2. package/README.md +160 -0
  3. package/dist/abac/index.cjs +7 -0
  4. package/dist/abac/index.d.cts +2 -0
  5. package/dist/abac/index.d.ts +2 -0
  6. package/dist/abac/index.js +2 -0
  7. package/dist/app-error.cjs +193 -0
  8. package/dist/app-error.cjs.map +1 -0
  9. package/dist/app-error.js +170 -0
  10. package/dist/app-error.js.map +1 -0
  11. package/dist/application/index.cjs +2 -1
  12. package/dist/application/index.d.cts +2 -1
  13. package/dist/application/index.d.ts +2 -1
  14. package/dist/application/index.js +2 -1
  15. package/dist/authorization-error.cjs +157 -0
  16. package/dist/authorization-error.cjs.map +1 -0
  17. package/dist/authorization-error.d.cts +113 -0
  18. package/dist/authorization-error.d.ts +113 -0
  19. package/dist/authorization-error.js +152 -0
  20. package/dist/authorization-error.js.map +1 -0
  21. package/dist/authorizer.port.d.cts +130 -0
  22. package/dist/authorizer.port.d.ts +130 -0
  23. package/dist/composite-authorizer.d.cts +216 -0
  24. package/dist/composite-authorizer.d.ts +216 -0
  25. package/dist/condition-evaluator.cjs +565 -0
  26. package/dist/condition-evaluator.cjs.map +1 -0
  27. package/dist/condition-evaluator.js +536 -0
  28. package/dist/condition-evaluator.js.map +1 -0
  29. package/dist/{gate-types.d.ts → core-config.d.cts} +78 -77
  30. package/dist/{gate-types.d.cts → core-config.d.ts} +78 -77
  31. package/dist/domain/index.cjs +2 -1
  32. package/dist/domain/index.d.cts +2 -1
  33. package/dist/domain/index.d.ts +2 -1
  34. package/dist/domain/index.js +2 -1
  35. package/dist/domain-event-contracts.cjs +3 -2
  36. package/dist/domain-event-contracts.cjs.map +1 -1
  37. package/dist/domain-event-contracts.js +2 -1
  38. package/dist/domain-event-contracts.js.map +1 -1
  39. package/dist/entity.cjs +126 -0
  40. package/dist/entity.cjs.map +1 -0
  41. package/dist/entity.js +115 -0
  42. package/dist/entity.js.map +1 -0
  43. package/dist/errors/index.cjs +8 -6
  44. package/dist/errors/index.d.cts +2 -1
  45. package/dist/errors/index.d.ts +2 -1
  46. package/dist/errors/index.js +4 -2
  47. package/dist/gate-engine-registry.cjs +5 -4
  48. package/dist/gate-engine-registry.cjs.map +1 -1
  49. package/dist/gate-engine-registry.d.cts +3 -2
  50. package/dist/gate-engine-registry.d.ts +3 -2
  51. package/dist/gate-engine-registry.js +2 -1
  52. package/dist/gate-engine-registry.js.map +1 -1
  53. package/dist/gate-v1-payload.schema.cjs +0 -562
  54. package/dist/gate-v1-payload.schema.cjs.map +1 -1
  55. package/dist/gate-v1-payload.schema.js +1 -533
  56. package/dist/gate-v1-payload.schema.js.map +1 -1
  57. package/dist/index.cjs +34 -16
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/index.d.cts +19 -12
  60. package/dist/index.d.ts +19 -12
  61. package/dist/index.js +15 -9
  62. package/dist/index.js.map +1 -1
  63. package/dist/not-found-error.cjs +5 -5
  64. package/dist/not-found-error.cjs.map +1 -1
  65. package/dist/not-found-error.js +1 -1
  66. package/dist/outcome.d.cts +1 -83
  67. package/dist/outcome.d.ts +1 -83
  68. package/dist/parse-gate-payload.d.cts +2 -2
  69. package/dist/parse-gate-payload.d.ts +2 -2
  70. package/dist/path.d.cts +2 -2
  71. package/dist/path.d.ts +2 -2
  72. package/dist/policies/engines/index.d.cts +1 -1
  73. package/dist/policies/engines/index.d.ts +1 -1
  74. package/dist/policies/engines/v1/gate/index.cjs +5 -4
  75. package/dist/policies/engines/v1/gate/index.cjs.map +1 -1
  76. package/dist/policies/engines/v1/gate/index.d.cts +2 -2
  77. package/dist/policies/engines/v1/gate/index.d.ts +2 -2
  78. package/dist/policies/engines/v1/gate/index.js +2 -1
  79. package/dist/policies/engines/v1/gate/index.js.map +1 -1
  80. package/dist/policies/index.cjs +5 -5
  81. package/dist/policies/index.d.cts +3 -2
  82. package/dist/policies/index.d.ts +3 -2
  83. package/dist/policies/index.js +2 -2
  84. package/dist/policy-bridge.cjs +437 -0
  85. package/dist/policy-bridge.cjs.map +1 -0
  86. package/dist/policy-bridge.d.cts +185 -0
  87. package/dist/policy-bridge.d.ts +185 -0
  88. package/dist/policy-bridge.js +396 -0
  89. package/dist/policy-bridge.js.map +1 -0
  90. package/dist/policy-service.cjs +239 -239
  91. package/dist/policy-service.cjs.map +1 -1
  92. package/dist/policy-service.d.cts +2 -2
  93. package/dist/policy-service.d.ts +2 -2
  94. package/dist/policy-service.js +239 -239
  95. package/dist/policy-service.js.map +1 -1
  96. package/dist/rbac/index.cjs +9 -0
  97. package/dist/rbac/index.d.cts +3 -0
  98. package/dist/rbac/index.d.ts +3 -0
  99. package/dist/rbac/index.js +2 -0
  100. package/dist/requested-by.cjs +54 -0
  101. package/dist/requested-by.cjs.map +1 -0
  102. package/dist/requested-by.d.cts +25 -0
  103. package/dist/requested-by.d.ts +25 -0
  104. package/dist/requested-by.js +49 -0
  105. package/dist/requested-by.js.map +1 -0
  106. package/dist/result/index.d.cts +2 -1
  107. package/dist/result/index.d.ts +2 -1
  108. package/dist/result.d.cts +84 -0
  109. package/dist/result.d.ts +84 -0
  110. package/dist/rule.cjs +327 -0
  111. package/dist/rule.cjs.map +1 -0
  112. package/dist/rule.js +298 -0
  113. package/dist/rule.js.map +1 -0
  114. package/dist/temporal-use-case.cjs +1 -53
  115. package/dist/temporal-use-case.cjs.map +1 -1
  116. package/dist/temporal-use-case.d.cts +5 -27
  117. package/dist/temporal-use-case.d.ts +5 -27
  118. package/dist/temporal-use-case.js +2 -48
  119. package/dist/temporal-use-case.js.map +1 -1
  120. package/dist/unexpected-error.cjs +3 -192
  121. package/dist/unexpected-error.cjs.map +1 -1
  122. package/dist/unexpected-error.js +2 -167
  123. package/dist/unexpected-error.js.map +1 -1
  124. package/dist/uuid-identifier.d.cts +2 -85
  125. package/dist/uuid-identifier.d.ts +2 -85
  126. package/dist/validation-error.cjs +33 -166
  127. package/dist/validation-error.cjs.map +1 -1
  128. package/dist/validation-error.d.cts +2 -98
  129. package/dist/validation-error.d.ts +2 -98
  130. package/dist/validation-error.js +7 -134
  131. package/dist/validation-error.js.map +1 -1
  132. package/dist/value-object.cjs +0 -123
  133. package/dist/value-object.cjs.map +1 -1
  134. package/dist/value-object.d.cts +89 -0
  135. package/dist/value-object.d.ts +89 -0
  136. package/dist/value-object.js +1 -112
  137. package/dist/value-object.js.map +1 -1
  138. package/meta.json +18 -4
  139. package/package.json +27 -1
  140. package/src/abac/index.ts +1 -0
  141. package/src/core/abac/abac-request.ts +29 -0
  142. package/src/core/abac/attributes.ts +39 -0
  143. package/src/core/abac/authorizer.ts +108 -0
  144. package/src/core/abac/combining.ts +63 -0
  145. package/src/core/abac/composite-authorizer.ts +45 -0
  146. package/src/core/abac/domain/policy-set.ts +52 -0
  147. package/src/core/abac/domain/rule.ts +197 -0
  148. package/src/core/abac/index.ts +21 -0
  149. package/src/core/application/ports/abac-authorizer.port.ts +20 -0
  150. package/src/core/application/ports/authorizer.port.ts +22 -0
  151. package/src/core/errors/authorization-error.ts +26 -0
  152. package/src/core/errors/error-codes.ts +1 -0
  153. package/src/core/index.ts +7 -0
  154. package/src/core/rbac/access-request.ts +32 -0
  155. package/src/core/rbac/authorizer.ts +91 -0
  156. package/src/core/rbac/domain/grant.ts +96 -0
  157. package/src/core/rbac/domain/permission-set.ts +67 -0
  158. package/src/core/rbac/domain/permission.ts +119 -0
  159. package/src/core/rbac/domain/role.ts +101 -0
  160. package/src/core/rbac/domain/scope.ts +84 -0
  161. package/src/core/rbac/index.ts +15 -0
  162. package/src/core/rbac/policy-bridge.ts +44 -0
  163. package/src/examples/application/authorize-cancel-order-abac.example.ts +107 -0
  164. package/src/examples/application/authorize-cancel-order.example.ts +101 -0
  165. package/src/rbac/index.ts +1 -0
  166. package/src/version.ts +1 -1
@@ -0,0 +1,437 @@
1
+ const require_authorization_error = require("./authorization-error.cjs");
2
+ const require_validation_code = require("./validation-code.cjs");
3
+ const require_validation_field = require("./validation-field.cjs");
4
+ const require_validation_exception = require("./validation-exception.cjs");
5
+ const require_requested_by = require("./requested-by.cjs");
6
+ const require_value_object = require("./value-object.cjs");
7
+ const require_result = require("./result.cjs");
8
+ //#region src/core/rbac/authorizer.ts
9
+ const REQUIRED_FIELD = require_validation_field.ValidationField.of("required");
10
+ /**
11
+ * The pure RBAC decisor. Given an {@link AccessRequest} and the {@link Grant}s
12
+ * already loaded for the actor, it answers "may this actor do this?" with no
13
+ * I/O — no storage, no network, no clock — returning a {@link Result}. An
14
+ * authorization *decision* is never thrown, always a value, mirroring the
15
+ * "errors as values" contract of `UseCase`/`PolicyService`. Loading the grants
16
+ * is the consumer's job (behind an `AuthorizerPort` adapter); this class only
17
+ * decides.
18
+ *
19
+ * The one thing it *does* throw is {@link InvalidValueException} when the caller
20
+ * misuses the API by passing a wildcard `required` permission — that is a
21
+ * programming error surfaced loudly, not an authorization outcome.
22
+ */
23
+ var RbacAuthorizer = class {
24
+ /**
25
+ * Decides the request against the supplied grants. The checks run
26
+ * role → capability → scope so the denial reason is the most informative
27
+ * one available:
28
+ *
29
+ * 1. no grant for the actor → `missing_role`;
30
+ * 2. has grants but none grants the permission → `missing_capability`;
31
+ * 3. grants the permission but not in scope → `out_of_scope`;
32
+ * 4. otherwise → ALLOW (`Result.ok`).
33
+ *
34
+ * @throws {@link InvalidValueException} when `request.required` is a wildcard
35
+ * permission (only *granted* permissions may wildcard, never the *required*
36
+ * one).
37
+ */
38
+ authorize(request, grants) {
39
+ if (request.required.hasWildcard()) throw new require_validation_exception.InvalidValueException(REQUIRED_FIELD, require_validation_code.ValidationCode.INVALID_FORMAT, `AccessRequest.required must be a concrete permission, not a wildcard, got "${request.required.toPrimitive()}"`);
40
+ const required = {
41
+ capability: request.required.toPrimitive(),
42
+ scope: request.scope.toPrimitive()
43
+ };
44
+ const metadata = {
45
+ action: request.action,
46
+ resource: request.resource,
47
+ actor: { userId: request.actor.raw },
48
+ required
49
+ };
50
+ const actorGrants = grants.filter((grant) => grant.appliesTo(request.actor));
51
+ if (actorGrants.length === 0) return require_result.Result.err(require_authorization_error.AuthorizationError.missingRole(metadata));
52
+ const withPermission = actorGrants.filter((grant) => grant.role.grants(request.required));
53
+ if (withPermission.length === 0) return require_result.Result.err(require_authorization_error.AuthorizationError.missingCapability(metadata));
54
+ if (withPermission.filter((grant) => grant.scope.includes(request.scope)).length === 0) return require_result.Result.err(require_authorization_error.AuthorizationError.outOfScope(metadata));
55
+ return require_result.Result.ok(void 0);
56
+ }
57
+ };
58
+ //#endregion
59
+ //#region src/core/rbac/domain/permission.ts
60
+ const PERMISSION_FIELD = require_validation_field.ValidationField.of("permission");
61
+ const SEGMENT_PATTERN = /^(?:\*|[a-z0-9_-]+)$/u;
62
+ /**
63
+ * A `"<resource>:<action>"` capability such as `"orders:cancel"`, with a
64
+ * single-level wildcard. Either segment may be the whole-segment wildcard `*`
65
+ * (`"orders:*"`, `"*:cancel"`, `"*:*"`), which is what lets a broad grant cover
66
+ * a narrower requirement — see {@link implies}.
67
+ *
68
+ * A zod-free value object: it validates its own format on construction
69
+ * (throwing {@link InvalidValueException}) and is frozen thereafter. Build one
70
+ * through {@link of} (from a raw `"resource:action"` string) or {@link for}
71
+ * (from already-separated parts); the constructor is private.
72
+ */
73
+ var Permission = class Permission extends require_value_object.ValueObject {
74
+ constructor(props) {
75
+ super(props);
76
+ this.finalize();
77
+ }
78
+ /**
79
+ * Parses a `"resource:action"` string. Throws {@link InvalidValueException}
80
+ * when the string is blank, lacks exactly one `:`, or carries an invalid
81
+ * segment.
82
+ */
83
+ static of(raw) {
84
+ if (typeof raw !== "string" || raw.trim().length === 0) throw new require_validation_exception.InvalidValueException(PERMISSION_FIELD, require_validation_code.ValidationCode.BLANK, `permission must be a non-empty "resource:action" string, got "${raw}"`);
85
+ const parts = raw.split(":");
86
+ if (parts.length !== 2) throw new require_validation_exception.InvalidValueException(PERMISSION_FIELD, require_validation_code.ValidationCode.INVALID_FORMAT, `permission must have exactly one ":" separating resource and action, got "${raw}"`);
87
+ return Permission.for(parts[0], parts[1]);
88
+ }
89
+ /**
90
+ * Builds from already-separated `resource` and `action` parts. Each must be
91
+ * a valid segment (`[a-z0-9_-]+` or the whole-segment wildcard `*`).
92
+ */
93
+ static for(resource, action) {
94
+ Permission.assertSegment(resource, "resource");
95
+ Permission.assertSegment(action, "action");
96
+ return new Permission({
97
+ resource,
98
+ action
99
+ });
100
+ }
101
+ static assertSegment(value, label) {
102
+ if (typeof value !== "string" || !SEGMENT_PATTERN.test(value)) throw new require_validation_exception.InvalidValueException(PERMISSION_FIELD.nested(label), require_validation_code.ValidationCode.INVALID_FORMAT, `permission ${label} must match [a-z0-9_-]+ or be the whole-segment wildcard "*" (no partial wildcards), got "${value}"`);
103
+ }
104
+ get resource() {
105
+ return this.value.resource;
106
+ }
107
+ get action() {
108
+ return this.value.action;
109
+ }
110
+ /**
111
+ * Whether holding this permission grants `other`. A `*` segment matches any
112
+ * value in the same position, so `"orders:*"` implies `"orders:cancel"` and
113
+ * `"*:*"` implies everything. Concrete segments must match exactly.
114
+ */
115
+ implies(other) {
116
+ return (this.resource === "*" || this.resource === other.resource) && (this.action === "*" || this.action === other.action);
117
+ }
118
+ /**
119
+ * Whether either segment is the whole-segment wildcard `*`. A *granted*
120
+ * permission may wildcard (see {@link implies}); a *required* one may not —
121
+ * `RbacAuthorizer` rejects a wildcard requirement as caller misuse.
122
+ */
123
+ hasWildcard() {
124
+ return this.value.resource === "*" || this.value.action === "*";
125
+ }
126
+ toPrimitive() {
127
+ return `${this.value.resource}:${this.value.action}`;
128
+ }
129
+ };
130
+ //#endregion
131
+ //#region src/core/rbac/domain/role.ts
132
+ const ROLE_FIELD = require_validation_field.ValidationField.of("role");
133
+ /**
134
+ * A named bundle of {@link Permission}s — `"cashier"`, `"manager"`, `"admin"`.
135
+ * There is **no role hierarchy** in v1: a role grants exactly the permissions
136
+ * it lists (wildcards included). Duplicate permissions are collapsed on
137
+ * construction, preserving first-seen order.
138
+ *
139
+ * A zod-free value object. Build through {@link of}; reconstruct a serialized
140
+ * one through {@link fromProps}.
141
+ */
142
+ var Role = class Role extends require_value_object.ValueObject {
143
+ constructor(props) {
144
+ super(props);
145
+ this._permissions = this.value.permissions.map(Permission.of);
146
+ this.finalize();
147
+ }
148
+ /**
149
+ * Builds a role from a name and its permissions. Throws
150
+ * {@link InvalidValueException} when the name is blank. Duplicate
151
+ * permissions are deduplicated.
152
+ */
153
+ static of(name, permissions) {
154
+ if (typeof name !== "string" || name.trim().length === 0) throw new require_validation_exception.InvalidValueException(ROLE_FIELD, require_validation_code.ValidationCode.BLANK, `role name must be a non-empty string, got "${name}"`);
155
+ const seen = /* @__PURE__ */ new Set();
156
+ const deduped = [];
157
+ for (const permission of permissions) {
158
+ const primitive = permission.toPrimitive();
159
+ if (seen.has(primitive)) continue;
160
+ seen.add(primitive);
161
+ deduped.push(primitive);
162
+ }
163
+ return new Role({
164
+ name,
165
+ permissions: deduped
166
+ });
167
+ }
168
+ /**
169
+ * Rebuilds a role from its serialized {@link RoleProps} — the inverse of
170
+ * {@link toPrimitive}. Each stored string is re-parsed through
171
+ * {@link Permission.of}, so a malformed payload still fails loudly.
172
+ */
173
+ static fromProps(props) {
174
+ return Role.of(props.name, props.permissions.map(Permission.of));
175
+ }
176
+ get name() {
177
+ return this.value.name;
178
+ }
179
+ /** The role's permissions, rehydrated from their stored primitive form. */
180
+ get permissions() {
181
+ return this._permissions;
182
+ }
183
+ /** Whether any permission in this role {@link Permission.implies | implies} `required`. */
184
+ grants(required) {
185
+ return this._permissions.some((permission) => permission.implies(required));
186
+ }
187
+ toPrimitive() {
188
+ return {
189
+ name: this.value.name,
190
+ permissions: [...this.value.permissions]
191
+ };
192
+ }
193
+ };
194
+ //#endregion
195
+ //#region src/core/rbac/domain/scope.ts
196
+ const SCOPE_FIELD = require_validation_field.ValidationField.of("scope");
197
+ const SCOPE_PATTERN = /^[a-z][a-z0-9_-]*:[A-Za-z0-9._-]+$/u;
198
+ /**
199
+ * Where a grant (or a target resource) lives, aligned with
200
+ * `AuthorizationRequirement.scope` and the policy `PolicyScope`
201
+ * (`tenantId`/`schoolId`): `"tenant:{id}"`, `"school:{id}"`, or the global
202
+ * `"*"`.
203
+ *
204
+ * v1 keeps containment ({@link includes}) flat — the global scope contains
205
+ * everything, and any other scope contains only itself. A real hierarchy
206
+ * (`tenant` ⊇ `school`) is a deliberately deferred extension point.
207
+ */
208
+ var Scope = class Scope extends require_value_object.ValueObject {
209
+ constructor(props) {
210
+ super(props);
211
+ this.finalize();
212
+ }
213
+ /** Validates `"type:id"` or the global `"*"`, throwing on anything else. */
214
+ static of(raw) {
215
+ if (typeof raw !== "string" || raw.trim().length === 0) throw new require_validation_exception.InvalidValueException(SCOPE_FIELD, require_validation_code.ValidationCode.BLANK, `scope must be a non-empty "type:id" string or "*", got "${raw}"`);
216
+ if (raw !== "*" && !SCOPE_PATTERN.test(raw)) throw new require_validation_exception.InvalidValueException(SCOPE_FIELD, require_validation_code.ValidationCode.INVALID_FORMAT, `scope must be "type:id" (e.g. "school:42") or the global "*", got "${raw}"`);
217
+ return new Scope({ raw });
218
+ }
219
+ /** The global scope `"*"`, which {@link includes} every other scope. */
220
+ static global() {
221
+ return new Scope({ raw: "*" });
222
+ }
223
+ /** The type segment, or `"*"` for the global scope. */
224
+ get type() {
225
+ if (this.value.raw === "*") return "*";
226
+ return this.value.raw.slice(0, this.value.raw.indexOf(":"));
227
+ }
228
+ /** The id segment, or `undefined` for the global scope. */
229
+ get id() {
230
+ if (this.value.raw === "*") return void 0;
231
+ return this.value.raw.slice(this.value.raw.indexOf(":") + 1);
232
+ }
233
+ /**
234
+ * Whether this scope contains `target`. The global scope contains
235
+ * everything; any other scope contains only an exact match of itself.
236
+ */
237
+ includes(target) {
238
+ if (this.value.raw === "*") return true;
239
+ return this.value.raw === target.value.raw;
240
+ }
241
+ toPrimitive() {
242
+ return this.value.raw;
243
+ }
244
+ };
245
+ //#endregion
246
+ //#region src/core/rbac/domain/grant.ts
247
+ /**
248
+ * A role binding — it ties one actor to one {@link Role} within one
249
+ * {@link Scope}. This is the unit the consumer stores (a `(subject, role,
250
+ * scope)` row) and rehydrates into the pure decisor; the kit itself persists
251
+ * nothing.
252
+ *
253
+ * A zod-free value object built through {@link of} from live
254
+ * `RequestedBy`/`Role`/`Scope` objects; the getters reconstruct those objects
255
+ * back from the frozen primitive form.
256
+ */
257
+ var Grant = class Grant extends require_value_object.ValueObject {
258
+ constructor(props) {
259
+ super(props);
260
+ this._subject = require_requested_by.RequestedBy.parse(this.value.subject);
261
+ this._role = Role.fromProps(this.value.role);
262
+ this._scope = Scope.of(this.value.scope);
263
+ this.finalize();
264
+ }
265
+ static of(params) {
266
+ return new Grant({
267
+ subject: params.subject.raw,
268
+ role: params.role.toPrimitive(),
269
+ scope: params.scope.toPrimitive()
270
+ });
271
+ }
272
+ /**
273
+ * Rebuilds a grant from its serialized {@link GrantProps} — the inverse of
274
+ * {@link toPrimitive}, symmetric to {@link Role.fromProps}. Each part is
275
+ * re-validated (subject through {@link RequestedBy.parse}, role through
276
+ * {@link Role.fromProps}, scope through {@link Scope.of}), so a malformed
277
+ * payload still fails loudly.
278
+ */
279
+ static fromProps(props) {
280
+ return new Grant(props);
281
+ }
282
+ get subject() {
283
+ return this._subject;
284
+ }
285
+ get role() {
286
+ return this._role;
287
+ }
288
+ get scope() {
289
+ return this._scope;
290
+ }
291
+ /** Whether this grant belongs to `actor`. */
292
+ appliesTo(actor) {
293
+ return this.value.subject === actor.raw;
294
+ }
295
+ toPrimitive() {
296
+ return {
297
+ subject: this.value.subject,
298
+ role: {
299
+ name: this.value.role.name,
300
+ permissions: [...this.value.role.permissions]
301
+ },
302
+ scope: this.value.scope
303
+ };
304
+ }
305
+ };
306
+ //#endregion
307
+ //#region src/core/rbac/domain/permission-set.ts
308
+ /**
309
+ * The flattened, deduplicated permissions an actor effectively holds across a
310
+ * set of {@link Grant}s, together with the role names that contributed them.
311
+ *
312
+ * Pure resolution, isolated from the decisor so the "roles → permissions"
313
+ * collapse can be tested on its own. Build through {@link fromGrants}; pre-filter
314
+ * the grants to a single actor first when that matters (the set does not know
315
+ * which actor it describes).
316
+ */
317
+ var PermissionSet = class PermissionSet {
318
+ constructor(permissions, _roleNames) {
319
+ this.permissions = permissions;
320
+ this._roleNames = _roleNames;
321
+ }
322
+ /**
323
+ * Collapses the roles across `grants` into one permission set. Permissions
324
+ * are deduplicated by their primitive form and role names by value, both
325
+ * preserving first-seen order.
326
+ */
327
+ static fromGrants(grants) {
328
+ const permissions = [];
329
+ const seenPermissions = /* @__PURE__ */ new Set();
330
+ const roleNames = [];
331
+ const seenRoles = /* @__PURE__ */ new Set();
332
+ for (const grant of grants) {
333
+ const role = grant.role;
334
+ if (!seenRoles.has(role.name)) {
335
+ seenRoles.add(role.name);
336
+ roleNames.push(role.name);
337
+ }
338
+ for (const permission of role.permissions) {
339
+ const primitive = permission.toPrimitive();
340
+ if (seenPermissions.has(primitive)) continue;
341
+ seenPermissions.add(primitive);
342
+ permissions.push(permission);
343
+ }
344
+ }
345
+ return new PermissionSet(permissions, roleNames);
346
+ }
347
+ /** Whether any held permission {@link Permission.implies | implies} `required`. */
348
+ has(required) {
349
+ return this.permissions.some((permission) => permission.implies(required));
350
+ }
351
+ /** The effective permissions, deduplicated. */
352
+ toArray() {
353
+ return this.permissions;
354
+ }
355
+ /** The names of the roles that contributed to this set, deduplicated. */
356
+ get roleNames() {
357
+ return this._roleNames;
358
+ }
359
+ };
360
+ //#endregion
361
+ //#region src/core/rbac/policy-bridge.ts
362
+ /**
363
+ * Projects an actor's RBAC facts into flat {@link PolicyContext}-style fields so
364
+ * a declarative gate policy can reason over them (ABAC) — without importing the
365
+ * policy engine or `zod`. It only builds a plain object; the consumer merges it
366
+ * into `seed.fields` of `PolicyService.evaluate(...)`.
367
+ *
368
+ * The grants are filtered to `actor` first, so passing an actor's full grant
369
+ * list (or a mixed one) is safe.
370
+ *
371
+ * **Wildcards are projected literally — they are NOT expanded.** `actor.roles`
372
+ * and `actor.permissions` are the exact stored strings, so a permission such as
373
+ * `"orders:*"` or `"*:*"` appears verbatim. A gate condition like
374
+ * `{ field: "actor.permissions", op: "in", value: "orders:cancel" }` does a
375
+ * *literal* membership test and will therefore NOT match a holder of
376
+ * `"orders:*"`. Open-ended wildcards cannot be enumerated into a finite list, so
377
+ * for wildcard-aware checks either match on the finite `actor.roles` instead, or
378
+ * make the wildcard-aware decision with `RbacAuthorizer` (which knows
379
+ * {@link Permission.implies}) and use the gate only for the extra ABAC
380
+ * conditions.
381
+ *
382
+ * @returns `{ "actor.id", "actor.roles", "actor.permissions" }`, where roles and
383
+ * permissions are plain string arrays (wildcards left literal).
384
+ */
385
+ function rbacContextFields(actor, grants) {
386
+ const set = PermissionSet.fromGrants(grants.filter((grant) => grant.appliesTo(actor)));
387
+ return {
388
+ "actor.id": actor.raw,
389
+ "actor.roles": [...set.roleNames],
390
+ "actor.permissions": set.toArray().map((permission) => permission.toPrimitive())
391
+ };
392
+ }
393
+ //#endregion
394
+ Object.defineProperty(exports, "Grant", {
395
+ enumerable: true,
396
+ get: function() {
397
+ return Grant;
398
+ }
399
+ });
400
+ Object.defineProperty(exports, "Permission", {
401
+ enumerable: true,
402
+ get: function() {
403
+ return Permission;
404
+ }
405
+ });
406
+ Object.defineProperty(exports, "PermissionSet", {
407
+ enumerable: true,
408
+ get: function() {
409
+ return PermissionSet;
410
+ }
411
+ });
412
+ Object.defineProperty(exports, "RbacAuthorizer", {
413
+ enumerable: true,
414
+ get: function() {
415
+ return RbacAuthorizer;
416
+ }
417
+ });
418
+ Object.defineProperty(exports, "Role", {
419
+ enumerable: true,
420
+ get: function() {
421
+ return Role;
422
+ }
423
+ });
424
+ Object.defineProperty(exports, "Scope", {
425
+ enumerable: true,
426
+ get: function() {
427
+ return Scope;
428
+ }
429
+ });
430
+ Object.defineProperty(exports, "rbacContextFields", {
431
+ enumerable: true,
432
+ get: function() {
433
+ return rbacContextFields;
434
+ }
435
+ });
436
+
437
+ //# sourceMappingURL=policy-bridge.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy-bridge.cjs","names":["ValidationField","InvalidValueException","ValidationCode","Result","AuthorizationError","ValidationField","ValueObject","InvalidValueException","ValidationCode","ValidationField","ValueObject","InvalidValueException","ValidationCode","ValidationField","ValueObject","InvalidValueException","ValidationCode","ValueObject","RequestedBy"],"sources":["../src/core/rbac/authorizer.ts","../src/core/rbac/domain/permission.ts","../src/core/rbac/domain/role.ts","../src/core/rbac/domain/scope.ts","../src/core/rbac/domain/grant.ts","../src/core/rbac/domain/permission-set.ts","../src/core/rbac/policy-bridge.ts"],"sourcesContent":["import {\n AuthorizationError,\n type AuthorizationRequirement,\n} from \"../errors/authorization-error.js\";\nimport { ValidationCode } from \"../exceptions/validation-code.js\";\nimport { InvalidValueException } from \"../exceptions/validation-exception.js\";\nimport { ValidationField } from \"../exceptions/validation-field.js\";\nimport { Result } from \"../result/result.js\";\n\nimport type { AccessRequest } from \"./access-request.js\";\nimport type { Grant } from \"./domain/grant.js\";\n\nconst REQUIRED_FIELD = ValidationField.of(\"required\");\n\n/**\n * The pure RBAC decisor. Given an {@link AccessRequest} and the {@link Grant}s\n * already loaded for the actor, it answers \"may this actor do this?\" with no\n * I/O — no storage, no network, no clock — returning a {@link Result}. An\n * authorization *decision* is never thrown, always a value, mirroring the\n * \"errors as values\" contract of `UseCase`/`PolicyService`. Loading the grants\n * is the consumer's job (behind an `AuthorizerPort` adapter); this class only\n * decides.\n *\n * The one thing it *does* throw is {@link InvalidValueException} when the caller\n * misuses the API by passing a wildcard `required` permission — that is a\n * programming error surfaced loudly, not an authorization outcome.\n */\nclass RbacAuthorizer {\n /**\n * Decides the request against the supplied grants. The checks run\n * role → capability → scope so the denial reason is the most informative\n * one available:\n *\n * 1. no grant for the actor → `missing_role`;\n * 2. has grants but none grants the permission → `missing_capability`;\n * 3. grants the permission but not in scope → `out_of_scope`;\n * 4. otherwise → ALLOW (`Result.ok`).\n *\n * @throws {@link InvalidValueException} when `request.required` is a wildcard\n * permission (only *granted* permissions may wildcard, never the *required*\n * one).\n */\n authorize(\n request: AccessRequest,\n grants: readonly Grant[],\n ): Result<void, AuthorizationError> {\n if (request.required.hasWildcard()) {\n throw new InvalidValueException(\n REQUIRED_FIELD,\n ValidationCode.INVALID_FORMAT,\n `AccessRequest.required must be a concrete permission, not a wildcard, got \"${request.required.toPrimitive()}\"`,\n );\n }\n\n const required: AuthorizationRequirement = {\n capability: request.required.toPrimitive(),\n scope: request.scope.toPrimitive(),\n };\n const metadata = {\n action: request.action,\n resource: request.resource,\n actor: { userId: request.actor.raw },\n required,\n };\n\n const actorGrants = grants.filter((grant) =>\n grant.appliesTo(request.actor),\n );\n if (actorGrants.length === 0) {\n return Result.err(AuthorizationError.missingRole(metadata));\n }\n\n const withPermission = actorGrants.filter((grant) =>\n grant.role.grants(request.required),\n );\n if (withPermission.length === 0) {\n return Result.err(AuthorizationError.missingCapability(metadata));\n }\n\n const inScope = withPermission.filter((grant) =>\n grant.scope.includes(request.scope),\n );\n if (inScope.length === 0) {\n return Result.err(AuthorizationError.outOfScope(metadata));\n }\n\n return Result.ok(undefined);\n }\n}\n\nexport { RbacAuthorizer };\n","import { ValidationCode } from \"../../exceptions/validation-code.js\";\nimport { InvalidValueException } from \"../../exceptions/validation-exception.js\";\nimport { ValidationField } from \"../../exceptions/validation-field.js\";\nimport { ValueObject } from \"../../domain/value-object.js\";\n\n/** The two halves of a permission: what is acted on, and what is done to it. */\ntype PermissionProps = {\n readonly resource: string;\n readonly action: string;\n};\n\nconst PERMISSION_FIELD = ValidationField.of(\"permission\");\n\n// A segment is either a whole-segment wildcard (`*`) or a run of lowercase\n// alphanumerics, hyphens and underscores. Partial wildcards (`ord*`) are\n// rejected on purpose: a `*` only ever stands for an entire segment.\nconst SEGMENT_PATTERN = /^(?:\\*|[a-z0-9_-]+)$/u;\n\n/**\n * A `\"<resource>:<action>\"` capability such as `\"orders:cancel\"`, with a\n * single-level wildcard. Either segment may be the whole-segment wildcard `*`\n * (`\"orders:*\"`, `\"*:cancel\"`, `\"*:*\"`), which is what lets a broad grant cover\n * a narrower requirement — see {@link implies}.\n *\n * A zod-free value object: it validates its own format on construction\n * (throwing {@link InvalidValueException}) and is frozen thereafter. Build one\n * through {@link of} (from a raw `\"resource:action\"` string) or {@link for}\n * (from already-separated parts); the constructor is private.\n */\nclass Permission extends ValueObject<PermissionProps, string> {\n private constructor(props: PermissionProps) {\n super(props);\n this.finalize();\n }\n\n /**\n * Parses a `\"resource:action\"` string. Throws {@link InvalidValueException}\n * when the string is blank, lacks exactly one `:`, or carries an invalid\n * segment.\n */\n static of(raw: string): Permission {\n if (typeof raw !== \"string\" || raw.trim().length === 0) {\n throw new InvalidValueException(\n PERMISSION_FIELD,\n ValidationCode.BLANK,\n `permission must be a non-empty \"resource:action\" string, got \"${raw}\"`,\n );\n }\n\n const parts = raw.split(\":\");\n if (parts.length !== 2) {\n throw new InvalidValueException(\n PERMISSION_FIELD,\n ValidationCode.INVALID_FORMAT,\n `permission must have exactly one \":\" separating resource and action, got \"${raw}\"`,\n );\n }\n\n return Permission.for(parts[0], parts[1]);\n }\n\n /**\n * Builds from already-separated `resource` and `action` parts. Each must be\n * a valid segment (`[a-z0-9_-]+` or the whole-segment wildcard `*`).\n */\n static for(resource: string, action: string): Permission {\n Permission.assertSegment(resource, \"resource\");\n Permission.assertSegment(action, \"action\");\n return new Permission({ resource, action });\n }\n\n private static assertSegment(\n value: string,\n label: \"resource\" | \"action\",\n ): void {\n if (typeof value !== \"string\" || !SEGMENT_PATTERN.test(value)) {\n throw new InvalidValueException(\n PERMISSION_FIELD.nested(label),\n ValidationCode.INVALID_FORMAT,\n `permission ${label} must match [a-z0-9_-]+ or be the whole-segment wildcard \"*\" (no partial wildcards), got \"${value}\"`,\n );\n }\n }\n\n get resource(): string {\n return this.value.resource;\n }\n\n get action(): string {\n return this.value.action;\n }\n\n /**\n * Whether holding this permission grants `other`. A `*` segment matches any\n * value in the same position, so `\"orders:*\"` implies `\"orders:cancel\"` and\n * `\"*:*\"` implies everything. Concrete segments must match exactly.\n */\n implies(other: Permission): boolean {\n return (\n (this.resource === \"*\" || this.resource === other.resource) &&\n (this.action === \"*\" || this.action === other.action)\n );\n }\n\n /**\n * Whether either segment is the whole-segment wildcard `*`. A *granted*\n * permission may wildcard (see {@link implies}); a *required* one may not —\n * `RbacAuthorizer` rejects a wildcard requirement as caller misuse.\n */\n hasWildcard(): boolean {\n return this.value.resource === \"*\" || this.value.action === \"*\";\n }\n\n toPrimitive(): string {\n return `${this.value.resource}:${this.value.action}`;\n }\n}\n\nexport { Permission, type PermissionProps };\n","import { ValidationCode } from \"../../exceptions/validation-code.js\";\nimport { InvalidValueException } from \"../../exceptions/validation-exception.js\";\nimport { ValidationField } from \"../../exceptions/validation-field.js\";\nimport { ValueObject } from \"../../domain/value-object.js\";\n\nimport { Permission } from \"./permission.js\";\n\n/**\n * The serializable shape of a role: a name plus its permissions kept as their\n * primitive `\"resource:action\"` strings (so the role round-trips through JSON\n * and stays deep-frozen). The {@link Role.permissions} getter rehydrates them\n * back into {@link Permission} objects.\n */\ntype RoleProps = {\n readonly name: string;\n readonly permissions: readonly string[];\n};\n\nconst ROLE_FIELD = ValidationField.of(\"role\");\n\n/**\n * A named bundle of {@link Permission}s — `\"cashier\"`, `\"manager\"`, `\"admin\"`.\n * There is **no role hierarchy** in v1: a role grants exactly the permissions\n * it lists (wildcards included). Duplicate permissions are collapsed on\n * construction, preserving first-seen order.\n *\n * A zod-free value object. Build through {@link of}; reconstruct a serialized\n * one through {@link fromProps}.\n */\nclass Role extends ValueObject<RoleProps, RoleProps> {\n // Parsed once, at construction, and cached: the decisor calls `grants` (and\n // `PermissionSet` reads `permissions`) repeatedly, so re-parsing the stored\n // strings on every access would be wasted work.\n private readonly _permissions: readonly Permission[];\n\n private constructor(props: RoleProps) {\n super(props);\n this._permissions = this.value.permissions.map(Permission.of);\n this.finalize();\n }\n\n /**\n * Builds a role from a name and its permissions. Throws\n * {@link InvalidValueException} when the name is blank. Duplicate\n * permissions are deduplicated.\n */\n static of(name: string, permissions: readonly Permission[]): Role {\n if (typeof name !== \"string\" || name.trim().length === 0) {\n throw new InvalidValueException(\n ROLE_FIELD,\n ValidationCode.BLANK,\n `role name must be a non-empty string, got \"${name}\"`,\n );\n }\n\n const seen = new Set<string>();\n const deduped: string[] = [];\n for (const permission of permissions) {\n const primitive = permission.toPrimitive();\n if (seen.has(primitive)) continue;\n seen.add(primitive);\n deduped.push(primitive);\n }\n\n return new Role({ name, permissions: deduped });\n }\n\n /**\n * Rebuilds a role from its serialized {@link RoleProps} — the inverse of\n * {@link toPrimitive}. Each stored string is re-parsed through\n * {@link Permission.of}, so a malformed payload still fails loudly.\n */\n static fromProps(props: RoleProps): Role {\n return Role.of(props.name, props.permissions.map(Permission.of));\n }\n\n get name(): string {\n return this.value.name;\n }\n\n /** The role's permissions, rehydrated from their stored primitive form. */\n get permissions(): readonly Permission[] {\n return this._permissions;\n }\n\n /** Whether any permission in this role {@link Permission.implies | implies} `required`. */\n grants(required: Permission): boolean {\n return this._permissions.some((permission) =>\n permission.implies(required),\n );\n }\n\n toPrimitive(): RoleProps {\n return {\n name: this.value.name,\n permissions: [...this.value.permissions],\n };\n }\n}\n\nexport { Role, type RoleProps };\n","import { ValidationCode } from \"../../exceptions/validation-code.js\";\nimport { InvalidValueException } from \"../../exceptions/validation-exception.js\";\nimport { ValidationField } from \"../../exceptions/validation-field.js\";\nimport { ValueObject } from \"../../domain/value-object.js\";\n\n/** The wrapped, already-validated scope string (`\"type:id\"` or `\"*\"`). */\ntype ScopeProps = { readonly raw: string };\n\nconst SCOPE_FIELD = ValidationField.of(\"scope\");\n\n// \"type:id\": a lowercase type segment, a colon, then a non-empty id. The id\n// charset is permissive enough for UUIDs and numeric keys (`school:42`,\n// `tenant:550e8400-e29b-41d4-a716-446655440000`).\nconst SCOPE_PATTERN = /^[a-z][a-z0-9_-]*:[A-Za-z0-9._-]+$/u;\n\n/**\n * Where a grant (or a target resource) lives, aligned with\n * `AuthorizationRequirement.scope` and the policy `PolicyScope`\n * (`tenantId`/`schoolId`): `\"tenant:{id}\"`, `\"school:{id}\"`, or the global\n * `\"*\"`.\n *\n * v1 keeps containment ({@link includes}) flat — the global scope contains\n * everything, and any other scope contains only itself. A real hierarchy\n * (`tenant` ⊇ `school`) is a deliberately deferred extension point.\n */\nclass Scope extends ValueObject<ScopeProps, string> {\n private constructor(props: ScopeProps) {\n super(props);\n this.finalize();\n }\n\n /** Validates `\"type:id\"` or the global `\"*\"`, throwing on anything else. */\n static of(raw: string): Scope {\n if (typeof raw !== \"string\" || raw.trim().length === 0) {\n throw new InvalidValueException(\n SCOPE_FIELD,\n ValidationCode.BLANK,\n `scope must be a non-empty \"type:id\" string or \"*\", got \"${raw}\"`,\n );\n }\n\n if (raw !== \"*\" && !SCOPE_PATTERN.test(raw)) {\n throw new InvalidValueException(\n SCOPE_FIELD,\n ValidationCode.INVALID_FORMAT,\n `scope must be \"type:id\" (e.g. \"school:42\") or the global \"*\", got \"${raw}\"`,\n );\n }\n\n return new Scope({ raw });\n }\n\n /** The global scope `\"*\"`, which {@link includes} every other scope. */\n static global(): Scope {\n return new Scope({ raw: \"*\" });\n }\n\n /** The type segment, or `\"*\"` for the global scope. */\n get type(): string {\n if (this.value.raw === \"*\") return \"*\";\n return this.value.raw.slice(0, this.value.raw.indexOf(\":\"));\n }\n\n /** The id segment, or `undefined` for the global scope. */\n get id(): string | undefined {\n if (this.value.raw === \"*\") return undefined;\n return this.value.raw.slice(this.value.raw.indexOf(\":\") + 1);\n }\n\n /**\n * Whether this scope contains `target`. The global scope contains\n * everything; any other scope contains only an exact match of itself.\n */\n includes(target: Scope): boolean {\n if (this.value.raw === \"*\") return true;\n return this.value.raw === target.value.raw;\n }\n\n toPrimitive(): string {\n return this.value.raw;\n }\n}\n\nexport { Scope, type ScopeProps };\n","import { RequestedBy } from \"../../application/commands/requested-by.js\";\nimport { ValueObject } from \"../../domain/value-object.js\";\n\nimport { Role, type RoleProps } from \"./role.js\";\nimport { Scope } from \"./scope.js\";\n\n/**\n * The serializable shape a consumer persists and loads: the actor's identity\n * (`RequestedBy.raw`), the role they hold (as {@link RoleProps}), and the scope\n * the role applies in (the {@link Scope} string).\n */\ntype GrantProps = {\n readonly subject: string;\n readonly role: RoleProps;\n readonly scope: string;\n};\n\n/**\n * A role binding — it ties one actor to one {@link Role} within one\n * {@link Scope}. This is the unit the consumer stores (a `(subject, role,\n * scope)` row) and rehydrates into the pure decisor; the kit itself persists\n * nothing.\n *\n * A zod-free value object built through {@link of} from live\n * `RequestedBy`/`Role`/`Scope` objects; the getters reconstruct those objects\n * back from the frozen primitive form.\n */\nclass Grant extends ValueObject<GrantProps, GrantProps> {\n // The live objects are rehydrated once, at construction, and cached — the\n // decisor reads `role`/`scope` at least once per grant, so parsing lazily on\n // each getter access would re-parse the same frozen primitives repeatedly.\n private readonly _subject: RequestedBy;\n private readonly _role: Role;\n private readonly _scope: Scope;\n\n private constructor(props: GrantProps) {\n super(props);\n this._subject = RequestedBy.parse(this.value.subject);\n this._role = Role.fromProps(this.value.role);\n this._scope = Scope.of(this.value.scope);\n this.finalize();\n }\n\n static of(params: {\n subject: RequestedBy;\n role: Role;\n scope: Scope;\n }): Grant {\n return new Grant({\n subject: params.subject.raw,\n role: params.role.toPrimitive(),\n scope: params.scope.toPrimitive(),\n });\n }\n\n /**\n * Rebuilds a grant from its serialized {@link GrantProps} — the inverse of\n * {@link toPrimitive}, symmetric to {@link Role.fromProps}. Each part is\n * re-validated (subject through {@link RequestedBy.parse}, role through\n * {@link Role.fromProps}, scope through {@link Scope.of}), so a malformed\n * payload still fails loudly.\n */\n static fromProps(props: GrantProps): Grant {\n return new Grant(props);\n }\n\n get subject(): RequestedBy {\n return this._subject;\n }\n\n get role(): Role {\n return this._role;\n }\n\n get scope(): Scope {\n return this._scope;\n }\n\n /** Whether this grant belongs to `actor`. */\n appliesTo(actor: RequestedBy): boolean {\n return this.value.subject === actor.raw;\n }\n\n toPrimitive(): GrantProps {\n return {\n subject: this.value.subject,\n role: {\n name: this.value.role.name,\n permissions: [...this.value.role.permissions],\n },\n scope: this.value.scope,\n };\n }\n}\n\nexport { Grant, type GrantProps };\n","import type { Grant } from \"./grant.js\";\nimport type { Permission } from \"./permission.js\";\n\n/**\n * The flattened, deduplicated permissions an actor effectively holds across a\n * set of {@link Grant}s, together with the role names that contributed them.\n *\n * Pure resolution, isolated from the decisor so the \"roles → permissions\"\n * collapse can be tested on its own. Build through {@link fromGrants}; pre-filter\n * the grants to a single actor first when that matters (the set does not know\n * which actor it describes).\n */\nclass PermissionSet {\n private constructor(\n private readonly permissions: readonly Permission[],\n private readonly _roleNames: readonly string[],\n ) {}\n\n /**\n * Collapses the roles across `grants` into one permission set. Permissions\n * are deduplicated by their primitive form and role names by value, both\n * preserving first-seen order.\n */\n static fromGrants(grants: readonly Grant[]): PermissionSet {\n const permissions: Permission[] = [];\n const seenPermissions = new Set<string>();\n const roleNames: string[] = [];\n const seenRoles = new Set<string>();\n\n for (const grant of grants) {\n const role = grant.role;\n\n if (!seenRoles.has(role.name)) {\n seenRoles.add(role.name);\n roleNames.push(role.name);\n }\n\n for (const permission of role.permissions) {\n const primitive = permission.toPrimitive();\n if (seenPermissions.has(primitive)) continue;\n seenPermissions.add(primitive);\n permissions.push(permission);\n }\n }\n\n return new PermissionSet(permissions, roleNames);\n }\n\n /** Whether any held permission {@link Permission.implies | implies} `required`. */\n has(required: Permission): boolean {\n return this.permissions.some((permission) =>\n permission.implies(required),\n );\n }\n\n /** The effective permissions, deduplicated. */\n toArray(): readonly Permission[] {\n return this.permissions;\n }\n\n /** The names of the roles that contributed to this set, deduplicated. */\n get roleNames(): readonly string[] {\n return this._roleNames;\n }\n}\n\nexport { PermissionSet };\n","import type { RequestedBy } from \"../application/commands/requested-by.js\";\n\nimport type { Grant } from \"./domain/grant.js\";\nimport { PermissionSet } from \"./domain/permission-set.js\";\n\n/**\n * Projects an actor's RBAC facts into flat {@link PolicyContext}-style fields so\n * a declarative gate policy can reason over them (ABAC) — without importing the\n * policy engine or `zod`. It only builds a plain object; the consumer merges it\n * into `seed.fields` of `PolicyService.evaluate(...)`.\n *\n * The grants are filtered to `actor` first, so passing an actor's full grant\n * list (or a mixed one) is safe.\n *\n * **Wildcards are projected literally — they are NOT expanded.** `actor.roles`\n * and `actor.permissions` are the exact stored strings, so a permission such as\n * `\"orders:*\"` or `\"*:*\"` appears verbatim. A gate condition like\n * `{ field: \"actor.permissions\", op: \"in\", value: \"orders:cancel\" }` does a\n * *literal* membership test and will therefore NOT match a holder of\n * `\"orders:*\"`. Open-ended wildcards cannot be enumerated into a finite list, so\n * for wildcard-aware checks either match on the finite `actor.roles` instead, or\n * make the wildcard-aware decision with `RbacAuthorizer` (which knows\n * {@link Permission.implies}) and use the gate only for the extra ABAC\n * conditions.\n *\n * @returns `{ \"actor.id\", \"actor.roles\", \"actor.permissions\" }`, where roles and\n * permissions are plain string arrays (wildcards left literal).\n */\nexport function rbacContextFields(\n actor: RequestedBy,\n grants: readonly Grant[],\n): Record<string, unknown> {\n const set = PermissionSet.fromGrants(\n grants.filter((grant) => grant.appliesTo(actor)),\n );\n\n return {\n \"actor.id\": actor.raw,\n \"actor.roles\": [...set.roleNames],\n \"actor.permissions\": set\n .toArray()\n .map((permission) => permission.toPrimitive()),\n };\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,iBAAiBA,yBAAAA,gBAAgB,GAAG,UAAU;;;;;;;;;;;;;;AAepD,IAAM,iBAAN,MAAqB;;;;;;;;;;;;;;;CAejB,UACI,SACA,QACgC;EAChC,IAAI,QAAQ,SAAS,YAAY,GAC7B,MAAM,IAAIC,6BAAAA,sBACN,gBACAC,wBAAAA,eAAe,gBACf,8EAA8E,QAAQ,SAAS,YAAY,EAAE,EACjH;EAGJ,MAAM,WAAqC;GACvC,YAAY,QAAQ,SAAS,YAAY;GACzC,OAAO,QAAQ,M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