@telperion/nest-pack 1.2.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -132,5 +132,5 @@
132
132
  }
133
133
  }
134
134
  ],
135
- "generatedAt": "2026-12-01T16:45:38.292Z"
135
+ "generatedAt": "2026-12-02T20:07:17.076Z"
136
136
  }
package/README.md CHANGED
@@ -21,7 +21,7 @@ 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
+ | `@telperion/nest-pack/auth` | `createJwtAuthGuard` | `@nestjs/jwt` 11 or 12 (optional peer dependency), unless the guard has a `verifier` |
25
25
  | `@telperion/nest-pack/validation` | `Trim` | `class-transformer` (optional peer dependency); usually with `class-validator` |
26
26
  | `@telperion/nest-pack/pagination` | `PageQuery`, `Page` | `class-transformer` and `class-validator` (optional peer dependencies) |
27
27
 
@@ -31,7 +31,7 @@ The root entry point does not include `auth`, `validation` or `pagination`, so p
31
31
 
32
32
  ### Create JWT Auth Guard
33
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.
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` in the app, or with a verifier of your own (see [Verifying with your own verifier](#verifying-with-your-own-verifier)).
35
35
 
36
36
  ```typescript
37
37
  import { createJwtAuthGuard } from '@telperion/nest-pack/auth';
@@ -59,26 +59,99 @@ export class HuddlesController {
59
59
 
60
60
  | Request | Answer |
61
61
  | --- | --- |
62
- | route or controller with `@AuthGuard.public()` | passes, without verifying any token |
62
+ | route or controller with `@AuthGuard.public()` | passes, without verifying any token (see [`publicRoutes`](#optional-users-on-public-routes)) |
63
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 |
64
+ | expired token (see `isExpired`) | **401** `expiredMessage` (`'TokenExpired'`), so clients can renew the token and retry |
65
65
  | valid token | passes; the payload is on `request.user`, `@AuthGuard.user()` and `AuthGuard.userOf(request)` |
66
66
 
67
+ Markers are per guard: `AuthGuard.isPublic()` reads only the `public()` markers of `AuthGuard`.
68
+
67
69
  **Options** (all optional):
68
70
 
69
71
  - `extract(request)` — reads the token; default: `Authorization: Bearer <token>` (scheme case-insensitive)
70
- - `verifyOptions` — options of `JwtService.verifyAsync`, e.g. `audience`, `issuer`
72
+ - `verifyOptions` — options of `JwtService.verifyAsync`, e.g. `audience`, `issuer`; only without a `verifier`
73
+ - `verifier` — the injection token of a verifier of your own, in place of the `JwtService`
74
+ - `isExpired(error)` — whether a verification error means an expired token; default: jsonwebtoken's (`error.name === 'TokenExpiredError'`) and jose's (`error.code === 'ERR_JWT_EXPIRED'`) errors
75
+ - `publicRoutes` — `'skip'` (default) or `'optional'`, see below
71
76
  - `expiredMessage`, `unauthorizedMessage` — messages of the 401 answers
72
77
  - `property` — the request property the payload is written to (default `'user'`, where Passport and most code expect it)
73
78
 
79
+ **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.
80
+
81
+ ```typescript
82
+ @Injectable()
83
+ export class CurrentUserInterceptor implements NestInterceptor {
84
+ intercept(context: ExecutionContext, next: CallHandler) {
85
+ return AuthGuard.isPublic(context) ? next.handle() : this.users.resolve(context).pipe(switchMap(() => next.handle()));
86
+ }
87
+ }
88
+ ```
89
+
74
90
  With `@telperion/ng-pack/http`, detect the expired answer in `ApiAuth.expired`: `error => error.status === 401 && error.error?.message === 'TokenExpired'`.
75
91
 
92
+ #### Verifying with your own verifier
93
+
94
+ Services that verify tokens otherwise, e.g. against a JWKS with [jose](https://github.com/panva/jose), provide an object with `verify(token, request)` and pass its injection token as `verifier`. `verify` returns the payload (or a promise of it) and throws or rejects for invalid tokens. With a `verifier` the guard never asks for the `JwtService`, so `@nestjs/jwt` need not be installed.
95
+
96
+ ```typescript
97
+ import { createJwtAuthGuard, type JwtAuthGuardVerifier } from '@telperion/nest-pack/auth';
98
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
99
+
100
+ const JWKS_VERIFIER = Symbol('jwks-verifier');
101
+ const jwks = createRemoteJWKSet(new URL('https://auth.example.com/.well-known/jwks.json'));
102
+
103
+ export const AuthGuard = createJwtAuthGuard<TokenPayload>({ verifier: JWKS_VERIFIER });
104
+
105
+ @Module({
106
+ providers: [
107
+ {
108
+ provide: JWKS_VERIFIER,
109
+ useValue: {
110
+ verify: token => jwtVerify<TokenPayload>(token, jwks, { issuer: 'https://auth.example.com' }).then(({ payload }) => payload),
111
+ } satisfies JwtAuthGuardVerifier<TokenPayload>,
112
+ },
113
+ { provide: APP_GUARD, useClass: AuthGuard },
114
+ ],
115
+ })
116
+ export class AppModule {}
117
+ ```
118
+
119
+ `verifyOptions` are options of the `JwtService` only: give the verifier its own options instead. Passing both is a type error, and `createJwtAuthGuard` throws at runtime. jose's expired error (`ERR_JWT_EXPIRED`) answers `expiredMessage` like jsonwebtoken's `TokenExpiredError`; for other libraries pass `isExpired`.
120
+
121
+ Without a `verifier`, the guard resolves the `JwtService` through `ModuleRef` across the whole app at the first request, so `@nestjs/jwt` is loaded only then. With several `JwtModule` registrations, Nest's lookup returns the last registered one; to pin one, pass a `verifier` that wraps it (`{ verify: token => jwt.verifyAsync(token) }`).
122
+
123
+ #### Optional users on public routes
124
+
125
+ With `publicRoutes: 'optional'`, public routes still read the token, so the handler knows the caller when there is one:
126
+
127
+ ```typescript
128
+ export const AuthGuard = createJwtAuthGuard<TokenPayload>({ publicRoutes: 'optional' });
129
+
130
+ @Controller('feed')
131
+ export class FeedController {
132
+ @Get()
133
+ @AuthGuard.public()
134
+ feed(@AuthGuard.user() user: TokenPayload | undefined) {
135
+ // user: the payload of a valid token, or undefined
136
+ }
137
+ }
138
+ ```
139
+
140
+ | Request on a public route | `'skip'` (default) | `'optional'` |
141
+ | --- | --- | --- |
142
+ | no token | passes, no user | passes, no user |
143
+ | valid token | passes, no user | passes; the payload is on `request.user`, `@AuthGuard.user()` and `userOf` |
144
+ | invalid or expired token | passes, no user | passes as anonymous (no 401) |
145
+
146
+ Routes without `public()` behave the same in both modes.
147
+
76
148
  ## Access
77
149
 
78
150
  ### Create Access Guard
79
- 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:
151
+ 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 (or a fixed or computed `id`), then checks the route's requirements:
80
152
 
81
- - malformed parameter (`validate`), or no access (`resolve` gives `null` or `undefined`): **404**, so callers can't probe which ids exist
153
+ - missing or malformed parameter (`validate`): **404**
154
+ - no access (`resolve` gives `null` or `undefined`): **404**, so callers can't probe which ids exist (or **403**, see `noAccess`)
82
155
  - access that does not meet every requirement of the route (`allows`): **403**
83
156
  - otherwise the request passes, and the access is kept on the request
84
157
 
@@ -140,6 +213,33 @@ export const ProjectMemberGuard = createAccessGuard({
140
213
 
141
214
  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.
142
215
 
216
+ #### A fixed or computed id
217
+
218
+ Services bound to one entity, e.g. only the `'botc'` group, pass `id` in place of `param`: a string, or a function computing the id from the request.
219
+
220
+ ```typescript
221
+ export const GroupAccessGuard = createAccessGuard({
222
+ id: 'botc', // or: request => request.user?.groupSlug
223
+ inject: [GroupsService],
224
+ resolve: (slug, request: AuthenticatedRequest, groups) => groups.membershipOf(request.user, slug),
225
+ allows: (membership, permission: GroupPermission) => membership.permissions.has(permission),
226
+ });
227
+ ```
228
+
229
+ Give exactly one of `param` and `id` (a type error otherwise, and `createAccessGuard` throws); `from` goes only with `param`. A function returning `null` or `undefined` answers **404**, like a missing parameter, and `validate` checks its result too.
230
+
231
+ #### 403 instead of 404
232
+
233
+ The 404 for "no access" hides which ids exist. When the entities are public anyway (e.g. group slugs), `noAccess: 'forbidden'` answers **403** `forbidden` when `resolve` finds no access. A missing or malformed id still answers 404.
234
+
235
+ ```typescript
236
+ export const GroupAccessGuard = createAccessGuard({
237
+ param: 'slug',
238
+ noAccess: 'forbidden', // default 'not-found'
239
+ // ...
240
+ });
241
+ ```
242
+
143
243
  #### Example: two guards, a few lines each
144
244
 
145
245
  A project guard, where the access is an object with permissions and only the owner of the token's actor may see the project:
@@ -20,9 +20,14 @@ type InjectedDependencies<Tokens extends readonly InjectionToken[]> = {
20
20
  -readonly [Index in keyof Tokens]: Tokens[Index] extends abstract new (...args: never) => infer Instance ? Instance : unknown;
21
21
  };
22
22
  /**
23
- * Options of {@link createAccessGuard}
23
+ * What an access guard answers when `resolve` finds no access: **404** (`'not-found'`), so callers can't probe which ids
24
+ * exist, or **403** (`'forbidden'`) for entities whose existence is public anyway
24
25
  */
25
- interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> {
26
+ type AccessGuardNoAccess = 'not-found' | 'forbidden';
27
+ /**
28
+ * An access guard reading the id from a request parameter
29
+ */
30
+ interface AccessGuardParamOptions {
26
31
  /**
27
32
  * The parameter holding the id of what is accessed, e.g. `'projectId'` for `/projects/:projectId/items`.
28
33
  * By default a route parameter; see `from` to read a body field or query parameter of that name.
@@ -36,8 +41,26 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
36
41
  * @default 'params'
37
42
  */
38
43
  from?: AccessGuardSource | readonly AccessGuardSource[];
44
+ id?: never;
45
+ }
46
+ /**
47
+ * An access guard with a fixed or computed id
48
+ */
49
+ interface AccessGuardIdOptions<Request> {
39
50
  /**
40
- * Checks the parameter's format before `resolve` runs, e.g. `isUUID` from class-validator.
51
+ * The id of what is accessed: fixed, for services bound to one entity (e.g. `'botc'`), or computed from the request.
52
+ * A computed `null` or `undefined` answers 404, like a missing parameter.
53
+ */
54
+ id: string | ((request: Request) => string | null | undefined);
55
+ param?: never;
56
+ from?: never;
57
+ }
58
+ /**
59
+ * The options of {@link createAccessGuard} besides where the id comes from
60
+ */
61
+ interface AccessGuardBaseOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> {
62
+ /**
63
+ * Checks the id's format before `resolve` runs, e.g. `isUUID` from class-validator.
41
64
  * Malformed values answer 404 without a lookup.
42
65
  *
43
66
  * @default accepts every string
@@ -48,10 +71,10 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
48
71
  */
49
72
  inject?: Tokens;
50
73
  /**
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
74
+ * Resolves the caller's access to what the id identifies; `null` or `undefined` when there is none
75
+ * (no such entity, or the caller may not see it), which answers 404 (see `noAccess`)
53
76
  *
54
- * @param value The parameter, after `validate`
77
+ * @param value The id, after `validate`
55
78
  * @param request The HTTP request, e.g. with the authenticated user
56
79
  * @param dependencies The instances of the `inject` tokens
57
80
  */
@@ -60,6 +83,12 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
60
83
  * 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
84
  */
62
85
  allows: (access: Access, requirement: Requirement) => boolean;
86
+ /**
87
+ * The answer when `resolve` finds no access; a missing or malformed id answers 404 either way
88
+ *
89
+ * @default 'not-found'
90
+ */
91
+ noAccess?: AccessGuardNoAccess;
63
92
  /**
64
93
  * Message of the 404 answer
65
94
  *
@@ -73,6 +102,10 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
73
102
  */
74
103
  forbidden?: string;
75
104
  }
105
+ /**
106
+ * Options of {@link createAccessGuard}: where the id comes from (`param` or `id`), how to resolve the access, and how to check a requirement
107
+ */
108
+ type AccessGuardOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> = AccessGuardBaseOptions<Access, Requirement, Request, Tokens> & (AccessGuardParamOptions | AccessGuardIdOptions<Request>);
76
109
  /**
77
110
  * The guard class {@link createAccessGuard} returns
78
111
  */
@@ -93,4 +126,4 @@ interface AccessGuardType<Access, Requirement> extends Type<CanActivate> {
93
126
  accessOf(request: object): Access | undefined;
94
127
  }
95
128
 
96
- export type { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies };
129
+ export type { AccessGuardBaseOptions, AccessGuardIdOptions, AccessGuardNoAccess, AccessGuardOptions, AccessGuardParamOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies };
@@ -20,9 +20,14 @@ type InjectedDependencies<Tokens extends readonly InjectionToken[]> = {
20
20
  -readonly [Index in keyof Tokens]: Tokens[Index] extends abstract new (...args: never) => infer Instance ? Instance : unknown;
21
21
  };
22
22
  /**
23
- * Options of {@link createAccessGuard}
23
+ * What an access guard answers when `resolve` finds no access: **404** (`'not-found'`), so callers can't probe which ids
24
+ * exist, or **403** (`'forbidden'`) for entities whose existence is public anyway
24
25
  */
25
- interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> {
26
+ type AccessGuardNoAccess = 'not-found' | 'forbidden';
27
+ /**
28
+ * An access guard reading the id from a request parameter
29
+ */
30
+ interface AccessGuardParamOptions {
26
31
  /**
27
32
  * The parameter holding the id of what is accessed, e.g. `'projectId'` for `/projects/:projectId/items`.
28
33
  * By default a route parameter; see `from` to read a body field or query parameter of that name.
@@ -36,8 +41,26 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
36
41
  * @default 'params'
37
42
  */
38
43
  from?: AccessGuardSource | readonly AccessGuardSource[];
44
+ id?: never;
45
+ }
46
+ /**
47
+ * An access guard with a fixed or computed id
48
+ */
49
+ interface AccessGuardIdOptions<Request> {
39
50
  /**
40
- * Checks the parameter's format before `resolve` runs, e.g. `isUUID` from class-validator.
51
+ * The id of what is accessed: fixed, for services bound to one entity (e.g. `'botc'`), or computed from the request.
52
+ * A computed `null` or `undefined` answers 404, like a missing parameter.
53
+ */
54
+ id: string | ((request: Request) => string | null | undefined);
55
+ param?: never;
56
+ from?: never;
57
+ }
58
+ /**
59
+ * The options of {@link createAccessGuard} besides where the id comes from
60
+ */
61
+ interface AccessGuardBaseOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> {
62
+ /**
63
+ * Checks the id's format before `resolve` runs, e.g. `isUUID` from class-validator.
41
64
  * Malformed values answer 404 without a lookup.
42
65
  *
43
66
  * @default accepts every string
@@ -48,10 +71,10 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
48
71
  */
49
72
  inject?: Tokens;
50
73
  /**
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
74
+ * Resolves the caller's access to what the id identifies; `null` or `undefined` when there is none
75
+ * (no such entity, or the caller may not see it), which answers 404 (see `noAccess`)
53
76
  *
54
- * @param value The parameter, after `validate`
77
+ * @param value The id, after `validate`
55
78
  * @param request The HTTP request, e.g. with the authenticated user
56
79
  * @param dependencies The instances of the `inject` tokens
57
80
  */
@@ -60,6 +83,12 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
60
83
  * 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
84
  */
62
85
  allows: (access: Access, requirement: Requirement) => boolean;
86
+ /**
87
+ * The answer when `resolve` finds no access; a missing or malformed id answers 404 either way
88
+ *
89
+ * @default 'not-found'
90
+ */
91
+ noAccess?: AccessGuardNoAccess;
63
92
  /**
64
93
  * Message of the 404 answer
65
94
  *
@@ -73,6 +102,10 @@ interface AccessGuardOptions<Access, Requirement, Request extends AccessGuardReq
73
102
  */
74
103
  forbidden?: string;
75
104
  }
105
+ /**
106
+ * Options of {@link createAccessGuard}: where the id comes from (`param` or `id`), how to resolve the access, and how to check a requirement
107
+ */
108
+ type AccessGuardOptions<Access, Requirement, Request extends AccessGuardRequest, Tokens extends readonly InjectionToken[]> = AccessGuardBaseOptions<Access, Requirement, Request, Tokens> & (AccessGuardParamOptions | AccessGuardIdOptions<Request>);
76
109
  /**
77
110
  * The guard class {@link createAccessGuard} returns
78
111
  */
@@ -93,4 +126,4 @@ interface AccessGuardType<Access, Requirement> extends Type<CanActivate> {
93
126
  accessOf(request: object): Access | undefined;
94
127
  }
95
128
 
96
- export type { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies };
129
+ export type { AccessGuardBaseOptions, AccessGuardIdOptions, AccessGuardNoAccess, AccessGuardOptions, AccessGuardParamOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies };
@@ -8,11 +8,12 @@ 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 (or a body field or query parameter, see `from`)
12
- * 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
+ * or a fixed or computed `id`) and checks the route's requirements:
13
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
14
+ * - missing or malformed id (see `validate`): **404**
15
+ * - no access (`resolve` gives `null`/`undefined`): **404**, so callers can't probe which ids exist
16
+ * (or **403** with `noAccess: 'forbidden'`)
16
17
  * - access that does not meet every requirement of the route (see `allows`): **403**
17
18
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
18
19
  *
@@ -46,15 +47,21 @@ var core = require('@nestjs/core');
46
47
  * To give the guard a class name of its own (in stack traces, or to inject it), extend it:
47
48
  * `@Injectable() export class ProjectAccessGuard extends createAccessGuard({ ... }) {}`.
48
49
  * * * *
49
- * @param options Which parameter to read, how to resolve the access, and how to check a requirement
50
+ * @param options Which parameter to read (or the `id`), how to resolve the access, and how to check a requirement
50
51
  * @returns An injectable guard class with `require()`, `access()` and `accessOf()`
52
+ * @throws When neither or both of `param` and `id` are given
51
53
  */
52
54
  function createAccessGuard(options) {
53
55
  var AccessGuard_1;
54
- const { param, from = 'params', validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
56
+ const { param, from = 'params', id, validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden', noAccess = 'not-found', } = options;
57
+ if ((param === undefined) === (id === undefined)) {
58
+ throw new Error('createAccessGuard: give exactly one of `param` (a request parameter) and `id` (a fixed or computed id)');
59
+ }
55
60
  const sources = typeof from === 'string' ? [from] : from;
56
- const requirementsKey = Symbol(`access-guard:${param}:requirements`);
57
- const accessKey = Symbol(`access-guard:${param}:access`);
61
+ /** Names the id in metadata keys and errors */
62
+ const label = param !== undefined ? `:${param}` : typeof id === 'string' ? id : 'the computed id';
63
+ const requirementsKey = Symbol(`access-guard:${label}:requirements`);
64
+ const accessKey = Symbol(`access-guard:${label}:access`);
58
65
  let AccessGuard = class AccessGuard {
59
66
  static { AccessGuard_1 = this; }
60
67
  static access = common.createParamDecorator((_data, context) => AccessGuard_1.accessOf(context.switchToHttp().getRequest()) ?? AccessGuard_1.notGuarded());
@@ -75,25 +82,31 @@ function createAccessGuard(options) {
75
82
  return request[accessKey];
76
83
  }
77
84
  /**
78
- * The parameter in the first source holding a string value
85
+ * The fixed or computed `id`, or else the parameter in the first source holding a string value
79
86
  */
80
87
  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');
88
+ return typeof id === 'function'
89
+ ? id(request)
90
+ : (id ??
91
+ sources
92
+ .map(source => request[source])
93
+ .map(holder => (typeof holder === 'object' && holder !== null ? holder[param] : undefined))
94
+ .find((value) => typeof value === 'string'));
95
+ }
96
+ /** The answer when `resolve` finds no access */
97
+ static noAccess() {
98
+ throw noAccess === 'forbidden' ? new common.ForbiddenException(forbidden) : new common.NotFoundException(notFound);
85
99
  }
86
100
  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`);
101
+ throw new Error(`The access of ${label} is read on a route without its access guard; add \`.require()\` to the route or controller`);
88
102
  }
89
103
  canActivate(context) {
90
104
  const request = context.switchToHttp().getRequest();
91
105
  const value = AccessGuard_1.idOf(request);
92
106
  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
- }
107
+ return (typeof value === 'string' && validate(value)
108
+ ? Promise.resolve(resolve(value, request, ...this.dependencies)).then(access => access ?? AccessGuard_1.noAccess())
109
+ : Promise.reject(new common.NotFoundException(notFound))).then(access => {
97
110
  if (!required.every(requirement => allows(access, requirement))) {
98
111
  throw new common.ForbiddenException(forbidden);
99
112
  }
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CG;AACG,SAAU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AAkB,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;;;;"}
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","ForbiddenException","NotFoundException","__decorate","Injectable","Reflector","Inject"],"mappings":";;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CG;AACG,SAAU,iBAAiB,CAK/B,OAAiE,EAAA;;AACjE,IAAA,MAAM,EACJ,KAAK,EACL,IAAI,GAAG,QAAQ,EACf,EAAE,EACF,QAAQ,GAAG,MAAM,IAAI,EACrB,MAAM,GAAG,EAAE,EACX,OAAO,EACP,MAAM,EACN,QAAQ,GAAG,WAAW,EACtB,SAAS,GAAG,WAAW,EACvB,QAAQ,GAAG,WAAW,GACvB,GAAG,OAAO;AAEX,IAAA,IAAI,CAAC,KAAK,KAAK,SAAS,OAAO,EAAE,KAAK,SAAS,CAAC,EAAE;AAChD,QAAA,MAAM,IAAI,KAAK,CAAC,wGAAwG,CAAC;IAC3H;AAEA,IAAA,MAAM,OAAO,GAAiC,OAAO,IAAI,KAAK,QAAQ,GAAG,CAAC,IAAI,CAAC,GAAG,IAAI;;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AAW,CAAC,CAAC,EAAE;AAC/D,oBAAA,MAAM,IAAID,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;;IAnEI,WAAW,GAAA,aAAA,GAAAE,gBAAA,CAAA;AADhB,QAAAC,iBAAU,EAAE;;AACP,KAAA,EAAA,WAAW,CAoEhB;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,11 +5,12 @@ 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 (or a body field or query parameter, see `from`)
9
- * 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
+ * or a fixed or computed `id`) and checks the route's requirements:
10
10
  *
11
- * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
12
- * so callers can't probe which ids exist
11
+ * - missing or malformed id (see `validate`): **404**
12
+ * - no access (`resolve` gives `null`/`undefined`): **404**, so callers can't probe which ids exist
13
+ * (or **403** with `noAccess: 'forbidden'`)
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()`
15
16
  *
@@ -43,8 +44,9 @@ import { InjectionToken } from '@nestjs/common';
43
44
  * To give the guard a class name of its own (in stack traces, or to inject it), extend it:
44
45
  * `@Injectable() export class ProjectAccessGuard extends createAccessGuard({ ... }) {}`.
45
46
  * * * *
46
- * @param options Which parameter to read, how to resolve the access, and how to check a requirement
47
+ * @param options Which parameter to read (or the `id`), how to resolve the access, and how to check a requirement
47
48
  * @returns An injectable guard class with `require()`, `access()` and `accessOf()`
49
+ * @throws When neither or both of `param` and `id` are given
48
50
  */
49
51
  declare function createAccessGuard<Access, Requirement, Request extends AccessGuardRequest = AccessGuardRequest, const Tokens extends readonly InjectionToken[] = []>(options: AccessGuardOptions<Access, Requirement, Request, Tokens>): AccessGuardType<Access, Requirement>;
50
52
 
@@ -5,11 +5,12 @@ 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 (or a body field or query parameter, see `from`)
9
- * 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
+ * or a fixed or computed `id`) and checks the route's requirements:
10
10
  *
11
- * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
12
- * so callers can't probe which ids exist
11
+ * - missing or malformed id (see `validate`): **404**
12
+ * - no access (`resolve` gives `null`/`undefined`): **404**, so callers can't probe which ids exist
13
+ * (or **403** with `noAccess: 'forbidden'`)
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()`
15
16
  *
@@ -43,8 +44,9 @@ import { InjectionToken } from '@nestjs/common';
43
44
  * To give the guard a class name of its own (in stack traces, or to inject it), extend it:
44
45
  * `@Injectable() export class ProjectAccessGuard extends createAccessGuard({ ... }) {}`.
45
46
  * * * *
46
- * @param options Which parameter to read, how to resolve the access, and how to check a requirement
47
+ * @param options Which parameter to read (or the `id`), how to resolve the access, and how to check a requirement
47
48
  * @returns An injectable guard class with `require()`, `access()` and `accessOf()`
49
+ * @throws When neither or both of `param` and `id` are given
48
50
  */
49
51
  declare function createAccessGuard<Access, Requirement, Request extends AccessGuardRequest = AccessGuardRequest, const Tokens extends readonly InjectionToken[] = []>(options: AccessGuardOptions<Access, Requirement, Request, Tokens>): AccessGuardType<Access, Requirement>;
50
52
 
@@ -1,16 +1,17 @@
1
1
  import { __decorate, __metadata } from 'tslib';
2
- import { createParamDecorator, applyDecorators, SetMetadata, UseGuards, NotFoundException, ForbiddenException, Injectable, Inject } from '@nestjs/common';
2
+ import { createParamDecorator, applyDecorators, SetMetadata, UseGuards, ForbiddenException, NotFoundException, Injectable, Inject } from '@nestjs/common';
3
3
  import { Reflector } from '@nestjs/core';
4
4
 
5
5
  /**
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 (or a body field or query parameter, see `from`)
10
- * 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
+ * or a fixed or computed `id`) and checks the route's requirements:
11
11
  *
12
- * - missing or malformed parameter (see `validate`), or no access (`resolve` gives `null`/`undefined`): **404**,
13
- * so callers can't probe which ids exist
12
+ * - missing or malformed id (see `validate`): **404**
13
+ * - no access (`resolve` gives `null`/`undefined`): **404**, so callers can't probe which ids exist
14
+ * (or **403** with `noAccess: 'forbidden'`)
14
15
  * - access that does not meet every requirement of the route (see `allows`): **403**
15
16
  * - otherwise the request passes, and the resolved access is kept on the request for `@Guard.access()`
16
17
  *
@@ -44,15 +45,21 @@ import { Reflector } from '@nestjs/core';
44
45
  * To give the guard a class name of its own (in stack traces, or to inject it), extend it:
45
46
  * `@Injectable() export class ProjectAccessGuard extends createAccessGuard({ ... }) {}`.
46
47
  * * * *
47
- * @param options Which parameter to read, how to resolve the access, and how to check a requirement
48
+ * @param options Which parameter to read (or the `id`), how to resolve the access, and how to check a requirement
48
49
  * @returns An injectable guard class with `require()`, `access()` and `accessOf()`
50
+ * @throws When neither or both of `param` and `id` are given
49
51
  */
50
52
  function createAccessGuard(options) {
51
53
  var AccessGuard_1;
52
- const { param, from = 'params', validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden' } = options;
54
+ const { param, from = 'params', id, validate = () => true, inject = [], resolve, allows, notFound = 'Not Found', forbidden = 'Forbidden', noAccess = 'not-found', } = options;
55
+ if ((param === undefined) === (id === undefined)) {
56
+ throw new Error('createAccessGuard: give exactly one of `param` (a request parameter) and `id` (a fixed or computed id)');
57
+ }
53
58
  const sources = typeof from === 'string' ? [from] : from;
54
- const requirementsKey = Symbol(`access-guard:${param}:requirements`);
55
- const accessKey = Symbol(`access-guard:${param}:access`);
59
+ /** Names the id in metadata keys and errors */
60
+ const label = param !== undefined ? `:${param}` : typeof id === 'string' ? id : 'the computed id';
61
+ const requirementsKey = Symbol(`access-guard:${label}:requirements`);
62
+ const accessKey = Symbol(`access-guard:${label}:access`);
56
63
  let AccessGuard = class AccessGuard {
57
64
  static { AccessGuard_1 = this; }
58
65
  static access = createParamDecorator((_data, context) => AccessGuard_1.accessOf(context.switchToHttp().getRequest()) ?? AccessGuard_1.notGuarded());
@@ -73,25 +80,31 @@ function createAccessGuard(options) {
73
80
  return request[accessKey];
74
81
  }
75
82
  /**
76
- * The parameter in the first source holding a string value
83
+ * The fixed or computed `id`, or else the parameter in the first source holding a string value
77
84
  */
78
85
  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');
86
+ return typeof id === 'function'
87
+ ? id(request)
88
+ : (id ??
89
+ sources
90
+ .map(source => request[source])
91
+ .map(holder => (typeof holder === 'object' && holder !== null ? holder[param] : undefined))
92
+ .find((value) => typeof value === 'string'));
93
+ }
94
+ /** The answer when `resolve` finds no access */
95
+ static noAccess() {
96
+ throw noAccess === 'forbidden' ? new ForbiddenException(forbidden) : new NotFoundException(notFound);
83
97
  }
84
98
  static notGuarded() {
85
- throw new Error(`The access of :${param} is read on a route without its access guard; add \`.require()\` to the route or controller`);
99
+ throw new Error(`The access of ${label} is read on a route without its access guard; add \`.require()\` to the route or controller`);
86
100
  }
87
101
  canActivate(context) {
88
102
  const request = context.switchToHttp().getRequest();
89
103
  const value = AccessGuard_1.idOf(request);
90
104
  const required = this.reflector.getAllAndOverride(requirementsKey, [context.getHandler(), context.getClass()]) ?? [];
91
- return Promise.resolve(typeof value === 'string' && validate(value) ? resolve(value, request, ...this.dependencies) : null).then(access => {
92
- if (access === null || access === undefined) {
93
- throw new NotFoundException(notFound);
94
- }
105
+ return (typeof value === 'string' && validate(value)
106
+ ? Promise.resolve(resolve(value, request, ...this.dependencies)).then(access => access ?? AccessGuard_1.noAccess())
107
+ : Promise.reject(new NotFoundException(notFound))).then(access => {
95
108
  if (!required.every(requirement => allows(access, requirement))) {
96
109
  throw new ForbiddenException(forbidden);
97
110
  }
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,GADjB,MAC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encies } from './access-guard-options.cjs';
1
+ export { AccessGuardBaseOptions, AccessGuardIdOptions, AccessGuardNoAccess, AccessGuardOptions, AccessGuardParamOptions, 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, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access-guard-options.js';
1
+ export { AccessGuardBaseOptions, AccessGuardIdOptions, AccessGuardNoAccess, AccessGuardOptions, AccessGuardParamOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access-guard-options.js';
2
2
  export { createAccessGuard } from './create-access-guard.js';
3
3
  import '@nestjs/common';