@payload-kit/rbac 0.0.0-stage → 0.1.0-alpha.1

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.
package/dist/index.js ADDED
@@ -0,0 +1,770 @@
1
+ // src/access/combinators.ts
2
+ /**
3
+ Combines multiple access rules with logical OR.
4
+
5
+ Evaluation semantics:
6
+ 1. If any rule evaluates to `true` (unrestricted access), access is granted immediately (`true`).
7
+ 2. If any rules return `Where` query constraints (row-level security filters):
8
+ - If exactly one `Where` constraint exists, it is returned directly.
9
+ - If multiple `Where` constraints exist, they are merged via `{ or: [...] }`.
10
+ 3. If all rules evaluate to `false`, access is denied (`false`).
11
+
12
+ @param rules - One or more Payload Access rules to evaluate.
13
+ @returns A composite Payload Access rule.
14
+
15
+ @example
16
+ ```typescript
17
+ // Grant access if user has orders:read_all capability, OR only to their own orders:
18
+ access: {
19
+ read: or(
20
+ requireCapability('orders:read_all'),
21
+ ({ req: { user } }) => ({ 'customer.email': { equals: user?.email } })
22
+ ),
23
+ }
24
+ ```
25
+ */
26
+ function or(...rules) {
27
+ return async (arguments_) => {
28
+ if (rules.length === 0) return false;
29
+ const results = await Promise.all(rules.map(async (rule) => rule(arguments_)));
30
+ if (results.includes(true)) return true;
31
+ const whereClauses = [];
32
+ for (const resultItem of results) if (typeof resultItem === "object" && resultItem !== null) whereClauses.push(resultItem);
33
+ if (whereClauses.length === 0) return false;
34
+ if (whereClauses.length === 1) return whereClauses[0];
35
+ return { or: whereClauses };
36
+ };
37
+ }
38
+ /**
39
+ Combines multiple access rules with logical AND.
40
+
41
+ Evaluation semantics:
42
+ 1. If any rule evaluates to `false` (denial), access is denied immediately (`false`).
43
+ 2. If any rules return `Where` query constraints:
44
+ - If exactly one `Where` constraint exists, it is returned directly.
45
+ - If multiple `Where` constraints exist, they are merged via `{ and: [...] }`.
46
+ 3. If all rules evaluate to `true` (and no `Where` constraints are returned), access is granted (`true`).
47
+
48
+ @param rules - One or more Payload Access rules to evaluate.
49
+ @returns A composite Payload Access rule.
50
+
51
+ @example
52
+ ```typescript
53
+ // User must be authenticated AND have the capability to create:
54
+ access: {
55
+ create: and(
56
+ requireAuth(),
57
+ requireCapability('orders:create')
58
+ ),
59
+ }
60
+ ```
61
+ */
62
+ function and(...rules) {
63
+ return async (arguments_) => {
64
+ if (rules.length === 0) return true;
65
+ const results = await Promise.all(rules.map(async (rule) => rule(arguments_)));
66
+ if (results.includes(false)) return false;
67
+ const whereClauses = [];
68
+ for (const resultItem of results) if (typeof resultItem === "object" && resultItem !== null) whereClauses.push(resultItem);
69
+ if (whereClauses.length === 0) return true;
70
+ if (whereClauses.length === 1) return whereClauses[0];
71
+ return { and: whereClauses };
72
+ };
73
+ }
74
+ /**
75
+ Inverts the outcome of a boolean access rule.
76
+
77
+ Note: Negating a Payload `Where` query condition is not supported because database-level
78
+ inverted filters cannot be generically inferred without schema reflection. For `Where` filters,
79
+ specify explicit query constraints instead.
80
+
81
+ @param rule - A boolean-returning Payload Access rule.
82
+ @returns An inverted Payload Access rule.
83
+ @throws {TypeError} If the evaluated rule returns a Where query object instead of a boolean.
84
+
85
+ @example
86
+ ```typescript
87
+ access: {
88
+ delete: not(requireRole('customer')),
89
+ }
90
+ ```
91
+ */
92
+ function not(rule) {
93
+ return async (arguments_) => {
94
+ const result = await rule(arguments_);
95
+ if (typeof result === "boolean") return !result;
96
+ throw new TypeError("The 'not' combinator only supports boolean access rules and cannot invert a Payload 'Where' query.");
97
+ };
98
+ }
99
+ // src/access/field-combinators.ts
100
+ /**
101
+ Combines multiple field-level access rules with logical OR.
102
+
103
+ Evaluation semantics:
104
+ 1. If any rule evaluates to `true`, access to the field is granted (`true`).
105
+ 2. If all rules evaluate to `false`, access to the field is denied (`false`).
106
+ 3. If no rules are provided, fails closed by returning `false`.
107
+
108
+ @param rules - One or more FieldAccess rules to evaluate.
109
+ @returns A composite FieldAccess rule.
110
+
111
+ @example
112
+ ```typescript
113
+ {
114
+ name: 'contactPhone',
115
+ type: 'text',
116
+ access: {
117
+ read: fieldOr(
118
+ requireFieldCapability('users:read_sensitive'),
119
+ ({ req: { user }, doc }) => user?.id === doc?.id
120
+ ),
121
+ },
122
+ }
123
+ ```
124
+ */
125
+ function fieldOr(...rules) {
126
+ return async (arguments_) => {
127
+ if (rules.length === 0) return false;
128
+ return (await Promise.all(rules.map(async (rule) => rule(arguments_)))).includes(true);
129
+ };
130
+ }
131
+ /**
132
+ Combines multiple field-level access rules with logical AND.
133
+
134
+ Evaluation semantics:
135
+ 1. If any rule evaluates to `false`, access to the field is denied (`false`).
136
+ 2. If all rules evaluate to `true`, access to the field is granted (`true`).
137
+ 3. If no rules are provided, returns `true`.
138
+
139
+ @param rules - One or more FieldAccess rules to evaluate.
140
+ @returns A composite FieldAccess rule.
141
+
142
+ @example
143
+ ```typescript
144
+ {
145
+ name: 'billingAddress',
146
+ type: 'text',
147
+ access: {
148
+ update: fieldAnd(
149
+ requireFieldAuth(),
150
+ requireFieldCapability('orders:update')
151
+ ),
152
+ },
153
+ }
154
+ ```
155
+ */
156
+ function fieldAnd(...rules) {
157
+ return async (arguments_) => {
158
+ if (rules.length === 0) return true;
159
+ return !(await Promise.all(rules.map(async (rule) => rule(arguments_)))).includes(false);
160
+ };
161
+ }
162
+ /**
163
+ Inverts the outcome of a field-level access rule.
164
+
165
+ @param rule - A FieldAccess rule to invert.
166
+ @returns An inverted FieldAccess rule.
167
+
168
+ @example
169
+ ```typescript
170
+ {
171
+ name: 'guestToken',
172
+ type: 'text',
173
+ access: {
174
+ read: fieldNot(requireFieldRole('customer')),
175
+ },
176
+ }
177
+ ```
178
+ */
179
+ function fieldNot(rule) {
180
+ return async (arguments_) => {
181
+ return !await rule(arguments_);
182
+ };
183
+ }
184
+ // src/registry.ts
185
+ /**
186
+ Module-level storage holding the active RBAC configuration.
187
+ */
188
+ const rbacRegistryState = {};
189
+ /**
190
+ Registers an RBAC configuration into the active runtime context.
191
+
192
+ @param config - The RBAC configuration options to activate.
193
+ */
194
+ function registerRbacConfig(config) {
195
+ rbacRegistryState.activeConfig = config;
196
+ }
197
+ /**
198
+ Retrieves the currently registered RBAC configuration.
199
+
200
+ @returns The active configuration, or undefined if not yet configured.
201
+ */
202
+ function getRbacConfig() {
203
+ return rbacRegistryState.activeConfig;
204
+ }
205
+ /**
206
+ Clears the active RBAC configuration. Primarily utilized in test suites to prevent leaks.
207
+ */
208
+ function resetRbacConfig() {
209
+ rbacRegistryState.activeConfig = void 0;
210
+ }
211
+ // src/roles/checker.ts
212
+ /**
213
+ Extracts and normalizes the assigned roles of a user into an array of string identifiers.
214
+
215
+ @param user - The user object to inspect, or null/undefined.
216
+ @param rolesFieldName - Name of the field containing the role(s). Defaults to plugin config or `'role'`.
217
+ @returns An array of trimmed, non-empty role identifiers.
218
+
219
+ @example
220
+ ```typescript
221
+ resolveUserRoles({ role: 'admin' }); // ['admin']
222
+ resolveUserRoles({ roles: ['editor', 'operator'] }); // ['editor', 'operator']
223
+ resolveUserRoles(null); // []
224
+ ```
225
+ */
226
+ function resolveUserRoles(user, optionsOrFieldName) {
227
+ const options = typeof optionsOrFieldName === "object" ? optionsOrFieldName : void 0;
228
+ const fieldName = typeof optionsOrFieldName === "string" ? optionsOrFieldName : options?.rolesFieldName ?? getRbacConfig()?.rolesFieldName ?? "role";
229
+ if (!user || typeof user !== "object") {
230
+ const anonymousRole = options?.anonymousRole === void 0 ? getRbacConfig()?.anonymousRole : options.anonymousRole;
231
+ return anonymousRole ? [anonymousRole] : [];
232
+ }
233
+ const candidateArray = Array.isArray(user.roles) ? user.roles : Array.isArray(user[fieldName]) ? user[fieldName] : void 0;
234
+ if (candidateArray) return candidateArray.filter((role) => typeof role === "string" && role.trim().length > 0).map((role) => role.trim());
235
+ const singular = user[fieldName] ?? user.role;
236
+ return typeof singular === "string" && singular.trim().length > 0 ? [singular.trim()] : [];
237
+ }
238
+ /**
239
+ Verifies whether a user has been assigned a specific role.
240
+
241
+ @param user - The user to evaluate.
242
+ @param role - The expected role identifier.
243
+ @param options - Optional overrides for role extraction.
244
+ @returns True if the user has the specified role, false otherwise.
245
+
246
+ @example
247
+ ```typescript
248
+ if (hasRole(user, 'admin')) {
249
+ // Authorized for administrator role
250
+ }
251
+ ```
252
+ */
253
+ function hasRole(user, role, options) {
254
+ return resolveUserRoles(user, options).includes(role);
255
+ }
256
+ /**
257
+ Verifies whether a user has at least one of the specified roles.
258
+
259
+ @param user - The user to evaluate.
260
+ @param roles - The list of acceptable roles.
261
+ @param options - Optional overrides for role extraction.
262
+ @returns True if the user has at least one matching role, false otherwise.
263
+
264
+ @example
265
+ ```typescript
266
+ if (hasAnyRole(user, ['admin', 'manager'])) {
267
+ // Authorized for either admin or manager
268
+ }
269
+ ```
270
+ */
271
+ function hasAnyRole(user, roles, options) {
272
+ if (roles.length === 0) return false;
273
+ const userRoles = resolveUserRoles(user, options);
274
+ const userRolesSet = new Set(userRoles);
275
+ return roles.some((role) => userRolesSet.has(role));
276
+ }
277
+ /**
278
+ Verifies whether a user has all of the specified roles.
279
+
280
+ @param user - The user to evaluate.
281
+ @param roles - The list of required roles.
282
+ @param options - Optional overrides for role extraction.
283
+ @returns True if the user possesses every required role, false otherwise.
284
+
285
+ @example
286
+ ```typescript
287
+ if (hasAllRoles(user, ['verified', 'subscriber'])) {
288
+ // Authorized only if both roles are present
289
+ }
290
+ ```
291
+ */
292
+ function hasAllRoles(user, roles, options) {
293
+ if (roles.length === 0) return true;
294
+ const userRoles = resolveUserRoles(user, options);
295
+ const userRolesSet = new Set(userRoles);
296
+ return roles.every((role) => userRolesSet.has(role));
297
+ }
298
+ // src/capabilities/matcher.ts
299
+ /**
300
+ Evaluates whether a granted capability pattern satisfies a requested capability.
301
+
302
+ Supported pattern formats:
303
+ - `'*'`: Global wildcard, matches any requested capability.
304
+ - `'domain:*'`: Domain wildcard, matches any capability starting with `'domain:'` (e.g., `'orders:*'` matches `'orders:create'`).
305
+ - `'exact:match'`: Exact match against requested capability.
306
+
307
+ @param grantedPattern - The capability or wildcard pattern possessed by the role or user.
308
+ @param requestedCapability - The specific capability required for an operation.
309
+ @returns True if the pattern satisfies the requested capability, false otherwise.
310
+
311
+ @example
312
+ ```typescript
313
+ matchesCapability('*', 'orders:delete'); // true
314
+ matchesCapability('orders:*', 'orders:delete'); // true
315
+ matchesCapability('orders:read', 'orders:delete'); // false
316
+ ```
317
+ */
318
+ function doesMatchCapability(grantedPattern, requestedCapability) {
319
+ const pattern = grantedPattern.trim();
320
+ const requested = requestedCapability.trim();
321
+ if (pattern === "*" || pattern === requested) return true;
322
+ if (pattern.endsWith(":*")) {
323
+ const domainPrefix = pattern.slice(0, -1);
324
+ return requested.startsWith(domainPrefix);
325
+ }
326
+ return false;
327
+ }
328
+ // src/capabilities/resolver.ts
329
+ /**
330
+ Recursively resolves all granted capabilities for a specified role, including
331
+ capabilities inherited from ancestor roles. Employs cycle-detection to prevent infinite recursion.
332
+
333
+ @param role - The role identifier to resolve.
334
+ @param rolesConfig - The dictionary of defined roles and their capabilities.
335
+ @param visitedRoles - Internal set tracking visited roles during recursion to avoid cycles.
336
+ @returns A Set containing all unique capability patterns granted to this role.
337
+
338
+ @example
339
+ ```typescript
340
+ const caps = resolveRoleCapabilities('manager', rolesConfig);
341
+ ```
342
+ */
343
+ function resolveRoleCapabilities(role, rolesConfig, visitedRoles = /* @__PURE__ */ new Set()) {
344
+ const result = /* @__PURE__ */ new Set();
345
+ if (visitedRoles.has(role)) return result;
346
+ visitedRoles.add(role);
347
+ const definition = rolesConfig[role];
348
+ if (!definition) return result;
349
+ for (const capability of definition.capabilities) result.add(capability);
350
+ if (definition.inherits && Array.isArray(definition.inherits)) for (const parentRole of definition.inherits) {
351
+ const parentCapabilities = resolveRoleCapabilities(parentRole, rolesConfig, visitedRoles);
352
+ for (const cap of parentCapabilities) result.add(cap);
353
+ }
354
+ return result;
355
+ }
356
+ /**
357
+ Aggregates all granted capabilities for a user, combining capabilities from
358
+ all their assigned roles and any direct capabilities explicitly assigned to the user object.
359
+
360
+ @param user - The user whose capabilities should be resolved.
361
+ @param options - Configuration options containing role definitions and field mapping.
362
+ @returns A Set of all capabilities granted to the user.
363
+
364
+ @example
365
+ ```typescript
366
+ const caps = resolveUserCapabilities(user, { roles: rolesConfig });
367
+ ```
368
+ */
369
+ function resolveUserCapabilities(user, options) {
370
+ const result = /* @__PURE__ */ new Set();
371
+ const globalConfig = getRbacConfig();
372
+ const rolesConfig = options?.roles ?? globalConfig?.roles;
373
+ if (!user || typeof user !== "object") {
374
+ const anonymousRole = options?.anonymousRole === void 0 ? globalConfig?.anonymousRole : options.anonymousRole;
375
+ return anonymousRole && rolesConfig && Object.hasOwn(rolesConfig, anonymousRole) ? resolveRoleCapabilities(anonymousRole, rolesConfig) : result;
376
+ }
377
+ if (rolesConfig) {
378
+ const userRoles = resolveUserRoles(user, {
379
+ rolesFieldName: options?.rolesFieldName,
380
+ anonymousRole: options?.anonymousRole
381
+ });
382
+ for (const role of userRoles) {
383
+ const roleCapabilities = resolveRoleCapabilities(role, rolesConfig);
384
+ for (const cap of roleCapabilities) result.add(cap);
385
+ }
386
+ }
387
+ if (Array.isArray(user.capabilities)) {
388
+ for (const cap of user.capabilities) if (typeof cap === "string" && cap.trim().length > 0) result.add(cap.trim());
389
+ }
390
+ return result;
391
+ }
392
+ // src/capabilities/checker.ts
393
+ /**
394
+ Checks whether a user possesses the required capability, either directly, through assigned roles,
395
+ role inheritance, wildcard patterns, anonymous/public role, or super-admin privilege.
396
+
397
+ @param user - The user to evaluate, or null/undefined for anonymous visitors.
398
+ @param capability - The specific capability string required (e.g., `'site:read'`).
399
+ @param options - Custom options to override roles configuration or super-admin role.
400
+ @returns True if the user has the capability, false otherwise.
401
+
402
+ @example
403
+ ```typescript
404
+ if (hasCapability(user, 'orders:delete')) {
405
+ // Proceed with order deletion
406
+ }
407
+ ```
408
+ */
409
+ function hasCapability(user, capability, options) {
410
+ const globalConfig = getRbacConfig();
411
+ const superAdminRole = options?.superAdminRole === void 0 ? globalConfig?.superAdminRole ?? "admin" : options.superAdminRole;
412
+ if (user && superAdminRole && hasRole(user, superAdminRole, options)) return true;
413
+ const userCapabilities = resolveUserCapabilities(user, options);
414
+ for (const grantedPattern of userCapabilities) if (doesMatchCapability(grantedPattern, capability)) return true;
415
+ return false;
416
+ }
417
+ /**
418
+ Checks whether a user possesses at least one capability from a list of capabilities.
419
+
420
+ @param user - The user to evaluate, or null/undefined for anonymous visitors.
421
+ @param capabilities - An array of capabilities to check against.
422
+ @param options - Custom options to override roles configuration or super-admin role.
423
+ @returns True if the user satisfies at least one capability, false otherwise.
424
+
425
+ @example
426
+ ```typescript
427
+ if (hasAnyCapability(user, ['orders:read', 'orders:read_all'])) {
428
+ // Authorized to view orders
429
+ }
430
+ ```
431
+ */
432
+ function hasAnyCapability(user, capabilities, options) {
433
+ return capabilities.some((cap) => hasCapability(user, cap, options));
434
+ }
435
+ /**
436
+ Checks whether a user possesses all capabilities from a list of capabilities.
437
+
438
+ @param user - The user to evaluate, or null/undefined for anonymous visitors.
439
+ @param capabilities - An array of required capabilities that must all be satisfied.
440
+ @param options - Custom options to override roles configuration or super-admin role.
441
+ @returns True if the user satisfies every capability in the list, false otherwise.
442
+
443
+ @example
444
+ ```typescript
445
+ if (hasAllCapabilities(user, ['orders:export', 'reports:generate'])) {
446
+ // Authorized for batch export and report generation
447
+ }
448
+ ```
449
+ */
450
+ function hasAllCapabilities(user, capabilities, options) {
451
+ return capabilities.every((cap) => hasCapability(user, cap, options));
452
+ }
453
+ // src/access/shared.ts
454
+ /**
455
+ Evaluates whether a request user satisfies at least one of the required roles.
456
+ */
457
+ function hasRoleAccess(user, roles, options) {
458
+ return Boolean(user) && hasAnyRole(user, roles, options);
459
+ }
460
+ /**
461
+ Evaluates whether a request user satisfies the required capability or capability list.
462
+ */
463
+ function hasCapabilityAccess(user, capability, options) {
464
+ if (!user) return false;
465
+ if (Array.isArray(capability)) return (options?.mode ?? "any") === "all" ? hasAllCapabilities(user, capability, options) : hasAnyCapability(user, capability, options);
466
+ return hasCapability(user, capability, options);
467
+ }
468
+ // src/access/field-guards.ts
469
+ const checkFieldAuthenticated = ({ req: { user } }) => Boolean(user);
470
+ /**
471
+ Creates a field-level access rule requiring that the requesting client is an authenticated user.
472
+
473
+ @returns A Payload FieldAccess function returning true if user is authenticated, false otherwise.
474
+ */
475
+ function requireFieldAuth() {
476
+ return checkFieldAuthenticated;
477
+ }
478
+ /**
479
+ Creates a field-level access rule requiring that the requesting user possesses one or more specified roles.
480
+
481
+ @param role - A single role name or array of acceptable roles.
482
+ @param options - Custom options for role extraction.
483
+ @returns A Payload FieldAccess rule returning boolean.
484
+ */
485
+ function requireFieldRole(role, options) {
486
+ const rolesArray = Array.isArray(role) ? role : [role];
487
+ return ({ req: { user } }) => hasRoleAccess(user, rolesArray, options);
488
+ }
489
+ /**
490
+ Creates a field-level access rule requiring that the requesting user possesses one or more specified capabilities.
491
+
492
+ @param capability - A single capability or array of capabilities.
493
+ @param options - Options for capability verification, including matching mode (`'any'` | `'all'`).
494
+ @returns A Payload FieldAccess rule returning boolean.
495
+ */
496
+ function requireFieldCapability(capability, options) {
497
+ return ({ req: { user } }) => hasCapabilityAccess(user, capability, options);
498
+ }
499
+ /**
500
+ Universal field access rule that strictly denies field access to everyone (public & authenticated).
501
+
502
+ @returns Always returns `false`.
503
+ */
504
+ const nobodyField = () => false;
505
+ /**
506
+ Universal field access rule that permits field access to everyone.
507
+
508
+ @returns Always returns `true`.
509
+ */
510
+ const anyoneField = () => true;
511
+ /**
512
+ Functional alias for `nobodyField`.
513
+ */
514
+ const denyField = nobodyField;
515
+ /**
516
+ Functional alias for `anyoneField`.
517
+ */
518
+ const allowField = anyoneField;
519
+ /**
520
+ Configures field access for a strictly read-only field (cannot be created or updated via API).
521
+ The field remains readable according to the collection's read access rules, but API writes are denied.
522
+
523
+ @returns Field access object with create and update set to `nobodyField`.
524
+ */
525
+ function readOnlyField() {
526
+ return {
527
+ create: nobodyField,
528
+ update: nobodyField
529
+ };
530
+ }
531
+ /**
532
+ Configures field access for an internal system field that cannot be read, created, or updated via public API.
533
+ Only local server operations (with `overrideAccess: true` or internal services) can access or modify it.
534
+
535
+ @returns Field access object with create, read, and update set to `nobodyField`.
536
+ */
537
+ function systemOnlyField() {
538
+ return {
539
+ create: nobodyField,
540
+ read: nobodyField,
541
+ update: nobodyField
542
+ };
543
+ }
544
+ // src/access/guards.ts
545
+ const checkAuthenticated = ({ req: { user } }) => Boolean(user);
546
+ /**
547
+ Creates an access rule requiring that the requesting client is an authenticated user.
548
+
549
+ @returns A Payload Access function returning true if user is present, false otherwise.
550
+
551
+ @example
552
+ ```typescript
553
+ export const Orders = {
554
+ access: {
555
+ create: requireAuth(),
556
+ },
557
+ };
558
+ ```
559
+ */
560
+ function requireAuth() {
561
+ return checkAuthenticated;
562
+ }
563
+ /**
564
+ Creates an access rule requiring that the requesting user possesses one or more specified roles.
565
+
566
+ @param role - A single role name or array of acceptable roles.
567
+ @param options - Custom options for role extraction.
568
+ @returns A Payload Access rule returning boolean.
569
+
570
+ @example
571
+ ```typescript
572
+ access: {
573
+ delete: requireRole('admin'),
574
+ update: requireRole(['admin', 'operator']),
575
+ }
576
+ ```
577
+ */
578
+ function requireRole(role, options) {
579
+ const rolesArray = Array.isArray(role) ? role : [role];
580
+ return ({ req: { user } }) => hasRoleAccess(user, rolesArray, options);
581
+ }
582
+ /**
583
+ Creates an access rule requiring that the requesting user possesses one or more specified capabilities.
584
+
585
+ @param capability - A single capability or array of capabilities.
586
+ @param options - Options for capability verification, including matching mode (`'any'` | `'all'`).
587
+ @returns A Payload Access rule returning boolean.
588
+
589
+ @example
590
+ ```typescript
591
+ access: {
592
+ read: requireCapability('orders:read'),
593
+ update: requireCapability(['orders:update', 'orders:manage'], { mode: 'any' }),
594
+ }
595
+ ```
596
+ */
597
+ function requireCapability(capability, options) {
598
+ return ({ req: { user } }) => hasCapabilityAccess(user, capability, options);
599
+ }
600
+ /**
601
+ Universal access rule that strictly denies collection or global access to everyone (public & authenticated).
602
+ Ideal for immutable collections, disabled actions (e.g. `delete: nobody`), or server-only models.
603
+
604
+ @returns Always returns `false`.
605
+ */
606
+ const nobody = () => false;
607
+ /**
608
+ Universal access rule that permits public access to everyone.
609
+ Ideal for public-facing collections, marketing pages, site settings, or public legal documents.
610
+
611
+ @returns Always returns `true`.
612
+ */
613
+ const anyone = () => true;
614
+ /**
615
+ Functional alias for `nobody`.
616
+ */
617
+ const denyAll = nobody;
618
+ /**
619
+ Functional alias for `anyone`.
620
+ */
621
+ const allowAll = anyone;
622
+ // src/plugin.ts
623
+ /**
624
+ Creates and initializes the Payload CMS RBAC (Role-Based Access Control) plugin.
625
+
626
+ @param options - Configuration options defining roles, capabilities, and defaults.
627
+ @returns A Payload plugin function.
628
+
629
+ @example
630
+ ```typescript
631
+ // In payload.config.ts:
632
+ export default buildConfig({
633
+ plugins: [
634
+ rbacPlugin({
635
+ roles: {
636
+ admin: { capabilities: ['*'], label: 'Administrador' },
637
+ operator: { capabilities: ['orders:read', 'orders:update'], label: 'Operador' },
638
+ customer: { capabilities: ['orders:create'], label: 'Cliente' },
639
+ },
640
+ defaultRole: 'customer',
641
+ superAdminRole: 'admin',
642
+ }),
643
+ ],
644
+ });
645
+ ```
646
+ */
647
+ function rbacPlugin(options) {
648
+ registerRbacConfig(options);
649
+ return (incomingConfig) => {
650
+ const config = { ...incomingConfig };
651
+ if (!options.syncUserRolesField || !Array.isArray(config.collections)) return config;
652
+ const userCollectionSlug = options.userCollectionSlug ?? "users";
653
+ const rolesFieldName = options.rolesFieldName ?? "role";
654
+ const roleOptions = Object.entries(options.roles).map(([roleKey, roleDefinition]) => ({
655
+ label: roleDefinition.label ?? roleKey,
656
+ value: roleKey
657
+ }));
658
+ config.collections = config.collections.map((collection) => {
659
+ if (collection.slug !== userCollectionSlug) return collection;
660
+ const updatedFields = collection.fields.map((field) => {
661
+ if ("name" in field && field.name === rolesFieldName && field.type === "select") {
662
+ const selectField = field;
663
+ return {
664
+ ...selectField,
665
+ options: roleOptions,
666
+ defaultValue: options.defaultRole ?? selectField.defaultValue
667
+ };
668
+ }
669
+ return field;
670
+ });
671
+ return {
672
+ ...collection,
673
+ fields: updatedFields
674
+ };
675
+ });
676
+ return config;
677
+ };
678
+ }
679
+ /**
680
+ Creates an isolated, type-safe suite of RBAC helper functions bound to a specific configuration.
681
+
682
+ @param options - Configuration options for the isolated instance.
683
+ @returns An object containing bound checkers, access guards, and combinators.
684
+
685
+ @example
686
+ ```typescript
687
+ const rbac = createRbac({
688
+ roles: {
689
+ admin: { capabilities: ['*'] },
690
+ editor: { capabilities: ['articles:*'] },
691
+ },
692
+ });
693
+
694
+ const canEdit = rbac.hasCapability(user, 'articles:publish');
695
+ ```
696
+ */
697
+ function createRbac(options) {
698
+ return {
699
+ options,
700
+ plugin: () => rbacPlugin(options),
701
+ resolveRoles: (user) => resolveUserRoles(user, options.rolesFieldName),
702
+ hasRole: (user, role, checkOptions) => hasRole(user, role, {
703
+ rolesFieldName: options.rolesFieldName,
704
+ ...checkOptions
705
+ }),
706
+ hasAnyRole: (user, roles, checkOptions) => hasAnyRole(user, roles, {
707
+ rolesFieldName: options.rolesFieldName,
708
+ ...checkOptions
709
+ }),
710
+ hasAllRoles: (user, roles, checkOptions) => hasAllRoles(user, roles, {
711
+ rolesFieldName: options.rolesFieldName,
712
+ ...checkOptions
713
+ }),
714
+ hasCapability: (user, capability, checkOptions) => hasCapability(user, capability, {
715
+ roles: options.roles,
716
+ superAdminRole: options.superAdminRole,
717
+ rolesFieldName: options.rolesFieldName,
718
+ ...checkOptions
719
+ }),
720
+ hasAnyCapability: (user, capabilities, checkOptions) => hasAnyCapability(user, capabilities, {
721
+ roles: options.roles,
722
+ superAdminRole: options.superAdminRole,
723
+ rolesFieldName: options.rolesFieldName,
724
+ ...checkOptions
725
+ }),
726
+ hasAllCapabilities: (user, capabilities, checkOptions) => hasAllCapabilities(user, capabilities, {
727
+ roles: options.roles,
728
+ superAdminRole: options.superAdminRole,
729
+ rolesFieldName: options.rolesFieldName,
730
+ ...checkOptions
731
+ }),
732
+ requireAuth,
733
+ requireRole: (role, checkOptions) => requireRole(role, {
734
+ rolesFieldName: options.rolesFieldName,
735
+ ...checkOptions
736
+ }),
737
+ requireCapability: (capability, guardOptions) => requireCapability(capability, {
738
+ roles: options.roles,
739
+ superAdminRole: options.superAdminRole,
740
+ rolesFieldName: options.rolesFieldName,
741
+ ...guardOptions
742
+ }),
743
+ requireFieldAuth,
744
+ requireFieldRole: (role, checkOptions) => requireFieldRole(role, {
745
+ rolesFieldName: options.rolesFieldName,
746
+ ...checkOptions
747
+ }),
748
+ requireFieldCapability: (capability, guardOptions) => requireFieldCapability(capability, {
749
+ roles: options.roles,
750
+ superAdminRole: options.superAdminRole,
751
+ rolesFieldName: options.rolesFieldName,
752
+ ...guardOptions
753
+ }),
754
+ and,
755
+ or,
756
+ not,
757
+ fieldAnd,
758
+ fieldOr,
759
+ fieldNot,
760
+ doesMatchCapability,
761
+ resolveRoleCapabilities: (role) => resolveRoleCapabilities(role, options.roles),
762
+ resolveUserCapabilities: (user) => resolveUserCapabilities(user, {
763
+ roles: options.roles,
764
+ rolesFieldName: options.rolesFieldName
765
+ })
766
+ };
767
+ }
768
+ export { allowAll, allowField, and, anyone, anyoneField, createRbac, denyAll, denyField, doesMatchCapability, fieldAnd, fieldNot, fieldOr, getRbacConfig, hasAllCapabilities, hasAllRoles, hasAnyCapability, hasAnyRole, hasCapability, hasRole, nobody, nobodyField, not, or, rbacPlugin, readOnlyField, registerRbacConfig, requireAuth, requireCapability, requireFieldAuth, requireFieldCapability, requireFieldRole, requireRole, resetRbacConfig, resolveRoleCapabilities, resolveUserCapabilities, resolveUserRoles, systemOnlyField };
769
+
770
+ //# sourceMappingURL=index.js.map