@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
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthServiceTokenVerifier = exports.getJwksUri = exports.AUTH_SERVICE_TOKEN_PROVIDER_NAME = void 0;
4
+ exports.authServiceAuthenticate = authServiceAuthenticate;
5
+ exports.authServiceAuthorize = authServiceAuthorize;
6
+ const tslib_1 = require("tslib");
7
+ const debug_1 = tslib_1.__importDefault(require("debug"));
8
+ const jsonwebtoken_1 = tslib_1.__importDefault(require("jsonwebtoken"));
9
+ const jwks_rsa_1 = tslib_1.__importDefault(require("jwks-rsa"));
10
+ const isEmpty_1 = tslib_1.__importDefault(require("lodash/isEmpty"));
11
+ const constants_1 = require("../constants");
12
+ const util_1 = require("../util");
13
+ exports.AUTH_SERVICE_TOKEN_PROVIDER_NAME = 'auth-service';
14
+ const debugAuthn = (0, debug_1.default)('auth-module:auth-service-auth-middleware');
15
+ const debugAuthz = (0, debug_1.default)('auth-module:Keycloak-auth-guard');
16
+ const getJwksUri = (params) => {
17
+ const url = new URL(params.baseUrl);
18
+ url.pathname = '/oidc/jwks';
19
+ return url;
20
+ };
21
+ exports.getJwksUri = getJwksUri;
22
+ /**
23
+ * Verifies tokens issued by the custom Auth Service against its JWKS.
24
+ * The signing key is cached per `kid` and fetched again once when the
25
+ * signature does not match (key rotation).
26
+ */
27
+ class AuthServiceTokenVerifier {
28
+ client;
29
+ keys = new Map();
30
+ constructor(params) {
31
+ // jwks-rsa cache is off: keys are cached here so a rotation can be forced.
32
+ this.client = (0, jwks_rsa_1.default)({
33
+ jwksUri: (0, exports.getJwksUri)(params).href,
34
+ cache: false,
35
+ });
36
+ }
37
+ async verify(token) {
38
+ try {
39
+ return await this.verifyWith(token, false);
40
+ }
41
+ catch (error) {
42
+ if (error.message === 'invalid signature') {
43
+ return this.verifyWith(token, true);
44
+ }
45
+ throw error;
46
+ }
47
+ }
48
+ verifyWith(token, refresh) {
49
+ return new Promise((resolve, reject) => {
50
+ jsonwebtoken_1.default.verify(token, (header, callback) => {
51
+ this.getKey(header, refresh).then(key => callback(null, key), err => callback(err));
52
+ }, undefined, (error, decoded) => error ? reject(error) : resolve(decoded));
53
+ });
54
+ }
55
+ async getKey(header, refresh) {
56
+ const kid = header.kid;
57
+ const cached = this.keys.get(kid);
58
+ if (cached && !refresh)
59
+ return cached;
60
+ const key = (await this.client.getSigningKey(kid));
61
+ const signingKey = (key.publicKey || key.rsaPublicKey);
62
+ this.keys.set(kid, signingKey);
63
+ return signingKey;
64
+ }
65
+ }
66
+ exports.AuthServiceTokenVerifier = AuthServiceTokenVerifier;
67
+ async function authServiceAuthenticate(request, reply, verifier) {
68
+ if ((0, util_1.isAuthDisabled)()) {
69
+ debugAuthn('[INFO] Auth disabled via BOLTTECH_PLATFORM=idp, bypassing middleware');
70
+ return true;
71
+ }
72
+ try {
73
+ const token = (0, util_1.getToken)(request);
74
+ debugAuthn('[INFO] Bearer token = %s', token);
75
+ if (!token) {
76
+ await reply.code(401).send({ status: false, message: 'Unauthorized' });
77
+ return false;
78
+ }
79
+ const user = await verifier.verify(token);
80
+ debugAuthn('[INFO] User data = %s', JSON.stringify(user));
81
+ request.auth.setUser(user);
82
+ request.auth.setToken(token);
83
+ request.auth.setEntityHeader();
84
+ request.auth.setTokenProvider(exports.AUTH_SERVICE_TOKEN_PROVIDER_NAME);
85
+ return true;
86
+ }
87
+ catch (error) {
88
+ debugAuthn('[ERROR] %O', error);
89
+ await reply.code(401).send((0, util_1.errorFormatter)(error));
90
+ return false;
91
+ }
92
+ }
93
+ async function authServiceAuthorize(request, reply) {
94
+ if ((0, util_1.isAuthDisabled)()) {
95
+ debugAuthz('[INFO] Auth disabled via BOLTTECH_PLATFORM=idp, bypassing guard');
96
+ return true;
97
+ }
98
+ try {
99
+ const { roles, permissions } = request.routeOptions.config;
100
+ debugAuthz('[INFO] Mapped endpoint roles = %O', roles);
101
+ debugAuthz('[INFO] Mapped endpoint permissions = %O', permissions);
102
+ if (!Array.isArray(roles) && !Array.isArray(permissions)) {
103
+ debugAuthz('[INFO] Unmapped endpoint');
104
+ return true;
105
+ }
106
+ const { user } = request;
107
+ debugAuthz('[INFO] User roles = %O', user?.roles);
108
+ debugAuthz('[INFO] User permissions = %O', user?.permissions);
109
+ if (!user ||
110
+ !Array.isArray(user.roles) ||
111
+ !Array.isArray(user.permissions)) {
112
+ debugAuthz('[INFO] User without roles and permissions');
113
+ return true;
114
+ }
115
+ if (!hasAny(roles, user.roles)) {
116
+ throw new Error(constants_1.AuthErrors.MANDATORY_ROLES);
117
+ }
118
+ if (!hasAny(permissions, user.permissions)) {
119
+ throw new Error(constants_1.AuthErrors.MANDATORY_PERMISSIONS);
120
+ }
121
+ return true;
122
+ }
123
+ catch (error) {
124
+ debugAuthz('[ERROR] %O', error);
125
+ await reply.code(403).send((0, util_1.errorFormatter)(error));
126
+ return false;
127
+ }
128
+ }
129
+ function hasAny(endpoint = [], user = []) {
130
+ if ((0, isEmpty_1.default)(endpoint))
131
+ return true;
132
+ if ((0, isEmpty_1.default)(user))
133
+ return false;
134
+ return endpoint.some(item => user.includes(item));
135
+ }
@@ -0,0 +1,16 @@
1
+ import type { FastifyReply, FastifyRequest } from 'fastify';
2
+ import { type ConfigSource } from '../config';
3
+ /**
4
+ * Picks the identity provider from the token claims and authenticates:
5
+ * `roles` + `permissions` means the Auth Service, `realm_access` +
6
+ * `resource_access` means Keycloak. Same behavior as `AuthMiddleware` of
7
+ * `@edirect/auth`.
8
+ */
9
+ export declare function createAutoAuthenticate(config: ConfigSource): (request: FastifyRequest, reply: FastifyReply) => Promise<boolean>;
10
+ /**
11
+ * Authorizes according to the provider that authenticated the request. Same
12
+ * behavior as `AuthGuard` of `@edirect/auth`, including letting a request
13
+ * through when no authentication ran (no `tokenProvider`).
14
+ */
15
+ export declare function createAutoAuthorize(config: ConfigSource): (request: FastifyRequest, reply: FastifyReply) => Promise<boolean>;
16
+ //# sourceMappingURL=auto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto.d.ts","sourceRoot":"","sources":["../../../src/hooks/auto.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAI5D,OAAO,EAAwB,KAAK,YAAY,EAAE,MAAM,WAAW,CAAC;AA8BpE;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,YAAY,IAIvD,SAAS,cAAc,EACvB,OAAO,YAAY,KAClB,OAAO,CAAC,OAAO,CAAC,CAsDpB;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,YAAY,IAEpD,SAAS,cAAc,EACvB,OAAO,YAAY,KAClB,OAAO,CAAC,OAAO,CAAC,CAiCpB"}
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createAutoAuthenticate = createAutoAuthenticate;
4
+ exports.createAutoAuthorize = createAutoAuthorize;
5
+ const tslib_1 = require("tslib");
6
+ const debug_1 = tslib_1.__importDefault(require("debug"));
7
+ const jwt = tslib_1.__importStar(require("jsonwebtoken"));
8
+ const has_1 = tslib_1.__importDefault(require("lodash/has"));
9
+ const constants_1 = require("../constants");
10
+ const config_1 = require("../config");
11
+ const util_1 = require("../util");
12
+ const auth_service_1 = require("./auth-service");
13
+ const keycloak_1 = require("./keycloak");
14
+ const debugAuthn = (0, debug_1.default)('auth-module:auth-middleware');
15
+ const debugAuthz = (0, debug_1.default)('auth-module:auth-guard');
16
+ const keycloakParams = (wrapper) => ({
17
+ baseUrl: wrapper.get('KEYCLOAK_BASE_URL'),
18
+ wellKnownPath: [
19
+ '/realms',
20
+ wrapper.get('KEYCLOAK_REALM'),
21
+ '.well-known/openid-configuration',
22
+ ].join('/'),
23
+ grantType: 'client_credentials',
24
+ clientId: wrapper.get('KEYCLOAK_CLIENT'),
25
+ });
26
+ /**
27
+ * Picks the identity provider from the token claims and authenticates:
28
+ * `roles` + `permissions` means the Auth Service, `realm_access` +
29
+ * `resource_access` means Keycloak. Same behavior as `AuthMiddleware` of
30
+ * `@edirect/auth`.
31
+ */
32
+ function createAutoAuthenticate(config) {
33
+ const verifiers = new Map();
34
+ return async function autoAuthenticate(request, reply) {
35
+ if ((0, util_1.isAuthDisabled)()) {
36
+ debugAuthn('[INFO] Auth disabled via BOLTTECH_PLATFORM=idp, bypassing middleware');
37
+ return true;
38
+ }
39
+ const wrapper = new config_1.ConfigServiceWrapper(config, request);
40
+ const token = (0, util_1.getToken)(request);
41
+ debugAuthn('[INFO] Bearer token = %s', token);
42
+ if (!token) {
43
+ await reply.code(401).send({ status: false, message: 'Unauthorized' });
44
+ return false;
45
+ }
46
+ const decoded = jwt.decode(token);
47
+ debugAuthn('[INFO] Token decoded = %s', JSON.stringify(decoded));
48
+ if (!decoded) {
49
+ await reply.code(401).send({ status: false, message: 'Invalid token' });
50
+ return false;
51
+ }
52
+ if ((0, util_1.checkPropertiesObject)(decoded, ['roles', 'permissions'])) {
53
+ const baseUrl = new URL(wrapper.get('AUTH_SERVICE_JWKS')).origin;
54
+ let verifier = verifiers.get(baseUrl);
55
+ if (!verifier) {
56
+ verifier = new auth_service_1.AuthServiceTokenVerifier({ baseUrl });
57
+ verifiers.set(baseUrl, verifier);
58
+ }
59
+ debugAuthn('[INFO] AuthServiceAuthMiddleware with baseUrl = %s', baseUrl);
60
+ return (0, auth_service_1.authServiceAuthenticate)(request, reply, verifier);
61
+ }
62
+ if ((0, util_1.checkPropertiesObject)(decoded, ['realm_access', 'resource_access'])) {
63
+ const params = keycloakParams(wrapper);
64
+ debugAuthn('[INFO] KeycloakAuthMiddleware with params = %O', params);
65
+ return (0, keycloak_1.keycloakAuthenticate)(request, reply, params);
66
+ }
67
+ debugAuthn('[WARN] AuthMiddleware defaut flow: %s', constants_1.AuthErrors.UNSUPPORTED_IDP);
68
+ await reply
69
+ .code(500)
70
+ .send({ status: false, message: constants_1.AuthErrors.UNSUPPORTED_IDP });
71
+ return false;
72
+ };
73
+ }
74
+ /**
75
+ * Authorizes according to the provider that authenticated the request. Same
76
+ * behavior as `AuthGuard` of `@edirect/auth`, including letting a request
77
+ * through when no authentication ran (no `tokenProvider`).
78
+ */
79
+ function createAutoAuthorize(config) {
80
+ return async function autoAuthorize(request, reply) {
81
+ if ((0, util_1.isAuthDisabled)()) {
82
+ debugAuthz('[INFO] Auth disabled via BOLTTECH_PLATFORM=idp, bypassing guard');
83
+ return true;
84
+ }
85
+ debugAuthz('[INFO] tokenProvider = %s', request.tokenProvider);
86
+ if (!(0, has_1.default)(request, 'tokenProvider') || !request.tokenProvider)
87
+ return true;
88
+ switch (request.tokenProvider) {
89
+ case auth_service_1.AUTH_SERVICE_TOKEN_PROVIDER_NAME:
90
+ return (0, auth_service_1.authServiceAuthorize)(request, reply);
91
+ case keycloak_1.KEYCLOAK_TOKEN_PROVIDER_NAME: {
92
+ const params = keycloakParams(new config_1.ConfigServiceWrapper(config, request));
93
+ debugAuthz('[INFO] KeycloakAuthGuard with params = %O', params);
94
+ return (0, keycloak_1.keycloakAuthorize)(request, reply, params);
95
+ }
96
+ default:
97
+ debugAuthz('[WARN] AuthGuard defaut flow: %s', constants_1.AuthErrors.UNSUPPORTED_IDP);
98
+ await reply
99
+ .code(500)
100
+ .send({ status: false, message: constants_1.AuthErrors.UNSUPPORTED_IDP });
101
+ return false;
102
+ }
103
+ };
104
+ }
@@ -0,0 +1,21 @@
1
+ import type { FastifyReply, FastifyRequest } from 'fastify';
2
+ import type { OAuth2ParamsInterface } from '../interfaces';
3
+ export declare const KEYCLOAK_TOKEN_PROVIDER_NAME = "keycloak";
4
+ export type KeycloakAuthConfig = {
5
+ baseUrl: string;
6
+ realm: string;
7
+ timeout?: number;
8
+ };
9
+ export declare const getKeycloakAuthConfig: (params: OAuth2ParamsInterface) => KeycloakAuthConfig;
10
+ /**
11
+ * Keycloak authentication. Decodes the token without verifying the signature
12
+ * (verification happens in the authorization step) and sets `request.user`.
13
+ * Returns true to continue, false when a response was already sent.
14
+ */
15
+ export declare function keycloakAuthenticate(request: FastifyRequest, reply: FastifyReply, params: OAuth2ParamsInterface): Promise<boolean>;
16
+ /**
17
+ * Keycloak authorization from the route `config` (`roles`, `permissions`,
18
+ * `resources`). Returns true to continue, false when a response was sent.
19
+ */
20
+ export declare function keycloakAuthorize(request: FastifyRequest, reply: FastifyReply, params: OAuth2ParamsInterface): Promise<boolean>;
21
+ //# sourceMappingURL=keycloak.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keycloak.d.ts","sourceRoot":"","sources":["../../../src/hooks/keycloak.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAQ5D,OAAO,KAAK,EAAuB,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAIhF,eAAO,MAAM,4BAA4B,aAAa,CAAC;AAYvD,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAChC,QAAQ,qBAAqB,KAC5B,kBAQD,CAAC;AAEH;;;;GAIG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,cAAc,EACvB,KAAK,EAAE,YAAY,EACnB,MAAM,EAAE,qBAAqB,GAC5B,OAAO,CAAC,OAAO,CAAC,CA2ClB;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,cAAc,EACvB,KAAK,EAAE,YAAY,EACnB,MAAM,EAAE,qBAAqB,GAC5B,OAAO,CAAC,OAAO,CAAC,CA2FlB"}
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getKeycloakAuthConfig = exports.KEYCLOAK_TOKEN_PROVIDER_NAME = void 0;
4
+ exports.keycloakAuthenticate = keycloakAuthenticate;
5
+ exports.keycloakAuthorize = keycloakAuthorize;
6
+ const tslib_1 = require("tslib");
7
+ const debug_1 = tslib_1.__importDefault(require("debug"));
8
+ const jwt = tslib_1.__importStar(require("jsonwebtoken"));
9
+ const keycloak_authorization_services_1 = require("keycloak-authorization-services");
10
+ const isEmpty_1 = tslib_1.__importDefault(require("lodash/isEmpty"));
11
+ const constants_1 = require("../constants");
12
+ const interfaces_1 = require("../interfaces");
13
+ const util_1 = require("../util");
14
+ exports.KEYCLOAK_TOKEN_PROVIDER_NAME = 'keycloak';
15
+ const debugAuthn = (0, debug_1.default)('auth-module:keycloak-auth-middleware');
16
+ const debugAuthz = (0, debug_1.default)('auth-module:Keycloak-auth-guard');
17
+ const getKeycloakAuthConfig = (params) => ({
18
+ baseUrl: params.baseUrl,
19
+ realm: params.wellKnownPath
20
+ .split('/')
21
+ .filter(i => i)
22
+ .at(1) ?? '',
23
+ timeout: parseInt(process.env.HTTP_TIMEOUT ?? '30000'),
24
+ });
25
+ exports.getKeycloakAuthConfig = getKeycloakAuthConfig;
26
+ /**
27
+ * Keycloak authentication. Decodes the token without verifying the signature
28
+ * (verification happens in the authorization step) and sets `request.user`.
29
+ * Returns true to continue, false when a response was already sent.
30
+ */
31
+ async function keycloakAuthenticate(request, reply, params) {
32
+ if ((0, util_1.isAuthDisabled)()) {
33
+ debugAuthn('[INFO] Auth disabled via BOLTTECH_PLATFORM=idp, bypassing middleware');
34
+ return true;
35
+ }
36
+ try {
37
+ const token = (0, util_1.getToken)(request);
38
+ debugAuthn('[INFO] Bearer token = %s', token);
39
+ if (!token) {
40
+ await reply.code(401).send({ status: false, message: 'Unauthorized' });
41
+ return false;
42
+ }
43
+ const decoded = jwt.decode(token);
44
+ debugAuthn('[INFO] Token decoded = %s', JSON.stringify(decoded));
45
+ if (!decoded) {
46
+ await reply.code(401).send({ status: false, message: 'Invalid token' });
47
+ return false;
48
+ }
49
+ const user = (0, interfaces_1.keycloakAccessTokenToUserInterface)(decoded, params.clientId);
50
+ debugAuthn('[INFO] User data = %s', JSON.stringify(user));
51
+ request.auth.setUser(user);
52
+ request.auth.setToken(token);
53
+ request.auth.setEntityHeader();
54
+ request.auth.setTokenProvider(exports.KEYCLOAK_TOKEN_PROVIDER_NAME);
55
+ return true;
56
+ }
57
+ catch (error) {
58
+ debugAuthn('[ERROR] %O', error);
59
+ await reply.code(401).send((0, util_1.errorFormatter)(error));
60
+ return false;
61
+ }
62
+ }
63
+ /**
64
+ * Keycloak authorization from the route `config` (`roles`, `permissions`,
65
+ * `resources`). Returns true to continue, false when a response was sent.
66
+ */
67
+ async function keycloakAuthorize(request, reply, params) {
68
+ if ((0, util_1.isAuthDisabled)()) {
69
+ debugAuthz('[INFO] Auth disabled via BOLTTECH_PLATFORM=idp, bypassing guard');
70
+ return true;
71
+ }
72
+ const config = (0, exports.getKeycloakAuthConfig)(params);
73
+ try {
74
+ const token = (request.headers.authorization || '').replace('Bearer ', '');
75
+ debugAuthz('[INFO] Token = %s', token);
76
+ const { resources, roles, permissions } = request.routeOptions.config;
77
+ debugAuthz('[INFO] Mapped endpoint resources = %O', resources);
78
+ debugAuthz('[INFO] Mapped endpoint roles = %O', roles);
79
+ debugAuthz('[INFO] Mapped endpoint permissions = %O', permissions);
80
+ const hasResources = !(0, isEmpty_1.default)(resources);
81
+ const hasRoles = !(0, isEmpty_1.default)(roles);
82
+ const hasPermissions = !(0, isEmpty_1.default)(permissions);
83
+ if ([hasResources, hasRoles, hasPermissions].every(i => !i)) {
84
+ debugAuthz('[INFO] Unmapped endpoint');
85
+ return true;
86
+ }
87
+ const caller = request.headers['x-caller'];
88
+ const isCallerKrakend = (Array.isArray(caller) ? caller[0] : caller || '').toLowerCase() ===
89
+ 'krakend';
90
+ debugAuthz('[INFO] Is the krakend caller? %s', String(isCallerKrakend));
91
+ let onlyDecode = hasResources || isCallerKrakend;
92
+ debugAuthz('[INFO] Should it just decode? %s', String(onlyDecode));
93
+ if (hasRoles) {
94
+ const authError = new Error(constants_1.AuthErrors.MANDATORY_ROLES);
95
+ await validateByRoles(token, config, params, onlyDecode, roles, authError);
96
+ onlyDecode = true;
97
+ }
98
+ if (hasPermissions) {
99
+ debugAuthz('[INFO] Validating permissions');
100
+ const authError = new Error(constants_1.AuthErrors.MANDATORY_PERMISSIONS);
101
+ await validateByRoles(token, config, params, onlyDecode, permissions, authError);
102
+ }
103
+ if (hasResources && !isCallerKrakend) {
104
+ const permission = { resource: resources[0] };
105
+ const options = {
106
+ audience: params.clientId,
107
+ permission,
108
+ };
109
+ debugAuthz('[INFO] Validating resources with configs %O', config);
110
+ debugAuthz('[INFO] Validating resources with options %O', options);
111
+ await (0, keycloak_authorization_services_1.validationByPermission)(token, config, options);
112
+ }
113
+ return true;
114
+ }
115
+ catch (error) {
116
+ debugAuthz('[ERROR] %O', error);
117
+ await reply.code(403).send((0, util_1.errorFormatter)(error));
118
+ return false;
119
+ }
120
+ }
121
+ async function validateByRoles(token, config, params, onlyDecode, roles, authError) {
122
+ try {
123
+ const options = {
124
+ decodedType: onlyDecode ? 'decode' : 'verify',
125
+ permission: { client: params.clientId, roles },
126
+ };
127
+ debugAuthz('[INFO] Validating roles with configs = %O', config);
128
+ debugAuthz('[INFO] Validating roles with options = %O', options);
129
+ await (0, keycloak_authorization_services_1.validationByRoles)(token, config, options);
130
+ }
131
+ catch (error) {
132
+ debugAuthz('[ERROR][validateByRoles] %O', error);
133
+ const err = error;
134
+ if (err.code && parseInt(err.code) === 401) {
135
+ throw authError;
136
+ }
137
+ throw error;
138
+ }
139
+ }
@@ -0,0 +1,11 @@
1
+ import type { FastifyReply, FastifyRequest } from 'fastify';
2
+ import type { OAuth2ParamsInterface } from '../interfaces';
3
+ import type { AuthCache } from '../providers/memory-cache';
4
+ import type { KeycloakTokenExchangeService } from '../providers/keycloak-token-exchange.service';
5
+ /**
6
+ * Replaces an external Keycloak token by an internal one before
7
+ * authentication. The original token and its user stay available as
8
+ * `request.externalToken` and `request.externalUser`.
9
+ */
10
+ export declare function createTokenExchange(exchangeService: KeycloakTokenExchangeService, cache: AuthCache, params: OAuth2ParamsInterface): (request: FastifyRequest, reply: FastifyReply) => Promise<boolean>;
11
+ //# sourceMappingURL=token-exchange.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-exchange.d.ts","sourceRoot":"","sources":["../../../src/hooks/token-exchange.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE5D,OAAO,KAAK,EAGV,qBAAqB,EACtB,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,8CAA8C,CAAC;AAKjG;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,eAAe,EAAE,4BAA4B,EAC7C,KAAK,EAAE,SAAS,EAChB,MAAM,EAAE,qBAAqB,IAoD3B,SAAS,cAAc,EACvB,OAAO,YAAY,KAClB,OAAO,CAAC,OAAO,CAAC,CAoBpB"}
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTokenExchange = createTokenExchange;
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 interfaces_1 = require("../interfaces");
8
+ const util_1 = require("../util");
9
+ const debug = (0, debug_1.default)('auth-module:keycloak-auth-token-exchange-middleware');
10
+ /**
11
+ * Replaces an external Keycloak token by an internal one before
12
+ * authentication. The original token and its user stay available as
13
+ * `request.externalToken` and `request.externalUser`.
14
+ */
15
+ function createTokenExchange(exchangeService, cache, params) {
16
+ async function replace(request, externalToken) {
17
+ const isExternalToken = await exchangeService.isExternalToken(externalToken);
18
+ debug('[INFO] Is it external token? %s', String(isExternalToken));
19
+ if (!isExternalToken)
20
+ return externalToken;
21
+ const decoded = jwt.decode(externalToken);
22
+ request.auth.setExternalToken(externalToken);
23
+ request.auth.setExternalUser((0, interfaces_1.keycloakAccessTokenToUserInterface)(decoded, params.clientId));
24
+ const key = externalToken;
25
+ const cached = await cache.get(key);
26
+ debug('[INFO] Get Cache with key %s = %s', key, cached);
27
+ if (cached) {
28
+ return JSON.parse(cached).access_token;
29
+ }
30
+ const identityProviderName = `${decoded?.partner_id ||
31
+ decoded?.entity?.rootEntityId ||
32
+ decoded?.entity?.entityId}-oidc`;
33
+ debug('[INFO] Identity provider name = %s', identityProviderName);
34
+ const exchanged = await exchangeService.exchangeExternalTokenForInternalToken(externalToken, identityProviderName);
35
+ let ttl = (exchanged.expires_in - 30) * 1000;
36
+ if (!(ttl > 0))
37
+ ttl = 30 * 1000;
38
+ await cache.set(key, JSON.stringify(exchanged), ttl);
39
+ return exchanged.access_token;
40
+ }
41
+ return async function tokenExchange(request, reply) {
42
+ try {
43
+ const token = (0, util_1.getToken)(request);
44
+ debug('[INFO] Original token = %s', token);
45
+ if (!token || token === 'undefined') {
46
+ await reply.code(401).send({ status: false, message: 'Unauthorized' });
47
+ return false;
48
+ }
49
+ (0, util_1.setToken)(request, await replace(request, token));
50
+ return true;
51
+ }
52
+ catch (error) {
53
+ debug('[ERROR] %O', error);
54
+ await reply.code(401).send((0, util_1.errorFormatter)(error));
55
+ return false;
56
+ }
57
+ };
58
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import './types';
2
+ export { authFastifyPlugin, authFastifyPlugin as default } from './plugin';
3
+ export type { AuthFastifyOptions, RouteMatcher } from './plugin';
4
+ export { AuthService } from './auth.service';
5
+ export { Roles, Permissions, Resources } from './decorators';
6
+ export { ConfigMissingError, ConfigServiceWrapper, processEnvConfig, } from './config';
7
+ export type { ConfigSource } from './config';
8
+ export { getProcessEnvByRealmKey, getRealmEnvKey } from './realm-env-key';
9
+ export { AUTH_SERVICE_TOKEN, PermissionsEnum, RolesEnum, AuthErrors, } from './constants';
10
+ export type { VerticalsEnum } from './constants';
11
+ export { KEYCLOAK_TOKEN_PROVIDER_NAME } from './hooks/keycloak';
12
+ export { AUTH_SERVICE_TOKEN_PROVIDER_NAME } from './hooks/auth-service';
13
+ export { MemoryAuthCache } from './providers/memory-cache';
14
+ export type { AuthCache } from './providers/memory-cache';
15
+ export { WellKnownService } from './providers/well-known.service';
16
+ export { KeycloakTokenExchangeService } from './providers/keycloak-token-exchange.service';
17
+ export type { AuthServiceInterface, EntityInterface, EntityUserInterface, FieldsInterface, JWTToken, KeycloakAccessToken, KeycloakResponseAccessToken, OAuth2ParamsInterface, UserInterface, WellKnown, } from './interfaces';
18
+ export { getEntityAttributeByClient, keycloakAccessTokenToEntityUserInterface, keycloakAccessTokenToUserInterface, } from './interfaces';
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,CAAC;AAEjB,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,IAAI,OAAO,EAAE,MAAM,UAAU,CAAC;AAC3E,YAAY,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAEjE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,gBAAgB,GACjB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,SAAS,EACT,UAAU,GACX,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,4BAA4B,EAAE,MAAM,6CAA6C,CAAC;AAE3F,YAAY,EACV,oBAAoB,EACpB,eAAe,EACf,mBAAmB,EACnB,eAAe,EACf,QAAQ,EACR,mBAAmB,EACnB,2BAA2B,EAC3B,qBAAqB,EACrB,aAAa,EACb,SAAS,GACV,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,0BAA0B,EAC1B,wCAAwC,EACxC,kCAAkC,GACnC,MAAM,cAAc,CAAC"}
package/src/index.js ADDED
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.keycloakAccessTokenToUserInterface = exports.keycloakAccessTokenToEntityUserInterface = exports.getEntityAttributeByClient = exports.KeycloakTokenExchangeService = exports.WellKnownService = exports.MemoryAuthCache = exports.AUTH_SERVICE_TOKEN_PROVIDER_NAME = exports.KEYCLOAK_TOKEN_PROVIDER_NAME = exports.AuthErrors = exports.RolesEnum = exports.PermissionsEnum = exports.AUTH_SERVICE_TOKEN = exports.getRealmEnvKey = exports.getProcessEnvByRealmKey = exports.processEnvConfig = exports.ConfigServiceWrapper = exports.ConfigMissingError = exports.Resources = exports.Permissions = exports.Roles = exports.AuthService = exports.default = exports.authFastifyPlugin = void 0;
4
+ require("./types");
5
+ var plugin_1 = require("./plugin");
6
+ Object.defineProperty(exports, "authFastifyPlugin", { enumerable: true, get: function () { return plugin_1.authFastifyPlugin; } });
7
+ Object.defineProperty(exports, "default", { enumerable: true, get: function () { return plugin_1.authFastifyPlugin; } });
8
+ var auth_service_1 = require("./auth.service");
9
+ Object.defineProperty(exports, "AuthService", { enumerable: true, get: function () { return auth_service_1.AuthService; } });
10
+ var decorators_1 = require("./decorators");
11
+ Object.defineProperty(exports, "Roles", { enumerable: true, get: function () { return decorators_1.Roles; } });
12
+ Object.defineProperty(exports, "Permissions", { enumerable: true, get: function () { return decorators_1.Permissions; } });
13
+ Object.defineProperty(exports, "Resources", { enumerable: true, get: function () { return decorators_1.Resources; } });
14
+ var config_1 = require("./config");
15
+ Object.defineProperty(exports, "ConfigMissingError", { enumerable: true, get: function () { return config_1.ConfigMissingError; } });
16
+ Object.defineProperty(exports, "ConfigServiceWrapper", { enumerable: true, get: function () { return config_1.ConfigServiceWrapper; } });
17
+ Object.defineProperty(exports, "processEnvConfig", { enumerable: true, get: function () { return config_1.processEnvConfig; } });
18
+ var realm_env_key_1 = require("./realm-env-key");
19
+ Object.defineProperty(exports, "getProcessEnvByRealmKey", { enumerable: true, get: function () { return realm_env_key_1.getProcessEnvByRealmKey; } });
20
+ Object.defineProperty(exports, "getRealmEnvKey", { enumerable: true, get: function () { return realm_env_key_1.getRealmEnvKey; } });
21
+ var constants_1 = require("./constants");
22
+ Object.defineProperty(exports, "AUTH_SERVICE_TOKEN", { enumerable: true, get: function () { return constants_1.AUTH_SERVICE_TOKEN; } });
23
+ Object.defineProperty(exports, "PermissionsEnum", { enumerable: true, get: function () { return constants_1.PermissionsEnum; } });
24
+ Object.defineProperty(exports, "RolesEnum", { enumerable: true, get: function () { return constants_1.RolesEnum; } });
25
+ Object.defineProperty(exports, "AuthErrors", { enumerable: true, get: function () { return constants_1.AuthErrors; } });
26
+ var keycloak_1 = require("./hooks/keycloak");
27
+ Object.defineProperty(exports, "KEYCLOAK_TOKEN_PROVIDER_NAME", { enumerable: true, get: function () { return keycloak_1.KEYCLOAK_TOKEN_PROVIDER_NAME; } });
28
+ var auth_service_2 = require("./hooks/auth-service");
29
+ Object.defineProperty(exports, "AUTH_SERVICE_TOKEN_PROVIDER_NAME", { enumerable: true, get: function () { return auth_service_2.AUTH_SERVICE_TOKEN_PROVIDER_NAME; } });
30
+ var memory_cache_1 = require("./providers/memory-cache");
31
+ Object.defineProperty(exports, "MemoryAuthCache", { enumerable: true, get: function () { return memory_cache_1.MemoryAuthCache; } });
32
+ var well_known_service_1 = require("./providers/well-known.service");
33
+ Object.defineProperty(exports, "WellKnownService", { enumerable: true, get: function () { return well_known_service_1.WellKnownService; } });
34
+ var keycloak_token_exchange_service_1 = require("./providers/keycloak-token-exchange.service");
35
+ Object.defineProperty(exports, "KeycloakTokenExchangeService", { enumerable: true, get: function () { return keycloak_token_exchange_service_1.KeycloakTokenExchangeService; } });
36
+ var interfaces_1 = require("./interfaces");
37
+ Object.defineProperty(exports, "getEntityAttributeByClient", { enumerable: true, get: function () { return interfaces_1.getEntityAttributeByClient; } });
38
+ Object.defineProperty(exports, "keycloakAccessTokenToEntityUserInterface", { enumerable: true, get: function () { return interfaces_1.keycloakAccessTokenToEntityUserInterface; } });
39
+ Object.defineProperty(exports, "keycloakAccessTokenToUserInterface", { enumerable: true, get: function () { return interfaces_1.keycloakAccessTokenToUserInterface; } });
@@ -0,0 +1,14 @@
1
+ import type { KeycloakAccessToken } from './keycloak-token.interface';
2
+ export interface EntityUserInterface {
3
+ entityId?: string;
4
+ accountId?: string;
5
+ entityUserId?: string;
6
+ email?: string;
7
+ firstName?: string;
8
+ lastName?: string;
9
+ phone?: string;
10
+ rootEntityId?: string;
11
+ entities?: string[];
12
+ }
13
+ export declare function keycloakAccessTokenToEntityUserInterface(data: KeycloakAccessToken): EntityUserInterface;
14
+ //# sourceMappingURL=entity-user.interface.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entity-user.interface.d.ts","sourceRoot":"","sources":["../../../src/interfaces/entity-user.interface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAKtE,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;IAsBtB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAED,wBAAgB,wCAAwC,CACtD,IAAI,EAAE,mBAAmB,GACxB,mBAAmB,CAerB"}
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.keycloakAccessTokenToEntityUserInterface = keycloakAccessTokenToEntityUserInterface;
4
+ const user_interface_1 = require("./user.interface");
5
+ function keycloakAccessTokenToEntityUserInterface(data) {
6
+ return {
7
+ entityId: (0, user_interface_1.getEntityAttributeByClient)(data, data.azp, 'entityId'),
8
+ accountId: (0, user_interface_1.getEntityAttributeByClient)(data, data.azp, 'accountId'),
9
+ entityUserId: (0, user_interface_1.getEntityAttributeByClient)(data, data.azp, 'entityUserId'),
10
+ rootEntityId: (0, user_interface_1.getEntityAttributeByClient)(data, data.azp, 'rootEntityId'),
11
+ email: data?.email,
12
+ firstName: data?.given_name || data?.clientId,
13
+ lastName: data?.family_name || data?.preferred_username,
14
+ phone: data?.phone_number,
15
+ entities: (0, user_interface_1.getEntityAttributeByClient)(data, data.azp, 'branches') ||
16
+ (0, user_interface_1.getEntityAttributeByClient)(data, data.azp, 'entities') ||
17
+ [],
18
+ };
19
+ }
@@ -0,0 +1,25 @@
1
+ import { VerticalsEnum } from '../constants';
2
+ export interface EntityInterface {
3
+ name?: string;
4
+ key?: string;
5
+ billingType?: 'STANDARD' | 'DEFERRED';
6
+ entityType?: 'COMPANY';
7
+ logo?: string;
8
+ fields?: FieldsInterface;
9
+ partnerIds?: string[];
10
+ createdAt?: Date;
11
+ udpatedAt?: Date;
12
+ deletedAt?: Date;
13
+ verticals?: VerticalsEnum[];
14
+ showPartnerPanel?: boolean;
15
+ productName?: object;
16
+ bankDetailsRequired?: boolean;
17
+ branding?: object;
18
+ }
19
+ export interface FieldsInterface {
20
+ partnerId: {
21
+ required: boolean;
22
+ maxlength: number;
23
+ };
24
+ }
25
+ //# sourceMappingURL=entity.interface.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entity.interface.d.ts","sourceRoot":"","sources":["../../../src/interfaces/entity.interface.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAI7C,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IACtC,UAAU,CAAC,EAAE,SAAS,CAAC;IACvB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,eAAe,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,SAAS,CAAC,EAAE,IAAI,CAAC;IACjB,SAAS,CAAC,EAAE,IAAI,CAAC;IACjB,SAAS,CAAC,EAAE,IAAI,CAAC;IACjB,SAAS,CAAC,EAAE,aAAa,EAAE,CAAC;IAC5B,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE;QACT,QAAQ,EAAE,OAAO,CAAC;QAClB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;CACH"}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });