@anievo-id/rbac-evolution-nestjs 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AniEvo-ID
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,95 @@
1
- # Temporary Holding Version
1
+ # @anievo-id/rbac-evolution-nestjs
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ NestJS integration for [rbac-evolution](../core): a global `RbacModule`, an `RbacGuard`, and the
4
+ `@RequirePermissions()`, `@RequireRoles()` and `@RequireRoleOrPermission()` decorators — the Nest counterpart of
5
+ spatie/laravel-permission's `permission`, `role` and `role_or_permission` middleware. Semantics and error bodies are
6
+ identical to [`@anievo-id/rbac-evolution-express`](../express).
7
+
8
+ ```bash
9
+ npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-nestjs
10
+ ```
11
+
12
+ `@nestjs/common`, `@nestjs/core` (10, 11 or 12) and `reflect-metadata` are peer dependencies.
13
+
14
+ ## Setup
15
+
16
+ ```ts
17
+ import { Module } from '@nestjs/common'
18
+ import { createRbac, MemoryAdapter } from '@anievo-id/rbac-evolution'
19
+ import { RbacModule } from '@anievo-id/rbac-evolution-nestjs'
20
+
21
+ const rbac = createRbac({ adapter: new MemoryAdapter() })
22
+
23
+ @Module({
24
+ imports: [
25
+ RbacModule.forRoot({
26
+ rbac,
27
+ // Return null / undefined for guests. Runs after your auth guard/middleware.
28
+ getSubject: (ctx) => {
29
+ const user = ctx.switchToHttp().getRequest().user
30
+ return user ? { type: 'user', id: user.id } : null
31
+ },
32
+ }),
33
+ ],
34
+ })
35
+ export class AppModule {}
36
+ ```
37
+
38
+ Options: `rbac`, `getSubject(ctx)`, `guard` (RBAC guard name, e.g. `'api'`), `team(ctx)` (for `teams: true`),
39
+ `exposeRequirements` (add `required` to 403 bodies) and `globalGuard` (register `RbacGuard` as `APP_GUARD`).
40
+
41
+ `RbacModule.forRootAsync({ imports, inject, useFactory, globalGuard })` builds the options from other providers
42
+ (e.g. a `ConfigService`).
43
+
44
+ ## Decorators
45
+
46
+ ```ts
47
+ import { Controller, Delete, Get, Post } from '@nestjs/common'
48
+ import { CurrentRbac, RequirePermissions, RequireRoleOrPermission, RequireRoles } from '@anievo-id/rbac-evolution-nestjs'
49
+ import type { SubjectRbac } from '@anievo-id/rbac-evolution'
50
+
51
+ @Controller('articles')
52
+ export class ArticlesController {
53
+ @Post()
54
+ @RequirePermissions('articles.create')
55
+ create() {}
56
+
57
+ @Post(':id/publish')
58
+ @RequirePermissions('articles.edit', 'articles.publish') // all of them
59
+ publish() {}
60
+
61
+ @Delete(':id')
62
+ @RequirePermissions('articles.delete|articles.moderate') // any of them (also: { any: true })
63
+ remove() {}
64
+
65
+ @Get('drafts')
66
+ @RequireRoles('editor|admin') // any; RequireRoles('a', 'b', { all: true }) for all
67
+ drafts() {}
68
+
69
+ @Get('stats')
70
+ @RequireRoleOrPermission('admin|stats.view')
71
+ stats(@CurrentRbac() rbac: SubjectRbac) {
72
+ return rbac.snapshot()
73
+ }
74
+ }
75
+ ```
76
+
77
+ - Decorators work on controllers and handlers; class-level and handler-level requirements must **all** pass,
78
+ and stacked decorators add up.
79
+ - Each decorator applies `@UseGuards(RbacGuard)` itself. `@CurrentRbac()` needs the guard to have run: use a
80
+ `@Require*()` decorator, `@UseGuards(RbacGuard)`, or `globalGuard: true`.
81
+ - The `Rbac` engine is injectable with `@Inject(RBAC)`.
82
+
83
+ ## Errors
84
+
85
+ | Situation | Exception | Body |
86
+ | -------------- | ----------------------- | -------------------------------------------------------- |
87
+ | No subject | `UnauthorizedException` | `{ error: 'UNAUTHENTICATED', message }` |
88
+ | Missing access | `ForbiddenException` | `{ error: 'FORBIDDEN', reason, message[, required] }` |
89
+
90
+ `reason` is `'permission'`, `'role'` or `'role_or_permission'`. Customize the response with a Nest exception filter.
91
+
92
+ ## Decorators & build tooling
93
+
94
+ The package is compiled with esbuild and does not rely on `emitDecoratorMetadata`: every injected dependency
95
+ uses an explicit `@Inject(token)`. Your app can use `tsc`, SWC or esbuild.
package/dist/index.cjs ADDED
@@ -0,0 +1,253 @@
1
+ 'use strict';
2
+
3
+ var common = require('@nestjs/common');
4
+ var core = require('@nestjs/core');
5
+ require('reflect-metadata');
6
+
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __decorateClass = (decorators, target, key, kind) => {
9
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
10
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
11
+ if (decorator = decorators[i])
12
+ result = (decorator(result)) || result;
13
+ return result;
14
+ };
15
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
16
+
17
+ // src/context.ts
18
+ var RbacGuardMissingError = class extends Error {
19
+ code = "RBAC_GUARD_MISSING";
20
+ constructor() {
21
+ super(
22
+ "`@CurrentRbac()` was used but `RbacGuard` did not run for this route. Add a `@Require*()` decorator, `@UseGuards(RbacGuard)`, or `RbacModule.forRoot({ globalGuard: true })`."
23
+ );
24
+ this.name = "RbacGuardMissingError";
25
+ }
26
+ };
27
+ var resolved = /* @__PURE__ */ new WeakMap();
28
+ function requestKey(context) {
29
+ let key;
30
+ switch (context.getType()) {
31
+ case "http":
32
+ key = context.switchToHttp().getRequest();
33
+ break;
34
+ case "rpc":
35
+ key = context.switchToRpc().getContext();
36
+ break;
37
+ case "ws":
38
+ key = context.switchToWs().getClient();
39
+ break;
40
+ default:
41
+ key = context.getArgByIndex(2);
42
+ }
43
+ return typeof key === "object" && key !== null ? key : void 0;
44
+ }
45
+ function hasResolved(key) {
46
+ return resolved.has(key);
47
+ }
48
+ function getResolved(key) {
49
+ return resolved.get(key);
50
+ }
51
+ function setResolved(key, rbac) {
52
+ resolved.set(key, rbac);
53
+ }
54
+ function getRbac(context) {
55
+ const key = requestKey(context);
56
+ if (key === void 0 || !resolved.has(key)) throw new RbacGuardMissingError();
57
+ return resolved.get(key) ?? null;
58
+ }
59
+
60
+ // src/requirements.ts
61
+ var MESSAGES = {
62
+ permission: "User does not have the right permissions.",
63
+ role: "User does not have the right roles.",
64
+ role_or_permission: "User does not have any of the necessary access rights."
65
+ };
66
+ var UNAUTHENTICATED_MESSAGE = "User is not logged in.";
67
+ var split = (name) => name.split("|").map((n) => n.trim()).filter((n) => n !== "");
68
+ function toGroups(names) {
69
+ const groups = [];
70
+ for (const name of names) {
71
+ for (const item of typeof name === "string" ? [name] : name) {
72
+ const group = split(item);
73
+ if (group.length > 0) groups.push(group);
74
+ }
75
+ }
76
+ return groups;
77
+ }
78
+ function parseArgs(args) {
79
+ const last = args[args.length - 1];
80
+ if (last !== void 0 && typeof last === "object" && !Array.isArray(last)) {
81
+ return { names: args.slice(0, -1), options: last };
82
+ }
83
+ return { names: args, options: void 0 };
84
+ }
85
+ function ensure(requirement) {
86
+ const { requirements } = requirement;
87
+ if (requirements.length === 0 || requirements.some((group) => group.length === 0)) {
88
+ throw new TypeError(`[rbac-evolution] A ${requirement.kind} requirement needs at least one name.`);
89
+ }
90
+ return requirement;
91
+ }
92
+ function permissionRequirement(args) {
93
+ const { names, options = {} } = parseArgs(args);
94
+ const groups = toGroups(names);
95
+ return ensure({ kind: "permission", requirements: options.any ? [groups.flat()] : groups });
96
+ }
97
+ function roleRequirement(args) {
98
+ const { names, options = {} } = parseArgs(args);
99
+ const all = toGroups(names).flat();
100
+ return ensure({ kind: "role", requirements: options.all ? all.map((r) => [r]) : [all] });
101
+ }
102
+ function roleOrPermissionRequirement(names) {
103
+ return ensure({ kind: "role_or_permission", requirements: [toGroups(names).flat()] });
104
+ }
105
+ async function satisfies(rbac, requirement) {
106
+ for (const group of requirement.requirements) {
107
+ let pass;
108
+ switch (requirement.kind) {
109
+ case "permission":
110
+ pass = await rbac.canAny(group);
111
+ break;
112
+ case "role":
113
+ pass = await rbac.hasAnyRole(group);
114
+ break;
115
+ default:
116
+ pass = await rbac.hasAnyRole(group) || await rbac.canAny(group);
117
+ }
118
+ if (!pass) return false;
119
+ }
120
+ return true;
121
+ }
122
+
123
+ // src/tokens.ts
124
+ var RBAC_MODULE_OPTIONS = /* @__PURE__ */ Symbol.for("rbac-evolution:nestjs:options");
125
+ var RBAC = /* @__PURE__ */ Symbol.for("rbac-evolution:nestjs:rbac");
126
+ var RBAC_REQUIREMENTS = "rbac-evolution:requirements";
127
+
128
+ // src/guard.ts
129
+ var enforced = /* @__PURE__ */ new WeakMap();
130
+ exports.RbacGuard = class RbacGuard {
131
+ // Explicit tokens: the package is built with esbuild, which does not emit `design:paramtypes`.
132
+ constructor(reflector, options) {
133
+ this.reflector = reflector;
134
+ this.options = options;
135
+ }
136
+ reflector;
137
+ options;
138
+ async canActivate(context) {
139
+ const key = requestKey(context);
140
+ const rbac = await this.resolve(context, key);
141
+ const handler = context.getHandler();
142
+ if (key !== void 0) {
143
+ const done = enforced.get(key) ?? /* @__PURE__ */ new Set();
144
+ if (done.has(handler)) return true;
145
+ enforced.set(key, done.add(handler));
146
+ }
147
+ const requirements = [
148
+ ...this.reflector.get(RBAC_REQUIREMENTS, context.getClass()) ?? [],
149
+ ...this.reflector.get(RBAC_REQUIREMENTS, handler) ?? []
150
+ ];
151
+ if (requirements.length === 0) return true;
152
+ if (rbac === null) {
153
+ throw new common.UnauthorizedException({ error: "UNAUTHENTICATED", message: UNAUTHENTICATED_MESSAGE });
154
+ }
155
+ for (const requirement of requirements) {
156
+ if (!await satisfies(rbac, requirement)) {
157
+ throw new common.ForbiddenException({
158
+ error: "FORBIDDEN",
159
+ reason: requirement.kind,
160
+ message: MESSAGES[requirement.kind],
161
+ ...this.options.exposeRequirements && { required: requirement.requirements }
162
+ });
163
+ }
164
+ }
165
+ return true;
166
+ }
167
+ async resolve(context, key) {
168
+ if (key !== void 0 && hasResolved(key)) return getResolved(key) ?? null;
169
+ const { rbac, getSubject, guard, team } = this.options;
170
+ const subject = await getSubject(context);
171
+ let result = null;
172
+ if (subject) {
173
+ const teamId = team ? await team(context) : void 0;
174
+ result = rbac.for(subject, {
175
+ ...guard !== void 0 && { guard },
176
+ ...teamId !== void 0 && { team: teamId }
177
+ });
178
+ }
179
+ if (key !== void 0) setResolved(key, result);
180
+ return result;
181
+ }
182
+ };
183
+ exports.RbacGuard = __decorateClass([
184
+ common.Injectable(),
185
+ __decorateParam(0, common.Inject(core.Reflector)),
186
+ __decorateParam(1, common.Inject(RBAC_MODULE_OPTIONS))
187
+ ], exports.RbacGuard);
188
+
189
+ // src/module.ts
190
+ function build(optionsProvider, globalGuard, imports = []) {
191
+ return {
192
+ module: exports.RbacModule,
193
+ global: true,
194
+ imports,
195
+ providers: [
196
+ optionsProvider,
197
+ { provide: RBAC, useFactory: (options) => options.rbac, inject: [RBAC_MODULE_OPTIONS] },
198
+ exports.RbacGuard,
199
+ ...globalGuard ? [{ provide: core.APP_GUARD, useClass: exports.RbacGuard }] : []
200
+ ],
201
+ exports: [RBAC_MODULE_OPTIONS, RBAC, exports.RbacGuard]
202
+ };
203
+ }
204
+ exports.RbacModule = class RbacModule {
205
+ static forRoot(config) {
206
+ const { globalGuard = false, ...options } = config;
207
+ return build({ provide: RBAC_MODULE_OPTIONS, useValue: options }, globalGuard);
208
+ }
209
+ /** Like {@link forRoot}, with options built by a factory (e.g. from a `ConfigService`). */
210
+ static forRootAsync(config) {
211
+ return build(
212
+ { provide: RBAC_MODULE_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },
213
+ config.globalGuard ?? false,
214
+ config.imports ?? []
215
+ );
216
+ }
217
+ };
218
+ exports.RbacModule = __decorateClass([
219
+ common.Global(),
220
+ common.Module({})
221
+ ], exports.RbacModule);
222
+ function appendRequirement(requirement) {
223
+ return (target, _propertyKey, descriptor) => {
224
+ const holder = descriptor?.value !== void 0 ? descriptor.value : target;
225
+ const current = Reflect.getMetadata(RBAC_REQUIREMENTS, holder) ?? [];
226
+ Reflect.defineMetadata(RBAC_REQUIREMENTS, [...current, requirement], holder);
227
+ };
228
+ }
229
+ var requirementDecorator = (requirement) => common.applyDecorators(appendRequirement(requirement), common.UseGuards(exports.RbacGuard));
230
+ function RequirePermissions(...args) {
231
+ return requirementDecorator(permissionRequirement(args));
232
+ }
233
+ function RequireRoles(...args) {
234
+ return requirementDecorator(roleRequirement(args));
235
+ }
236
+ function RequireRoleOrPermission(...names) {
237
+ return requirementDecorator(roleOrPermissionRequirement(names));
238
+ }
239
+ var CurrentRbac = common.createParamDecorator(
240
+ (_data, context) => getRbac(context)
241
+ );
242
+
243
+ exports.CurrentRbac = CurrentRbac;
244
+ exports.RBAC = RBAC;
245
+ exports.RBAC_MODULE_OPTIONS = RBAC_MODULE_OPTIONS;
246
+ exports.RBAC_REQUIREMENTS = RBAC_REQUIREMENTS;
247
+ exports.RbacGuardMissingError = RbacGuardMissingError;
248
+ exports.RequirePermissions = RequirePermissions;
249
+ exports.RequireRoleOrPermission = RequireRoleOrPermission;
250
+ exports.RequireRoles = RequireRoles;
251
+ exports.getRbac = getRbac;
252
+ //# sourceMappingURL=index.cjs.map
253
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context.ts","../src/requirements.ts","../src/tokens.ts","../src/guard.ts","../src/module.ts","../src/decorators.ts"],"names":["RbacGuard","UnauthorizedException","ForbiddenException","Injectable","Reflector","RbacModule","APP_GUARD","Global","Module","applyDecorators","UseGuards","createParamDecorator"],"mappings":";;;;;;;;;;;;;;;;;AAGO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EACtC,IAAA,GAAO,oBAAA;AAAA,EAEhB,WAAA,GAAc;AACZ,IAAA,KAAA;AAAA,MACE;AAAA,KAEF;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EACd;AACF;AAGA,IAAM,QAAA,uBAAe,OAAA,EAAoC;AAMlD,SAAS,WAAW,OAAA,EAA+C;AACxE,EAAA,IAAI,GAAA;AACJ,EAAA,QAAQ,OAAA,CAAQ,SAAgB;AAAG,IACjC,KAAK,MAAA;AACH,MAAA,GAAA,GAAM,OAAA,CAAQ,YAAA,EAAa,CAAE,UAAA,EAAW;AACxC,MAAA;AAAA,IACF,KAAK,KAAA;AACH,MAAA,GAAA,GAAM,OAAA,CAAQ,WAAA,EAAY,CAAE,UAAA,EAAW;AACvC,MAAA;AAAA,IACF,KAAK,IAAA;AACH,MAAA,GAAA,GAAM,OAAA,CAAQ,UAAA,EAAW,CAAE,SAAA,EAAU;AACrC,MAAA;AAAA,IACF;AACE,MAAA,GAAA,GAAM,OAAA,CAAQ,cAAc,CAAC,CAAA;AAAA;AAEjC,EAAA,OAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,OAAO,GAAA,GAAM,MAAA;AACzD;AAEO,SAAS,YAAY,GAAA,EAAsB;AAChD,EAAA,OAAO,QAAA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AC,MAAA,EAAQ,YAAA,EAAc,UAAA,KAAe;AAC3C,IAAA,MAAM,MAAA,GAAiB,UAAA,EAAY,KAAA,KAAU,MAAA,GAAa,WAAW,KAAA,GAAmB,MAAA;AACxF,IAAA,MAAM,UAAW,OAAA,CAAQ,WAAA,CAAY,iBAAA,EAAmB,MAAM,KAAuC,EAAC;AACtG,IAAA,OAAA,CAAQ,eAAe,iBAAA,EAAmB,CAAC,GAAG,OAAA,EAAS,WAAW,GAAG,MAAM,CAAA;AAAA,EAC7E,CAAA;AACF;AAEA,IAAM,oBAAA,GAAuB,CAAC,WAAA,KAC5BI,sBAAA,CAAgB,kBAAkB,WAAW,CAAA,EAAGC,gBAAA,CAAUV,iBAAS,CAAC,CAAA;AAU/D,SAAS,sBAAsB,IAAA,EAA2D;AAC/F,EAAA,OAAO,oBAAA,CAAqB,qBAAA,CAAsB,IAAI,CAAC,CAAA;AACzD;AAQO,SAAS,gBAAgB,IAAA,EAAqD;AACnF,EAAA,OAAO,oBAAA,CAAqB,eAAA,CAAgB,IAAI,CAAC,CAAA;AACnD;AAQO,SAAS,2BAA2B,KAAA,EAA2B;AACpE,EAAA,OAAO,oBAAA,CAAqB,2BAAA,CAA4B,KAAK,CAAC,CAAA;AAChE;AAaO,IAAM,WAAA,GAAwCW,2BAAA;AAAA,EACnD,CAAC,KAAA,EAAgB,OAAA,KAAkD,OAAA,CAAQ,OAAO;AACpF","file":"index.cjs","sourcesContent":["import type { SubjectRbac } from '@anievo-id/rbac-evolution'\nimport type { ExecutionContext } from '@nestjs/common'\n\nexport class RbacGuardMissingError extends Error {\n readonly code = 'RBAC_GUARD_MISSING'\n\n constructor() {\n super(\n '`@CurrentRbac()` was used but `RbacGuard` did not run for this route. Add a `@Require*()` decorator, ' +\n '`@UseGuards(RbacGuard)`, or `RbacModule.forRoot({ globalGuard: true })`.',\n )\n this.name = 'RbacGuardMissingError'\n }\n}\n\n/** Per-request resolved `SubjectRbac` (`null` for guests), keyed by the request/client/context object. */\nconst resolved = new WeakMap<object, SubjectRbac | null>()\n\n/**\n * The object that identifies the current request: the HTTP request, the RPC context, the WebSocket client,\n * or (for GraphQL and other context types) the third handler argument.\n */\nexport function requestKey(context: ExecutionContext): object | undefined {\n let key: unknown\n switch (context.getType<string>()) {\n case 'http':\n key = context.switchToHttp().getRequest()\n break\n case 'rpc':\n key = context.switchToRpc().getContext()\n break\n case 'ws':\n key = context.switchToWs().getClient()\n break\n default:\n key = context.getArgByIndex(2)\n }\n return typeof key === 'object' && key !== null ? key : undefined\n}\n\nexport function hasResolved(key: object): boolean {\n return resolved.has(key)\n}\n\nexport function getResolved(key: object): SubjectRbac | null | undefined {\n return resolved.get(key)\n}\n\nexport function setResolved(key: object, rbac: SubjectRbac | null): void {\n resolved.set(key, rbac)\n}\n\n/**\n * Returns the `SubjectRbac` that `RbacGuard` resolved for this execution context (`null` for guests).\n * Throws {@link RbacGuardMissingError} when the guard has not run.\n */\nexport function getRbac(context: ExecutionContext): SubjectRbac | null {\n const key = requestKey(context)\n if (key === undefined || !resolved.has(key)) throw new RbacGuardMissingError()\n return resolved.get(key) ?? null\n}\n","import type { SubjectRbac } from '@anievo-id/rbac-evolution'\n\n/** Which kind of requirement failed — same values as the Express package. */\nexport type RequirementKind = 'permission' | 'role' | 'role_or_permission'\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type RequirementNames = string | readonly string[]\n\n/** One `@Require*` decorator, normalized. */\nexport interface RbacRequirement {\n kind: RequirementKind\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\n requirements: string[][]\n}\n\nexport interface PermissionRequirementOptions {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean\n}\n\nexport interface RoleRequirementOptions {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean\n}\n\nexport const MESSAGES: Record<RequirementKind, string> = {\n permission: 'User does not have the right permissions.',\n role: 'User does not have the right roles.',\n role_or_permission: 'User does not have any of the necessary access rights.',\n}\n\nexport const UNAUTHENTICATED_MESSAGE = 'User is not logged in.'\n\nconst split = (name: string): string[] =>\n name\n .split('|')\n .map((n) => n.trim())\n .filter((n) => n !== '')\n\n/** Each argument is a group (pipes = any within the group); arrays contribute one group per item. */\nfunction toGroups(names: readonly RequirementNames[]): string[][] {\n const groups: string[][] = []\n for (const name of names) {\n for (const item of typeof name === 'string' ? [name] : name) {\n const group = split(item)\n if (group.length > 0) groups.push(group)\n }\n }\n return groups\n}\n\nfunction parseArgs<O extends object>(args: readonly (RequirementNames | O)[]): { names: RequirementNames[]; options: O | undefined } {\n const last = args[args.length - 1]\n if (last !== undefined && typeof last === 'object' && !Array.isArray(last)) {\n return { names: args.slice(0, -1) as RequirementNames[], options: last as O }\n }\n return { names: args as RequirementNames[], options: undefined }\n}\n\nfunction ensure(requirement: RbacRequirement): RbacRequirement {\n const { requirements } = requirement\n if (requirements.length === 0 || requirements.some((group) => group.length === 0)) {\n throw new TypeError(`[rbac-evolution] A ${requirement.kind} requirement needs at least one name.`)\n }\n return requirement\n}\n\n/** `'a', 'b'` = all; `'a|b'` = any; `{ any: true }` = any of everything. */\nexport function permissionRequirement(args: readonly (RequirementNames | PermissionRequirementOptions)[]): RbacRequirement {\n const { names, options = {} } = parseArgs<PermissionRequirementOptions>(args)\n const groups = toGroups(names)\n return ensure({ kind: 'permission', requirements: options.any ? [groups.flat()] : groups })\n}\n\n/** Any of the roles by default; `{ all: true }` = all of them. */\nexport function roleRequirement(args: readonly (RequirementNames | RoleRequirementOptions)[]): RbacRequirement {\n const { names, options = {} } = parseArgs<RoleRequirementOptions>(args)\n const all = toGroups(names).flat()\n return ensure({ kind: 'role', requirements: options.all ? all.map((r) => [r]) : [all] })\n}\n\n/** Any of the names, as a role OR as a permission. */\nexport function roleOrPermissionRequirement(names: readonly RequirementNames[]): RbacRequirement {\n return ensure({ kind: 'role_or_permission', requirements: [toGroups(names).flat()] })\n}\n\n/** `true` when every group of the requirement passes for the subject. */\nexport async function satisfies(rbac: SubjectRbac, requirement: RbacRequirement): Promise<boolean> {\n for (const group of requirement.requirements) {\n let pass: boolean\n switch (requirement.kind) {\n case 'permission':\n pass = await rbac.canAny(group)\n break\n case 'role':\n pass = await rbac.hasAnyRole(group)\n break\n default:\n pass = (await rbac.hasAnyRole(group)) || (await rbac.canAny(group))\n }\n if (!pass) return false\n }\n return true\n}\n","/** Injection token for the resolved {@link RbacModuleOptions}. */\nexport const RBAC_MODULE_OPTIONS = Symbol.for('rbac-evolution:nestjs:options')\n\n/** Injection token for the `Rbac` engine passed to `RbacModule.forRoot({ rbac })`. */\nexport const RBAC = Symbol.for('rbac-evolution:nestjs:rbac')\n\n/** Metadata key under which `@Require*` decorators store their requirements. */\nexport const RBAC_REQUIREMENTS = 'rbac-evolution:requirements'\n","import type { SubjectRbac } from '@anievo-id/rbac-evolution'\nimport {\n type CanActivate,\n type ExecutionContext,\n ForbiddenException,\n Inject,\n Injectable,\n UnauthorizedException,\n} from '@nestjs/common'\nimport { Reflector } from '@nestjs/core'\nimport { getResolved, hasResolved, requestKey, setResolved } from './context'\nimport type { RbacModuleOptions } from './options'\nimport { MESSAGES, type RbacRequirement, satisfies, UNAUTHENTICATED_MESSAGE } from './requirements'\nimport { RBAC_MODULE_OPTIONS, RBAC_REQUIREMENTS } from './tokens'\n\n/** Handlers already enforced for a request — the guard may run twice (global + `@UseGuards`). */\nconst enforced = new WeakMap<object, Set<unknown>>()\n\n/**\n * Resolves the current subject (once per request) and enforces the `@RequirePermissions()`,\n * `@RequireRoles()` and `@RequireRoleOrPermission()` metadata of the class and the handler.\n *\n * - no subject → `UnauthorizedException` `401 { error: 'UNAUTHENTICATED', message }`\n * - missing access → `ForbiddenException` `403 { error: 'FORBIDDEN', reason, message }`\n *\n * Bodies are identical to `@anievo-id/rbac-evolution-express`.\n */\n@Injectable()\nexport class RbacGuard implements CanActivate {\n // Explicit tokens: the package is built with esbuild, which does not emit `design:paramtypes`.\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(RBAC_MODULE_OPTIONS) private readonly options: RbacModuleOptions,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const key = requestKey(context)\n const rbac = await this.resolve(context, key)\n\n const handler = context.getHandler()\n if (key !== undefined) {\n const done = enforced.get(key) ?? new Set<unknown>()\n if (done.has(handler)) return true\n enforced.set(key, done.add(handler))\n }\n\n const requirements = [\n ...(this.reflector.get<RbacRequirement[] | undefined>(RBAC_REQUIREMENTS, context.getClass()) ?? []),\n ...(this.reflector.get<RbacRequirement[] | undefined>(RBAC_REQUIREMENTS, handler) ?? []),\n ]\n if (requirements.length === 0) return true\n\n if (rbac === null) {\n throw new UnauthorizedException({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE })\n }\n\n for (const requirement of requirements) {\n if (!(await satisfies(rbac, requirement))) {\n throw new ForbiddenException({\n error: 'FORBIDDEN',\n reason: requirement.kind,\n message: MESSAGES[requirement.kind],\n ...(this.options.exposeRequirements && { required: requirement.requirements }),\n })\n }\n }\n return true\n }\n\n private async resolve(context: ExecutionContext, key: object | undefined): Promise<SubjectRbac | null> {\n if (key !== undefined && hasResolved(key)) return getResolved(key) ?? null\n\n const { rbac, getSubject, guard, team } = this.options\n const subject = await getSubject(context)\n let result: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(context) : undefined\n result = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n if (key !== undefined) setResolved(key, result)\n return result\n }\n}\n","import { type DynamicModule, Global, Module, type Provider } from '@nestjs/common'\nimport { APP_GUARD } from '@nestjs/core'\nimport { RbacGuard } from './guard'\nimport type { RbacModuleAsyncConfig, RbacModuleConfig, RbacModuleOptions } from './options'\nimport { RBAC, RBAC_MODULE_OPTIONS } from './tokens'\n\nfunction build(optionsProvider: Provider, globalGuard: boolean, imports: DynamicModule['imports'] = []): DynamicModule {\n return {\n module: RbacModule,\n global: true,\n imports,\n providers: [\n optionsProvider,\n { provide: RBAC, useFactory: (options: RbacModuleOptions) => options.rbac, inject: [RBAC_MODULE_OPTIONS] },\n RbacGuard,\n ...(globalGuard ? [{ provide: APP_GUARD, useClass: RbacGuard }] : []),\n ],\n exports: [RBAC_MODULE_OPTIONS, RBAC, RbacGuard],\n }\n}\n\n/**\n * Registers rbac-evolution in a Nest application (global module).\n *\n * ```ts\n * @Module({\n * imports: [\n * RbacModule.forRoot({\n * rbac,\n * getSubject: (ctx) => {\n * const user = ctx.switchToHttp().getRequest().user\n * return user ? { type: 'user', id: user.id } : null\n * },\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n@Global()\n@Module({})\nexport class RbacModule {\n static forRoot(config: RbacModuleConfig): DynamicModule {\n const { globalGuard = false, ...options } = config\n return build({ provide: RBAC_MODULE_OPTIONS, useValue: options }, globalGuard)\n }\n\n /** Like {@link forRoot}, with options built by a factory (e.g. from a `ConfigService`). */\n static forRootAsync(config: RbacModuleAsyncConfig): DynamicModule {\n return build(\n { provide: RBAC_MODULE_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },\n config.globalGuard ?? false,\n config.imports ?? [],\n )\n }\n}\n","import 'reflect-metadata'\nimport type { SubjectRbac } from '@anievo-id/rbac-evolution'\nimport { applyDecorators, createParamDecorator, type ExecutionContext, UseGuards } from '@nestjs/common'\nimport { getRbac } from './context'\nimport { RbacGuard } from './guard'\nimport {\n type PermissionRequirementOptions,\n permissionRequirement,\n type RbacRequirement,\n type RequirementNames,\n roleOrPermissionRequirement,\n roleRequirement,\n type RoleRequirementOptions,\n} from './requirements'\nimport { RBAC_REQUIREMENTS } from './tokens'\n\ntype ClassOrMethodDecorator = <T>(\n target: object,\n propertyKey?: string | symbol,\n descriptor?: TypedPropertyDescriptor<T>,\n) => void\n\n/** Appends a requirement (stacked decorators all apply), unlike `SetMetadata` which overwrites. */\nfunction appendRequirement(requirement: RbacRequirement): ClassOrMethodDecorator {\n return (target, _propertyKey, descriptor) => {\n const holder: object = descriptor?.value !== undefined ? (descriptor.value as object) : target\n const current = (Reflect.getMetadata(RBAC_REQUIREMENTS, holder) as RbacRequirement[] | undefined) ?? []\n Reflect.defineMetadata(RBAC_REQUIREMENTS, [...current, requirement], holder)\n }\n}\n\nconst requirementDecorator = (requirement: RbacRequirement) =>\n applyDecorators(appendRequirement(requirement), UseGuards(RbacGuard))\n\n/**\n * Requires permissions, like spatie's `permission:` middleware. Works on controllers and handlers.\n *\n * - `@RequirePermissions('edit articles')`\n * - `@RequirePermissions('edit articles|delete articles')` — any of them\n * - `@RequirePermissions('edit articles', 'publish articles')` — all of them\n * - `@RequirePermissions('a', 'b', { any: true })` — any of them\n */\nexport function RequirePermissions(...args: (RequirementNames | PermissionRequirementOptions)[]) {\n return requirementDecorator(permissionRequirement(args))\n}\n\n/**\n * Requires roles, like spatie's `role:` middleware.\n *\n * - `@RequireRoles('admin')`, `@RequireRoles('admin|editor')`, `@RequireRoles('admin', 'editor')` — any of them\n * - `@RequireRoles('admin', 'editor', { all: true })` — all of them\n */\nexport function RequireRoles(...args: (RequirementNames | RoleRequirementOptions)[]) {\n return requirementDecorator(roleRequirement(args))\n}\n\n/**\n * Passes when the subject has ANY of the names as a role OR as a permission,\n * like spatie's `role_or_permission:` middleware.\n *\n * - `@RequireRoleOrPermission('admin|edit articles')`\n */\nexport function RequireRoleOrPermission(...names: RequirementNames[]) {\n return requirementDecorator(roleOrPermissionRequirement(names))\n}\n\n/**\n * Injects the current subject's `SubjectRbac` (`null` for guests), as resolved by `RbacGuard`.\n *\n * ```ts\n * @Get('me/permissions')\n * @UseGuards(RbacGuard)\n * snapshot(@CurrentRbac() rbac: SubjectRbac | null) {\n * return rbac?.snapshot() ?? null\n * }\n * ```\n */\nexport const CurrentRbac: () => ParameterDecorator = createParamDecorator(\n (_data: unknown, context: ExecutionContext): SubjectRbac | null => getRbac(context),\n)\n"]}
@@ -0,0 +1,153 @@
1
+ import { ExecutionContext, ModuleMetadata, FactoryProvider, DynamicModule, CanActivate } from '@nestjs/common';
2
+ import { Rbac, Subject, TeamId, SubjectRbac } from '@anievo-id/rbac-evolution';
3
+ import { Reflector } from '@nestjs/core';
4
+
5
+ type MaybePromise<T> = T | Promise<T>;
6
+ interface RbacModuleOptions {
7
+ /** The RBAC engine created with `createRbac(...)`. */
8
+ rbac: Rbac;
9
+ /**
10
+ * Resolves the authenticated subject for this execution context (e.g. from `request.user`).
11
+ * Return `null` / `undefined` for guests.
12
+ */
13
+ getSubject: (context: ExecutionContext) => MaybePromise<Subject | null | undefined>;
14
+ /** RBAC guard name (e.g. `web` or `api`) — not a Nest guard. Defaults to the engine's `defaultGuard`. */
15
+ guard?: string;
16
+ /** Resolves the current team (only when the engine was created with `teams: true`). */
17
+ team?: (context: ExecutionContext) => MaybePromise<TeamId | undefined>;
18
+ /**
19
+ * Include the required roles/permissions in the 403 body (`required`).
20
+ * Default: `false` (like spatie's `display_permission_in_exception`).
21
+ */
22
+ exposeRequirements?: boolean;
23
+ }
24
+ interface GlobalGuardOption {
25
+ /**
26
+ * Register `RbacGuard` as a global guard (`APP_GUARD`), so every route resolves the subject
27
+ * (and `@CurrentRbac()` works without a `@Require*` decorator). Default: `false`.
28
+ */
29
+ globalGuard?: boolean;
30
+ }
31
+ interface RbacModuleConfig extends RbacModuleOptions, GlobalGuardOption {
32
+ }
33
+ interface RbacModuleAsyncConfig extends GlobalGuardOption, Pick<ModuleMetadata, 'imports'> {
34
+ /** Providers to inject into `useFactory`. */
35
+ inject?: FactoryProvider['inject'];
36
+ /** Builds the options, e.g. from a `ConfigService`. */
37
+ useFactory: (...args: never[]) => MaybePromise<RbacModuleOptions>;
38
+ }
39
+
40
+ /**
41
+ * Registers rbac-evolution in a Nest application (global module).
42
+ *
43
+ * ```ts
44
+ * @Module({
45
+ * imports: [
46
+ * RbacModule.forRoot({
47
+ * rbac,
48
+ * getSubject: (ctx) => {
49
+ * const user = ctx.switchToHttp().getRequest().user
50
+ * return user ? { type: 'user', id: user.id } : null
51
+ * },
52
+ * }),
53
+ * ],
54
+ * })
55
+ * export class AppModule {}
56
+ * ```
57
+ */
58
+ declare class RbacModule {
59
+ static forRoot(config: RbacModuleConfig): DynamicModule;
60
+ /** Like {@link forRoot}, with options built by a factory (e.g. from a `ConfigService`). */
61
+ static forRootAsync(config: RbacModuleAsyncConfig): DynamicModule;
62
+ }
63
+
64
+ /**
65
+ * Resolves the current subject (once per request) and enforces the `@RequirePermissions()`,
66
+ * `@RequireRoles()` and `@RequireRoleOrPermission()` metadata of the class and the handler.
67
+ *
68
+ * - no subject → `UnauthorizedException` `401 { error: 'UNAUTHENTICATED', message }`
69
+ * - missing access → `ForbiddenException` `403 { error: 'FORBIDDEN', reason, message }`
70
+ *
71
+ * Bodies are identical to `@anievo-id/rbac-evolution-express`.
72
+ */
73
+ declare class RbacGuard implements CanActivate {
74
+ private readonly reflector;
75
+ private readonly options;
76
+ constructor(reflector: Reflector, options: RbacModuleOptions);
77
+ canActivate(context: ExecutionContext): Promise<boolean>;
78
+ private resolve;
79
+ }
80
+
81
+ /** Which kind of requirement failed — same values as the Express package. */
82
+ type RequirementKind = 'permission' | 'role' | 'role_or_permission';
83
+ /** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
84
+ type RequirementNames = string | readonly string[];
85
+ /** One `@Require*` decorator, normalized. */
86
+ interface RbacRequirement {
87
+ kind: RequirementKind;
88
+ /** Groups of names: every group must pass, a group passes when ANY of its names matches. */
89
+ requirements: string[][];
90
+ }
91
+ interface PermissionRequirementOptions {
92
+ /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
93
+ any?: boolean;
94
+ }
95
+ interface RoleRequirementOptions {
96
+ /** Require ALL of the roles (instead of any). Default: `false`. */
97
+ all?: boolean;
98
+ }
99
+
100
+ /**
101
+ * Requires permissions, like spatie's `permission:` middleware. Works on controllers and handlers.
102
+ *
103
+ * - `@RequirePermissions('edit articles')`
104
+ * - `@RequirePermissions('edit articles|delete articles')` — any of them
105
+ * - `@RequirePermissions('edit articles', 'publish articles')` — all of them
106
+ * - `@RequirePermissions('a', 'b', { any: true })` — any of them
107
+ */
108
+ declare function RequirePermissions(...args: (RequirementNames | PermissionRequirementOptions)[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
109
+ /**
110
+ * Requires roles, like spatie's `role:` middleware.
111
+ *
112
+ * - `@RequireRoles('admin')`, `@RequireRoles('admin|editor')`, `@RequireRoles('admin', 'editor')` — any of them
113
+ * - `@RequireRoles('admin', 'editor', { all: true })` — all of them
114
+ */
115
+ declare function RequireRoles(...args: (RequirementNames | RoleRequirementOptions)[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
116
+ /**
117
+ * Passes when the subject has ANY of the names as a role OR as a permission,
118
+ * like spatie's `role_or_permission:` middleware.
119
+ *
120
+ * - `@RequireRoleOrPermission('admin|edit articles')`
121
+ */
122
+ declare function RequireRoleOrPermission(...names: RequirementNames[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
123
+ /**
124
+ * Injects the current subject's `SubjectRbac` (`null` for guests), as resolved by `RbacGuard`.
125
+ *
126
+ * ```ts
127
+ * @Get('me/permissions')
128
+ * @UseGuards(RbacGuard)
129
+ * snapshot(@CurrentRbac() rbac: SubjectRbac | null) {
130
+ * return rbac?.snapshot() ?? null
131
+ * }
132
+ * ```
133
+ */
134
+ declare const CurrentRbac: () => ParameterDecorator;
135
+
136
+ declare class RbacGuardMissingError extends Error {
137
+ readonly code = "RBAC_GUARD_MISSING";
138
+ constructor();
139
+ }
140
+ /**
141
+ * Returns the `SubjectRbac` that `RbacGuard` resolved for this execution context (`null` for guests).
142
+ * Throws {@link RbacGuardMissingError} when the guard has not run.
143
+ */
144
+ declare function getRbac(context: ExecutionContext): SubjectRbac | null;
145
+
146
+ /** Injection token for the resolved {@link RbacModuleOptions}. */
147
+ declare const RBAC_MODULE_OPTIONS: unique symbol;
148
+ /** Injection token for the `Rbac` engine passed to `RbacModule.forRoot({ rbac })`. */
149
+ declare const RBAC: unique symbol;
150
+ /** Metadata key under which `@Require*` decorators store their requirements. */
151
+ declare const RBAC_REQUIREMENTS = "rbac-evolution:requirements";
152
+
153
+ export { CurrentRbac, type PermissionRequirementOptions, RBAC, RBAC_MODULE_OPTIONS, RBAC_REQUIREMENTS, RbacGuard, RbacGuardMissingError, RbacModule, type RbacModuleAsyncConfig, type RbacModuleConfig, type RbacModuleOptions, type RbacRequirement, RequirePermissions, RequireRoleOrPermission, RequireRoles, type RequirementKind, type RequirementNames, type RoleRequirementOptions, getRbac };
@@ -0,0 +1,153 @@
1
+ import { ExecutionContext, ModuleMetadata, FactoryProvider, DynamicModule, CanActivate } from '@nestjs/common';
2
+ import { Rbac, Subject, TeamId, SubjectRbac } from '@anievo-id/rbac-evolution';
3
+ import { Reflector } from '@nestjs/core';
4
+
5
+ type MaybePromise<T> = T | Promise<T>;
6
+ interface RbacModuleOptions {
7
+ /** The RBAC engine created with `createRbac(...)`. */
8
+ rbac: Rbac;
9
+ /**
10
+ * Resolves the authenticated subject for this execution context (e.g. from `request.user`).
11
+ * Return `null` / `undefined` for guests.
12
+ */
13
+ getSubject: (context: ExecutionContext) => MaybePromise<Subject | null | undefined>;
14
+ /** RBAC guard name (e.g. `web` or `api`) — not a Nest guard. Defaults to the engine's `defaultGuard`. */
15
+ guard?: string;
16
+ /** Resolves the current team (only when the engine was created with `teams: true`). */
17
+ team?: (context: ExecutionContext) => MaybePromise<TeamId | undefined>;
18
+ /**
19
+ * Include the required roles/permissions in the 403 body (`required`).
20
+ * Default: `false` (like spatie's `display_permission_in_exception`).
21
+ */
22
+ exposeRequirements?: boolean;
23
+ }
24
+ interface GlobalGuardOption {
25
+ /**
26
+ * Register `RbacGuard` as a global guard (`APP_GUARD`), so every route resolves the subject
27
+ * (and `@CurrentRbac()` works without a `@Require*` decorator). Default: `false`.
28
+ */
29
+ globalGuard?: boolean;
30
+ }
31
+ interface RbacModuleConfig extends RbacModuleOptions, GlobalGuardOption {
32
+ }
33
+ interface RbacModuleAsyncConfig extends GlobalGuardOption, Pick<ModuleMetadata, 'imports'> {
34
+ /** Providers to inject into `useFactory`. */
35
+ inject?: FactoryProvider['inject'];
36
+ /** Builds the options, e.g. from a `ConfigService`. */
37
+ useFactory: (...args: never[]) => MaybePromise<RbacModuleOptions>;
38
+ }
39
+
40
+ /**
41
+ * Registers rbac-evolution in a Nest application (global module).
42
+ *
43
+ * ```ts
44
+ * @Module({
45
+ * imports: [
46
+ * RbacModule.forRoot({
47
+ * rbac,
48
+ * getSubject: (ctx) => {
49
+ * const user = ctx.switchToHttp().getRequest().user
50
+ * return user ? { type: 'user', id: user.id } : null
51
+ * },
52
+ * }),
53
+ * ],
54
+ * })
55
+ * export class AppModule {}
56
+ * ```
57
+ */
58
+ declare class RbacModule {
59
+ static forRoot(config: RbacModuleConfig): DynamicModule;
60
+ /** Like {@link forRoot}, with options built by a factory (e.g. from a `ConfigService`). */
61
+ static forRootAsync(config: RbacModuleAsyncConfig): DynamicModule;
62
+ }
63
+
64
+ /**
65
+ * Resolves the current subject (once per request) and enforces the `@RequirePermissions()`,
66
+ * `@RequireRoles()` and `@RequireRoleOrPermission()` metadata of the class and the handler.
67
+ *
68
+ * - no subject → `UnauthorizedException` `401 { error: 'UNAUTHENTICATED', message }`
69
+ * - missing access → `ForbiddenException` `403 { error: 'FORBIDDEN', reason, message }`
70
+ *
71
+ * Bodies are identical to `@anievo-id/rbac-evolution-express`.
72
+ */
73
+ declare class RbacGuard implements CanActivate {
74
+ private readonly reflector;
75
+ private readonly options;
76
+ constructor(reflector: Reflector, options: RbacModuleOptions);
77
+ canActivate(context: ExecutionContext): Promise<boolean>;
78
+ private resolve;
79
+ }
80
+
81
+ /** Which kind of requirement failed — same values as the Express package. */
82
+ type RequirementKind = 'permission' | 'role' | 'role_or_permission';
83
+ /** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
84
+ type RequirementNames = string | readonly string[];
85
+ /** One `@Require*` decorator, normalized. */
86
+ interface RbacRequirement {
87
+ kind: RequirementKind;
88
+ /** Groups of names: every group must pass, a group passes when ANY of its names matches. */
89
+ requirements: string[][];
90
+ }
91
+ interface PermissionRequirementOptions {
92
+ /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
93
+ any?: boolean;
94
+ }
95
+ interface RoleRequirementOptions {
96
+ /** Require ALL of the roles (instead of any). Default: `false`. */
97
+ all?: boolean;
98
+ }
99
+
100
+ /**
101
+ * Requires permissions, like spatie's `permission:` middleware. Works on controllers and handlers.
102
+ *
103
+ * - `@RequirePermissions('edit articles')`
104
+ * - `@RequirePermissions('edit articles|delete articles')` — any of them
105
+ * - `@RequirePermissions('edit articles', 'publish articles')` — all of them
106
+ * - `@RequirePermissions('a', 'b', { any: true })` — any of them
107
+ */
108
+ declare function RequirePermissions(...args: (RequirementNames | PermissionRequirementOptions)[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
109
+ /**
110
+ * Requires roles, like spatie's `role:` middleware.
111
+ *
112
+ * - `@RequireRoles('admin')`, `@RequireRoles('admin|editor')`, `@RequireRoles('admin', 'editor')` — any of them
113
+ * - `@RequireRoles('admin', 'editor', { all: true })` — all of them
114
+ */
115
+ declare function RequireRoles(...args: (RequirementNames | RoleRequirementOptions)[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
116
+ /**
117
+ * Passes when the subject has ANY of the names as a role OR as a permission,
118
+ * like spatie's `role_or_permission:` middleware.
119
+ *
120
+ * - `@RequireRoleOrPermission('admin|edit articles')`
121
+ */
122
+ declare function RequireRoleOrPermission(...names: RequirementNames[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
123
+ /**
124
+ * Injects the current subject's `SubjectRbac` (`null` for guests), as resolved by `RbacGuard`.
125
+ *
126
+ * ```ts
127
+ * @Get('me/permissions')
128
+ * @UseGuards(RbacGuard)
129
+ * snapshot(@CurrentRbac() rbac: SubjectRbac | null) {
130
+ * return rbac?.snapshot() ?? null
131
+ * }
132
+ * ```
133
+ */
134
+ declare const CurrentRbac: () => ParameterDecorator;
135
+
136
+ declare class RbacGuardMissingError extends Error {
137
+ readonly code = "RBAC_GUARD_MISSING";
138
+ constructor();
139
+ }
140
+ /**
141
+ * Returns the `SubjectRbac` that `RbacGuard` resolved for this execution context (`null` for guests).
142
+ * Throws {@link RbacGuardMissingError} when the guard has not run.
143
+ */
144
+ declare function getRbac(context: ExecutionContext): SubjectRbac | null;
145
+
146
+ /** Injection token for the resolved {@link RbacModuleOptions}. */
147
+ declare const RBAC_MODULE_OPTIONS: unique symbol;
148
+ /** Injection token for the `Rbac` engine passed to `RbacModule.forRoot({ rbac })`. */
149
+ declare const RBAC: unique symbol;
150
+ /** Metadata key under which `@Require*` decorators store their requirements. */
151
+ declare const RBAC_REQUIREMENTS = "rbac-evolution:requirements";
152
+
153
+ export { CurrentRbac, type PermissionRequirementOptions, RBAC, RBAC_MODULE_OPTIONS, RBAC_REQUIREMENTS, RbacGuard, RbacGuardMissingError, RbacModule, type RbacModuleAsyncConfig, type RbacModuleConfig, type RbacModuleOptions, type RbacRequirement, RequirePermissions, RequireRoleOrPermission, RequireRoles, type RequirementKind, type RequirementNames, type RoleRequirementOptions, getRbac };
package/dist/index.js ADDED
@@ -0,0 +1,243 @@
1
+ import { Injectable, Inject, Global, Module, createParamDecorator, UnauthorizedException, ForbiddenException, applyDecorators, UseGuards } from '@nestjs/common';
2
+ import { Reflector, APP_GUARD } from '@nestjs/core';
3
+ import 'reflect-metadata';
4
+
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __decorateClass = (decorators, target, key, kind) => {
7
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
8
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
9
+ if (decorator = decorators[i])
10
+ result = (decorator(result)) || result;
11
+ return result;
12
+ };
13
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
14
+
15
+ // src/context.ts
16
+ var RbacGuardMissingError = class extends Error {
17
+ code = "RBAC_GUARD_MISSING";
18
+ constructor() {
19
+ super(
20
+ "`@CurrentRbac()` was used but `RbacGuard` did not run for this route. Add a `@Require*()` decorator, `@UseGuards(RbacGuard)`, or `RbacModule.forRoot({ globalGuard: true })`."
21
+ );
22
+ this.name = "RbacGuardMissingError";
23
+ }
24
+ };
25
+ var resolved = /* @__PURE__ */ new WeakMap();
26
+ function requestKey(context) {
27
+ let key;
28
+ switch (context.getType()) {
29
+ case "http":
30
+ key = context.switchToHttp().getRequest();
31
+ break;
32
+ case "rpc":
33
+ key = context.switchToRpc().getContext();
34
+ break;
35
+ case "ws":
36
+ key = context.switchToWs().getClient();
37
+ break;
38
+ default:
39
+ key = context.getArgByIndex(2);
40
+ }
41
+ return typeof key === "object" && key !== null ? key : void 0;
42
+ }
43
+ function hasResolved(key) {
44
+ return resolved.has(key);
45
+ }
46
+ function getResolved(key) {
47
+ return resolved.get(key);
48
+ }
49
+ function setResolved(key, rbac) {
50
+ resolved.set(key, rbac);
51
+ }
52
+ function getRbac(context) {
53
+ const key = requestKey(context);
54
+ if (key === void 0 || !resolved.has(key)) throw new RbacGuardMissingError();
55
+ return resolved.get(key) ?? null;
56
+ }
57
+
58
+ // src/requirements.ts
59
+ var MESSAGES = {
60
+ permission: "User does not have the right permissions.",
61
+ role: "User does not have the right roles.",
62
+ role_or_permission: "User does not have any of the necessary access rights."
63
+ };
64
+ var UNAUTHENTICATED_MESSAGE = "User is not logged in.";
65
+ var split = (name) => name.split("|").map((n) => n.trim()).filter((n) => n !== "");
66
+ function toGroups(names) {
67
+ const groups = [];
68
+ for (const name of names) {
69
+ for (const item of typeof name === "string" ? [name] : name) {
70
+ const group = split(item);
71
+ if (group.length > 0) groups.push(group);
72
+ }
73
+ }
74
+ return groups;
75
+ }
76
+ function parseArgs(args) {
77
+ const last = args[args.length - 1];
78
+ if (last !== void 0 && typeof last === "object" && !Array.isArray(last)) {
79
+ return { names: args.slice(0, -1), options: last };
80
+ }
81
+ return { names: args, options: void 0 };
82
+ }
83
+ function ensure(requirement) {
84
+ const { requirements } = requirement;
85
+ if (requirements.length === 0 || requirements.some((group) => group.length === 0)) {
86
+ throw new TypeError(`[rbac-evolution] A ${requirement.kind} requirement needs at least one name.`);
87
+ }
88
+ return requirement;
89
+ }
90
+ function permissionRequirement(args) {
91
+ const { names, options = {} } = parseArgs(args);
92
+ const groups = toGroups(names);
93
+ return ensure({ kind: "permission", requirements: options.any ? [groups.flat()] : groups });
94
+ }
95
+ function roleRequirement(args) {
96
+ const { names, options = {} } = parseArgs(args);
97
+ const all = toGroups(names).flat();
98
+ return ensure({ kind: "role", requirements: options.all ? all.map((r) => [r]) : [all] });
99
+ }
100
+ function roleOrPermissionRequirement(names) {
101
+ return ensure({ kind: "role_or_permission", requirements: [toGroups(names).flat()] });
102
+ }
103
+ async function satisfies(rbac, requirement) {
104
+ for (const group of requirement.requirements) {
105
+ let pass;
106
+ switch (requirement.kind) {
107
+ case "permission":
108
+ pass = await rbac.canAny(group);
109
+ break;
110
+ case "role":
111
+ pass = await rbac.hasAnyRole(group);
112
+ break;
113
+ default:
114
+ pass = await rbac.hasAnyRole(group) || await rbac.canAny(group);
115
+ }
116
+ if (!pass) return false;
117
+ }
118
+ return true;
119
+ }
120
+
121
+ // src/tokens.ts
122
+ var RBAC_MODULE_OPTIONS = /* @__PURE__ */ Symbol.for("rbac-evolution:nestjs:options");
123
+ var RBAC = /* @__PURE__ */ Symbol.for("rbac-evolution:nestjs:rbac");
124
+ var RBAC_REQUIREMENTS = "rbac-evolution:requirements";
125
+
126
+ // src/guard.ts
127
+ var enforced = /* @__PURE__ */ new WeakMap();
128
+ var RbacGuard = class {
129
+ // Explicit tokens: the package is built with esbuild, which does not emit `design:paramtypes`.
130
+ constructor(reflector, options) {
131
+ this.reflector = reflector;
132
+ this.options = options;
133
+ }
134
+ reflector;
135
+ options;
136
+ async canActivate(context) {
137
+ const key = requestKey(context);
138
+ const rbac = await this.resolve(context, key);
139
+ const handler = context.getHandler();
140
+ if (key !== void 0) {
141
+ const done = enforced.get(key) ?? /* @__PURE__ */ new Set();
142
+ if (done.has(handler)) return true;
143
+ enforced.set(key, done.add(handler));
144
+ }
145
+ const requirements = [
146
+ ...this.reflector.get(RBAC_REQUIREMENTS, context.getClass()) ?? [],
147
+ ...this.reflector.get(RBAC_REQUIREMENTS, handler) ?? []
148
+ ];
149
+ if (requirements.length === 0) return true;
150
+ if (rbac === null) {
151
+ throw new UnauthorizedException({ error: "UNAUTHENTICATED", message: UNAUTHENTICATED_MESSAGE });
152
+ }
153
+ for (const requirement of requirements) {
154
+ if (!await satisfies(rbac, requirement)) {
155
+ throw new ForbiddenException({
156
+ error: "FORBIDDEN",
157
+ reason: requirement.kind,
158
+ message: MESSAGES[requirement.kind],
159
+ ...this.options.exposeRequirements && { required: requirement.requirements }
160
+ });
161
+ }
162
+ }
163
+ return true;
164
+ }
165
+ async resolve(context, key) {
166
+ if (key !== void 0 && hasResolved(key)) return getResolved(key) ?? null;
167
+ const { rbac, getSubject, guard, team } = this.options;
168
+ const subject = await getSubject(context);
169
+ let result = null;
170
+ if (subject) {
171
+ const teamId = team ? await team(context) : void 0;
172
+ result = rbac.for(subject, {
173
+ ...guard !== void 0 && { guard },
174
+ ...teamId !== void 0 && { team: teamId }
175
+ });
176
+ }
177
+ if (key !== void 0) setResolved(key, result);
178
+ return result;
179
+ }
180
+ };
181
+ RbacGuard = __decorateClass([
182
+ Injectable(),
183
+ __decorateParam(0, Inject(Reflector)),
184
+ __decorateParam(1, Inject(RBAC_MODULE_OPTIONS))
185
+ ], RbacGuard);
186
+
187
+ // src/module.ts
188
+ function build(optionsProvider, globalGuard, imports = []) {
189
+ return {
190
+ module: RbacModule,
191
+ global: true,
192
+ imports,
193
+ providers: [
194
+ optionsProvider,
195
+ { provide: RBAC, useFactory: (options) => options.rbac, inject: [RBAC_MODULE_OPTIONS] },
196
+ RbacGuard,
197
+ ...globalGuard ? [{ provide: APP_GUARD, useClass: RbacGuard }] : []
198
+ ],
199
+ exports: [RBAC_MODULE_OPTIONS, RBAC, RbacGuard]
200
+ };
201
+ }
202
+ var RbacModule = class {
203
+ static forRoot(config) {
204
+ const { globalGuard = false, ...options } = config;
205
+ return build({ provide: RBAC_MODULE_OPTIONS, useValue: options }, globalGuard);
206
+ }
207
+ /** Like {@link forRoot}, with options built by a factory (e.g. from a `ConfigService`). */
208
+ static forRootAsync(config) {
209
+ return build(
210
+ { provide: RBAC_MODULE_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },
211
+ config.globalGuard ?? false,
212
+ config.imports ?? []
213
+ );
214
+ }
215
+ };
216
+ RbacModule = __decorateClass([
217
+ Global(),
218
+ Module({})
219
+ ], RbacModule);
220
+ function appendRequirement(requirement) {
221
+ return (target, _propertyKey, descriptor) => {
222
+ const holder = descriptor?.value !== void 0 ? descriptor.value : target;
223
+ const current = Reflect.getMetadata(RBAC_REQUIREMENTS, holder) ?? [];
224
+ Reflect.defineMetadata(RBAC_REQUIREMENTS, [...current, requirement], holder);
225
+ };
226
+ }
227
+ var requirementDecorator = (requirement) => applyDecorators(appendRequirement(requirement), UseGuards(RbacGuard));
228
+ function RequirePermissions(...args) {
229
+ return requirementDecorator(permissionRequirement(args));
230
+ }
231
+ function RequireRoles(...args) {
232
+ return requirementDecorator(roleRequirement(args));
233
+ }
234
+ function RequireRoleOrPermission(...names) {
235
+ return requirementDecorator(roleOrPermissionRequirement(names));
236
+ }
237
+ var CurrentRbac = createParamDecorator(
238
+ (_data, context) => getRbac(context)
239
+ );
240
+
241
+ export { CurrentRbac, RBAC, RBAC_MODULE_OPTIONS, RBAC_REQUIREMENTS, RbacGuard, RbacGuardMissingError, RbacModule, RequirePermissions, RequireRoleOrPermission, RequireRoles, getRbac };
242
+ //# sourceMappingURL=index.js.map
243
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context.ts","../src/requirements.ts","../src/tokens.ts","../src/guard.ts","../src/module.ts","../src/decorators.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAGO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EACtC,IAAA,GAAO,oBAAA;AAAA,EAEhB,WAAA,GAAc;AACZ,IAAA,KAAA;AAAA,MACE;AAAA,KAEF;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EACd;AACF;AAGA,IAAM,QAAA,uBAAe,OAAA,EAAoC;AAMlD,SAAS,WAAW,OAAA,EAA+C;AACxE,EAAA,IAAI,GAAA;AACJ,EAAA,QAAQ,OAAA,CAAQ,SAAgB;AAAG,IACjC,KAAK,MAAA;AACH,MAAA,GAAA,GAAM,OAAA,CAAQ,YAAA,EAAa,CAAE,UAAA,EAAW;AACxC,MAAA;AAAA,IACF,KAAK,KAAA;AACH,MAAA,GAAA,GAAM,OAAA,CAAQ,WAAA,EAAY,CAAE,UAAA,EAAW;AACvC,MAAA;AAAA,IACF,KAAK,IAAA;AACH,MAAA,GAAA,GAAM,OAAA,CAAQ,UAAA,EAAW,CAAE,SAAA,EAAU;AACrC,MAAA;AAAA,IACF;AACE,MAAA,GAAA,GAAM,OAAA,CAAQ,cAAc,CAAC,CAAA;AAAA;AAEjC,EAAA,OAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,OAAO,GAAA,GAAM,MAAA;AACzD;AAEO,SAAS,YAAY,GAAA,EAAsB;AAChD,EAAA,OAAO,QAAA,CAAS,IAAI,GAAG,CAAA;AACzB;AAEO,SAAS,YAAY,GAAA,EAA6C;AACvE,EAAA,OAAO,QAAA,CAAS,IAAI,GAAG,CAAA;AACzB;AAEO,SAAS,WAAA,CAAY,KAAa,IA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BAAA,EAAmB,MAAM,KAAuC,EAAC;AACtG,IAAA,OAAA,CAAQ,eAAe,iBAAA,EAAmB,CAAC,GAAG,OAAA,EAAS,WAAW,GAAG,MAAM,CAAA;AAAA,EAC7E,CAAA;AACF;AAEA,IAAM,oBAAA,GAAuB,CAAC,WAAA,KAC5B,eAAA,CAAgB,kBAAkB,WAAW,CAAA,EAAG,SAAA,CAAU,SAAS,CAAC,CAAA;AAU/D,SAAS,sBAAsB,IAAA,EAA2D;AAC/F,EAAA,OAAO,oBAAA,CAAqB,qBAAA,CAAsB,IAAI,CAAC,CAAA;AACzD;AAQO,SAAS,gBAAgB,IAAA,EAAqD;AACnF,EAAA,OAAO,oBAAA,CAAqB,eAAA,CAAgB,IAAI,CAAC,CAAA;AACnD;AAQO,SAAS,2BAA2B,KAAA,EAA2B;AACpE,EAAA,OAAO,oBAAA,CAAqB,2BAAA,CAA4B,KAAK,CAAC,CAAA;AAChE;AAaO,IAAM,WAAA,GAAwC,oBAAA;AAAA,EACnD,CAAC,KAAA,EAAgB,OAAA,KAAkD,OAAA,CAAQ,OAAO;AACpF","file":"index.js","sourcesContent":["import type { SubjectRbac } from '@anievo-id/rbac-evolution'\nimport type { ExecutionContext } from '@nestjs/common'\n\nexport class RbacGuardMissingError extends Error {\n readonly code = 'RBAC_GUARD_MISSING'\n\n constructor() {\n super(\n '`@CurrentRbac()` was used but `RbacGuard` did not run for this route. Add a `@Require*()` decorator, ' +\n '`@UseGuards(RbacGuard)`, or `RbacModule.forRoot({ globalGuard: true })`.',\n )\n this.name = 'RbacGuardMissingError'\n }\n}\n\n/** Per-request resolved `SubjectRbac` (`null` for guests), keyed by the request/client/context object. */\nconst resolved = new WeakMap<object, SubjectRbac | null>()\n\n/**\n * The object that identifies the current request: the HTTP request, the RPC context, the WebSocket client,\n * or (for GraphQL and other context types) the third handler argument.\n */\nexport function requestKey(context: ExecutionContext): object | undefined {\n let key: unknown\n switch (context.getType<string>()) {\n case 'http':\n key = context.switchToHttp().getRequest()\n break\n case 'rpc':\n key = context.switchToRpc().getContext()\n break\n case 'ws':\n key = context.switchToWs().getClient()\n break\n default:\n key = context.getArgByIndex(2)\n }\n return typeof key === 'object' && key !== null ? key : undefined\n}\n\nexport function hasResolved(key: object): boolean {\n return resolved.has(key)\n}\n\nexport function getResolved(key: object): SubjectRbac | null | undefined {\n return resolved.get(key)\n}\n\nexport function setResolved(key: object, rbac: SubjectRbac | null): void {\n resolved.set(key, rbac)\n}\n\n/**\n * Returns the `SubjectRbac` that `RbacGuard` resolved for this execution context (`null` for guests).\n * Throws {@link RbacGuardMissingError} when the guard has not run.\n */\nexport function getRbac(context: ExecutionContext): SubjectRbac | null {\n const key = requestKey(context)\n if (key === undefined || !resolved.has(key)) throw new RbacGuardMissingError()\n return resolved.get(key) ?? null\n}\n","import type { SubjectRbac } from '@anievo-id/rbac-evolution'\n\n/** Which kind of requirement failed — same values as the Express package. */\nexport type RequirementKind = 'permission' | 'role' | 'role_or_permission'\n\n/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */\nexport type RequirementNames = string | readonly string[]\n\n/** One `@Require*` decorator, normalized. */\nexport interface RbacRequirement {\n kind: RequirementKind\n /** Groups of names: every group must pass, a group passes when ANY of its names matches. */\n requirements: string[][]\n}\n\nexport interface PermissionRequirementOptions {\n /** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */\n any?: boolean\n}\n\nexport interface RoleRequirementOptions {\n /** Require ALL of the roles (instead of any). Default: `false`. */\n all?: boolean\n}\n\nexport const MESSAGES: Record<RequirementKind, string> = {\n permission: 'User does not have the right permissions.',\n role: 'User does not have the right roles.',\n role_or_permission: 'User does not have any of the necessary access rights.',\n}\n\nexport const UNAUTHENTICATED_MESSAGE = 'User is not logged in.'\n\nconst split = (name: string): string[] =>\n name\n .split('|')\n .map((n) => n.trim())\n .filter((n) => n !== '')\n\n/** Each argument is a group (pipes = any within the group); arrays contribute one group per item. */\nfunction toGroups(names: readonly RequirementNames[]): string[][] {\n const groups: string[][] = []\n for (const name of names) {\n for (const item of typeof name === 'string' ? [name] : name) {\n const group = split(item)\n if (group.length > 0) groups.push(group)\n }\n }\n return groups\n}\n\nfunction parseArgs<O extends object>(args: readonly (RequirementNames | O)[]): { names: RequirementNames[]; options: O | undefined } {\n const last = args[args.length - 1]\n if (last !== undefined && typeof last === 'object' && !Array.isArray(last)) {\n return { names: args.slice(0, -1) as RequirementNames[], options: last as O }\n }\n return { names: args as RequirementNames[], options: undefined }\n}\n\nfunction ensure(requirement: RbacRequirement): RbacRequirement {\n const { requirements } = requirement\n if (requirements.length === 0 || requirements.some((group) => group.length === 0)) {\n throw new TypeError(`[rbac-evolution] A ${requirement.kind} requirement needs at least one name.`)\n }\n return requirement\n}\n\n/** `'a', 'b'` = all; `'a|b'` = any; `{ any: true }` = any of everything. */\nexport function permissionRequirement(args: readonly (RequirementNames | PermissionRequirementOptions)[]): RbacRequirement {\n const { names, options = {} } = parseArgs<PermissionRequirementOptions>(args)\n const groups = toGroups(names)\n return ensure({ kind: 'permission', requirements: options.any ? [groups.flat()] : groups })\n}\n\n/** Any of the roles by default; `{ all: true }` = all of them. */\nexport function roleRequirement(args: readonly (RequirementNames | RoleRequirementOptions)[]): RbacRequirement {\n const { names, options = {} } = parseArgs<RoleRequirementOptions>(args)\n const all = toGroups(names).flat()\n return ensure({ kind: 'role', requirements: options.all ? all.map((r) => [r]) : [all] })\n}\n\n/** Any of the names, as a role OR as a permission. */\nexport function roleOrPermissionRequirement(names: readonly RequirementNames[]): RbacRequirement {\n return ensure({ kind: 'role_or_permission', requirements: [toGroups(names).flat()] })\n}\n\n/** `true` when every group of the requirement passes for the subject. */\nexport async function satisfies(rbac: SubjectRbac, requirement: RbacRequirement): Promise<boolean> {\n for (const group of requirement.requirements) {\n let pass: boolean\n switch (requirement.kind) {\n case 'permission':\n pass = await rbac.canAny(group)\n break\n case 'role':\n pass = await rbac.hasAnyRole(group)\n break\n default:\n pass = (await rbac.hasAnyRole(group)) || (await rbac.canAny(group))\n }\n if (!pass) return false\n }\n return true\n}\n","/** Injection token for the resolved {@link RbacModuleOptions}. */\nexport const RBAC_MODULE_OPTIONS = Symbol.for('rbac-evolution:nestjs:options')\n\n/** Injection token for the `Rbac` engine passed to `RbacModule.forRoot({ rbac })`. */\nexport const RBAC = Symbol.for('rbac-evolution:nestjs:rbac')\n\n/** Metadata key under which `@Require*` decorators store their requirements. */\nexport const RBAC_REQUIREMENTS = 'rbac-evolution:requirements'\n","import type { SubjectRbac } from '@anievo-id/rbac-evolution'\nimport {\n type CanActivate,\n type ExecutionContext,\n ForbiddenException,\n Inject,\n Injectable,\n UnauthorizedException,\n} from '@nestjs/common'\nimport { Reflector } from '@nestjs/core'\nimport { getResolved, hasResolved, requestKey, setResolved } from './context'\nimport type { RbacModuleOptions } from './options'\nimport { MESSAGES, type RbacRequirement, satisfies, UNAUTHENTICATED_MESSAGE } from './requirements'\nimport { RBAC_MODULE_OPTIONS, RBAC_REQUIREMENTS } from './tokens'\n\n/** Handlers already enforced for a request — the guard may run twice (global + `@UseGuards`). */\nconst enforced = new WeakMap<object, Set<unknown>>()\n\n/**\n * Resolves the current subject (once per request) and enforces the `@RequirePermissions()`,\n * `@RequireRoles()` and `@RequireRoleOrPermission()` metadata of the class and the handler.\n *\n * - no subject → `UnauthorizedException` `401 { error: 'UNAUTHENTICATED', message }`\n * - missing access → `ForbiddenException` `403 { error: 'FORBIDDEN', reason, message }`\n *\n * Bodies are identical to `@anievo-id/rbac-evolution-express`.\n */\n@Injectable()\nexport class RbacGuard implements CanActivate {\n // Explicit tokens: the package is built with esbuild, which does not emit `design:paramtypes`.\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(RBAC_MODULE_OPTIONS) private readonly options: RbacModuleOptions,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const key = requestKey(context)\n const rbac = await this.resolve(context, key)\n\n const handler = context.getHandler()\n if (key !== undefined) {\n const done = enforced.get(key) ?? new Set<unknown>()\n if (done.has(handler)) return true\n enforced.set(key, done.add(handler))\n }\n\n const requirements = [\n ...(this.reflector.get<RbacRequirement[] | undefined>(RBAC_REQUIREMENTS, context.getClass()) ?? []),\n ...(this.reflector.get<RbacRequirement[] | undefined>(RBAC_REQUIREMENTS, handler) ?? []),\n ]\n if (requirements.length === 0) return true\n\n if (rbac === null) {\n throw new UnauthorizedException({ error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE })\n }\n\n for (const requirement of requirements) {\n if (!(await satisfies(rbac, requirement))) {\n throw new ForbiddenException({\n error: 'FORBIDDEN',\n reason: requirement.kind,\n message: MESSAGES[requirement.kind],\n ...(this.options.exposeRequirements && { required: requirement.requirements }),\n })\n }\n }\n return true\n }\n\n private async resolve(context: ExecutionContext, key: object | undefined): Promise<SubjectRbac | null> {\n if (key !== undefined && hasResolved(key)) return getResolved(key) ?? null\n\n const { rbac, getSubject, guard, team } = this.options\n const subject = await getSubject(context)\n let result: SubjectRbac | null = null\n if (subject) {\n const teamId = team ? await team(context) : undefined\n result = rbac.for(subject, {\n ...(guard !== undefined && { guard }),\n ...(teamId !== undefined && { team: teamId }),\n })\n }\n if (key !== undefined) setResolved(key, result)\n return result\n }\n}\n","import { type DynamicModule, Global, Module, type Provider } from '@nestjs/common'\nimport { APP_GUARD } from '@nestjs/core'\nimport { RbacGuard } from './guard'\nimport type { RbacModuleAsyncConfig, RbacModuleConfig, RbacModuleOptions } from './options'\nimport { RBAC, RBAC_MODULE_OPTIONS } from './tokens'\n\nfunction build(optionsProvider: Provider, globalGuard: boolean, imports: DynamicModule['imports'] = []): DynamicModule {\n return {\n module: RbacModule,\n global: true,\n imports,\n providers: [\n optionsProvider,\n { provide: RBAC, useFactory: (options: RbacModuleOptions) => options.rbac, inject: [RBAC_MODULE_OPTIONS] },\n RbacGuard,\n ...(globalGuard ? [{ provide: APP_GUARD, useClass: RbacGuard }] : []),\n ],\n exports: [RBAC_MODULE_OPTIONS, RBAC, RbacGuard],\n }\n}\n\n/**\n * Registers rbac-evolution in a Nest application (global module).\n *\n * ```ts\n * @Module({\n * imports: [\n * RbacModule.forRoot({\n * rbac,\n * getSubject: (ctx) => {\n * const user = ctx.switchToHttp().getRequest().user\n * return user ? { type: 'user', id: user.id } : null\n * },\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n@Global()\n@Module({})\nexport class RbacModule {\n static forRoot(config: RbacModuleConfig): DynamicModule {\n const { globalGuard = false, ...options } = config\n return build({ provide: RBAC_MODULE_OPTIONS, useValue: options }, globalGuard)\n }\n\n /** Like {@link forRoot}, with options built by a factory (e.g. from a `ConfigService`). */\n static forRootAsync(config: RbacModuleAsyncConfig): DynamicModule {\n return build(\n { provide: RBAC_MODULE_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },\n config.globalGuard ?? false,\n config.imports ?? [],\n )\n }\n}\n","import 'reflect-metadata'\nimport type { SubjectRbac } from '@anievo-id/rbac-evolution'\nimport { applyDecorators, createParamDecorator, type ExecutionContext, UseGuards } from '@nestjs/common'\nimport { getRbac } from './context'\nimport { RbacGuard } from './guard'\nimport {\n type PermissionRequirementOptions,\n permissionRequirement,\n type RbacRequirement,\n type RequirementNames,\n roleOrPermissionRequirement,\n roleRequirement,\n type RoleRequirementOptions,\n} from './requirements'\nimport { RBAC_REQUIREMENTS } from './tokens'\n\ntype ClassOrMethodDecorator = <T>(\n target: object,\n propertyKey?: string | symbol,\n descriptor?: TypedPropertyDescriptor<T>,\n) => void\n\n/** Appends a requirement (stacked decorators all apply), unlike `SetMetadata` which overwrites. */\nfunction appendRequirement(requirement: RbacRequirement): ClassOrMethodDecorator {\n return (target, _propertyKey, descriptor) => {\n const holder: object = descriptor?.value !== undefined ? (descriptor.value as object) : target\n const current = (Reflect.getMetadata(RBAC_REQUIREMENTS, holder) as RbacRequirement[] | undefined) ?? []\n Reflect.defineMetadata(RBAC_REQUIREMENTS, [...current, requirement], holder)\n }\n}\n\nconst requirementDecorator = (requirement: RbacRequirement) =>\n applyDecorators(appendRequirement(requirement), UseGuards(RbacGuard))\n\n/**\n * Requires permissions, like spatie's `permission:` middleware. Works on controllers and handlers.\n *\n * - `@RequirePermissions('edit articles')`\n * - `@RequirePermissions('edit articles|delete articles')` — any of them\n * - `@RequirePermissions('edit articles', 'publish articles')` — all of them\n * - `@RequirePermissions('a', 'b', { any: true })` — any of them\n */\nexport function RequirePermissions(...args: (RequirementNames | PermissionRequirementOptions)[]) {\n return requirementDecorator(permissionRequirement(args))\n}\n\n/**\n * Requires roles, like spatie's `role:` middleware.\n *\n * - `@RequireRoles('admin')`, `@RequireRoles('admin|editor')`, `@RequireRoles('admin', 'editor')` — any of them\n * - `@RequireRoles('admin', 'editor', { all: true })` — all of them\n */\nexport function RequireRoles(...args: (RequirementNames | RoleRequirementOptions)[]) {\n return requirementDecorator(roleRequirement(args))\n}\n\n/**\n * Passes when the subject has ANY of the names as a role OR as a permission,\n * like spatie's `role_or_permission:` middleware.\n *\n * - `@RequireRoleOrPermission('admin|edit articles')`\n */\nexport function RequireRoleOrPermission(...names: RequirementNames[]) {\n return requirementDecorator(roleOrPermissionRequirement(names))\n}\n\n/**\n * Injects the current subject's `SubjectRbac` (`null` for guests), as resolved by `RbacGuard`.\n *\n * ```ts\n * @Get('me/permissions')\n * @UseGuards(RbacGuard)\n * snapshot(@CurrentRbac() rbac: SubjectRbac | null) {\n * return rbac?.snapshot() ?? null\n * }\n * ```\n */\nexport const CurrentRbac: () => ParameterDecorator = createParamDecorator(\n (_data: unknown, context: ExecutionContext): SubjectRbac | null => getRbac(context),\n)\n"]}
package/package.json CHANGED
@@ -1,6 +1,79 @@
1
1
  {
2
2
  "name": "@anievo-id/rbac-evolution-nestjs",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "NestJS module, guard & decorators for rbac-evolution.",
5
+ "license": "MIT",
6
+ "author": "AniEvo-ID (https://github.com/AniEvo-ID)",
7
+ "homepage": "https://github.com/AniEvo-ID/rbac-evolution/tree/main/packages/nestjs#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/AniEvo-ID/rbac-evolution/issues"
10
+ },
11
+ "type": "module",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/AniEvo-ID/rbac-evolution.git",
15
+ "directory": "packages/nestjs"
16
+ },
17
+ "keywords": [
18
+ "rbac",
19
+ "permissions",
20
+ "roles",
21
+ "authorization",
22
+ "nestjs",
23
+ "nest",
24
+ "guard",
25
+ "decorators"
26
+ ],
27
+ "sideEffects": false,
28
+ "main": "./dist/index.cjs",
29
+ "module": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "import": {
34
+ "types": "./dist/index.d.ts",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "require": {
38
+ "types": "./dist/index.d.cts",
39
+ "default": "./dist/index.cjs"
40
+ }
41
+ },
42
+ "./package.json": "./package.json"
43
+ },
44
+ "files": [
45
+ "dist"
46
+ ],
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "dependencies": {
51
+ "@anievo-id/rbac-evolution": "^0.3.0"
52
+ },
53
+ "peerDependencies": {
54
+ "@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0",
55
+ "@nestjs/core": "^10.0.0 || ^11.0.0 || ^12.0.0",
56
+ "reflect-metadata": "^0.1.13 || ^0.2.0"
57
+ },
58
+ "devDependencies": {
59
+ "@nestjs/common": "^12.5.0",
60
+ "@nestjs/core": "^12.5.0",
61
+ "@nestjs/platform-express": "^12.5.0",
62
+ "@nestjs/testing": "^12.5.0",
63
+ "reflect-metadata": "^0.2.2",
64
+ "rxjs": "^7.8.2",
65
+ "tsup": "^8.3.0",
66
+ "typescript": "^5.7.0",
67
+ "vitest": "^2.1.0"
68
+ },
69
+ "engines": {
70
+ "node": ">=20"
71
+ },
72
+ "scripts": {
73
+ "build": "tsup",
74
+ "dev": "tsup --watch",
75
+ "typecheck": "tsc --noEmit",
76
+ "test": "vitest run --passWithNoTests",
77
+ "clean": "rm -rf dist .turbo"
78
+ }
6
79
  }