@payload-kit/rbac 0.1.0-alpha.0 → 0.1.0-alpha.2

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/README.md CHANGED
@@ -1,122 +1,92 @@
1
1
  # @payload-kit/rbac
2
2
 
3
- High-precision, type-safe **Role-Based Access Control (RBAC)** and Capability engine for **Payload CMS v3**.
3
+ Role-Based Access Control (RBAC) and capability engine for Payload CMS. Maps business roles to atomic capabilities with inheritance, domain wildcards (`orders:*`, `*`), collection and field access guards, and logical combinators (`and`, `or`, `not`) where `and`/`or` preserve Payload `Where` query constraints.
4
4
 
5
- Decouples business roles from atomic permissions (capabilities), supports role inheritance, domain wildcards (`domain:*`, `*`), and provides logical access combinators (`and`, `or`, `not`) with full support for Payload CMS Row-Level Security (`Where` query conditions).
5
+ ## Installation
6
6
 
7
- ---
8
-
9
- ## Key Features
10
-
11
- - **Decoupled RBAC Architecture**: Define roles as collections of atomic capabilities instead of checking rigid role strings in collection access files.
12
- - **Atomic Capabilities**: Check fine-grained permissions such as `orders:create`, `orders:read`, `stock:manage`.
13
- - **Wildcards & Inheritance**: Full support for wildcard permissions (`'*'`), domain prefixes (`'orders:*'`), and multi-level role inheritance without circular dependencies.
14
- - **Payload RLS Combinators**:
15
- - `or(...)`: Grants access if any rule returns `true`, merges row-level constraints with `{ or: [...] }`, or denies if all return `false`.
16
- - `and(...)`: Denies access immediately if any rule returns `false`, merges constraints with `{ and: [...] }`, or allows if all return `true`.
17
- - `not(...)`: Inverts boolean access decisions cleanly.
18
- - **High Performance**: Pure in-memory capability resolution with zero extra database round-trips.
19
- - **100% Type-Safe**: Full TypeScript autocomplete and compile-time type verification.
7
+ ```bash
8
+ pnpm add @payload-kit/rbac
9
+ ```
20
10
 
21
- ---
11
+ Peer dependency: `payload` (`^3.0.0`).
22
12
 
23
- ## Installation & Configuration
13
+ ## Usage
24
14
 
25
- ### 1. Register the Plugin in `payload.config.ts`
15
+ ### 1. Register the plugin
26
16
 
27
- ```typescript
17
+ ```ts
18
+ import { buildConfig } from "payload";
28
19
  import { rbacPlugin } from "@payload-kit/rbac";
29
20
 
30
- export const rbac = rbacPlugin({
31
- // 1. Define roles and their granted capabilities
32
- roles: {
33
- customer: {
34
- label: "Cliente",
35
- capabilities: ["orders:create", "orders:read-own"],
36
- },
37
- operator: {
38
- label: "Operador de Impressão",
39
- capabilities: ["orders:read", "orders:update", "stock:manage"],
40
- inherits: ["customer"], // Inherits customer capabilities
41
- },
42
- admin: {
43
- label: "Administrador",
44
- capabilities: ["*"], // Wildcard access to all capabilities
45
- },
46
- },
47
-
48
- // 2. Default role for new users
49
- defaultRole: "customer",
50
-
51
- // 3. Super-admin role with automatic bypass (defaults to 'admin')
52
- superAdminRole: "admin",
21
+ export default buildConfig({
22
+ plugins: [
23
+ rbacPlugin({
24
+ roles: {
25
+ customer: {
26
+ label: "Customer",
27
+ capabilities: ["orders:create", "orders:read-own"],
28
+ },
29
+ operator: {
30
+ label: "Operator",
31
+ capabilities: ["orders:read", "orders:update", "inventory:manage"],
32
+ inherits: ["customer"],
33
+ },
34
+ admin: {
35
+ label: "Administrator",
36
+ capabilities: ["*"],
37
+ },
38
+ },
39
+ defaultRole: "customer",
40
+ superAdminRole: "admin",
41
+ }),
42
+ ],
53
43
  });
54
44
  ```
55
45
 
56
- ---
57
-
58
- ## Usage Guide
46
+ `superAdminRole` is opt-in (`undefined` by default); set it explicitly (e.g. `"admin"`) to enable super-admin capability bypass. Capability resolution runs in memory with no extra database queries and handles circular inheritance safely.
59
47
 
60
- ### 1. Protecting Collections with Access Guards and Combinators
48
+ ### 2. Protect collections
61
49
 
62
- The combinators (`or`, `and`, `not`) seamlessly merge boolean capabilities with Payload CMS Row-Level Security (`Where` query filters). Declarative constant guards (`nobody`, `anyone`) are also provided for common lockouts:
50
+ Combinators (`or`, `and`) merge boolean capability checks with Payload Row-Level Security (`Where`) filters (`not` inverts boolean rules and throws a `TypeError` on `Where` clauses):
63
51
 
64
- ```typescript
52
+ ```ts
65
53
  import type { CollectionConfig } from "payload";
66
- import {
67
- requireCapability,
68
- requireRole,
69
- requireAuth,
70
- nobody,
71
- anyone,
72
- or,
73
- and,
74
- } from "@payload-kit/rbac";
54
+ import { and, nobody, or, requireAuth, requireCapability, requireRole } from "@payload-kit/rbac";
75
55
 
76
- export const PrintOrders: CollectionConfig = {
56
+ export const Orders: CollectionConfig = {
77
57
  slug: "orders",
78
58
  access: {
79
- // Read: Users with 'orders:read' see all orders; customers only see their own
80
59
  read: or(requireCapability("orders:read"), ({ req: { user } }) => ({
81
- "customer.email": {
82
- equals: user?.email,
83
- },
60
+ "customer.email": { equals: user?.email },
84
61
  })),
85
-
86
- // Create: Requires authentication AND 'orders:create' capability
87
62
  create: and(requireAuth(), requireCapability("orders:create")),
88
-
89
- // Update / Delete: Only users with explicit management capability
90
63
  update: requireCapability("orders:update"),
91
64
  delete: requireCapability("orders:delete"),
92
65
  },
93
- // ...
66
+ fields: [],
94
67
  };
95
68
 
96
69
  export const AuditLogs: CollectionConfig = {
97
70
  slug: "audit-logs",
98
71
  access: {
99
- // Immutable collection: completely lock out creation or updates via API
100
72
  create: nobody,
101
73
  update: nobody,
102
74
  delete: requireRole("admin"),
103
75
  },
76
+ fields: [],
104
77
  };
105
78
  ```
106
79
 
107
- ### 2. Protecting Fields (Field-Level Access Control)
80
+ ### 3. Protect fields
108
81
 
109
- Protect specific fields against unauthorized reads or privilege escalation using declarative helpers like `readOnlyField()` or granular field guards:
82
+ Use field guards to restrict sensitive fields or prevent privilege escalation on role fields:
110
83
 
111
- ```typescript
84
+ ```ts
112
85
  import {
113
- requireFieldAuth,
86
+ readOnlyField,
114
87
  requireFieldCapability,
115
88
  requireFieldRole,
116
- readOnlyField,
117
89
  systemOnlyField,
118
- nobodyField,
119
- fieldOr,
120
90
  } from "@payload-kit/rbac";
121
91
 
122
92
  export const Users = {
@@ -126,7 +96,6 @@ export const Users = {
126
96
  name: "role",
127
97
  type: "select",
128
98
  access: {
129
- // Prevent privilege escalation: only users with 'users:manage' can modify roles
130
99
  update: requireFieldCapability("users:manage"),
131
100
  },
132
101
  },
@@ -139,14 +108,12 @@ export const Users = {
139
108
  },
140
109
  },
141
110
  {
142
- // Completely read-only field: can be read, but never created or updated via API
143
111
  name: "oidcSub",
144
112
  type: "text",
145
113
  access: readOnlyField(),
146
114
  },
147
115
  {
148
- // Sensitive system internal field: completely hidden and immutable via public API
149
- name: "paymentWebhookSecret",
116
+ name: "webhookSecret",
150
117
  type: "text",
151
118
  access: systemOnlyField(),
152
119
  },
@@ -154,85 +121,83 @@ export const Users = {
154
121
  };
155
122
  ```
156
123
 
157
- ### 3. Functional Checkers in Server / UI Components
158
-
159
- Check capabilities or roles directly in custom endpoints, hooks, or server actions:
124
+ ### 4. Check capabilities in server code
160
125
 
161
- ```typescript
162
- import { hasCapability, hasAnyCapability, hasRole } from "@payload-kit/rbac";
126
+ ```ts
127
+ import { hasAnyCapability, hasCapability, hasRole } from "@payload-kit/rbac";
163
128
 
164
- // Check single capability:
165
- if (hasCapability(user, "stock:manage")) {
166
- // Allow spool adjustments
129
+ if (hasCapability(user, "inventory:manage")) {
130
+ // allow stock update
167
131
  }
168
132
 
169
- // Check any capability:
170
133
  if (hasAnyCapability(user, ["orders:update", "orders:delete"])) {
171
- // Display administrative toolbar
134
+ // show management actions
172
135
  }
173
136
 
174
- // Check role:
175
137
  if (hasRole(user, "admin")) {
176
- // Super-admin only operation
138
+ // admin-only branch
177
139
  }
178
140
  ```
179
141
 
180
- ### 4. Isolated Instances with `createRbac`
142
+ ### 5. Isolated instances with `createRbac`
181
143
 
182
- If you need a scoped RBAC engine (for example, in a multi-tenant setup or micro-service):
144
+ When you need an RBAC engine scoped to a specific tenant or module instead of the global registry:
183
145
 
184
- ```typescript
146
+ ```ts
185
147
  import { createRbac } from "@payload-kit/rbac";
186
148
 
187
149
  const appRbac = createRbac({
188
150
  roles: {
189
- viewer: { capabilities: ["models:view"] },
190
- designer: { capabilities: ["models:*"], inherits: ["viewer"] },
151
+ viewer: { capabilities: ["reports:view"] },
152
+ editor: { capabilities: ["reports:*"], inherits: ["viewer"] },
191
153
  },
192
154
  });
193
155
 
194
- const canExport = appRbac.hasCapability(user, "models:export");
156
+ const canExport = appRbac.hasCapability(user, "reports:export");
195
157
  ```
196
158
 
197
- ---
159
+ ## API reference
198
160
 
199
- ## API Reference
161
+ ### Plugin options (`RbacPluginOptions`)
200
162
 
201
- ### Verifiers
163
+ - `roles`: Map of role names to `{ label?, capabilities, inherits? }`.
164
+ - `capabilities`: Optional exhaustive list of valid capabilities.
165
+ - `defaultRole`: Default role applied by `createRoleField` / `rbac.roleField()`.
166
+ - `superAdminRole`: Optional role that bypasses all capability checks (opt-in; e.g. `"admin"`).
167
+ - `anonymousRole`: Optional role for unauthenticated visitors in role/capability checkers.
168
+ - `userCollectionSlug`: Optional user collection slug enforced during runtime `user.collection` validation (fails closed for other auth collections when set).
169
+ - `rolesFieldName`: Field name storing the user role(s) (default `"role"`).
170
+ - `createRoleField(options, overrides?)` / `rbac.roleField(overrides?)`: Field builder returning a write-protected `SelectField` that you can place anywhere in your users collection (`fields`, `tabs`, `row`, or `sidebar`).
202
171
 
203
- - `hasRole(user, role, options?)`: Checks if user has a specific role.
204
- - `hasAnyRole(user, roles, options?)`: Checks if user has at least one of the roles.
205
- - `hasAllRoles(user, roles, options?)`: Checks if user has all listed roles.
206
- - `hasCapability(user, capability, options?)`: Checks if user has capability (evaluating wildcards, inheritance, and super-admin bypass).
207
- - `hasAnyCapability(user, capabilities, options?)`: Checks if user has at least one capability.
208
- - `hasAllCapabilities(user, capabilities, options?)`: Checks if user has all listed capabilities.
172
+ ### Role and capability checkers
209
173
 
210
- ### Collection-Level Access Guards & Combinators
174
+ - `hasRole(user, role, options?)`: Checks whether the user has the given role.
175
+ - `hasAnyRole(user, roles, options?)`: Checks whether the user has at least one listed role.
176
+ - `hasAllRoles(user, roles, options?)`: Checks whether the user has every listed role.
177
+ - `hasCapability(user, capability, options?)`: Evaluates wildcards, inheritance, and `superAdminRole`.
178
+ - `hasAnyCapability(user, capabilities, options?)`: Checks whether the user has at least one capability.
179
+ - `hasAllCapabilities(user, capabilities, options?)`: Checks whether the user has every listed capability.
211
180
 
212
- - `nobody` / `denyAll`: Access guard that always denies access (`() => false`). Ideal for locking immutable collections.
213
- - `anyone` / `allowAll`: Access guard that always allows access (`() => true`). Ideal for public collections.
214
- - `requireAuth()`: Access guard requiring an authenticated user.
215
- - `requireRole(role | role[])`: Access guard checking user roles.
216
- - `requireCapability(capability | capability[], options?)`: Access guard checking user capabilities.
217
- - `or(...rules)`: Logical OR merging boolean checks and Payload `Where` queries.
218
- - `and(...rules)`: Logical AND merging boolean checks and Payload `Where` queries.
219
- - `not(rule)`: Logical NOT inverting boolean access decisions.
181
+ ### Collection guards and combinators
220
182
 
221
- ### Field-Level Access Guards & Combinators
183
+ - `nobody` / `denyAll`: Always returns `false`.
184
+ - `anyone` / `allowAll`: Always returns `true`.
185
+ - `requireAuth(options?)`: Requires an authenticated user (accepts `AuthCheckOptions` with `userCollectionSlug`, failing closed for other auth collections when configured).
186
+ - `requireRole(role | role[])`: Requires one of the listed roles.
187
+ - `requireCapability(capability | capability[], options?)`: Requires matching capability.
188
+ - `or(...rules)`: Returns `true` if any rule returns `true`, merges `Where` clauses with `{ or: [...] }`, or returns `false` if all deny.
189
+ - `and(...rules)`: Returns `false` if any rule returns `false`, merges `Where` clauses with `{ and: [...] }`, or returns `true` if all allow.
190
+ - `not(rule)`: Inverts a boolean access decision.
222
191
 
223
- - `readOnlyField()`: Returns `{ create: nobodyField, update: nobodyField }`, making a field completely immutable via API.
224
- - `systemOnlyField()`: Returns `{ create: nobodyField, read: nobodyField, update: nobodyField }`, hiding and locking an internal field from public API access.
225
- - `nobodyField` / `denyField`: Field guard that always denies modification (`() => false`).
226
- - `anyoneField` / `allowField`: Field guard that always allows modification (`() => true`).
227
- - `requireFieldAuth()`: Field guard requiring an authenticated user.
228
- - `requireFieldRole(role | role[])`: Field guard checking user roles.
229
- - `requireFieldCapability(capability | capability[], options?)`: Field guard checking user capabilities (ideal for privilege escalation prevention on `role` fields).
230
- - `fieldOr(...rules)`: Logical OR for boolean field checks.
231
- - `fieldAnd(...rules)`: Logical AND for boolean field checks.
232
- - `fieldNot(rule)`: Logical NOT for boolean field checks.
192
+ ### Field guards and combinators
233
193
 
234
- ---
194
+ - `readOnlyField()`: Returns `{ create: nobodyField, update: nobodyField }`.
195
+ - `systemOnlyField()`: Returns `{ create: nobodyField, read: nobodyField, update: nobodyField }`.
196
+ - `nobodyField` / `denyField`: Always returns `false`.
197
+ - `anyoneField` / `allowField`: Always returns `true`.
198
+ - `requireFieldAuth(options?)`, `requireFieldRole(role | role[])`, `requireFieldCapability(capability | capability[], options?)`: Field-level equivalents of the collection guards (`requireFieldAuth` accepts `AuthCheckOptions` for `userCollectionSlug` enforcement).
199
+ - `fieldOr(...rules)`, `fieldAnd(...rules)`, `fieldNot(rule)`: Boolean combinators for field access.
235
200
 
236
201
  ## License
237
202
 
238
- MIT © gngz
203
+ MIT