@edirect/auth-fastify 0.0.0-stage → 11.2.5

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 (65) hide show
  1. package/README.md +87 -2
  2. package/package.json +34 -3
  3. package/src/auth.service.d.ts +34 -0
  4. package/src/auth.service.d.ts.map +1 -0
  5. package/src/auth.service.js +117 -0
  6. package/src/config.d.ts +33 -0
  7. package/src/config.d.ts.map +1 -0
  8. package/src/config.js +74 -0
  9. package/src/constants.d.ts +57 -0
  10. package/src/constants.d.ts.map +1 -0
  11. package/src/constants.js +74 -0
  12. package/src/decorators.d.ts +17 -0
  13. package/src/decorators.d.ts.map +1 -0
  14. package/src/decorators.js +16 -0
  15. package/src/hooks/auth-service.d.ts +20 -0
  16. package/src/hooks/auth-service.d.ts.map +1 -0
  17. package/src/hooks/auth-service.js +135 -0
  18. package/src/hooks/auto.d.ts +16 -0
  19. package/src/hooks/auto.d.ts.map +1 -0
  20. package/src/hooks/auto.js +104 -0
  21. package/src/hooks/keycloak.d.ts +21 -0
  22. package/src/hooks/keycloak.d.ts.map +1 -0
  23. package/src/hooks/keycloak.js +139 -0
  24. package/src/hooks/token-exchange.d.ts +11 -0
  25. package/src/hooks/token-exchange.d.ts.map +1 -0
  26. package/src/hooks/token-exchange.js +58 -0
  27. package/src/index.d.ts +19 -0
  28. package/src/index.d.ts.map +1 -0
  29. package/src/index.js +39 -0
  30. package/src/interfaces/entity-user.interface.d.ts +14 -0
  31. package/src/interfaces/entity-user.interface.d.ts.map +1 -0
  32. package/src/interfaces/entity-user.interface.js +19 -0
  33. package/src/interfaces/entity.interface.d.ts +25 -0
  34. package/src/interfaces/entity.interface.d.ts.map +1 -0
  35. package/src/interfaces/entity.interface.js +2 -0
  36. package/src/interfaces/index.d.ts +26 -0
  37. package/src/interfaces/index.d.ts.map +1 -0
  38. package/src/interfaces/index.js +8 -0
  39. package/src/interfaces/keycloak-token.interface.d.ts +84 -0
  40. package/src/interfaces/keycloak-token.interface.d.ts.map +1 -0
  41. package/src/interfaces/keycloak-token.interface.js +2 -0
  42. package/src/interfaces/user.interface.d.ts +40 -0
  43. package/src/interfaces/user.interface.d.ts.map +1 -0
  44. package/src/interfaces/user.interface.js +91 -0
  45. package/src/plugin.d.ts +44 -0
  46. package/src/plugin.d.ts.map +1 -0
  47. package/src/plugin.js +103 -0
  48. package/src/providers/keycloak-token-exchange.service.d.ts +15 -0
  49. package/src/providers/keycloak-token-exchange.service.d.ts.map +1 -0
  50. package/src/providers/keycloak-token-exchange.service.js +62 -0
  51. package/src/providers/memory-cache.d.ts +16 -0
  52. package/src/providers/memory-cache.d.ts.map +1 -0
  53. package/src/providers/memory-cache.js +24 -0
  54. package/src/providers/well-known.service.d.ts +18 -0
  55. package/src/providers/well-known.service.d.ts.map +1 -0
  56. package/src/providers/well-known.service.js +41 -0
  57. package/src/realm-env-key.d.ts +3 -0
  58. package/src/realm-env-key.d.ts.map +1 -0
  59. package/src/realm-env-key.js +27 -0
  60. package/src/types.d.ts +27 -0
  61. package/src/types.d.ts.map +1 -0
  62. package/src/types.js +2 -0
  63. package/src/util.d.ts +18 -0
  64. package/src/util.d.ts.map +1 -0
  65. package/src/util.js +41 -0
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # @edirect/auth-fastify
2
2
 
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.
3
+ Fastify 5 plugin with the same authentication and authorization rules and the same configuration as [`@edirect/auth`](../edirect-auth/README.md). Keycloak and the custom Auth Service are supported. It has no NestJS dependency.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @edirect/auth-fastify fastify
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import Fastify from 'fastify';
15
+ import {
16
+ authFastifyPlugin,
17
+ Roles,
18
+ Permissions,
19
+ Resources,
20
+ } from '@edirect/auth-fastify';
21
+
22
+ const app = Fastify();
23
+
24
+ await app.register(authFastifyPlugin); // mode "auto", configured from process.env
25
+
26
+ app.get('/me', async req => req.user);
27
+
28
+ app.get(
29
+ '/admin',
30
+ { config: { ...Roles('ROLE_ADMIN'), ...Permissions('QUOTE.READ') } },
31
+ async () => ({ ok: true })
32
+ );
33
+
34
+ app.get('/health', { config: { auth: false } }, async () => ({ ok: true }));
35
+ ```
36
+
37
+ The plugin is not encapsulated (`fastify-plugin`). Register it inside a `register()` scope to protect only the routes of that scope.
38
+
39
+ ### Equivalence with `@edirect/auth`
40
+
41
+ | `@edirect/auth` (Nest) | `@edirect/auth-fastify` |
42
+ | ---------------------------------------------------- | ----------------------------------------------------- |
43
+ | `AuthMiddleware` + `AuthGuard` | `mode: 'auto'` (default) |
44
+ | `KeycloakAuthMiddleware` + `KeycloakAuthGuard` | `mode: 'keycloak'` with `keycloak` params |
45
+ | `AuthServiceAuthMiddleware` + guard | `mode: 'auth-service'` with `authService.baseUrl` |
46
+ | `KeycloakAuthTokenExchangeMiddleware` | `tokenExchange: { params, paths?, cache? }` |
47
+ | `@Roles()`, `@Permissions()`, `@Resources()` | `Roles()`, `Permissions()`, `Resources()` in `config` |
48
+ | `AuthService` (request scoped) | `request.auth` (same methods) |
49
+ | `ConfigService` | `config` option, defaults to `process.env` |
50
+ | `req.user`, `externalUser`, `token`, `tokenProvider` | same properties on the Fastify request |
51
+
52
+ Authentication runs in the `preValidation` hook (the body is parsed, so `body.token` works) and authorization runs right after it. Responses match `@edirect/auth`: `401 {status:false,message:'Unauthorized' | 'Invalid token' | <error>}`, `403` from the guards, `500 'IdP not supported in auth module'`.
53
+
54
+ ### Options
55
+
56
+ | Option | Description |
57
+ | --------------- | ---------------------------------------------------------------------------------------------------- |
58
+ | `mode` | `auto` (default), `keycloak` or `auth-service`. |
59
+ | `keycloak` | `OAuth2ParamsInterface` for `mode: 'keycloak'`. |
60
+ | `authService` | `{ baseUrl }` for `mode: 'auth-service'`. The JWKS is `<baseUrl>/oidc/jwks`. |
61
+ | `config` | Config source with `get` and `getOrThrow`. The `ConfigService` of `@edirect/config` fits. |
62
+ | `exclude` | Paths that skip auth: exact string, prefix string ending in `*`, `RegExp` or `(request) => boolean`. |
63
+ | `tokenExchange` | Exchanges external Keycloak tokens for internal ones before authentication. |
64
+
65
+ ## Environment variables
66
+
67
+ Same as `@edirect/auth`, read in `auto` mode:
68
+
69
+ | Variable | Description |
70
+ | -------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
71
+ | `KEYCLOAK_BASE_URL`, `KEYCLOAK_REALM`, `KEYCLOAK_CLIENT` | Keycloak server, realm and client. |
72
+ | `KEYCLOAK_<REALM>_<NAME>` | Per-realm override, for example `KEYCLOAK_TH_BROKER_CLIENT`. Used by the authorization step. |
73
+ | `AUTH_SERVICE_JWKS` | Auth Service JWKS URL. Its origin is the Auth Service base URL. |
74
+ | `HTTP_TIMEOUT` | HTTP timeout in ms. Default `30000`. |
75
+ | `BOLTTECH_PLATFORM`, `ENABLE_IDP_AUTH` | With `BOLTTECH_PLATFORM=idp` auth is bypassed unless `ENABLE_IDP_AUTH=true`. |
76
+
77
+ ## Authorization rules
78
+
79
+ - No `roles`, `permissions` or `resources` on the route: any authenticated request passes.
80
+ - Keycloak: roles and permissions are matched with "any of". The token signature is verified unless the route has `resources` or the caller sends `x-caller: krakend`, in which case it is only decoded. With `resources`, the first one is validated against Keycloak.
81
+ - Auth Service: roles and permissions are matched with "any of" against the claims of the verified token.
82
+ - A request that was not authenticated (excluded path or `auth: false`) is not authorized either, as in `@edirect/auth`.
83
+
84
+ ## Differences from `@edirect/auth`
85
+
86
+ - Auth Service signing keys are cached per `kid` and refetched once on an invalid signature. `@edirect/auth` keeps a single key for all `kid`s.
87
+ - HTTP calls use axios directly instead of `@nestjs/axios`, and the token exchange cache is an in-memory one unless `cache` (any `get`/`set` with ms TTL, such as `cache-manager`) is given.
88
+ - Not included: the IAM providers (user, group and client administration), `ServerAuthService` and the NestJS modules.
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@edirect/auth-fastify",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "11.2.5",
4
+ "main": "./src/index.js",
5
+ "types": "./src/index.d.ts",
6
+ "exports": {
7
+ ".": {
8
+ "import": "./src/index.js",
9
+ "default": "./src/index.js",
10
+ "require": "./src/index.js",
11
+ "types": "./src/index.d.ts"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "src"
17
+ ],
18
+ "dependencies": {
19
+ "axios": "^1.21.1",
20
+ "debug": "^4.4.3",
21
+ "fastify-plugin": "^6.0.1",
22
+ "jsonwebtoken": "^9.0.3",
23
+ "jwks-rsa": "^4.1.0",
24
+ "keycloak-authorization-services": "^2.0.6",
25
+ "lodash": "^4.18.1",
26
+ "tslib": "^2.9.1"
27
+ },
28
+ "peerDependencies": {
29
+ "fastify": "^5.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/debug": "^4.1.13",
33
+ "@types/jsonwebtoken": "^9.0.10",
34
+ "@types/lodash": "^4.17.27"
35
+ },
36
+ "type": "commonjs"
6
37
  }
@@ -0,0 +1,34 @@
1
+ import type { FastifyRequest } from 'fastify';
2
+ import type { AuthServiceInterface, EntityUserInterface, UserInterface } from './interfaces';
3
+ /**
4
+ * Request-scoped helper, same API as the `AuthService` of `@edirect/auth`.
5
+ * Reachable as `request.auth`.
6
+ */
7
+ export declare class AuthService implements AuthServiceInterface {
8
+ private readonly request;
9
+ constructor(request: FastifyRequest);
10
+ getToken(): string;
11
+ setToken(token: string): void;
12
+ getExternalToken(): string;
13
+ setExternalToken(externalToken: string): void;
14
+ getUser(): UserInterface;
15
+ setUser(user: UserInterface): void;
16
+ getExternalUser(): UserInterface;
17
+ setExternalUser(externalUser: UserInterface): void;
18
+ getEntityUser(): EntityUserInterface;
19
+ setEntityHeader(): void;
20
+ hasRoles(roles: string[]): boolean;
21
+ hasRole(role: string): boolean;
22
+ hasPermissions(permissions: string[]): boolean;
23
+ hasPermission(permission: string): boolean;
24
+ isAdmin(): boolean;
25
+ isUser(): boolean;
26
+ isService(): boolean;
27
+ isCrm(): boolean;
28
+ isBroker(): boolean;
29
+ isAgentLicensed(): boolean;
30
+ isAgentUnlicensed(): boolean;
31
+ getTokenProvider(): string;
32
+ setTokenProvider(tokenProvider: string): void;
33
+ }
34
+ //# sourceMappingURL=auth.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.service.d.ts","sourceRoot":"","sources":["../../src/auth.service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAK9C,OAAO,KAAK,EACV,oBAAoB,EACpB,mBAAmB,EACnB,aAAa,EACd,MAAM,cAAc,CAAC;AAEtB;;;GAGG;AACH,qBAAa,WAAY,YAAW,oBAAoB;IAC1C,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,cAAc;IAEpD,QAAQ,IAAI,MAAM;IAIlB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAI7B,gBAAgB,IAAI,MAAM;IAI1B,gBAAgB,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI;IAI7C,OAAO,IAAI,aAAa;IAIxB,OAAO,CAAC,IAAI,EAAE,aAAa,GAAG,IAAI;IAIlC,eAAe,IAAI,aAAa;IAIhC,eAAe,CAAC,YAAY,EAAE,aAAa,GAAG,IAAI;IAIlD,aAAa,IAAI,mBAAmB;IAIpC,eAAe,IAAI,IAAI;IAkBvB,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO;IAQlC,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAM9B,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,OAAO;IAS9C,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO;IAM1C,OAAO,IAAI,OAAO;IAIlB,MAAM,IAAI,OAAO;IAIjB,SAAS,IAAI,OAAO;IAIpB,KAAK,IAAI,OAAO;IAIhB,QAAQ,IAAI,OAAO;IAInB,eAAe,IAAI,OAAO;IAO1B,iBAAiB,IAAI,OAAO;IAI5B,gBAAgB,IAAI,MAAM;IAI1B,gBAAgB,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI;CAG9C"}
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthService = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const first_1 = tslib_1.__importDefault(require("lodash/first"));
6
+ const get_1 = tslib_1.__importDefault(require("lodash/get"));
7
+ const has_1 = tslib_1.__importDefault(require("lodash/has"));
8
+ const constants_1 = require("./constants");
9
+ /**
10
+ * Request-scoped helper, same API as the `AuthService` of `@edirect/auth`.
11
+ * Reachable as `request.auth`.
12
+ */
13
+ class AuthService {
14
+ request;
15
+ constructor(request) {
16
+ this.request = request;
17
+ }
18
+ getToken() {
19
+ return (0, get_1.default)(this.request, 'token');
20
+ }
21
+ setToken(token) {
22
+ this.request.token = token;
23
+ }
24
+ getExternalToken() {
25
+ return (0, get_1.default)(this.request, 'externalToken');
26
+ }
27
+ setExternalToken(externalToken) {
28
+ this.request.externalToken = externalToken;
29
+ }
30
+ getUser() {
31
+ return (0, get_1.default)(this.request, 'user');
32
+ }
33
+ setUser(user) {
34
+ this.request.user = user;
35
+ }
36
+ getExternalUser() {
37
+ return (0, get_1.default)(this.request, 'externalUser');
38
+ }
39
+ setExternalUser(externalUser) {
40
+ this.request.externalUser = externalUser;
41
+ }
42
+ getEntityUser() {
43
+ return (0, get_1.default)(this.request, 'user.entityUser');
44
+ }
45
+ setEntityHeader() {
46
+ if (!(0, has_1.default)(this.request, 'user.username'))
47
+ return;
48
+ const { username } = this.request.user;
49
+ const splittedContent = username.split(constants_1.EntityHeader.SEPARATOR);
50
+ let entity;
51
+ if (splittedContent.length <= constants_1.EntityHeader.LENGTH) {
52
+ entity = (0, get_1.default)(this.request, 'user.entityUser.entityId');
53
+ }
54
+ else {
55
+ entity = (0, first_1.default)(splittedContent);
56
+ }
57
+ if (!entity)
58
+ return;
59
+ Object.assign(this.request.headers, {
60
+ [constants_1.HeadersPlaceHolder.ENTITY]: entity,
61
+ });
62
+ }
63
+ hasRoles(roles) {
64
+ const userRoles = this.request.user?.roles;
65
+ if (!userRoles)
66
+ return false;
67
+ return (roles.filter(role => userRoles.includes(role)).length === roles.length);
68
+ }
69
+ hasRole(role) {
70
+ const userRoles = this.request.user?.roles;
71
+ if (!userRoles)
72
+ return false;
73
+ return userRoles.includes(role);
74
+ }
75
+ hasPermissions(permissions) {
76
+ const userPermissions = this.request.user?.permissions;
77
+ if (!userPermissions || !permissions)
78
+ return false;
79
+ return (permissions.filter(permission => userPermissions.includes(permission))
80
+ .length === permissions.length);
81
+ }
82
+ hasPermission(permission) {
83
+ const userPermissions = this.request.user?.permissions;
84
+ if (!userPermissions || !permission)
85
+ return false;
86
+ return userPermissions.includes(permission);
87
+ }
88
+ isAdmin() {
89
+ return this.hasRole(constants_1.RolesEnum.ROLE_ADMIN);
90
+ }
91
+ isUser() {
92
+ return this.hasRole(constants_1.RolesEnum.ROLE_USER);
93
+ }
94
+ isService() {
95
+ return this.hasRole(constants_1.RolesEnum.ROLE_SERVICE);
96
+ }
97
+ isCrm() {
98
+ return this.hasRole(constants_1.RolesEnum.ROLE_CRM);
99
+ }
100
+ isBroker() {
101
+ return this.hasRole(constants_1.RolesEnum.ROLE_BROKER);
102
+ }
103
+ isAgentLicensed() {
104
+ return (this.hasRole(constants_1.RolesEnum.ROLE_AGENT_LICENSED) ||
105
+ this.hasRole(constants_1.RolesEnum.ROLE_SALES_AGENT_LICENSED));
106
+ }
107
+ isAgentUnlicensed() {
108
+ return this.hasRole(constants_1.RolesEnum.ROLE_AGENT_UNLICENSED);
109
+ }
110
+ getTokenProvider() {
111
+ return (0, get_1.default)(this.request, 'tokenProvider');
112
+ }
113
+ setTokenProvider(tokenProvider) {
114
+ this.request.tokenProvider = tokenProvider;
115
+ }
116
+ }
117
+ exports.AuthService = AuthService;
@@ -0,0 +1,33 @@
1
+ import type { FastifyRequest } from 'fastify';
2
+ /**
3
+ * Thrown when a required environment variable is absent or empty. Same
4
+ * message as `ConfigMissingError` from `@edirect/config`.
5
+ */
6
+ export declare class ConfigMissingError extends Error {
7
+ readonly missingKey: string;
8
+ constructor(missingKey: string);
9
+ }
10
+ /**
11
+ * Where configuration is read from. Structurally compatible with the
12
+ * `ConfigService` of `@edirect/config`, so an instance can be passed as is.
13
+ */
14
+ export interface ConfigSource {
15
+ get(key: string): string | undefined;
16
+ getOrThrow(key: string): string;
17
+ }
18
+ /** Reads from `process.env`, which is what `@edirect/config` does. */
19
+ export declare const processEnvConfig: ConfigSource;
20
+ /**
21
+ * Resolves `KEYCLOAK_*` keys per realm. When the request was already
22
+ * authenticated by Keycloak, the realm is the last segment of the token
23
+ * issuer and `KEYCLOAK_<REALM>_<NAME>` wins over `KEYCLOAK_<NAME>`.
24
+ */
25
+ export declare class ConfigServiceWrapper {
26
+ private readonly configService;
27
+ private readonly request;
28
+ private issuer;
29
+ constructor(configService: ConfigSource, request: FastifyRequest);
30
+ private getRealm;
31
+ get(key: string): string;
32
+ }
33
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAM9C;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;IAC/B,QAAQ,CAAC,UAAU,EAAE,MAAM;gBAAlB,UAAU,EAAE,MAAM;CAIxC;AAED;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACrC,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACjC;AAED,sEAAsE;AACtE,eAAO,MAAM,gBAAgB,EAAE,YAO9B,CAAC;AAEF;;;;GAIG;AACH,qBAAa,oBAAoB;IAI7B,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,OAAO;IAJ1B,OAAO,CAAC,MAAM,CAAqB;gBAGhB,aAAa,EAAE,YAAY,EAC3B,OAAO,EAAE,cAAc;IAS1C,OAAO,CAAC,QAAQ;IAQhB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;CAezB"}
package/src/config.js ADDED
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConfigServiceWrapper = exports.processEnvConfig = exports.ConfigMissingError = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const debug_1 = tslib_1.__importDefault(require("debug"));
6
+ const jwt = tslib_1.__importStar(require("jsonwebtoken"));
7
+ const last_1 = tslib_1.__importDefault(require("lodash/last"));
8
+ const realm_env_key_1 = require("./realm-env-key");
9
+ const util_1 = require("./util");
10
+ const debug = (0, debug_1.default)('auth-module:config-service-wrapper');
11
+ /**
12
+ * Thrown when a required environment variable is absent or empty. Same
13
+ * message as `ConfigMissingError` from `@edirect/config`.
14
+ */
15
+ class ConfigMissingError extends Error {
16
+ missingKey;
17
+ constructor(missingKey) {
18
+ super(`Missing required environment variable: "${missingKey}"`);
19
+ this.missingKey = missingKey;
20
+ this.name = 'ConfigMissingError';
21
+ }
22
+ }
23
+ exports.ConfigMissingError = ConfigMissingError;
24
+ /** Reads from `process.env`, which is what `@edirect/config` does. */
25
+ exports.processEnvConfig = {
26
+ get: key => process.env[key],
27
+ getOrThrow: key => {
28
+ const value = process.env[key];
29
+ if (!value)
30
+ throw new ConfigMissingError(key);
31
+ return value;
32
+ },
33
+ };
34
+ /**
35
+ * Resolves `KEYCLOAK_*` keys per realm. When the request was already
36
+ * authenticated by Keycloak, the realm is the last segment of the token
37
+ * issuer and `KEYCLOAK_<REALM>_<NAME>` wins over `KEYCLOAK_<NAME>`.
38
+ */
39
+ class ConfigServiceWrapper {
40
+ configService;
41
+ request;
42
+ issuer;
43
+ constructor(configService, request) {
44
+ this.configService = configService;
45
+ this.request = request;
46
+ const token = (0, util_1.getToken)(this.request);
47
+ if (token) {
48
+ const decoded = jwt.decode(token);
49
+ this.issuer = decoded?.iss;
50
+ }
51
+ }
52
+ getRealm() {
53
+ if (this.request?.tokenProvider !== 'keycloak' || !this.issuer) {
54
+ return 'default';
55
+ }
56
+ const url = new URL(this.issuer);
57
+ return (0, last_1.default)(url.pathname.split('/'));
58
+ }
59
+ get(key) {
60
+ const realm = this.getRealm();
61
+ if (realm === 'default') {
62
+ return this.configService.getOrThrow(key);
63
+ }
64
+ const realmKey = (0, realm_env_key_1.getRealmEnvKey)(key, realm);
65
+ if (key !== realmKey) {
66
+ const result = this.configService.get(realmKey);
67
+ if (result)
68
+ return result;
69
+ debug('[WARN] Config %s not found', realmKey);
70
+ }
71
+ return this.configService.getOrThrow(key);
72
+ }
73
+ }
74
+ exports.ConfigServiceWrapper = ConfigServiceWrapper;
@@ -0,0 +1,57 @@
1
+ export declare const AUTH_SERVICE_TOKEN = "AUTH_SERVICE";
2
+ export declare const BOLTTECH_PLATFORM_ENV_KEY = "BOLTTECH_PLATFORM";
3
+ export declare const BOLTTECH_ENABLE_IDP_AUTH_ENV_KEY = "ENABLE_IDP_AUTH";
4
+ export declare const BOLTTECH_PLATFORM_IDP = "idp";
5
+ export declare const BOLTTECH_ENABLE_IDP_AUTH = "true";
6
+ export type VerticalsEnum = 'car-insurance' | 'car-ctpl-insurance' | 'motorcycle-insurance' | 'motorcycle-ctpl-insurance' | 'personal-accidents-insurance' | 'property-insurance' | 'travel-insurance' | 'group-insurance' | 'health-insurance';
7
+ export declare enum RolesEnum {
8
+ ROLE_ADMIN = "ROLE_ADMIN",
9
+ ROLE_USER = "ROLE_USER",
10
+ ROLE_SERVICE = "ROLE_SERVICE",
11
+ ROLE_BROKER = "ROLE_BROKER",
12
+ ROLE_AGENT_LICENSED = "ROLE_AGENT_LICENSED",
13
+ ROLE_AGENT_UNLICENSED = "ROLE_AGENT_UNLICENSED",
14
+ ROLE_CRM = "ROLE_CRM",
15
+ ROLE_SALES_AGENT_LICENSED = "ROLE_SALES_AGENT_LICENSED"
16
+ }
17
+ export declare enum PermissionsEnum {
18
+ ENTITY_CREATE = "ENTITY.CREATE",
19
+ ENTITY_REATE_ONLY_OWN = "ENTITY.CREATE_ONLY_OWN",
20
+ ENTITY_DELETE = "ENTITY.DELETE",
21
+ ENTITY_DELETE_ONLY_OWN = "ENTITY.DELETE_ONLY_OWN",
22
+ ENTITY_READ = "ENTITY.READ",
23
+ ENTITY_READ_ONLY_OWN = "ENTITY.READ_ONLY_OWN",
24
+ ENTITY_UPDATE = "ENTITY.UPDATE",
25
+ ENTITY_UPDATE_ONLY_OWN = "ENTITY.UPDATE_ONLY_OWN",
26
+ QUOTE_CREATE = "QUOTE.CREATE",
27
+ QUOTE_DELETE = "QUOTE.DELETE",
28
+ QUOTE_ENTITY_CREATE = "QUOTE.ENTITY.CREATE",
29
+ QUOTE_ENTITY_DELETE = "QUOTE.ENTITY.DELETE",
30
+ QUOTE_ENTITY_LICENSED_FLOW = "QUOTE.ENTITY.LICENSED_FLOW",
31
+ QUOTE_ENTITY_READ = "QUOTE.ENTITY.READ",
32
+ QUOTE_ENTITY_READ_ONLY_OWN = "QUOTE.ENTITY.READ_ONLY_OWN",
33
+ QUOTE_ENTITY_SHOW_COMMISSION = "QUOTE.ENTITY.SHOW_COMMISSION",
34
+ QUOTE_ENTITY_TRANSFER = "QUOTE.ENTITY.TRANSFER",
35
+ QUOTE_ENTITY_UNLICENSED_FLOW = "QUOTE.ENTITY.UNLICENSED_FLOW",
36
+ QUOTE_ENTITY_UPDATE = "QUOTE.ENTITY.UPDATE",
37
+ QUOTE_READ = "QUOTE.READ",
38
+ QUOTE_READ_ONLY_OWN = "QUOTE.READ_ONLY_OWN",
39
+ QUOTE_UPDATE = "QUOTE.UPDATE",
40
+ STORAGE_READ = "STORAGE.READ",
41
+ STORAGE_CREATE = "STORAGE.CREATE",
42
+ STORAGE_UPDATE = "STORAGE.UPDATE",
43
+ STORAGE_DELETE = "STORAGE.DELETE"
44
+ }
45
+ export declare enum HeadersPlaceHolder {
46
+ ENTITY = "x-auth-entity"
47
+ }
48
+ export declare enum EntityHeader {
49
+ LENGTH = 1,
50
+ SEPARATOR = "#"
51
+ }
52
+ export declare enum AuthErrors {
53
+ MANDATORY_ROLES = "Must have at least one of the mandatory roles for the endpoint",
54
+ MANDATORY_PERMISSIONS = "Must have at least one of the mandatory permissions for the endpoint",
55
+ UNSUPPORTED_IDP = "IdP not supported in auth module"
56
+ }
57
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,kBAAkB,iBAAiB,CAAC;AAGjD,eAAO,MAAM,yBAAyB,sBAAsB,CAAC;AAE7D,eAAO,MAAM,gCAAgC,oBAAoB,CAAC;AAGlE,eAAO,MAAM,qBAAqB,QAAQ,CAAC;AAE3C,eAAO,MAAM,wBAAwB,SAAS,CAAC;AAG/C,MAAM,MAAM,aAAa,GACrB,eAAe,GACf,oBAAoB,GACpB,sBAAsB,GACtB,2BAA2B,GAC3B,8BAA8B,GAC9B,oBAAoB,GACpB,kBAAkB,GAClB,iBAAiB,GACjB,kBAAkB,CAAC;AAKvB,oBAAY,SAAS;IACnB,UAAU,eAAe;IACzB,SAAS,cAAc;IACvB,YAAY,iBAAiB;IAC7B,WAAW,gBAAgB;IAC3B,mBAAmB,wBAAwB;IAC3C,qBAAqB,0BAA0B;IAC/C,QAAQ,aAAa;IACrB,yBAAyB,8BAA8B;CACxD;AAKD,oBAAY,eAAe;IACzB,aAAa,kBAAkB;IAC/B,qBAAqB,2BAA2B;IAChD,aAAa,kBAAkB;IAC/B,sBAAsB,2BAA2B;IACjD,WAAW,gBAAgB;IAC3B,oBAAoB,yBAAyB;IAC7C,aAAa,kBAAkB;IAC/B,sBAAsB,2BAA2B;IACjD,YAAY,iBAAiB;IAC7B,YAAY,iBAAiB;IAC7B,mBAAmB,wBAAwB;IAC3C,mBAAmB,wBAAwB;IAC3C,0BAA0B,+BAA+B;IACzD,iBAAiB,sBAAsB;IACvC,0BAA0B,+BAA+B;IACzD,4BAA4B,iCAAiC;IAC7D,qBAAqB,0BAA0B;IAC/C,4BAA4B,iCAAiC;IAC7D,mBAAmB,wBAAwB;IAC3C,UAAU,eAAe;IACzB,mBAAmB,wBAAwB;IAC3C,YAAY,iBAAiB;IAC7B,YAAY,iBAAiB;IAC7B,cAAc,mBAAmB;IACjC,cAAc,mBAAmB;IACjC,cAAc,mBAAmB;CAClC;AAED,oBAAY,kBAAkB;IAC5B,MAAM,kBAAkB;CACzB;AAED,oBAAY,YAAY;IACtB,MAAM,IAAI;IACV,SAAS,MAAM;CAChB;AAED,oBAAY,UAAU;IACpB,eAAe,mEAAmE;IAClF,qBAAqB,yEAAyE;IAC9F,eAAe,qCAAqC;CACrD"}
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthErrors = exports.EntityHeader = exports.HeadersPlaceHolder = exports.PermissionsEnum = exports.RolesEnum = exports.BOLTTECH_ENABLE_IDP_AUTH = exports.BOLTTECH_PLATFORM_IDP = exports.BOLTTECH_ENABLE_IDP_AUTH_ENV_KEY = exports.BOLTTECH_PLATFORM_ENV_KEY = exports.AUTH_SERVICE_TOKEN = void 0;
4
+ // TODO: deprecated
5
+ exports.AUTH_SERVICE_TOKEN = 'AUTH_SERVICE';
6
+ // Env var that identifies the running platform.
7
+ exports.BOLTTECH_PLATFORM_ENV_KEY = 'BOLTTECH_PLATFORM';
8
+ // Env var that re-enables auth on the idp platform when set to ENABLE_IDP_AUTH.
9
+ exports.BOLTTECH_ENABLE_IDP_AUTH_ENV_KEY = 'ENABLE_IDP_AUTH';
10
+ // Platform value for which auth is disabled by default.
11
+ exports.BOLTTECH_PLATFORM_IDP = 'idp';
12
+ // Value of ENABLE_IDP_AUTH that re-enables auth on the idp platform.
13
+ exports.BOLTTECH_ENABLE_IDP_AUTH = 'true';
14
+ // TODO: Tem a vantagem de disponibilizar constantes para as aplicações,
15
+ // mas exige que a cada novo role seja feito um deploy desse pacote
16
+ // para ter uma nova constante.
17
+ var RolesEnum;
18
+ (function (RolesEnum) {
19
+ RolesEnum["ROLE_ADMIN"] = "ROLE_ADMIN";
20
+ RolesEnum["ROLE_USER"] = "ROLE_USER";
21
+ RolesEnum["ROLE_SERVICE"] = "ROLE_SERVICE";
22
+ RolesEnum["ROLE_BROKER"] = "ROLE_BROKER";
23
+ RolesEnum["ROLE_AGENT_LICENSED"] = "ROLE_AGENT_LICENSED";
24
+ RolesEnum["ROLE_AGENT_UNLICENSED"] = "ROLE_AGENT_UNLICENSED";
25
+ RolesEnum["ROLE_CRM"] = "ROLE_CRM";
26
+ RolesEnum["ROLE_SALES_AGENT_LICENSED"] = "ROLE_SALES_AGENT_LICENSED";
27
+ })(RolesEnum || (exports.RolesEnum = RolesEnum = {}));
28
+ // TODO: Tem a vantagem de disponibilizar constantes para as aplicações,
29
+ // mas exige que a cada nova permission seja feito um deploy desse pacote
30
+ // para ter uma nova constante.
31
+ var PermissionsEnum;
32
+ (function (PermissionsEnum) {
33
+ PermissionsEnum["ENTITY_CREATE"] = "ENTITY.CREATE";
34
+ PermissionsEnum["ENTITY_REATE_ONLY_OWN"] = "ENTITY.CREATE_ONLY_OWN";
35
+ PermissionsEnum["ENTITY_DELETE"] = "ENTITY.DELETE";
36
+ PermissionsEnum["ENTITY_DELETE_ONLY_OWN"] = "ENTITY.DELETE_ONLY_OWN";
37
+ PermissionsEnum["ENTITY_READ"] = "ENTITY.READ";
38
+ PermissionsEnum["ENTITY_READ_ONLY_OWN"] = "ENTITY.READ_ONLY_OWN";
39
+ PermissionsEnum["ENTITY_UPDATE"] = "ENTITY.UPDATE";
40
+ PermissionsEnum["ENTITY_UPDATE_ONLY_OWN"] = "ENTITY.UPDATE_ONLY_OWN";
41
+ PermissionsEnum["QUOTE_CREATE"] = "QUOTE.CREATE";
42
+ PermissionsEnum["QUOTE_DELETE"] = "QUOTE.DELETE";
43
+ PermissionsEnum["QUOTE_ENTITY_CREATE"] = "QUOTE.ENTITY.CREATE";
44
+ PermissionsEnum["QUOTE_ENTITY_DELETE"] = "QUOTE.ENTITY.DELETE";
45
+ PermissionsEnum["QUOTE_ENTITY_LICENSED_FLOW"] = "QUOTE.ENTITY.LICENSED_FLOW";
46
+ PermissionsEnum["QUOTE_ENTITY_READ"] = "QUOTE.ENTITY.READ";
47
+ PermissionsEnum["QUOTE_ENTITY_READ_ONLY_OWN"] = "QUOTE.ENTITY.READ_ONLY_OWN";
48
+ PermissionsEnum["QUOTE_ENTITY_SHOW_COMMISSION"] = "QUOTE.ENTITY.SHOW_COMMISSION";
49
+ PermissionsEnum["QUOTE_ENTITY_TRANSFER"] = "QUOTE.ENTITY.TRANSFER";
50
+ PermissionsEnum["QUOTE_ENTITY_UNLICENSED_FLOW"] = "QUOTE.ENTITY.UNLICENSED_FLOW";
51
+ PermissionsEnum["QUOTE_ENTITY_UPDATE"] = "QUOTE.ENTITY.UPDATE";
52
+ PermissionsEnum["QUOTE_READ"] = "QUOTE.READ";
53
+ PermissionsEnum["QUOTE_READ_ONLY_OWN"] = "QUOTE.READ_ONLY_OWN";
54
+ PermissionsEnum["QUOTE_UPDATE"] = "QUOTE.UPDATE";
55
+ PermissionsEnum["STORAGE_READ"] = "STORAGE.READ";
56
+ PermissionsEnum["STORAGE_CREATE"] = "STORAGE.CREATE";
57
+ PermissionsEnum["STORAGE_UPDATE"] = "STORAGE.UPDATE";
58
+ PermissionsEnum["STORAGE_DELETE"] = "STORAGE.DELETE";
59
+ })(PermissionsEnum || (exports.PermissionsEnum = PermissionsEnum = {}));
60
+ var HeadersPlaceHolder;
61
+ (function (HeadersPlaceHolder) {
62
+ HeadersPlaceHolder["ENTITY"] = "x-auth-entity";
63
+ })(HeadersPlaceHolder || (exports.HeadersPlaceHolder = HeadersPlaceHolder = {}));
64
+ var EntityHeader;
65
+ (function (EntityHeader) {
66
+ EntityHeader[EntityHeader["LENGTH"] = 1] = "LENGTH";
67
+ EntityHeader["SEPARATOR"] = "#";
68
+ })(EntityHeader || (exports.EntityHeader = EntityHeader = {}));
69
+ var AuthErrors;
70
+ (function (AuthErrors) {
71
+ AuthErrors["MANDATORY_ROLES"] = "Must have at least one of the mandatory roles for the endpoint";
72
+ AuthErrors["MANDATORY_PERMISSIONS"] = "Must have at least one of the mandatory permissions for the endpoint";
73
+ AuthErrors["UNSUPPORTED_IDP"] = "IdP not supported in auth module";
74
+ })(AuthErrors || (exports.AuthErrors = AuthErrors = {}));
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Route-level equivalents of the `@Roles`, `@Permissions` and `@Resources`
3
+ * decorators. Fastify has no decorators, so each one returns a fragment of the
4
+ * route `config`. Spread them together:
5
+ *
6
+ * app.get('/x', { config: { ...Roles('ROLE_ADMIN'), ...Permissions('A') } }, handler)
7
+ */
8
+ export declare const Roles: (...roles: string[]) => {
9
+ roles: string[];
10
+ };
11
+ export declare const Permissions: (...permissions: string[]) => {
12
+ permissions: string[];
13
+ };
14
+ export declare const Resources: (...resources: string[]) => {
15
+ resources: string[];
16
+ };
17
+ //# sourceMappingURL=decorators.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../../src/decorators.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,eAAO,MAAM,KAAK,GAAI,GAAG,OAAO,MAAM,EAAE;;CAAgB,CAAC;AACzD,eAAO,MAAM,WAAW,GAAI,GAAG,aAAa,MAAM,EAAE;;CAAsB,CAAC;AAC3E,eAAO,MAAM,SAAS,GAAI,GAAG,WAAW,MAAM,EAAE;;CAAoB,CAAC"}
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Resources = exports.Permissions = exports.Roles = void 0;
4
+ /**
5
+ * Route-level equivalents of the `@Roles`, `@Permissions` and `@Resources`
6
+ * decorators. Fastify has no decorators, so each one returns a fragment of the
7
+ * route `config`. Spread them together:
8
+ *
9
+ * app.get('/x', { config: { ...Roles('ROLE_ADMIN'), ...Permissions('A') } }, handler)
10
+ */
11
+ const Roles = (...roles) => ({ roles });
12
+ exports.Roles = Roles;
13
+ const Permissions = (...permissions) => ({ permissions });
14
+ exports.Permissions = Permissions;
15
+ const Resources = (...resources) => ({ resources });
16
+ exports.Resources = Resources;
@@ -0,0 +1,20 @@
1
+ import type { FastifyReply, FastifyRequest } from 'fastify';
2
+ import type { OAuth2ParamsInterface, UserInterface } from '../interfaces';
3
+ export declare const AUTH_SERVICE_TOKEN_PROVIDER_NAME = "auth-service";
4
+ export declare const getJwksUri: (params: Pick<OAuth2ParamsInterface, "baseUrl">) => import("node:url").URL;
5
+ /**
6
+ * Verifies tokens issued by the custom Auth Service against its JWKS.
7
+ * The signing key is cached per `kid` and fetched again once when the
8
+ * signature does not match (key rotation).
9
+ */
10
+ export declare class AuthServiceTokenVerifier {
11
+ private readonly client;
12
+ private readonly keys;
13
+ constructor(params: Pick<OAuth2ParamsInterface, 'baseUrl'>);
14
+ verify(token: string): Promise<UserInterface>;
15
+ private verifyWith;
16
+ private getKey;
17
+ }
18
+ export declare function authServiceAuthenticate(request: FastifyRequest, reply: FastifyReply, verifier: AuthServiceTokenVerifier): Promise<boolean>;
19
+ export declare function authServiceAuthorize(request: FastifyRequest, reply: FastifyReply): Promise<boolean>;
20
+ //# sourceMappingURL=auth-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-service.d.ts","sourceRoot":"","sources":["../../../src/hooks/auth-service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAK5D,OAAO,KAAK,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAG1E,eAAO,MAAM,gCAAgC,iBAAiB,CAAC;AAK/D,eAAO,MAAM,UAAU,GAAI,QAAQ,IAAI,CAAC,qBAAqB,EAAE,SAAS,CAAC,2BAIxE,CAAC;AAEF;;;;GAIG;AACH,qBAAa,wBAAwB;IACnC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAa;IACpC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6B;gBAEtC,MAAM,EAAE,IAAI,CAAC,qBAAqB,EAAE,SAAS,CAAC;IAQpD,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC;IAWnD,OAAO,CAAC,UAAU;YAiBJ,MAAM;CAarB;AAED,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,cAAc,EACvB,KAAK,EAAE,YAAY,EACnB,QAAQ,EAAE,wBAAwB,GACjC,OAAO,CAAC,OAAO,CAAC,CAkClB;AAED,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,cAAc,EACvB,KAAK,EAAE,YAAY,GAClB,OAAO,CAAC,OAAO,CAAC,CAgDlB"}