@telperion/nest-pack 0.0.0-stage → 1.1.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 (60) hide show
  1. package/.build-manifest.json +106 -0
  2. package/LICENSE +21 -0
  3. package/README.md +207 -2
  4. package/access/access-guard-options.cjs +3 -0
  5. package/access/access-guard-options.cjs.map +1 -0
  6. package/access/access-guard-options.d.cts +96 -0
  7. package/access/access-guard-options.d.ts +96 -0
  8. package/access/access-guard-options.js +2 -0
  9. package/access/access-guard-options.js.map +1 -0
  10. package/access/create-access-guard.cjs +114 -0
  11. package/access/create-access-guard.cjs.map +1 -0
  12. package/access/create-access-guard.d.cts +51 -0
  13. package/access/create-access-guard.d.ts +51 -0
  14. package/access/create-access-guard.js +112 -0
  15. package/access/create-access-guard.js.map +1 -0
  16. package/access/index.cjs +8 -0
  17. package/access/index.cjs.map +1 -0
  18. package/access/index.d.cts +3 -0
  19. package/access/index.d.ts +3 -0
  20. package/access/index.js +2 -0
  21. package/access/index.js.map +1 -0
  22. package/fesm/nest-pack.mjs +112 -0
  23. package/fesm/nest-pack.mjs.map +1 -0
  24. package/index.cjs +8 -0
  25. package/index.cjs.map +1 -0
  26. package/index.d.cts +3 -0
  27. package/index.d.ts +3 -0
  28. package/index.js +2 -0
  29. package/index.js.map +1 -0
  30. package/package.json +181 -4
  31. package/pagination/index.cjs +10 -0
  32. package/pagination/index.cjs.map +1 -0
  33. package/pagination/index.d.cts +2 -0
  34. package/pagination/index.d.ts +2 -0
  35. package/pagination/index.js +3 -0
  36. package/pagination/index.js.map +1 -0
  37. package/pagination/page-query.cjs +92 -0
  38. package/pagination/page-query.cjs.map +1 -0
  39. package/pagination/page-query.d.cts +63 -0
  40. package/pagination/page-query.d.ts +63 -0
  41. package/pagination/page-query.js +90 -0
  42. package/pagination/page-query.js.map +1 -0
  43. package/pagination/page.cjs +48 -0
  44. package/pagination/page.cjs.map +1 -0
  45. package/pagination/page.d.cts +40 -0
  46. package/pagination/page.d.ts +40 -0
  47. package/pagination/page.js +46 -0
  48. package/pagination/page.js.map +1 -0
  49. package/validation/index.cjs +8 -0
  50. package/validation/index.cjs.map +1 -0
  51. package/validation/index.d.cts +1 -0
  52. package/validation/index.d.ts +1 -0
  53. package/validation/index.js +2 -0
  54. package/validation/index.js.map +1 -0
  55. package/validation/trim.cjs +40 -0
  56. package/validation/trim.cjs.map +1 -0
  57. package/validation/trim.d.cts +33 -0
  58. package/validation/trim.d.ts +33 -0
  59. package/validation/trim.js +38 -0
  60. package/validation/trim.js.map +1 -0
@@ -0,0 +1,106 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "nest-pack",
4
+ "version": "0.0.0",
5
+ "formats": [
6
+ "esm",
7
+ "cjs",
8
+ "dts",
9
+ "dcts",
10
+ "esmFlat"
11
+ ],
12
+ "entries": [
13
+ {
14
+ "name": "access/access-guard-options",
15
+ "sourcePath": "src/access/access-guard-options.ts",
16
+ "outputs": {
17
+ "esm": "access/access-guard-options.js",
18
+ "cjs": "access/access-guard-options.cjs",
19
+ "dts": "access/access-guard-options.d.ts",
20
+ "dcts": "access/access-guard-options.d.cts"
21
+ }
22
+ },
23
+ {
24
+ "name": "access/create-access-guard",
25
+ "sourcePath": "src/access/create-access-guard.ts",
26
+ "outputs": {
27
+ "esm": "access/create-access-guard.js",
28
+ "cjs": "access/create-access-guard.cjs",
29
+ "dts": "access/create-access-guard.d.ts",
30
+ "dcts": "access/create-access-guard.d.cts"
31
+ }
32
+ },
33
+ {
34
+ "name": "access/index",
35
+ "sourcePath": "src/access/index.ts",
36
+ "outputs": {
37
+ "esm": "access/index.js",
38
+ "cjs": "access/index.cjs",
39
+ "dts": "access/index.d.ts",
40
+ "dcts": "access/index.d.cts"
41
+ }
42
+ },
43
+ {
44
+ "name": "index",
45
+ "sourcePath": "src/index.ts",
46
+ "outputs": {
47
+ "esm": "index.js",
48
+ "esmFlat": "fesm/nest-pack.mjs",
49
+ "cjs": "index.cjs",
50
+ "dts": "index.d.ts",
51
+ "dcts": "index.d.cts"
52
+ }
53
+ },
54
+ {
55
+ "name": "pagination/index",
56
+ "sourcePath": "src/pagination/index.ts",
57
+ "outputs": {
58
+ "esm": "pagination/index.js",
59
+ "cjs": "pagination/index.cjs",
60
+ "dts": "pagination/index.d.ts",
61
+ "dcts": "pagination/index.d.cts"
62
+ }
63
+ },
64
+ {
65
+ "name": "pagination/page-query",
66
+ "sourcePath": "src/pagination/page-query.ts",
67
+ "outputs": {
68
+ "esm": "pagination/page-query.js",
69
+ "cjs": "pagination/page-query.cjs",
70
+ "dts": "pagination/page-query.d.ts",
71
+ "dcts": "pagination/page-query.d.cts"
72
+ }
73
+ },
74
+ {
75
+ "name": "pagination/page",
76
+ "sourcePath": "src/pagination/page.ts",
77
+ "outputs": {
78
+ "esm": "pagination/page.js",
79
+ "cjs": "pagination/page.cjs",
80
+ "dts": "pagination/page.d.ts",
81
+ "dcts": "pagination/page.d.cts"
82
+ }
83
+ },
84
+ {
85
+ "name": "validation/index",
86
+ "sourcePath": "src/validation/index.ts",
87
+ "outputs": {
88
+ "esm": "validation/index.js",
89
+ "cjs": "validation/index.cjs",
90
+ "dts": "validation/index.d.ts",
91
+ "dcts": "validation/index.d.cts"
92
+ }
93
+ },
94
+ {
95
+ "name": "validation/trim",
96
+ "sourcePath": "src/validation/trim.ts",
97
+ "outputs": {
98
+ "esm": "validation/trim.js",
99
+ "cjs": "validation/trim.cjs",
100
+ "dts": "validation/trim.d.ts",
101
+ "dcts": "validation/trim.d.cts"
102
+ }
103
+ }
104
+ ],
105
+ "generatedAt": "2026-12-01T11:22:52.238Z"
106
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Telperion Technology
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,208 @@
1
- # Temporary Holding Version
1
+ # @telperion/nest-pack
2
+ NestJS utilities: access guards, validation helpers and pagination
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ [![npm](https://img.shields.io/npm/v/@telperion/nest-pack.svg)](https://www.npmjs.com/package/@telperion/nest-pack)
5
+ [![npm](https://img.shields.io/npm/dm/@telperion/nest-pack.svg)](https://www.npmjs.com/package/@telperion/nest-pack)
6
+ [![codecov](https://codecov.io/gh/telperiontech/telperion/graph/badge.svg?token=dz46LY3onk&flag=nest-pack)](https://app.codecov.io/gh/telperiontech/telperion/tree/main?flags%5B0%5D=nest-pack)
7
+ [![npm](https://img.shields.io/npm/l/@telperion/nest-pack.svg)](https://github.com/telperiontech/telperion/blob/main/LICENSE)
8
+
9
+ The NestJS counterpart of [`@telperion/ng-pack`](../ng-pack).
10
+
11
+ ## Installation
12
+ * npm: `npm install @telperion/nest-pack --save`
13
+ * yarn: `yarn add @telperion/nest-pack`
14
+ * pnpm: `pnpm i -S @telperion/nest-pack`
15
+
16
+ Requires `@nestjs/common` and `@nestjs/core` (11 or 12).
17
+
18
+ ## Entry points
19
+
20
+ | Import path | Contents | Extra requirements |
21
+ | --- | --- | --- |
22
+ | `@telperion/nest-pack` | `createAccessGuard` | |
23
+ | `@telperion/nest-pack/access` | `createAccessGuard` | |
24
+ | `@telperion/nest-pack/validation` | `Trim` | `class-transformer` (optional peer dependency); usually with `class-validator` |
25
+ | `@telperion/nest-pack/pagination` | `PageQuery`, `Page` | `class-transformer` and `class-validator` (optional peer dependencies) |
26
+
27
+ The root entry point does not include `validation` or `pagination`, so projects without class-transformer or class-validator are not affected.
28
+
29
+ ## Access
30
+
31
+ ### Create Access Guard
32
+ Creates a guard for routes about one entity, e.g. a project in `/projects/:projectId/...`. The guard resolves the caller's access to the entity in a route parameter, then checks the route's requirements:
33
+
34
+ - malformed parameter (`validate`), or no access (`resolve` gives `null` or `undefined`): **404**, so callers can't probe which ids exist
35
+ - access that does not meet every requirement of the route (`allows`): **403**
36
+ - otherwise the request passes, and the access is kept on the request
37
+
38
+ ```typescript
39
+ import { createAccessGuard } from '@telperion/nest-pack/access';
40
+ import { isUUID } from 'class-validator';
41
+
42
+ export const ProjectAccessGuard = createAccessGuard({
43
+ param: 'projectId', // the route parameter
44
+ validate: isUUID, // malformed ids answer 404 without a lookup
45
+ inject: [ProjectAccessService], // providers passed to resolve, like a factory provider's inject
46
+ resolve: (projectId, request: AuthenticatedRequest, access) => request.actor && access.of(request.actor, projectId),
47
+ allows: (access, permission: ProjectPermission) => access.permissions.has(permission),
48
+ notFound: 'Project not found', // default 'Not Found'
49
+ forbidden: 'Missing project permission', // default 'Forbidden'
50
+ });
51
+
52
+ @Controller('projects/:projectId/items')
53
+ @ProjectAccessGuard.require('project.view') // controller-wide requirements
54
+ export class ItemsController {
55
+ @Post()
56
+ @ProjectAccessGuard.require('items.edit') // replaces the controller's requirements
57
+ create(@ProjectAccessGuard.access() access: ProjectAccess, @Body() body: CreateItemDto) {
58
+ // access: what resolve returned for this request
59
+ }
60
+ }
61
+ ```
62
+
63
+ The guard class has:
64
+ - `require(...requirements)`: route or controller decorator that applies the guard (`UseGuards`) and sets the requirements (`SetMetadata`). A method's requirements replace its controller's; with no requirements any resolved access passes
65
+ - `access()`: parameter decorator giving the resolved access. It throws (500) on routes without the guard
66
+ - `accessOf(request)`: the resolved access of a request, e.g. in an interceptor; `undefined` when the guard did not let it through
67
+
68
+ Types are inferred: `require` accepts only the `allows` requirement type, and the `inject` providers arrive typed in `resolve` (string and symbol tokens arrive as `unknown`; annotate those parameters).
69
+
70
+ Nest creates the guard in the module of the controller using it, so its `inject` providers must be available there. To give the guard its own class name, extend it:
71
+
72
+ ```typescript
73
+ @Injectable()
74
+ export class ProjectAccessGuard extends createAccessGuard({ /* ... */ }) {}
75
+ ```
76
+
77
+ HTTP only: the guard reads `request.params`, or the body or query string (see below).
78
+
79
+ #### Reading the id from the body or query string
80
+
81
+ `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:
82
+
83
+ ```typescript
84
+ export const ProjectMemberGuard = createAccessGuard({
85
+ param: 'projectId',
86
+ from: ['params', 'body'], // /projects/:projectId/..., or { "projectId": "..." } in the body
87
+ validate: isUUID,
88
+ inject: [ProjectsService],
89
+ resolve: (projectId, request: AuthenticatedRequest, projects) => projects.membershipOf(request.user, projectId),
90
+ allows: () => true,
91
+ });
92
+ ```
93
+
94
+ 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.
95
+
96
+ #### Example: two guards, a few lines each
97
+
98
+ A project guard, where the access is an object with permissions and only the owner of the token's actor may see the project:
99
+
100
+ ```typescript
101
+ export const ProjectAccessGuard = createAccessGuard({
102
+ param: 'projectId',
103
+ validate: isUUID,
104
+ inject: [ProjectAccessService],
105
+ resolve: (projectId, request: AuthenticatedRequest, access) => request.actor && access.of(request.actor, projectId),
106
+ allows: (access, permission: ProjectPermission) => access.permissions.has(permission),
107
+ notFound: 'Project not found',
108
+ forbidden: 'Missing project permission',
109
+ });
110
+ ```
111
+
112
+ An organization guard, where the access is the set of permissions a user holds in the organization, checked against the database instead of the token:
113
+
114
+ ```typescript
115
+ export const OrgAccessGuard = createAccessGuard({
116
+ param: 'orgId',
117
+ validate: isUUID,
118
+ inject: [OrganizationsService],
119
+ resolve: (orgId, request: AuthenticatedRequest, organizations) =>
120
+ request.actor?.type === 'user' ? organizations.permissionsIn(request.actor.id, orgId) : null,
121
+ allows: (held, permission: OrgPermission) => held.has(permission),
122
+ notFound: 'Organization not found',
123
+ forbidden: 'Missing organization permission',
124
+ });
125
+ ```
126
+
127
+ Each replaces a hand-written guard class with the same steps: reading the metadata, checking the parameter, the 404 and 403 answers, and the parameter decorator.
128
+
129
+ ## Validation
130
+
131
+ ### Trim
132
+ A class-transformer decorator that trims string values when a plain object becomes a DTO, so `' '` fails `@IsNotEmpty()` and `' a@example.com '` passes `@IsEmail()`. Other values pass unchanged.
133
+
134
+ ```typescript
135
+ import { Trim } from '@telperion/nest-pack/validation';
136
+ import { IsNotEmpty, MaxLength } from 'class-validator';
137
+
138
+ export class CreateProjectDto {
139
+ @Trim()
140
+ @IsNotEmpty()
141
+ @MaxLength(80)
142
+ name!: string;
143
+ }
144
+
145
+ app.useGlobalPipes(new ValidationPipe({ transform: true }));
146
+ ```
147
+
148
+ `ValidationPipe` validates the transformed DTO either way; its `transform` option makes the handler receive the trimmed values too.
149
+
150
+ ## Pagination
151
+
152
+ ### Page Query
153
+ The query DTO of a paged list endpoint (`?page=2&pageSize=50&search=ada`), with class-validator and class-transformer decorators:
154
+
155
+ | Property | Rules | Default |
156
+ | --- | --- | --- |
157
+ | `page` | integer, at least 1 | `1` |
158
+ | `pageSize` | integer from 1 to 100 | `25` |
159
+ | `search` | optional string, at most 200 characters | |
160
+
161
+ Query values arrive as strings; `@Type(() => Number)` converts them, so use it with `ValidationPipe({ transform: true })`. Missing values keep their defaults.
162
+
163
+ Two static helpers go with it:
164
+ - `PageQuery.skipTake(query)`: `{ skip, take }` for the page, as TypeORM's and Prisma's options
165
+ - `PageQuery.likePattern(search)`: a `LIKE`/`ILIKE` pattern that contains the search text literally: `\`, `%` and `_` are escaped with `\`, and the text is wrapped in `%`
166
+
167
+ ### Page
168
+ The response of a paged list endpoint: `{ items, total, page, pageSize }`. `Page.of(items, total, query)` creates it.
169
+
170
+ ```typescript
171
+ import { Page, PageQuery } from '@telperion/nest-pack/pagination';
172
+
173
+ @Controller('users')
174
+ export class UsersController {
175
+ @Get()
176
+ async list(@Query() query: PageQuery): Promise<Page<User>> {
177
+ const [items, total] = await this.users.findAndCount({
178
+ where: query.search ? { name: ILike(PageQuery.likePattern(query.search)) } : {},
179
+ order: { name: 'ASC' },
180
+ ...PageQuery.skipTake(query),
181
+ });
182
+
183
+ return Page.of(items, total, query);
184
+ }
185
+ }
186
+ ```
187
+
188
+ Extend `PageQuery` to add filters, or to redeclare a property with other limits:
189
+
190
+ ```typescript
191
+ export class UserPageQuery extends PageQuery {
192
+ @IsOptional()
193
+ @IsIn(['active', 'invited'])
194
+ status?: 'active' | 'invited';
195
+ }
196
+ ```
197
+
198
+ #### Swagger
199
+
200
+ The package does not depend on `@nestjs/swagger`, so the properties carry no `@ApiProperty` decorators. Either:
201
+ - 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
202
+ - extend `PageQuery` and redeclare the properties with `@ApiPropertyOptional(...)` next to their validators.
203
+
204
+ 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 })`.
205
+
206
+ ## License
207
+
208
+ [MIT](./LICENSE)
@@ -0,0 +1,3 @@
1
+ 'use strict';
2
+
3
+ //# sourceMappingURL=access-guard-options.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access-guard-options.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
@@ -0,0 +1,96 @@
1
+ import { InjectionToken, Type, CanActivate } from '@nestjs/common';
2
+
3
+ /**
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})
9
+ */
10
+ interface AccessGuardRequest {
11
+ params?: Record<string, unknown>;
12
+ body?: unknown;
13
+ query?: unknown;
14
+ }
15
+ /**
16
+ * The instances of the injection tokens in {@link AccessGuardOptions.inject}, in order:
17
+ * class tokens give their instance type, string and symbol tokens give `unknown` (annotate those parameters)
18
+ */
19
+ type InjectedDependencies<Tokens extends readonly InjectionToken[]> = {
20
+ -readonly [Index in keyof Tokens]: Tokens[Index] extends abstract new (...args: never) => infer Instance ? Instance : unknown;
21
+ };
22
+ /**
23
+ * Options of {@link createAccessGuard}
24
+ */
25
+ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> {
26
+ /**
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.
29
+ */
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[];
39
+ /**
40
+ * Checks the parameter's format before `resolve` runs, e.g. `isUUID` from class-validator.
41
+ * Malformed values answer 404 without a lookup.
42
+ *
43
+ * @default accepts every string
44
+ */
45
+ validate?: (value: string) => boolean;
46
+ /**
47
+ * Providers `resolve` receives after the request, like `inject` of a factory provider
48
+ */
49
+ inject?: Tokens;
50
+ /**
51
+ * Resolves the caller's access to what the parameter identifies; `null` or `undefined` when there is none
52
+ * (no such entity, or the caller may not see it), which answers 404
53
+ *
54
+ * @param value The parameter, after `validate`
55
+ * @param request The HTTP request, e.g. with the authenticated user
56
+ * @param dependencies The instances of the `inject` tokens
57
+ */
58
+ resolve: (value: string, request: Request, ...dependencies: InjectedDependencies<Tokens>) => Access | null | undefined | Promise<Access | null | undefined>;
59
+ /**
60
+ * Whether the access meets one requirement of the route, e.g. holds a permission. A route passes when the access meets all of them.
61
+ */
62
+ allows: (access: Access, requirement: Requirement) => boolean;
63
+ /**
64
+ * Message of the 404 answer
65
+ *
66
+ * @default 'Not Found'
67
+ */
68
+ notFound?: string;
69
+ /**
70
+ * Message of the 403 answer
71
+ *
72
+ * @default 'Forbidden'
73
+ */
74
+ forbidden?: string;
75
+ }
76
+ /**
77
+ * The guard class {@link createAccessGuard} returns
78
+ */
79
+ interface AccessGuardType<Access, Requirement> extends Type<CanActivate> {
80
+ /**
81
+ * Route or controller decorator: applies the guard and sets the requirements of the route.
82
+ * A method's requirements replace its controller's. Without requirements, any resolved access passes.
83
+ */
84
+ require(...requirements: Requirement[]): MethodDecorator & ClassDecorator;
85
+ /**
86
+ * Parameter decorator: the access the guard resolved for this request.
87
+ * Throws when the route does not use the guard.
88
+ */
89
+ access(...pipes: unknown[]): ParameterDecorator;
90
+ /**
91
+ * The access the guard resolved for a request, or `undefined` before the guard ran or when it did not let the request through
92
+ */
93
+ accessOf(request: object): Access | undefined;
94
+ }
95
+
96
+ export type { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies };
@@ -0,0 +1,96 @@
1
+ import { InjectionToken, Type, CanActivate } from '@nestjs/common';
2
+
3
+ /**
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})
9
+ */
10
+ interface AccessGuardRequest {
11
+ params?: Record<string, unknown>;
12
+ body?: unknown;
13
+ query?: unknown;
14
+ }
15
+ /**
16
+ * The instances of the injection tokens in {@link AccessGuardOptions.inject}, in order:
17
+ * class tokens give their instance type, string and symbol tokens give `unknown` (annotate those parameters)
18
+ */
19
+ type InjectedDependencies<Tokens extends readonly InjectionToken[]> = {
20
+ -readonly [Index in keyof Tokens]: Tokens[Index] extends abstract new (...args: never) => infer Instance ? Instance : unknown;
21
+ };
22
+ /**
23
+ * Options of {@link createAccessGuard}
24
+ */
25
+ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> {
26
+ /**
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.
29
+ */
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[];
39
+ /**
40
+ * Checks the parameter's format before `resolve` runs, e.g. `isUUID` from class-validator.
41
+ * Malformed values answer 404 without a lookup.
42
+ *
43
+ * @default accepts every string
44
+ */
45
+ validate?: (value: string) => boolean;
46
+ /**
47
+ * Providers `resolve` receives after the request, like `inject` of a factory provider
48
+ */
49
+ inject?: Tokens;
50
+ /**
51
+ * Resolves the caller's access to what the parameter identifies; `null` or `undefined` when there is none
52
+ * (no such entity, or the caller may not see it), which answers 404
53
+ *
54
+ * @param value The parameter, after `validate`
55
+ * @param request The HTTP request, e.g. with the authenticated user
56
+ * @param dependencies The instances of the `inject` tokens
57
+ */
58
+ resolve: (value: string, request: Request, ...dependencies: InjectedDependencies<Tokens>) => Access | null | undefined | Promise<Access | null | undefined>;
59
+ /**
60
+ * Whether the access meets one requirement of the route, e.g. holds a permission. A route passes when the access meets all of them.
61
+ */
62
+ allows: (access: Access, requirement: Requirement) => boolean;
63
+ /**
64
+ * Message of the 404 answer
65
+ *
66
+ * @default 'Not Found'
67
+ */
68
+ notFound?: string;
69
+ /**
70
+ * Message of the 403 answer
71
+ *
72
+ * @default 'Forbidden'
73
+ */
74
+ forbidden?: string;
75
+ }
76
+ /**
77
+ * The guard class {@link createAccessGuard} returns
78
+ */
79
+ interface AccessGuardType<Access, Requirement> extends Type<CanActivate> {
80
+ /**
81
+ * Route or controller decorator: applies the guard and sets the requirements of the route.
82
+ * A method's requirements replace its controller's. Without requirements, any resolved access passes.
83
+ */
84
+ require(...requirements: Requirement[]): MethodDecorator & ClassDecorator;
85
+ /**
86
+ * Parameter decorator: the access the guard resolved for this request.
87
+ * Throws when the route does not use the guard.
88
+ */
89
+ access(...pipes: unknown[]): ParameterDecorator;
90
+ /**
91
+ * The access the guard resolved for a request, or `undefined` before the guard ran or when it did not let the request through
92
+ */
93
+ accessOf(request: object): Access | undefined;
94
+ }
95
+
96
+ export type { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies };
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=access-guard-options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access-guard-options.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,114 @@
1
+ 'use strict';
2
+
3
+ var tslib = require('tslib');
4
+ var common = require('@nestjs/common');
5
+ var core = require('@nestjs/core');
6
+
7
+ /**
8
+ * #### Create Access Guard
9
+ *
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 (or a body field or query parameter, see `from`)
12
+ * and checks the route's requirements:
13
+ *
14
+ * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
15
+ * so callers can't probe which ids exist
16
+ * - access that does not meet every requirement of the route (see `allows`): **403**
17
+ * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
18
+ *
19
+ * `resolve` receives the `inject` providers, like a factory provider's `useFactory`, so the guard works
20
+ * with Nest's dependency injection: provide it where its dependencies are (e.g. in the module of the controllers using it).
21
+ * HTTP only.
22
+ *
23
+ * * * *
24
+ * Example:
25
+ * ```typescript
26
+ * import { createAccessGuard } from '@telperion/nest-pack/access';
27
+ * import { isUUID } from 'class-validator';
28
+ *
29
+ * export const ProjectAccessGuard = createAccessGuard({
30
+ * param: 'projectId',
31
+ * validate: isUUID,
32
+ * inject: [ProjectAccessService],
33
+ * resolve: (projectId, request: AuthenticatedRequest, access) => request.user && access.of(request.user, projectId),
34
+ * allows: (access, permission: ProjectPermission) => access.permissions.has(permission),
35
+ * notFound: 'Project not found',
36
+ * });
37
+ *
38
+ * @Controller('projects/:projectId/items')
39
+ * export class ItemsController {
40
+ * @Post()
41
+ * @ProjectAccessGuard.require('items.edit')
42
+ * create(@ProjectAccessGuard.access() access: ProjectAccess, @Body() body: CreateItemDto) {}
43
+ * }
44
+ * ```
45
+ *
46
+ * To give the guard a class name of its own (in stack traces, or to inject it), extend it:
47
+ * `@Injectable() export class ProjectAccessGuard extends createAccessGuard({ ... }) {}`.
48
+ * * * *
49
+ * @param options Which parameter to read, how to resolve the access, and how to check a requirement
50
+ * @returns An injectable guard class with `require()`, `access()` and `accessOf()`
51
+ */
52
+ function createAccessGuard(options) {
53
+ var AccessGuard_1;
54
+ const { param, from = 'params', validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
55
+ const sources = typeof from === 'string' ? [from] : from;
56
+ const requirementsKey = Symbol(`access-guard:${param}:requirements`);
57
+ const accessKey = Symbol(`access-guard:${param}:access`);
58
+ let AccessGuard = class AccessGuard {
59
+ static { AccessGuard_1 = this; }
60
+ static access = common.createParamDecorator((_data, context) => AccessGuard_1.accessOf(context.switchToHttp().getRequest()) ?? AccessGuard_1.notGuarded());
61
+ reflector;
62
+ dependencies;
63
+ /**
64
+ * @param injected The `Reflector`, then the `inject` providers
65
+ */
66
+ constructor(...injected) {
67
+ const [reflector, ...dependencies] = injected;
68
+ this.reflector = reflector;
69
+ this.dependencies = dependencies;
70
+ }
71
+ static require(...requirements) {
72
+ return common.applyDecorators(common.SetMetadata(requirementsKey, requirements), common.UseGuards(this));
73
+ }
74
+ static accessOf(request) {
75
+ return request[accessKey];
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
+ }
86
+ static notGuarded() {
87
+ throw new Error(`The access of :${param} is read on a route without its access guard; add \`.require()\` to the route or controller`);
88
+ }
89
+ canActivate(context) {
90
+ const request = context.switchToHttp().getRequest();
91
+ const value = AccessGuard_1.idOf(request);
92
+ const required = this.reflector.getAllAndOverride(requirementsKey, [context.getHandler(), context.getClass()]) ?? [];
93
+ return Promise.resolve(typeof value === 'string' && validate(value) ? resolve(value, request, ...this.dependencies) : null).then(access => {
94
+ if (access === null || access === undefined) {
95
+ throw new common.NotFoundException(notFound);
96
+ }
97
+ if (!required.every(requirement => allows(access, requirement))) {
98
+ throw new common.ForbiddenException(forbidden);
99
+ }
100
+ Object.assign(request, { [accessKey]: access });
101
+ return true;
102
+ });
103
+ }
104
+ };
105
+ AccessGuard = AccessGuard_1 = tslib.__decorate([
106
+ common.Injectable(),
107
+ tslib.__metadata("design:paramtypes", [Object])
108
+ ], AccessGuard);
109
+ [core.Reflector, ...inject].forEach((token, index) => common.Inject(token)(AccessGuard, undefined, index));
110
+ return AccessGuard;
111
+ }
112
+
113
+ exports.createAccessGuard = createAccessGuard;
114
+ //# sourceMappingURL=create-access-guard.cjs.map
@@ -0,0 +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":"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"}