@application-kit/authorization 0.0.0-stage → 0.0.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.
- package/LICENSE +21 -0
- package/README.md +70 -2
- package/dist/cjs/build-ability.d.ts +7 -0
- package/dist/cjs/build-ability.js +13 -0
- package/dist/cjs/compose-ability-grants.d.ts +3 -0
- package/dist/cjs/compose-ability-grants.js +28 -0
- package/dist/cjs/index.d.ts +3 -0
- package/dist/cjs/index.js +19 -0
- package/dist/cjs/nest/ability.factory.d.ts +8 -0
- package/dist/cjs/nest/ability.factory.js +33 -0
- package/dist/cjs/nest/authorization-logger.d.ts +5 -0
- package/dist/cjs/nest/authorization-logger.interface.d.ts +3 -0
- package/dist/cjs/nest/authorization-logger.interface.js +2 -0
- package/dist/cjs/nest/authorization-logger.js +59 -0
- package/dist/cjs/nest/check-policies.decorator.d.ts +5 -0
- package/dist/cjs/nest/check-policies.decorator.js +7 -0
- package/dist/cjs/nest/constants.d.ts +3 -0
- package/dist/cjs/nest/constants.js +6 -0
- package/dist/cjs/nest/index.d.ts +8 -0
- package/dist/cjs/nest/index.js +24 -0
- package/dist/cjs/nest/policies.guard.d.ts +14 -0
- package/dist/cjs/nest/policies.guard.js +78 -0
- package/dist/cjs/nest/policy-handlers.d.ts +2 -0
- package/dist/cjs/nest/policy-handlers.js +5 -0
- package/dist/cjs/nest/public.decorator.d.ts +3 -0
- package/dist/cjs/nest/public.decorator.js +7 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/types/ability-grant.d.ts +5 -0
- package/dist/cjs/types/ability-grant.js +2 -0
- package/dist/cjs/types/ability.d.ts +4 -0
- package/dist/cjs/types/ability.js +2 -0
- package/dist/cjs/types/actions.d.ts +2 -0
- package/dist/cjs/types/actions.js +2 -0
- package/dist/cjs/types/index.d.ts +5 -0
- package/dist/cjs/types/index.js +21 -0
- package/dist/cjs/types/roles.d.ts +3 -0
- package/dist/cjs/types/roles.js +2 -0
- package/dist/cjs/types/subjects.d.ts +4 -0
- package/dist/cjs/types/subjects.js +2 -0
- package/dist/esm/build-ability.d.ts +7 -0
- package/dist/esm/build-ability.js +9 -0
- package/dist/esm/compose-ability-grants.d.ts +3 -0
- package/dist/esm/compose-ability-grants.js +24 -0
- package/dist/esm/index.d.ts +3 -0
- package/dist/esm/index.js +3 -0
- package/dist/esm/nest/ability.factory.d.ts +8 -0
- package/dist/esm/nest/ability.factory.js +30 -0
- package/dist/esm/nest/authorization-logger.d.ts +5 -0
- package/dist/esm/nest/authorization-logger.interface.d.ts +3 -0
- package/dist/esm/nest/authorization-logger.interface.js +1 -0
- package/dist/esm/nest/authorization-logger.js +23 -0
- package/dist/esm/nest/check-policies.decorator.d.ts +5 -0
- package/dist/esm/nest/check-policies.decorator.js +3 -0
- package/dist/esm/nest/constants.d.ts +3 -0
- package/dist/esm/nest/constants.js +3 -0
- package/dist/esm/nest/index.d.ts +8 -0
- package/dist/esm/nest/index.js +8 -0
- package/dist/esm/nest/policies.guard.d.ts +14 -0
- package/dist/esm/nest/policies.guard.js +75 -0
- package/dist/esm/nest/policy-handlers.d.ts +2 -0
- package/dist/esm/nest/policy-handlers.js +1 -0
- package/dist/esm/nest/public.decorator.d.ts +3 -0
- package/dist/esm/nest/public.decorator.js +3 -0
- package/dist/esm/types/ability-grant.d.ts +5 -0
- package/dist/esm/types/ability-grant.js +1 -0
- package/dist/esm/types/ability.d.ts +4 -0
- package/dist/esm/types/ability.js +1 -0
- package/dist/esm/types/actions.d.ts +2 -0
- package/dist/esm/types/actions.js +1 -0
- package/dist/esm/types/index.d.ts +5 -0
- package/dist/esm/types/index.js +5 -0
- package/dist/esm/types/roles.d.ts +3 -0
- package/dist/esm/types/roles.js +1 -0
- package/dist/esm/types/subjects.d.ts +4 -0
- package/dist/esm/types/subjects.js +1 -0
- package/package.json +84 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 application-kit
|
|
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,71 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @application-kit/authorization
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Авторизация на CASL для NestJS-приложений с браузерным клиентом. Пакет не знает ни одной роли, subject'а и
|
|
4
|
+
правила: словарь и гранты объявляют модули приложения, механизм собирает из них ability и проверяет политики.
|
|
5
|
+
Одна и та же карта грантов строит ability и на сервере (проверка доступа), и в браузере (скрытие недоступного UI).
|
|
6
|
+
|
|
7
|
+
## Установка
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
yarn add @application-kit/authorization
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Peer-зависимости: `@casl/ability`, `@nestjs/common`, `@nestjs/core`, `nestjs-pino`. Все обязательные.
|
|
14
|
+
`@nestjs/graphql` пакету не нужен: guard узнаёт GraphQL-запрос по типу контекста и работает и в приложении без GraphQL.
|
|
15
|
+
|
|
16
|
+
## Входы
|
|
17
|
+
|
|
18
|
+
| Вход | Для чего | Тянет |
|
|
19
|
+
|------|----------|-------|
|
|
20
|
+
| `@application-kit/authorization` | сервер и браузер: реестры, `buildAbilityFor`, `composeAbilityGrants` | только `@casl/ability` |
|
|
21
|
+
| `@application-kit/authorization/nest` | сервер: guard, декораторы, фабрика, логгер | `@nestjs/*`, `nestjs-pino` |
|
|
22
|
+
|
|
23
|
+
Корневой вход не импортирует Nest — его можно собирать в браузерный бандл.
|
|
24
|
+
|
|
25
|
+
## Словарь приложения
|
|
26
|
+
|
|
27
|
+
Роли, subject'ы и их action'ы объявляются расширением реестров пакета (module augmentation):
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
declare module '@application-kit/authorization' {
|
|
31
|
+
interface RoleRegistryInterface { EDITOR: true, VIEWER: true }
|
|
32
|
+
interface SubjectRegistryInterface { Article: 'publish' | 'read' }
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Пока реестр ролей пуст, тип роли — `never`: грант нельзя выдать роли, которой приложение не объявило.
|
|
37
|
+
|
|
38
|
+
## Гранты
|
|
39
|
+
|
|
40
|
+
Модуль объявляет фрагмент карты «роль → грант» рядом со своим subject'ом; фрагменты складываются в одну карту.
|
|
41
|
+
Гранты одной роли из разных модулей складываются, а не перезаписывают друг друга. Роль без гранта не получает
|
|
42
|
+
ни одного правила (deny-by-default).
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
const grants = composeAbilityGrants(['EDITOR', 'VIEWER'], articleGrants, commentGrants)
|
|
46
|
+
const ability = buildAbilityFor({ role: 'EDITOR' }, grants)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Nest
|
|
50
|
+
|
|
51
|
+
- `PoliciesGuard` — глобальный guard (`APP_GUARD`): обработчик с `@Public()` пропускается, с `@CheckPolicies(...)` —
|
|
52
|
+
проверяется конъюнкцией политик над ability актора из `request.user`. GraphQL-резолвер без обоих декораторов
|
|
53
|
+
запрещён (fail-closed) с предупреждением в лог, REST-обработчик — пропускается: его авторизация на маршруте.
|
|
54
|
+
- `CheckPolicies(...handlers)`, `PolicyHandler`, `permitAuthenticated` — политики обработчика.
|
|
55
|
+
- `Public()`, `IS_PUBLIC_KEY` — открытый обработчик; ключ читает и guard аутентификации приложения.
|
|
56
|
+
- `AbilityFactory` — ability актора по карте грантов.
|
|
57
|
+
|
|
58
|
+
Провайдеры токенов приносит приложение:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
providers: [
|
|
62
|
+
AbilityFactory,
|
|
63
|
+
{ provide: ABILITY_FACTORY, useExisting: AbilityFactory },
|
|
64
|
+
{ provide: ABILITY_GRANTS, useValue: grants },
|
|
65
|
+
{ provide: AUTHORIZATION_LOGGER, useClass: AuthorizationLogger },
|
|
66
|
+
{ provide: APP_GUARD, useClass: PoliciesGuard },
|
|
67
|
+
]
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`AuthorizationLogger` — pino-логгер пакета с контекстом `AuthorizationLogger`; собирается из глобального
|
|
71
|
+
`LoggerModule` `nestjs-pino`.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { AbilityGrantMap } from './types/ability-grant.js';
|
|
2
|
+
import type { AppAbility } from './types/ability.js';
|
|
3
|
+
import type { Role } from './types/roles.js';
|
|
4
|
+
export interface AbilityActorInterface {
|
|
5
|
+
role: Role;
|
|
6
|
+
}
|
|
7
|
+
export declare const buildAbilityFor: (actor: AbilityActorInterface | null, grants: AbilityGrantMap) => AppAbility;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildAbilityFor = void 0;
|
|
4
|
+
const ability_1 = require("@casl/ability");
|
|
5
|
+
const grantOf = (grants, role) => grants[role];
|
|
6
|
+
const buildAbilityFor = (actor, grants) => {
|
|
7
|
+
const builder = new ability_1.AbilityBuilder(ability_1.createMongoAbility);
|
|
8
|
+
if (actor !== null) {
|
|
9
|
+
grantOf(grants, actor.role)?.(builder);
|
|
10
|
+
}
|
|
11
|
+
return builder.build();
|
|
12
|
+
};
|
|
13
|
+
exports.buildAbilityFor = buildAbilityFor;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.composeAbilityGrants = void 0;
|
|
4
|
+
const grantsForRole = (fragments, role) => {
|
|
5
|
+
const grants = [];
|
|
6
|
+
for (const fragment of fragments) {
|
|
7
|
+
const grant = fragment[role];
|
|
8
|
+
if (grant !== undefined) {
|
|
9
|
+
grants.push(grant);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
return grants;
|
|
13
|
+
};
|
|
14
|
+
const composeAbilityGrants = (roles, ...fragments) => {
|
|
15
|
+
const composed = new Map();
|
|
16
|
+
for (const role of roles) {
|
|
17
|
+
const grants = grantsForRole(fragments, role);
|
|
18
|
+
if (grants.length > 0) {
|
|
19
|
+
composed.set(role, (builder) => {
|
|
20
|
+
for (const grant of grants) {
|
|
21
|
+
grant(builder);
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return Object.fromEntries(composed);
|
|
27
|
+
};
|
|
28
|
+
exports.composeAbilityGrants = composeAbilityGrants;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./types/index.js"), exports);
|
|
18
|
+
__exportStar(require("./build-ability.js"), exports);
|
|
19
|
+
__exportStar(require("./compose-ability-grants.js"), exports);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { AbilityActorInterface } from '../build-ability.js';
|
|
2
|
+
import type { AbilityGrantMap } from '../types/ability-grant.js';
|
|
3
|
+
import type { AppAbility } from '../types/ability.js';
|
|
4
|
+
export declare class AbilityFactory {
|
|
5
|
+
private readonly grants;
|
|
6
|
+
constructor(grants: AbilityGrantMap);
|
|
7
|
+
createForActor(actor: AbilityActorInterface): AppAbility;
|
|
8
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.AbilityFactory = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const build_ability_js_1 = require("../build-ability.js");
|
|
18
|
+
const constants_js_1 = require("./constants.js");
|
|
19
|
+
let AbilityFactory = class AbilityFactory {
|
|
20
|
+
grants;
|
|
21
|
+
constructor(grants) {
|
|
22
|
+
this.grants = grants;
|
|
23
|
+
}
|
|
24
|
+
createForActor(actor) {
|
|
25
|
+
return (0, build_ability_js_1.buildAbilityFor)(actor, this.grants);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
exports.AbilityFactory = AbilityFactory;
|
|
29
|
+
exports.AbilityFactory = AbilityFactory = __decorate([
|
|
30
|
+
(0, common_1.Injectable)(),
|
|
31
|
+
__param(0, (0, common_1.Inject)(constants_js_1.ABILITY_GRANTS)),
|
|
32
|
+
__metadata("design:paramtypes", [Object])
|
|
33
|
+
], AbilityFactory);
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import * as nestjsPino from 'nestjs-pino';
|
|
2
|
+
import type { AuthorizationLoggerInterface } from './authorization-logger.interface.js';
|
|
3
|
+
export declare class AuthorizationLogger extends nestjsPino.PinoLogger implements AuthorizationLoggerInterface {
|
|
4
|
+
constructor(options: nestjsPino.Params);
|
|
5
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
19
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
20
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
21
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
22
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
23
|
+
};
|
|
24
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
25
|
+
var ownKeys = function(o) {
|
|
26
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
27
|
+
var ar = [];
|
|
28
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
29
|
+
return ar;
|
|
30
|
+
};
|
|
31
|
+
return ownKeys(o);
|
|
32
|
+
};
|
|
33
|
+
return function (mod) {
|
|
34
|
+
if (mod && mod.__esModule) return mod;
|
|
35
|
+
var result = {};
|
|
36
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
37
|
+
__setModuleDefault(result, mod);
|
|
38
|
+
return result;
|
|
39
|
+
};
|
|
40
|
+
})();
|
|
41
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
42
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
43
|
+
};
|
|
44
|
+
var AuthorizationLogger_1;
|
|
45
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
46
|
+
exports.AuthorizationLogger = void 0;
|
|
47
|
+
const common_1 = require("@nestjs/common");
|
|
48
|
+
const nestjsPino = __importStar(require("nestjs-pino"));
|
|
49
|
+
let AuthorizationLogger = AuthorizationLogger_1 = class AuthorizationLogger extends nestjsPino.PinoLogger {
|
|
50
|
+
constructor(options) {
|
|
51
|
+
super(options);
|
|
52
|
+
this.setContext(AuthorizationLogger_1.name);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
exports.AuthorizationLogger = AuthorizationLogger;
|
|
56
|
+
exports.AuthorizationLogger = AuthorizationLogger = AuthorizationLogger_1 = __decorate([
|
|
57
|
+
(0, common_1.Injectable)(),
|
|
58
|
+
__metadata("design:paramtypes", [Object])
|
|
59
|
+
], AuthorizationLogger);
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { CustomDecorator } from '@nestjs/common';
|
|
2
|
+
import type { AppAbility } from '../types/ability.js';
|
|
3
|
+
export declare const CHECK_POLICIES_KEY = "checkPolicies";
|
|
4
|
+
export type PolicyHandler = (ability: AppAbility) => boolean;
|
|
5
|
+
export declare const CheckPolicies: (...handlers: PolicyHandler[]) => CustomDecorator;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CheckPolicies = exports.CHECK_POLICIES_KEY = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
exports.CHECK_POLICIES_KEY = 'checkPolicies';
|
|
6
|
+
const CheckPolicies = (...handlers) => (0, common_1.SetMetadata)(exports.CHECK_POLICIES_KEY, handlers);
|
|
7
|
+
exports.CheckPolicies = CheckPolicies;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AUTHORIZATION_LOGGER = exports.ABILITY_GRANTS = exports.ABILITY_FACTORY = void 0;
|
|
4
|
+
exports.ABILITY_FACTORY = Symbol('ABILITY_FACTORY');
|
|
5
|
+
exports.ABILITY_GRANTS = Symbol('ABILITY_GRANTS');
|
|
6
|
+
exports.AUTHORIZATION_LOGGER = Symbol('AUTHORIZATION_LOGGER');
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './ability.factory.js';
|
|
2
|
+
export * from './authorization-logger.js';
|
|
3
|
+
export * from './authorization-logger.interface.js';
|
|
4
|
+
export * from './check-policies.decorator.js';
|
|
5
|
+
export * from './constants.js';
|
|
6
|
+
export * from './policies.guard.js';
|
|
7
|
+
export * from './policy-handlers.js';
|
|
8
|
+
export * from './public.decorator.js';
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./ability.factory.js"), exports);
|
|
18
|
+
__exportStar(require("./authorization-logger.js"), exports);
|
|
19
|
+
__exportStar(require("./authorization-logger.interface.js"), exports);
|
|
20
|
+
__exportStar(require("./check-policies.decorator.js"), exports);
|
|
21
|
+
__exportStar(require("./constants.js"), exports);
|
|
22
|
+
__exportStar(require("./policies.guard.js"), exports);
|
|
23
|
+
__exportStar(require("./policy-handlers.js"), exports);
|
|
24
|
+
__exportStar(require("./public.decorator.js"), exports);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
import type { AbilityFactory } from './ability.factory.js';
|
|
4
|
+
import type { AuthorizationLoggerInterface } from './authorization-logger.interface.js';
|
|
5
|
+
export declare class PoliciesGuard implements CanActivate {
|
|
6
|
+
private readonly reflector;
|
|
7
|
+
private readonly abilityFactory;
|
|
8
|
+
private readonly logger;
|
|
9
|
+
constructor(reflector: Reflector, abilityFactory: AbilityFactory, logger: AuthorizationLoggerInterface);
|
|
10
|
+
canActivate(context: ExecutionContext): boolean;
|
|
11
|
+
private allowWithoutPolicies;
|
|
12
|
+
private enforcePolicies;
|
|
13
|
+
private extractActor;
|
|
14
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.PoliciesGuard = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const core_1 = require("@nestjs/core");
|
|
18
|
+
const check_policies_decorator_js_1 = require("./check-policies.decorator.js");
|
|
19
|
+
const constants_js_1 = require("./constants.js");
|
|
20
|
+
const public_decorator_js_1 = require("./public.decorator.js");
|
|
21
|
+
const GRAPHQL_CONTEXT_TYPE = 'graphql';
|
|
22
|
+
const GRAPHQL_CONTEXT_ARGUMENT_INDEX = 2;
|
|
23
|
+
const isGraphql = (context) => context.getType() === GRAPHQL_CONTEXT_TYPE;
|
|
24
|
+
let PoliciesGuard = class PoliciesGuard {
|
|
25
|
+
reflector;
|
|
26
|
+
abilityFactory;
|
|
27
|
+
logger;
|
|
28
|
+
constructor(reflector, abilityFactory, logger) {
|
|
29
|
+
this.reflector = reflector;
|
|
30
|
+
this.abilityFactory = abilityFactory;
|
|
31
|
+
this.logger = logger;
|
|
32
|
+
}
|
|
33
|
+
canActivate(context) {
|
|
34
|
+
const isPublic = this.reflector.getAllAndOverride(public_decorator_js_1.IS_PUBLIC_KEY, [
|
|
35
|
+
context.getHandler(),
|
|
36
|
+
context.getClass(),
|
|
37
|
+
]);
|
|
38
|
+
if (isPublic === true) {
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
const handlers = this.reflector.getAllAndOverride(check_policies_decorator_js_1.CHECK_POLICIES_KEY, [context.getHandler(), context.getClass()]) ?? [];
|
|
42
|
+
return handlers.length === 0 ? this.allowWithoutPolicies(context) : this.enforcePolicies({ context, handlers });
|
|
43
|
+
}
|
|
44
|
+
allowWithoutPolicies(context) {
|
|
45
|
+
if (isGraphql(context)) {
|
|
46
|
+
this.logger.warn({ class: context.getClass().name, handler: context.getHandler().name }, 'PoliciesGuard deny-by-default — GraphQL resolver missing @Public/@CheckPolicies');
|
|
47
|
+
throw new common_1.ForbiddenException('Forbidden by policy');
|
|
48
|
+
}
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
enforcePolicies(parameters) {
|
|
52
|
+
const actor = this.extractActor(parameters.context);
|
|
53
|
+
if (actor === null) {
|
|
54
|
+
throw new common_1.ForbiddenException('No authenticated user');
|
|
55
|
+
}
|
|
56
|
+
const ability = this.abilityFactory.createForActor({
|
|
57
|
+
role: actor.role,
|
|
58
|
+
});
|
|
59
|
+
const isAllowed = parameters.handlers.every((handler) => handler(ability));
|
|
60
|
+
if (!isAllowed) {
|
|
61
|
+
throw new common_1.ForbiddenException('Forbidden by policy');
|
|
62
|
+
}
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
extractActor(context) {
|
|
66
|
+
const request = isGraphql(context)
|
|
67
|
+
? context.getArgByIndex(GRAPHQL_CONTEXT_ARGUMENT_INDEX).req
|
|
68
|
+
: context.switchToHttp().getRequest();
|
|
69
|
+
return request?.user ?? null;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
exports.PoliciesGuard = PoliciesGuard;
|
|
73
|
+
exports.PoliciesGuard = PoliciesGuard = __decorate([
|
|
74
|
+
(0, common_1.Injectable)(),
|
|
75
|
+
__param(1, (0, common_1.Inject)(constants_js_1.ABILITY_FACTORY)),
|
|
76
|
+
__param(2, (0, common_1.Inject)(constants_js_1.AUTHORIZATION_LOGGER)),
|
|
77
|
+
__metadata("design:paramtypes", [core_1.Reflector, Function, Object])
|
|
78
|
+
], PoliciesGuard);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Public = exports.IS_PUBLIC_KEY = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
exports.IS_PUBLIC_KEY = 'isPublic';
|
|
6
|
+
const Public = () => (0, common_1.SetMetadata)(exports.IS_PUBLIC_KEY, true);
|
|
7
|
+
exports.Public = Public;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AbilityBuilder } from '@casl/ability';
|
|
2
|
+
import type { AppAbility } from './ability.js';
|
|
3
|
+
import type { Role } from './roles.js';
|
|
4
|
+
export type AbilityGrant = (builder: AbilityBuilder<AppAbility>) => void;
|
|
5
|
+
export type AbilityGrantMap = Partial<Record<Role, AbilityGrant>>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./ability.js"), exports);
|
|
18
|
+
__exportStar(require("./ability-grant.js"), exports);
|
|
19
|
+
__exportStar(require("./actions.js"), exports);
|
|
20
|
+
__exportStar(require("./roles.js"), exports);
|
|
21
|
+
__exportStar(require("./subjects.js"), exports);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { AbilityGrantMap } from './types/ability-grant.js';
|
|
2
|
+
import type { AppAbility } from './types/ability.js';
|
|
3
|
+
import type { Role } from './types/roles.js';
|
|
4
|
+
export interface AbilityActorInterface {
|
|
5
|
+
role: Role;
|
|
6
|
+
}
|
|
7
|
+
export declare const buildAbilityFor: (actor: AbilityActorInterface | null, grants: AbilityGrantMap) => AppAbility;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { AbilityBuilder, createMongoAbility } from '@casl/ability';
|
|
2
|
+
const grantOf = (grants, role) => grants[role];
|
|
3
|
+
export const buildAbilityFor = (actor, grants) => {
|
|
4
|
+
const builder = new AbilityBuilder(createMongoAbility);
|
|
5
|
+
if (actor !== null) {
|
|
6
|
+
grantOf(grants, actor.role)?.(builder);
|
|
7
|
+
}
|
|
8
|
+
return builder.build();
|
|
9
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const grantsForRole = (fragments, role) => {
|
|
2
|
+
const grants = [];
|
|
3
|
+
for (const fragment of fragments) {
|
|
4
|
+
const grant = fragment[role];
|
|
5
|
+
if (grant !== undefined) {
|
|
6
|
+
grants.push(grant);
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
return grants;
|
|
10
|
+
};
|
|
11
|
+
export const composeAbilityGrants = (roles, ...fragments) => {
|
|
12
|
+
const composed = new Map();
|
|
13
|
+
for (const role of roles) {
|
|
14
|
+
const grants = grantsForRole(fragments, role);
|
|
15
|
+
if (grants.length > 0) {
|
|
16
|
+
composed.set(role, (builder) => {
|
|
17
|
+
for (const grant of grants) {
|
|
18
|
+
grant(builder);
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return Object.fromEntries(composed);
|
|
24
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { AbilityActorInterface } from '../build-ability.js';
|
|
2
|
+
import type { AbilityGrantMap } from '../types/ability-grant.js';
|
|
3
|
+
import type { AppAbility } from '../types/ability.js';
|
|
4
|
+
export declare class AbilityFactory {
|
|
5
|
+
private readonly grants;
|
|
6
|
+
constructor(grants: AbilityGrantMap);
|
|
7
|
+
createForActor(actor: AbilityActorInterface): AppAbility;
|
|
8
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { Inject, Injectable } from '@nestjs/common';
|
|
14
|
+
import { buildAbilityFor } from '../build-ability.js';
|
|
15
|
+
import { ABILITY_GRANTS } from './constants.js';
|
|
16
|
+
let AbilityFactory = class AbilityFactory {
|
|
17
|
+
grants;
|
|
18
|
+
constructor(grants) {
|
|
19
|
+
this.grants = grants;
|
|
20
|
+
}
|
|
21
|
+
createForActor(actor) {
|
|
22
|
+
return buildAbilityFor(actor, this.grants);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
AbilityFactory = __decorate([
|
|
26
|
+
Injectable(),
|
|
27
|
+
__param(0, Inject(ABILITY_GRANTS)),
|
|
28
|
+
__metadata("design:paramtypes", [Object])
|
|
29
|
+
], AbilityFactory);
|
|
30
|
+
export { AbilityFactory };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import * as nestjsPino from 'nestjs-pino';
|
|
2
|
+
import type { AuthorizationLoggerInterface } from './authorization-logger.interface.js';
|
|
3
|
+
export declare class AuthorizationLogger extends nestjsPino.PinoLogger implements AuthorizationLoggerInterface {
|
|
4
|
+
constructor(options: nestjsPino.Params);
|
|
5
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var AuthorizationLogger_1;
|
|
11
|
+
import { Injectable } from '@nestjs/common';
|
|
12
|
+
import * as nestjsPino from 'nestjs-pino';
|
|
13
|
+
let AuthorizationLogger = AuthorizationLogger_1 = class AuthorizationLogger extends nestjsPino.PinoLogger {
|
|
14
|
+
constructor(options) {
|
|
15
|
+
super(options);
|
|
16
|
+
this.setContext(AuthorizationLogger_1.name);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
AuthorizationLogger = AuthorizationLogger_1 = __decorate([
|
|
20
|
+
Injectable(),
|
|
21
|
+
__metadata("design:paramtypes", [Object])
|
|
22
|
+
], AuthorizationLogger);
|
|
23
|
+
export { AuthorizationLogger };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { CustomDecorator } from '@nestjs/common';
|
|
2
|
+
import type { AppAbility } from '../types/ability.js';
|
|
3
|
+
export declare const CHECK_POLICIES_KEY = "checkPolicies";
|
|
4
|
+
export type PolicyHandler = (ability: AppAbility) => boolean;
|
|
5
|
+
export declare const CheckPolicies: (...handlers: PolicyHandler[]) => CustomDecorator;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './ability.factory.js';
|
|
2
|
+
export * from './authorization-logger.js';
|
|
3
|
+
export * from './authorization-logger.interface.js';
|
|
4
|
+
export * from './check-policies.decorator.js';
|
|
5
|
+
export * from './constants.js';
|
|
6
|
+
export * from './policies.guard.js';
|
|
7
|
+
export * from './policy-handlers.js';
|
|
8
|
+
export * from './public.decorator.js';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './ability.factory.js';
|
|
2
|
+
export * from './authorization-logger.js';
|
|
3
|
+
export * from './authorization-logger.interface.js';
|
|
4
|
+
export * from './check-policies.decorator.js';
|
|
5
|
+
export * from './constants.js';
|
|
6
|
+
export * from './policies.guard.js';
|
|
7
|
+
export * from './policy-handlers.js';
|
|
8
|
+
export * from './public.decorator.js';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
import type { AbilityFactory } from './ability.factory.js';
|
|
4
|
+
import type { AuthorizationLoggerInterface } from './authorization-logger.interface.js';
|
|
5
|
+
export declare class PoliciesGuard implements CanActivate {
|
|
6
|
+
private readonly reflector;
|
|
7
|
+
private readonly abilityFactory;
|
|
8
|
+
private readonly logger;
|
|
9
|
+
constructor(reflector: Reflector, abilityFactory: AbilityFactory, logger: AuthorizationLoggerInterface);
|
|
10
|
+
canActivate(context: ExecutionContext): boolean;
|
|
11
|
+
private allowWithoutPolicies;
|
|
12
|
+
private enforcePolicies;
|
|
13
|
+
private extractActor;
|
|
14
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { ForbiddenException, Inject, Injectable, } from '@nestjs/common';
|
|
14
|
+
import { Reflector } from '@nestjs/core';
|
|
15
|
+
import { CHECK_POLICIES_KEY } from './check-policies.decorator.js';
|
|
16
|
+
import { ABILITY_FACTORY, AUTHORIZATION_LOGGER } from './constants.js';
|
|
17
|
+
import { IS_PUBLIC_KEY } from './public.decorator.js';
|
|
18
|
+
const GRAPHQL_CONTEXT_TYPE = 'graphql';
|
|
19
|
+
const GRAPHQL_CONTEXT_ARGUMENT_INDEX = 2;
|
|
20
|
+
const isGraphql = (context) => context.getType() === GRAPHQL_CONTEXT_TYPE;
|
|
21
|
+
let PoliciesGuard = class PoliciesGuard {
|
|
22
|
+
reflector;
|
|
23
|
+
abilityFactory;
|
|
24
|
+
logger;
|
|
25
|
+
constructor(reflector, abilityFactory, logger) {
|
|
26
|
+
this.reflector = reflector;
|
|
27
|
+
this.abilityFactory = abilityFactory;
|
|
28
|
+
this.logger = logger;
|
|
29
|
+
}
|
|
30
|
+
canActivate(context) {
|
|
31
|
+
const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [
|
|
32
|
+
context.getHandler(),
|
|
33
|
+
context.getClass(),
|
|
34
|
+
]);
|
|
35
|
+
if (isPublic === true) {
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
const handlers = this.reflector.getAllAndOverride(CHECK_POLICIES_KEY, [context.getHandler(), context.getClass()]) ?? [];
|
|
39
|
+
return handlers.length === 0 ? this.allowWithoutPolicies(context) : this.enforcePolicies({ context, handlers });
|
|
40
|
+
}
|
|
41
|
+
allowWithoutPolicies(context) {
|
|
42
|
+
if (isGraphql(context)) {
|
|
43
|
+
this.logger.warn({ class: context.getClass().name, handler: context.getHandler().name }, 'PoliciesGuard deny-by-default — GraphQL resolver missing @Public/@CheckPolicies');
|
|
44
|
+
throw new ForbiddenException('Forbidden by policy');
|
|
45
|
+
}
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
enforcePolicies(parameters) {
|
|
49
|
+
const actor = this.extractActor(parameters.context);
|
|
50
|
+
if (actor === null) {
|
|
51
|
+
throw new ForbiddenException('No authenticated user');
|
|
52
|
+
}
|
|
53
|
+
const ability = this.abilityFactory.createForActor({
|
|
54
|
+
role: actor.role,
|
|
55
|
+
});
|
|
56
|
+
const isAllowed = parameters.handlers.every((handler) => handler(ability));
|
|
57
|
+
if (!isAllowed) {
|
|
58
|
+
throw new ForbiddenException('Forbidden by policy');
|
|
59
|
+
}
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
extractActor(context) {
|
|
63
|
+
const request = isGraphql(context)
|
|
64
|
+
? context.getArgByIndex(GRAPHQL_CONTEXT_ARGUMENT_INDEX).req
|
|
65
|
+
: context.switchToHttp().getRequest();
|
|
66
|
+
return request?.user ?? null;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
PoliciesGuard = __decorate([
|
|
70
|
+
Injectable(),
|
|
71
|
+
__param(1, Inject(ABILITY_FACTORY)),
|
|
72
|
+
__param(2, Inject(AUTHORIZATION_LOGGER)),
|
|
73
|
+
__metadata("design:paramtypes", [Reflector, Function, Object])
|
|
74
|
+
], PoliciesGuard);
|
|
75
|
+
export { PoliciesGuard };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const permitAuthenticated = () => true;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AbilityBuilder } from '@casl/ability';
|
|
2
|
+
import type { AppAbility } from './ability.js';
|
|
3
|
+
import type { Role } from './roles.js';
|
|
4
|
+
export type AbilityGrant = (builder: AbilityBuilder<AppAbility>) => void;
|
|
5
|
+
export type AbilityGrantMap = Partial<Record<Role, AbilityGrant>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,87 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@application-kit/authorization",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Авторизация на CASL для NestJS и браузера: реестры subject'ов и ролей, ability из грантов модулей, глобальный guard политик",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"authorization",
|
|
7
|
+
"casl",
|
|
8
|
+
"nestjs",
|
|
9
|
+
"policies"
|
|
10
|
+
],
|
|
11
|
+
"homepage": "https://gitlab.com/application-kit/application-kit/-/tree/main/packages/authorization",
|
|
12
|
+
"bugs": "https://gitlab.com/application-kit/application-kit/-/issues",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "https://gitlab.com/application-kit/application-kit.git",
|
|
16
|
+
"directory": "packages/authorization"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"author": {
|
|
20
|
+
"name": "application-kit"
|
|
21
|
+
},
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"import": {
|
|
27
|
+
"types": "./dist/esm/index.d.ts",
|
|
28
|
+
"default": "./dist/esm/index.js"
|
|
29
|
+
},
|
|
30
|
+
"require": {
|
|
31
|
+
"types": "./dist/cjs/index.d.ts",
|
|
32
|
+
"default": "./dist/cjs/index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"./nest": {
|
|
36
|
+
"import": {
|
|
37
|
+
"types": "./dist/esm/nest/index.d.ts",
|
|
38
|
+
"default": "./dist/esm/nest/index.js"
|
|
39
|
+
},
|
|
40
|
+
"require": {
|
|
41
|
+
"types": "./dist/cjs/nest/index.d.ts",
|
|
42
|
+
"default": "./dist/cjs/nest/index.js"
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"./package.json": "./package.json"
|
|
46
|
+
},
|
|
47
|
+
"main": "./dist/cjs/index.js",
|
|
48
|
+
"module": "./dist/esm/index.js",
|
|
49
|
+
"types": "./dist/cjs/index.d.ts",
|
|
50
|
+
"files": [
|
|
51
|
+
"dist"
|
|
52
|
+
],
|
|
53
|
+
"scripts": {
|
|
54
|
+
"build": "rm -rf ./dist && node ../../scripts/barrels.mjs create ./src --entry-only=nest && tsc --project tsconfig.build.json && tsc --project tsconfig.build.cjs.json && node ../../scripts/barrels.mjs clean ./src && node ../../scripts/mark-cjs.mjs ./dist/cjs",
|
|
55
|
+
"lint:tsc": "tsc --noEmit --pretty --project .",
|
|
56
|
+
"test:mutation": "stryker run",
|
|
57
|
+
"test:unit": "vitest run"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@casl/ability": "^7.0.1",
|
|
61
|
+
"@nestjs/common": "^11.2.7",
|
|
62
|
+
"@nestjs/core": "^11.2.7",
|
|
63
|
+
"@nestjs/testing": "^11.2.7",
|
|
64
|
+
"@stryker-mutator/core": "^10.0.0",
|
|
65
|
+
"@stryker-mutator/vitest-runner": "^10.0.0",
|
|
66
|
+
"@types/node": "^26.2.0",
|
|
67
|
+
"nestjs-pino": "^4.6.1",
|
|
68
|
+
"pino": "^10.3.1",
|
|
69
|
+
"pino-http": "^11.0.0",
|
|
70
|
+
"reflect-metadata": "^0.2.2",
|
|
71
|
+
"rxjs": "^7.8.2",
|
|
72
|
+
"typescript": "^6.0.3",
|
|
73
|
+
"vitest": "^4.1.11"
|
|
74
|
+
},
|
|
75
|
+
"peerDependencies": {
|
|
76
|
+
"@casl/ability": "^7.0.0",
|
|
77
|
+
"@nestjs/common": "^11.0.0",
|
|
78
|
+
"@nestjs/core": "^11.0.0",
|
|
79
|
+
"nestjs-pino": "^4.6.1"
|
|
80
|
+
},
|
|
81
|
+
"engines": {
|
|
82
|
+
"node": ">=24"
|
|
83
|
+
},
|
|
84
|
+
"publishConfig": {
|
|
85
|
+
"access": "public"
|
|
86
|
+
}
|
|
6
87
|
}
|