@blimu/nestjs 1.1.3 → 1.2.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.
Files changed (55) hide show
  1. package/dist/index.cjs +33 -11
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +73 -9
  4. package/dist/index.d.ts +73 -9
  5. package/dist/index.mjs +33 -11
  6. package/dist/index.mjs.map +1 -1
  7. package/package.json +5 -4
  8. package/dist/__tests__/example.test.cjs +0 -17135
  9. package/dist/__tests__/example.test.cjs.map +0 -1
  10. package/dist/__tests__/example.test.d.cts +0 -2
  11. package/dist/__tests__/example.test.d.ts +0 -2
  12. package/dist/__tests__/example.test.mjs +0 -17134
  13. package/dist/__tests__/example.test.mjs.map +0 -1
  14. package/dist/config/blimu.config.cjs +0 -31
  15. package/dist/config/blimu.config.cjs.map +0 -1
  16. package/dist/config/blimu.config.d.cts +0 -11
  17. package/dist/config/blimu.config.d.ts +0 -11
  18. package/dist/config/blimu.config.mjs +0 -6
  19. package/dist/config/blimu.config.mjs.map +0 -1
  20. package/dist/decorators/entitlement.decorator.cjs +0 -178
  21. package/dist/decorators/entitlement.decorator.cjs.map +0 -1
  22. package/dist/decorators/entitlement.decorator.d.cts +0 -9
  23. package/dist/decorators/entitlement.decorator.d.ts +0 -9
  24. package/dist/decorators/entitlement.decorator.mjs +0 -161
  25. package/dist/decorators/entitlement.decorator.mjs.map +0 -1
  26. package/dist/exceptions/blimu-forbidden.exception.cjs +0 -86
  27. package/dist/exceptions/blimu-forbidden.exception.cjs.map +0 -1
  28. package/dist/exceptions/blimu-forbidden.exception.d.cts +0 -14
  29. package/dist/exceptions/blimu-forbidden.exception.d.ts +0 -14
  30. package/dist/exceptions/blimu-forbidden.exception.mjs +0 -61
  31. package/dist/exceptions/blimu-forbidden.exception.mjs.map +0 -1
  32. package/dist/guards/entitlement.guard.cjs +0 -174
  33. package/dist/guards/entitlement.guard.cjs.map +0 -1
  34. package/dist/guards/entitlement.guard.d.cts +0 -24
  35. package/dist/guards/entitlement.guard.d.ts +0 -24
  36. package/dist/guards/entitlement.guard.mjs +0 -154
  37. package/dist/guards/entitlement.guard.mjs.map +0 -1
  38. package/dist/modules/blimu.module.cjs +0 -413
  39. package/dist/modules/blimu.module.cjs.map +0 -1
  40. package/dist/modules/blimu.module.d.cts +0 -14
  41. package/dist/modules/blimu.module.d.ts +0 -14
  42. package/dist/modules/blimu.module.mjs +0 -398
  43. package/dist/modules/blimu.module.mjs.map +0 -1
  44. package/dist/services/index.cjs +0 -93
  45. package/dist/services/index.cjs.map +0 -1
  46. package/dist/services/index.d.cts +0 -2
  47. package/dist/services/index.d.ts +0 -2
  48. package/dist/services/index.mjs +0 -69
  49. package/dist/services/index.mjs.map +0 -1
  50. package/dist/services/jwk.service.cjs +0 -91
  51. package/dist/services/jwk.service.cjs.map +0 -1
  52. package/dist/services/jwk.service.d.cts +0 -12
  53. package/dist/services/jwk.service.d.ts +0 -12
  54. package/dist/services/jwk.service.mjs +0 -69
  55. package/dist/services/jwk.service.mjs.map +0 -1
package/dist/index.cjs CHANGED
@@ -113,9 +113,9 @@ var BlimuForbiddenException = class _BlimuForbiddenException extends import_comm
113
113
  var import_backend = require("@blimu/backend");
114
114
  var ENTITLEMENT_KEY = "entitlement";
115
115
  var ENTITLEMENT_METADATA_KEY = /* @__PURE__ */ Symbol("entitlement");
116
- var SetEntitlementMetadata = (entitlementKey, getEntitlementInfo) => (0, import_common2.SetMetadata)(ENTITLEMENT_METADATA_KEY, {
116
+ var SetEntitlementMetadata = (entitlementKey, entitlementCtxResolver) => (0, import_common2.SetMetadata)(ENTITLEMENT_METADATA_KEY, {
117
117
  entitlementKey,
118
- getEntitlementInfo
118
+ entitlementCtxResolver
119
119
  });
120
120
  var EntitlementGuard = class {
121
121
  constructor(config, runtime) {
@@ -138,22 +138,36 @@ var EntitlementGuard = class {
138
138
  if (!userId) {
139
139
  throw new import_common2.ForbiddenException("User ID is required for entitlement check");
140
140
  }
141
- const entitlementInfo = await metadata.getEntitlementInfo(request);
142
- if (!entitlementInfo?.resourceId) {
141
+ let entitlementCtx;
142
+ if (metadata.entitlementCtxResolver) {
143
+ entitlementCtx = await metadata.entitlementCtxResolver(request);
144
+ } else if (this.config.defaultEntitlementCtxResolver) {
145
+ const resourceType = metadata.entitlementKey.split(":")[0] || "";
146
+ entitlementCtx = await this.config.defaultEntitlementCtxResolver(
147
+ {
148
+ entitlement: metadata.entitlementKey,
149
+ resourceType
150
+ },
151
+ request
152
+ );
153
+ } else {
154
+ throw new import_common2.ForbiddenException("No entitlement context resolver available");
155
+ }
156
+ if (!entitlementCtx?.resourceId) {
143
157
  throw new import_common2.ForbiddenException("Resource ID is required for entitlement check");
144
158
  }
145
159
  try {
146
160
  const result = await this.runtime.entitlements.checkEntitlement({
147
161
  userId,
148
162
  entitlement: metadata.entitlementKey,
149
- resourceId: entitlementInfo.resourceId,
150
- ...entitlementInfo.amount !== void 0 ? { amount: entitlementInfo.amount } : {}
163
+ resourceId: entitlementCtx.resourceId,
164
+ ...entitlementCtx.amount !== void 0 ? { amount: entitlementCtx.amount } : {}
151
165
  });
152
166
  if (!result.allowed) {
153
167
  throw new BlimuForbiddenException(
154
168
  result,
155
169
  metadata.entitlementKey,
156
- entitlementInfo.resourceId,
170
+ entitlementCtx.resourceId,
157
171
  userId
158
172
  );
159
173
  }
@@ -243,6 +257,9 @@ var BlimuModule = class {
243
257
  * environmentId: 'your-environment-id', // optional
244
258
  * timeoutMs: 30000, // optional
245
259
  * getUserId: (req) => req.user?.id, // required
260
+ * defaultEntitlementCtxResolver: ({ entitlement, resourceType }, req) => ({
261
+ * resourceId: req.params.resourceId,
262
+ * }), // optional
246
263
  * }),
247
264
  * ],
248
265
  * })
@@ -280,7 +297,8 @@ var BlimuModule = class {
280
297
  baseURL: config.baseURL ?? DEFAULT_BASE_URL,
281
298
  environmentId: config.environmentId,
282
299
  timeoutMs: config.timeoutMs ?? 3e4,
283
- getUserId: config.getUserId
300
+ getUserId: config.getUserId,
301
+ defaultEntitlementCtxResolver: config.defaultEntitlementCtxResolver
284
302
  }
285
303
  },
286
304
  {
@@ -323,6 +341,9 @@ var BlimuModule = class {
323
341
  * environmentId: configService.get('BLIMU_ENVIRONMENT_ID'),
324
342
  * timeoutMs: configService.get('BLIMU_TIMEOUT_MS'),
325
343
  * getUserId: (req) => req.user?.id,
344
+ * defaultEntitlementCtxResolver: (entitlementKey, req) => ({
345
+ * resourceId: req.params.resourceId,
346
+ * }),
326
347
  * }),
327
348
  * inject: [ConfigService],
328
349
  * }),
@@ -393,7 +414,8 @@ var BlimuModule = class {
393
414
  baseURL: config.baseURL ?? DEFAULT_BASE_URL,
394
415
  environmentId: config.environmentId,
395
416
  timeoutMs: config.timeoutMs ?? 3e4,
396
- getUserId: config.getUserId
417
+ getUserId: config.getUserId,
418
+ defaultEntitlementCtxResolver: config.defaultEntitlementCtxResolver
397
419
  };
398
420
  },
399
421
  ...options.inject ? { inject: options.inject } : {}
@@ -424,9 +446,9 @@ BlimuModule = __decorateClass([
424
446
 
425
447
  // src/decorators/entitlement.decorator.ts
426
448
  var import_common5 = require("@nestjs/common");
427
- var Entitlement = (entitlementKey, getEntitlementInfo) => {
449
+ var Entitlement = (entitlementKey, entitlementCtxResolver) => {
428
450
  return (0, import_common5.applyDecorators)(
429
- SetEntitlementMetadata(entitlementKey, getEntitlementInfo),
451
+ SetEntitlementMetadata(entitlementKey, entitlementCtxResolver),
430
452
  (0, import_common5.UseGuards)(EntitlementGuard)
431
453
  );
432
454
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/modules/blimu.module.ts","../src/config/blimu.config.ts","../src/guards/entitlement.guard.ts","../src/exceptions/blimu-forbidden.exception.ts","../src/services/jwk.service.ts","../src/decorators/entitlement.decorator.ts"],"sourcesContent":["// Main module\nexport * from './modules/blimu.module';\n\n// Configuration\nexport * from './config/blimu.config';\n\n// Guards\nexport * from './guards/entitlement.guard';\n\n// Decorators\nexport * from './decorators/entitlement.decorator';\n\n// Exceptions\nexport * from './exceptions/blimu-forbidden.exception';\n\n// Services\nexport * from './services';\n","import {\n Module,\n type DynamicModule,\n type Type,\n type ForwardReference,\n type InjectionToken,\n type OptionalFactoryDependency,\n} from '@nestjs/common';\n\nimport { BLIMU_CONFIG, type BlimuConfig } from '../config/blimu.config';\nimport { EntitlementGuard } from 'guards/entitlement.guard';\nimport { JWKService } from 'services/jwk.service';\nimport { Blimu } from '@blimu/backend';\n\nconst DEFAULT_BASE_URL = 'https://api.blimu.dev';\n\n/**\n * Blimu NestJS Module\n *\n * This module provides entitlement checking capabilities and Blimu Runtime SDK integration\n * for NestJS applications. It can be configured synchronously or asynchronously.\n */\n@Module({})\nexport class BlimuModule {\n /**\n * Configure the Blimu module with static configuration\n *\n * @param config - The Blimu configuration object\n * @returns A configured dynamic module\n *\n * @example\n * Basic usage with default Request type:\n * ```typescript\n * @Module({\n * imports: [\n * BlimuModule.forRoot({\n * apiKey: 'your-api-secret-key',\n * baseURL: 'https://api.blimu.dev', // optional\n * environmentId: 'your-environment-id', // optional\n * timeoutMs: 30000, // optional\n * getUserId: (req) => req.user?.id, // required\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example\n * Usage with custom request type:\n * ```typescript\n * interface AuthenticatedRequest {\n * user: { id: string; email: string };\n * }\n *\n * @Module({\n * imports: [\n * BlimuModule.forRoot<AuthenticatedRequest>({\n * apiKey: 'your-api-secret-key',\n * getUserId: (req) => req.user.id, // req is typed as AuthenticatedRequest\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n static forRoot<TRequest = unknown>(config: BlimuConfig<TRequest>): DynamicModule {\n return {\n ...(config.global ? { global: true } : {}),\n module: BlimuModule,\n providers: [\n // Register factory providers first so dependencies are available\n {\n provide: BLIMU_CONFIG,\n useValue: {\n apiKey: config.apiKey,\n baseURL: config.baseURL ?? DEFAULT_BASE_URL,\n environmentId: config.environmentId,\n timeoutMs: config.timeoutMs ?? 30000,\n getUserId: config.getUserId,\n },\n },\n {\n provide: Blimu,\n useFactory: (config: BlimuConfig) => {\n return new Blimu({\n apiKey: config.apiKey,\n baseURL: config.baseURL ?? DEFAULT_BASE_URL,\n timeoutMs: config.timeoutMs ?? 30000,\n });\n },\n inject: [BLIMU_CONFIG],\n },\n // Register class providers after their dependencies are available\n EntitlementGuard,\n JWKService,\n ],\n exports: [EntitlementGuard, Blimu, BLIMU_CONFIG, JWKService],\n };\n }\n\n /**\n * Configure the Blimu module with async configuration\n *\n * This is useful when you need to load configuration from environment variables,\n * configuration services, or other async sources.\n *\n * @param options - Async configuration options\n * @returns A configured dynamic module\n *\n * @example\n * Using with ConfigService:\n * ```typescript\n * @Module({\n * imports: [\n * ConfigModule.forRoot(),\n * BlimuModule.forRootAsync({\n * useFactory: (configService: ConfigService) => ({\n * apiKey: configService.get('BLIMU_API_SECRET_KEY'),\n * baseURL: configService.get('BLIMU_BASE_URL'),\n * environmentId: configService.get('BLIMU_ENVIRONMENT_ID'),\n * timeoutMs: configService.get('BLIMU_TIMEOUT_MS'),\n * getUserId: (req) => req.user?.id,\n * }),\n * inject: [ConfigService],\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example\n * Using with custom request type:\n * ```typescript\n * interface AuthenticatedRequest {\n * user: { id: string; email: string };\n * }\n *\n * @Module({\n * imports: [\n * BlimuModule.forRootAsync<AuthenticatedRequest>({\n * useFactory: (configService: ConfigService) => ({\n * apiKey: configService.get('BLIMU_API_SECRET_KEY'),\n * getUserId: (req) => req.user.id, // req is typed as AuthenticatedRequest\n * }),\n * inject: [ConfigService],\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example\n * Using with custom provider:\n * ```typescript\n * @Module({\n * imports: [\n * BlimuModule.forRootAsync({\n * imports: [MyConfigModule],\n * useFactory: async (myConfigService: MyConfigService) => {\n * const config = await myConfigService.getBlimuConfig();\n * return {\n * apiKey: config.apiKey,\n * baseURL: config.baseUrl,\n * environmentId: config.environmentId,\n * getUserId: (req) => req.user?.id,\n * };\n * },\n * inject: [MyConfigService],\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n static forRootAsync<TRequest = unknown>(options: {\n global?: boolean | undefined;\n useFactory: (...args: unknown[]) => Promise<BlimuConfig<TRequest>> | BlimuConfig<TRequest>;\n inject?: (InjectionToken | OptionalFactoryDependency)[];\n imports?: (\n | Type<unknown>\n | DynamicModule\n | Promise<DynamicModule>\n | ForwardReference<() => Type<unknown>>\n )[];\n }): DynamicModule {\n const additionalImports = options.imports ?? [];\n\n const module = {\n ...(options.global ? { global: true } : {}),\n module: BlimuModule,\n imports: [...additionalImports] as (\n | Type<unknown>\n | DynamicModule\n | Promise<DynamicModule>\n | ForwardReference\n )[],\n providers: [\n // Register factory providers first so dependencies are available\n {\n provide: BLIMU_CONFIG,\n useFactory: async (...args: unknown[]) => {\n const configResult = options.useFactory(...args);\n const config = configResult instanceof Promise ? await configResult : configResult;\n return {\n apiKey: config.apiKey,\n baseURL: config.baseURL ?? DEFAULT_BASE_URL,\n environmentId: config.environmentId,\n timeoutMs: config.timeoutMs ?? 30000,\n getUserId: config.getUserId,\n };\n },\n ...(options.inject ? { inject: options.inject } : {}),\n },\n {\n provide: Blimu,\n useFactory: (config: BlimuConfig) => {\n return new Blimu({\n apiKey: config.apiKey,\n baseURL: config.baseURL ?? DEFAULT_BASE_URL,\n timeoutMs: config.timeoutMs ?? 30000,\n });\n },\n inject: [BLIMU_CONFIG],\n },\n // Register class providers after their dependencies are available\n EntitlementGuard,\n JWKService,\n ],\n exports: [EntitlementGuard, Blimu, BLIMU_CONFIG, JWKService],\n };\n return module;\n }\n}\n","/**\n * Configuration interface for Blimu NestJS integration\n */\nexport interface BlimuConfig<TRequest = unknown> {\n global?: boolean | undefined;\n /**\n * The API secret key for authenticating with Blimu Runtime API\n */\n apiKey: string;\n\n /**\n * The base URL for the Blimu Runtime API\n * @default 'https://api.blimu.dev'\n */\n baseURL?: string | undefined;\n\n /**\n * Environment ID for the Blimu environment\n * This will be used in future versions for environment-specific configurations\n */\n environmentId?: string | undefined;\n\n /**\n * Request timeout in milliseconds\n * @default 30000\n */\n timeoutMs?: number | undefined;\n\n /**\n * Function to extract user ID from the request\n *\n * This function is called by the EntitlementGuard to determine which user\n * to check entitlements for. It should return the user ID as a string.\n *\n * @param request - The incoming HTTP request\n * @returns The user ID as a string, or a Promise that resolves to the user ID\n *\n * @example\n * ```typescript\n * // Extract from JWT token in Authorization header\n * getUserId: (req) => {\n * const token = req.headers.authorization?.replace('Bearer ', '');\n * const decoded = jwt.verify(token, secret);\n * return decoded.sub;\n * }\n *\n * // Extract from request.user (common with Passport.js)\n * getUserId: (req) => req.user?.id\n *\n * // Extract from custom header\n * getUserId: (req) => req.headers['x-user-id']\n * ```\n */\n getUserId: (request: TRequest) => string | Promise<string>;\n}\n\n/**\n * Injection token for Blimu configuration\n */\nexport const BLIMU_CONFIG = Symbol('BLIMU_CONFIG');\n","import {\n type CanActivate,\n type ExecutionContext,\n ForbiddenException,\n Injectable,\n SetMetadata,\n Inject,\n} from '@nestjs/common';\nimport 'reflect-metadata';\n\nimport type { EntitlementType } from '@blimu/types';\nimport { BlimuForbiddenException } from '../exceptions/blimu-forbidden.exception';\nimport { Blimu } from '@blimu/backend';\nimport { BLIMU_CONFIG, type BlimuConfig } from 'config/blimu.config';\n\nexport const ENTITLEMENT_KEY = 'entitlement';\nexport const ENTITLEMENT_METADATA_KEY = Symbol('entitlement');\n\n/**\n * Entitlement information returned by the getEntitlementInfo callback\n */\nexport interface EntitlementInfo {\n resourceId: string;\n amount?: number; // Amount to check against usage limit (for consumption)\n}\n\n/**\n * Metadata interface for entitlement checks\n */\nexport interface EntitlementMetadata<TRequest = unknown> {\n entitlementKey: EntitlementType;\n getEntitlementInfo: (request: TRequest) => EntitlementInfo | Promise<EntitlementInfo>;\n}\n\n/**\n * Sets entitlement metadata for a route handler\n * @internal This is used internally by the @Entitlement decorator\n */\nexport const SetEntitlementMetadata = <TRequest = unknown>(\n entitlementKey: string,\n getEntitlementInfo: (request: TRequest) => EntitlementInfo | Promise<EntitlementInfo>,\n): MethodDecorator =>\n SetMetadata(ENTITLEMENT_METADATA_KEY, {\n entitlementKey,\n getEntitlementInfo,\n } as EntitlementMetadata<TRequest>);\n\n/**\n * Guard that checks if the authenticated user has the required entitlement on a resource\n *\n * This guard automatically:\n * 1. Extracts the user from the request\n * 2. Extracts the resource ID using the provided extractor function\n * 3. Calls the Blimu Runtime API to check entitlements\n * 4. Allows or denies access based on the result\n */\n@Injectable()\nexport class EntitlementGuard<TRequest = unknown> implements CanActivate {\n constructor(\n @Inject(BLIMU_CONFIG)\n private readonly config: BlimuConfig<TRequest>,\n @Inject(Blimu)\n private readonly runtime: Blimu,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<TRequest>();\n const handler = context.getHandler();\n const metadata = Reflect.getMetadata(ENTITLEMENT_METADATA_KEY, handler) as\n | EntitlementMetadata<TRequest>\n | undefined;\n\n if (!metadata) {\n // No entitlement check required\n return true;\n }\n\n // Extract user ID using the configured getUserId function\n let userId: string;\n try {\n userId = await this.config.getUserId(request);\n } catch {\n throw new ForbiddenException('Failed to extract user ID from request');\n }\n\n if (!userId) {\n throw new ForbiddenException('User ID is required for entitlement check');\n }\n\n // Extract entitlement info from request\n const entitlementInfo = await metadata.getEntitlementInfo(request);\n\n if (!entitlementInfo?.resourceId) {\n throw new ForbiddenException('Resource ID is required for entitlement check');\n }\n\n try {\n // Check entitlement\n const result = await this.runtime.entitlements.checkEntitlement({\n userId,\n entitlement: metadata.entitlementKey,\n resourceId: entitlementInfo.resourceId,\n ...(entitlementInfo.amount !== undefined ? { amount: entitlementInfo.amount } : {}),\n });\n\n if (!result.allowed) {\n throw new BlimuForbiddenException(\n result,\n metadata.entitlementKey,\n entitlementInfo.resourceId,\n userId,\n );\n }\n\n return true;\n } catch (error) {\n if (error instanceof BlimuForbiddenException || error instanceof ForbiddenException) {\n throw error;\n }\n\n // Log the error for debugging but don't expose internal details\n console.error('Entitlement check failed:', error);\n throw new ForbiddenException('Failed to verify entitlements');\n }\n }\n}\n","import { ForbiddenException } from '@nestjs/common';\nimport type { Schema } from '@blimu/backend';\nimport type { EntitlementType } from '@blimu/types';\n/**\n * Custom exception for Blimu entitlement check failures\n *\n * This exception extends NestJS's ForbiddenException and includes\n * the typed EntitlementCheckResult, providing detailed information\n * about why the entitlement check failed (roles, plans, limits, etc.)\n */\nexport class BlimuForbiddenException extends ForbiddenException {\n /**\n * The entitlement check result containing detailed failure information\n */\n public readonly entitlementResult: Schema.EntitlementCheckResult;\n\n /**\n * The entitlement key that was checked\n */\n public readonly entitlementKey: EntitlementType;\n\n /**\n * The resource ID that was checked\n */\n public readonly resourceId: string;\n\n /**\n * The user ID that was checked\n */\n public readonly userId: string;\n\n constructor(\n entitlementResult: Schema.EntitlementCheckResult,\n entitlementKey: EntitlementType,\n resourceId: string,\n userId: string,\n ) {\n // Create a user-friendly message based on the failure reason\n const message = BlimuForbiddenException.buildMessage(entitlementResult, entitlementKey);\n\n super({\n message,\n entitlementResult,\n entitlementKey,\n resourceId,\n userId,\n });\n\n this.entitlementResult = entitlementResult;\n this.entitlementKey = entitlementKey;\n this.resourceId = resourceId;\n this.userId = userId;\n }\n\n /**\n * Builds a user-friendly error message from the entitlement check result\n */\n private static buildMessage(\n result: Schema.EntitlementCheckResult,\n entitlementKey: EntitlementType,\n ): string {\n const reasons: string[] = [];\n\n if (result.roles && !result.roles.allowed) {\n reasons.push(\n `Insufficient roles. Required: ${result.roles.allowedRoles?.join(', ') || 'unknown'}. User has: ${result.roles.userRoles?.join(', ') || 'none'}.`,\n );\n }\n\n if (result.plans && !result.plans.allowed) {\n reasons.push(\n `Plan restriction. Required plans: ${result.plans.allowedPlans?.join(', ') || 'unknown'}. Current plan: ${result.plans.plan || 'none'}.`,\n );\n }\n\n if (result.limit && !result.limit.allowed) {\n reasons.push(`Usage limit exceeded. ${result.limit.reason || 'Limit has been reached'}.`);\n }\n\n if (reasons.length === 0) {\n return `Access denied for entitlement: ${entitlementKey}`;\n }\n\n return `Access denied for entitlement \"${entitlementKey}\": ${reasons.join(' ')}`;\n }\n}\n","import { Inject, Injectable, Logger } from '@nestjs/common';\nimport { TokenVerifier } from '@blimu/backend';\nimport { BLIMU_CONFIG, type BlimuConfig } from '../config/blimu.config';\n\n@Injectable()\nexport class JWKService {\n private readonly logger = new Logger(JWKService.name);\n private readonly tokenVerifier: TokenVerifier;\n\n constructor(@Inject(BLIMU_CONFIG) private readonly config: BlimuConfig) {\n this.tokenVerifier = new TokenVerifier({\n runtimeApiUrl: this.config.baseURL,\n });\n }\n\n /**\n * Verify JWT token using JWKs from runtime-api\n */\n async verifyToken<T = unknown>(token: string): Promise<T> {\n try {\n this.logger.debug(\n `🔍 Verifying token. Runtime API URL: ${this.config.baseURL}, API Key prefix: ${this.config.apiKey?.substring(0, 10)}...`,\n );\n\n const result = await this.tokenVerifier.verifyToken<T>({\n secretKey: this.config.apiKey,\n token,\n runtimeApiUrl: this.config.baseURL,\n });\n\n this.logger.debug(`✅ Token verified successfully`);\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n this.logger.error(`❌ Token verification failed: ${errorMessage}`);\n if (error instanceof Error && error.stack) {\n this.logger.error(`Stack trace: ${error.stack}`);\n }\n throw error;\n }\n }\n\n /**\n * Clear cache (useful for testing or key rotation)\n */\n clearCache(): void {\n this.tokenVerifier.clearCache(this.config.apiKey);\n this.logger.debug('JWK cache cleared');\n }\n}\n","import { applyDecorators, UseGuards } from '@nestjs/common';\nimport {\n EntitlementGuard,\n SetEntitlementMetadata,\n type EntitlementInfo,\n} from '../guards/entitlement.guard';\nimport type { EntitlementType } from '@blimu/types';\n\n/**\n * Decorator to check if the authenticated user has a specific entitlement on a resource.\n *\n * This decorator combines the entitlement metadata setting and guard application\n * to provide a clean, declarative way to protect routes with entitlement checks.\n *\n * @param entitlementKey - The entitlement key to check (e.g., 'brand:read', 'organization:create_workspace')\n * @param getEntitlementInfo - Function that returns entitlement information including resourceId and optionally amount for usage limits\n *\n * @example\n * Basic usage with path parameter:\n * ```typescript\n * @Get('/:resourceId')\n * @Entitlement('brand:read', (req) => ({ resourceId: req.params.resourceId }))\n * async getBrand(@Param('resourceId') resourceId: string) {\n * // User is guaranteed to have 'brand:read' entitlement on this resource\n * }\n * ```\n *\n * @example\n * Using with typed parameters:\n * ```typescript\n * @Get('/:resourceType/:resourceId')\n * @Entitlement('workspace:delete', (req) => ({ resourceId: req.params.resourceId }))\n * async deleteResource(@Param() params: ResourceParamsDto) {\n * // User is guaranteed to have 'workspace:delete' entitlement\n * }\n * ```\n *\n * @example\n * Complex resource ID extraction:\n * ```typescript\n * @Post('/organizations/:orgId/workspaces')\n * @Entitlement('organization:create_workspace', (req) => {\n * const params = req.params as { orgId: string };\n * return { resourceId: params.orgId };\n * })\n * async createWorkspace(@Param() params: CreateWorkspaceParamsDto, @Body() body: CreateWorkspaceDto) {\n * // User is guaranteed to have 'organization:create_workspace' entitlement on the organization\n * }\n * ```\n *\n * @example\n * With usage limit consumption:\n * ```typescript\n * @Post('/api-calls')\n * @Entitlement('organization:make_api_call', (req) => ({\n * resourceId: req.params.orgId,\n * amount: req.body.apiCallsCount, // Amount to consume from usage limit\n * }))\n * async makeApiCalls(@Param('orgId') orgId: string, @Body() body: { apiCallsCount: number }) {\n * // User is guaranteed to have 'organization:make_api_call' entitlement\n * // and sufficient usage limit balance\n * }\n * ```\n *\n * @example\n * Async entitlement info extraction (e.g., from database):\n * ```typescript\n * @Delete('/items/:itemId')\n * @Entitlement('workspace:delete_item', async (req) => {\n * // You could fetch the workspace ID from your database\n * const item = await itemService.findById(req.params.itemId);\n * return { resourceId: item.workspaceId };\n * })\n * async deleteItem(@Param('itemId') itemId: string) {\n * // User is guaranteed to have 'workspace:delete_item' entitlement on the item's workspace\n * }\n * ```\n *\n * @example\n * Using with custom request type:\n * ```typescript\n * interface AuthenticatedRequest {\n * user: { id: string; email: string };\n * }\n *\n * @Get('/:resourceId')\n * @Entitlement<AuthenticatedRequest>('brand:read', (req) => {\n * // req is typed as AuthenticatedRequest, so req.user is properly typed\n * console.log(req.user.email); // TypeScript knows this exists\n * return { resourceId: req.params.resourceId };\n * })\n * async getBrand(@Param('resourceId') resourceId: string) {\n * // User is guaranteed to have 'brand:read' entitlement on this resource\n * }\n * ```\n */\nexport const Entitlement = <TRequest = unknown>(\n entitlementKey: EntitlementType,\n getEntitlementInfo: (request: TRequest) => EntitlementInfo | Promise<EntitlementInfo>,\n): MethodDecorator => {\n return applyDecorators(\n SetEntitlementMetadata<TRequest>(entitlementKey, getEntitlementInfo),\n UseGuards(EntitlementGuard),\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAOO;;;ACoDA,IAAM,eAAe,uBAAO,cAAc;;;AC3DjD,IAAAC,iBAOO;AACP,8BAAO;;;ACRP,oBAAmC;AAU5B,IAAM,0BAAN,MAAM,iCAAgC,iCAAmB;AAAA;AAAA;AAAA;AAAA,EAI9C;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EAEhB,YACE,mBACA,gBACA,YACA,QACA;AAEA,UAAM,UAAU,yBAAwB,aAAa,mBAAmB,cAAc;AAEtF,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAED,SAAK,oBAAoB;AACzB,SAAK,iBAAiB;AACtB,SAAK,aAAa;AAClB,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA,EAKA,OAAe,aACb,QACA,gBACQ;AACR,UAAM,UAAoB,CAAC;AAE3B,QAAI,OAAO,SAAS,CAAC,OAAO,MAAM,SAAS;AAC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wB,UAAU,MAAM,eAAe;AACtE,mBAAO;AAAA,cACL,QAAQ,OAAO;AAAA,cACf,SAAS,OAAO,WAAW;AAAA,cAC3B,eAAe,OAAO;AAAA,cACtB,WAAW,OAAO,aAAa;AAAA,cAC/B,WAAW,OAAO;AAAA,YACpB;AAAA,UACF;AAAA,UACA,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;AAAA,QACrD;AAAA,QACA;AAAA,UACE,SAAS;AAAA,UACT,YAAY,CAAC,WAAwB;AACnC,mBAAO,IAAI,sBAAM;AAAA,cACf,QAAQ,OAAO;AAAA,cACf,SAAS,OAAO,WAAW;AAAA,cAC3B,WAAW,OAAO,aAAa;AAAA,YACjC,CAAC;AAAA,UACH;AAAA,UACA,QAAQ,CAAC,YAAY;AAAA,QACvB;AAAA;AAAA,QAEA;AAAA,QACA;AAAA,MACF;AAAA,MACA,SAAS,CAAC,kBAAkB,uBAAO,cAAc,UAAU;AAAA,IAC7D;AACA,WAAOA;AAAA,EACT;AACF;AAjNa,cAAN;AAAA,MADN,uBAAO,CAAC,CAAC;AAAA,GACG;;;AKvBb,IAAAC,iBAA2C;AAgGpC,IAAM,cAAc,CACzB,gBACA,uBACoB;AACpB,aAAO;AAAA,IACL,uBAAiC,gBAAgB,kBAAkB;AAAA,QACnE,0BAAU,gBAAgB;AAAA,EAC5B;AACF;","names":["import_common","import_common","import_common","import_backend","import_backend","config","module","import_common"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/modules/blimu.module.ts","../src/config/blimu.config.ts","../src/guards/entitlement.guard.ts","../src/exceptions/blimu-forbidden.exception.ts","../src/services/jwk.service.ts","../src/decorators/entitlement.decorator.ts"],"sourcesContent":["// Main module\nexport * from './modules/blimu.module';\n\n// Configuration\nexport * from './config/blimu.config';\n\n// Guards\nexport * from './guards/entitlement.guard';\n\n// Decorators\nexport * from './decorators/entitlement.decorator';\n\n// Exceptions\nexport * from './exceptions/blimu-forbidden.exception';\n\n// Services\nexport * from './services';\n","import {\n Module,\n type DynamicModule,\n type Type,\n type ForwardReference,\n type InjectionToken,\n type OptionalFactoryDependency,\n} from '@nestjs/common';\n\nimport { BLIMU_CONFIG, type BlimuConfig } from '../config/blimu.config';\nimport { EntitlementGuard } from '../guards/entitlement.guard';\nimport { JWKService } from '../services/jwk.service';\nimport { Blimu } from '@blimu/backend';\n\nconst DEFAULT_BASE_URL = 'https://api.blimu.dev';\n\n/**\n * Blimu NestJS Module\n *\n * This module provides entitlement checking capabilities and Blimu Runtime SDK integration\n * for NestJS applications. It can be configured synchronously or asynchronously.\n */\n@Module({})\nexport class BlimuModule {\n /**\n * Configure the Blimu module with static configuration\n *\n * @param config - The Blimu configuration object\n * @returns A configured dynamic module\n *\n * @example\n * Basic usage with default Request type:\n * ```typescript\n * @Module({\n * imports: [\n * BlimuModule.forRoot({\n * apiKey: 'your-api-secret-key',\n * baseURL: 'https://api.blimu.dev', // optional\n * environmentId: 'your-environment-id', // optional\n * timeoutMs: 30000, // optional\n * getUserId: (req) => req.user?.id, // required\n * defaultEntitlementCtxResolver: ({ entitlement, resourceType }, req) => ({\n * resourceId: req.params.resourceId,\n * }), // optional\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example\n * Usage with custom request type:\n * ```typescript\n * interface AuthenticatedRequest {\n * user: { id: string; email: string };\n * }\n *\n * @Module({\n * imports: [\n * BlimuModule.forRoot<AuthenticatedRequest>({\n * apiKey: 'your-api-secret-key',\n * getUserId: (req) => req.user.id, // req is typed as AuthenticatedRequest\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n static forRoot<TRequest = unknown>(config: BlimuConfig<TRequest>): DynamicModule {\n return {\n ...(config.global ? { global: true } : {}),\n module: BlimuModule,\n providers: [\n // Register factory providers first so dependencies are available\n {\n provide: BLIMU_CONFIG,\n useValue: {\n apiKey: config.apiKey,\n baseURL: config.baseURL ?? DEFAULT_BASE_URL,\n environmentId: config.environmentId,\n timeoutMs: config.timeoutMs ?? 30000,\n getUserId: config.getUserId,\n defaultEntitlementCtxResolver: config.defaultEntitlementCtxResolver,\n },\n },\n {\n provide: Blimu,\n useFactory: (config: BlimuConfig) => {\n return new Blimu({\n apiKey: config.apiKey,\n baseURL: config.baseURL ?? DEFAULT_BASE_URL,\n timeoutMs: config.timeoutMs ?? 30000,\n });\n },\n inject: [BLIMU_CONFIG],\n },\n // Register class providers after their dependencies are available\n EntitlementGuard,\n JWKService,\n ],\n exports: [EntitlementGuard, Blimu, BLIMU_CONFIG, JWKService],\n };\n }\n\n /**\n * Configure the Blimu module with async configuration\n *\n * This is useful when you need to load configuration from environment variables,\n * configuration services, or other async sources.\n *\n * @param options - Async configuration options\n * @returns A configured dynamic module\n *\n * @example\n * Using with ConfigService:\n * ```typescript\n * @Module({\n * imports: [\n * ConfigModule.forRoot(),\n * BlimuModule.forRootAsync({\n * useFactory: (configService: ConfigService) => ({\n * apiKey: configService.get('BLIMU_API_SECRET_KEY'),\n * baseURL: configService.get('BLIMU_BASE_URL'),\n * environmentId: configService.get('BLIMU_ENVIRONMENT_ID'),\n * timeoutMs: configService.get('BLIMU_TIMEOUT_MS'),\n * getUserId: (req) => req.user?.id,\n * defaultEntitlementCtxResolver: (entitlementKey, req) => ({\n * resourceId: req.params.resourceId,\n * }),\n * }),\n * inject: [ConfigService],\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example\n * Using with custom request type:\n * ```typescript\n * interface AuthenticatedRequest {\n * user: { id: string; email: string };\n * }\n *\n * @Module({\n * imports: [\n * BlimuModule.forRootAsync<AuthenticatedRequest>({\n * useFactory: (configService: ConfigService) => ({\n * apiKey: configService.get('BLIMU_API_SECRET_KEY'),\n * getUserId: (req) => req.user.id, // req is typed as AuthenticatedRequest\n * }),\n * inject: [ConfigService],\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * @example\n * Using with custom provider:\n * ```typescript\n * @Module({\n * imports: [\n * BlimuModule.forRootAsync({\n * imports: [MyConfigModule],\n * useFactory: async (myConfigService: MyConfigService) => {\n * const config = await myConfigService.getBlimuConfig();\n * return {\n * apiKey: config.apiKey,\n * baseURL: config.baseUrl,\n * environmentId: config.environmentId,\n * getUserId: (req) => req.user?.id,\n * };\n * },\n * inject: [MyConfigService],\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n static forRootAsync<TRequest = unknown>(options: {\n global?: boolean | undefined;\n useFactory: (...args: unknown[]) => Promise<BlimuConfig<TRequest>> | BlimuConfig<TRequest>;\n inject?: (InjectionToken | OptionalFactoryDependency)[];\n imports?: (\n | Type<unknown>\n | DynamicModule\n | Promise<DynamicModule>\n | ForwardReference<() => Type<unknown>>\n )[];\n }): DynamicModule {\n const additionalImports = options.imports ?? [];\n\n const module = {\n ...(options.global ? { global: true } : {}),\n module: BlimuModule,\n imports: [...additionalImports] as (\n | Type<unknown>\n | DynamicModule\n | Promise<DynamicModule>\n | ForwardReference\n )[],\n providers: [\n // Register factory providers first so dependencies are available\n {\n provide: BLIMU_CONFIG,\n useFactory: async (...args: unknown[]) => {\n const configResult = options.useFactory(...args);\n const config = configResult instanceof Promise ? await configResult : configResult;\n return {\n apiKey: config.apiKey,\n baseURL: config.baseURL ?? DEFAULT_BASE_URL,\n environmentId: config.environmentId,\n timeoutMs: config.timeoutMs ?? 30000,\n getUserId: config.getUserId,\n defaultEntitlementCtxResolver: config.defaultEntitlementCtxResolver,\n };\n },\n ...(options.inject ? { inject: options.inject } : {}),\n },\n {\n provide: Blimu,\n useFactory: (config: BlimuConfig) => {\n return new Blimu({\n apiKey: config.apiKey,\n baseURL: config.baseURL ?? DEFAULT_BASE_URL,\n timeoutMs: config.timeoutMs ?? 30000,\n });\n },\n inject: [BLIMU_CONFIG],\n },\n // Register class providers after their dependencies are available\n EntitlementGuard,\n JWKService,\n ],\n exports: [EntitlementGuard, Blimu, BLIMU_CONFIG, JWKService],\n };\n return module;\n }\n}\n","import type { EntitlementType } from '@blimu/types';\n/**\n * Configuration interface for Blimu NestJS integration\n */\nexport interface BlimuConfig<TRequest = unknown> {\n global?: boolean | undefined;\n /**\n * The API secret key for authenticating with Blimu Runtime API\n */\n apiKey: string;\n\n /**\n * The base URL for the Blimu Runtime API\n * @default 'https://api.blimu.dev'\n */\n baseURL?: string | undefined;\n\n /**\n * Environment ID for the Blimu environment\n * This will be used in future versions for environment-specific configurations\n */\n environmentId?: string | undefined;\n\n /**\n * Request timeout in milliseconds\n * @default 30000\n */\n timeoutMs?: number | undefined;\n\n /**\n * Function to extract user ID from the request\n *\n * This function is called by the EntitlementGuard to determine which user\n * to check entitlements for. It should return the user ID as a string.\n *\n * @param request - The incoming HTTP request\n * @returns The user ID as a string, or a Promise that resolves to the user ID\n *\n * @example\n * ```typescript\n * // Extract from JWT token in Authorization header\n * getUserId: (req) => {\n * const token = req.headers.authorization?.replace('Bearer ', '');\n * const decoded = jwt.verify(token, secret);\n * return decoded.sub;\n * }\n *\n * // Extract from request.user (common with Passport.js)\n * getUserId: (req) => req.user?.id\n *\n * // Extract from custom header\n * getUserId: (req) => req.headers['x-user-id']\n * ```\n */\n getUserId: (request: TRequest) => string | Promise<string>;\n\n /**\n * Optional default entitlement context resolver for entitlement checks\n *\n * This function is used as a fallback when a decorator-specific resolver is not provided.\n * It receives an object with the entitlement key and parsed resource type, along with the request,\n * allowing for context-aware resolution.\n *\n * @param context - Object containing the entitlement and resource type (parsed from entitlement by splitting on ':')\n * @param request - The incoming HTTP request\n * @returns Entitlement context with resourceId and optionally amount, or a Promise that resolves to it\n *\n * @example\n * ```typescript\n * // Extract resourceId from path parameter\n * defaultEntitlementCtxResolver: ({ entitlement, resourceType }, req) => ({\n * resourceId: req.params.resourceId,\n * })\n *\n * // Context-aware resolution based on resource type\n * defaultEntitlementCtxResolver: ({ resourceType }, req) => {\n * if (resourceType === 'organization') {\n * return { resourceId: req.params.orgId };\n * }\n * return { resourceId: req.params.resourceId };\n * }\n *\n * // Extract from request body or query with amount for consumption\n * defaultEntitlementCtxResolver: ({ entitlement, resourceType }, req) => ({\n * resourceId: req.body?.resourceId || req.query?.resourceId,\n * amount: req.body?.amount, // Amount to consume for usage-based entitlements\n * })\n * ```\n */\n defaultEntitlementCtxResolver?: (\n context: { entitlement: EntitlementType; resourceType: string },\n request: TRequest,\n ) => { resourceId: string; amount?: number } | Promise<{ resourceId: string; amount?: number }> | undefined;\n}\n\n/**\n * Injection token for Blimu configuration\n */\nexport const BLIMU_CONFIG = Symbol('BLIMU_CONFIG');\n","import {\n type CanActivate,\n type ExecutionContext,\n ForbiddenException,\n Injectable,\n SetMetadata,\n Inject,\n} from '@nestjs/common';\nimport 'reflect-metadata';\n\nimport type { EntitlementType } from '@blimu/types';\nimport { BlimuForbiddenException } from '../exceptions/blimu-forbidden.exception';\nimport { Blimu } from '@blimu/backend';\nimport { BLIMU_CONFIG, type BlimuConfig } from '../config/blimu.config';\n\nexport const ENTITLEMENT_KEY = 'entitlement';\nexport const ENTITLEMENT_METADATA_KEY = Symbol('entitlement');\n\n/**\n * Entitlement context returned by the entitlementCtxResolver callback\n */\nexport interface EntitlementCtx {\n resourceId: string;\n amount?: number; // Amount to check against usage limit (for consumption)\n}\n\n/**\n * Metadata interface for entitlement checks\n */\nexport interface EntitlementMetadata<TRequest = unknown> {\n entitlementKey: EntitlementType;\n entitlementCtxResolver?: (request: TRequest) => EntitlementCtx | Promise<EntitlementCtx>;\n}\n\n/**\n * Sets entitlement metadata for a route handler\n * @internal This is used internally by the @Entitlement decorator\n */\nexport const SetEntitlementMetadata = <TRequest = unknown>(\n entitlementKey: string,\n entitlementCtxResolver?: (request: TRequest) => EntitlementCtx | Promise<EntitlementCtx>,\n): MethodDecorator =>\n SetMetadata(ENTITLEMENT_METADATA_KEY, {\n entitlementKey,\n entitlementCtxResolver,\n } as EntitlementMetadata<TRequest>);\n\n/**\n * Guard that checks if the authenticated user has the required entitlement on a resource\n *\n * This guard automatically:\n * 1. Extracts the user from the request\n * 2. Extracts the resource ID using the provided extractor function\n * 3. Calls the Blimu Runtime API to check entitlements\n * 4. Allows or denies access based on the result\n */\n@Injectable()\nexport class EntitlementGuard<TRequest = unknown> implements CanActivate {\n constructor(\n @Inject(BLIMU_CONFIG)\n private readonly config: BlimuConfig<TRequest>,\n @Inject(Blimu)\n private readonly runtime: Blimu,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<TRequest>();\n const handler = context.getHandler();\n const metadata = Reflect.getMetadata(ENTITLEMENT_METADATA_KEY, handler) as\n | EntitlementMetadata<TRequest>\n | undefined;\n\n if (!metadata) {\n // No entitlement check required\n return true;\n }\n\n // Extract user ID using the configured getUserId function\n let userId: string;\n try {\n userId = await this.config.getUserId(request);\n } catch {\n throw new ForbiddenException('Failed to extract user ID from request');\n }\n\n if (!userId) {\n throw new ForbiddenException('User ID is required for entitlement check');\n }\n\n // Resolve entitlement context from request\n // Priority: decorator resolver > default resolver > error\n let entitlementCtx: EntitlementCtx | undefined;\n if (metadata.entitlementCtxResolver) {\n entitlementCtx = await metadata.entitlementCtxResolver(request);\n } else if (this.config.defaultEntitlementCtxResolver) {\n // Parse resourceType from entitlementKey (format: \"resourceType:action\")\n const resourceType = metadata.entitlementKey.split(':')[0] || '';\n entitlementCtx = await this.config.defaultEntitlementCtxResolver(\n {\n entitlement: metadata.entitlementKey,\n resourceType,\n },\n request,\n );\n } else {\n throw new ForbiddenException('No entitlement context resolver available');\n }\n\n if (!entitlementCtx?.resourceId) {\n throw new ForbiddenException('Resource ID is required for entitlement check');\n }\n\n try {\n // Check entitlement\n const result = await this.runtime.entitlements.checkEntitlement({\n userId,\n entitlement: metadata.entitlementKey,\n resourceId: entitlementCtx.resourceId,\n ...(entitlementCtx.amount !== undefined ? { amount: entitlementCtx.amount } : {}),\n });\n\n if (!result.allowed) {\n throw new BlimuForbiddenException(\n result,\n metadata.entitlementKey,\n entitlementCtx.resourceId,\n userId,\n );\n }\n\n return true;\n } catch (error) {\n if (error instanceof BlimuForbiddenException || error instanceof ForbiddenException) {\n throw error;\n }\n\n // Log the error for debugging but don't expose internal details\n console.error('Entitlement check failed:', error);\n throw new ForbiddenException('Failed to verify entitlements');\n }\n }\n}\n","import { ForbiddenException } from '@nestjs/common';\nimport type { Schema } from '@blimu/backend';\nimport type { EntitlementType } from '@blimu/types';\n/**\n * Custom exception for Blimu entitlement check failures\n *\n * This exception extends NestJS's ForbiddenException and includes\n * the typed EntitlementCheckResult, providing detailed information\n * about why the entitlement check failed (roles, plans, limits, etc.)\n */\nexport class BlimuForbiddenException extends ForbiddenException {\n /**\n * The entitlement check result containing detailed failure information\n */\n public readonly entitlementResult: Schema.EntitlementCheckResult;\n\n /**\n * The entitlement key that was checked\n */\n public readonly entitlementKey: EntitlementType;\n\n /**\n * The resource ID that was checked\n */\n public readonly resourceId: string;\n\n /**\n * The user ID that was checked\n */\n public readonly userId: string;\n\n constructor(\n entitlementResult: Schema.EntitlementCheckResult,\n entitlementKey: EntitlementType,\n resourceId: string,\n userId: string,\n ) {\n // Create a user-friendly message based on the failure reason\n const message = BlimuForbiddenException.buildMessage(entitlementResult, entitlementKey);\n\n super({\n message,\n entitlementResult,\n entitlementKey,\n resourceId,\n userId,\n });\n\n this.entitlementResult = entitlementResult;\n this.entitlementKey = entitlementKey;\n this.resourceId = resourceId;\n this.userId = userId;\n }\n\n /**\n * Builds a user-friendly error message from the entitlement check result\n */\n private static buildMessage(\n result: Schema.EntitlementCheckResult,\n entitlementKey: EntitlementType,\n ): string {\n const reasons: string[] = [];\n\n if (result.roles && !result.roles.allowed) {\n reasons.push(\n `Insufficient roles. Required: ${result.roles.allowedRoles?.join(', ') || 'unknown'}. User has: ${result.roles.userRoles?.join(', ') || 'none'}.`,\n );\n }\n\n if (result.plans && !result.plans.allowed) {\n reasons.push(\n `Plan restriction. Required plans: ${result.plans.allowedPlans?.join(', ') || 'unknown'}. Current plan: ${result.plans.plan || 'none'}.`,\n );\n }\n\n if (result.limit && !result.limit.allowed) {\n reasons.push(`Usage limit exceeded. ${result.limit.reason || 'Limit has been reached'}.`);\n }\n\n if (reasons.length === 0) {\n return `Access denied for entitlement: ${entitlementKey}`;\n }\n\n return `Access denied for entitlement \"${entitlementKey}\": ${reasons.join(' ')}`;\n }\n}\n","import { Inject, Injectable, Logger } from '@nestjs/common';\nimport { TokenVerifier } from '@blimu/backend';\nimport { BLIMU_CONFIG, type BlimuConfig } from '../config/blimu.config';\n\n@Injectable()\nexport class JWKService {\n private readonly logger = new Logger(JWKService.name);\n private readonly tokenVerifier: TokenVerifier;\n\n constructor(@Inject(BLIMU_CONFIG) private readonly config: BlimuConfig) {\n this.tokenVerifier = new TokenVerifier({\n runtimeApiUrl: this.config.baseURL,\n });\n }\n\n /**\n * Verify JWT token using JWKs from runtime-api\n */\n async verifyToken<T = unknown>(token: string): Promise<T> {\n try {\n this.logger.debug(\n `🔍 Verifying token. Runtime API URL: ${this.config.baseURL}, API Key prefix: ${this.config.apiKey?.substring(0, 10)}...`,\n );\n\n const result = await this.tokenVerifier.verifyToken<T>({\n secretKey: this.config.apiKey,\n token,\n runtimeApiUrl: this.config.baseURL,\n });\n\n this.logger.debug(`✅ Token verified successfully`);\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n this.logger.error(`❌ Token verification failed: ${errorMessage}`);\n if (error instanceof Error && error.stack) {\n this.logger.error(`Stack trace: ${error.stack}`);\n }\n throw error;\n }\n }\n\n /**\n * Clear cache (useful for testing or key rotation)\n */\n clearCache(): void {\n this.tokenVerifier.clearCache(this.config.apiKey);\n this.logger.debug('JWK cache cleared');\n }\n}\n","import { applyDecorators, UseGuards } from '@nestjs/common';\nimport {\n EntitlementGuard,\n SetEntitlementMetadata,\n type EntitlementCtx,\n} from '../guards/entitlement.guard';\nimport type { EntitlementType } from '@blimu/types';\n\n/**\n * Decorator to check if the authenticated user has a specific entitlement on a resource.\n *\n * This decorator combines the entitlement metadata setting and guard application\n * to provide a clean, declarative way to protect routes with entitlement checks.\n *\n * @param entitlementKey - The entitlement key to check (e.g., 'brand:read', 'organization:create_workspace')\n * @param entitlementCtxResolver - Optional function that returns entitlement context including resourceId and optionally amount for usage limits.\n * If not provided, the default resolver from module configuration will be used.\n *\n * @example\n * Basic usage with path parameter:\n * ```typescript\n * @Get('/:resourceId')\n * @Entitlement('brand:read', (req) => ({ resourceId: req.params.resourceId }))\n * async getBrand(@Param('resourceId') resourceId: string) {\n * // User is guaranteed to have 'brand:read' entitlement on this resource\n * }\n * ```\n *\n * @example\n * Using default resolver from module configuration:\n * ```typescript\n * // In module configuration:\n * BlimuModule.forRoot({\n * // ... other config\n * defaultEntitlementCtxResolver: ({ entitlement, resourceType }, req) => ({\n * resourceId: req.params.resourceId,\n * }),\n * })\n *\n * // In controller (no resolver needed):\n * @Get('/:resourceId')\n * @Entitlement('brand:read')\n * async getBrand(@Param('resourceId') resourceId: string) {\n * // Uses default resolver from config\n * }\n * ```\n *\n * @example\n * Using with typed parameters:\n * ```typescript\n * @Get('/:resourceType/:resourceId')\n * @Entitlement('workspace:delete', (req) => ({ resourceId: req.params.resourceId }))\n * async deleteResource(@Param() params: ResourceParamsDto) {\n * // User is guaranteed to have 'workspace:delete' entitlement\n * }\n * ```\n *\n * @example\n * Complex resource ID extraction:\n * ```typescript\n * @Post('/organizations/:orgId/workspaces')\n * @Entitlement('organization:create_workspace', (req) => {\n * const params = req.params as { orgId: string };\n * return { resourceId: params.orgId };\n * })\n * async createWorkspace(@Param() params: CreateWorkspaceParamsDto, @Body() body: CreateWorkspaceDto) {\n * // User is guaranteed to have 'organization:create_workspace' entitlement on the organization\n * }\n * ```\n *\n * @example\n * With usage limit consumption:\n * ```typescript\n * @Post('/api-calls')\n * @Entitlement('organization:make_api_call', (req) => ({\n * resourceId: req.params.orgId,\n * amount: req.body.apiCallsCount, // Amount to consume from usage limit\n * }))\n * async makeApiCalls(@Param('orgId') orgId: string, @Body() body: { apiCallsCount: number }) {\n * // User is guaranteed to have 'organization:make_api_call' entitlement\n * // and sufficient usage limit balance\n * }\n * ```\n *\n * @example\n * Async resource context extraction (e.g., from database):\n * ```typescript\n * @Delete('/items/:itemId')\n * @Entitlement('workspace:delete_item', async (req) => {\n * // You could fetch the workspace ID from your database\n * const item = await itemService.findById(req.params.itemId);\n * return { resourceId: item.workspaceId };\n * })\n * async deleteItem(@Param('itemId') itemId: string) {\n * // User is guaranteed to have 'workspace:delete_item' entitlement on the item's workspace\n * }\n * ```\n *\n * @example\n * Using with custom request type:\n * ```typescript\n * interface AuthenticatedRequest {\n * user: { id: string; email: string };\n * }\n *\n * @Get('/:resourceId')\n * @Entitlement<AuthenticatedRequest>('brand:read', (req) => {\n * // req is typed as AuthenticatedRequest, so req.user is properly typed\n * console.log(req.user.email); // TypeScript knows this exists\n * return { resourceId: req.params.resourceId };\n * })\n * async getBrand(@Param('resourceId') resourceId: string) {\n * // User is guaranteed to have 'brand:read' entitlement on this resource\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const Entitlement = <TRequest = any>(\n entitlementKey: EntitlementType,\n entitlementCtxResolver?: (request: TRequest) => EntitlementCtx | Promise<EntitlementCtx>,\n): MethodDecorator => {\n return applyDecorators(\n SetEntitlementMetadata<TRequest>(entitlementKey, entitlementCtxResolver),\n UseGuards(EntitlementGuard),\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAOO;;;AC2FA,IAAM,eAAe,uBAAO,cAAc;;;AClGjD,IAAAC,iBAOO;AACP,8BAAO;;;ACRP,oBAAmC;AAU5B,IAAM,0BAAN,MAAM,iCAAgC,iCAAmB;AAAA;AAAA;AAAA;AAAA,EAI9C;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EAEhB,YACE,mBACA,gBACA,YACA,QACA;AAEA,UAAM,UA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;AAAA;AAAA,QAEA;AAAA,QACA;AAAA,MACF;AAAA,MACA,SAAS,CAAC,kBAAkB,uBAAO,cAAc,UAAU;AAAA,IAC7D;AACA,WAAOA;AAAA,EACT;AACF;AAzNa,cAAN;AAAA,MADN,uBAAO,CAAC,CAAC;AAAA,GACG;;;AKvBb,IAAAC,iBAA2C;AAqHpC,IAAM,cAAc,CACzB,gBACA,2BACoB;AACpB,aAAO;AAAA,IACL,uBAAiC,gBAAgB,sBAAsB;AAAA,QACvE,0BAAU,gBAAgB;AAAA,EAC5B;AACF;","names":["import_common","import_common","import_common","import_backend","import_backend","config","module","import_common"]}
package/dist/index.d.cts CHANGED
@@ -1,9 +1,73 @@
1
- export { BlimuModule } from './modules/blimu.module.cjs';
2
- export { BLIMU_CONFIG, BlimuConfig } from './config/blimu.config.cjs';
3
- export { ENTITLEMENT_KEY, ENTITLEMENT_METADATA_KEY, EntitlementGuard, EntitlementInfo, EntitlementMetadata, SetEntitlementMetadata } from './guards/entitlement.guard.cjs';
4
- export { Entitlement } from './decorators/entitlement.decorator.cjs';
5
- export { BlimuForbiddenException } from './exceptions/blimu-forbidden.exception.cjs';
6
- export { JWKService } from './services/jwk.service.cjs';
7
- import '@nestjs/common';
8
- import '@blimu/types';
9
- import '@blimu/backend';
1
+ import { DynamicModule, InjectionToken, OptionalFactoryDependency, Type, ForwardReference, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
2
+ import { EntitlementType } from '@blimu/types';
3
+ import { Blimu, Schema } from '@blimu/backend';
4
+
5
+ interface BlimuConfig<TRequest = unknown> {
6
+ global?: boolean | undefined;
7
+ apiKey: string;
8
+ baseURL?: string | undefined;
9
+ environmentId?: string | undefined;
10
+ timeoutMs?: number | undefined;
11
+ getUserId: (request: TRequest) => string | Promise<string>;
12
+ defaultEntitlementCtxResolver?: (context: {
13
+ entitlement: EntitlementType;
14
+ resourceType: string;
15
+ }, request: TRequest) => {
16
+ resourceId: string;
17
+ amount?: number;
18
+ } | Promise<{
19
+ resourceId: string;
20
+ amount?: number;
21
+ }> | undefined;
22
+ }
23
+ declare const BLIMU_CONFIG: unique symbol;
24
+
25
+ declare class BlimuModule {
26
+ static forRoot<TRequest = unknown>(config: BlimuConfig<TRequest>): DynamicModule;
27
+ static forRootAsync<TRequest = unknown>(options: {
28
+ global?: boolean | undefined;
29
+ useFactory: (...args: unknown[]) => Promise<BlimuConfig<TRequest>> | BlimuConfig<TRequest>;
30
+ inject?: (InjectionToken | OptionalFactoryDependency)[];
31
+ imports?: (Type<unknown> | DynamicModule | Promise<DynamicModule> | ForwardReference<() => Type<unknown>>)[];
32
+ }): DynamicModule;
33
+ }
34
+
35
+ declare const ENTITLEMENT_KEY = "entitlement";
36
+ declare const ENTITLEMENT_METADATA_KEY: unique symbol;
37
+ interface EntitlementCtx {
38
+ resourceId: string;
39
+ amount?: number;
40
+ }
41
+ interface EntitlementMetadata<TRequest = unknown> {
42
+ entitlementKey: EntitlementType;
43
+ entitlementCtxResolver?: (request: TRequest) => EntitlementCtx | Promise<EntitlementCtx>;
44
+ }
45
+ declare const SetEntitlementMetadata: <TRequest = unknown>(entitlementKey: string, entitlementCtxResolver?: (request: TRequest) => EntitlementCtx | Promise<EntitlementCtx>) => MethodDecorator;
46
+ declare class EntitlementGuard<TRequest = unknown> implements CanActivate {
47
+ private readonly config;
48
+ private readonly runtime;
49
+ constructor(config: BlimuConfig<TRequest>, runtime: Blimu);
50
+ canActivate(context: ExecutionContext): Promise<boolean>;
51
+ }
52
+
53
+ declare const Entitlement: <TRequest = any>(entitlementKey: EntitlementType, entitlementCtxResolver?: (request: TRequest) => EntitlementCtx | Promise<EntitlementCtx>) => MethodDecorator;
54
+
55
+ declare class BlimuForbiddenException extends ForbiddenException {
56
+ readonly entitlementResult: Schema.EntitlementCheckResult;
57
+ readonly entitlementKey: EntitlementType;
58
+ readonly resourceId: string;
59
+ readonly userId: string;
60
+ constructor(entitlementResult: Schema.EntitlementCheckResult, entitlementKey: EntitlementType, resourceId: string, userId: string);
61
+ private static buildMessage;
62
+ }
63
+
64
+ declare class JWKService {
65
+ private readonly config;
66
+ private readonly logger;
67
+ private readonly tokenVerifier;
68
+ constructor(config: BlimuConfig);
69
+ verifyToken<T = unknown>(token: string): Promise<T>;
70
+ clearCache(): void;
71
+ }
72
+
73
+ export { BLIMU_CONFIG, type BlimuConfig, BlimuForbiddenException, BlimuModule, ENTITLEMENT_KEY, ENTITLEMENT_METADATA_KEY, Entitlement, type EntitlementCtx, EntitlementGuard, type EntitlementMetadata, JWKService, SetEntitlementMetadata };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,73 @@
1
- export { BlimuModule } from './modules/blimu.module.js';
2
- export { BLIMU_CONFIG, BlimuConfig } from './config/blimu.config.js';
3
- export { ENTITLEMENT_KEY, ENTITLEMENT_METADATA_KEY, EntitlementGuard, EntitlementInfo, EntitlementMetadata, SetEntitlementMetadata } from './guards/entitlement.guard.js';
4
- export { Entitlement } from './decorators/entitlement.decorator.js';
5
- export { BlimuForbiddenException } from './exceptions/blimu-forbidden.exception.js';
6
- export { JWKService } from './services/jwk.service.js';
7
- import '@nestjs/common';
8
- import '@blimu/types';
9
- import '@blimu/backend';
1
+ import { DynamicModule, InjectionToken, OptionalFactoryDependency, Type, ForwardReference, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
2
+ import { EntitlementType } from '@blimu/types';
3
+ import { Blimu, Schema } from '@blimu/backend';
4
+
5
+ interface BlimuConfig<TRequest = unknown> {
6
+ global?: boolean | undefined;
7
+ apiKey: string;
8
+ baseURL?: string | undefined;
9
+ environmentId?: string | undefined;
10
+ timeoutMs?: number | undefined;
11
+ getUserId: (request: TRequest) => string | Promise<string>;
12
+ defaultEntitlementCtxResolver?: (context: {
13
+ entitlement: EntitlementType;
14
+ resourceType: string;
15
+ }, request: TRequest) => {
16
+ resourceId: string;
17
+ amount?: number;
18
+ } | Promise<{
19
+ resourceId: string;
20
+ amount?: number;
21
+ }> | undefined;
22
+ }
23
+ declare const BLIMU_CONFIG: unique symbol;
24
+
25
+ declare class BlimuModule {
26
+ static forRoot<TRequest = unknown>(config: BlimuConfig<TRequest>): DynamicModule;
27
+ static forRootAsync<TRequest = unknown>(options: {
28
+ global?: boolean | undefined;
29
+ useFactory: (...args: unknown[]) => Promise<BlimuConfig<TRequest>> | BlimuConfig<TRequest>;
30
+ inject?: (InjectionToken | OptionalFactoryDependency)[];
31
+ imports?: (Type<unknown> | DynamicModule | Promise<DynamicModule> | ForwardReference<() => Type<unknown>>)[];
32
+ }): DynamicModule;
33
+ }
34
+
35
+ declare const ENTITLEMENT_KEY = "entitlement";
36
+ declare const ENTITLEMENT_METADATA_KEY: unique symbol;
37
+ interface EntitlementCtx {
38
+ resourceId: string;
39
+ amount?: number;
40
+ }
41
+ interface EntitlementMetadata<TRequest = unknown> {
42
+ entitlementKey: EntitlementType;
43
+ entitlementCtxResolver?: (request: TRequest) => EntitlementCtx | Promise<EntitlementCtx>;
44
+ }
45
+ declare const SetEntitlementMetadata: <TRequest = unknown>(entitlementKey: string, entitlementCtxResolver?: (request: TRequest) => EntitlementCtx | Promise<EntitlementCtx>) => MethodDecorator;
46
+ declare class EntitlementGuard<TRequest = unknown> implements CanActivate {
47
+ private readonly config;
48
+ private readonly runtime;
49
+ constructor(config: BlimuConfig<TRequest>, runtime: Blimu);
50
+ canActivate(context: ExecutionContext): Promise<boolean>;
51
+ }
52
+
53
+ declare const Entitlement: <TRequest = any>(entitlementKey: EntitlementType, entitlementCtxResolver?: (request: TRequest) => EntitlementCtx | Promise<EntitlementCtx>) => MethodDecorator;
54
+
55
+ declare class BlimuForbiddenException extends ForbiddenException {
56
+ readonly entitlementResult: Schema.EntitlementCheckResult;
57
+ readonly entitlementKey: EntitlementType;
58
+ readonly resourceId: string;
59
+ readonly userId: string;
60
+ constructor(entitlementResult: Schema.EntitlementCheckResult, entitlementKey: EntitlementType, resourceId: string, userId: string);
61
+ private static buildMessage;
62
+ }
63
+
64
+ declare class JWKService {
65
+ private readonly config;
66
+ private readonly logger;
67
+ private readonly tokenVerifier;
68
+ constructor(config: BlimuConfig);
69
+ verifyToken<T = unknown>(token: string): Promise<T>;
70
+ clearCache(): void;
71
+ }
72
+
73
+ export { BLIMU_CONFIG, type BlimuConfig, BlimuForbiddenException, BlimuModule, ENTITLEMENT_KEY, ENTITLEMENT_METADATA_KEY, Entitlement, type EntitlementCtx, EntitlementGuard, type EntitlementMetadata, JWKService, SetEntitlementMetadata };
package/dist/index.mjs CHANGED
@@ -89,9 +89,9 @@ var BlimuForbiddenException = class _BlimuForbiddenException extends ForbiddenEx
89
89
  import { Blimu } from "@blimu/backend";
90
90
  var ENTITLEMENT_KEY = "entitlement";
91
91
  var ENTITLEMENT_METADATA_KEY = /* @__PURE__ */ Symbol("entitlement");
92
- var SetEntitlementMetadata = (entitlementKey, getEntitlementInfo) => SetMetadata(ENTITLEMENT_METADATA_KEY, {
92
+ var SetEntitlementMetadata = (entitlementKey, entitlementCtxResolver) => SetMetadata(ENTITLEMENT_METADATA_KEY, {
93
93
  entitlementKey,
94
- getEntitlementInfo
94
+ entitlementCtxResolver
95
95
  });
96
96
  var EntitlementGuard = class {
97
97
  constructor(config, runtime) {
@@ -114,22 +114,36 @@ var EntitlementGuard = class {
114
114
  if (!userId) {
115
115
  throw new ForbiddenException2("User ID is required for entitlement check");
116
116
  }
117
- const entitlementInfo = await metadata.getEntitlementInfo(request);
118
- if (!entitlementInfo?.resourceId) {
117
+ let entitlementCtx;
118
+ if (metadata.entitlementCtxResolver) {
119
+ entitlementCtx = await metadata.entitlementCtxResolver(request);
120
+ } else if (this.config.defaultEntitlementCtxResolver) {
121
+ const resourceType = metadata.entitlementKey.split(":")[0] || "";
122
+ entitlementCtx = await this.config.defaultEntitlementCtxResolver(
123
+ {
124
+ entitlement: metadata.entitlementKey,
125
+ resourceType
126
+ },
127
+ request
128
+ );
129
+ } else {
130
+ throw new ForbiddenException2("No entitlement context resolver available");
131
+ }
132
+ if (!entitlementCtx?.resourceId) {
119
133
  throw new ForbiddenException2("Resource ID is required for entitlement check");
120
134
  }
121
135
  try {
122
136
  const result = await this.runtime.entitlements.checkEntitlement({
123
137
  userId,
124
138
  entitlement: metadata.entitlementKey,
125
- resourceId: entitlementInfo.resourceId,
126
- ...entitlementInfo.amount !== void 0 ? { amount: entitlementInfo.amount } : {}
139
+ resourceId: entitlementCtx.resourceId,
140
+ ...entitlementCtx.amount !== void 0 ? { amount: entitlementCtx.amount } : {}
127
141
  });
128
142
  if (!result.allowed) {
129
143
  throw new BlimuForbiddenException(
130
144
  result,
131
145
  metadata.entitlementKey,
132
- entitlementInfo.resourceId,
146
+ entitlementCtx.resourceId,
133
147
  userId
134
148
  );
135
149
  }
@@ -219,6 +233,9 @@ var BlimuModule = class {
219
233
  * environmentId: 'your-environment-id', // optional
220
234
  * timeoutMs: 30000, // optional
221
235
  * getUserId: (req) => req.user?.id, // required
236
+ * defaultEntitlementCtxResolver: ({ entitlement, resourceType }, req) => ({
237
+ * resourceId: req.params.resourceId,
238
+ * }), // optional
222
239
  * }),
223
240
  * ],
224
241
  * })
@@ -256,7 +273,8 @@ var BlimuModule = class {
256
273
  baseURL: config.baseURL ?? DEFAULT_BASE_URL,
257
274
  environmentId: config.environmentId,
258
275
  timeoutMs: config.timeoutMs ?? 3e4,
259
- getUserId: config.getUserId
276
+ getUserId: config.getUserId,
277
+ defaultEntitlementCtxResolver: config.defaultEntitlementCtxResolver
260
278
  }
261
279
  },
262
280
  {
@@ -299,6 +317,9 @@ var BlimuModule = class {
299
317
  * environmentId: configService.get('BLIMU_ENVIRONMENT_ID'),
300
318
  * timeoutMs: configService.get('BLIMU_TIMEOUT_MS'),
301
319
  * getUserId: (req) => req.user?.id,
320
+ * defaultEntitlementCtxResolver: (entitlementKey, req) => ({
321
+ * resourceId: req.params.resourceId,
322
+ * }),
302
323
  * }),
303
324
  * inject: [ConfigService],
304
325
  * }),
@@ -369,7 +390,8 @@ var BlimuModule = class {
369
390
  baseURL: config.baseURL ?? DEFAULT_BASE_URL,
370
391
  environmentId: config.environmentId,
371
392
  timeoutMs: config.timeoutMs ?? 3e4,
372
- getUserId: config.getUserId
393
+ getUserId: config.getUserId,
394
+ defaultEntitlementCtxResolver: config.defaultEntitlementCtxResolver
373
395
  };
374
396
  },
375
397
  ...options.inject ? { inject: options.inject } : {}
@@ -400,9 +422,9 @@ BlimuModule = __decorateClass([
400
422
 
401
423
  // src/decorators/entitlement.decorator.ts
402
424
  import { applyDecorators, UseGuards } from "@nestjs/common";
403
- var Entitlement = (entitlementKey, getEntitlementInfo) => {
425
+ var Entitlement = (entitlementKey, entitlementCtxResolver) => {
404
426
  return applyDecorators(
405
- SetEntitlementMetadata(entitlementKey, getEntitlementInfo),
427
+ SetEntitlementMetadata(entitlementKey, entitlementCtxResolver),
406
428
  UseGuards(EntitlementGuard)
407
429
  );
408
430
  };