@telperion/nest-pack 1.3.0 → 1.4.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.
@@ -3,21 +3,22 @@
3
3
  var tslib = require('tslib');
4
4
  var common = require('@nestjs/common');
5
5
  var core = require('@nestjs/core');
6
- var jwt = require('@nestjs/jwt');
7
6
 
8
7
  /**
9
8
  * #### Create JWT Auth Guard
10
9
  *
11
10
  * Creates a guard that requires a valid JWT on every route, for use as the global `APP_GUARD`:
12
11
  *
13
- * - routes and controllers marked with `@Guard.public()` pass without a token
12
+ * - routes and controllers marked with `@Guard.public()` pass without a token; with `publicRoutes: 'optional'` a valid
13
+ * token still gives them the user, and a missing, invalid or expired one passes as anonymous
14
14
  * - a missing, malformed or invalid token (bad signature, wrong audience, …): **401** `unauthorizedMessage`
15
- * - an expired token: **401** `expiredMessage` (`'TokenExpired'`), so clients can tell "renew and retry" from "sign in"
15
+ * - an expired token (see `isExpired`): **401** `expiredMessage` (`'TokenExpired'`), so clients can tell "renew and retry" from "sign in"
16
16
  * - otherwise the payload is written to `request.user` (see `property`) and is available through `@Guard.user()`
17
17
  *
18
18
  * Tokens are verified with the `JwtService` of `@nestjs/jwt`: register `JwtModule` (with the secret or keys) in
19
- * the module that provides the guard. The token comes from the `Authorization: Bearer` header unless `extract`
20
- * reads it from elsewhere. HTTP only.
19
+ * the app. To verify otherwise (e.g. with a JWKS and `jose`), provide a {@link JwtAuthGuardVerifier} and pass its
20
+ * injection token as `verifier`; then `@nestjs/jwt` is not needed. The token comes from the `Authorization: Bearer`
21
+ * header unless `extract` reads it from elsewhere. HTTP only.
21
22
  *
22
23
  * * * *
23
24
  * Example:
@@ -49,28 +50,41 @@ var jwt = require('@nestjs/jwt');
49
50
  *
50
51
  * Other guards and interceptors can skip public routes with `AuthGuard.isPublic(context)`.
51
52
  * * * *
52
- * @param options Messages, where the token comes from, verification options and where the payload goes
53
+ * @param options Messages, where the token comes from, how it is verified, public routes and where the payload goes
53
54
  * @returns An injectable guard class with `public()`, `isPublic()`, `user()` and `userOf()`
55
+ * @throws When `verifyOptions` come with a `verifier`, as only the `JwtService` reads them
54
56
  */
55
57
  function createJwtAuthGuard(options = {}) {
56
58
  var JwtAuthGuard_1;
57
- const { expiredMessage = 'TokenExpired', unauthorizedMessage = 'Unauthorized', extract, verifyOptions, property = 'user', } = options;
59
+ const { expiredMessage = 'TokenExpired', unauthorizedMessage = 'Unauthorized', extract, verifier, verifyOptions, publicRoutes = 'skip', property = 'user', } = options;
58
60
  const publicKey = Symbol('jwt-auth-guard:public');
61
+ if (verifier !== undefined && verifyOptions !== undefined) {
62
+ throw new Error('createJwtAuthGuard: `verifyOptions` are options of the JwtService of @nestjs/jwt; pass them to the `verifier` instead');
63
+ }
59
64
  let JwtAuthGuard = class JwtAuthGuard {
60
65
  static { JwtAuthGuard_1 = this; }
61
66
  reflector;
62
- jwt;
63
67
  static user = common.createParamDecorator((_data, context) => JwtAuthGuard_1.userOf(context.switchToHttp().getRequest()));
68
+ /** Reads `public()` markers when `isPublic()` gets no reflector; `Reflector` needs no dependencies */
69
+ static defaultReflector = new core.Reflector();
70
+ /** Whether a verification error means an expired token: jsonwebtoken's `TokenExpiredError` or jose's `JWTExpired` */
71
+ static isExpired = options.isExpired ??
72
+ ((error) => typeof error === 'object' &&
73
+ error !== null &&
74
+ (error.name === 'TokenExpiredError' || error.code === 'ERR_JWT_EXPIRED'));
75
+ /** The verifier of the requests */
76
+ verifier;
64
77
  /**
65
78
  * @param reflector Reads `public()` markers
66
- * @param jwt Verifies tokens
79
+ * @param source The `verifier`, or without one the `ModuleRef` the `JwtService` is resolved from
67
80
  */
68
- constructor(reflector, jwt) {
81
+ constructor(reflector, source) {
69
82
  this.reflector = reflector;
70
- this.jwt = jwt;
83
+ this.verifier =
84
+ verifier === undefined
85
+ ? () => JwtAuthGuard_1.jwtServiceVerifier(source)
86
+ : () => Promise.resolve(source);
71
87
  }
72
- /** Reads `public()` markers when `isPublic()` gets no reflector; `Reflector` needs no dependencies */
73
- static defaultReflector = new core.Reflector();
74
88
  static public() {
75
89
  return common.SetMetadata(publicKey, true);
76
90
  }
@@ -87,23 +101,35 @@ function createJwtAuthGuard(options = {}) {
87
101
  const header = headers['authorization'];
88
102
  return (typeof header === 'string' ? /^Bearer +(\S+)$/i.exec(header) : null)?.[1];
89
103
  }
104
+ /**
105
+ * Verifies with the `JwtService` of `@nestjs/jwt`, imported only here so apps with a `verifier` need not install it.
106
+ * Looked up in the whole app, as the guard's module only imports `JwtModule`.
107
+ */
108
+ static jwtServiceVerifier(moduleRef) {
109
+ return import('@nestjs/jwt')
110
+ .then(({ JwtService }) => moduleRef.get(JwtService, { strict: false }))
111
+ .then(jwt => ({ verify: token => jwt.verifyAsync(token, verifyOptions) }));
112
+ }
90
113
  canActivate(context) {
91
- if (JwtAuthGuard_1.isPublic(context, this.reflector)) {
92
- return true;
93
- }
94
114
  const request = context.switchToHttp().getRequest();
95
- const token = extract ? extract(request) : JwtAuthGuard_1.bearerToken(request);
115
+ const optional = JwtAuthGuard_1.isPublic(context, this.reflector);
116
+ const token = optional && publicRoutes === 'skip'
117
+ ? undefined
118
+ : extract
119
+ ? extract(request)
120
+ : JwtAuthGuard_1.bearerToken(request);
96
121
  return token
97
- ? this.jwt.verifyAsync(token, verifyOptions).then(payload => (Object.assign(request, { [property]: payload }), true), (error) => Promise.reject(new common.UnauthorizedException(error instanceof jwt.TokenExpiredError ? expiredMessage : unauthorizedMessage)))
98
- : Promise.reject(new common.UnauthorizedException(unauthorizedMessage));
122
+ ? this.verifier().then(verifier => Promise.resolve(token)
123
+ .then(value => verifier.verify(value, request))
124
+ .then(payload => (Object.assign(request, { [property]: payload }), true), (error) => optional || Promise.reject(new common.UnauthorizedException(JwtAuthGuard_1.isExpired(error) ? expiredMessage : unauthorizedMessage))))
125
+ : optional || Promise.reject(new common.UnauthorizedException(unauthorizedMessage));
99
126
  }
100
127
  };
101
128
  JwtAuthGuard = JwtAuthGuard_1 = tslib.__decorate([
102
129
  common.Injectable(),
103
- tslib.__metadata("design:paramtypes", [core.Reflector,
104
- jwt.JwtService])
130
+ tslib.__metadata("design:paramtypes", [core.Reflector, Object])
105
131
  ], JwtAuthGuard);
106
- [core.Reflector, jwt.JwtService].forEach((token, index) => common.Inject(token)(JwtAuthGuard, undefined, index));
132
+ [core.Reflector, verifier ?? core.ModuleRef].forEach((token, index) => common.Inject(token)(JwtAuthGuard, undefined, index));
107
133
  return JwtAuthGuard;
108
134
  }
109
135
 
@@ -1 +1 @@
1
- {"version":3,"file":"create-jwt-auth-guard.cjs","sources":["../../../../libs/nest-pack/src/auth/create-jwt-auth-guard.ts"],"sourcesContent":[null],"names":["createParamDecorator","Reflector","SetMetadata","UnauthorizedException","TokenExpiredError","__decorate","Injectable","JwtService","Inject"],"mappings":";;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CG;AACG,SAAU,kBAAkB,CAChC,OAAA,GAAwC,EAAE,EAAA;;AAE1C,IAAA,MAAM,EACJ,cAAc,GAAG,cAAc,EAC/B,mBAAmB,GAAG,cAAc,EACpC,OAAO,EACP,aAAa,EACb,QAAQ,GAAG,MAAM,GAClB,GAAG,OAAO;AACX,IAAA,MAAM,SAAS,GAAG,MAAM,CAAC,uBAAuB,CAAC;IAEjD,IACM,YAAY,GADlB,MACM,YAAY,CAAA;;AAUG,QAAA,SAAA;AACA,QAAA,GAAA;QAVnB,OAAgB,IAAI,GAAGA,2BAAoB,CACzC,CAAC,KAAc,EAAE,OAAyB,KAA0B,cAAY,CAAC,MAAM,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,UAAU,EAAU,CAAC,CACrI;AAED;;;AAGG;QACH,WAAA,CACmB,SAAoB,EACpB,GAAe,EAAA;YADf,IAAA,CAAA,SAAS,GAAT,SAAS;YACT,IAAA,CAAA,GAAG,GAAH,GAAG;QACnB;;AAGK,QAAA,OAAgB,gBAAgB,GAAG,IAAIC,c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O,CAAC,MAAM,CAAC,IAAIC,4BAAqB,CAAC,KAAK,YAAYC,qBAAiB,GAAG,cAAc,GAAG,mBAAmB,CAAC,CAAC;kBAE1I,OAAO,CAAC,MAAM,CAAC,IAAID,4BAAqB,CAAC,mBAAmB,CAAC,CAAC;QACpE;;IApDI,YAAY,GAAA,cAAA,GAAAE,gBAAA,CAAA;AADjB,QAAAC,iBAAU,EAAE;+CAWmBL,cAAS;YACfM,cAAU,CAAA;AAX9B,KAAA,EAAA,YAAY,CAqDjB;IAED,CAACN,cAAS,EAAEM,cAAU,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAKC,aAAM,CAAC,KAAK,CAAC,CAAC,YAAY,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAEhG,IAAA,OAAO,YAAY;AACrB;;;;"}
1
+ {"version":3,"file":"create-jwt-auth-guard.cjs","sources":["../../../../libs/nest-pack/src/auth/create-jwt-auth-guard.ts"],"sourcesContent":[null],"names":["createParamDecorator","Reflector","SetMetadata","UnauthorizedException","__decorate","Injectable","ModuleRef","Inject"],"mappings":";;;;;;AAaA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDG;AACG,SAAU,kBAAkB,CAChC,OAAA,GAAwC,EAAE,EAAA;;IAE1C,MAAM,EACJ,cAAc,GAAG,cAAc,EAC/B,mBAAmB,GAAG,cAAc,EACpC,OAAO,EACP,QAAQ,EACR,aAAa,EACb,YAAY,GAAG,MAAM,EACrB,QAAQ,GAAG,MAAM,GAClB,GAAG,OAAO;AACX,IAAA,MAAM,SAAS,GAAG,MAAM,CAAC,uBAAuB,CAAC;IAEjD,IAAI,QAAQ,KAAK,SAAS,IAAI,aAAa,KAAK,SAAS,EAAE;AACzD,QAAA,MAAM,IAAI,KAAK,CAAC,uHAAuH,CAAC;IAC1I;IAEA,IACM,YAAY,GADlB,MACM,YAAY,CAAA;;AAwBG,QAAA,SAAA;QAvBnB,OAAgB,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CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAC9H;AAEP,kBAAE,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC,IAAIA,4BAAqB,CAAC,mBAAmB,CAAC,CAAC;QAChF;;IArFI,YAAY,GAAA,cAAA,GAAAC,gBAAA,CAAA;AADjB,QAAAC,iBAAU,EAAE;+CAyBmBJ,cAAS,EAAA,MAAA,CAAA;AAxBnC,KAAA,EAAA,YAAY,CAsFjB;AAED,IAAA,CAACA,cAAS,EAAE,QAAQ,IAAIK,cAAS,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAKC,aAAM,CAAC,KAAK,CAAC,CAAC,YAAY,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAE3G,IAAA,OAAO,YAAY;AACrB;;;;"}
@@ -8,14 +8,16 @@ import '@nestjs/jwt';
8
8
  *
9
9
  * Creates a guard that requires a valid JWT on every route, for use as the global `APP_GUARD`:
10
10
  *
11
- * - routes and controllers marked with `@Guard.public()` pass without a token
11
+ * - routes and controllers marked with `@Guard.public()` pass without a token; with `publicRoutes: 'optional'` a valid
12
+ * token still gives them the user, and a missing, invalid or expired one passes as anonymous
12
13
  * - a missing, malformed or invalid token (bad signature, wrong audience, …): **401** `unauthorizedMessage`
13
- * - an expired token: **401** `expiredMessage` (`'TokenExpired'`), so clients can tell "renew and retry" from "sign in"
14
+ * - an expired token (see `isExpired`): **401** `expiredMessage` (`'TokenExpired'`), so clients can tell "renew and retry" from "sign in"
14
15
  * - otherwise the payload is written to `request.user` (see `property`) and is available through `@Guard.user()`
15
16
  *
16
17
  * Tokens are verified with the `JwtService` of `@nestjs/jwt`: register `JwtModule` (with the secret or keys) in
17
- * the module that provides the guard. The token comes from the `Authorization: Bearer` header unless `extract`
18
- * reads it from elsewhere. HTTP only.
18
+ * the app. To verify otherwise (e.g. with a JWKS and `jose`), provide a {@link JwtAuthGuardVerifier} and pass its
19
+ * injection token as `verifier`; then `@nestjs/jwt` is not needed. The token comes from the `Authorization: Bearer`
20
+ * header unless `extract` reads it from elsewhere. HTTP only.
19
21
  *
20
22
  * * * *
21
23
  * Example:
@@ -47,8 +49,9 @@ import '@nestjs/jwt';
47
49
  *
48
50
  * Other guards and interceptors can skip public routes with `AuthGuard.isPublic(context)`.
49
51
  * * * *
50
- * @param options Messages, where the token comes from, verification options and where the payload goes
52
+ * @param options Messages, where the token comes from, how it is verified, public routes and where the payload goes
51
53
  * @returns An injectable guard class with `public()`, `isPublic()`, `user()` and `userOf()`
54
+ * @throws When `verifyOptions` come with a `verifier`, as only the `JwtService` reads them
52
55
  */
53
56
  declare function createJwtAuthGuard<Payload extends object, Request extends object = JwtAuthGuardRequest>(options?: JwtAuthGuardOptions<Request>): JwtAuthGuardType<Payload>;
54
57
 
@@ -8,14 +8,16 @@ import '@nestjs/jwt';
8
8
  *
9
9
  * Creates a guard that requires a valid JWT on every route, for use as the global `APP_GUARD`:
10
10
  *
11
- * - routes and controllers marked with `@Guard.public()` pass without a token
11
+ * - routes and controllers marked with `@Guard.public()` pass without a token; with `publicRoutes: 'optional'` a valid
12
+ * token still gives them the user, and a missing, invalid or expired one passes as anonymous
12
13
  * - a missing, malformed or invalid token (bad signature, wrong audience, …): **401** `unauthorizedMessage`
13
- * - an expired token: **401** `expiredMessage` (`'TokenExpired'`), so clients can tell "renew and retry" from "sign in"
14
+ * - an expired token (see `isExpired`): **401** `expiredMessage` (`'TokenExpired'`), so clients can tell "renew and retry" from "sign in"
14
15
  * - otherwise the payload is written to `request.user` (see `property`) and is available through `@Guard.user()`
15
16
  *
16
17
  * Tokens are verified with the `JwtService` of `@nestjs/jwt`: register `JwtModule` (with the secret or keys) in
17
- * the module that provides the guard. The token comes from the `Authorization: Bearer` header unless `extract`
18
- * reads it from elsewhere. HTTP only.
18
+ * the app. To verify otherwise (e.g. with a JWKS and `jose`), provide a {@link JwtAuthGuardVerifier} and pass its
19
+ * injection token as `verifier`; then `@nestjs/jwt` is not needed. The token comes from the `Authorization: Bearer`
20
+ * header unless `extract` reads it from elsewhere. HTTP only.
19
21
  *
20
22
  * * * *
21
23
  * Example:
@@ -47,8 +49,9 @@ import '@nestjs/jwt';
47
49
  *
48
50
  * Other guards and interceptors can skip public routes with `AuthGuard.isPublic(context)`.
49
51
  * * * *
50
- * @param options Messages, where the token comes from, verification options and where the payload goes
52
+ * @param options Messages, where the token comes from, how it is verified, public routes and where the payload goes
51
53
  * @returns An injectable guard class with `public()`, `isPublic()`, `user()` and `userOf()`
54
+ * @throws When `verifyOptions` come with a `verifier`, as only the `JwtService` reads them
52
55
  */
53
56
  declare function createJwtAuthGuard<Payload extends object, Request extends object = JwtAuthGuardRequest>(options?: JwtAuthGuardOptions<Request>): JwtAuthGuardType<Payload>;
54
57
 
@@ -1,21 +1,22 @@
1
1
  import { __decorate, __metadata } from 'tslib';
2
2
  import { createParamDecorator, SetMetadata, UnauthorizedException, Injectable, Inject } from '@nestjs/common';
3
- import { Reflector } from '@nestjs/core';
4
- import { TokenExpiredError, JwtService } from '@nestjs/jwt';
3
+ import { Reflector, ModuleRef } from '@nestjs/core';
5
4
 
6
5
  /**
7
6
  * #### Create JWT Auth Guard
8
7
  *
9
8
  * Creates a guard that requires a valid JWT on every route, for use as the global `APP_GUARD`:
10
9
  *
11
- * - routes and controllers marked with `@Guard.public()` pass without a token
10
+ * - routes and controllers marked with `@Guard.public()` pass without a token; with `publicRoutes: 'optional'` a valid
11
+ * token still gives them the user, and a missing, invalid or expired one passes as anonymous
12
12
  * - a missing, malformed or invalid token (bad signature, wrong audience, …): **401** `unauthorizedMessage`
13
- * - an expired token: **401** `expiredMessage` (`'TokenExpired'`), so clients can tell "renew and retry" from "sign in"
13
+ * - an expired token (see `isExpired`): **401** `expiredMessage` (`'TokenExpired'`), so clients can tell "renew and retry" from "sign in"
14
14
  * - otherwise the payload is written to `request.user` (see `property`) and is available through `@Guard.user()`
15
15
  *
16
16
  * Tokens are verified with the `JwtService` of `@nestjs/jwt`: register `JwtModule` (with the secret or keys) in
17
- * the module that provides the guard. The token comes from the `Authorization: Bearer` header unless `extract`
18
- * reads it from elsewhere. HTTP only.
17
+ * the app. To verify otherwise (e.g. with a JWKS and `jose`), provide a {@link JwtAuthGuardVerifier} and pass its
18
+ * injection token as `verifier`; then `@nestjs/jwt` is not needed. The token comes from the `Authorization: Bearer`
19
+ * header unless `extract` reads it from elsewhere. HTTP only.
19
20
  *
20
21
  * * * *
21
22
  * Example:
@@ -47,28 +48,41 @@ import { TokenExpiredError, JwtService } from '@nestjs/jwt';
47
48
  *
48
49
  * Other guards and interceptors can skip public routes with `AuthGuard.isPublic(context)`.
49
50
  * * * *
50
- * @param options Messages, where the token comes from, verification options and where the payload goes
51
+ * @param options Messages, where the token comes from, how it is verified, public routes and where the payload goes
51
52
  * @returns An injectable guard class with `public()`, `isPublic()`, `user()` and `userOf()`
53
+ * @throws When `verifyOptions` come with a `verifier`, as only the `JwtService` reads them
52
54
  */
53
55
  function createJwtAuthGuard(options = {}) {
54
56
  var JwtAuthGuard_1;
55
- const { expiredMessage = 'TokenExpired', unauthorizedMessage = 'Unauthorized', extract, verifyOptions, property = 'user', } = options;
57
+ const { expiredMessage = 'TokenExpired', unauthorizedMessage = 'Unauthorized', extract, verifier, verifyOptions, publicRoutes = 'skip', property = 'user', } = options;
56
58
  const publicKey = Symbol('jwt-auth-guard:public');
59
+ if (verifier !== undefined && verifyOptions !== undefined) {
60
+ throw new Error('createJwtAuthGuard: `verifyOptions` are options of the JwtService of @nestjs/jwt; pass them to the `verifier` instead');
61
+ }
57
62
  let JwtAuthGuard = class JwtAuthGuard {
58
63
  static { JwtAuthGuard_1 = this; }
59
64
  reflector;
60
- jwt;
61
65
  static user = createParamDecorator((_data, context) => JwtAuthGuard_1.userOf(context.switchToHttp().getRequest()));
66
+ /** Reads `public()` markers when `isPublic()` gets no reflector; `Reflector` needs no dependencies */
67
+ static defaultReflector = new Reflector();
68
+ /** Whether a verification error means an expired token: jsonwebtoken's `TokenExpiredError` or jose's `JWTExpired` */
69
+ static isExpired = options.isExpired ??
70
+ ((error) => typeof error === 'object' &&
71
+ error !== null &&
72
+ (error.name === 'TokenExpiredError' || error.code === 'ERR_JWT_EXPIRED'));
73
+ /** The verifier of the requests */
74
+ verifier;
62
75
  /**
63
76
  * @param reflector Reads `public()` markers
64
- * @param jwt Verifies tokens
77
+ * @param source The `verifier`, or without one the `ModuleRef` the `JwtService` is resolved from
65
78
  */
66
- constructor(reflector, jwt) {
79
+ constructor(reflector, source) {
67
80
  this.reflector = reflector;
68
- this.jwt = jwt;
81
+ this.verifier =
82
+ verifier === undefined
83
+ ? () => JwtAuthGuard_1.jwtServiceVerifier(source)
84
+ : () => Promise.resolve(source);
69
85
  }
70
- /** Reads `public()` markers when `isPublic()` gets no reflector; `Reflector` needs no dependencies */
71
- static defaultReflector = new Reflector();
72
86
  static public() {
73
87
  return SetMetadata(publicKey, true);
74
88
  }
@@ -85,23 +99,35 @@ function createJwtAuthGuard(options = {}) {
85
99
  const header = headers['authorization'];
86
100
  return (typeof header === 'string' ? /^Bearer +(\S+)$/i.exec(header) : null)?.[1];
87
101
  }
102
+ /**
103
+ * Verifies with the `JwtService` of `@nestjs/jwt`, imported only here so apps with a `verifier` need not install it.
104
+ * Looked up in the whole app, as the guard's module only imports `JwtModule`.
105
+ */
106
+ static jwtServiceVerifier(moduleRef) {
107
+ return import('@nestjs/jwt')
108
+ .then(({ JwtService }) => moduleRef.get(JwtService, { strict: false }))
109
+ .then(jwt => ({ verify: token => jwt.verifyAsync(token, verifyOptions) }));
110
+ }
88
111
  canActivate(context) {
89
- if (JwtAuthGuard_1.isPublic(context, this.reflector)) {
90
- return true;
91
- }
92
112
  const request = context.switchToHttp().getRequest();
93
- const token = extract ? extract(request) : JwtAuthGuard_1.bearerToken(request);
113
+ const optional = JwtAuthGuard_1.isPublic(context, this.reflector);
114
+ const token = optional && publicRoutes === 'skip'
115
+ ? undefined
116
+ : extract
117
+ ? extract(request)
118
+ : JwtAuthGuard_1.bearerToken(request);
94
119
  return token
95
- ? this.jwt.verifyAsync(token, verifyOptions).then(payload => (Object.assign(request, { [property]: payload }), true), (error) => Promise.reject(new UnauthorizedException(error instanceof TokenExpiredError ? expiredMessage : unauthorizedMessage)))
96
- : Promise.reject(new UnauthorizedException(unauthorizedMessage));
120
+ ? this.verifier().then(verifier => Promise.resolve(token)
121
+ .then(value => verifier.verify(value, request))
122
+ .then(payload => (Object.assign(request, { [property]: payload }), true), (error) => optional || Promise.reject(new UnauthorizedException(JwtAuthGuard_1.isExpired(error) ? expiredMessage : unauthorizedMessage))))
123
+ : optional || Promise.reject(new UnauthorizedException(unauthorizedMessage));
97
124
  }
98
125
  };
99
126
  JwtAuthGuard = JwtAuthGuard_1 = __decorate([
100
127
  Injectable(),
101
- __metadata("design:paramtypes", [Reflector,
102
- JwtService])
128
+ __metadata("design:paramtypes", [Reflector, Object])
103
129
  ], JwtAuthGuard);
104
- [Reflector, JwtService].forEach((token, index) => Inject(token)(JwtAuthGuard, undefined, index));
130
+ [Reflector, verifier ?? ModuleRef].forEach((token, index) => Inject(token)(JwtAuthGuard, undefined, index));
105
131
  return JwtAuthGuard;
106
132
  }
107
133
 
@@ -1 +1 @@
1
- {"version":3,"file":"create-jwt-auth-guard.js","sources":["../../../../libs/nest-pack/src/auth/create-jwt-auth-guard.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CG;AACG,SAAU,kBAAkB,CAChC,OAAA,GAAwC,EAAE,EAAA;;AAE1C,IAAA,MAAM,EACJ,cAAc,GAAG,cAAc,EAC/B,mBAAmB,GAAG,cAAc,EACpC,OAAO,EACP,aAAa,EACb,QAAQ,GAAG,MAAM,GAClB,GAAG,OAAO;AACX,IAAA,MAAM,SAAS,GAAG,MAAM,CAAC,uBAAuB,CAAC;IAEjD,IACM,YAAY,GADlB,MACM,YAAY,CAAA;;AAUG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AAI,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC;qBAC7C,IAAI,CACH,OAAO,KAAK,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC,QAAQ,GAAG,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC,EAClE,CAAC,KAAc,KACb,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC,IAAI,qBAAqB,CAAC,cAAY,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAC9H;AAEP,kBAAE,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC,IAAI,qBAAqB,CAAC,mBAAmB,CAAC,CAAC;QAChF;;IArFI,YAAY,GAAA,cAAA,GAAA,UAAA,CAAA;AADjB,QAAA,UAAU,EAAE;yCAyBmB,SAAS,EAAA,MAAA,CAAA;AAxBnC,KAAA,EAAA,YAAY,CAsFjB;AAED,IAAA,CAAC,SAAS,EAAE,QAAQ,IAAI,SAAS,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,CAAC,YAAY,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAE3G,IAAA,OAAO,YAAY;AACrB;;;;"}
package/auth/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- export { JwtAuthGuardOptions, JwtAuthGuardRequest, JwtAuthGuardType } from './jwt-auth-guard-options.cjs';
1
+ export { JwtAuthGuardBaseOptions, JwtAuthGuardCustomVerifierOptions, JwtAuthGuardJwtServiceOptions, JwtAuthGuardOptions, JwtAuthGuardPublicRoutes, JwtAuthGuardRequest, JwtAuthGuardType, JwtAuthGuardVerifier } from './jwt-auth-guard-options.cjs';
2
2
  export { createJwtAuthGuard } from './create-jwt-auth-guard.cjs';
3
3
  import '@nestjs/common';
4
4
  import '@nestjs/core';
package/auth/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { JwtAuthGuardOptions, JwtAuthGuardRequest, JwtAuthGuardType } from './jwt-auth-guard-options.js';
1
+ export { JwtAuthGuardBaseOptions, JwtAuthGuardCustomVerifierOptions, JwtAuthGuardJwtServiceOptions, JwtAuthGuardOptions, JwtAuthGuardPublicRoutes, JwtAuthGuardRequest, JwtAuthGuardType, JwtAuthGuardVerifier } from './jwt-auth-guard-options.js';
2
2
  export { createJwtAuthGuard } from './create-jwt-auth-guard.js';
3
3
  import '@nestjs/common';
4
4
  import '@nestjs/core';
@@ -1,4 +1,4 @@
1
- import { Type, CanActivate, ExecutionContext } from '@nestjs/common';
1
+ import { InjectionToken, Type, CanActivate, ExecutionContext } from '@nestjs/common';
2
2
  import { Reflector } from '@nestjs/core';
3
3
  import { JwtVerifyOptions } from '@nestjs/jwt';
4
4
 
@@ -9,9 +9,29 @@ interface JwtAuthGuardRequest {
9
9
  headers: Record<string, string | string[] | undefined>;
10
10
  }
11
11
  /**
12
- * Options of {@link createJwtAuthGuard}
12
+ * Verifies tokens for a {@link createJwtAuthGuard} in place of the `JwtService` of `@nestjs/jwt`,
13
+ * e.g. with `jwtVerify` and a JWKS of `jose`. Provide it under the token given as `verifier`.
13
14
  */
14
- interface JwtAuthGuardOptions<Request extends object = JwtAuthGuardRequest> {
15
+ interface JwtAuthGuardVerifier<Payload extends object = object, Request extends object = JwtAuthGuardRequest> {
16
+ /**
17
+ * The payload of a valid token; throws (or rejects) for an invalid or expired one
18
+ *
19
+ * @param token The token `extract` read
20
+ * @param request The HTTP request the token came with
21
+ */
22
+ verify(token: string, request: Request): Payload | Promise<Payload>;
23
+ }
24
+ /**
25
+ * How a {@link createJwtAuthGuard} treats routes marked with `public()`:
26
+ *
27
+ * - `'skip'`: the token is not read, the route has no user
28
+ * - `'optional'`: a valid token gives the route its user; a missing, invalid or expired token passes as anonymous
29
+ */
30
+ type JwtAuthGuardPublicRoutes = 'skip' | 'optional';
31
+ /**
32
+ * The options of {@link createJwtAuthGuard} besides the verification
33
+ */
34
+ interface JwtAuthGuardBaseOptions<Request extends object = JwtAuthGuardRequest> {
15
35
  /**
16
36
  * The message of the 401 answer for an expired token, so clients can renew the token and retry
17
37
  * (e.g. `ApiAuth.expired` of `@telperion/ng-pack/http`)
@@ -32,9 +52,17 @@ interface JwtAuthGuardOptions<Request extends object = JwtAuthGuardRequest> {
32
52
  */
33
53
  extract?: (request: Request) => string | null | undefined;
34
54
  /**
35
- * Options of `JwtService.verifyAsync`, e.g. the `audience`, `issuer` or a `secret` other than the `JwtModule`'s
55
+ * Whether a verification error means an expired token, which answers `expiredMessage`
56
+ *
57
+ * @default recognizes the errors of jsonwebtoken (`@nestjs/jwt`, `name === 'TokenExpiredError'`) and jose (`code === 'ERR_JWT_EXPIRED'`)
36
58
  */
37
- verifyOptions?: JwtVerifyOptions;
59
+ isExpired?: (error: unknown) => boolean;
60
+ /**
61
+ * How routes marked with `public()` treat tokens, see {@link JwtAuthGuardPublicRoutes}
62
+ *
63
+ * @default 'skip'
64
+ */
65
+ publicRoutes?: JwtAuthGuardPublicRoutes;
38
66
  /**
39
67
  * The request property the verified payload is written to
40
68
  *
@@ -42,12 +70,40 @@ interface JwtAuthGuardOptions<Request extends object = JwtAuthGuardRequest> {
42
70
  */
43
71
  property?: string;
44
72
  }
73
+ /**
74
+ * Verification with the `JwtService` of `@nestjs/jwt`
75
+ */
76
+ interface JwtAuthGuardJwtServiceOptions {
77
+ verifier?: undefined;
78
+ /**
79
+ * Options of `JwtService.verifyAsync`, e.g. the `audience`, `issuer` or a `secret` other than the `JwtModule`'s
80
+ */
81
+ verifyOptions?: JwtVerifyOptions;
82
+ }
83
+ /**
84
+ * Verification with a verifier of its own
85
+ */
86
+ interface JwtAuthGuardCustomVerifierOptions {
87
+ /**
88
+ * The injection token of a {@link JwtAuthGuardVerifier}, e.g. one verifying with a JWKS. With it, the guard does not use `@nestjs/jwt`.
89
+ */
90
+ verifier: InjectionToken;
91
+ /**
92
+ * Only for the `JwtService`; pass these options to the verifier itself
93
+ */
94
+ verifyOptions?: never;
95
+ }
96
+ /**
97
+ * Options of {@link createJwtAuthGuard}: the `JwtService` of `@nestjs/jwt` verifies the tokens, or the `verifier`
98
+ */
99
+ type JwtAuthGuardOptions<Request extends object = JwtAuthGuardRequest> = JwtAuthGuardBaseOptions<Request> & (JwtAuthGuardJwtServiceOptions | JwtAuthGuardCustomVerifierOptions);
45
100
  /**
46
101
  * The guard class {@link createJwtAuthGuard} returns, with its decorators
47
102
  */
48
103
  interface JwtAuthGuardType<Payload extends object> extends Type<CanActivate> {
49
104
  /**
50
- * Route or controller decorator: the route needs no token. A method's setting replaces its controller's.
105
+ * Route or controller decorator: the route needs no token (see `publicRoutes` for reading one anyway).
106
+ * A method's setting replaces its controller's.
51
107
  */
52
108
  public(): MethodDecorator & ClassDecorator;
53
109
  /**
@@ -59,13 +115,14 @@ interface JwtAuthGuardType<Payload extends object> extends Type<CanActivate> {
59
115
  */
60
116
  isPublic(context: ExecutionContext, reflector?: Reflector): boolean;
61
117
  /**
62
- * Parameter decorator: the verified token payload, `undefined` on public routes
118
+ * Parameter decorator: the verified token payload; on public routes `undefined`, or with `publicRoutes: 'optional'`
119
+ * the payload of a valid token
63
120
  */
64
121
  user(...pipes: unknown[]): ParameterDecorator;
65
122
  /**
66
- * The verified payload of a request, `undefined` before the guard ran or on public routes
123
+ * The verified payload of a request, `undefined` before the guard ran or on public routes without a valid token
67
124
  */
68
125
  userOf(request: object): Payload | undefined;
69
126
  }
70
127
 
71
- export type { JwtAuthGuardOptions, JwtAuthGuardRequest, JwtAuthGuardType };
128
+ export type { JwtAuthGuardBaseOptions, JwtAuthGuardCustomVerifierOptions, JwtAuthGuardJwtServiceOptions, JwtAuthGuardOptions, JwtAuthGuardPublicRoutes, JwtAuthGuardRequest, JwtAuthGuardType, JwtAuthGuardVerifier };
@@ -1,4 +1,4 @@
1
- import { Type, CanActivate, ExecutionContext } from '@nestjs/common';
1
+ import { InjectionToken, Type, CanActivate, ExecutionContext } from '@nestjs/common';
2
2
  import { Reflector } from '@nestjs/core';
3
3
  import { JwtVerifyOptions } from '@nestjs/jwt';
4
4
 
@@ -9,9 +9,29 @@ interface JwtAuthGuardRequest {
9
9
  headers: Record<string, string | string[] | undefined>;
10
10
  }
11
11
  /**
12
- * Options of {@link createJwtAuthGuard}
12
+ * Verifies tokens for a {@link createJwtAuthGuard} in place of the `JwtService` of `@nestjs/jwt`,
13
+ * e.g. with `jwtVerify` and a JWKS of `jose`. Provide it under the token given as `verifier`.
13
14
  */
14
- interface JwtAuthGuardOptions<Request extends object = JwtAuthGuardRequest> {
15
+ interface JwtAuthGuardVerifier<Payload extends object = object, Request extends object = JwtAuthGuardRequest> {
16
+ /**
17
+ * The payload of a valid token; throws (or rejects) for an invalid or expired one
18
+ *
19
+ * @param token The token `extract` read
20
+ * @param request The HTTP request the token came with
21
+ */
22
+ verify(token: string, request: Request): Payload | Promise<Payload>;
23
+ }
24
+ /**
25
+ * How a {@link createJwtAuthGuard} treats routes marked with `public()`:
26
+ *
27
+ * - `'skip'`: the token is not read, the route has no user
28
+ * - `'optional'`: a valid token gives the route its user; a missing, invalid or expired token passes as anonymous
29
+ */
30
+ type JwtAuthGuardPublicRoutes = 'skip' | 'optional';
31
+ /**
32
+ * The options of {@link createJwtAuthGuard} besides the verification
33
+ */
34
+ interface JwtAuthGuardBaseOptions<Request extends object = JwtAuthGuardRequest> {
15
35
  /**
16
36
  * The message of the 401 answer for an expired token, so clients can renew the token and retry
17
37
  * (e.g. `ApiAuth.expired` of `@telperion/ng-pack/http`)
@@ -32,9 +52,17 @@ interface JwtAuthGuardOptions<Request extends object = JwtAuthGuardRequest> {
32
52
  */
33
53
  extract?: (request: Request) => string | null | undefined;
34
54
  /**
35
- * Options of `JwtService.verifyAsync`, e.g. the `audience`, `issuer` or a `secret` other than the `JwtModule`'s
55
+ * Whether a verification error means an expired token, which answers `expiredMessage`
56
+ *
57
+ * @default recognizes the errors of jsonwebtoken (`@nestjs/jwt`, `name === 'TokenExpiredError'`) and jose (`code === 'ERR_JWT_EXPIRED'`)
36
58
  */
37
- verifyOptions?: JwtVerifyOptions;
59
+ isExpired?: (error: unknown) => boolean;
60
+ /**
61
+ * How routes marked with `public()` treat tokens, see {@link JwtAuthGuardPublicRoutes}
62
+ *
63
+ * @default 'skip'
64
+ */
65
+ publicRoutes?: JwtAuthGuardPublicRoutes;
38
66
  /**
39
67
  * The request property the verified payload is written to
40
68
  *
@@ -42,12 +70,40 @@ interface JwtAuthGuardOptions<Request extends object = JwtAuthGuardRequest> {
42
70
  */
43
71
  property?: string;
44
72
  }
73
+ /**
74
+ * Verification with the `JwtService` of `@nestjs/jwt`
75
+ */
76
+ interface JwtAuthGuardJwtServiceOptions {
77
+ verifier?: undefined;
78
+ /**
79
+ * Options of `JwtService.verifyAsync`, e.g. the `audience`, `issuer` or a `secret` other than the `JwtModule`'s
80
+ */
81
+ verifyOptions?: JwtVerifyOptions;
82
+ }
83
+ /**
84
+ * Verification with a verifier of its own
85
+ */
86
+ interface JwtAuthGuardCustomVerifierOptions {
87
+ /**
88
+ * The injection token of a {@link JwtAuthGuardVerifier}, e.g. one verifying with a JWKS. With it, the guard does not use `@nestjs/jwt`.
89
+ */
90
+ verifier: InjectionToken;
91
+ /**
92
+ * Only for the `JwtService`; pass these options to the verifier itself
93
+ */
94
+ verifyOptions?: never;
95
+ }
96
+ /**
97
+ * Options of {@link createJwtAuthGuard}: the `JwtService` of `@nestjs/jwt` verifies the tokens, or the `verifier`
98
+ */
99
+ type JwtAuthGuardOptions<Request extends object = JwtAuthGuardRequest> = JwtAuthGuardBaseOptions<Request> & (JwtAuthGuardJwtServiceOptions | JwtAuthGuardCustomVerifierOptions);
45
100
  /**
46
101
  * The guard class {@link createJwtAuthGuard} returns, with its decorators
47
102
  */
48
103
  interface JwtAuthGuardType<Payload extends object> extends Type<CanActivate> {
49
104
  /**
50
- * Route or controller decorator: the route needs no token. A method's setting replaces its controller's.
105
+ * Route or controller decorator: the route needs no token (see `publicRoutes` for reading one anyway).
106
+ * A method's setting replaces its controller's.
51
107
  */
52
108
  public(): MethodDecorator & ClassDecorator;
53
109
  /**
@@ -59,13 +115,14 @@ interface JwtAuthGuardType<Payload extends object> extends Type<CanActivate> {
59
115
  */
60
116
  isPublic(context: ExecutionContext, reflector?: Reflector): boolean;
61
117
  /**
62
- * Parameter decorator: the verified token payload, `undefined` on public routes
118
+ * Parameter decorator: the verified token payload; on public routes `undefined`, or with `publicRoutes: 'optional'`
119
+ * the payload of a valid token
63
120
  */
64
121
  user(...pipes: unknown[]): ParameterDecorator;
65
122
  /**
66
- * The verified payload of a request, `undefined` before the guard ran or on public routes
123
+ * The verified payload of a request, `undefined` before the guard ran or on public routes without a valid token
67
124
  */
68
125
  userOf(request: object): Payload | undefined;
69
126
  }
70
127
 
71
- export type { JwtAuthGuardOptions, JwtAuthGuardRequest, JwtAuthGuardType };
128
+ export type { JwtAuthGuardBaseOptions, JwtAuthGuardCustomVerifierOptions, JwtAuthGuardJwtServiceOptions, JwtAuthGuardOptions, JwtAuthGuardPublicRoutes, JwtAuthGuardRequest, JwtAuthGuardType, JwtAuthGuardVerifier };