@anievo-id/rbac-evolution-nestjs 0.3.0 → 0.4.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
@@ -127,6 +127,7 @@ var RBAC_REQUIREMENTS = "rbac-evolution:requirements";
127
127
 
128
128
  // src/guard.ts
129
129
  var enforced = /* @__PURE__ */ new WeakMap();
130
+ var isPerCall = (context) => ["http", "rpc"].includes(context.getType());
130
131
  exports.RbacGuard = class RbacGuard {
131
132
  // Explicit tokens: the package is built with esbuild, which does not emit `design:paramtypes`.
132
133
  constructor(reflector, options) {
@@ -137,13 +138,10 @@ exports.RbacGuard = class RbacGuard {
137
138
  options;
138
139
  async canActivate(context) {
139
140
  const key = requestKey(context);
140
- const rbac = await this.resolve(context, key);
141
+ const perCall = isPerCall(context);
142
+ const rbac = await this.resolve(context, key, perCall);
141
143
  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
- }
144
+ if (perCall && key !== void 0 && enforced.get(key)?.has(handler)) return true;
147
145
  const requirements = [
148
146
  ...this.reflector.get(RBAC_REQUIREMENTS, context.getClass()) ?? [],
149
147
  ...this.reflector.get(RBAC_REQUIREMENTS, handler) ?? []
@@ -162,10 +160,11 @@ exports.RbacGuard = class RbacGuard {
162
160
  });
163
161
  }
164
162
  }
163
+ if (perCall && key !== void 0) enforced.set(key, (enforced.get(key) ?? /* @__PURE__ */ new Set()).add(handler));
165
164
  return true;
166
165
  }
167
- async resolve(context, key) {
168
- if (key !== void 0 && hasResolved(key)) return getResolved(key) ?? null;
166
+ async resolve(context, key, perCall) {
167
+ if (perCall && key !== void 0 && hasResolved(key)) return getResolved(key) ?? null;
169
168
  const { rbac, getSubject, guard, team } = this.options;
170
169
  const subject = await getSubject(context);
171
170
  let result = null;
@@ -230,6 +229,12 @@ var requirementDecorator = (requirement) => common.applyDecorators(appendRequire
230
229
  function RequirePermissions(...args) {
231
230
  return requirementDecorator(permissionRequirement(args));
232
231
  }
232
+ function CanAny(...names) {
233
+ return RequirePermissions(...names, { any: true });
234
+ }
235
+ function CanAll(...names) {
236
+ return RequirePermissions(...names);
237
+ }
233
238
  function RequireRoles(...args) {
234
239
  return requirementDecorator(roleRequirement(args));
235
240
  }
@@ -240,6 +245,8 @@ var CurrentRbac = common.createParamDecorator(
240
245
  (_data, context) => getRbac(context)
241
246
  );
242
247
 
248
+ exports.CanAll = CanAll;
249
+ exports.CanAny = CanAny;
243
250
  exports.CurrentRbac = CurrentRbac;
244
251
  exports.RBAC = RBAC;
245
252
  exports.RBAC_MODULE_OPTIONS = RBAC_MODULE_OPTIONS;
@@ -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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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"]}
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,O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ACpE,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"]}
package/dist/index.d.cts CHANGED
@@ -106,6 +106,18 @@ interface RoleRequirementOptions {
106
106
  * - `@RequirePermissions('a', 'b', { any: true })` — any of them
107
107
  */
108
108
  declare function RequirePermissions(...args: (RequirementNames | PermissionRequirementOptions)[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
109
+ /**
110
+ * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.
111
+ *
112
+ * - `@CanAny('edit articles', 'publish articles')`, `@CanAny(['edit articles', 'publish articles'])`
113
+ */
114
+ declare function CanAny(...names: RequirementNames[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
115
+ /**
116
+ * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means "a or b".
117
+ *
118
+ * - `@CanAll('edit articles', 'publish articles')`, `@CanAll(['edit articles', 'publish|review'])`
119
+ */
120
+ declare function CanAll(...names: RequirementNames[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
109
121
  /**
110
122
  * Requires roles, like spatie's `role:` middleware.
111
123
  *
@@ -150,4 +162,4 @@ declare const RBAC: unique symbol;
150
162
  /** Metadata key under which `@Require*` decorators store their requirements. */
151
163
  declare const RBAC_REQUIREMENTS = "rbac-evolution:requirements";
152
164
 
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 };
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 };
package/dist/index.d.ts CHANGED
@@ -106,6 +106,18 @@ interface RoleRequirementOptions {
106
106
  * - `@RequirePermissions('a', 'b', { any: true })` — any of them
107
107
  */
108
108
  declare function RequirePermissions(...args: (RequirementNames | PermissionRequirementOptions)[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
109
+ /**
110
+ * spatie v8.5 `canAny()`: passes with ANY of the listed permissions.
111
+ *
112
+ * - `@CanAny('edit articles', 'publish articles')`, `@CanAny(['edit articles', 'publish articles'])`
113
+ */
114
+ declare function CanAny(...names: RequirementNames[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
115
+ /**
116
+ * spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means "a or b".
117
+ *
118
+ * - `@CanAll('edit articles', 'publish articles')`, `@CanAll(['edit articles', 'publish|review'])`
119
+ */
120
+ declare function CanAll(...names: RequirementNames[]): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
109
121
  /**
110
122
  * Requires roles, like spatie's `role:` middleware.
111
123
  *
@@ -150,4 +162,4 @@ declare const RBAC: unique symbol;
150
162
  /** Metadata key under which `@Require*` decorators store their requirements. */
151
163
  declare const RBAC_REQUIREMENTS = "rbac-evolution:requirements";
152
164
 
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 };
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 };
package/dist/index.js CHANGED
@@ -125,6 +125,7 @@ var RBAC_REQUIREMENTS = "rbac-evolution:requirements";
125
125
 
126
126
  // src/guard.ts
127
127
  var enforced = /* @__PURE__ */ new WeakMap();
128
+ var isPerCall = (context) => ["http", "rpc"].includes(context.getType());
128
129
  var RbacGuard = class {
129
130
  // Explicit tokens: the package is built with esbuild, which does not emit `design:paramtypes`.
130
131
  constructor(reflector, options) {
@@ -135,13 +136,10 @@ var RbacGuard = class {
135
136
  options;
136
137
  async canActivate(context) {
137
138
  const key = requestKey(context);
138
- const rbac = await this.resolve(context, key);
139
+ const perCall = isPerCall(context);
140
+ const rbac = await this.resolve(context, key, perCall);
139
141
  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
- }
142
+ if (perCall && key !== void 0 && enforced.get(key)?.has(handler)) return true;
145
143
  const requirements = [
146
144
  ...this.reflector.get(RBAC_REQUIREMENTS, context.getClass()) ?? [],
147
145
  ...this.reflector.get(RBAC_REQUIREMENTS, handler) ?? []
@@ -160,10 +158,11 @@ var RbacGuard = class {
160
158
  });
161
159
  }
162
160
  }
161
+ if (perCall && key !== void 0) enforced.set(key, (enforced.get(key) ?? /* @__PURE__ */ new Set()).add(handler));
163
162
  return true;
164
163
  }
165
- async resolve(context, key) {
166
- if (key !== void 0 && hasResolved(key)) return getResolved(key) ?? null;
164
+ async resolve(context, key, perCall) {
165
+ if (perCall && key !== void 0 && hasResolved(key)) return getResolved(key) ?? null;
167
166
  const { rbac, getSubject, guard, team } = this.options;
168
167
  const subject = await getSubject(context);
169
168
  let result = null;
@@ -228,6 +227,12 @@ var requirementDecorator = (requirement) => applyDecorators(appendRequirement(re
228
227
  function RequirePermissions(...args) {
229
228
  return requirementDecorator(permissionRequirement(args));
230
229
  }
230
+ function CanAny(...names) {
231
+ return RequirePermissions(...names, { any: true });
232
+ }
233
+ function CanAll(...names) {
234
+ return RequirePermissions(...names);
235
+ }
231
236
  function RequireRoles(...args) {
232
237
  return requirementDecorator(roleRequirement(args));
233
238
  }
@@ -238,6 +243,6 @@ var CurrentRbac = createParamDecorator(
238
243
  (_data, context) => getRbac(context)
239
244
  );
240
245
 
241
- export { CurrentRbac, RBAC, RBAC_MODULE_OPTIONS, RBAC_REQUIREMENTS, RbacGuard, RbacGuardMissingError, RbacModule, RequirePermissions, RequireRoleOrPermission, RequireRoles, getRbac };
246
+ export { CanAll, CanAny, CurrentRbac, RBAC, RBAC_MODULE_OPTIONS, RBAC_REQUIREMENTS, RbacGuard, RbacGuardMissingError, RbacModule, RequirePermissions, RequireRoleOrPermission, RequireRoles, getRbac };
242
247
  //# sourceMappingURL=index.js.map
243
248
  //# sourceMappingURL=index.js.map
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,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;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} 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"]}
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,YA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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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anievo-id/rbac-evolution-nestjs",
3
- "version": "0.3.0",
3
+ "version": "0.4.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.3.0"
51
+ "@anievo-id/rbac-evolution": "^0.4.0"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0",