@anievo-id/rbac-evolution-nestjs 0.7.0 → 0.7.1

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.
@@ -1 +1 @@
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;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AAA;AACxF,IAAA,MAAM,UAAW,OAAA,CAAQ,WAAA,CAAY,iBAAA,EAAmB,MAAM,KAAuC,EAAC;AACtG,IAAA,OAAA,CAAQ,eAAe,iBAAA,EAAmB,CAAC,GAAG,OAAA,EAAS,WAAW,GAAG,MAAM,CAAA;AAAA,EAC7E,CAAA;AACF;AAEA,IAAM,oBAAA,GAAuB,CAAC,WAAA,KAC5BI,sBAAA,CAAgB,kBAAkB,WAAW,CAAA,EAAGC,gBAAA,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"]}
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,Y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AM,UAAW,OAAA,CAAQ,WAAA,CAAY,iBAAA,EAAmB,MAAM,KAAuC,EAAC;AACtG,IAAA,OAAA,CAAQ,eAAe,iBAAA,EAAmB,CAAC,GAAG,OAAA,EAAS,WAAW,GAAG,MAAM,CAAA;AAAA,EAC7E,CAAA;AACF;AAEA,IAAM,oBAAA,GAAuB,CAAC,WAAA,KAC5BI,sBAAA,CAAgB,kBAAkB,WAAW,CAAA,EAAGC,gBAAA,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 | undefined,\n descriptor?: TypedPropertyDescriptor<T> | undefined,\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
@@ -13,27 +13,27 @@ interface RbacModuleOptions {
13
13
  */
14
14
  getSubject: (context: ExecutionContext) => MaybePromise<Subject | null | undefined>;
15
15
  /** RBAC guard name (e.g. `web` or `api`) — not a Nest guard. Defaults to the engine's `defaultGuard`. */
16
- guard?: string;
16
+ guard?: string | undefined;
17
17
  /** Resolves the current team (only when the engine was created with `teams: true`). */
18
18
  team?: (context: ExecutionContext) => MaybePromise<TeamId | undefined>;
19
19
  /**
20
20
  * Include the required roles/permissions in the 403 body (`required`).
21
21
  * Default: `false` (like spatie's `display_permission_in_exception`).
22
22
  */
23
- exposeRequirements?: boolean;
23
+ exposeRequirements?: boolean | undefined;
24
24
  }
25
25
  interface GlobalGuardOption {
26
26
  /**
27
27
  * Register `RbacGuard` as a global guard (`APP_GUARD`), so every route resolves the subject
28
28
  * (and `@CurrentRbac()` works without a `@Require*` decorator). Default: `false`.
29
29
  */
30
- globalGuard?: boolean;
30
+ globalGuard?: boolean | undefined;
31
31
  }
32
32
  interface RbacModuleConfig extends RbacModuleOptions, GlobalGuardOption {
33
33
  }
34
34
  interface RbacModuleAsyncConfig extends GlobalGuardOption, Pick<ModuleMetadata, 'imports'> {
35
35
  /** Providers to inject into `useFactory`. */
36
- inject?: FactoryProvider['inject'];
36
+ inject?: FactoryProvider['inject'] | undefined;
37
37
  /** Builds the options, e.g. from a `ConfigService`. */
38
38
  useFactory: (...args: never[]) => MaybePromise<RbacModuleOptions>;
39
39
  }
package/dist/index.d.ts CHANGED
@@ -13,27 +13,27 @@ interface RbacModuleOptions {
13
13
  */
14
14
  getSubject: (context: ExecutionContext) => MaybePromise<Subject | null | undefined>;
15
15
  /** RBAC guard name (e.g. `web` or `api`) — not a Nest guard. Defaults to the engine's `defaultGuard`. */
16
- guard?: string;
16
+ guard?: string | undefined;
17
17
  /** Resolves the current team (only when the engine was created with `teams: true`). */
18
18
  team?: (context: ExecutionContext) => MaybePromise<TeamId | undefined>;
19
19
  /**
20
20
  * Include the required roles/permissions in the 403 body (`required`).
21
21
  * Default: `false` (like spatie's `display_permission_in_exception`).
22
22
  */
23
- exposeRequirements?: boolean;
23
+ exposeRequirements?: boolean | undefined;
24
24
  }
25
25
  interface GlobalGuardOption {
26
26
  /**
27
27
  * Register `RbacGuard` as a global guard (`APP_GUARD`), so every route resolves the subject
28
28
  * (and `@CurrentRbac()` works without a `@Require*` decorator). Default: `false`.
29
29
  */
30
- globalGuard?: boolean;
30
+ globalGuard?: boolean | undefined;
31
31
  }
32
32
  interface RbacModuleConfig extends RbacModuleOptions, GlobalGuardOption {
33
33
  }
34
34
  interface RbacModuleAsyncConfig extends GlobalGuardOption, Pick<ModuleMetadata, 'imports'> {
35
35
  /** Providers to inject into `useFactory`. */
36
- inject?: FactoryProvider['inject'];
36
+ inject?: FactoryProvider['inject'] | undefined;
37
37
  /** Builds the options, e.g. from a `ConfigService`. */
38
38
  useFactory: (...args: never[]) => MaybePromise<RbacModuleOptions>;
39
39
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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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AAqB,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"]}
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,IAC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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 | undefined,\n descriptor?: TypedPropertyDescriptor<T> | undefined,\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.7.0",
3
+ "version": "0.7.1",
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.7.0"
51
+ "@anievo-id/rbac-evolution": "^0.7.1"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0",