@telperion/nest-pack 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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":"nest-pack.mjs","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,MACM,WAAW,CAAA;;AAC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encies } from './access/access-guard-options.cjs';
1
+ export { AccessGuardBaseOptions, AccessGuardIdOptions, AccessGuardNoAccess, AccessGuardOptions, AccessGuardParamOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access/access-guard-options.cjs';
2
2
  export { createAccessGuard } from './access/create-access-guard.cjs';
3
3
  import '@nestjs/common';
package/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { AccessGuardOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access/access-guard-options.js';
1
+ export { AccessGuardBaseOptions, AccessGuardIdOptions, AccessGuardNoAccess, AccessGuardOptions, AccessGuardParamOptions, AccessGuardRequest, AccessGuardSource, AccessGuardType, InjectedDependencies } from './access/access-guard-options.js';
2
2
  export { createAccessGuard } from './access/create-access-guard.js';
3
3
  import '@nestjs/common';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telperion/nest-pack",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "NestJS utilities: JWT auth and access guards, validation helpers and pagination",
5
5
  "keywords": [
6
6
  "nestjs",