@anievo-id/rbac-evolution-nestjs 0.4.1 → 0.6.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/dist/index.cjs CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var common = require('@nestjs/common');
4
4
  var core = require('@nestjs/core');
5
+ var rbacEvolution = require('@anievo-id/rbac-evolution');
5
6
  require('reflect-metadata');
6
7
 
7
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -57,69 +58,6 @@ function getRbac(context) {
57
58
  return resolved.get(key) ?? null;
58
59
  }
59
60
 
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
61
  // src/tokens.ts
124
62
  var RBAC_MODULE_OPTIONS = /* @__PURE__ */ Symbol.for("rbac-evolution:nestjs:options");
125
63
  var RBAC = /* @__PURE__ */ Symbol.for("rbac-evolution:nestjs:rbac");
@@ -148,14 +86,14 @@ exports.RbacGuard = class RbacGuard {
148
86
  ];
149
87
  if (requirements.length === 0) return true;
150
88
  if (rbac === null) {
151
- throw new common.UnauthorizedException({ error: "UNAUTHENTICATED", message: UNAUTHENTICATED_MESSAGE });
89
+ throw new common.UnauthorizedException({ error: "UNAUTHENTICATED", message: rbacEvolution.UNAUTHENTICATED_MESSAGE });
152
90
  }
153
91
  for (const requirement of requirements) {
154
- if (!await satisfies(rbac, requirement)) {
92
+ if (!await rbacEvolution.satisfiesRequirement(rbac, requirement)) {
155
93
  throw new common.ForbiddenException({
156
94
  error: "FORBIDDEN",
157
95
  reason: requirement.kind,
158
- message: MESSAGES[requirement.kind],
96
+ message: rbacEvolution.REQUIREMENT_MESSAGES[requirement.kind],
159
97
  ...this.options.exposeRequirements && { required: requirement.requirements }
160
98
  });
161
99
  }
@@ -227,7 +165,8 @@ function appendRequirement(requirement) {
227
165
  }
228
166
  var requirementDecorator = (requirement) => common.applyDecorators(appendRequirement(requirement), common.UseGuards(exports.RbacGuard));
229
167
  function RequirePermissions(...args) {
230
- return requirementDecorator(permissionRequirement(args));
168
+ const { names, options } = rbacEvolution.splitRequirementArgs(args);
169
+ return requirementDecorator(rbacEvolution.permissionRequirement(names, options));
231
170
  }
232
171
  function CanAny(...names) {
233
172
  return RequirePermissions(...names, { any: true });
@@ -236,10 +175,11 @@ function CanAll(...names) {
236
175
  return RequirePermissions(...names);
237
176
  }
238
177
  function RequireRoles(...args) {
239
- return requirementDecorator(roleRequirement(args));
178
+ const { names, options } = rbacEvolution.splitRequirementArgs(args);
179
+ return requirementDecorator(rbacEvolution.roleRequirement(names, options));
240
180
  }
241
181
  function RequireRoleOrPermission(...names) {
242
- return requirementDecorator(roleOrPermissionRequirement(names));
182
+ return requirementDecorator(rbacEvolution.roleOrPermissionRequirement(names));
243
183
  }
244
184
  var CurrentRbac = common.createParamDecorator(
245
185
  (_data, context) => getRbac(context)
@@ -1 +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,I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AAS,UAAU,KAAA,EAA2B;AACnD,EAAA,OAAO,kBAAA,CAAmB,GAAG,KAAK,CAAA;AACpC;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 * Only HTTP requests and RPC messages get a fresh key object per call. A WebSocket client or a\n * GraphQL context lives across many calls, so caching or skipping checks by it would let a denied\n * client through on its next message.\n */\nconst isPerCall = (context: ExecutionContext): boolean => ['http', 'rpc'].includes(context.getType<string>())\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 perCall = isPerCall(context)\n const rbac = await this.resolve(context, key, perCall)\n\n const handler = context.getHandler()\n if (perCall && key !== undefined && enforced.get(key)?.has(handler)) return true\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 // Mark as enforced only once every requirement passed.\n if (perCall && key !== undefined) enforced.set(key, (enforced.get(key) ?? new Set<unknown>()).add(handler))\n return true\n }\n\n private async resolve(context: ExecutionContext, key: object | undefined, perCall: boolean): Promise<SubjectRbac | null> {\n if (perCall && 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 * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `@CanAny('edit articles', 'publish articles')`, `@CanAny(['edit articles', 'publish articles'])`\n */\nexport function CanAny(...names: RequirementNames[]) {\n return RequirePermissions(...names, { any: true })\n}\n\n/**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `@CanAll('edit articles', 'publish articles')`, `@CanAll(['edit articles', 'publish|review'])`\n */\nexport function CanAll(...names: RequirementNames[]) {\n return RequirePermissions(...names)\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"]}
1
+ {"version":3,"sources":["../src/context.ts","../src/tokens.ts","../src/guard.ts","../src/module.ts","../src/decorators.ts"],"names":["RbacGuard","UnauthorizedException","UNAUTHENTICATED_MESSAGE","satisfiesRequirement","ForbiddenException","REQUIREMENT_MESSAGES","Injectable","Reflector","RbacModule","APP_GUARD","Global","Module","applyDecorators","UseGuards","splitRequirementArgs","permissionRequirement","roleRequirement","roleOrPermissionRequirement","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,CAAS,IAAI,GAAG,CAAA;AACzB;AAEO,SAAS,YAAY,GAAA,EA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,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,CAAUb,iBAAS,CAAC,CAAA;AAU/D,SAAS,sBAAsB,IAAA,EAA2D;AAC/F,EAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAIc,mCAAmD,IAAI,CAAA;AAClF,EAAA,OAAO,oBAAA,CAAqBC,mCAAA,CAAsB,KAAA,EAAO,OAAO,CAAC,CAAA;AACnE;AAOO,SAAS,UAAU,KAAA,EAA2B;AACnD,EAAA,OAAO,mBAAmB,GAAG,KAAA,EAAO,EAAE,GAAA,EAAK,MAAM,CAAA;AACnD;AAOO,SAAS,UAAU,KAAA,EAA2B;AACnD,EAAA,OAAO,kBAAA,CAAmB,GAAG,KAAK,CAAA;AACpC;AAQO,SAAS,gBAAgB,IAAA,EAAqD;AACnF,EAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAID,mCAA6C,IAAI,CAAA;AAC5E,EAAA,OAAO,oBAAA,CAAqBE,6BAAA,CAAgB,KAAA,EAAO,OAAO,CAAC,CAAA;AAC7D;AAQO,SAAS,2BAA2B,KAAA,EAA2B;AACpE,EAAA,OAAO,oBAAA,CAAqBC,yCAAA,CAA4B,KAAK,CAAC,CAAA;AAChE;AAaO,IAAM,WAAA,GAAwCC,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","/** 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 {\n type RbacRequirement,\n REQUIREMENT_MESSAGES,\n satisfiesRequirement,\n type SubjectRbac,\n UNAUTHENTICATED_MESSAGE,\n} 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 { 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 * Only HTTP requests and RPC messages get a fresh key object per call. A WebSocket client or a\n * GraphQL context lives across many calls, so caching or skipping checks by it would let a denied\n * client through on its next message.\n */\nconst isPerCall = (context: ExecutionContext): boolean => ['http', 'rpc'].includes(context.getType<string>())\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 perCall = isPerCall(context)\n const rbac = await this.resolve(context, key, perCall)\n\n const handler = context.getHandler()\n if (perCall && key !== undefined && enforced.get(key)?.has(handler)) return true\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 satisfiesRequirement(rbac, requirement))) {\n throw new ForbiddenException({\n error: 'FORBIDDEN',\n reason: requirement.kind,\n message: REQUIREMENT_MESSAGES[requirement.kind],\n ...(this.options.exposeRequirements && { required: requirement.requirements }),\n })\n }\n }\n // Mark as enforced only once every requirement passed.\n if (perCall && key !== undefined) enforced.set(key, (enforced.get(key) ?? new Set<unknown>()).add(handler))\n return true\n }\n\n private async resolve(context: ExecutionContext, key: object | undefined, perCall: boolean): Promise<SubjectRbac | null> {\n if (perCall && 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 { 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 splitRequirementArgs,\n type SubjectRbac,\n} from '@anievo-id/rbac-evolution'\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 const { names, options } = splitRequirementArgs<PermissionRequirementOptions>(args)\n return requirementDecorator(permissionRequirement(names, options))\n}\n\n/**\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `@CanAny('edit articles', 'publish articles')`, `@CanAny(['edit articles', 'publish articles'])`\n */\nexport function CanAny(...names: RequirementNames[]) {\n return RequirePermissions(...names, { any: true })\n}\n\n/**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `@CanAll('edit articles', 'publish articles')`, `@CanAll(['edit articles', 'publish|review'])`\n */\nexport function CanAll(...names: RequirementNames[]) {\n return RequirePermissions(...names)\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 const { names, options } = splitRequirementArgs<RoleRequirementOptions>(args)\n return requirementDecorator(roleRequirement(names, options))\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/dist/index.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ExecutionContext, ModuleMetadata, FactoryProvider, DynamicModule, CanActivate } from '@nestjs/common';
2
- import { Rbac, Subject, TeamId, SubjectRbac } from '@anievo-id/rbac-evolution';
2
+ import { Rbac, Subject, TeamId, RequirementNames, PermissionRequirementOptions, RoleRequirementOptions, SubjectRbac } from '@anievo-id/rbac-evolution';
3
+ export { PermissionRequirementOptions, RbacRequirement, RequirementKind, RequirementNames, RoleRequirementOptions } from '@anievo-id/rbac-evolution';
3
4
  import { Reflector } from '@nestjs/core';
4
5
 
5
6
  type MaybePromise<T> = T | Promise<T>;
@@ -78,25 +79,6 @@ declare class RbacGuard implements CanActivate {
78
79
  private resolve;
79
80
  }
80
81
 
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
82
  /**
101
83
  * Requires permissions, like spatie's `permission:` middleware. Works on controllers and handlers.
102
84
  *
@@ -162,4 +144,4 @@ declare const RBAC: unique symbol;
162
144
  /** Metadata key under which `@Require*` decorators store their requirements. */
163
145
  declare const RBAC_REQUIREMENTS = "rbac-evolution:requirements";
164
146
 
165
- export { CanAll, CanAny, 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 };
147
+ export { CanAll, CanAny, CurrentRbac, RBAC, RBAC_MODULE_OPTIONS, RBAC_REQUIREMENTS, RbacGuard, RbacGuardMissingError, RbacModule, type RbacModuleAsyncConfig, type RbacModuleConfig, type RbacModuleOptions, RequirePermissions, RequireRoleOrPermission, RequireRoles, getRbac };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ExecutionContext, ModuleMetadata, FactoryProvider, DynamicModule, CanActivate } from '@nestjs/common';
2
- import { Rbac, Subject, TeamId, SubjectRbac } from '@anievo-id/rbac-evolution';
2
+ import { Rbac, Subject, TeamId, RequirementNames, PermissionRequirementOptions, RoleRequirementOptions, SubjectRbac } from '@anievo-id/rbac-evolution';
3
+ export { PermissionRequirementOptions, RbacRequirement, RequirementKind, RequirementNames, RoleRequirementOptions } from '@anievo-id/rbac-evolution';
3
4
  import { Reflector } from '@nestjs/core';
4
5
 
5
6
  type MaybePromise<T> = T | Promise<T>;
@@ -78,25 +79,6 @@ declare class RbacGuard implements CanActivate {
78
79
  private resolve;
79
80
  }
80
81
 
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
82
  /**
101
83
  * Requires permissions, like spatie's `permission:` middleware. Works on controllers and handlers.
102
84
  *
@@ -162,4 +144,4 @@ declare const RBAC: unique symbol;
162
144
  /** Metadata key under which `@Require*` decorators store their requirements. */
163
145
  declare const RBAC_REQUIREMENTS = "rbac-evolution:requirements";
164
146
 
165
- export { CanAll, CanAny, 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 };
147
+ export { CanAll, CanAny, CurrentRbac, RBAC, RBAC_MODULE_OPTIONS, RBAC_REQUIREMENTS, RbacGuard, RbacGuardMissingError, RbacModule, type RbacModuleAsyncConfig, type RbacModuleConfig, type RbacModuleOptions, RequirePermissions, RequireRoleOrPermission, RequireRoles, getRbac };
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Injectable, Inject, Global, Module, createParamDecorator, UnauthorizedException, ForbiddenException, applyDecorators, UseGuards } from '@nestjs/common';
2
2
  import { Reflector, APP_GUARD } from '@nestjs/core';
3
+ import { UNAUTHENTICATED_MESSAGE, satisfiesRequirement, REQUIREMENT_MESSAGES, splitRequirementArgs, permissionRequirement, roleRequirement, roleOrPermissionRequirement } from '@anievo-id/rbac-evolution';
3
4
  import 'reflect-metadata';
4
5
 
5
6
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -55,69 +56,6 @@ function getRbac(context) {
55
56
  return resolved.get(key) ?? null;
56
57
  }
57
58
 
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
59
  // src/tokens.ts
122
60
  var RBAC_MODULE_OPTIONS = /* @__PURE__ */ Symbol.for("rbac-evolution:nestjs:options");
123
61
  var RBAC = /* @__PURE__ */ Symbol.for("rbac-evolution:nestjs:rbac");
@@ -149,11 +87,11 @@ var RbacGuard = class {
149
87
  throw new UnauthorizedException({ error: "UNAUTHENTICATED", message: UNAUTHENTICATED_MESSAGE });
150
88
  }
151
89
  for (const requirement of requirements) {
152
- if (!await satisfies(rbac, requirement)) {
90
+ if (!await satisfiesRequirement(rbac, requirement)) {
153
91
  throw new ForbiddenException({
154
92
  error: "FORBIDDEN",
155
93
  reason: requirement.kind,
156
- message: MESSAGES[requirement.kind],
94
+ message: REQUIREMENT_MESSAGES[requirement.kind],
157
95
  ...this.options.exposeRequirements && { required: requirement.requirements }
158
96
  });
159
97
  }
@@ -225,7 +163,8 @@ function appendRequirement(requirement) {
225
163
  }
226
164
  var requirementDecorator = (requirement) => applyDecorators(appendRequirement(requirement), UseGuards(RbacGuard));
227
165
  function RequirePermissions(...args) {
228
- return requirementDecorator(permissionRequirement(args));
166
+ const { names, options } = splitRequirementArgs(args);
167
+ return requirementDecorator(permissionRequirement(names, options));
229
168
  }
230
169
  function CanAny(...names) {
231
170
  return RequirePermissions(...names, { any: true });
@@ -234,7 +173,8 @@ function CanAll(...names) {
234
173
  return RequirePermissions(...names);
235
174
  }
236
175
  function RequireRoles(...args) {
237
- return requirementDecorator(roleRequirement(args));
176
+ const { names, options } = splitRequirementArgs(args);
177
+ return requirementDecorator(roleRequirement(names, options));
238
178
  }
239
179
  function RequireRoleOrPermission(...names) {
240
180
  return requirementDecorator(roleOrPermissionRequirement(names));
package/dist/index.js.map CHANGED
@@ -1 +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,SAAg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A,OAAO,oBAAA,CAAqB,qBAAA,CAAsB,IAAI,CAAC,CAAA;AACzD;AAOO,SAAS,UAAU,KAAA,EAA2B;AACnD,EAAA,OAAO,mBAAmB,GAAG,KAAA,EAAO,EAAE,GAAA,EAAK,MAAM,CAAA;AACnD;AAOO,SAAS,UAAU,KAAA,EAA2B;AACnD,EAAA,OAAO,kBAAA,CAAmB,GAAG,KAAK,CAAA;AACpC;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 * Only HTTP requests and RPC messages get a fresh key object per call. A WebSocket client or a\n * GraphQL context lives across many calls, so caching or skipping checks by it would let a denied\n * client through on its next message.\n */\nconst isPerCall = (context: ExecutionContext): boolean => ['http', 'rpc'].includes(context.getType<string>())\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 perCall = isPerCall(context)\n const rbac = await this.resolve(context, key, perCall)\n\n const handler = context.getHandler()\n if (perCall && key !== undefined && enforced.get(key)?.has(handler)) return true\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 // Mark as enforced only once every requirement passed.\n if (perCall && key !== undefined) enforced.set(key, (enforced.get(key) ?? new Set<unknown>()).add(handler))\n return true\n }\n\n private async resolve(context: ExecutionContext, key: object | undefined, perCall: boolean): Promise<SubjectRbac | null> {\n if (perCall && 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 * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `@CanAny('edit articles', 'publish articles')`, `@CanAny(['edit articles', 'publish articles'])`\n */\nexport function CanAny(...names: RequirementNames[]) {\n return RequirePermissions(...names, { any: true })\n}\n\n/**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `@CanAll('edit articles', 'publish articles')`, `@CanAll(['edit articles', 'publish|review'])`\n */\nexport function CanAll(...names: RequirementNames[]) {\n return RequirePermissions(...names)\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"]}
1
+ {"version":3,"sources":["../src/context.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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AM,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,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAI,qBAAmD,IAAI,CAAA;AAClF,EAAA,OAAO,oBAAA,CAAqB,qBAAA,CAAsB,KAAA,EAAO,OAAO,CAAC,CAAA;AACnE;AAOO,SAAS,UAAU,KAAA,EAA2B;AACnD,EAAA,OAAO,mBAAmB,GAAG,KAAA,EAAO,EAAE,GAAA,EAAK,MAAM,CAAA;AACnD;AAOO,SAAS,UAAU,KAAA,EAA2B;AACnD,EAAA,OAAO,kBAAA,CAAmB,GAAG,KAAK,CAAA;AACpC;AAQO,SAAS,gBAAgB,IAAA,EAAqD;AACnF,EAAA,MAAM,EAAE,KAAA,EAAO,OAAA,EAAQ,GAAI,qBAA6C,IAAI,CAAA;AAC5E,EAAA,OAAO,oBAAA,CAAqB,eAAA,CAAgB,KAAA,EAAO,OAAO,CAAC,CAAA;AAC7D;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","/** 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 {\n type RbacRequirement,\n REQUIREMENT_MESSAGES,\n satisfiesRequirement,\n type SubjectRbac,\n UNAUTHENTICATED_MESSAGE,\n} 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 { 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 * Only HTTP requests and RPC messages get a fresh key object per call. A WebSocket client or a\n * GraphQL context lives across many calls, so caching or skipping checks by it would let a denied\n * client through on its next message.\n */\nconst isPerCall = (context: ExecutionContext): boolean => ['http', 'rpc'].includes(context.getType<string>())\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 perCall = isPerCall(context)\n const rbac = await this.resolve(context, key, perCall)\n\n const handler = context.getHandler()\n if (perCall && key !== undefined && enforced.get(key)?.has(handler)) return true\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 satisfiesRequirement(rbac, requirement))) {\n throw new ForbiddenException({\n error: 'FORBIDDEN',\n reason: requirement.kind,\n message: REQUIREMENT_MESSAGES[requirement.kind],\n ...(this.options.exposeRequirements && { required: requirement.requirements }),\n })\n }\n }\n // Mark as enforced only once every requirement passed.\n if (perCall && key !== undefined) enforced.set(key, (enforced.get(key) ?? new Set<unknown>()).add(handler))\n return true\n }\n\n private async resolve(context: ExecutionContext, key: object | undefined, perCall: boolean): Promise<SubjectRbac | null> {\n if (perCall && 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 { 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 splitRequirementArgs,\n type SubjectRbac,\n} from '@anievo-id/rbac-evolution'\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 const { names, options } = splitRequirementArgs<PermissionRequirementOptions>(args)\n return requirementDecorator(permissionRequirement(names, options))\n}\n\n/**\n * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.\n *\n * - `@CanAny('edit articles', 'publish articles')`, `@CanAny(['edit articles', 'publish articles'])`\n */\nexport function CanAny(...names: RequirementNames[]) {\n return RequirePermissions(...names, { any: true })\n}\n\n/**\n * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means \"a or b\".\n *\n * - `@CanAll('edit articles', 'publish articles')`, `@CanAll(['edit articles', 'publish|review'])`\n */\nexport function CanAll(...names: RequirementNames[]) {\n return RequirePermissions(...names)\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 const { names, options } = splitRequirementArgs<RoleRequirementOptions>(args)\n return requirementDecorator(roleRequirement(names, options))\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,6 @@
1
1
  {
2
2
  "name": "@anievo-id/rbac-evolution-nestjs",
3
- "version": "0.4.1",
3
+ "version": "0.6.0",
4
4
  "description": "NestJS module, guard & decorators for rbac-evolution.",
5
5
  "license": "MIT",
6
6
  "author": "AniEvo-ID (https://github.com/AniEvo-ID)",
@@ -48,7 +48,7 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@anievo-id/rbac-evolution": "^0.4.1"
51
+ "@anievo-id/rbac-evolution": "^0.6.0"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0",