@telperion/nest-pack 1.0.0 → 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 (53) hide show
  1. package/.build-manifest.json +61 -1
  2. package/README.md +124 -3
  3. package/access/access-guard-options.d.cts +19 -4
  4. package/access/access-guard-options.d.ts +19 -4
  5. package/access/create-access-guard.cjs +15 -4
  6. package/access/create-access-guard.cjs.map +1 -1
  7. package/access/create-access-guard.d.cts +3 -2
  8. package/access/create-access-guard.d.ts +3 -2
  9. package/access/create-access-guard.js +15 -4
  10. package/access/create-access-guard.js.map +1 -1
  11. package/access/index.d.cts +1 -1
  12. package/access/index.d.ts +1 -1
  13. package/auth/create-jwt-auth-guard.cjs +104 -0
  14. package/auth/create-jwt-auth-guard.cjs.map +1 -0
  15. package/auth/create-jwt-auth-guard.d.cts +52 -0
  16. package/auth/create-jwt-auth-guard.d.ts +52 -0
  17. package/auth/create-jwt-auth-guard.js +102 -0
  18. package/auth/create-jwt-auth-guard.js.map +1 -0
  19. package/auth/index.cjs +8 -0
  20. package/auth/index.cjs.map +1 -0
  21. package/auth/index.d.cts +4 -0
  22. package/auth/index.d.ts +4 -0
  23. package/auth/index.js +2 -0
  24. package/auth/index.js.map +1 -0
  25. package/auth/jwt-auth-guard-options.cjs +3 -0
  26. package/auth/jwt-auth-guard-options.cjs.map +1 -0
  27. package/auth/jwt-auth-guard-options.d.cts +62 -0
  28. package/auth/jwt-auth-guard-options.d.ts +62 -0
  29. package/auth/jwt-auth-guard-options.js +2 -0
  30. package/auth/jwt-auth-guard-options.js.map +1 -0
  31. package/fesm/nest-pack.mjs +15 -4
  32. package/fesm/nest-pack.mjs.map +1 -1
  33. package/index.d.cts +1 -1
  34. package/index.d.ts +1 -1
  35. package/package.json +96 -4
  36. package/pagination/index.cjs +10 -0
  37. package/pagination/index.cjs.map +1 -0
  38. package/pagination/index.d.cts +2 -0
  39. package/pagination/index.d.ts +2 -0
  40. package/pagination/index.js +3 -0
  41. package/pagination/index.js.map +1 -0
  42. package/pagination/page-query.cjs +92 -0
  43. package/pagination/page-query.cjs.map +1 -0
  44. package/pagination/page-query.d.cts +63 -0
  45. package/pagination/page-query.d.ts +63 -0
  46. package/pagination/page-query.js +90 -0
  47. package/pagination/page-query.js.map +1 -0
  48. package/pagination/page.cjs +48 -0
  49. package/pagination/page.cjs.map +1 -0
  50. package/pagination/page.d.cts +40 -0
  51. package/pagination/page.d.ts +40 -0
  52. package/pagination/page.js +46 -0
  53. package/pagination/page.js.map +1 -0
@@ -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",
@@ -51,6 +81,36 @@
51
81
  "dcts": "index.d.cts"
52
82
  }
53
83
  },
84
+ {
85
+ "name": "pagination/index",
86
+ "sourcePath": "src/pagination/index.ts",
87
+ "outputs": {
88
+ "esm": "pagination/index.js",
89
+ "cjs": "pagination/index.cjs",
90
+ "dts": "pagination/index.d.ts",
91
+ "dcts": "pagination/index.d.cts"
92
+ }
93
+ },
94
+ {
95
+ "name": "pagination/page-query",
96
+ "sourcePath": "src/pagination/page-query.ts",
97
+ "outputs": {
98
+ "esm": "pagination/page-query.js",
99
+ "cjs": "pagination/page-query.cjs",
100
+ "dts": "pagination/page-query.d.ts",
101
+ "dcts": "pagination/page-query.d.cts"
102
+ }
103
+ },
104
+ {
105
+ "name": "pagination/page",
106
+ "sourcePath": "src/pagination/page.ts",
107
+ "outputs": {
108
+ "esm": "pagination/page.js",
109
+ "cjs": "pagination/page.cjs",
110
+ "dts": "pagination/page.d.ts",
111
+ "dcts": "pagination/page.d.cts"
112
+ }
113
+ },
54
114
  {
55
115
  "name": "validation/index",
56
116
  "sourcePath": "src/validation/index.ts",
@@ -72,5 +132,5 @@
72
132
  }
73
133
  }
74
134
  ],
75
- "generatedAt": "2026-11-30T09:36:10.845Z"
135
+ "generatedAt": "2026-12-01T16:45:38.292Z"
76
136
  }
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  # @telperion/nest-pack
2
- NestJS utilities: access guards and validation helpers
2
+ NestJS utilities: access guards, validation helpers and pagination
3
3
 
4
4
  [![npm](https://img.shields.io/npm/v/@telperion/nest-pack.svg)](https://www.npmjs.com/package/@telperion/nest-pack)
5
5
  [![npm](https://img.shields.io/npm/dm/@telperion/nest-pack.svg)](https://www.npmjs.com/package/@telperion/nest-pack)
@@ -21,9 +21,57 @@ 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` |
26
+ | `@telperion/nest-pack/pagination` | `PageQuery`, `Page` | `class-transformer` and `class-validator` (optional peer dependencies) |
25
27
 
26
- The root entry point does not include `validation`, so projects without class-transformer 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
+ **Options** (all optional):
68
+
69
+ - `extract(request)` — reads the token; default: `Authorization: Bearer <token>` (scheme case-insensitive)
70
+ - `verifyOptions` — options of `JwtService.verifyAsync`, e.g. `audience`, `issuer`
71
+ - `expiredMessage`, `unauthorizedMessage` — messages of the 401 answers
72
+ - `property` — the request property the payload is written to (default `'user'`, where Passport and most code expect it)
73
+
74
+ With `@telperion/ng-pack/http`, detect the expired answer in `ApiAuth.expired`: `error => error.status === 401 && error.error?.message === 'TokenExpired'`.
27
75
 
28
76
  ## Access
29
77
 
@@ -73,7 +121,24 @@ Nest creates the guard in the module of the controller using it, so its `inject`
73
121
  export class ProjectAccessGuard extends createAccessGuard({ /* ... */ }) {}
74
122
  ```
75
123
 
76
- HTTP only: the guard reads `request.params`.
124
+ HTTP only: the guard reads `request.params`, or the body or query string (see below).
125
+
126
+ #### Reading the id from the body or query string
127
+
128
+ `from` picks where `param` is read: `'params'` (default), `'body'` or `'query'`. With a list, the first source holding a string value is used, e.g. for endpoints that take the id in the path or, without a route parameter, in the body:
129
+
130
+ ```typescript
131
+ export const ProjectMemberGuard = createAccessGuard({
132
+ param: 'projectId',
133
+ from: ['params', 'body'], // /projects/:projectId/..., or { "projectId": "..." } in the body
134
+ validate: isUUID,
135
+ inject: [ProjectsService],
136
+ resolve: (projectId, request: AuthenticatedRequest, projects) => projects.membershipOf(request.user, projectId),
137
+ allows: () => true,
138
+ });
139
+ ```
140
+
141
+ A missing or non-string value answers **404**, like a malformed one; this includes a repeated query parameter (`?projectId=a&projectId=b`), which arrives as an array. Hand-written guards often answer 400 for a missing id instead; the guard keeps 404 so every failed lookup looks the same. The body is read as parsed by Nest's body parser, before any `ValidationPipe` runs.
77
142
 
78
143
  #### Example: two guards, a few lines each
79
144
 
@@ -129,6 +194,62 @@ app.useGlobalPipes(new ValidationPipe({ transform: true }));
129
194
 
130
195
  `ValidationPipe` validates the transformed DTO either way; its `transform` option makes the handler receive the trimmed values too.
131
196
 
197
+ ## Pagination
198
+
199
+ ### Page Query
200
+ The query DTO of a paged list endpoint (`?page=2&pageSize=50&search=ada`), with class-validator and class-transformer decorators:
201
+
202
+ | Property | Rules | Default |
203
+ | --- | --- | --- |
204
+ | `page` | integer, at least 1 | `1` |
205
+ | `pageSize` | integer from 1 to 100 | `25` |
206
+ | `search` | optional string, at most 200 characters | |
207
+
208
+ Query values arrive as strings; `@Type(() => Number)` converts them, so use it with `ValidationPipe({ transform: true })`. Missing values keep their defaults.
209
+
210
+ Two static helpers go with it:
211
+ - `PageQuery.skipTake(query)`: `{ skip, take }` for the page, as TypeORM's and Prisma's options
212
+ - `PageQuery.likePattern(search)`: a `LIKE`/`ILIKE` pattern that contains the search text literally: `\`, `%` and `_` are escaped with `\`, and the text is wrapped in `%`
213
+
214
+ ### Page
215
+ The response of a paged list endpoint: `{ items, total, page, pageSize }`. `Page.of(items, total, query)` creates it.
216
+
217
+ ```typescript
218
+ import { Page, PageQuery } from '@telperion/nest-pack/pagination';
219
+
220
+ @Controller('users')
221
+ export class UsersController {
222
+ @Get()
223
+ async list(@Query() query: PageQuery): Promise<Page<User>> {
224
+ const [items, total] = await this.users.findAndCount({
225
+ where: query.search ? { name: ILike(PageQuery.likePattern(query.search)) } : {},
226
+ order: { name: 'ASC' },
227
+ ...PageQuery.skipTake(query),
228
+ });
229
+
230
+ return Page.of(items, total, query);
231
+ }
232
+ }
233
+ ```
234
+
235
+ Extend `PageQuery` to add filters, or to redeclare a property with other limits:
236
+
237
+ ```typescript
238
+ export class UserPageQuery extends PageQuery {
239
+ @IsOptional()
240
+ @IsIn(['active', 'invited'])
241
+ status?: 'active' | 'invited';
242
+ }
243
+ ```
244
+
245
+ #### Swagger
246
+
247
+ The package does not depend on `@nestjs/swagger`, so the properties carry no `@ApiProperty` decorators. Either:
248
+ - turn on the [Swagger CLI plugin](https://docs.nestjs.com/openapi/cli-plugin) for your DTOs; it reads the types and class-validator decorators, including those of `PageQuery` when your query class extends it (the plugin only annotates files matching its `dtoFileNameSuffix`, so extend it in such a file), or
249
+ - extend `PageQuery` and redeclare the properties with `@ApiPropertyOptional(...)` next to their validators.
250
+
251
+ For the response, declare a subclass per item type (e.g. `class UserPage extends Page<UserDto>` with `@ApiProperty({ type: [UserDto] }) declare readonly items: UserDto[]`) and use it in `@ApiOkResponse({ type: UserPage })`.
252
+
132
253
  ## License
133
254
 
134
255
  [MIT](./LICENSE)
@@ -1,10 +1,16 @@
1
1
  import { InjectionToken, Type, CanActivate } from '@nestjs/common';
2
2
 
3
3
  /**
4
- * The part of an HTTP request an access guard reads: the route parameters
4
+ * A part of an HTTP request an access guard can read the id from: the route parameters, the parsed body or the query string
5
+ */
6
+ type AccessGuardSource = 'params' | 'body' | 'query';
7
+ /**
8
+ * The parts of an HTTP request an access guard reads (see {@link AccessGuardOptions.from})
5
9
  */
6
10
  interface AccessGuardRequest {
7
11
  params?: Record<string, unknown>;
12
+ body?: unknown;
13
+ query?: unknown;
8
14
  }
9
15
  /**
10
16
  * The instances of the injection tokens in {@link AccessGuardOptions.inject}, in order:
@@ -18,9 +24,18 @@ type InjectedDependencies<Tokens extends readonly InjectionToken[]> = {
18
24
  */
19
25
  interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> {
20
26
  /**
21
- * The route parameter holding the id of what is accessed, e.g. `'projectId'` for `/projects/:projectId/items`
27
+ * The parameter holding the id of what is accessed, e.g. `'projectId'` for `/projects/:projectId/items`.
28
+ * By default a route parameter; see `from` to read a body field or query parameter of that name.
22
29
  */
23
30
  param: string;
31
+ /**
32
+ * Where to read `param` from. With several sources, the first one holding a string value is used,
33
+ * e.g. `['params', 'body']` for routes that take the id in the path or, without a route parameter, in the body.
34
+ * A missing or non-string value (also a repeated query parameter, which arrives as an array) answers 404.
35
+ *
36
+ * @default 'params'
37
+ */
38
+ from?: AccessGuardSource | readonly AccessGuardSource[];
24
39
  /**
25
40
  * Checks the parameter's format before `resolve` runs, e.g. `isUUID` from class-validator.
26
41
  * Malformed values answer 404 without a lookup.
@@ -36,7 +51,7 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
36
51
  * Resolves the caller's access to what the parameter identifies; `null` or `undefined` when there is none
37
52
  * (no such entity, or the caller may not see it), which answers 404
38
53
  *
39
- * @param value The route parameter, after `validate`
54
+ * @param value The parameter, after `validate`
40
55
  * @param request The HTTP request, e.g. with the authenticated user
41
56
  * @param dependencies The instances of the `inject` tokens
42
57
  */
@@ -78,4 +93,4 @@ interface AccessGuardType<Access, Requirement> extends Type<CanActivate> {
78
93
  accessOf(request: object): Access | undefined;
79
94
  }
80
95
 
81
- export type { AccessGuardOptions, AccessGuardRequest, AccessGuardType, InjectedDependencies };
96
+ export type { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies };
@@ -1,10 +1,16 @@
1
1
  import { InjectionToken, Type, CanActivate } from '@nestjs/common';
2
2
 
3
3
  /**
4
- * The part of an HTTP request an access guard reads: the route parameters
4
+ * A part of an HTTP request an access guard can read the id from: the route parameters, the parsed body or the query string
5
+ */
6
+ type AccessGuardSource = 'params' | 'body' | 'query';
7
+ /**
8
+ * The parts of an HTTP request an access guard reads (see {@link AccessGuardOptions.from})
5
9
  */
6
10
  interface AccessGuardRequest {
7
11
  params?: Record<string, unknown>;
12
+ body?: unknown;
13
+ query?: unknown;
8
14
  }
9
15
  /**
10
16
  * The instances of the injection tokens in {@link AccessGuardOptions.inject}, in order:
@@ -18,9 +24,18 @@ type InjectedDependencies<Tokens extends readonly InjectionToken[]> = {
18
24
  */
19
25
  interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> {
20
26
  /**
21
- * The route parameter holding the id of what is accessed, e.g. `'projectId'` for `/projects/:projectId/items`
27
+ * The parameter holding the id of what is accessed, e.g. `'projectId'` for `/projects/:projectId/items`.
28
+ * By default a route parameter; see `from` to read a body field or query parameter of that name.
22
29
  */
23
30
  param: string;
31
+ /**
32
+ * Where to read `param` from. With several sources, the first one holding a string value is used,
33
+ * e.g. `['params', 'body']` for routes that take the id in the path or, without a route parameter, in the body.
34
+ * A missing or non-string value (also a repeated query parameter, which arrives as an array) answers 404.
35
+ *
36
+ * @default 'params'
37
+ */
38
+ from?: AccessGuardSource | readonly AccessGuardSource[];
24
39
  /**
25
40
  * Checks the parameter's format before `resolve` runs, e.g. `isUUID` from class-validator.
26
41
  * Malformed values answer 404 without a lookup.
@@ -36,7 +51,7 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
36
51
  * Resolves the caller's access to what the parameter identifies; `null` or `undefined` when there is none
37
52
  * (no such entity, or the caller may not see it), which answers 404
38
53
  *
39
- * @param value The route parameter, after `validate`
54
+ * @param value The parameter, after `validate`
40
55
  * @param request The HTTP request, e.g. with the authenticated user
41
56
  * @param dependencies The instances of the `inject` tokens
42
57
  */
@@ -78,4 +93,4 @@ interface AccessGuardType<Access, Requirement> extends Type<CanActivate> {
78
93
  accessOf(request: object): Access | undefined;
79
94
  }
80
95
 
81
- export type { AccessGuardOptions, AccessGuardRequest, AccessGuardType, InjectedDependencies };
96
+ export type { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies };
@@ -8,9 +8,10 @@ var core = require('@nestjs/core');
8
8
  * #### Create Access Guard
9
9
  *
10
10
  * Creates a guard for routes about one entity, e.g. a project in `/projects/:projectId/...`.
11
- * The guard resolves the caller's access to the entity in a route parameter and checks the route's requirements:
11
+ * The guard resolves the caller's access to the entity in a route parameter (or a body field or query parameter, see `from`)
12
+ * and checks the route's requirements:
12
13
  *
13
- * - malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
14
+ * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
14
15
  * so callers can't probe which ids exist
15
16
  * - access that does not meet every requirement of the route (see `allows`): **403**
16
17
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
@@ -50,7 +51,8 @@ var core = require('@nestjs/core');
50
51
  */
51
52
  function createAccessGuard(options) {
52
53
  var AccessGuard_1;
53
- const { param, validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
54
+ const { param, from = 'params', validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
55
+ const sources = typeof from === 'string' ? [from] : from;
54
56
  const requirementsKey = Symbol(`access-guard:${param}:requirements`);
55
57
  const accessKey = Symbol(`access-guard:${param}:access`);
56
58
  let AccessGuard = class AccessGuard {
@@ -72,12 +74,21 @@ function createAccessGuard(options) {
72
74
  static accessOf(request) {
73
75
  return request[accessKey];
74
76
  }
77
+ /**
78
+ * The parameter in the first source holding a string value
79
+ */
80
+ static idOf(request) {
81
+ return sources
82
+ .map(source => request[source])
83
+ .map(holder => (typeof holder === 'object' && holder !== null ? holder[param] : undefined))
84
+ .find((value) => typeof value === 'string');
85
+ }
75
86
  static notGuarded() {
76
87
  throw new Error(`The access of :${param} is read on a route without its access guard; add \`.require()\` to the route or controller`);
77
88
  }
78
89
  canActivate(context) {
79
90
  const request = context.switchToHttp().getRequest();
80
- const value = request.params?.[param];
91
+ const value = AccessGuard_1.idOf(request);
81
92
  const required = this.reflector.getAllAndOverride(requirementsKey, [context.getHandler(), context.getClass()]) ?? [];
82
93
  return Promise.resolve(typeof value === 'string' && validate(value) ? resolve(value, request, ...this.dependencies) : null).then(access => {
83
94
  if (access === null || access === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"create-access-guard.cjs","sources":["../../../../libs/nest-pack/src/access/create-access-guard.ts"],"sourcesContent":[null],"names":["createParamDecorator","applyDecorators","SetMetadata","UseGuards","NotFoundException","ForbiddenException","__decorate","Injectable","Reflector","Inject"],"mappings":";;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CG;AACG,SAAU,iBAAiB,CAK/B,OAAiE,EAAA;;AACjE,IAAA,MAAM,EAAE,KAAK,EAAE,QAAQ,GAAG,MAAM,IAAI,EAAE,MAAM,GAAG,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAG,WAAW,EAAE,SAAS,GAAG,WAAW,EAAE,GAAG,OAAO;IAC/H,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,KA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AAC,QAAQ,EAAE,CAAC,CAAC,IAAI,EAAE;AAE/I,YAAA,OAAO,OAAO,CAAC,OAAO,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,IAAG;gBACxI,IAAI,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,EAAE;AAC3C,oBAAA,MAAM,IAAIC,wBAAiB,CAAC,QAAQ,CAAC;gBACvC;AAEA,gBAAA,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,EAAE;AAC/D,oBAAA,MAAM,IAAIC,yBAAkB,CAAC,SAAS,CAAC;gBACzC;AAEA,gBAAA,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC,SAAS,GAAG,MAAM,EAAE,CAAC;AAE/C,gBAAA,OAAO,IAAI;AACb,YAAA,CAAC,CAAC;QACJ;;IAjDI,WAAW,GAAA,aAAA,GAAAC,gBAAA,CAAA;AADhB,QAAAC,iBAAU,EAAE;;AACP,KAAA,EAAA,WAAW,CAkDhB;IAED,CAACC,cAAS,EAAE,GAAG,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAKC,aAAM,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAE9F,IAAA,OAAO,WAAW;AACpB;;;;"}
1
+ {"version":3,"file":"create-access-guard.cjs","sources":["../../../../libs/nest-pack/src/access/create-access-guard.ts"],"sourcesContent":[null],"names":["createParamDecorator","applyDecorators","SetMetadata","UseGuards","NotFoundException","ForbiddenException","__decorate","Injectable","Reflector","Inject"],"mappings":";;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;AAC/D,oBAAA,MAAM,IAAIC,yBAAkB,CAAC,SAAS,CAAC;gBACzC;AAEA,gBAAA,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC,SAAS,GAAG,MAAM,EAAE,CAAC;AAE/C,gBAAA,OAAO,IAAI;AACb,YAAA,CAAC,CAAC;QACJ;;IA3DI,WAAW,GAAA,aAAA,GAAAC,gBAAA,CAAA;AADhB,QAAAC,iBAAU,EAAE;;AACP,KAAA,EAAA,WAAW,CA4DhB;IAED,CAACC,cAAS,EAAE,GAAG,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAKC,aAAM,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAE9F,IAAA,OAAO,WAAW;AACpB;;;;"}
@@ -5,9 +5,10 @@ import { InjectionToken } from '@nestjs/common';
5
5
  * #### Create Access Guard
6
6
  *
7
7
  * Creates a guard for routes about one entity, e.g. a project in `/projects/:projectId/...`.
8
- * The guard resolves the caller's access to the entity in a route parameter and checks the route's requirements:
8
+ * The guard resolves the caller's access to the entity in a route parameter (or a body field or query parameter, see `from`)
9
+ * and checks the route's requirements:
9
10
  *
10
- * - malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
11
+ * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
11
12
  * so callers can't probe which ids exist
12
13
  * - access that does not meet every requirement of the route (see `allows`): **403**
13
14
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
@@ -5,9 +5,10 @@ import { InjectionToken } from '@nestjs/common';
5
5
  * #### Create Access Guard
6
6
  *
7
7
  * Creates a guard for routes about one entity, e.g. a project in `/projects/:projectId/...`.
8
- * The guard resolves the caller's access to the entity in a route parameter and checks the route's requirements:
8
+ * The guard resolves the caller's access to the entity in a route parameter (or a body field or query parameter, see `from`)
9
+ * and checks the route's requirements:
9
10
  *
10
- * - malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
11
+ * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
11
12
  * so callers can't probe which ids exist
12
13
  * - access that does not meet every requirement of the route (see `allows`): **403**
13
14
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
@@ -6,9 +6,10 @@ import { Reflector } from '@nestjs/core';
6
6
  * #### Create Access Guard
7
7
  *
8
8
  * Creates a guard for routes about one entity, e.g. a project in `/projects/:projectId/...`.
9
- * The guard resolves the caller's access to the entity in a route parameter and checks the route's requirements:
9
+ * The guard resolves the caller's access to the entity in a route parameter (or a body field or query parameter, see `from`)
10
+ * and checks the route's requirements:
10
11
  *
11
- * - malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
12
+ * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
12
13
  * so callers can't probe which ids exist
13
14
  * - access that does not meet every requirement of the route (see `allows`): **403**
14
15
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
@@ -48,7 +49,8 @@ import { Reflector } from '@nestjs/core';
48
49
  */
49
50
  function createAccessGuard(options) {
50
51
  var AccessGuard_1;
51
- const { param, validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
52
+ const { param, from = 'params', validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
53
+ const sources = typeof from === 'string' ? [from] : from;
52
54
  const requirementsKey = Symbol(`access-guard:${param}:requirements`);
53
55
  const accessKey = Symbol(`access-guard:${param}:access`);
54
56
  let AccessGuard = class AccessGuard {
@@ -70,12 +72,21 @@ function createAccessGuard(options) {
70
72
  static accessOf(request) {
71
73
  return request[accessKey];
72
74
  }
75
+ /**
76
+ * The parameter in the first source holding a string value
77
+ */
78
+ static idOf(request) {
79
+ return sources
80
+ .map(source => request[source])
81
+ .map(holder => (typeof holder === 'object' && holder !== null ? holder[param] : undefined))
82
+ .find((value) => typeof value === 'string');
83
+ }
73
84
  static notGuarded() {
74
85
  throw new Error(`The access of :${param} is read on a route without its access guard; add \`.require()\` to the route or controller`);
75
86
  }
76
87
  canActivate(context) {
77
88
  const request = context.switchToHttp().getRequest();
78
- const value = request.params?.[param];
89
+ const value = AccessGuard_1.idOf(request);
79
90
  const required = this.reflector.getAllAndOverride(requirementsKey, [context.getHandler(), context.getClass()]) ?? [];
80
91
  return Promise.resolve(typeof value === 'string' && validate(value) ? resolve(value, request, ...this.dependencies) : null).then(access => {
81
92
  if (access === null || access === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"create-access-guard.js","sources":["../../../../libs/nest-pack/src/access/create-access-guard.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CG;AACG,SAAU,iBAAiB,CAK/B,OAAiE,EAAA;;AACjE,IAAA,MAAM,EAAE,KAAK,EAAE,QAAQ,GAAG,MAAM,IAAI,EAAE,MAAM,GAAG,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAG,WAAW,EAAE,SAAS,GAAG,WAAW,EAAE,GAAG,OAAO;IAC/H,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,KAAK,CAAA,aAAA,CAAe,CAAC;IACpE,MAAM,SAAS,GAAG,MAAM,CAAC,gBAAgB,KAAK,CAAA,OAAA,CAAS,CAAC;IAExD,IACM,WAAW,GADjB,MACM,WAAW,CAAA;;AACf,QAAA,OAAgB,MAAM,GAAG,oBAAoB,CAC3C,CAAC,KAAc,EAAE,OAAyB,KACxC,aAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,UAAU,EAAU,CAAC,IAAI,aAAW,CAAC,UAAU,EAAE,CAChG;AAEgB,QAAA,SAAS;AACT,QAAA,YAAY;AAE7B;;AAEG;AACH,QAAA,WAAA,CAAY,GAAG,QAAmC,EAAA;YAChD,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WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,EAAE;AAC/D,oBAAA,MAAM,IAAI,kBAAkB,CAAC,SAAS,CAAC;gBACzC;AAEA,gBAAA,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC,SAAS,GAAG,MAAM,EAAE,CAAC;AAE/C,gBAAA,OAAO,IAAI;AACb,YAAA,CAAC,CAAC;QACJ;;IAjDI,WAAW,GAAA,aAAA,GAAA,UAAA,CAAA;AADhB,QAAA,UAAU,EAAE;;AACP,KAAA,EAAA,WAAW,CAkDhB;IAED,CAAC,SAAS,EAAE,GAAG,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAE9F,IAAA,OAAO,WAAW;AACpB;;;;"}
1
+ {"version":3,"file":"create-access-guard.js","sources":["../../../../libs/nest-pack/src/access/create-access-guard.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CG;AACG,SAAU,iBAAiB,CAK/B,OAAiE,EAAA;;AACjE,IAAA,MAAM,EAAE,KAAK,EAAE,IAAI,GAAG,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,EAAE,MAAM,GAAG,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAG,WAAW,EAAE,SAAS,GAAG,WAAW,EAAE,GAAG,OAAO;AAChJ,IAAA,MAAM,OAAO,GAAiC,OAAO,IAAI,KAAK,QAAQ,GAAG,CAAC,IAAI,CAAC,GAAG,IAAI;IACtF,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,KAAK,CAAA,aAAA,CAAe,CAAC;IACpE,MAAM,SAAS,GAAG,MAAM,CAAC,gBAAgB,KAAK,CAAA,OAAA,CAAS,CAAC;IAExD,IACM,WAAW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export { AccessGuardOptions, AccessGuardRequest, AccessGuardType, InjectedDependencies } from './access-guard-options.cjs';
1
+ export { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access-guard-options.cjs';
2
2
  export { createAccessGuard } from './create-access-guard.cjs';
3
3
  import '@nestjs/common';
package/access/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { AccessGuardOptions, AccessGuardRequest, AccessGuardType, InjectedDependencies } from './access-guard-options.js';
1
+ export { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access-guard-options.js';
2
2
  export { createAccessGuard } from './create-access-guard.js';
3
3
  import '@nestjs/common';
@@ -0,0 +1,104 @@
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
+ * @param options Messages, where the token comes from, verification options and where the payload goes
51
+ * @returns An injectable guard class with `public()`, `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 = common.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
+ static public() {
71
+ return common.SetMetadata(publicKey, true);
72
+ }
73
+ static userOf(request) {
74
+ return request[property];
75
+ }
76
+ /**
77
+ * The token of an `Authorization: Bearer <token>` header (the scheme is case-insensitive)
78
+ */
79
+ static bearerToken({ headers }) {
80
+ const header = headers['authorization'];
81
+ return (typeof header === 'string' ? /^Bearer +(\S+)$/i.exec(header) : null)?.[1];
82
+ }
83
+ canActivate(context) {
84
+ if (this.reflector.getAllAndOverride(publicKey, [context.getHandler(), context.getClass()])) {
85
+ return true;
86
+ }
87
+ const request = context.switchToHttp().getRequest();
88
+ const token = extract ? extract(request) : JwtAuthGuard_1.bearerToken(request);
89
+ return token
90
+ ? 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)))
91
+ : Promise.reject(new common.UnauthorizedException(unauthorizedMessage));
92
+ }
93
+ };
94
+ JwtAuthGuard = JwtAuthGuard_1 = tslib.__decorate([
95
+ common.Injectable(),
96
+ tslib.__metadata("design:paramtypes", [core.Reflector,
97
+ jwt.JwtService])
98
+ ], JwtAuthGuard);
99
+ [core.Reflector, jwt.JwtService].forEach((token, index) => common.Inject(token)(JwtAuthGuard, undefined, index));
100
+ return JwtAuthGuard;
101
+ }
102
+
103
+ exports.createJwtAuthGuard = createJwtAuthGuard;
104
+ //# 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","SetMetadata","UnauthorizedException","TokenExpiredError","__decorate","Injectable","Reflector","JwtService","Inject"],"mappings":";;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CG;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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