@anievo-id/rbac-evolution 0.8.0 → 1.0.0-rc.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.
package/README.md CHANGED
@@ -1,197 +1,45 @@
1
1
  # @anievo-id/rbac-evolution
2
2
 
3
- 📖 **[Documentation](https://creation.anievo.id/rbac-evolution/guide/introduction)**
3
+ Framework-agnostic roles and permissions (RBAC) for JavaScript and TypeScript, modelled on
4
+ [spatie/laravel-permission](https://github.com/spatie/laravel-permission): guards, wildcards, teams, super-admins,
5
+ caching and events.
4
6
 
5
- Framework-agnostic RBAC engine for [rbac-evolution](https://github.com/AniEvo-ID/rbac-evolution) —
6
- roles, permissions, guards, wildcards and teams. Inspired by
7
- [spatie/laravel-permission](https://github.com/spatie/laravel-permission).
7
+ **Status: early development. The API may change before 1.0.**
8
8
 
9
- **Status: 🚧 early development — API may change before 1.0.**
9
+ ## Install
10
10
 
11
11
  ```bash
12
12
  npm i @anievo-id/rbac-evolution
13
13
  ```
14
14
 
15
- ## Quick start
15
+ ## Usage
16
16
 
17
17
  ```ts
18
18
  import { createRbac, MemoryAdapter } from '@anievo-id/rbac-evolution'
19
19
 
20
20
  const rbac = createRbac({ adapter: new MemoryAdapter() })
21
21
 
22
- // define permissions & roles
23
22
  await rbac.createPermission('edit articles')
24
- await rbac.createPermission('delete articles')
25
23
  await rbac.createRole('writer')
26
24
  await rbac.role('writer').givePermissionTo('edit articles')
27
25
 
28
- // assign to a user (any { type, id } works)
29
- const user = rbac.for({ type: 'user', id: 1 })
26
+ const user = rbac.for({ type: 'user', id: 1 }) // any { type, id }
30
27
  await user.assignRole('writer')
31
28
 
32
- await user.hasRole('writer') // true
33
- await user.hasPermissionTo('edit articles') // true
34
- await user.can('delete articles') // false
29
+ await user.can('edit articles') // true
30
+ await user.can('delete articles') // false
31
+ await user.snapshot() // { roles: ['writer'], permissions: ['edit articles'] }
35
32
  ```
36
33
 
37
- ## Subjects
38
-
39
- A subject is anything that holds roles — `{ type: string, id: string | number }`.
40
- Use `rbac.for(subject)` to work with it:
41
-
42
- | Method | Description |
43
- | --- | --- |
44
- | `assignRole(...roles)` / `removeRole(...roles)` / `syncRoles(...roles)` | Manage roles |
45
- | `hasRole(role \| roles[])` / `hasAnyRole(...)` / `hasAllRoles(...)` | Check roles |
46
- | `givePermissionTo(...)` / `revokePermissionTo(...)` / `syncPermissions(...)` | Manage direct permissions |
47
- | `hasPermissionTo(p)` | Check a permission (direct or via roles). Throws if `p` doesn't exist |
48
- | `can(p)` / `cannot(p)` / `canAny(...)` / `canAll(...)` | Same check, never throws |
49
- | `hasDirectPermission(p)` | Check direct permissions only |
50
- | `hasAnyPermission(...)` / `hasAllPermissions(...)` | Data check for several permissions, never throws |
51
- | `hasExactRoles(...roles)` | Has all of these roles and no others |
52
- | `getRoles()` / `getRoleNames()` | Read roles |
53
- | `getDirectPermissions()` / `getPermissionsViaRoles()` / `getAllPermissions()` / `getPermissionNames()` | Read permissions |
54
- | `snapshot()` | `{ roles, permissions }` — serializable, for the client |
55
-
56
- All methods accept names or objects, and either `fn('a', 'b')` or `fn(['a', 'b'])`.
57
-
58
- ## Roles
59
-
60
- ```ts
61
- const writer = rbac.role('writer')
62
- await writer.givePermissionTo('edit articles', 'delete articles')
63
- await writer.revokePermissionTo('delete articles')
64
- await writer.syncPermissions(['edit articles'])
65
- await writer.getPermissionNames() // ['edit articles']
66
- ```
67
-
68
- ## Seeding (`rbac.sync`)
69
-
70
- Declare your roles & permissions once and sync them — idempotent, so it's safe to run on every deploy:
71
-
72
- ```ts
73
- const summary = await rbac.sync(
74
- {
75
- permissions: ['edit articles', 'delete articles', 'publish articles'],
76
- roles: {
77
- admin: '*', // every permission of the guard
78
- writer: ['edit articles'],
79
- },
80
- },
81
- { prune: false, dryRun: false },
82
- )
83
- // summary: { dryRun, created: { permissions, roles }, updated: { roles }, deleted: { permissions, roles } }
84
- ```
85
-
86
- Missing permissions & roles are created, and each role's permissions are synced to exactly the
87
- given list. Pass an array of definitions with their own `guard` / `team` to sync several scopes;
88
- `prune: true` deletes what's not in the definition (only in the synced scopes); `dryRun: true`
89
- returns the plan without writing. The regular events fire.
90
-
91
- ## Guards
92
-
93
- Like Laravel guards — separate sets of roles/permissions (e.g. `web` and `api`):
94
-
95
- ```ts
96
- await rbac.createPermission('edit articles', { guard: 'api' })
97
- await rbac.for(client, { guard: 'api' }).givePermissionTo('edit articles')
98
- ```
99
-
100
- The default guard is `web` (`createRbac({ defaultGuard: 'api' })` to change it).
101
-
102
- ## Wildcard permissions
103
-
104
- ```ts
105
- const rbac = createRbac({ adapter, wildcard: true })
106
-
107
- await rbac.createPermission('articles.*')
108
- await rbac.for(user).givePermissionTo('articles.*')
109
-
110
- await rbac.for(user).can('articles.edit') // true
111
- await rbac.for(user).can('articles.edit.own') // true
112
- await rbac.for(user).can('posts.edit') // false
113
- ```
114
-
115
- Supports `*`, `articles.*`, `articles.edit,delete` and shorter permissions implying deeper ones.
116
-
117
- ## Teams (multi-tenancy)
118
-
119
- ```ts
120
- const rbac = createRbac({ adapter, teams: true })
121
-
122
- await rbac.createRole('admin') // global role, usable in any team
123
- await rbac.createRole('manager', { team: 42 }) // only exists in team 42
124
-
125
- await rbac.for(user, { team: 42 }).assignRole('admin')
126
- await rbac.for(user, { team: 42 }).hasRole('admin') // true
127
- await rbac.for(user, { team: 7 }).hasRole('admin') // false
128
- ```
129
-
130
- ## Super-admin
131
-
132
- Like spatie's `Gate::before`, you can let some subjects pass every check:
133
-
134
- ```ts
135
- const rbac = createRbac({ adapter, superAdminRoles: ['super-admin'] })
136
-
137
- await rbac.for(root).assignRole('super-admin')
138
- await rbac.for(root).can('anything') // true, even if the permission doesn't exist
139
- await rbac.for(root).hasPermissionTo('edit articles') // false: pure data check
140
- ```
141
-
142
- For full control use a `before` hook. Return `true` to allow, `false` to deny, or
143
- `undefined` to continue with the normal check. It may be async:
144
-
145
- ```ts
146
- createRbac({
147
- adapter,
148
- superAdminRoles: ['super-admin'],
149
- before: async ({ subject, permission }) => {
150
- if (permission === 'delete everything') return false // nobody, not even super-admins
151
- if (await isBanned(subject.subject)) return false
152
- return undefined
153
- },
154
- })
155
- ```
156
-
157
- `before` runs first. If it returns `undefined`, `superAdminRoles` is checked, then the normal
158
- check. `subject` is the scoped `SubjectRbac` (it has `subject`, `guardName`, `teamId`, `hasRole()`...).
159
-
160
- > As in spatie, only `can()`, `cannot()`, `canAny()` and `canAll()` use `before` and
161
- > `superAdminRoles`. `hasPermissionTo()`, `hasDirectPermission()`, `hasAnyPermission()`,
162
- > `hasAllPermissions()` and the role checks only look at the stored data.
163
-
164
- ## Events
165
-
166
- ```ts
167
- const off = rbac.on('role.attached', async ({ subject, roles, teamId }) => {
168
- await audit.log(`${subject.type}#${subject.id} got ${roles.map((r) => r.name).join(', ')}`)
169
- })
170
- off() // or rbac.off('role.attached', listener)
171
- ```
172
-
173
- | Event | Fired by | Payload |
174
- | --- | --- | --- |
175
- | `role.attached` / `role.detached` | `assignRole`, `removeRole`, `syncRoles` | `{ subject, roles, guardName, teamId }` |
176
- | `permission.attached` / `permission.detached` | `givePermissionTo`, `revokePermissionTo`, `syncPermissions` on a subject or a role | `{ target: 'subject', subject, ... }` or `{ target: 'role', role, ... }`, plus `{ permissions, guardName, teamId }` |
177
- | `role.created` / `role.deleted` | `createRole` (and `findOrCreateRole`), `deleteRole` | `{ role, teamId }` |
178
- | `permission.created` / `permission.deleted` | `createPermission` (and `findOrCreatePermission`), `deletePermission` | `{ permission }` |
179
-
180
- Every payload has an `event` field, so `RbacEvent` is a discriminated union.
181
-
182
- - Events fire only after the adapter write succeeds and the cache has been cleared.
183
- - Listeners run in registration order. Async listeners are awaited one by one, and the
184
- method (e.g. `assignRole`) resolves after all of them. If a listener throws, the error
185
- reaches the caller, but the change is already saved.
186
- - Only real changes are reported. Assigning a role the subject already has emits nothing.
187
- `sync*` emits `detached` for what was removed and then `attached` for what was added.
188
- - To find what changed, attach/detach do one extra adapter read, but only when a listener
189
- is registered for that event.
190
- - Deleting a role or permission emits only `*.deleted`, not `detached` for every subject.
34
+ `MemoryAdapter` is built in. For a database, use one of the adapter packages:
35
+ [Prisma](https://www.npmjs.com/package/@anievo-id/rbac-evolution-prisma),
36
+ [Drizzle](https://www.npmjs.com/package/@anievo-id/rbac-evolution-drizzle),
37
+ [Kysely](https://www.npmjs.com/package/@anievo-id/rbac-evolution-kysely) or
38
+ [Mongoose](https://www.npmjs.com/package/@anievo-id/rbac-evolution-mongoose).
191
39
 
192
40
  ## Typed names
193
41
 
194
- Like spatie's enum support, you can tell the engine which permission and role names are valid:
42
+ Tell the engine which names are valid, and a typo becomes a compile error:
195
43
 
196
44
  ```ts
197
45
  type AppRbac = {
@@ -202,65 +50,17 @@ type AppRbac = {
202
50
  const rbac = createRbac<AppRbac>({ adapter })
203
51
 
204
52
  await rbac.for(user).can('edit articles') // ok
205
- await rbac.for(user).can('fly') // type error
206
53
  await rbac.for(user).assignRole('ghost') // type error
207
54
  ```
208
55
 
209
- TS string enums work too, either as enum members or as their literal values:
210
-
211
- ```ts
212
- enum Perm { Edit = 'edit articles', Delete = 'delete articles' }
213
- const rbac = createRbac<{ permissions: Perm }>({ adapter }) // roles: any string
214
-
215
- await rbac.for(user).can(Perm.Edit) // ok
216
- await rbac.for(user).can('edit articles') // ok
217
- ```
218
-
219
- - Name inputs are type-checked everywhere: `createPermission`, `findRole`, `role()`,
220
- `givePermissionTo`, `can`, `hasRole`, `assignRole`, `superAdminRoles`, the query methods, and so on.
221
- `Permission` and `Role` objects are always accepted.
222
- - Return values (`getRoleNames()`, `snapshot()`, ...) stay `string[]`, because the database may
223
- contain other names.
224
- - With `wildcard: true`, add the names you check to the union too (`'articles.*' | 'articles.edit'`).
225
- - With no type argument everything accepts `string`, as before. `Rbac`, `SubjectRbac` and
226
- `RoleRbac` without type arguments still work, and a typed instance can be passed where `Rbac` is expected.
227
- - Helper types: `RbacTypeConfig`, `PermissionName<T>`, `RoleName<T>`.
228
-
229
- ## Querying subjects
230
-
231
- Like spatie's `User::role('writer')` and `User::permission('edit articles')` scopes, these return
232
- the ids of matching subjects of a type:
233
-
234
- ```ts
235
- await rbac.subjectsWithRole('user', 'writer') // [1, 4]
236
- await rbac.subjectsWithRole('user', ['writer', 'editor']) // any of the roles
237
- await rbac.subjectsWithPermission('user', 'edit articles') // direct or via a role
238
- await rbac.subjectsWithPermission('user', 'edit articles', { team: 42, guard: 'api' })
239
- ```
240
-
241
- - Unknown names throw `RoleDoesNotExist` / `PermissionDoesNotExist`.
242
- - Wildcard patterns are not expanded. A subject is found only if it has exactly that permission,
243
- directly or through a role.
244
-
245
- On a subject, `hasExactRoles('writer', 'editor')` is `true` only if the subject has exactly
246
- those roles, no more and no fewer.
247
-
248
- ## Caching
249
-
250
- Each subject's roles & permissions are cached (in memory by default, 24h TTL) and the
251
- cache is cleared automatically on every change. Plug in your own store (Redis, KV, ...):
252
-
253
- ```ts
254
- createRbac({ adapter, cache: myStore, cacheTtl: 60_000 }) // implements CacheStore
255
- createRbac({ adapter, cache: false }) // disable
256
- ```
56
+ String enums work too. Return values (`getRoleNames()`, `snapshot()`, ...) stay `string[]`. See
57
+ [Typed names](https://creation.anievo.id/rbac-evolution/basic-usage/typed-names).
257
58
 
258
- ## Adapters
59
+ > Client-side checks are for the UI only. Always enforce permissions on the server.
259
60
 
260
- `MemoryAdapter` is built in. For databases use [`@anievo-id/rbac-evolution-prisma`](https://www.npmjs.com/package/@anievo-id/rbac-evolution-prisma) or [`@anievo-id/rbac-evolution-drizzle`](https://www.npmjs.com/package/@anievo-id/rbac-evolution-drizzle).
261
- To support another database, implement the `RbacAdapter` interface.
61
+ ## Documentation
262
62
 
263
- > ⚠️ Client-side checks are for UI only. Always enforce permissions on the server.
63
+ https://creation.anievo.id/rbac-evolution/guide/introduction
264
64
 
265
65
  ## License
266
66
 
@@ -407,6 +407,11 @@ var Rbac = class _Rbac {
407
407
  if (!permission) throw new PermissionDoesNotExist(normalizeName(name), this.#resolveGuard(options.guard));
408
408
  return permission;
409
409
  }
410
+ /** Finds a permission by id in the guard (spatie: `Permission::findById($id, $guard)`), or `null`. */
411
+ async findPermissionById(id, options = {}) {
412
+ const [permission] = await this.adapter.findPermissions({ ids: [id], guardName: this.#resolveGuard(options.guard) });
413
+ return permission ?? null;
414
+ }
410
415
  async findOrCreatePermission(name, options = {}) {
411
416
  return await this.findPermission(name, options) ?? this.createPermission(name, options);
412
417
  }
@@ -445,6 +450,25 @@ var Rbac = class _Rbac {
445
450
  if (!role) throw new RoleDoesNotExist(normalizeName(name), this.#resolveGuard(options.guard));
446
451
  return role;
447
452
  }
453
+ /** Finds a role by id in the guard (spatie: `Role::findById($id, $guard)`), or `null`. */
454
+ async findRoleById(id, options = {}) {
455
+ const [role] = await this.adapter.findRoles({ ids: [id], guardName: this.#resolveGuard(options.guard) });
456
+ return role ?? null;
457
+ }
458
+ /**
459
+ * Roles in the given scope that grant the permission directly (spatie: `$permission->roles`).
460
+ * Throws `PermissionDoesNotExist` for an unknown permission. Wildcard grants are not expanded.
461
+ */
462
+ async rolesWithPermission(permission, options = {}) {
463
+ const guardName = this.#resolveGuard(options.guard);
464
+ const teamId = this.#resolveTeam(options.team);
465
+ const [resolved] = await this.#resolvePermissions([permission], guardName);
466
+ const roles = await this.adapter.findRoles({ guardName, teamIds: this.#visibleTeams(teamId) });
467
+ if (roles.length === 0) return [];
468
+ const links = await this.adapter.getRolePermissionLinks(roles.map((r) => r.id));
469
+ const holders = new Set(links.filter((l) => idKey2(l.permissionId) === idKey2(resolved.id)).map((l) => idKey2(l.roleId)));
470
+ return roles.filter((r) => holders.has(idKey2(r.id)));
471
+ }
448
472
  async findOrCreateRole(name, options = {}) {
449
473
  return await this.findRole(name, options) ?? this.createRole(name, options);
450
474
  }
@@ -744,6 +768,20 @@ var SubjectRbac = class _SubjectRbac {
744
768
  guardName;
745
769
  teamId;
746
770
  #core;
771
+ /**
772
+ * The same subject in another guard and/or team; options left out keep the current ones (spatie passes the
773
+ * guard to each check: `$user->hasRole('admin', 'api')`).
774
+ *
775
+ * ```ts
776
+ * await rbac.for(user).withScope({ guard: 'api' }).hasRole('admin')
777
+ * ```
778
+ */
779
+ withScope(options) {
780
+ return this.rbac.for(this.subject, {
781
+ guard: options.guard ?? this.guardName,
782
+ team: options.team === void 0 ? this.teamId : options.team
783
+ });
784
+ }
747
785
  // ------------------------------------------------------------------------ roles
748
786
  async assignRole(...roles) {
749
787
  const { adapter } = this.rbac;
@@ -877,6 +915,27 @@ var SubjectRbac = class _SubjectRbac {
877
915
  const direct = (await this.state()).direct.map((p) => p.name);
878
916
  return this.#core.permissionMatches(direct, name);
879
917
  }
918
+ /** `true` if the subject has ANY of the permissions directly (ignores roles). Never throws. */
919
+ async hasAnyDirectPermission(...permissions) {
920
+ for (const permission of flatten(permissions)) {
921
+ if (await this.checkDirect(permission)) return true;
922
+ }
923
+ return false;
924
+ }
925
+ /** `true` if the subject has ALL the permissions directly (ignores roles). Never throws. */
926
+ async hasAllDirectPermissions(...permissions) {
927
+ for (const permission of flatten(permissions)) {
928
+ if (!await this.checkDirect(permission)) return false;
929
+ }
930
+ return true;
931
+ }
932
+ /**
933
+ * {@link hasPermissionTo} that returns `false` instead of throwing for an unknown permission or another guard
934
+ * (spatie: `checkPermissionTo`). Pure data check: no `before` hook or super-admin.
935
+ */
936
+ async checkPermissionTo(permission) {
937
+ return this.check(permission);
938
+ }
880
939
  /**
881
940
  * Authorization check: runs the `before` hook and `superAdminRoles` first, then falls back
882
941
  * to {@link hasPermissionTo}, returning `false` instead of throwing.
@@ -930,6 +989,15 @@ var SubjectRbac = class _SubjectRbac {
930
989
  throw error;
931
990
  }
932
991
  }
992
+ /** {@link hasDirectPermission} that returns `false` instead of throwing. */
993
+ async checkDirect(permission) {
994
+ try {
995
+ return await this.hasDirectPermission(permission);
996
+ } catch (error) {
997
+ if (error instanceof RbacError) return false;
998
+ throw error;
999
+ }
1000
+ }
933
1001
  async requirePermissionName(permission) {
934
1002
  if (typeof permission !== "string") {
935
1003
  if (permission.guardName !== this.guardName) throw new GuardDoesNotMatch(permission.guardName, this.guardName);
@@ -984,5 +1052,5 @@ function createRbac(options) {
984
1052
  }
985
1053
 
986
1054
  export { GuardDoesNotMatch, InvalidWildcardPermission, MemoryCache, PermissionAlreadyExists, PermissionDoesNotExist, Rbac, RbacError, RoleAlreadyExists, RoleDoesNotExist, RoleRbac, SubjectRbac, createRbac, parseWildcardPermission, wildcardImplies };
987
- //# sourceMappingURL=chunk-4IVKUA7F.js.map
988
- //# sourceMappingURL=chunk-4IVKUA7F.js.map
1055
+ //# sourceMappingURL=chunk-TYHFU62A.js.map
1056
+ //# sourceMappingURL=chunk-TYHFU62A.js.map