@anievo-id/rbac-evolution 0.2.1 → 0.3.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 +23 -0
- package/dist/{adapter-BBs9C5pT.d.cts → adapter-XWQmXahX.d.cts} +1 -1
- package/dist/{adapter-BBs9C5pT.d.ts → adapter-XWQmXahX.d.ts} +1 -1
- package/dist/{chunk-WIB3HDSP.js → chunk-7NQQUZ3Q.js} +192 -13
- package/dist/chunk-7NQQUZ3Q.js.map +1 -0
- package/dist/index.cjs +191 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +101 -3
- package/dist/index.d.ts +101 -3
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/testing.cjs +190 -11
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-WIB3HDSP.js.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as Subject, R as Role, T as TeamId, P as Permission, a as RbacTypeConfig, D as DefaultRbacTypes, b as
|
|
1
|
+
import { S as Subject, R as Role, T as TeamId, P as Permission, a as RbacTypeConfig, D as DefaultRbacTypes, b as PermissionName, c as RoleName, d as RbacAdapter, e as RoleInput, M as Many, f as PermissionInput, I as Id, g as RbacSnapshot, F as FindPermissionsQuery, h as FindRolesQuery, i as RolePermissionLink } from './adapter-XWQmXahX.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Cache used to store each subject's resolved roles & permissions.
|
|
@@ -105,6 +105,83 @@ declare class RbacEmitter {
|
|
|
105
105
|
}): Promise<void>;
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
/** The permissions of a role in a {@link SyncDefinition}: an explicit list, or `'*'` for every permission of the guard. */
|
|
109
|
+
type SyncRolePermissions<T extends RbacTypeConfig = DefaultRbacTypes> = readonly PermissionName<T>[] | '*';
|
|
110
|
+
/**
|
|
111
|
+
* Declarative description of the roles & permissions of ONE guard (and optionally one team).
|
|
112
|
+
*
|
|
113
|
+
* ```ts
|
|
114
|
+
* await rbac.sync({
|
|
115
|
+
* permissions: ['edit articles', 'delete articles'],
|
|
116
|
+
* roles: { admin: '*', writer: ['edit articles'] },
|
|
117
|
+
* })
|
|
118
|
+
* ```
|
|
119
|
+
*
|
|
120
|
+
* Pass an array of definitions to sync several guards / teams at once.
|
|
121
|
+
*/
|
|
122
|
+
interface SyncDefinition<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
123
|
+
/** Guard of this block. Default: the `guard` option, then `defaultGuard`. */
|
|
124
|
+
guard?: string;
|
|
125
|
+
/** Team of the roles in this block (requires `teams: true`). Default: the `team` option, then global (`null`). */
|
|
126
|
+
team?: TeamId;
|
|
127
|
+
/** Permissions of the guard. Permissions referenced by a role are created too, even if not listed here. */
|
|
128
|
+
permissions?: readonly PermissionName<T>[];
|
|
129
|
+
/** Roles and their permissions. Each role's permissions are synced (replaced) to exactly this list. */
|
|
130
|
+
roles?: {
|
|
131
|
+
readonly [R in RoleName<T>]?: SyncRolePermissions<T>;
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
interface SyncOptions {
|
|
135
|
+
/** Default guard for definitions without a `guard`. Default: `defaultGuard`. */
|
|
136
|
+
guard?: string;
|
|
137
|
+
/** Default team for definitions without a `team`. */
|
|
138
|
+
team?: TeamId;
|
|
139
|
+
/**
|
|
140
|
+
* Delete roles & permissions that are not in the definition. Roles are pruned per guard + team
|
|
141
|
+
* scope present in the definition; permissions (which are guard-wide) only for guards that have a
|
|
142
|
+
* global (team-less) definition. Other guards and teams are never touched. Default: `false`.
|
|
143
|
+
*/
|
|
144
|
+
prune?: boolean;
|
|
145
|
+
/** Compute and return the plan without writing anything. Default: `false`. */
|
|
146
|
+
dryRun?: boolean;
|
|
147
|
+
}
|
|
148
|
+
interface SyncPermissionChange {
|
|
149
|
+
name: string;
|
|
150
|
+
guard: string;
|
|
151
|
+
}
|
|
152
|
+
interface SyncRoleChange {
|
|
153
|
+
name: string;
|
|
154
|
+
guard: string;
|
|
155
|
+
team: TeamId;
|
|
156
|
+
/** Permissions of the role: given to a created role / held by a deleted role. */
|
|
157
|
+
permissions: string[];
|
|
158
|
+
}
|
|
159
|
+
interface SyncRoleUpdate {
|
|
160
|
+
name: string;
|
|
161
|
+
guard: string;
|
|
162
|
+
team: TeamId;
|
|
163
|
+
/** Permissions newly given to the role. */
|
|
164
|
+
attached: string[];
|
|
165
|
+
/** Permissions taken away from the role. */
|
|
166
|
+
detached: string[];
|
|
167
|
+
}
|
|
168
|
+
/** What {@link Rbac.sync} did — or, with `dryRun`, would do. */
|
|
169
|
+
interface SyncResult {
|
|
170
|
+
dryRun: boolean;
|
|
171
|
+
created: {
|
|
172
|
+
permissions: SyncPermissionChange[];
|
|
173
|
+
roles: SyncRoleChange[];
|
|
174
|
+
};
|
|
175
|
+
/** Existing roles whose permissions changed. */
|
|
176
|
+
updated: {
|
|
177
|
+
roles: SyncRoleUpdate[];
|
|
178
|
+
};
|
|
179
|
+
deleted: {
|
|
180
|
+
permissions: SyncPermissionChange[];
|
|
181
|
+
roles: SyncRoleChange[];
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
108
185
|
interface GuardOptions {
|
|
109
186
|
/** Guard name, e.g. `web` or `api`. Defaults to `defaultGuard`. */
|
|
110
187
|
guard?: string;
|
|
@@ -195,6 +272,27 @@ declare class Rbac<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
|
195
272
|
/** Lists roles visible in the given scope (global roles + roles of the given team). */
|
|
196
273
|
getRoles(options?: ScopeOptions): Promise<Role[]>;
|
|
197
274
|
deleteRole(role: RoleInput<RoleName<T>>, options?: ScopeOptions): Promise<void>;
|
|
275
|
+
/**
|
|
276
|
+
* Declaratively seeds roles & permissions (spatie's "Database Seeding"): creates missing
|
|
277
|
+
* permissions and roles, and syncs each role's permissions to exactly the given list.
|
|
278
|
+
* Idempotent — running it again changes nothing. Uses the regular engine methods, so the
|
|
279
|
+
* usual events fire.
|
|
280
|
+
*
|
|
281
|
+
* ```ts
|
|
282
|
+
* await rbac.sync({
|
|
283
|
+
* permissions: ['edit articles', 'delete articles'],
|
|
284
|
+
* roles: { admin: '*', writer: ['edit articles'] },
|
|
285
|
+
* })
|
|
286
|
+
* ```
|
|
287
|
+
*
|
|
288
|
+
* - `'*'` gives a role every permission of its guard (after the sync).
|
|
289
|
+
* - Pass an array of definitions (each with its own `guard` / `team`) to sync several scopes.
|
|
290
|
+
* - `prune: true` deletes roles & permissions of the synced scopes that aren't in the definition.
|
|
291
|
+
* - `dryRun: true` returns the plan without writing anything.
|
|
292
|
+
*
|
|
293
|
+
* Not atomic: adapters have no transactions, so a failure midway leaves the earlier changes.
|
|
294
|
+
*/
|
|
295
|
+
sync(definition: SyncDefinition<T> | readonly SyncDefinition<T>[], options?: SyncOptions): Promise<SyncResult>;
|
|
198
296
|
/**
|
|
199
297
|
* Ids of subjects of `subjectType` that have ANY of the given roles in the given scope
|
|
200
298
|
* (spatie: `User::role('writer')->get()`). Throws `RoleDoesNotExist` for unknown roles.
|
|
@@ -356,7 +454,7 @@ declare class MemoryAdapter implements RbacAdapter {
|
|
|
356
454
|
private static reverse;
|
|
357
455
|
}
|
|
358
456
|
|
|
359
|
-
type RbacErrorCode = 'PERMISSION_DOES_NOT_EXIST' | 'PERMISSION_ALREADY_EXISTS' | 'ROLE_DOES_NOT_EXIST' | 'ROLE_ALREADY_EXISTS' | 'GUARD_DOES_NOT_MATCH' | 'TEAM_DOES_NOT_MATCH' | 'TEAMS_NOT_ENABLED' | 'INVALID_NAME' | 'INVALID_WILDCARD_PERMISSION';
|
|
457
|
+
type RbacErrorCode = 'PERMISSION_DOES_NOT_EXIST' | 'PERMISSION_ALREADY_EXISTS' | 'ROLE_DOES_NOT_EXIST' | 'ROLE_ALREADY_EXISTS' | 'GUARD_DOES_NOT_MATCH' | 'TEAM_DOES_NOT_MATCH' | 'TEAMS_NOT_ENABLED' | 'INVALID_NAME' | 'INVALID_WILDCARD_PERMISSION' | 'INVALID_SYNC_DEFINITION';
|
|
360
458
|
declare class RbacError extends Error {
|
|
361
459
|
readonly code: RbacErrorCode;
|
|
362
460
|
constructor(code: RbacErrorCode, message: string);
|
|
@@ -406,4 +504,4 @@ declare function wildcardImplies(granted: string, required: string): boolean;
|
|
|
406
504
|
/** Version of this package (read from package.json at build time). */
|
|
407
505
|
declare const VERSION: string;
|
|
408
506
|
|
|
409
|
-
export { type BeforeContext, type BeforeHook, type CacheStore, DefaultRbacTypes, FindPermissionsQuery, FindRolesQuery, GuardDoesNotMatch, type GuardOptions, Id, InvalidWildcardPermission, Many, MemoryAdapter, MemoryCache, Permission, PermissionAlreadyExists, type PermissionAttachedEvent, type PermissionCreatedEvent, type PermissionDeletedEvent, type PermissionDetachedEvent, PermissionDoesNotExist, PermissionInput, PermissionName, type PermissionTarget, Rbac, RbacAdapter, RbacError, type RbacErrorCode, type RbacEvent, type RbacEventListener, type RbacEventMap, type RbacEventName, type RbacOptions, RbacSnapshot, RbacTypeConfig, Role, RoleAlreadyExists, type RoleAttachedEvent, type RoleCreatedEvent, type RoleDeletedEvent, type RoleDetachedEvent, RoleDoesNotExist, RoleInput, RoleName, RolePermissionLink, RoleRbac, type ScopeOptions, Subject, SubjectRbac, TeamId, VERSION, createRbac, parseWildcardPermission, wildcardImplies };
|
|
507
|
+
export { type BeforeContext, type BeforeHook, type CacheStore, DefaultRbacTypes, FindPermissionsQuery, FindRolesQuery, GuardDoesNotMatch, type GuardOptions, Id, InvalidWildcardPermission, Many, MemoryAdapter, MemoryCache, Permission, PermissionAlreadyExists, type PermissionAttachedEvent, type PermissionCreatedEvent, type PermissionDeletedEvent, type PermissionDetachedEvent, PermissionDoesNotExist, PermissionInput, PermissionName, type PermissionTarget, Rbac, RbacAdapter, RbacError, type RbacErrorCode, type RbacEvent, type RbacEventListener, type RbacEventMap, type RbacEventName, type RbacOptions, RbacSnapshot, RbacTypeConfig, Role, RoleAlreadyExists, type RoleAttachedEvent, type RoleCreatedEvent, type RoleDeletedEvent, type RoleDetachedEvent, RoleDoesNotExist, RoleInput, RoleName, RolePermissionLink, RoleRbac, type ScopeOptions, Subject, SubjectRbac, type SyncDefinition, type SyncOptions, type SyncPermissionChange, type SyncResult, type SyncRoleChange, type SyncRolePermissions, type SyncRoleUpdate, TeamId, VERSION, createRbac, parseWildcardPermission, wildcardImplies };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as Subject, R as Role, T as TeamId, P as Permission, a as RbacTypeConfig, D as DefaultRbacTypes, b as
|
|
1
|
+
import { S as Subject, R as Role, T as TeamId, P as Permission, a as RbacTypeConfig, D as DefaultRbacTypes, b as PermissionName, c as RoleName, d as RbacAdapter, e as RoleInput, M as Many, f as PermissionInput, I as Id, g as RbacSnapshot, F as FindPermissionsQuery, h as FindRolesQuery, i as RolePermissionLink } from './adapter-XWQmXahX.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Cache used to store each subject's resolved roles & permissions.
|
|
@@ -105,6 +105,83 @@ declare class RbacEmitter {
|
|
|
105
105
|
}): Promise<void>;
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
/** The permissions of a role in a {@link SyncDefinition}: an explicit list, or `'*'` for every permission of the guard. */
|
|
109
|
+
type SyncRolePermissions<T extends RbacTypeConfig = DefaultRbacTypes> = readonly PermissionName<T>[] | '*';
|
|
110
|
+
/**
|
|
111
|
+
* Declarative description of the roles & permissions of ONE guard (and optionally one team).
|
|
112
|
+
*
|
|
113
|
+
* ```ts
|
|
114
|
+
* await rbac.sync({
|
|
115
|
+
* permissions: ['edit articles', 'delete articles'],
|
|
116
|
+
* roles: { admin: '*', writer: ['edit articles'] },
|
|
117
|
+
* })
|
|
118
|
+
* ```
|
|
119
|
+
*
|
|
120
|
+
* Pass an array of definitions to sync several guards / teams at once.
|
|
121
|
+
*/
|
|
122
|
+
interface SyncDefinition<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
123
|
+
/** Guard of this block. Default: the `guard` option, then `defaultGuard`. */
|
|
124
|
+
guard?: string;
|
|
125
|
+
/** Team of the roles in this block (requires `teams: true`). Default: the `team` option, then global (`null`). */
|
|
126
|
+
team?: TeamId;
|
|
127
|
+
/** Permissions of the guard. Permissions referenced by a role are created too, even if not listed here. */
|
|
128
|
+
permissions?: readonly PermissionName<T>[];
|
|
129
|
+
/** Roles and their permissions. Each role's permissions are synced (replaced) to exactly this list. */
|
|
130
|
+
roles?: {
|
|
131
|
+
readonly [R in RoleName<T>]?: SyncRolePermissions<T>;
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
interface SyncOptions {
|
|
135
|
+
/** Default guard for definitions without a `guard`. Default: `defaultGuard`. */
|
|
136
|
+
guard?: string;
|
|
137
|
+
/** Default team for definitions without a `team`. */
|
|
138
|
+
team?: TeamId;
|
|
139
|
+
/**
|
|
140
|
+
* Delete roles & permissions that are not in the definition. Roles are pruned per guard + team
|
|
141
|
+
* scope present in the definition; permissions (which are guard-wide) only for guards that have a
|
|
142
|
+
* global (team-less) definition. Other guards and teams are never touched. Default: `false`.
|
|
143
|
+
*/
|
|
144
|
+
prune?: boolean;
|
|
145
|
+
/** Compute and return the plan without writing anything. Default: `false`. */
|
|
146
|
+
dryRun?: boolean;
|
|
147
|
+
}
|
|
148
|
+
interface SyncPermissionChange {
|
|
149
|
+
name: string;
|
|
150
|
+
guard: string;
|
|
151
|
+
}
|
|
152
|
+
interface SyncRoleChange {
|
|
153
|
+
name: string;
|
|
154
|
+
guard: string;
|
|
155
|
+
team: TeamId;
|
|
156
|
+
/** Permissions of the role: given to a created role / held by a deleted role. */
|
|
157
|
+
permissions: string[];
|
|
158
|
+
}
|
|
159
|
+
interface SyncRoleUpdate {
|
|
160
|
+
name: string;
|
|
161
|
+
guard: string;
|
|
162
|
+
team: TeamId;
|
|
163
|
+
/** Permissions newly given to the role. */
|
|
164
|
+
attached: string[];
|
|
165
|
+
/** Permissions taken away from the role. */
|
|
166
|
+
detached: string[];
|
|
167
|
+
}
|
|
168
|
+
/** What {@link Rbac.sync} did — or, with `dryRun`, would do. */
|
|
169
|
+
interface SyncResult {
|
|
170
|
+
dryRun: boolean;
|
|
171
|
+
created: {
|
|
172
|
+
permissions: SyncPermissionChange[];
|
|
173
|
+
roles: SyncRoleChange[];
|
|
174
|
+
};
|
|
175
|
+
/** Existing roles whose permissions changed. */
|
|
176
|
+
updated: {
|
|
177
|
+
roles: SyncRoleUpdate[];
|
|
178
|
+
};
|
|
179
|
+
deleted: {
|
|
180
|
+
permissions: SyncPermissionChange[];
|
|
181
|
+
roles: SyncRoleChange[];
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
108
185
|
interface GuardOptions {
|
|
109
186
|
/** Guard name, e.g. `web` or `api`. Defaults to `defaultGuard`. */
|
|
110
187
|
guard?: string;
|
|
@@ -195,6 +272,27 @@ declare class Rbac<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
|
195
272
|
/** Lists roles visible in the given scope (global roles + roles of the given team). */
|
|
196
273
|
getRoles(options?: ScopeOptions): Promise<Role[]>;
|
|
197
274
|
deleteRole(role: RoleInput<RoleName<T>>, options?: ScopeOptions): Promise<void>;
|
|
275
|
+
/**
|
|
276
|
+
* Declaratively seeds roles & permissions (spatie's "Database Seeding"): creates missing
|
|
277
|
+
* permissions and roles, and syncs each role's permissions to exactly the given list.
|
|
278
|
+
* Idempotent — running it again changes nothing. Uses the regular engine methods, so the
|
|
279
|
+
* usual events fire.
|
|
280
|
+
*
|
|
281
|
+
* ```ts
|
|
282
|
+
* await rbac.sync({
|
|
283
|
+
* permissions: ['edit articles', 'delete articles'],
|
|
284
|
+
* roles: { admin: '*', writer: ['edit articles'] },
|
|
285
|
+
* })
|
|
286
|
+
* ```
|
|
287
|
+
*
|
|
288
|
+
* - `'*'` gives a role every permission of its guard (after the sync).
|
|
289
|
+
* - Pass an array of definitions (each with its own `guard` / `team`) to sync several scopes.
|
|
290
|
+
* - `prune: true` deletes roles & permissions of the synced scopes that aren't in the definition.
|
|
291
|
+
* - `dryRun: true` returns the plan without writing anything.
|
|
292
|
+
*
|
|
293
|
+
* Not atomic: adapters have no transactions, so a failure midway leaves the earlier changes.
|
|
294
|
+
*/
|
|
295
|
+
sync(definition: SyncDefinition<T> | readonly SyncDefinition<T>[], options?: SyncOptions): Promise<SyncResult>;
|
|
198
296
|
/**
|
|
199
297
|
* Ids of subjects of `subjectType` that have ANY of the given roles in the given scope
|
|
200
298
|
* (spatie: `User::role('writer')->get()`). Throws `RoleDoesNotExist` for unknown roles.
|
|
@@ -356,7 +454,7 @@ declare class MemoryAdapter implements RbacAdapter {
|
|
|
356
454
|
private static reverse;
|
|
357
455
|
}
|
|
358
456
|
|
|
359
|
-
type RbacErrorCode = 'PERMISSION_DOES_NOT_EXIST' | 'PERMISSION_ALREADY_EXISTS' | 'ROLE_DOES_NOT_EXIST' | 'ROLE_ALREADY_EXISTS' | 'GUARD_DOES_NOT_MATCH' | 'TEAM_DOES_NOT_MATCH' | 'TEAMS_NOT_ENABLED' | 'INVALID_NAME' | 'INVALID_WILDCARD_PERMISSION';
|
|
457
|
+
type RbacErrorCode = 'PERMISSION_DOES_NOT_EXIST' | 'PERMISSION_ALREADY_EXISTS' | 'ROLE_DOES_NOT_EXIST' | 'ROLE_ALREADY_EXISTS' | 'GUARD_DOES_NOT_MATCH' | 'TEAM_DOES_NOT_MATCH' | 'TEAMS_NOT_ENABLED' | 'INVALID_NAME' | 'INVALID_WILDCARD_PERMISSION' | 'INVALID_SYNC_DEFINITION';
|
|
360
458
|
declare class RbacError extends Error {
|
|
361
459
|
readonly code: RbacErrorCode;
|
|
362
460
|
constructor(code: RbacErrorCode, message: string);
|
|
@@ -406,4 +504,4 @@ declare function wildcardImplies(granted: string, required: string): boolean;
|
|
|
406
504
|
/** Version of this package (read from package.json at build time). */
|
|
407
505
|
declare const VERSION: string;
|
|
408
506
|
|
|
409
|
-
export { type BeforeContext, type BeforeHook, type CacheStore, DefaultRbacTypes, FindPermissionsQuery, FindRolesQuery, GuardDoesNotMatch, type GuardOptions, Id, InvalidWildcardPermission, Many, MemoryAdapter, MemoryCache, Permission, PermissionAlreadyExists, type PermissionAttachedEvent, type PermissionCreatedEvent, type PermissionDeletedEvent, type PermissionDetachedEvent, PermissionDoesNotExist, PermissionInput, PermissionName, type PermissionTarget, Rbac, RbacAdapter, RbacError, type RbacErrorCode, type RbacEvent, type RbacEventListener, type RbacEventMap, type RbacEventName, type RbacOptions, RbacSnapshot, RbacTypeConfig, Role, RoleAlreadyExists, type RoleAttachedEvent, type RoleCreatedEvent, type RoleDeletedEvent, type RoleDetachedEvent, RoleDoesNotExist, RoleInput, RoleName, RolePermissionLink, RoleRbac, type ScopeOptions, Subject, SubjectRbac, TeamId, VERSION, createRbac, parseWildcardPermission, wildcardImplies };
|
|
507
|
+
export { type BeforeContext, type BeforeHook, type CacheStore, DefaultRbacTypes, FindPermissionsQuery, FindRolesQuery, GuardDoesNotMatch, type GuardOptions, Id, InvalidWildcardPermission, Many, MemoryAdapter, MemoryCache, Permission, PermissionAlreadyExists, type PermissionAttachedEvent, type PermissionCreatedEvent, type PermissionDeletedEvent, type PermissionDetachedEvent, PermissionDoesNotExist, PermissionInput, PermissionName, type PermissionTarget, Rbac, RbacAdapter, RbacError, type RbacErrorCode, type RbacEvent, type RbacEventListener, type RbacEventMap, type RbacEventName, type RbacOptions, RbacSnapshot, RbacTypeConfig, Role, RoleAlreadyExists, type RoleAttachedEvent, type RoleCreatedEvent, type RoleDeletedEvent, type RoleDetachedEvent, RoleDoesNotExist, RoleInput, RoleName, RolePermissionLink, RoleRbac, type ScopeOptions, Subject, SubjectRbac, type SyncDefinition, type SyncOptions, type SyncPermissionChange, type SyncResult, type SyncRoleChange, type SyncRolePermissions, type SyncRoleUpdate, TeamId, VERSION, createRbac, parseWildcardPermission, wildcardImplies };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { GuardDoesNotMatch, InvalidWildcardPermission, MemoryCache, PermissionAlreadyExists, PermissionDoesNotExist, Rbac, RbacError, RoleAlreadyExists, RoleDoesNotExist, RoleRbac, SubjectRbac, createRbac, parseWildcardPermission, wildcardImplies } from './chunk-
|
|
1
|
+
export { GuardDoesNotMatch, InvalidWildcardPermission, MemoryCache, PermissionAlreadyExists, PermissionDoesNotExist, Rbac, RbacError, RoleAlreadyExists, RoleDoesNotExist, RoleRbac, SubjectRbac, createRbac, parseWildcardPermission, wildcardImplies } from './chunk-7NQQUZ3Q.js';
|
|
2
2
|
|
|
3
3
|
// package.json
|
|
4
|
-
var version = "0.
|
|
4
|
+
var version = "0.3.0";
|
|
5
5
|
|
|
6
6
|
// src/adapters/memory.ts
|
|
7
7
|
var key = (id) => id === null ? "\0null" : String(id);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json","../src/adapters/memory.ts","../src/index.ts"],"names":[],"mappings":";;;AAEE,IAAA,OAAA,GAAW,OAAA;;;ACQb,IAAM,MAAM,CAAC,EAAA,KAA2B,OAAO,IAAA,GAAO,QAAA,GAAe,OAAO,EAAE,CAAA;AAC9E,IAAM,IAAA,GAAO,CAAC,CAAA,EAAc,CAAA,KAA0B,IAAI,CAAC,CAAA,KAAM,IAAI,CAAC,CAAA;AACtE,IAAM,KAAA,GAAQ,CAAC,GAAA,EAA6B,EAAA,KAA2B,GAAA,CAAI,IAAA,CAAK,CAAC,CAAA,KAAM,IAAA,CAAK,CAAA,EAAG,EAAE,CAAC,CAAA;AAClG,IAAM,SAAA,GAAY,CAAC,CAAA,EAAgB,CAAA,KAAwB,CAAA,CAAE,WAAA,KAAgB,CAAA,CAAE,IAAA,IAAQ,IAAA,CAAK,CAAA,CAAE,SAAA,EAAW,CAAA,CAAE,EAAE,CAAA;AAMtG,IAAM,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,MAAA;AAAA,MACX,CAAC,CAAA,KAAM,EAAE,SAAA,CAAU,CAAA,EAAG,OAAO,CAAA,IAAK,IAAA,CAAK,CAAA,CAAE,MAAA,EAAQ,MAAM,CAAA,KAAM,GAAA,KAAQ,UAAa,KAAA,CAAM,GAAA,EAAK,EAAE,QAAQ,CAAA,CAAA;AAAA,KACzG;AAAA,EACF;AAAA,EAEA,OAAe,OAAA,CAAQ,KAAA,EAAsB,WAAA,EAAqB,KAAoB,MAAA,EAAsB;AAC1G,IAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,IAAA,MAAM,MAAY,EAAC;AACnB,IAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,MAAA,IAAI,CAAA,CAAE,WAAA,KAAgB,WAAA,IAAe,CAAC,KAAK,CAAA,CAAE,MAAA,EAAQ,MAAM,CAAA,IAAK,CAAC,KAAA,CAAM,GAAA,EAAK,CAAA,CAAE,QAAQ,CAAA,EAAG;AACzF,MAAA,MAAM,CAAA,GAAI,GAAA,CAAI,CAAA,CAAE,SAAS,CAAA;AACzB,MAAA,IAAI,IAAA,CAAK,GAAA,CAAI,CAAC,CAAA,EAAG;AACjB,MAAA,IAAA,CAAK,IAAI,CAAC,CAAA;AACV,MAAA,GAAA,CAAI,IAAA,CAAK,EAAE,SAAS,CAAA;AAAA,IACtB;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACF;;;ACvGO,IAAM,OAAA,GAAkB","file":"index.js","sourcesContent":["{\n \"name\": \"@anievo-id/rbac-evolution\",\n \"version\": \"0.2.1\",\n \"description\": \"Framework-agnostic RBAC engine for rbac-evolution — roles, permissions, guards.\",\n \"license\": \"MIT\",\n \"author\": \"AniEvo-ID (https://github.com/AniEvo-ID)\",\n \"homepage\": \"https://github.com/AniEvo-ID/rbac-evolution/tree/main/packages/core#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/AniEvo-ID/rbac-evolution/issues\"\n },\n \"type\": \"module\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/AniEvo-ID/rbac-evolution.git\",\n \"directory\": \"packages/core\"\n },\n \"keywords\": [\n \"rbac\",\n \"permissions\",\n \"roles\",\n \"authorization\",\n \"acl\",\n \"typescript\"\n ],\n \"sideEffects\": false,\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./testing\": {\n \"import\": {\n \"types\": \"./dist/testing.d.ts\",\n \"default\": \"./dist/testing.js\"\n },\n \"require\": {\n \"types\": \"./dist/testing.d.cts\",\n \"default\": \"./dist/testing.cjs\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run --passWithNoTests\",\n \"clean\": \"rm -rf dist .turbo\"\n },\n \"devDependencies\": {\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.7.0\",\n \"vitest\": \"^2.1.0\"\n },\n \"peerDependencies\": {\n \"vitest\": \">=2\"\n },\n \"peerDependenciesMeta\": {\n \"vitest\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=20\"\n }\n}\n","import type { FindPermissionsQuery, FindRolesQuery, RbacAdapter, RolePermissionLink } from '../adapter'\nimport type { Id, Permission, Role, Subject, TeamId } from '../types'\n\ninterface SubjectLink {\n subjectType: string\n subjectId: Id\n targetId: Id\n teamId: TeamId\n}\n\nconst key = (id: Id | null): string => (id === null ? '\\u0000null' : String(id))\nconst same = (a: Id | null, b: Id | null): boolean => key(a) === key(b)\nconst inIds = (ids: readonly (Id | null)[], id: Id | null): boolean => ids.some((x) => same(x, id))\nconst isSubject = (l: SubjectLink, s: Subject): boolean => l.subjectType === s.type && same(l.subjectId, s.id)\n\n/**\n * In-memory adapter. Great for tests, prototypes, or apps whose roles are defined in code.\n * Data is lost when the process exits.\n */\nexport class MemoryAdapter implements RbacAdapter {\n private nextId = 1\n private permissions: Permission[] = []\n private roles: Role[] = []\n private rolePermissions: RolePermissionLink[] = []\n private subjectRoles: SubjectLink[] = []\n private subjectPermissions: SubjectLink[] = []\n\n // ---------------------------------------------------------------- permissions\n\n async createPermission(data: { name: string; guardName: string }): Promise<Permission> {\n const permission: Permission = { id: this.nextId++, name: data.name, guardName: data.guardName }\n this.permissions.push(permission)\n return { ...permission }\n }\n\n async findPermissions(query: FindPermissionsQuery = {}): Promise<Permission[]> {\n return this.permissions\n .filter(\n (p) =>\n (query.ids === undefined || inIds(query.ids, p.id)) &&\n (query.names === undefined || query.names.includes(p.name)) &&\n (query.guardName === undefined || p.guardName === query.guardName),\n )\n .map((p) => ({ ...p }))\n }\n\n async deletePermission(id: Id): Promise<void> {\n this.permissions = this.permissions.filter((p) => !same(p.id, id))\n this.rolePermissions = this.rolePermissions.filter((l) => !same(l.permissionId, id))\n this.subjectPermissions = this.subjectPermissions.filter((l) => !same(l.targetId, id))\n }\n\n // ---------------------------------------------------------------------- roles\n\n async createRole(data: { name: string; guardName: string; teamId: TeamId }): Promise<Role> {\n const role: Role = { id: this.nextId++, name: data.name, guardName: data.guardName, teamId: data.teamId }\n this.roles.push(role)\n return { ...role }\n }\n\n async findRoles(query: FindRolesQuery = {}): Promise<Role[]> {\n return this.roles\n .filter(\n (r) =>\n (query.ids === undefined || inIds(query.ids, r.id)) &&\n (query.names === undefined || query.names.includes(r.name)) &&\n (query.guardName === undefined || r.guardName === query.guardName) &&\n (query.teamIds === undefined || inIds(query.teamIds, r.teamId)),\n )\n .map((r) => ({ ...r }))\n }\n\n async deleteRole(id: Id): Promise<void> {\n this.roles = this.roles.filter((r) => !same(r.id, id))\n this.rolePermissions = this.rolePermissions.filter((l) => !same(l.roleId, id))\n this.subjectRoles = this.subjectRoles.filter((l) => !same(l.targetId, id))\n }\n\n // ---------------------------------------------------------- role ↔ permission\n\n async getRolePermissionLinks(roleIds: readonly Id[]): Promise<RolePermissionLink[]> {\n return this.rolePermissions.filter((l) => inIds(roleIds, l.roleId)).map((l) => ({ ...l }))\n }\n\n async attachRolePermissions(roleId: Id, permissionIds: readonly Id[]): Promise<void> {\n for (const permissionId of permissionIds) {\n const exists = this.rolePermissions.some((l) => same(l.roleId, roleId) && same(l.permissionId, permissionId))\n if (!exists) this.rolePermissions.push({ roleId, permissionId })\n }\n }\n\n async detachRolePermissions(roleId: Id, permissionIds?: readonly Id[]): Promise<void> {\n this.rolePermissions = this.rolePermissions.filter(\n (l) => !(same(l.roleId, roleId) && (permissionIds === undefined || inIds(permissionIds, l.permissionId))),\n )\n }\n\n // ------------------------------------------------------------- subject links\n\n async getSubjectRoleIds(subject: Subject, teamId: TeamId): Promise<Id[]> {\n return MemoryAdapter.getLinks(this.subjectRoles, subject, teamId)\n }\n\n async attachSubjectRoles(subject: Subject, roleIds: readonly Id[], teamId: TeamId): Promise<void> {\n MemoryAdapter.attach(this.subjectRoles, subject, roleIds, teamId)\n }\n\n async detachSubjectRoles(subject: Subject, roleIds: readonly Id[] | undefined, teamId: TeamId): Promise<void> {\n this.subjectRoles = MemoryAdapter.detach(this.subjectRoles, subject, roleIds, teamId)\n }\n\n async getSubjectPermissionIds(subject: Subject, teamId: TeamId): Promise<Id[]> {\n return MemoryAdapter.getLinks(this.subjectPermissions, subject, teamId)\n }\n\n async attachSubjectPermissions(subject: Subject, permissionIds: readonly Id[], teamId: TeamId): Promise<void> {\n MemoryAdapter.attach(this.subjectPermissions, subject, permissionIds, teamId)\n }\n\n async detachSubjectPermissions(\n subject: Subject,\n permissionIds: readonly Id[] | undefined,\n teamId: TeamId,\n ): Promise<void> {\n this.subjectPermissions = MemoryAdapter.detach(this.subjectPermissions, subject, permissionIds, teamId)\n }\n\n async getSubjectIdsWithRoles(subjectType: string, roleIds: readonly Id[], teamId: TeamId): Promise<Id[]> {\n return MemoryAdapter.reverse(this.subjectRoles, subjectType, roleIds, teamId)\n }\n\n async getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId): Promise<Id[]> {\n return MemoryAdapter.reverse(this.subjectPermissions, subjectType, permissionIds, teamId)\n }\n\n // -------------------------------------------------------------------- helpers\n\n private static getLinks(links: SubjectLink[], subject: Subject, teamId: TeamId): Id[] {\n return links.filter((l) => isSubject(l, subject) && same(l.teamId, teamId)).map((l) => l.targetId)\n }\n\n private static attach(links: SubjectLink[], subject: Subject, ids: readonly Id[], teamId: TeamId): void {\n for (const targetId of ids) {\n const exists = links.some((l) => isSubject(l, subject) && same(l.targetId, targetId) && same(l.teamId, teamId))\n if (!exists) links.push({ subjectType: subject.type, subjectId: subject.id, targetId, teamId })\n }\n }\n\n private static detach(\n links: SubjectLink[],\n subject: Subject,\n ids: readonly Id[] | undefined,\n teamId: TeamId,\n ): SubjectLink[] {\n return links.filter(\n (l) => !(isSubject(l, subject) && same(l.teamId, teamId) && (ids === undefined || inIds(ids, l.targetId))),\n )\n }\n\n private static reverse(links: SubjectLink[], subjectType: string, ids: readonly Id[], teamId: TeamId): Id[] {\n const seen = new Set<string>()\n const out: Id[] = []\n for (const l of links) {\n if (l.subjectType !== subjectType || !same(l.teamId, teamId) || !inIds(ids, l.targetId)) continue\n const k = key(l.subjectId)\n if (seen.has(k)) continue\n seen.add(k)\n out.push(l.subjectId)\n }\n return out\n }\n}\n","/**\n * @anievo-id/rbac-evolution\n *\n * Framework-agnostic RBAC engine — roles, permissions, guards, wildcards and teams.\n */\n\nimport { version } from '../package.json'\n\nexport { createRbac, Rbac, RoleRbac, SubjectRbac } from './rbac'\nexport type { BeforeContext, BeforeHook, GuardOptions, RbacOptions, ScopeOptions } from './rbac'\n\nexport type {\n PermissionAttachedEvent,\n PermissionCreatedEvent,\n PermissionDeletedEvent,\n PermissionDetachedEvent,\n PermissionTarget,\n RbacEvent,\n RbacEventListener,\n RbacEventMap,\n RbacEventName,\n RoleAttachedEvent,\n RoleCreatedEvent,\n RoleDeletedEvent,\n RoleDetachedEvent,\n} from './events'\n\nexport type {\n FindPermissionsQuery,\n FindRolesQuery,\n RbacAdapter,\n RolePermissionLink,\n} from './adapter'\nexport { MemoryAdapter } from './adapters/memory'\n\nexport { MemoryCache } from './cache'\nexport type { CacheStore } from './cache'\n\nexport {\n GuardDoesNotMatch,\n InvalidWildcardPermission,\n PermissionAlreadyExists,\n PermissionDoesNotExist,\n RbacError,\n RoleAlreadyExists,\n RoleDoesNotExist,\n} from './errors'\nexport type { RbacErrorCode } from './errors'\n\nexport { parseWildcardPermission, wildcardImplies } from './wildcard'\n\nexport type {\n DefaultRbacTypes,\n Id,\n Many,\n Permission,\n PermissionInput,\n PermissionName,\n RbacSnapshot,\n RbacTypeConfig,\n Role,\n RoleInput,\n RoleName,\n Subject,\n TeamId,\n} from './types'\n\n/** Version of this package (read from package.json at build time). */\nexport const VERSION: string = version\n"]}
|
|
1
|
+
{"version":3,"sources":["../package.json","../src/adapters/memory.ts","../src/index.ts"],"names":[],"mappings":";;;AAEE,IAAA,OAAA,GAAW,OAAA;;;ACQb,IAAM,MAAM,CAAC,EAAA,KAA2B,OAAO,IAAA,GAAO,QAAA,GAAe,OAAO,EAAE,CAAA;AAC9E,IAAM,IAAA,GAAO,CAAC,CAAA,EAAc,CAAA,KAA0B,IAAI,CAAC,CAAA,KAAM,IAAI,CAAC,CAAA;AACtE,IAAM,KAAA,GAAQ,CAAC,GAAA,EAA6B,EAAA,KAA2B,GAAA,CAAI,IAAA,CAAK,CAAC,CAAA,KAAM,IAAA,CAAK,CAAA,EAAG,EAAE,CAAC,CAAA;AAClG,IAAM,SAAA,GAAY,CAAC,CAAA,EAAgB,CAAA,KAAwB,CAAA,CAAE,WAAA,KAAgB,CAAA,CAAE,IAAA,IAAQ,IAAA,CAAK,CAA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ACA,OAAA,EACA,KACA,MAAA,EACe;AACf,IAAA,OAAO,KAAA,CAAM,MAAA;AAAA,MACX,CAAC,CAAA,KAAM,EAAE,SAAA,CAAU,CAAA,EAAG,OAAO,CAAA,IAAK,IAAA,CAAK,CAAA,CAAE,MAAA,EAAQ,MAAM,CAAA,KAAM,GAAA,KAAQ,UAAa,KAAA,CAAM,GAAA,EAAK,EAAE,QAAQ,CAAA,CAAA;AAAA,KACzG;AAAA,EACF;AAAA,EAEA,OAAe,OAAA,CAAQ,KAAA,EAAsB,WAAA,EAAqB,KAAoB,MAAA,EAAsB;AAC1G,IAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,IAAA,MAAM,MAAY,EAAC;AACnB,IAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,MAAA,IAAI,CAAA,CAAE,WAAA,KAAgB,WAAA,IAAe,CAAC,KAAK,CAAA,CAAE,MAAA,EAAQ,MAAM,CAAA,IAAK,CAAC,KAAA,CAAM,GAAA,EAAK,CAAA,CAAE,QAAQ,CAAA,EAAG;AACzF,MAAA,MAAM,CAAA,GAAI,GAAA,CAAI,CAAA,CAAE,SAAS,CAAA;AACzB,MAAA,IAAI,IAAA,CAAK,GAAA,CAAI,CAAC,CAAA,EAAG;AACjB,MAAA,IAAA,CAAK,IAAI,CAAC,CAAA;AACV,MAAA,GAAA,CAAI,IAAA,CAAK,EAAE,SAAS,CAAA;AAAA,IACtB;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACF;;;AC9FO,IAAM,OAAA,GAAkB","file":"index.js","sourcesContent":["{\n \"name\": \"@anievo-id/rbac-evolution\",\n \"version\": \"0.3.0\",\n \"description\": \"Framework-agnostic RBAC engine for rbac-evolution — roles, permissions, guards.\",\n \"license\": \"MIT\",\n \"author\": \"AniEvo-ID (https://github.com/AniEvo-ID)\",\n \"homepage\": \"https://github.com/AniEvo-ID/rbac-evolution/tree/main/packages/core#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/AniEvo-ID/rbac-evolution/issues\"\n },\n \"type\": \"module\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/AniEvo-ID/rbac-evolution.git\",\n \"directory\": \"packages/core\"\n },\n \"keywords\": [\n \"rbac\",\n \"permissions\",\n \"roles\",\n \"authorization\",\n \"acl\",\n \"typescript\"\n ],\n \"sideEffects\": false,\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./testing\": {\n \"import\": {\n \"types\": \"./dist/testing.d.ts\",\n \"default\": \"./dist/testing.js\"\n },\n \"require\": {\n \"types\": \"./dist/testing.d.cts\",\n \"default\": \"./dist/testing.cjs\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run --passWithNoTests\",\n \"clean\": \"rm -rf dist .turbo\"\n },\n \"devDependencies\": {\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.7.0\",\n \"vitest\": \"^2.1.0\"\n },\n \"peerDependencies\": {\n \"vitest\": \">=2\"\n },\n \"peerDependenciesMeta\": {\n \"vitest\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=20\"\n }\n}\n","import type { FindPermissionsQuery, FindRolesQuery, RbacAdapter, RolePermissionLink } from '../adapter'\nimport type { Id, Permission, Role, Subject, TeamId } from '../types'\n\ninterface SubjectLink {\n subjectType: string\n subjectId: Id\n targetId: Id\n teamId: TeamId\n}\n\nconst key = (id: Id | null): string => (id === null ? '\\u0000null' : String(id))\nconst same = (a: Id | null, b: Id | null): boolean => key(a) === key(b)\nconst inIds = (ids: readonly (Id | null)[], id: Id | null): boolean => ids.some((x) => same(x, id))\nconst isSubject = (l: SubjectLink, s: Subject): boolean => l.subjectType === s.type && same(l.subjectId, s.id)\n\n/**\n * In-memory adapter. Great for tests, prototypes, or apps whose roles are defined in code.\n * Data is lost when the process exits.\n */\nexport class MemoryAdapter implements RbacAdapter {\n private nextId = 1\n private permissions: Permission[] = []\n private roles: Role[] = []\n private rolePermissions: RolePermissionLink[] = []\n private subjectRoles: SubjectLink[] = []\n private subjectPermissions: SubjectLink[] = []\n\n // ---------------------------------------------------------------- permissions\n\n async createPermission(data: { name: string; guardName: string }): Promise<Permission> {\n const permission: Permission = { id: this.nextId++, name: data.name, guardName: data.guardName }\n this.permissions.push(permission)\n return { ...permission }\n }\n\n async findPermissions(query: FindPermissionsQuery = {}): Promise<Permission[]> {\n return this.permissions\n .filter(\n (p) =>\n (query.ids === undefined || inIds(query.ids, p.id)) &&\n (query.names === undefined || query.names.includes(p.name)) &&\n (query.guardName === undefined || p.guardName === query.guardName),\n )\n .map((p) => ({ ...p }))\n }\n\n async deletePermission(id: Id): Promise<void> {\n this.permissions = this.permissions.filter((p) => !same(p.id, id))\n this.rolePermissions = this.rolePermissions.filter((l) => !same(l.permissionId, id))\n this.subjectPermissions = this.subjectPermissions.filter((l) => !same(l.targetId, id))\n }\n\n // ---------------------------------------------------------------------- roles\n\n async createRole(data: { name: string; guardName: string; teamId: TeamId }): Promise<Role> {\n const role: Role = { id: this.nextId++, name: data.name, guardName: data.guardName, teamId: data.teamId }\n this.roles.push(role)\n return { ...role }\n }\n\n async findRoles(query: FindRolesQuery = {}): Promise<Role[]> {\n return this.roles\n .filter(\n (r) =>\n (query.ids === undefined || inIds(query.ids, r.id)) &&\n (query.names === undefined || query.names.includes(r.name)) &&\n (query.guardName === undefined || r.guardName === query.guardName) &&\n (query.teamIds === undefined || inIds(query.teamIds, r.teamId)),\n )\n .map((r) => ({ ...r }))\n }\n\n async deleteRole(id: Id): Promise<void> {\n this.roles = this.roles.filter((r) => !same(r.id, id))\n this.rolePermissions = this.rolePermissions.filter((l) => !same(l.roleId, id))\n this.subjectRoles = this.subjectRoles.filter((l) => !same(l.targetId, id))\n }\n\n // ---------------------------------------------------------- role ↔ permission\n\n async getRolePermissionLinks(roleIds: readonly Id[]): Promise<RolePermissionLink[]> {\n return this.rolePermissions.filter((l) => inIds(roleIds, l.roleId)).map((l) => ({ ...l }))\n }\n\n async attachRolePermissions(roleId: Id, permissionIds: readonly Id[]): Promise<void> {\n for (const permissionId of permissionIds) {\n const exists = this.rolePermissions.some((l) => same(l.roleId, roleId) && same(l.permissionId, permissionId))\n if (!exists) this.rolePermissions.push({ roleId, permissionId })\n }\n }\n\n async detachRolePermissions(roleId: Id, permissionIds?: readonly Id[]): Promise<void> {\n this.rolePermissions = this.rolePermissions.filter(\n (l) => !(same(l.roleId, roleId) && (permissionIds === undefined || inIds(permissionIds, l.permissionId))),\n )\n }\n\n // ------------------------------------------------------------- subject links\n\n async getSubjectRoleIds(subject: Subject, teamId: TeamId): Promise<Id[]> {\n return MemoryAdapter.getLinks(this.subjectRoles, subject, teamId)\n }\n\n async attachSubjectRoles(subject: Subject, roleIds: readonly Id[], teamId: TeamId): Promise<void> {\n MemoryAdapter.attach(this.subjectRoles, subject, roleIds, teamId)\n }\n\n async detachSubjectRoles(subject: Subject, roleIds: readonly Id[] | undefined, teamId: TeamId): Promise<void> {\n this.subjectRoles = MemoryAdapter.detach(this.subjectRoles, subject, roleIds, teamId)\n }\n\n async getSubjectPermissionIds(subject: Subject, teamId: TeamId): Promise<Id[]> {\n return MemoryAdapter.getLinks(this.subjectPermissions, subject, teamId)\n }\n\n async attachSubjectPermissions(subject: Subject, permissionIds: readonly Id[], teamId: TeamId): Promise<void> {\n MemoryAdapter.attach(this.subjectPermissions, subject, permissionIds, teamId)\n }\n\n async detachSubjectPermissions(\n subject: Subject,\n permissionIds: readonly Id[] | undefined,\n teamId: TeamId,\n ): Promise<void> {\n this.subjectPermissions = MemoryAdapter.detach(this.subjectPermissions, subject, permissionIds, teamId)\n }\n\n async getSubjectIdsWithRoles(subjectType: string, roleIds: readonly Id[], teamId: TeamId): Promise<Id[]> {\n return MemoryAdapter.reverse(this.subjectRoles, subjectType, roleIds, teamId)\n }\n\n async getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId): Promise<Id[]> {\n return MemoryAdapter.reverse(this.subjectPermissions, subjectType, permissionIds, teamId)\n }\n\n // -------------------------------------------------------------------- helpers\n\n private static getLinks(links: SubjectLink[], subject: Subject, teamId: TeamId): Id[] {\n return links.filter((l) => isSubject(l, subject) && same(l.teamId, teamId)).map((l) => l.targetId)\n }\n\n private static attach(links: SubjectLink[], subject: Subject, ids: readonly Id[], teamId: TeamId): void {\n for (const targetId of ids) {\n const exists = links.some((l) => isSubject(l, subject) && same(l.targetId, targetId) && same(l.teamId, teamId))\n if (!exists) links.push({ subjectType: subject.type, subjectId: subject.id, targetId, teamId })\n }\n }\n\n private static detach(\n links: SubjectLink[],\n subject: Subject,\n ids: readonly Id[] | undefined,\n teamId: TeamId,\n ): SubjectLink[] {\n return links.filter(\n (l) => !(isSubject(l, subject) && same(l.teamId, teamId) && (ids === undefined || inIds(ids, l.targetId))),\n )\n }\n\n private static reverse(links: SubjectLink[], subjectType: string, ids: readonly Id[], teamId: TeamId): Id[] {\n const seen = new Set<string>()\n const out: Id[] = []\n for (const l of links) {\n if (l.subjectType !== subjectType || !same(l.teamId, teamId) || !inIds(ids, l.targetId)) continue\n const k = key(l.subjectId)\n if (seen.has(k)) continue\n seen.add(k)\n out.push(l.subjectId)\n }\n return out\n }\n}\n","/**\n * @anievo-id/rbac-evolution\n *\n * Framework-agnostic RBAC engine — roles, permissions, guards, wildcards and teams.\n */\n\nimport { version } from '../package.json'\n\nexport { createRbac, Rbac, RoleRbac, SubjectRbac } from './rbac'\nexport type { BeforeContext, BeforeHook, GuardOptions, RbacOptions, ScopeOptions } from './rbac'\nexport type {\n SyncDefinition,\n SyncOptions,\n SyncPermissionChange,\n SyncResult,\n SyncRoleChange,\n SyncRolePermissions,\n SyncRoleUpdate,\n} from './sync'\n\nexport type {\n PermissionAttachedEvent,\n PermissionCreatedEvent,\n PermissionDeletedEvent,\n PermissionDetachedEvent,\n PermissionTarget,\n RbacEvent,\n RbacEventListener,\n RbacEventMap,\n RbacEventName,\n RoleAttachedEvent,\n RoleCreatedEvent,\n RoleDeletedEvent,\n RoleDetachedEvent,\n} from './events'\n\nexport type {\n FindPermissionsQuery,\n FindRolesQuery,\n RbacAdapter,\n RolePermissionLink,\n} from './adapter'\nexport { MemoryAdapter } from './adapters/memory'\n\nexport { MemoryCache } from './cache'\nexport type { CacheStore } from './cache'\n\nexport {\n GuardDoesNotMatch,\n InvalidWildcardPermission,\n PermissionAlreadyExists,\n PermissionDoesNotExist,\n RbacError,\n RoleAlreadyExists,\n RoleDoesNotExist,\n} from './errors'\nexport type { RbacErrorCode } from './errors'\n\nexport { parseWildcardPermission, wildcardImplies } from './wildcard'\n\nexport type {\n DefaultRbacTypes,\n Id,\n Many,\n Permission,\n PermissionInput,\n PermissionName,\n RbacSnapshot,\n RbacTypeConfig,\n Role,\n RoleInput,\n RoleName,\n Subject,\n TeamId,\n} from './types'\n\n/** Version of this package (read from package.json at build time). */\nexport const VERSION: string = version\n"]}
|
package/dist/testing.cjs
CHANGED
|
@@ -121,9 +121,164 @@ function wildcardImplies(granted, required) {
|
|
|
121
121
|
return true;
|
|
122
122
|
}
|
|
123
123
|
|
|
124
|
+
// src/sync.ts
|
|
125
|
+
var idKey = (id) => id === null ? "\0null" : String(id);
|
|
126
|
+
function invalid(message) {
|
|
127
|
+
return new RbacError("INVALID_SYNC_DEFINITION", message);
|
|
128
|
+
}
|
|
129
|
+
function cleanName(value, where) {
|
|
130
|
+
if (typeof value !== "string") throw invalid(`${where} must be a string, got ${typeof value}.`);
|
|
131
|
+
const name = value.trim();
|
|
132
|
+
if (name === "") throw new RbacError("INVALID_NAME", "Role and permission names must not be empty.");
|
|
133
|
+
return name;
|
|
134
|
+
}
|
|
135
|
+
function pushUnique(list, name) {
|
|
136
|
+
if (!list.includes(name)) list.push(name);
|
|
137
|
+
}
|
|
138
|
+
function normalize(rbac, definition, options) {
|
|
139
|
+
const list = Array.isArray(definition) ? definition : [definition];
|
|
140
|
+
const blocks = [];
|
|
141
|
+
list.forEach((raw, index) => {
|
|
142
|
+
const at = list.length > 1 ? `definition[${index}]` : "definition";
|
|
143
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw invalid(`${at} must be an object.`);
|
|
144
|
+
const def = raw;
|
|
145
|
+
const guardInput = def["guard"] ?? options.guard;
|
|
146
|
+
if (guardInput !== void 0 && typeof guardInput !== "string") throw invalid(`${at}.guard must be a string.`);
|
|
147
|
+
const guard = rbac.resolveGuard(guardInput === void 0 ? void 0 : cleanName(guardInput, `${at}.guard`));
|
|
148
|
+
const teamInput = def["team"] !== void 0 ? def["team"] : options.team;
|
|
149
|
+
if (teamInput !== void 0 && teamInput !== null && typeof teamInput !== "string" && typeof teamInput !== "number") {
|
|
150
|
+
throw invalid(`${at}.team must be a string, a number or null.`);
|
|
151
|
+
}
|
|
152
|
+
const team = rbac.resolveTeam(teamInput);
|
|
153
|
+
let block = blocks.find((b) => b.guard === guard && idKey(b.team) === idKey(team));
|
|
154
|
+
if (!block) {
|
|
155
|
+
block = { guard, team, permissions: [], roles: /* @__PURE__ */ new Map() };
|
|
156
|
+
blocks.push(block);
|
|
157
|
+
}
|
|
158
|
+
const permissions = def["permissions"];
|
|
159
|
+
if (permissions !== void 0) {
|
|
160
|
+
if (!Array.isArray(permissions)) throw invalid(`${at}.permissions must be an array of names.`);
|
|
161
|
+
for (const p of permissions) pushUnique(block.permissions, cleanName(p, `${at}.permissions[]`));
|
|
162
|
+
}
|
|
163
|
+
const roles = def["roles"];
|
|
164
|
+
if (roles !== void 0) {
|
|
165
|
+
if (typeof roles !== "object" || roles === null || Array.isArray(roles)) {
|
|
166
|
+
throw invalid(`${at}.roles must be an object mapping role names to permissions.`);
|
|
167
|
+
}
|
|
168
|
+
for (const [rawName, value] of Object.entries(roles)) {
|
|
169
|
+
if (value === void 0) continue;
|
|
170
|
+
const name = cleanName(rawName, `${at}.roles key`);
|
|
171
|
+
if (block.roles.has(name)) {
|
|
172
|
+
throw invalid(`Role \`${name}\` is defined twice for guard \`${guard}\`${team === null ? "" : ` (team ${String(team)})`}.`);
|
|
173
|
+
}
|
|
174
|
+
if (value === "*") {
|
|
175
|
+
block.roles.set(name, "*");
|
|
176
|
+
} else if (Array.isArray(value)) {
|
|
177
|
+
const names = [];
|
|
178
|
+
for (const p of value) pushUnique(names, cleanName(p, `${at}.roles.${name}[]`));
|
|
179
|
+
block.roles.set(name, names);
|
|
180
|
+
} else {
|
|
181
|
+
throw invalid(`${at}.roles.${name} must be an array of permission names or '*'.`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
return blocks;
|
|
187
|
+
}
|
|
188
|
+
async function syncDefinition(rbac, definition, options = {}) {
|
|
189
|
+
const blocks = normalize(rbac, definition, options);
|
|
190
|
+
const prune = options.prune ?? false;
|
|
191
|
+
const dryRun = options.dryRun ?? false;
|
|
192
|
+
const result = {
|
|
193
|
+
dryRun,
|
|
194
|
+
created: { permissions: [], roles: [] },
|
|
195
|
+
updated: { roles: [] },
|
|
196
|
+
deleted: { permissions: [], roles: [] }
|
|
197
|
+
};
|
|
198
|
+
const guards = [...new Set(blocks.map((b) => b.guard))];
|
|
199
|
+
const existingPermissions = /* @__PURE__ */ new Map();
|
|
200
|
+
const finalPermissions = /* @__PURE__ */ new Map();
|
|
201
|
+
const permissionsToDelete = [];
|
|
202
|
+
for (const guard of guards) {
|
|
203
|
+
const declared = [];
|
|
204
|
+
for (const block of blocks.filter((b) => b.guard === guard)) {
|
|
205
|
+
for (const p of block.permissions) pushUnique(declared, p);
|
|
206
|
+
for (const list of block.roles.values()) if (list !== "*") for (const p of list) pushUnique(declared, p);
|
|
207
|
+
}
|
|
208
|
+
if (rbac.wildcard) for (const p of declared) parseWildcardPermission(p);
|
|
209
|
+
const existing = await rbac.adapter.findPermissions({ guardName: guard });
|
|
210
|
+
existingPermissions.set(guard, existing);
|
|
211
|
+
const existingNames = existing.map((p) => p.name);
|
|
212
|
+
for (const name of declared) {
|
|
213
|
+
if (!existingNames.includes(name)) result.created.permissions.push({ name, guard });
|
|
214
|
+
}
|
|
215
|
+
const ownsPermissions = blocks.some((b) => b.guard === guard && b.team === null);
|
|
216
|
+
const stale = prune && ownsPermissions ? existing.filter((p) => !declared.includes(p.name)) : [];
|
|
217
|
+
permissionsToDelete.push(...stale);
|
|
218
|
+
for (const p of stale) result.deleted.permissions.push({ name: p.name, guard });
|
|
219
|
+
finalPermissions.set(guard, [
|
|
220
|
+
...existingNames.filter((n) => !stale.some((p) => p.name === n)),
|
|
221
|
+
...declared.filter((n) => !existingNames.includes(n))
|
|
222
|
+
]);
|
|
223
|
+
}
|
|
224
|
+
const plans = [];
|
|
225
|
+
const rolesToDelete = [];
|
|
226
|
+
for (const block of blocks) {
|
|
227
|
+
const { guard, team } = block;
|
|
228
|
+
const existing = await rbac.adapter.findRoles({ guardName: guard, teamIds: [team] });
|
|
229
|
+
const links = existing.length > 0 ? await rbac.adapter.getRolePermissionLinks(existing.map((r) => r.id)) : [];
|
|
230
|
+
const permissionNames = new Map((existingPermissions.get(guard) ?? []).map((p) => [idKey(p.id), p.name]));
|
|
231
|
+
const namesOf = (role) => {
|
|
232
|
+
const names = [];
|
|
233
|
+
for (const link of links) {
|
|
234
|
+
if (idKey(link.roleId) !== idKey(role.id)) continue;
|
|
235
|
+
const name = permissionNames.get(idKey(link.permissionId));
|
|
236
|
+
if (name !== void 0) pushUnique(names, name);
|
|
237
|
+
}
|
|
238
|
+
return names;
|
|
239
|
+
};
|
|
240
|
+
for (const [name, wanted] of block.roles) {
|
|
241
|
+
const role = existing.find((r) => r.name === name) ?? null;
|
|
242
|
+
const desired = wanted === "*" ? [...finalPermissions.get(guard) ?? []] : wanted;
|
|
243
|
+
const plan = { name, guard, team, existing: role, desired, current: role ? namesOf(role) : [] };
|
|
244
|
+
plans.push(plan);
|
|
245
|
+
if (!role) {
|
|
246
|
+
result.created.roles.push({ name, guard, team, permissions: [...desired] });
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
const attached = desired.filter((p) => !plan.current.includes(p));
|
|
250
|
+
const detached = plan.current.filter((p) => !desired.includes(p));
|
|
251
|
+
if (attached.length > 0 || detached.length > 0) {
|
|
252
|
+
result.updated.roles.push({ name, guard, team, attached, detached });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (prune) {
|
|
256
|
+
for (const role of existing) {
|
|
257
|
+
if (block.roles.has(role.name)) continue;
|
|
258
|
+
rolesToDelete.push(role);
|
|
259
|
+
result.deleted.roles.push({ name: role.name, guard, team, permissions: namesOf(role) });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (dryRun) return result;
|
|
264
|
+
for (const { name, guard } of result.created.permissions) {
|
|
265
|
+
await rbac.createPermission(name, { guard });
|
|
266
|
+
}
|
|
267
|
+
for (const plan of plans) {
|
|
268
|
+
const changed = plan.existing === null || plan.desired.length !== plan.current.length || plan.desired.some((p) => !plan.current.includes(p));
|
|
269
|
+
if (!changed) continue;
|
|
270
|
+
const role = plan.existing ?? await rbac.createRole(plan.name, { guard: plan.guard, team: plan.team });
|
|
271
|
+
if (plan.existing === null && plan.desired.length === 0) continue;
|
|
272
|
+
await rbac.role(role).syncPermissions(plan.desired);
|
|
273
|
+
}
|
|
274
|
+
for (const role of rolesToDelete) await rbac.deleteRole(role);
|
|
275
|
+
for (const permission of permissionsToDelete) await rbac.deletePermission(permission);
|
|
276
|
+
return result;
|
|
277
|
+
}
|
|
278
|
+
|
|
124
279
|
// src/rbac.ts
|
|
125
280
|
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
126
|
-
var
|
|
281
|
+
var idKey2 = (id) => id === null ? "\0null" : String(id);
|
|
127
282
|
function flatten(items) {
|
|
128
283
|
const out = [];
|
|
129
284
|
for (const item of items) {
|
|
@@ -135,7 +290,7 @@ function flatten(items) {
|
|
|
135
290
|
function uniqueById(items) {
|
|
136
291
|
const seen = /* @__PURE__ */ new Set();
|
|
137
292
|
return items.filter((item) => {
|
|
138
|
-
const k =
|
|
293
|
+
const k = idKey2(item.id);
|
|
139
294
|
if (seen.has(k)) return false;
|
|
140
295
|
seen.add(k);
|
|
141
296
|
return true;
|
|
@@ -144,15 +299,15 @@ function uniqueById(items) {
|
|
|
144
299
|
function uniqueIds(ids) {
|
|
145
300
|
const seen = /* @__PURE__ */ new Set();
|
|
146
301
|
return ids.filter((id) => {
|
|
147
|
-
const k =
|
|
302
|
+
const k = idKey2(id);
|
|
148
303
|
if (seen.has(k)) return false;
|
|
149
304
|
seen.add(k);
|
|
150
305
|
return true;
|
|
151
306
|
});
|
|
152
307
|
}
|
|
153
308
|
function filterByIds(items, ids, keep) {
|
|
154
|
-
const set = new Set(ids.map(
|
|
155
|
-
return items.filter((item) => set.has(
|
|
309
|
+
const set = new Set(ids.map(idKey2));
|
|
310
|
+
return items.filter((item) => set.has(idKey2(item.id)) === keep);
|
|
156
311
|
}
|
|
157
312
|
function normalizeName(name) {
|
|
158
313
|
const trimmed = name.trim();
|
|
@@ -281,6 +436,30 @@ var Rbac = class _Rbac {
|
|
|
281
436
|
await this.forgetCachedPermissions();
|
|
282
437
|
await this.#events.emit({ event: "role.deleted", role: resolved, teamId: resolved.teamId });
|
|
283
438
|
}
|
|
439
|
+
// ------------------------------------------------------------------------- sync
|
|
440
|
+
/**
|
|
441
|
+
* Declaratively seeds roles & permissions (spatie's "Database Seeding"): creates missing
|
|
442
|
+
* permissions and roles, and syncs each role's permissions to exactly the given list.
|
|
443
|
+
* Idempotent — running it again changes nothing. Uses the regular engine methods, so the
|
|
444
|
+
* usual events fire.
|
|
445
|
+
*
|
|
446
|
+
* ```ts
|
|
447
|
+
* await rbac.sync({
|
|
448
|
+
* permissions: ['edit articles', 'delete articles'],
|
|
449
|
+
* roles: { admin: '*', writer: ['edit articles'] },
|
|
450
|
+
* })
|
|
451
|
+
* ```
|
|
452
|
+
*
|
|
453
|
+
* - `'*'` gives a role every permission of its guard (after the sync).
|
|
454
|
+
* - Pass an array of definitions (each with its own `guard` / `team`) to sync several scopes.
|
|
455
|
+
* - `prune: true` deletes roles & permissions of the synced scopes that aren't in the definition.
|
|
456
|
+
* - `dryRun: true` returns the plan without writing anything.
|
|
457
|
+
*
|
|
458
|
+
* Not atomic: adapters have no transactions, so a failure midway leaves the earlier changes.
|
|
459
|
+
*/
|
|
460
|
+
async sync(definition, options = {}) {
|
|
461
|
+
return syncDefinition(this, definition, options);
|
|
462
|
+
}
|
|
284
463
|
// ---------------------------------------------------------------------- queries
|
|
285
464
|
/**
|
|
286
465
|
* Ids of subjects of `subjectType` that have ANY of the given roles in the given scope
|
|
@@ -308,10 +487,10 @@ var Rbac = class _Rbac {
|
|
|
308
487
|
const resolved = await this.resolvePermissions(flatten([permissions]), guardName);
|
|
309
488
|
if (resolved.length === 0) return [];
|
|
310
489
|
const permissionIds = resolved.map((p) => p.id);
|
|
311
|
-
const wanted = new Set(permissionIds.map(
|
|
490
|
+
const wanted = new Set(permissionIds.map(idKey2));
|
|
312
491
|
const roles = await this.adapter.findRoles({ guardName, teamIds: this.visibleTeams(teamId) });
|
|
313
492
|
const links = roles.length > 0 ? await this.adapter.getRolePermissionLinks(roles.map((r) => r.id)) : [];
|
|
314
|
-
const roleIds = uniqueIds(links.filter((l) => wanted.has(
|
|
493
|
+
const roleIds = uniqueIds(links.filter((l) => wanted.has(idKey2(l.permissionId))).map((l) => l.roleId));
|
|
315
494
|
const viaRoles = roleIds.length > 0 ? await this.adapter.getSubjectIdsWithRoles(subjectType, roleIds, teamId) : [];
|
|
316
495
|
const direct = await this.adapter.getSubjectIdsWithPermissions(subjectType, permissionIds, teamId);
|
|
317
496
|
return uniqueIds([...viaRoles, ...direct]);
|
|
@@ -401,7 +580,7 @@ var Rbac = class _Rbac {
|
|
|
401
580
|
names.push(normalizeName(input));
|
|
402
581
|
} else {
|
|
403
582
|
if (input.guardName !== guardName) throw new GuardDoesNotMatch(input.guardName, guardName);
|
|
404
|
-
if (input.teamId !== null &&
|
|
583
|
+
if (input.teamId !== null && idKey2(input.teamId) !== idKey2(teamId)) {
|
|
405
584
|
throw new RbacError("TEAM_DOES_NOT_MATCH", `Role \`${input.name}\` belongs to another team.`);
|
|
406
585
|
}
|
|
407
586
|
objects.push(input);
|
|
@@ -428,7 +607,7 @@ var Rbac = class _Rbac {
|
|
|
428
607
|
}
|
|
429
608
|
static pickRole(roles, name, teamId) {
|
|
430
609
|
const candidates = roles.filter((r) => r.name === name);
|
|
431
|
-
return candidates.find((r) =>
|
|
610
|
+
return candidates.find((r) => idKey2(r.teamId) === idKey2(teamId)) ?? candidates.find((r) => r.teamId === null);
|
|
432
611
|
}
|
|
433
612
|
};
|
|
434
613
|
var RoleRbac = class {
|
|
@@ -579,7 +758,7 @@ var SubjectRbac = class _SubjectRbac {
|
|
|
579
758
|
for (const wanted of flatten(roles)) {
|
|
580
759
|
const role = mine.find((r) => _SubjectRbac.roleMatches(r, wanted));
|
|
581
760
|
if (!role) return false;
|
|
582
|
-
matched.add(
|
|
761
|
+
matched.add(idKey2(role.id));
|
|
583
762
|
}
|
|
584
763
|
return matched.size === mine.length;
|
|
585
764
|
}
|
|
@@ -744,7 +923,7 @@ var SubjectRbac = class _SubjectRbac {
|
|
|
744
923
|
});
|
|
745
924
|
}
|
|
746
925
|
static roleMatches(role, wanted) {
|
|
747
|
-
return typeof wanted === "string" ? role.name === wanted.trim() :
|
|
926
|
+
return typeof wanted === "string" ? role.name === wanted.trim() : idKey2(role.id) === idKey2(wanted.id);
|
|
748
927
|
}
|
|
749
928
|
};
|
|
750
929
|
function createRbac(options) {
|