@telperion/nest-pack 1.1.0 → 1.3.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.
@@ -40,6 +40,36 @@
40
40
  "dcts": "access/index.d.cts"
41
41
  }
42
42
  },
43
+ {
44
+ "name": "auth/create-jwt-auth-guard",
45
+ "sourcePath": "src/auth/create-jwt-auth-guard.ts",
46
+ "outputs": {
47
+ "esm": "auth/create-jwt-auth-guard.js",
48
+ "cjs": "auth/create-jwt-auth-guard.cjs",
49
+ "dts": "auth/create-jwt-auth-guard.d.ts",
50
+ "dcts": "auth/create-jwt-auth-guard.d.cts"
51
+ }
52
+ },
53
+ {
54
+ "name": "auth/index",
55
+ "sourcePath": "src/auth/index.ts",
56
+ "outputs": {
57
+ "esm": "auth/index.js",
58
+ "cjs": "auth/index.cjs",
59
+ "dts": "auth/index.d.ts",
60
+ "dcts": "auth/index.d.cts"
61
+ }
62
+ },
63
+ {
64
+ "name": "auth/jwt-auth-guard-options",
65
+ "sourcePath": "src/auth/jwt-auth-guard-options.ts",
66
+ "outputs": {
67
+ "esm": "auth/jwt-auth-guard-options.js",
68
+ "cjs": "auth/jwt-auth-guard-options.cjs",
69
+ "dts": "auth/jwt-auth-guard-options.d.ts",
70
+ "dcts": "auth/jwt-auth-guard-options.d.cts"
71
+ }
72
+ },
43
73
  {
44
74
  "name": "index",
45
75
  "sourcePath": "src/index.ts",
@@ -102,5 +132,5 @@
102
132
  }
103
133
  }
104
134
  ],
105
- "generatedAt": "2026-12-01T11:22:52.238Z"
135
+ "generatedAt": "2026-12-02T11:03:41.174Z"
106
136
  }
package/README.md CHANGED
@@ -21,10 +21,70 @@ Requires `@nestjs/common` and `@nestjs/core` (11 or 12).
21
21
  | --- | --- | --- |
22
22
  | `@telperion/nest-pack` | `createAccessGuard` | |
23
23
  | `@telperion/nest-pack/access` | `createAccessGuard` | |
24
+ | `@telperion/nest-pack/auth` | `createJwtAuthGuard` | `@nestjs/jwt` 11 or 12 (optional peer dependency) |
24
25
  | `@telperion/nest-pack/validation` | `Trim` | `class-transformer` (optional peer dependency); usually with `class-validator` |
25
26
  | `@telperion/nest-pack/pagination` | `PageQuery`, `Page` | `class-transformer` and `class-validator` (optional peer dependencies) |
26
27
 
27
- The root entry point does not include `validation` or `pagination`, so projects without class-transformer or class-validator are not affected.
28
+ The root entry point does not include `auth`, `validation` or `pagination`, so projects without `@nestjs/jwt`, class-transformer or class-validator are not affected.
29
+
30
+ ## Auth
31
+
32
+ ### Create JWT Auth Guard
33
+
34
+ Creates a guard that requires a valid JWT on every route, for use as the global `APP_GUARD`. Tokens are verified with the `JwtService` of `@nestjs/jwt`, so register `JwtModule` next to the guard.
35
+
36
+ ```typescript
37
+ import { createJwtAuthGuard } from '@telperion/nest-pack/auth';
38
+ import { APP_GUARD } from '@nestjs/core';
39
+ import { JwtModule } from '@nestjs/jwt';
40
+
41
+ export const AuthGuard = createJwtAuthGuard<TokenPayload>();
42
+
43
+ @Module({
44
+ imports: [JwtModule.register({ secret: process.env.JWT_SECRET })],
45
+ providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
46
+ })
47
+ export class AppModule {}
48
+
49
+ @Controller('huddles')
50
+ export class HuddlesController {
51
+ @Get()
52
+ list(@AuthGuard.user() user: TokenPayload) {}
53
+
54
+ @Get('health')
55
+ @AuthGuard.public() // no token needed; also works on a controller
56
+ health() {}
57
+ }
58
+ ```
59
+
60
+ | Request | Answer |
61
+ | --- | --- |
62
+ | route or controller with `@AuthGuard.public()` | passes, without verifying any token |
63
+ | no token, another scheme, invalid signature or claims | **401** `unauthorizedMessage` (`'Unauthorized'`) |
64
+ | expired token | **401** `expiredMessage` (`'TokenExpired'`), so clients can renew the token and retry |
65
+ | valid token | passes; the payload is on `request.user`, `@AuthGuard.user()` and `AuthGuard.userOf(request)` |
66
+
67
+ Markers are per guard: `AuthGuard.isPublic()` reads only the `public()` markers of `AuthGuard`.
68
+
69
+ **Options** (all optional):
70
+
71
+ - `extract(request)` — reads the token; default: `Authorization: Bearer <token>` (scheme case-insensitive)
72
+ - `verifyOptions` — options of `JwtService.verifyAsync`, e.g. `audience`, `issuer`
73
+ - `expiredMessage`, `unauthorizedMessage` — messages of the 401 answers
74
+ - `property` — the request property the payload is written to (default `'user'`, where Passport and most code expect it)
75
+
76
+ **Public routes in other guards and interceptors**: `AuthGuard.isPublic(context)` tells whether the route is marked with `@AuthGuard.public()` (a method's setting replaces its controller's), so throttling, auditing or user-resolving code can skip public routes without knowing the metadata key. Pass the injected `Reflector` as the second argument, or leave it out to use one of the guard's own.
77
+
78
+ ```typescript
79
+ @Injectable()
80
+ export class CurrentUserInterceptor implements NestInterceptor {
81
+ intercept(context: ExecutionContext, next: CallHandler) {
82
+ return AuthGuard.isPublic(context) ? next.handle() : this.users.resolve(context).pipe(switchMap(() => next.handle()));
83
+ }
84
+ }
85
+ ```
86
+
87
+ With `@telperion/ng-pack/http`, detect the expired answer in `ApiAuth.expired`: `error => error.status === 401 && error.error?.message === 'TokenExpired'`.
28
88
 
29
89
  ## Access
30
90
 
@@ -0,0 +1,111 @@
1
+ 'use strict';
2
+
3
+ var tslib = require('tslib');
4
+ var common = require('@nestjs/common');
5
+ var core = require('@nestjs/core');
6
+ var jwt = require('@nestjs/jwt');
7
+
8
+ /**
9
+ * #### Create JWT Auth Guard
10
+ *
11
+ * Creates a guard that requires a valid JWT on every route, for use as the global `APP_GUARD`:
12
+ *
13
+ * - routes and controllers marked with `@Guard.public()` pass without a token
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"
16
+ * - otherwise the payload is written to `request.user` (see `property`) and is available through `@Guard.user()`
17
+ *
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.
21
+ *
22
+ * * * *
23
+ * Example:
24
+ * ```typescript
25
+ * import { createJwtAuthGuard } from '@telperion/nest-pack/auth';
26
+ * import { APP_GUARD } from '@nestjs/core';
27
+ * import { JwtModule } from '@nestjs/jwt';
28
+ *
29
+ * export const AuthGuard = createJwtAuthGuard<TokenPayload>();
30
+ *
31
+ * @Module({
32
+ * imports: [JwtModule.register({ secret: process.env.JWT_SECRET })],
33
+ * providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
34
+ * })
35
+ * export class AppModule {}
36
+ *
37
+ * @Controller('huddles')
38
+ * export class HuddlesController {
39
+ * @Get()
40
+ * list(@AuthGuard.user() user: TokenPayload) {}
41
+ *
42
+ * @Get('health')
43
+ * @AuthGuard.public()
44
+ * health() {}
45
+ * }
46
+ * ```
47
+ *
48
+ * To give the guard a class name of its own, extend it: `@Injectable() export class AuthGuard extends createJwtAuthGuard<TokenPayload>() {}`.
49
+ *
50
+ * Other guards and interceptors can skip public routes with `AuthGuard.isPublic(context)`.
51
+ * * * *
52
+ * @param options Messages, where the token comes from, verification options and where the payload goes
53
+ * @returns An injectable guard class with `public()`, `isPublic()`, `user()` and `userOf()`
54
+ */
55
+ function createJwtAuthGuard(options = {}) {
56
+ var JwtAuthGuard_1;
57
+ const { expiredMessage = 'TokenExpired', unauthorizedMessage = 'Unauthorized', extract, verifyOptions, property = 'user', } = options;
58
+ const publicKey = Symbol('jwt-auth-guard:public');
59
+ let JwtAuthGuard = class JwtAuthGuard {
60
+ static { JwtAuthGuard_1 = this; }
61
+ reflector;
62
+ jwt;
63
+ static user = common.createParamDecorator((_data, context) => JwtAuthGuard_1.userOf(context.switchToHttp().getRequest()));
64
+ /**
65
+ * @param reflector Reads `public()` markers
66
+ * @param jwt Verifies tokens
67
+ */
68
+ constructor(reflector, jwt) {
69
+ this.reflector = reflector;
70
+ this.jwt = jwt;
71
+ }
72
+ /** Reads `public()` markers when `isPublic()` gets no reflector; `Reflector` needs no dependencies */
73
+ static defaultReflector = new core.Reflector();
74
+ static public() {
75
+ return common.SetMetadata(publicKey, true);
76
+ }
77
+ static isPublic(context, reflector = JwtAuthGuard_1.defaultReflector) {
78
+ return !!reflector.getAllAndOverride(publicKey, [context.getHandler(), context.getClass()]);
79
+ }
80
+ static userOf(request) {
81
+ return request[property];
82
+ }
83
+ /**
84
+ * The token of an `Authorization: Bearer <token>` header (the scheme is case-insensitive)
85
+ */
86
+ static bearerToken({ headers }) {
87
+ const header = headers['authorization'];
88
+ return (typeof header === 'string' ? /^Bearer +(\S+)$/i.exec(header) : null)?.[1];
89
+ }
90
+ canActivate(context) {
91
+ if (JwtAuthGuard_1.isPublic(context, this.reflector)) {
92
+ return true;
93
+ }
94
+ const request = context.switchToHttp().getRequest();
95
+ const token = extract ? extract(request) : JwtAuthGuard_1.bearerToken(request);
96
+ 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));
99
+ }
100
+ };
101
+ JwtAuthGuard = JwtAuthGuard_1 = tslib.__decorate([
102
+ common.Injectable(),
103
+ tslib.__metadata("design:paramtypes", [core.Reflector,
104
+ jwt.JwtService])
105
+ ], JwtAuthGuard);
106
+ [core.Reflector, jwt.JwtService].forEach((token, index) => common.Inject(token)(JwtAuthGuard, undefined, index));
107
+ return JwtAuthGuard;
108
+ }
109
+
110
+ exports.createJwtAuthGuard = createJwtAuthGuard;
111
+ //# sourceMappingURL=create-jwt-auth-guard.cjs.map
@@ -0,0 +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;;;;;;;;;;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@
1
+ import { JwtAuthGuardRequest, JwtAuthGuardOptions, JwtAuthGuardType } from './jwt-auth-guard-options.cjs';
2
+ import '@nestjs/common';
3
+ import '@nestjs/core';
4
+ import '@nestjs/jwt';
5
+
6
+ /**
7
+ * #### Create JWT Auth Guard
8
+ *
9
+ * Creates a guard that requires a valid JWT on every route, for use as the global `APP_GUARD`:
10
+ *
11
+ * - routes and controllers marked with `@Guard.public()` pass without a token
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"
14
+ * - otherwise the payload is written to `request.user` (see `property`) and is available through `@Guard.user()`
15
+ *
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.
19
+ *
20
+ * * * *
21
+ * Example:
22
+ * ```typescript
23
+ * import { createJwtAuthGuard } from '@telperion/nest-pack/auth';
24
+ * import { APP_GUARD } from '@nestjs/core';
25
+ * import { JwtModule } from '@nestjs/jwt';
26
+ *
27
+ * export const AuthGuard = createJwtAuthGuard<TokenPayload>();
28
+ *
29
+ * @Module({
30
+ * imports: [JwtModule.register({ secret: process.env.JWT_SECRET })],
31
+ * providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
32
+ * })
33
+ * export class AppModule {}
34
+ *
35
+ * @Controller('huddles')
36
+ * export class HuddlesController {
37
+ * @Get()
38
+ * list(@AuthGuard.user() user: TokenPayload) {}
39
+ *
40
+ * @Get('health')
41
+ * @AuthGuard.public()
42
+ * health() {}
43
+ * }
44
+ * ```
45
+ *
46
+ * To give the guard a class name of its own, extend it: `@Injectable() export class AuthGuard extends createJwtAuthGuard<TokenPayload>() {}`.
47
+ *
48
+ * Other guards and interceptors can skip public routes with `AuthGuard.isPublic(context)`.
49
+ * * * *
50
+ * @param options Messages, where the token comes from, verification options and where the payload goes
51
+ * @returns An injectable guard class with `public()`, `isPublic()`, `user()` and `userOf()`
52
+ */
53
+ declare function createJwtAuthGuard<Payload extends object, Request extends object = JwtAuthGuardRequest>(options?: JwtAuthGuardOptions<Request>): JwtAuthGuardType<Payload>;
54
+
55
+ export { createJwtAuthGuard };
@@ -0,0 +1,55 @@
1
+ import { JwtAuthGuardRequest, JwtAuthGuardOptions, JwtAuthGuardType } from './jwt-auth-guard-options.js';
2
+ import '@nestjs/common';
3
+ import '@nestjs/core';
4
+ import '@nestjs/jwt';
5
+
6
+ /**
7
+ * #### Create JWT Auth Guard
8
+ *
9
+ * Creates a guard that requires a valid JWT on every route, for use as the global `APP_GUARD`:
10
+ *
11
+ * - routes and controllers marked with `@Guard.public()` pass without a token
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"
14
+ * - otherwise the payload is written to `request.user` (see `property`) and is available through `@Guard.user()`
15
+ *
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.
19
+ *
20
+ * * * *
21
+ * Example:
22
+ * ```typescript
23
+ * import { createJwtAuthGuard } from '@telperion/nest-pack/auth';
24
+ * import { APP_GUARD } from '@nestjs/core';
25
+ * import { JwtModule } from '@nestjs/jwt';
26
+ *
27
+ * export const AuthGuard = createJwtAuthGuard<TokenPayload>();
28
+ *
29
+ * @Module({
30
+ * imports: [JwtModule.register({ secret: process.env.JWT_SECRET })],
31
+ * providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
32
+ * })
33
+ * export class AppModule {}
34
+ *
35
+ * @Controller('huddles')
36
+ * export class HuddlesController {
37
+ * @Get()
38
+ * list(@AuthGuard.user() user: TokenPayload) {}
39
+ *
40
+ * @Get('health')
41
+ * @AuthGuard.public()
42
+ * health() {}
43
+ * }
44
+ * ```
45
+ *
46
+ * To give the guard a class name of its own, extend it: `@Injectable() export class AuthGuard extends createJwtAuthGuard<TokenPayload>() {}`.
47
+ *
48
+ * Other guards and interceptors can skip public routes with `AuthGuard.isPublic(context)`.
49
+ * * * *
50
+ * @param options Messages, where the token comes from, verification options and where the payload goes
51
+ * @returns An injectable guard class with `public()`, `isPublic()`, `user()` and `userOf()`
52
+ */
53
+ declare function createJwtAuthGuard<Payload extends object, Request extends object = JwtAuthGuardRequest>(options?: JwtAuthGuardOptions<Request>): JwtAuthGuardType<Payload>;
54
+
55
+ export { createJwtAuthGuard };
@@ -0,0 +1,109 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { createParamDecorator, SetMetadata, UnauthorizedException, Injectable, Inject } from '@nestjs/common';
3
+ import { Reflector } from '@nestjs/core';
4
+ import { TokenExpiredError, JwtService } from '@nestjs/jwt';
5
+
6
+ /**
7
+ * #### Create JWT Auth Guard
8
+ *
9
+ * Creates a guard that requires a valid JWT on every route, for use as the global `APP_GUARD`:
10
+ *
11
+ * - routes and controllers marked with `@Guard.public()` pass without a token
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"
14
+ * - otherwise the payload is written to `request.user` (see `property`) and is available through `@Guard.user()`
15
+ *
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.
19
+ *
20
+ * * * *
21
+ * Example:
22
+ * ```typescript
23
+ * import { createJwtAuthGuard } from '@telperion/nest-pack/auth';
24
+ * import { APP_GUARD } from '@nestjs/core';
25
+ * import { JwtModule } from '@nestjs/jwt';
26
+ *
27
+ * export const AuthGuard = createJwtAuthGuard<TokenPayload>();
28
+ *
29
+ * @Module({
30
+ * imports: [JwtModule.register({ secret: process.env.JWT_SECRET })],
31
+ * providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
32
+ * })
33
+ * export class AppModule {}
34
+ *
35
+ * @Controller('huddles')
36
+ * export class HuddlesController {
37
+ * @Get()
38
+ * list(@AuthGuard.user() user: TokenPayload) {}
39
+ *
40
+ * @Get('health')
41
+ * @AuthGuard.public()
42
+ * health() {}
43
+ * }
44
+ * ```
45
+ *
46
+ * To give the guard a class name of its own, extend it: `@Injectable() export class AuthGuard extends createJwtAuthGuard<TokenPayload>() {}`.
47
+ *
48
+ * Other guards and interceptors can skip public routes with `AuthGuard.isPublic(context)`.
49
+ * * * *
50
+ * @param options Messages, where the token comes from, verification options and where the payload goes
51
+ * @returns An injectable guard class with `public()`, `isPublic()`, `user()` and `userOf()`
52
+ */
53
+ function createJwtAuthGuard(options = {}) {
54
+ var JwtAuthGuard_1;
55
+ const { expiredMessage = 'TokenExpired', unauthorizedMessage = 'Unauthorized', extract, verifyOptions, property = 'user', } = options;
56
+ const publicKey = Symbol('jwt-auth-guard:public');
57
+ let JwtAuthGuard = class JwtAuthGuard {
58
+ static { JwtAuthGuard_1 = this; }
59
+ reflector;
60
+ jwt;
61
+ static user = createParamDecorator((_data, context) => JwtAuthGuard_1.userOf(context.switchToHttp().getRequest()));
62
+ /**
63
+ * @param reflector Reads `public()` markers
64
+ * @param jwt Verifies tokens
65
+ */
66
+ constructor(reflector, jwt) {
67
+ this.reflector = reflector;
68
+ this.jwt = jwt;
69
+ }
70
+ /** Reads `public()` markers when `isPublic()` gets no reflector; `Reflector` needs no dependencies */
71
+ static defaultReflector = new Reflector();
72
+ static public() {
73
+ return SetMetadata(publicKey, true);
74
+ }
75
+ static isPublic(context, reflector = JwtAuthGuard_1.defaultReflector) {
76
+ return !!reflector.getAllAndOverride(publicKey, [context.getHandler(), context.getClass()]);
77
+ }
78
+ static userOf(request) {
79
+ return request[property];
80
+ }
81
+ /**
82
+ * The token of an `Authorization: Bearer <token>` header (the scheme is case-insensitive)
83
+ */
84
+ static bearerToken({ headers }) {
85
+ const header = headers['authorization'];
86
+ return (typeof header === 'string' ? /^Bearer +(\S+)$/i.exec(header) : null)?.[1];
87
+ }
88
+ canActivate(context) {
89
+ if (JwtAuthGuard_1.isPublic(context, this.reflector)) {
90
+ return true;
91
+ }
92
+ const request = context.switchToHttp().getRequest();
93
+ const token = extract ? extract(request) : JwtAuthGuard_1.bearerToken(request);
94
+ 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));
97
+ }
98
+ };
99
+ JwtAuthGuard = JwtAuthGuard_1 = __decorate([
100
+ Injectable(),
101
+ __metadata("design:paramtypes", [Reflector,
102
+ JwtService])
103
+ ], JwtAuthGuard);
104
+ [Reflector, JwtService].forEach((token, index) => Inject(token)(JwtAuthGuard, undefined, index));
105
+ return JwtAuthGuard;
106
+ }
107
+
108
+ export { createJwtAuthGuard };
109
+ //# sourceMappingURL=create-jwt-auth-guard.js.map
@@ -0,0 +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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W;AAC5D,YAAA,MAAM,KAAK,GAAG,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,cAAY,CAAC,WAAW,CAAC,OAAyC,CAAC;AAE9G,YAAA,OAAO;AACL,kBAAE,IAAI,CAAC,GAAG,CAAC,WAAW,CAAU,KAAK,EAAE,aAAa,CAAC,CAAC,IAAI,CACtD,OAAO,KAAK,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC,QAAQ,GAAG,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC,EAClE,CAAC,KAAc,KAAK,OAAO,CAAC,MAAM,CAAC,IAAI,qBAAqB,CAAC,KAAK,YAAY,iBAAiB,GAAG,cAAc,GAAG,mBAAmB,CAAC,CAAC;kBAE1I,OAAO,CAAC,MAAM,CAAC,IAAI,qBAAqB,CAAC,mBAAmB,CAAC,CAAC;QACpE;;IApDI,YAAY,GAAA,cAAA,GAAA,UAAA,CAAA;AADjB,QAAA,UAAU,EAAE;yCAWmB,SAAS;YACf,UAAU,CAAA;AAX9B,KAAA,EAAA,YAAY,CAqDjB;IAED,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,CAAC,YAAY,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAEhG,IAAA,OAAO,YAAY;AACrB;;;;"}
package/auth/index.cjs ADDED
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+
3
+ var auth_createJwtAuthGuard = require('./create-jwt-auth-guard.cjs');
4
+
5
+
6
+
7
+ exports.createJwtAuthGuard = auth_createJwtAuthGuard.createJwtAuthGuard;
8
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;"}
@@ -0,0 +1,5 @@
1
+ export { JwtAuthGuardOptions, JwtAuthGuardRequest, JwtAuthGuardType } from './jwt-auth-guard-options.cjs';
2
+ export { createJwtAuthGuard } from './create-jwt-auth-guard.cjs';
3
+ import '@nestjs/common';
4
+ import '@nestjs/core';
5
+ import '@nestjs/jwt';
@@ -0,0 +1,5 @@
1
+ export { JwtAuthGuardOptions, JwtAuthGuardRequest, JwtAuthGuardType } from './jwt-auth-guard-options.js';
2
+ export { createJwtAuthGuard } from './create-jwt-auth-guard.js';
3
+ import '@nestjs/common';
4
+ import '@nestjs/core';
5
+ import '@nestjs/jwt';
package/auth/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createJwtAuthGuard } from './create-jwt-auth-guard.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,3 @@
1
+ 'use strict';
2
+
3
+ //# sourceMappingURL=jwt-auth-guard-options.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt-auth-guard-options.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
@@ -0,0 +1,71 @@
1
+ import { Type, CanActivate, ExecutionContext } from '@nestjs/common';
2
+ import { Reflector } from '@nestjs/core';
3
+ import { JwtVerifyOptions } from '@nestjs/jwt';
4
+
5
+ /**
6
+ * What a {@link createJwtAuthGuard} reads from a request
7
+ */
8
+ interface JwtAuthGuardRequest {
9
+ headers: Record<string, string | string[] | undefined>;
10
+ }
11
+ /**
12
+ * Options of {@link createJwtAuthGuard}
13
+ */
14
+ interface JwtAuthGuardOptions<Request extends object = JwtAuthGuardRequest> {
15
+ /**
16
+ * The message of the 401 answer for an expired token, so clients can renew the token and retry
17
+ * (e.g. `ApiAuth.expired` of `@telperion/ng-pack/http`)
18
+ *
19
+ * @default 'TokenExpired'
20
+ */
21
+ expiredMessage?: string;
22
+ /**
23
+ * The message of the 401 answer for a missing or invalid token
24
+ *
25
+ * @default 'Unauthorized'
26
+ */
27
+ unauthorizedMessage?: string;
28
+ /**
29
+ * Reads the token from a request
30
+ *
31
+ * @default the token of an `Authorization: Bearer <token>` header
32
+ */
33
+ extract?: (request: Request) => string | null | undefined;
34
+ /**
35
+ * Options of `JwtService.verifyAsync`, e.g. the `audience`, `issuer` or a `secret` other than the `JwtModule`'s
36
+ */
37
+ verifyOptions?: JwtVerifyOptions;
38
+ /**
39
+ * The request property the verified payload is written to
40
+ *
41
+ * @default 'user'
42
+ */
43
+ property?: string;
44
+ }
45
+ /**
46
+ * The guard class {@link createJwtAuthGuard} returns, with its decorators
47
+ */
48
+ interface JwtAuthGuardType<Payload extends object> extends Type<CanActivate> {
49
+ /**
50
+ * Route or controller decorator: the route needs no token. A method's setting replaces its controller's.
51
+ */
52
+ public(): MethodDecorator & ClassDecorator;
53
+ /**
54
+ * Whether the route of a context is marked with `public()`, for other guards and interceptors that skip public
55
+ * routes (throttling, auditing, resolving the user, …). A method's setting replaces its controller's.
56
+ *
57
+ * @param context The context of the route, e.g. of `canActivate` or `intercept`
58
+ * @param reflector Reads the markers; a `Reflector` of its own by default
59
+ */
60
+ isPublic(context: ExecutionContext, reflector?: Reflector): boolean;
61
+ /**
62
+ * Parameter decorator: the verified token payload, `undefined` on public routes
63
+ */
64
+ user(...pipes: unknown[]): ParameterDecorator;
65
+ /**
66
+ * The verified payload of a request, `undefined` before the guard ran or on public routes
67
+ */
68
+ userOf(request: object): Payload | undefined;
69
+ }
70
+
71
+ export type { JwtAuthGuardOptions, JwtAuthGuardRequest, JwtAuthGuardType };
@@ -0,0 +1,71 @@
1
+ import { Type, CanActivate, ExecutionContext } from '@nestjs/common';
2
+ import { Reflector } from '@nestjs/core';
3
+ import { JwtVerifyOptions } from '@nestjs/jwt';
4
+
5
+ /**
6
+ * What a {@link createJwtAuthGuard} reads from a request
7
+ */
8
+ interface JwtAuthGuardRequest {
9
+ headers: Record<string, string | string[] | undefined>;
10
+ }
11
+ /**
12
+ * Options of {@link createJwtAuthGuard}
13
+ */
14
+ interface JwtAuthGuardOptions<Request extends object = JwtAuthGuardRequest> {
15
+ /**
16
+ * The message of the 401 answer for an expired token, so clients can renew the token and retry
17
+ * (e.g. `ApiAuth.expired` of `@telperion/ng-pack/http`)
18
+ *
19
+ * @default 'TokenExpired'
20
+ */
21
+ expiredMessage?: string;
22
+ /**
23
+ * The message of the 401 answer for a missing or invalid token
24
+ *
25
+ * @default 'Unauthorized'
26
+ */
27
+ unauthorizedMessage?: string;
28
+ /**
29
+ * Reads the token from a request
30
+ *
31
+ * @default the token of an `Authorization: Bearer <token>` header
32
+ */
33
+ extract?: (request: Request) => string | null | undefined;
34
+ /**
35
+ * Options of `JwtService.verifyAsync`, e.g. the `audience`, `issuer` or a `secret` other than the `JwtModule`'s
36
+ */
37
+ verifyOptions?: JwtVerifyOptions;
38
+ /**
39
+ * The request property the verified payload is written to
40
+ *
41
+ * @default 'user'
42
+ */
43
+ property?: string;
44
+ }
45
+ /**
46
+ * The guard class {@link createJwtAuthGuard} returns, with its decorators
47
+ */
48
+ interface JwtAuthGuardType<Payload extends object> extends Type<CanActivate> {
49
+ /**
50
+ * Route or controller decorator: the route needs no token. A method's setting replaces its controller's.
51
+ */
52
+ public(): MethodDecorator & ClassDecorator;
53
+ /**
54
+ * Whether the route of a context is marked with `public()`, for other guards and interceptors that skip public
55
+ * routes (throttling, auditing, resolving the user, …). A method's setting replaces its controller's.
56
+ *
57
+ * @param context The context of the route, e.g. of `canActivate` or `intercept`
58
+ * @param reflector Reads the markers; a `Reflector` of its own by default
59
+ */
60
+ isPublic(context: ExecutionContext, reflector?: Reflector): boolean;
61
+ /**
62
+ * Parameter decorator: the verified token payload, `undefined` on public routes
63
+ */
64
+ user(...pipes: unknown[]): ParameterDecorator;
65
+ /**
66
+ * The verified payload of a request, `undefined` before the guard ran or on public routes
67
+ */
68
+ userOf(request: object): Payload | undefined;
69
+ }
70
+
71
+ export type { JwtAuthGuardOptions, JwtAuthGuardRequest, JwtAuthGuardType };
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=jwt-auth-guard-options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt-auth-guard-options.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@telperion/nest-pack",
3
- "version": "1.1.0",
4
- "description": "NestJS utilities: access guards, validation helpers and pagination",
3
+ "version": "1.3.0",
4
+ "description": "NestJS utilities: JWT auth and access guards, validation helpers and pagination",
5
5
  "keywords": [
6
6
  "nestjs",
7
7
  "nest",
@@ -16,7 +16,12 @@
16
16
  "trim",
17
17
  "pagination",
18
18
  "paging",
19
- "dto"
19
+ "dto",
20
+ "jwt",
21
+ "authentication",
22
+ "auth guard",
23
+ "bearer token",
24
+ "public route"
20
25
  ],
21
26
  "homepage": "https://github.com/telperiontech/telperion/tree/main/libs/nest-pack#readme",
22
27
  "repository": {
@@ -35,9 +40,13 @@
35
40
  "@nestjs/common": "^11.0.0 || ^12.0.0",
36
41
  "@nestjs/core": "^11.0.0 || ^12.0.0",
37
42
  "class-transformer": "^0.5.0",
38
- "class-validator": "^0.14.0 || ^0.15.0"
43
+ "class-validator": "^0.14.0 || ^0.15.0",
44
+ "@nestjs/jwt": "^11.0.0 || ^12.0.0"
39
45
  },
40
46
  "peerDependenciesMeta": {
47
+ "@nestjs/jwt": {
48
+ "optional": true
49
+ },
41
50
  "class-transformer": {
42
51
  "optional": true
43
52
  },
@@ -108,6 +117,46 @@
108
117
  "node": "./access/index.cjs",
109
118
  "default": "./access/index.js"
110
119
  },
120
+ "./auth/create-jwt-auth-guard": {
121
+ "types": {
122
+ "import": "./auth/create-jwt-auth-guard.d.ts",
123
+ "require": "./auth/create-jwt-auth-guard.d.cts"
124
+ },
125
+ "import": "./auth/create-jwt-auth-guard.js",
126
+ "require": "./auth/create-jwt-auth-guard.cjs",
127
+ "node": "./auth/create-jwt-auth-guard.cjs",
128
+ "default": "./auth/create-jwt-auth-guard.js"
129
+ },
130
+ "./auth/index": {
131
+ "types": {
132
+ "import": "./auth/index.d.ts",
133
+ "require": "./auth/index.d.cts"
134
+ },
135
+ "import": "./auth/index.js",
136
+ "require": "./auth/index.cjs",
137
+ "node": "./auth/index.cjs",
138
+ "default": "./auth/index.js"
139
+ },
140
+ "./auth": {
141
+ "types": {
142
+ "import": "./auth/index.d.ts",
143
+ "require": "./auth/index.d.cts"
144
+ },
145
+ "import": "./auth/index.js",
146
+ "require": "./auth/index.cjs",
147
+ "node": "./auth/index.cjs",
148
+ "default": "./auth/index.js"
149
+ },
150
+ "./auth/jwt-auth-guard-options": {
151
+ "types": {
152
+ "import": "./auth/jwt-auth-guard-options.d.ts",
153
+ "require": "./auth/jwt-auth-guard-options.d.cts"
154
+ },
155
+ "import": "./auth/jwt-auth-guard-options.js",
156
+ "require": "./auth/jwt-auth-guard-options.cjs",
157
+ "node": "./auth/jwt-auth-guard-options.cjs",
158
+ "default": "./auth/jwt-auth-guard-options.js"
159
+ },
111
160
  "./pagination/index": {
112
161
  "types": {
113
162
  "import": "./pagination/index.d.ts",