@rxap/nest-auth0 10.0.1 → 10.1.0-dev.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,18 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [10.1.0-dev.1](https://gitlab.com/rxap/packages/compare/@rxap/nest-auth0@10.1.0-dev.0...@rxap/nest-auth0@10.1.0-dev.1) (2025-03-14)
7
+
8
+ ### Features
9
+
10
+ - **auth0:** replace jwt.strategy with auth0.guard for enhanced JWT validation ([3fe0564](https://gitlab.com/rxap/packages/commit/3fe0564722c09dc1735ca4921879d02e6d6839ec))
11
+
12
+ # [10.1.0-dev.0](https://gitlab.com/rxap/packages/compare/@rxap/nest-auth0@10.0.1...@rxap/nest-auth0@10.1.0-dev.0) (2025-03-12)
13
+
14
+ ### Features
15
+
16
+ - **auth0:** enhance validation schema with default values support ([10cd7ce](https://gitlab.com/rxap/packages/commit/10cd7ce818e022bc46247f761ece006257b4c29a))
17
+
6
18
  ## [10.0.1](https://gitlab.com/rxap/packages/compare/@rxap/nest-auth0@10.0.1-dev.2...@rxap/nest-auth0@10.0.1) (2025-02-23)
7
19
 
8
20
  **Note:** Version bump only for package @rxap/nest-auth0
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
- "version": "10.0.1",
2
+ "version": "10.1.0-dev.1",
3
3
  "name": "@rxap/nest-auth0",
4
4
  "description": "This package provides an Auth0 module for NestJS applications, simplifying integration with Auth0 for authentication and authorization. It includes a configurable module, JWT strategy, and service for interacting with the Auth0 Authentication API. The module also offers validation schemas for environment variables related to Auth0 configuration.\n",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "dependencies": {
7
7
  "@nestjs/passport": "^11.0.5",
8
- "@nx/devkit": "20.4.6",
8
+ "@nx/devkit": "20.5.0",
9
9
  "auth0": "^4.18.0",
10
10
  "passport-jwt": "^4.0.1",
11
11
  "tslib": "^2.3.0"
@@ -39,5 +39,5 @@
39
39
  "schematics": "./generators.json",
40
40
  "type": "commonjs",
41
41
  "types": "./src/index.d.ts",
42
- "gitHead": "d77504e6fd71447b1032f897cabb2aefac17c260"
42
+ "gitHead": "70c885dac01229b385d60bdeaf77140f0fc6bc8f"
43
43
  }
package/src/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export * from './lib/auth0-module-options.factory';
2
2
  export * from './lib/auth0-validation-schema';
3
+ export * from './lib/auth0.guard';
3
4
  export * from './lib/auth0.module';
4
5
  export * from './lib/auth0.service';
5
- export * from './lib/jwt.strategy';
6
6
  export * from './lib/tokens';
package/src/index.js CHANGED
@@ -4,8 +4,8 @@ const tslib_1 = require("tslib");
4
4
  // region
5
5
  tslib_1.__exportStar(require("./lib/auth0-module-options.factory"), exports);
6
6
  tslib_1.__exportStar(require("./lib/auth0-validation-schema"), exports);
7
+ tslib_1.__exportStar(require("./lib/auth0.guard"), exports);
7
8
  tslib_1.__exportStar(require("./lib/auth0.module"), exports);
8
9
  tslib_1.__exportStar(require("./lib/auth0.service"), exports);
9
- tslib_1.__exportStar(require("./lib/jwt.strategy"), exports);
10
10
  tslib_1.__exportStar(require("./lib/tokens"), exports);
11
11
  // endregion
@@ -1,19 +1,37 @@
1
1
  import { Environment } from '@rxap/nest-utilities';
2
2
  import * as Joi from 'joi';
3
3
  /**
4
- * Generates a Joi validation schema for Auth0 configuration values based on the provided environment.
4
+ * Auth0ValidationSchema defines the structure for environment variables
5
+ * used in configuring and validating Auth0 authentication.
5
6
  *
6
- * @param environment - The environment parameters that may influence the validation schema.
7
+ * This interface specifies the required properties needed for integrating
8
+ * Auth0, including URLs, audience, domain, client ID, and client secret.
7
9
  *
8
- * @returns A Joi schema map that defines validation rules for the following Auth0 configuration keys:
9
- * - `AUTH0_ISSUER_URL`: Must be a string.
10
- * - `AUTH0_AUDIENCE`: Must be a string.
11
- * - `AUTH0_DOMAIN`: Must be a string and a valid domain.
12
- * - `AUTH0_CLIENT_ID`: Must be a string.
13
- * - `AUTH0_CLIENT_SECRET`: Must be a string.
10
+ * Properties:
11
+ * - AUTH0_ISSUER_URL: The URL representing the Auth0 issuer, typically used
12
+ * for validating tokens and identifying the authorization server.
13
+ * - AUTH0_AUDIENCE: The unique identifier representing the API audience
14
+ * that tokens will be issued for.
15
+ * - AUTH0_DOMAIN: The domain of the Auth0 tenant, used for constructing
16
+ * URLs and making Auth0 API calls.
17
+ * - AUTH0_CLIENT_ID: The client identifier for the application, provided
18
+ * by Auth0 during application registration.
19
+ * - AUTH0_CLIENT_SECRET: The secret key associated with the application,
20
+ * used for validating communication and securing requests.
21
+ */
22
+ export interface Auth0ValidationSchema {
23
+ AUTH0_ISSUER_URL: string;
24
+ AUTH0_AUDIENCE: string;
25
+ AUTH0_DOMAIN: string;
26
+ AUTH0_CLIENT_ID: string;
27
+ AUTH0_CLIENT_SECRET: string;
28
+ }
29
+ /**
30
+ * Generates a validation schema for Auth0 configuration settings using Joi.
31
+ * This schema can be used to validate environment-specific variables.
14
32
  *
15
- * @example
16
- * ```typescript
17
- * const schema = auth0ValidationSchema(environment);
33
+ * @param {Environment} environment - The application's environment configuration used to determine the applicable validation schema.
34
+ * @param {Partial<Auth0ValidationSchema>} [defaults={}] - An optional object with default values for the schema keys.
35
+ * @return {Record<string, StringSchema>} The Joi validation schema object for Auth0 configuration.
18
36
  */
19
- export declare function auth0ValidationSchema(environment: Environment): Joi.PartialSchemaMap<any>;
37
+ export declare function auth0ValidationSchema(environment: Environment, defaults?: Partial<Auth0ValidationSchema>): Record<string, Joi.StringSchema<string>>;
@@ -3,27 +3,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.auth0ValidationSchema = auth0ValidationSchema;
4
4
  const Joi = require("joi");
5
5
  /**
6
- * Generates a Joi validation schema for Auth0 configuration values based on the provided environment.
6
+ * Generates a validation schema for Auth0 configuration settings using Joi.
7
+ * This schema can be used to validate environment-specific variables.
7
8
  *
8
- * @param environment - The environment parameters that may influence the validation schema.
9
- *
10
- * @returns A Joi schema map that defines validation rules for the following Auth0 configuration keys:
11
- * - `AUTH0_ISSUER_URL`: Must be a string.
12
- * - `AUTH0_AUDIENCE`: Must be a string.
13
- * - `AUTH0_DOMAIN`: Must be a string and a valid domain.
14
- * - `AUTH0_CLIENT_ID`: Must be a string.
15
- * - `AUTH0_CLIENT_SECRET`: Must be a string.
16
- *
17
- * @example
18
- * ```typescript
19
- * const schema = auth0ValidationSchema(environment);
9
+ * @param {Environment} environment - The application's environment configuration used to determine the applicable validation schema.
10
+ * @param {Partial<Auth0ValidationSchema>} [defaults={}] - An optional object with default values for the schema keys.
11
+ * @return {Record<string, StringSchema>} The Joi validation schema object for Auth0 configuration.
20
12
  */
21
- function auth0ValidationSchema(environment) {
13
+ function auth0ValidationSchema(environment, defaults = {}) {
22
14
  const schema = {};
23
15
  schema['AUTH0_ISSUER_URL'] = Joi.string();
24
16
  schema['AUTH0_AUDIENCE'] = Joi.string();
25
17
  schema['AUTH0_DOMAIN'] = Joi.string().domain();
26
18
  schema['AUTH0_CLIENT_ID'] = Joi.string();
27
19
  schema['AUTH0_CLIENT_SECRET'] = Joi.string();
20
+ for (const [key, value] of Object.keys(defaults)) {
21
+ schema[key] = schema[key].default(value);
22
+ }
28
23
  return schema;
29
24
  }
@@ -0,0 +1,8 @@
1
+ import { CanActivate, ExecutionContext } from '@nestjs/common';
2
+ import { Reflector } from '@nestjs/core';
3
+ export declare class Auth0Guard implements CanActivate {
4
+ private readonly jwtService;
5
+ private readonly logger;
6
+ protected readonly reflector: Reflector;
7
+ canActivate(context: ExecutionContext): Promise<boolean>;
8
+ }
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Auth0Guard = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const common_1 = require("@nestjs/common");
6
+ const core_1 = require("@nestjs/core");
7
+ const jwt_1 = require("@nestjs/jwt");
8
+ const nest_utilities_1 = require("@rxap/nest-utilities");
9
+ const passport_jwt_1 = require("passport-jwt");
10
+ let Auth0Guard = class Auth0Guard {
11
+ async canActivate(context) {
12
+ const isPublic = this.reflector.getAllAndOverride(nest_utilities_1.IS_PUBLIC_KEY, [
13
+ context.getHandler(),
14
+ context.getClass(),
15
+ ]);
16
+ if (isPublic) {
17
+ return true;
18
+ }
19
+ const request = context.switchToHttp().getRequest();
20
+ const jwt = passport_jwt_1.ExtractJwt.fromAuthHeaderAsBearerToken()(request);
21
+ if (!jwt) {
22
+ this.logger.debug('No Bearer token found in authorization header', 'Auth0Guard');
23
+ return false;
24
+ }
25
+ const payload = await this.jwtService.verifyAsync(jwt);
26
+ if (!payload) {
27
+ this.logger.warn('JWT verification failed', 'Auth0Guard');
28
+ return false;
29
+ }
30
+ this.logger.verbose(`JWT verification succeeded for user ${payload.sub}`, 'Auth0Guard');
31
+ request.user = payload;
32
+ return true;
33
+ }
34
+ };
35
+ exports.Auth0Guard = Auth0Guard;
36
+ tslib_1.__decorate([
37
+ (0, common_1.Inject)(jwt_1.JwtService),
38
+ tslib_1.__metadata("design:type", jwt_1.JwtService)
39
+ ], Auth0Guard.prototype, "jwtService", void 0);
40
+ tslib_1.__decorate([
41
+ (0, common_1.Inject)(common_1.Logger),
42
+ tslib_1.__metadata("design:type", common_1.Logger)
43
+ ], Auth0Guard.prototype, "logger", void 0);
44
+ tslib_1.__decorate([
45
+ (0, common_1.Inject)(core_1.Reflector),
46
+ tslib_1.__metadata("design:type", core_1.Reflector)
47
+ ], Auth0Guard.prototype, "reflector", void 0);
48
+ exports.Auth0Guard = Auth0Guard = tslib_1.__decorate([
49
+ (0, common_1.Injectable)()
50
+ ], Auth0Guard);
@@ -4,9 +4,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.Auth0Module = exports.ASYNC_OPTIONS_TYPE = exports.OPTIONS_TYPE = exports.MODULE_OPTIONS_TOKEN = exports.ConfigurableModuleClass = void 0;
5
5
  const tslib_1 = require("tslib");
6
6
  const common_1 = require("@nestjs/common");
7
- const passport_1 = require("@nestjs/passport");
7
+ const config_1 = require("@nestjs/config");
8
+ const jwt_1 = require("@nestjs/jwt");
9
+ const jwks_rsa_1 = require("jwks-rsa");
10
+ const auth0_guard_1 = require("./auth0.guard");
8
11
  const auth0_service_1 = require("./auth0.service");
9
- const jwt_strategy_1 = require("./jwt.strategy");
10
12
  const tokens_1 = require("./tokens");
11
13
  _a = new common_1.ConfigurableModuleBuilder()
12
14
  .build(), exports.ConfigurableModuleClass = _a.ConfigurableModuleClass, exports.MODULE_OPTIONS_TOKEN = _a.MODULE_OPTIONS_TOKEN, exports.OPTIONS_TYPE = _a.OPTIONS_TYPE, exports.ASYNC_OPTIONS_TYPE = _a.ASYNC_OPTIONS_TYPE;
@@ -136,8 +138,39 @@ let Auth0Module = class Auth0Module extends exports.ConfigurableModuleClass {
136
138
  exports.Auth0Module = Auth0Module;
137
139
  exports.Auth0Module = Auth0Module = tslib_1.__decorate([
138
140
  (0, common_1.Module)({
139
- imports: [passport_1.PassportModule.register({ defaultStrategy: 'jwt' })],
140
- providers: [jwt_strategy_1.JwtStrategy],
141
- exports: [passport_1.PassportModule],
141
+ imports: [
142
+ jwt_1.JwtModule.registerAsync({
143
+ useFactory: (config) => ({
144
+ secretOrKeyProvider: (_, tokenOrPayload) => {
145
+ return new Promise((resolve, reject) => {
146
+ (0, jwks_rsa_1.passportJwtSecret)({
147
+ cache: true,
148
+ rateLimit: true,
149
+ jwksRequestsPerMinute: 5,
150
+ jwksUri: `${config.get('AUTH0_ISSUER_URL')}.well-known/jwks.json`,
151
+ })(null, tokenOrPayload, (err, secret) => {
152
+ if (err) {
153
+ reject(err);
154
+ }
155
+ else if (secret) {
156
+ resolve(secret);
157
+ }
158
+ else {
159
+ reject(new Error('No secret found'));
160
+ }
161
+ });
162
+ });
163
+ },
164
+ verifyOptions: {
165
+ audience: config.get('AUTH0_AUDIENCE'),
166
+ issuer: config.get('AUTH0_ISSUER_URL'),
167
+ algorithms: [config.get('AUTH0_ALGORITHM', 'RS256')],
168
+ },
169
+ }),
170
+ inject: [config_1.ConfigService],
171
+ }),
172
+ ],
173
+ providers: [auth0_guard_1.Auth0Guard],
174
+ exports: [auth0_guard_1.Auth0Guard],
142
175
  })
143
176
  ], Auth0Module);
@@ -1,76 +0,0 @@
1
- import { ConfigService } from '@nestjs/config';
2
- import { Strategy } from 'passport-jwt';
3
- declare const JwtStrategy_base: new (...args: [opt: import("passport-jwt").StrategyOptionsWithRequest] | [opt: import("passport-jwt").StrategyOptionsWithoutRequest]) => Strategy & {
4
- validate(...args: any[]): unknown;
5
- };
6
- /**
7
- * Here's the TSDoc documentation for the `JwtStrategy` class:
8
- *
9
- * A JWT (JSON Web Token) strategy implementation for authentication using Passport.js in NestJS applications.
10
- *
11
- * @summary
12
- * This class implements the JWT strategy for authentication, integrating with Auth0's JWKS (JSON Web Key Set) for token validation.
13
- *
14
- * @example
15
- * ```typescript
16
- * import { JwtStrategy } from './jwt.strategy';
17
- *
18
- * @Module({
19
- * providers: [JwtStrategy],
20
- * })
21
- * export class AuthModule {
22
- * constructor(private readonly jwtStrategy: JwtStrategy) {}
23
- * }
24
- * ```
25
- *
26
- * @example
27
- * ```typescript
28
- * // Using the strategy in a guard
29
- * @Injectable()
30
- * export class JwtAuthGuard extends AuthGuard('jwt') {
31
- * constructor(private jwtStrategy: JwtStrategy) {
32
- * super();
33
- * }
34
- * }
35
- * ```
36
- *
37
- * @throws {@link Error} If the configuration parameters for Auth0 are invalid or missing
38
- * @throws {@link Error} If the JWT token validation fails
39
- * @throws {@link Error} If the JWKS endpoint is unreachable or returns invalid data
40
- *
41
- * @property logger - A NestJS logger instance for verbose logging of validation operations
42
- * @property validate - Method to validate the JWT payload and return the verified token contents
43
- *
44
- * @returns An instance of the JWT strategy that can be used for token validation in passport-based authentication
45
- */
46
- export declare class JwtStrategy extends JwtStrategy_base {
47
- private readonly logger;
48
- constructor(config: ConfigService);
49
- /**
50
- * Here's the TSDoc documentation for the `validate` method:
51
- *
52
- * Validates the JWT payload received from the authentication process.
53
- *
54
- * @summary
55
- * Performs validation of the decoded JWT payload and logs the validation process for debugging purposes.
56
- *
57
- * @param payload - The decoded JWT token payload to be validated. This can contain any JWT claims such as subject, issuer, or custom claims.
58
- *
59
- * @returns The validated payload object that will be attached to the request object for use in subsequent request handlers.
60
- *
61
- * @example
62
- * ```typescript
63
- * const jwtStrategy = new JwtStrategy(configService);
64
- * const payload = await jwtStrategy.validate({
65
- * sub: '123456789',
66
- * email: 'user@example.com',
67
- * permissions: ['read:users']
68
- * });
69
- * // payload will be available in your request object
70
- * ```
71
- *
72
- * @throws {@link Error} If the payload fails validation or contains invalid claims.
73
- */
74
- validate(payload: unknown): unknown;
75
- }
76
- export {};
@@ -1,103 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.JwtStrategy = void 0;
4
- const tslib_1 = require("tslib");
5
- const common_1 = require("@nestjs/common");
6
- const config_1 = require("@nestjs/config");
7
- const passport_1 = require("@nestjs/passport");
8
- const passport_jwt_1 = require("passport-jwt");
9
- const jwks_rsa_1 = require("jwks-rsa");
10
- /**
11
- * Here's the TSDoc documentation for the `JwtStrategy` class:
12
- *
13
- * A JWT (JSON Web Token) strategy implementation for authentication using Passport.js in NestJS applications.
14
- *
15
- * @summary
16
- * This class implements the JWT strategy for authentication, integrating with Auth0's JWKS (JSON Web Key Set) for token validation.
17
- *
18
- * @example
19
- * ```typescript
20
- * import { JwtStrategy } from './jwt.strategy';
21
- *
22
- * @Module({
23
- * providers: [JwtStrategy],
24
- * })
25
- * export class AuthModule {
26
- * constructor(private readonly jwtStrategy: JwtStrategy) {}
27
- * }
28
- * ```
29
- *
30
- * @example
31
- * ```typescript
32
- * // Using the strategy in a guard
33
- * @Injectable()
34
- * export class JwtAuthGuard extends AuthGuard('jwt') {
35
- * constructor(private jwtStrategy: JwtStrategy) {
36
- * super();
37
- * }
38
- * }
39
- * ```
40
- *
41
- * @throws {@link Error} If the configuration parameters for Auth0 are invalid or missing
42
- * @throws {@link Error} If the JWT token validation fails
43
- * @throws {@link Error} If the JWKS endpoint is unreachable or returns invalid data
44
- *
45
- * @property logger - A NestJS logger instance for verbose logging of validation operations
46
- * @property validate - Method to validate the JWT payload and return the verified token contents
47
- *
48
- * @returns An instance of the JWT strategy that can be used for token validation in passport-based authentication
49
- */
50
- let JwtStrategy = class JwtStrategy extends (0, passport_1.PassportStrategy)(passport_jwt_1.Strategy) {
51
- constructor(config) {
52
- super({
53
- secretOrKeyProvider: (0, jwks_rsa_1.passportJwtSecret)({
54
- cache: true,
55
- rateLimit: true,
56
- jwksRequestsPerMinute: 5,
57
- jwksUri: `${config.get('AUTH0_ISSUER_URL')}.well-known/jwks.json`,
58
- }),
59
- jwtFromRequest: passport_jwt_1.ExtractJwt.fromAuthHeaderAsBearerToken(),
60
- audience: config.get('AUTH0_AUDIENCE'),
61
- issuer: `${config.get('AUTH0_ISSUER_URL')}`,
62
- algorithms: ['RS256'],
63
- });
64
- }
65
- /**
66
- * Here's the TSDoc documentation for the `validate` method:
67
- *
68
- * Validates the JWT payload received from the authentication process.
69
- *
70
- * @summary
71
- * Performs validation of the decoded JWT payload and logs the validation process for debugging purposes.
72
- *
73
- * @param payload - The decoded JWT token payload to be validated. This can contain any JWT claims such as subject, issuer, or custom claims.
74
- *
75
- * @returns The validated payload object that will be attached to the request object for use in subsequent request handlers.
76
- *
77
- * @example
78
- * ```typescript
79
- * const jwtStrategy = new JwtStrategy(configService);
80
- * const payload = await jwtStrategy.validate({
81
- * sub: '123456789',
82
- * email: 'user@example.com',
83
- * permissions: ['read:users']
84
- * });
85
- * // payload will be available in your request object
86
- * ```
87
- *
88
- * @throws {@link Error} If the payload fails validation or contains invalid claims.
89
- */
90
- validate(payload) {
91
- this.logger.verbose('validate: %JSON', payload, 'JwtStrategy');
92
- return payload;
93
- }
94
- };
95
- exports.JwtStrategy = JwtStrategy;
96
- tslib_1.__decorate([
97
- (0, common_1.Inject)(common_1.Logger),
98
- tslib_1.__metadata("design:type", common_1.Logger)
99
- ], JwtStrategy.prototype, "logger", void 0);
100
- exports.JwtStrategy = JwtStrategy = tslib_1.__decorate([
101
- (0, common_1.Injectable)(),
102
- tslib_1.__metadata("design:paramtypes", [config_1.ConfigService])
103
- ], JwtStrategy);