@telia-ace/alliance-internal-node-utilities 1.0.4 → 1.0.5-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,300 +1,46 @@
1
- import { InjectPinoLogger, LoggerModule as LoggerModule$1, PinoLogger } from 'nestjs-pino';
2
- export { LoggerErrorInterceptor } from 'nestjs-pino';
3
- import { Store } from 'express-session';
4
- import { auth } from 'express-openid-connect';
5
- import { createClient } from 'redis';
1
+ import jwt from 'jsonwebtoken';
6
2
  import { z } from 'zod';
7
- import { sign } from 'jsonwebtoken';
8
3
  import { validate } from 'jsonschema';
9
4
  import { existsSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
10
5
  import { resolve } from 'node:path';
11
- import { GraphQLError } from 'graphql';
12
- import { HttpStatus, HttpException, Catch, Injectable, Module } from '@nestjs/common';
13
- import { ConfigModule, ConfigService } from '@nestjs/config';
14
- import { HealthIndicator } from '@nestjs/terminus';
15
6
  import _slugify from 'slugify';
7
+ import pino from 'pino';
16
8
 
17
- var __defProp = Object.defineProperty;
18
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
19
- var noop = /* @__PURE__ */ __name((_err, _data) => {
20
- }, "noop");
21
- var RedisStore = class RedisStore2 extends Store {
22
- static {
23
- __name(this, "RedisStore");
24
- }
25
- constructor(opts) {
26
- super();
27
- this.prefix = opts.prefix == null ? "sess:" : opts.prefix;
28
- this.scanCount = opts.scanCount || 100;
29
- this.serializer = opts.serializer || JSON;
30
- this.ttl = opts.ttl || 86400;
31
- this.disableTTL = opts.disableTTL || false;
32
- this.disableTouch = opts.disableTouch || false;
33
- this.client = this.normalizeClient(opts.client);
34
- }
35
- // Create a redis and ioredis compatible client
36
- normalizeClient(client) {
37
- let isRedis = "scanIterator" in client;
38
- return {
39
- get: (key) => client.get(key),
40
- set: (key, val, ttl) => {
41
- if (ttl) {
42
- return isRedis ? client.set(key, val, {
43
- EX: ttl
44
- }) : client.set(key, val, "EX", ttl);
45
- }
46
- return client.set(key, val);
47
- },
48
- del: (key) => client.del(key),
49
- expire: (key, ttl) => client.expire(key, ttl),
50
- mget: (keys) => isRedis ? client.mGet(keys) : client.mget(keys),
51
- scanIterator: (match, count) => {
52
- if (isRedis)
53
- return client.scanIterator({
54
- MATCH: match,
55
- COUNT: count
56
- });
57
- return async function* () {
58
- let [c, xs] = await client.scan("0", "MATCH", match, "COUNT", count);
59
- for (let key of xs)
60
- yield key;
61
- while (c !== "0") {
62
- [c, xs] = await client.scan(c, "MATCH", match, "COUNT", count);
63
- for (let key of xs)
64
- yield key;
65
- }
66
- }();
67
- }
68
- };
69
- }
70
- async get(sid, cb = noop) {
71
- let key = this.prefix + sid;
72
- try {
73
- let data = await this.client.get(key);
74
- if (!data)
75
- return cb();
76
- return cb(null, await this.serializer.parse(data));
77
- } catch (err) {
78
- return cb(err);
79
- }
80
- }
81
- async set(sid, sess, cb = noop) {
82
- let key = this.prefix + sid;
83
- let ttl = this._getTTL(sess);
84
- try {
85
- let val = this.serializer.stringify(sess);
86
- if (ttl > 0) {
87
- if (this.disableTTL)
88
- await this.client.set(key, val);
89
- else
90
- await this.client.set(key, val, ttl);
91
- return cb();
92
- } else {
93
- return this.destroy(sid, cb);
94
- }
95
- } catch (err) {
96
- return cb(err);
97
- }
98
- }
99
- async touch(sid, sess, cb = noop) {
100
- let key = this.prefix + sid;
101
- if (this.disableTouch || this.disableTTL)
102
- return cb();
103
- try {
104
- await this.client.expire(key, this._getTTL(sess));
105
- return cb();
106
- } catch (err) {
107
- return cb(err);
108
- }
109
- }
110
- async destroy(sid, cb = noop) {
111
- let key = this.prefix + sid;
112
- try {
113
- await this.client.del([
114
- key
115
- ]);
116
- return cb();
117
- } catch (err) {
118
- return cb(err);
119
- }
120
- }
121
- async clear(cb = noop) {
122
- try {
123
- let keys = await this._getAllKeys();
124
- if (!keys.length)
125
- return cb();
126
- await this.client.del(keys);
127
- return cb();
128
- } catch (err) {
129
- return cb(err);
130
- }
131
- }
132
- async length(cb = noop) {
133
- try {
134
- let keys = await this._getAllKeys();
135
- return cb(null, keys.length);
136
- } catch (err) {
137
- return cb(err);
138
- }
139
- }
140
- async ids(cb = noop) {
141
- let len = this.prefix.length;
142
- try {
143
- let keys = await this._getAllKeys();
144
- return cb(null, keys.map((k) => k.substring(len)));
145
- } catch (err) {
146
- return cb(err);
147
- }
148
- }
149
- async all(cb = noop) {
150
- let len = this.prefix.length;
151
- try {
152
- let keys = await this._getAllKeys();
153
- if (keys.length === 0)
154
- return cb(null, []);
155
- let data = await this.client.mget(keys);
156
- let results = data.reduce((acc, raw, idx) => {
157
- if (!raw)
158
- return acc;
159
- let sess = this.serializer.parse(raw);
160
- sess.id = keys[idx].substring(len);
161
- acc.push(sess);
162
- return acc;
163
- }, []);
164
- return cb(null, results);
165
- } catch (err) {
166
- return cb(err);
167
- }
168
- }
169
- _getTTL(sess) {
170
- if (typeof this.ttl === "function") {
171
- return this.ttl(sess);
172
- }
173
- let ttl;
174
- if (sess && sess.cookie && sess.cookie.expires) {
175
- let ms = Number(new Date(sess.cookie.expires)) - Date.now();
176
- ttl = Math.ceil(ms / 1e3);
177
- } else {
178
- ttl = this.ttl;
179
- }
180
- return ttl;
181
- }
182
- async _getAllKeys() {
183
- let pattern = this.prefix + "*";
184
- let keys = [];
185
- for await (let key of this.client.scanIterator(pattern, this.scanCount)) {
186
- keys.push(key);
187
- }
188
- return keys;
189
- }
190
- };
191
- var esm_default = RedisStore;
192
- var SharedConfigKeys;
193
- (function(SharedConfigKeys2) {
194
- SharedConfigKeys2["AuthCookieName"] = "AUTH_COOKIE_NAME";
195
- SharedConfigKeys2["AuthCookieSecret"] = "AUTH_COOKIE_SECRET";
196
- SharedConfigKeys2["DbEndpoint"] = "DB_ENDPOINT";
197
- SharedConfigKeys2["JwtPrivateKey"] = "JWT_PRIVATE_KEY";
198
- SharedConfigKeys2["ServiceLogLevel"] = "SERVICE_LOG_LEVEL";
199
- SharedConfigKeys2["ServicePort"] = "SERVICE_PORT";
200
- SharedConfigKeys2["RedisHost"] = "REDIS_HOST";
201
- SharedConfigKeys2["RedisPassword"] = "REDIS_PASSWORD";
202
- })(SharedConfigKeys || (SharedConfigKeys = {}));
203
- var zBooleanEnum = z.enum([
204
- "true",
205
- "false"
206
- ]).transform((strBool) => strBool === "true");
207
- var zNonEmptyString = z.string().min(1);
208
- var zSharedConfig = z.object({
209
- ["AUTH_COOKIE_NAME"]: zNonEmptyString.default("alliance-auth"),
210
- ["AUTH_COOKIE_SECRET"]: zNonEmptyString.default("zlLZBlk7wt8lypP5lA4D"),
211
- ["DB_ENDPOINT"]: zNonEmptyString,
212
- ["JWT_PRIVATE_KEY"]: zNonEmptyString.default("MIIEogIBAAKCAQEAsGqOzjnfQtCYlDqhgGAnKuJOCiPt2WpCmL1Cs+SLBQlyoNn6LT8BJ6ZRj8t/vK8Sw0p51Uq/3k0tazh7bLGkWNMBLY3BqFiNRMMnCqHJfvGIUi/itNXNe2kbP7H3rbyQTu4O7yH/ZAMitdpF2KLucVRlFxrQ/ggZjxwEGso4JUnCwmAnoKct/uupKz9Y2PMTr00WWN79aPfD4LcKi570VJqBT3ISSucdwFLYNqnOkQnEa8O8xbthQhiI0k1GGJT+GCQcATUPeEbaCFXonOrJm+CyuMmQWYLFF3NbE5NllU1jz9PYHzp2hAgAx8WGeretTvpEA1dE2gvXNESGbQ8FxQIDAQABAoIBAAjTJmud1348eGAfLV8CRaij2MAxxenJ9/ozVXfcPIa2+fCelsuBSv8pwbYODvNoVT7xpcs2nwccGI6JgnBl09EhqlMWCT7w7GLT2aBy3A/T6JF76xJICQGzDfWPYygMtlyhv0YqZDUjjFlJHun+/ysqIUMY81AR0FLUAEc6yw41ChcdSvTgIqBM9f5PsBRK7zOgdW1vcVQiZbf2Vqr+7wTJ+6b9A4rWnnAqesGDXqYupx3UJEu3x0wRNQB8FeiG9iJrw4cyD9SmM95doTyKosQ2PWWnUO1NMgmWCR/mWcKZAUcfZUpnQ8rz75WAWept8ZIOOdha8UZ1B/kw3EsVdEECgYEA3iN0BRUqMN0J69bazvlNOWtI+Chc1lYMt/tZ4p78pIJpAZvc3rQ9lAp6JvOEno2IglULA4I+ZLUmpz+lfu7XxKMNOI3cnG7WdiGbiIlwOSwuxzeO1FJqhtnc0U6mNkIjptV8b2etj8U2/SXAC3CC8XgsawAj9A/I7awlCL3NXdECgYEAy07gun3rcd3Y0ISmd3+SbAn/MbGf8uRLcfSc2ls9B6m3pXj25prXJWIrB6DyGuL/HQmHzffQkOeXmwFGHFXyiIFOIITX4z8b9lMnavgUZoPDY+ZFsxp6I7vMn75AetB8wYXpOFFeCG/Ck/VSIYP7oAN8kLw8EHdOuNbZYbu34bUCgYBYd14ZOBiZZS4yUlrJ2tc6atOgoNJ4OcTO8LcXXaHYEmenUF9iAf4UGygSoyDJ1CvtW9kLCK+4g7xlFx/dsVkU4qq9PyIA2tNmMHQ0qCedXU8z35huTnRGSDV81gmzyhtQsezgoTWp8Cy6HHKjG6fKasWlx2SKKk8m+Eu3c396QQKBgBMY2asq4M7VU+RiUXCwHwTe+4Wjda7PGvcdTw6Du3vYyVNVxXtr2AG+8uPIjnVQFT6ZApSqToEOAAOjXv6SZDHGU5xiXhUOfIXq0a0OmHv4rIXZv3pPZmGs5k+rA0uGAfH7riiIHBkWxmQ3ivty9lPVgAHobIvvaQmbxNeVVnRxAoGAUzUmcBiUAiODfjulrpYvWG0tCn5B//yk7g1Tm3Chrh9huA1qGEN3jDoqSsTd5k4Yi5foyAZt5ORgoiUVm4IsfS56aoxIco1CtFG3zeMQRy4uKzTsvUTOdsJ4RlQdjNwpngXR44VL0WelgCDqTqJwn5ubzPvuIHuTj3cBpmJCjOo="),
213
- ["SERVICE_LOG_LEVEL"]: z.enum([
214
- "silent",
215
- "fatal",
216
- "error",
217
- "warn",
218
- "info",
219
- "debug",
220
- "trace"
221
- ]).default("trace"),
222
- ["SERVICE_PORT"]: zNonEmptyString.transform(Number).default("3000"),
223
- ["REDIS_HOST"]: zNonEmptyString.optional(),
224
- ["REDIS_PASSWORD"]: zNonEmptyString.optional()
225
- });
226
-
227
- // src/constants/headers.ts
228
- var AllianceHeaders;
229
- (function(AllianceHeaders2) {
230
- AllianceHeaders2["TargetUrl"] = "alliance-target-url";
231
- AllianceHeaders2["TargetApp"] = "alliance-target-app";
232
- AllianceHeaders2["TargetWorkspace"] = "alliance-target-workspace";
233
- })(AllianceHeaders || (AllianceHeaders = {}));
234
-
235
- // src/auth/auth.middleware.ts
236
- function authMiddleware(configService, { baseURL = "https://127.0.0.1", clientSecret, clientID = " ", authRequired = true, authorizationParams = {}, afterCallback, issuerBaseURL = "https://127.0.0.1", sessionCookiePath } = {}) {
237
- let store;
238
- const redisHostUrl = configService.get(SharedConfigKeys.RedisHost);
239
- if (redisHostUrl) {
240
- const redisClient = createClient({
241
- url: configService.getOrThrow(SharedConfigKeys.RedisHost),
242
- password: configService.get(SharedConfigKeys.RedisPassword)
243
- });
244
- redisClient.connect().catch(console.error);
245
- store = new esm_default({
246
- client: redisClient
247
- });
248
- }
249
- return auth({
250
- baseURL,
251
- clientSecret,
252
- clientID,
253
- authRequired,
254
- authorizationParams,
255
- afterCallback,
256
- issuerBaseURL,
257
- secret: configService.getOrThrow(SharedConfigKeys.AuthCookieSecret),
258
- session: {
259
- name: configService.getOrThrow(SharedConfigKeys.AuthCookieName),
260
- // @ts-ignore
261
- store,
262
- cookie: {
263
- path: sessionCookiePath
264
- }
9
+ // src/auth/tokens.ts
10
+ function createBearerToken({
11
+ privateKey,
12
+ aud,
13
+ sub,
14
+ name,
15
+ user,
16
+ workspace
17
+ }) {
18
+ const token = jwt.sign(
19
+ {
20
+ iss: "Alliance",
21
+ aud,
22
+ sub,
23
+ name,
24
+ "https://alliance.teliacompany.net/user_type": user.type,
25
+ "https://alliance.teliacompany.net/user_email": user.email,
26
+ "https://alliance.teliacompany.net/user_privileges": user.permissions,
27
+ "https://alliance.teliacompany.net/workspace": workspace.slug,
28
+ "https://alliance.teliacompany.net/workspace_name": workspace.name,
29
+ "https://alliance.teliacompany.net/tenant": workspace.slug,
30
+ "https://alliance.teliacompany.net/tenant_name": workspace.name
265
31
  },
266
- routes: {
267
- callback: "/signin-oidc"
32
+ privateKey,
33
+ {
34
+ expiresIn: "1h",
35
+ algorithm: "RS256"
268
36
  }
269
- });
270
- }
271
- __name(authMiddleware, "authMiddleware");
272
- function createBearerToken({ privateKey, aud, sub, name, user, workspace }) {
273
- const jwt = sign({
274
- iss: "Alliance",
275
- aud,
276
- sub,
277
- name,
278
- "https://alliance.teliacompany.net/user_type": user.type,
279
- "https://alliance.teliacompany.net/user_email": user.email,
280
- "https://alliance.teliacompany.net/user_privileges": user.permissions,
281
- "https://alliance.teliacompany.net/workspace": workspace.slug,
282
- "https://alliance.teliacompany.net/workspace_name": workspace.name,
283
- "https://alliance.teliacompany.net/tenant": workspace.slug,
284
- "https://alliance.teliacompany.net/tenant_name": workspace.name
285
- }, privateKey, {
286
- expiresIn: "1h",
287
- algorithm: "RS256"
288
- });
289
- return `Bearer ${jwt}`;
37
+ );
38
+ return `Bearer ${token}`;
290
39
  }
291
- __name(createBearerToken, "createBearerToken");
292
- function getPrivateKey(configService) {
293
- const privateKey = configService.getOrThrow(SharedConfigKeys.JwtPrivateKey);
294
- return "-----BEGIN RSA PRIVATE KEY-----\n" + privateKey + "\n-----END RSA PRIVATE KEY-----";
40
+ function getPrivateKey(config) {
41
+ return "-----BEGIN RSA PRIVATE KEY-----\n" + config.JWT_PRIVATE_KEY + "\n-----END RSA PRIVATE KEY-----";
295
42
  }
296
- __name(getPrivateKey, "getPrivateKey");
297
- function createSystemUserToken(configService) {
43
+ function createSystemUserToken(config) {
298
44
  return createBearerToken({
299
45
  aud: "system",
300
46
  sub: "system",
@@ -308,10 +54,69 @@ function createSystemUserToken(configService) {
308
54
  permissions: [],
309
55
  email: "system"
310
56
  },
311
- privateKey: getPrivateKey(configService)
57
+ privateKey: getPrivateKey(config)
312
58
  });
313
59
  }
314
- __name(createSystemUserToken, "createSystemUserToken");
60
+ var zBooleanEnum = z.enum(["true", "false"]).transform((strBool) => strBool === "true");
61
+ var zNonEmptyString = z.string().min(1);
62
+ var zSharedConfig = z.object({
63
+ /**
64
+ * Name for the cookie storing the user session
65
+ *
66
+ * Optional, defaults to "alliance-auth"
67
+ */
68
+ AUTH_COOKIE_NAME: zNonEmptyString.default("alliance-auth"),
69
+ /**
70
+ * Secret to use when signing the user session cookie
71
+ *
72
+ * Optional, defaults to "zlLZBlk7wt8lypP5lA4D"
73
+ */
74
+ AUTH_COOKIE_SECRET: zNonEmptyString.default("zlLZBlk7wt8lypP5lA4D"),
75
+ /**
76
+ * Endpoint to use when communicating with the Data API
77
+ */
78
+ DB_ENDPOINT: zNonEmptyString,
79
+ /**
80
+ * Private key to use when signing JWT tokens
81
+ *
82
+ * Optional, defaults to "MIIEogIBAAKCAQEAsGqOzjnfQtCYlDqhgGAnKuJOCiPt2WpCmL1Cs+SLBQlyoNn6LT8BJ6ZRj8t/vK8Sw0p51Uq/3k0tazh7bLGkWNMBLY3BqFiNRMMnCqHJfvGIUi/itNXNe2kbP7H3rbyQTu4O7yH/ZAMitdpF2KLucVRlFxrQ/ggZjxwEGso4JUnCwmAnoKct/uupKz9Y2PMTr00WWN79aPfD4LcKi570VJqBT3ISSucdwFLYNqnOkQnEa8O8xbthQhiI0k1GGJT+GCQcATUPeEbaCFXonOrJm+CyuMmQWYLFF3NbE5NllU1jz9PYHzp2hAgAx8WGeretTvpEA1dE2gvXNESGbQ8FxQIDAQABAoIBAAjTJmud1348eGAfLV8CRaij2MAxxenJ9/ozVXfcPIa2+fCelsuBSv8pwbYODvNoVT7xpcs2nwccGI6JgnBl09EhqlMWCT7w7GLT2aBy3A/T6JF76xJICQGzDfWPYygMtlyhv0YqZDUjjFlJHun+/ysqIUMY81AR0FLUAEc6yw41ChcdSvTgIqBM9f5PsBRK7zOgdW1vcVQiZbf2Vqr+7wTJ+6b9A4rWnnAqesGDXqYupx3UJEu3x0wRNQB8FeiG9iJrw4cyD9SmM95doTyKosQ2PWWnUO1NMgmWCR/mWcKZAUcfZUpnQ8rz75WAWept8ZIOOdha8UZ1B/kw3EsVdEECgYEA3iN0BRUqMN0J69bazvlNOWtI+Chc1lYMt/tZ4p78pIJpAZvc3rQ9lAp6JvOEno2IglULA4I+ZLUmpz+lfu7XxKMNOI3cnG7WdiGbiIlwOSwuxzeO1FJqhtnc0U6mNkIjptV8b2etj8U2/SXAC3CC8XgsawAj9A/I7awlCL3NXdECgYEAy07gun3rcd3Y0ISmd3+SbAn/MbGf8uRLcfSc2ls9B6m3pXj25prXJWIrB6DyGuL/HQmHzffQkOeXmwFGHFXyiIFOIITX4z8b9lMnavgUZoPDY+ZFsxp6I7vMn75AetB8wYXpOFFeCG/Ck/VSIYP7oAN8kLw8EHdOuNbZYbu34bUCgYBYd14ZOBiZZS4yUlrJ2tc6atOgoNJ4OcTO8LcXXaHYEmenUF9iAf4UGygSoyDJ1CvtW9kLCK+4g7xlFx/dsVkU4qq9PyIA2tNmMHQ0qCedXU8z35huTnRGSDV81gmzyhtQsezgoTWp8Cy6HHKjG6fKasWlx2SKKk8m+Eu3c396QQKBgBMY2asq4M7VU+RiUXCwHwTe+4Wjda7PGvcdTw6Du3vYyVNVxXtr2AG+8uPIjnVQFT6ZApSqToEOAAOjXv6SZDHGU5xiXhUOfIXq0a0OmHv4rIXZv3pPZmGs5k+rA0uGAfH7riiIHBkWxmQ3ivty9lPVgAHobIvvaQmbxNeVVnRxAoGAUzUmcBiUAiODfjulrpYvWG0tCn5B//yk7g1Tm3Chrh9huA1qGEN3jDoqSsTd5k4Yi5foyAZt5ORgoiUVm4IsfS56aoxIco1CtFG3zeMQRy4uKzTsvUTOdsJ4RlQdjNwpngXR44VL0WelgCDqTqJwn5ubzPvuIHuTj3cBpmJCjOo="
83
+ */
84
+ JWT_PRIVATE_KEY: zNonEmptyString.default(
85
+ "MIIEogIBAAKCAQEAsGqOzjnfQtCYlDqhgGAnKuJOCiPt2WpCmL1Cs+SLBQlyoNn6LT8BJ6ZRj8t/vK8Sw0p51Uq/3k0tazh7bLGkWNMBLY3BqFiNRMMnCqHJfvGIUi/itNXNe2kbP7H3rbyQTu4O7yH/ZAMitdpF2KLucVRlFxrQ/ggZjxwEGso4JUnCwmAnoKct/uupKz9Y2PMTr00WWN79aPfD4LcKi570VJqBT3ISSucdwFLYNqnOkQnEa8O8xbthQhiI0k1GGJT+GCQcATUPeEbaCFXonOrJm+CyuMmQWYLFF3NbE5NllU1jz9PYHzp2hAgAx8WGeretTvpEA1dE2gvXNESGbQ8FxQIDAQABAoIBAAjTJmud1348eGAfLV8CRaij2MAxxenJ9/ozVXfcPIa2+fCelsuBSv8pwbYODvNoVT7xpcs2nwccGI6JgnBl09EhqlMWCT7w7GLT2aBy3A/T6JF76xJICQGzDfWPYygMtlyhv0YqZDUjjFlJHun+/ysqIUMY81AR0FLUAEc6yw41ChcdSvTgIqBM9f5PsBRK7zOgdW1vcVQiZbf2Vqr+7wTJ+6b9A4rWnnAqesGDXqYupx3UJEu3x0wRNQB8FeiG9iJrw4cyD9SmM95doTyKosQ2PWWnUO1NMgmWCR/mWcKZAUcfZUpnQ8rz75WAWept8ZIOOdha8UZ1B/kw3EsVdEECgYEA3iN0BRUqMN0J69bazvlNOWtI+Chc1lYMt/tZ4p78pIJpAZvc3rQ9lAp6JvOEno2IglULA4I+ZLUmpz+lfu7XxKMNOI3cnG7WdiGbiIlwOSwuxzeO1FJqhtnc0U6mNkIjptV8b2etj8U2/SXAC3CC8XgsawAj9A/I7awlCL3NXdECgYEAy07gun3rcd3Y0ISmd3+SbAn/MbGf8uRLcfSc2ls9B6m3pXj25prXJWIrB6DyGuL/HQmHzffQkOeXmwFGHFXyiIFOIITX4z8b9lMnavgUZoPDY+ZFsxp6I7vMn75AetB8wYXpOFFeCG/Ck/VSIYP7oAN8kLw8EHdOuNbZYbu34bUCgYBYd14ZOBiZZS4yUlrJ2tc6atOgoNJ4OcTO8LcXXaHYEmenUF9iAf4UGygSoyDJ1CvtW9kLCK+4g7xlFx/dsVkU4qq9PyIA2tNmMHQ0qCedXU8z35huTnRGSDV81gmzyhtQsezgoTWp8Cy6HHKjG6fKasWlx2SKKk8m+Eu3c396QQKBgBMY2asq4M7VU+RiUXCwHwTe+4Wjda7PGvcdTw6Du3vYyVNVxXtr2AG+8uPIjnVQFT6ZApSqToEOAAOjXv6SZDHGU5xiXhUOfIXq0a0OmHv4rIXZv3pPZmGs5k+rA0uGAfH7riiIHBkWxmQ3ivty9lPVgAHobIvvaQmbxNeVVnRxAoGAUzUmcBiUAiODfjulrpYvWG0tCn5B//yk7g1Tm3Chrh9huA1qGEN3jDoqSsTd5k4Yi5foyAZt5ORgoiUVm4IsfS56aoxIco1CtFG3zeMQRy4uKzTsvUTOdsJ4RlQdjNwpngXR44VL0WelgCDqTqJwn5ubzPvuIHuTj3cBpmJCjOo="
86
+ ),
87
+ /**
88
+ * Log level to output
89
+ *
90
+ * Supports "silent" | "fatal" | "error" | "warn" | "info" | "debug" | "trace"
91
+ *
92
+ * Optional, defaults to "trace"
93
+ */
94
+ SERVICE_LOG_LEVEL: z.enum(["silent", "fatal", "error", "warn", "info", "debug", "trace"]).default("trace"),
95
+ /**
96
+ * Port to run the service on.
97
+ *
98
+ * Optional, defaults to "3000"
99
+ */
100
+ SERVICE_PORT: zNonEmptyString.transform(Number).default("3000"),
101
+ /**
102
+ * Url to redis server to use when storing / reading user session information.
103
+ */
104
+ REDIS_HOST: zNonEmptyString,
105
+ /**
106
+ * Password to redis server to use when storing / reading user session information.
107
+ *
108
+ * Optional
109
+ */
110
+ REDIS_PASSWORD: zNonEmptyString.optional()
111
+ });
112
+
113
+ // src/constants/headers.ts
114
+ var AllianceHeaders = /* @__PURE__ */ ((AllianceHeaders2) => {
115
+ AllianceHeaders2["TargetUrl"] = "alliance-target-url";
116
+ AllianceHeaders2["TargetApp"] = "alliance-target-app";
117
+ AllianceHeaders2["TargetWorkspace"] = "alliance-target-workspace";
118
+ return AllianceHeaders2;
119
+ })(AllianceHeaders || {});
315
120
 
316
121
  // src/distribution/cookie-policy.ts
317
122
  function generateCookiePolicyHtml(appManifests) {
@@ -328,11 +133,8 @@ function generateCookiePolicyHtml(appManifests) {
328
133
  }
329
134
  return cookiePolicyHtml.replace("{APP_COOKIES}", cookiePolicyTableRows.join(""));
330
135
  }
331
- __name(generateCookiePolicyHtml, "generateCookiePolicyHtml");
332
136
  function createCookiePolicyTableRow(key, claimEntry) {
333
- const rows = [
334
- "<tr>"
335
- ];
137
+ const rows = ["<tr>"];
336
138
  const { category, purpose, lifespan } = claimEntry;
337
139
  rows.push(`<td>${key}</td>`);
338
140
  rows.push(`<td>${category}</td>`);
@@ -341,7 +143,6 @@ function createCookiePolicyTableRow(key, claimEntry) {
341
143
  rows.push("</tr>");
342
144
  return rows.join("");
343
145
  }
344
- __name(createCookiePolicyTableRow, "createCookiePolicyTableRow");
345
146
  var cookiePolicyHtml = `
346
147
  <!DOCTYPE html>
347
148
  <html lang="en">
@@ -631,7 +432,12 @@ var cookiePolicyHtml = `
631
432
  </html>
632
433
  `;
633
434
  function getJsonSchemas() {
634
- const frameworkDistDirPath = resolve(process.cwd(), "node_modules", "@telia-ace/alliance-framework", "dist");
435
+ const frameworkDistDirPath = resolve(
436
+ process.cwd(),
437
+ "node_modules",
438
+ "@telia-ace/alliance-framework",
439
+ "dist"
440
+ );
635
441
  const appConfigSchemaPath = resolve(frameworkDistDirPath, "config.schema.json");
636
442
  const appManifestSchemaPath = resolve(frameworkDistDirPath, "manifest.schema.json");
637
443
  const appConfigSchemaFile = readFileSync(appConfigSchemaPath).toString();
@@ -643,17 +449,13 @@ function getJsonSchemas() {
643
449
  appManifest
644
450
  };
645
451
  }
646
- __name(getJsonSchemas, "getJsonSchemas");
647
452
  async function createTempModuleAndImport(moduleString, fileName) {
648
453
  const file = resolve(process.cwd(), `${fileName}.mjs`);
649
454
  writeFileSync(file, moduleString);
650
455
  const importedModule = await import(`file:///${file}`);
651
- rmSync(file, {
652
- force: true
653
- });
456
+ rmSync(file, { force: true });
654
457
  return importedModule;
655
458
  }
656
- __name(createTempModuleAndImport, "createTempModuleAndImport");
657
459
  async function getAppManifests(apps) {
658
460
  const moduleStringParts = [];
659
461
  const manifestImportVariables = [];
@@ -663,10 +465,12 @@ async function getAppManifests(apps) {
663
465
  moduleStringParts.push(`import ${manifestImportVariable} from '${packageName}/manifest';`);
664
466
  }
665
467
  moduleStringParts.push(`export default [${manifestImportVariables.join(", ")}];`);
666
- const result = await createTempModuleAndImport(moduleStringParts.join("\n"), "app-manifests");
468
+ const result = await createTempModuleAndImport(
469
+ moduleStringParts.join("\n"),
470
+ "app-manifests"
471
+ );
667
472
  return result.default;
668
473
  }
669
- __name(getAppManifests, "getAppManifests");
670
474
 
671
475
  // src/distribution/pkg-json.ts
672
476
  function getPkgJson() {
@@ -674,7 +478,6 @@ function getPkgJson() {
674
478
  const pkgJsonFile = readFileSync(packageJson).toString();
675
479
  return JSON.parse(pkgJsonFile);
676
480
  }
677
- __name(getPkgJson, "getPkgJson");
678
481
  async function getManifests(pkgJson) {
679
482
  if (!pkgJson || !pkgJson.alliance || !pkgJson.alliance.apps) {
680
483
  throw new Error("Alliance apps not defined in package.json.");
@@ -685,7 +488,6 @@ async function getManifests(pkgJson) {
685
488
  return acc;
686
489
  }, {});
687
490
  }
688
- __name(getManifests, "getManifests");
689
491
 
690
492
  // src/distribution/create-public-files.ts
691
493
  var PUBLIC_DIR_NAME = "public";
@@ -701,9 +503,13 @@ async function createPublicDistributionFiles() {
701
503
  const manifest = manifests[appName];
702
504
  const validationResult = validate(manifest, schemas.appManifest);
703
505
  if (validationResult.errors.length) {
704
- const errors = validationResult.errors.map((e) => JSON.stringify(e, null, 2));
705
- throw new Error(`Validation of app manifest for app '${appName}' failed with the following errors:
706
- ${errors.join("\n")}`);
506
+ const errors2 = validationResult.errors.map((e) => JSON.stringify(e, null, 2));
507
+ throw new Error(
508
+ `Validation of app manifest for app '${appName}' failed with the following errors:
509
+ ${errors2.join(
510
+ "\n"
511
+ )}`
512
+ );
707
513
  }
708
514
  }
709
515
  const publicDirPath = resolve(process.cwd(), PUBLIC_DIR_NAME);
@@ -719,370 +525,188 @@ ${errors.join("\n")}`);
719
525
  writeFileSync(appConfigSchemaFilePath, JSON.stringify(schemas.appConfig));
720
526
  writeFileSync(appManifestSchemaFilePath, JSON.stringify(schemas.appManifest));
721
527
  }
722
- __name(createPublicDistributionFiles, "createPublicDistributionFiles");
723
- var GatewayErrorCodes;
724
- (function(GatewayErrorCodes2) {
725
- GatewayErrorCodes2[GatewayErrorCodes2["NoObjectId"] = 10001] = "NoObjectId";
726
- GatewayErrorCodes2[GatewayErrorCodes2["NoTargetAppHeader"] = 10002] = "NoTargetAppHeader";
727
- GatewayErrorCodes2[GatewayErrorCodes2["NoTargetWorkspaceHeader"] = 10003] = "NoTargetWorkspaceHeader";
728
- GatewayErrorCodes2[GatewayErrorCodes2["NoManifestsInCache"] = 10004] = "NoManifestsInCache";
729
- GatewayErrorCodes2[GatewayErrorCodes2["NoDevSessionInCache"] = 10005] = "NoDevSessionInCache";
730
- GatewayErrorCodes2[GatewayErrorCodes2["NoManifest"] = 10006] = "NoManifest";
731
- GatewayErrorCodes2[GatewayErrorCodes2["NoRequestContext"] = 10007] = "NoRequestContext";
732
- GatewayErrorCodes2[GatewayErrorCodes2["NoUserInRequestContext"] = 10008] = "NoUserInRequestContext";
733
- GatewayErrorCodes2[GatewayErrorCodes2["NoAppInRequestContext"] = 10009] = "NoAppInRequestContext";
734
- GatewayErrorCodes2[GatewayErrorCodes2["NoWorkspaceInRequestContext"] = 10010] = "NoWorkspaceInRequestContext";
735
- GatewayErrorCodes2[GatewayErrorCodes2["NoUserPermissionsInRequestContext"] = 10012] = "NoUserPermissionsInRequestContext";
736
- GatewayErrorCodes2[GatewayErrorCodes2["WorkspacePermissionDenied"] = 10013] = "WorkspacePermissionDenied";
737
- })(GatewayErrorCodes || (GatewayErrorCodes = {}));
738
- var DatabasesErrorCodes;
739
- (function(DatabasesErrorCodes2) {
740
- DatabasesErrorCodes2[DatabasesErrorCodes2["NoPublicKey"] = 11e3] = "NoPublicKey";
741
- DatabasesErrorCodes2[DatabasesErrorCodes2["NoAuthHeader"] = 11001] = "NoAuthHeader";
742
- DatabasesErrorCodes2[DatabasesErrorCodes2["FailedFileStore"] = 11002] = "FailedFileStore";
743
- DatabasesErrorCodes2[DatabasesErrorCodes2["FailedFileRead"] = 11003] = "FailedFileRead";
744
- DatabasesErrorCodes2[DatabasesErrorCodes2["NoRecord"] = 11004] = "NoRecord";
745
- DatabasesErrorCodes2[DatabasesErrorCodes2["UniqueConstrain"] = 11005] = "UniqueConstrain";
746
- })(DatabasesErrorCodes || (DatabasesErrorCodes = {}));
747
- var PortalErrorCodes;
748
- (function(PortalErrorCodes2) {
749
- PortalErrorCodes2[PortalErrorCodes2["NoObjectId"] = 12e3] = "NoObjectId";
750
- })(PortalErrorCodes || (PortalErrorCodes = {}));
751
- var allianceErrors = {
752
- // gateway
753
- [10001]: {
754
- httpCode: HttpStatus.UNAUTHORIZED,
755
- message: "No object id available on authenticated user."
528
+ function slugify(name) {
529
+ return _slugify(name, { strict: true, replacement: "-", lower: true });
530
+ }
531
+ function logFn(instance) {
532
+ return (level) => {
533
+ return (msg, data) => instance[level]({ ...data, msg });
534
+ };
535
+ }
536
+ function createLogger(config) {
537
+ const instance = pino({
538
+ level: config.SERVICE_LOG_LEVEL,
539
+ redact: [
540
+ "authorization",
541
+ "headers.authorization",
542
+ "req.headers.authorization",
543
+ "res.headers.authorization",
544
+ "req.headers.cookie",
545
+ 'res.headers["set-cookie"]'
546
+ ]
547
+ });
548
+ return {
549
+ fatal: logFn(instance)("fatal"),
550
+ error: logFn(instance)("error"),
551
+ warn: logFn(instance)("warn"),
552
+ info: logFn(instance)("info"),
553
+ debug: logFn(instance)("debug"),
554
+ trace: logFn(instance)("trace"),
555
+ silent: logFn(instance)("silent"),
556
+ child: () => createLogger(config),
557
+ level: config.SERVICE_LOG_LEVEL
558
+ };
559
+ }
560
+ function requestLoggerHandler(logger) {
561
+ return (req, _, next) => {
562
+ logger.trace("received request", {
563
+ url: req.url,
564
+ params: req.params,
565
+ query: req.query,
566
+ body: req.body
567
+ });
568
+ return next();
569
+ };
570
+ }
571
+
572
+ // src/errors/codes.ts
573
+ var GatewayErrorCode = /* @__PURE__ */ ((GatewayErrorCode2) => {
574
+ GatewayErrorCode2[GatewayErrorCode2["NoObjectId"] = 10001] = "NoObjectId";
575
+ GatewayErrorCode2[GatewayErrorCode2["NoTargetAppHeader"] = 10002] = "NoTargetAppHeader";
576
+ GatewayErrorCode2[GatewayErrorCode2["NoTargetWorkspaceHeader"] = 10003] = "NoTargetWorkspaceHeader";
577
+ GatewayErrorCode2[GatewayErrorCode2["NoManifestsInCache"] = 10004] = "NoManifestsInCache";
578
+ GatewayErrorCode2[GatewayErrorCode2["NoDevSessionInCache"] = 10005] = "NoDevSessionInCache";
579
+ GatewayErrorCode2[GatewayErrorCode2["NoManifest"] = 10006] = "NoManifest";
580
+ GatewayErrorCode2[GatewayErrorCode2["NoRequestContext"] = 10007] = "NoRequestContext";
581
+ GatewayErrorCode2[GatewayErrorCode2["NoUserInRequestContext"] = 10008] = "NoUserInRequestContext";
582
+ GatewayErrorCode2[GatewayErrorCode2["NoAppInRequestContext"] = 10009] = "NoAppInRequestContext";
583
+ GatewayErrorCode2[GatewayErrorCode2["NoWorkspaceInRequestContext"] = 10010] = "NoWorkspaceInRequestContext";
584
+ GatewayErrorCode2[GatewayErrorCode2["NoUserPermissionsInRequestContext"] = 10012] = "NoUserPermissionsInRequestContext";
585
+ GatewayErrorCode2[GatewayErrorCode2["WorkspacePermissionDenied"] = 10013] = "WorkspacePermissionDenied";
586
+ GatewayErrorCode2[GatewayErrorCode2["NoTargetUrlHeader"] = 10014] = "NoTargetUrlHeader";
587
+ GatewayErrorCode2[GatewayErrorCode2["NoSessionInRedisCache"] = 10015] = "NoSessionInRedisCache";
588
+ return GatewayErrorCode2;
589
+ })(GatewayErrorCode || {});
590
+ var DataErrorCode = /* @__PURE__ */ ((DataErrorCode2) => {
591
+ DataErrorCode2[DataErrorCode2["NoPublicKey"] = 11e3] = "NoPublicKey";
592
+ DataErrorCode2[DataErrorCode2["NoAuthHeader"] = 11001] = "NoAuthHeader";
593
+ DataErrorCode2[DataErrorCode2["FailedFileUpload"] = 11002] = "FailedFileUpload";
594
+ DataErrorCode2[DataErrorCode2["FailedFileDownload"] = 11003] = "FailedFileDownload";
595
+ return DataErrorCode2;
596
+ })(DataErrorCode || {});
597
+ var errors = {
598
+ [10001 /* NoObjectId */]: {
599
+ statusCode: 401,
600
+ msg: "No object id available on authenticated user."
756
601
  },
757
- [10002]: {
758
- httpCode: HttpStatus.BAD_REQUEST,
759
- message: `Request missing header '${AllianceHeaders.TargetApp}'.`
602
+ [10002 /* NoTargetAppHeader */]: {
603
+ statusCode: 400,
604
+ msg: `Request missing header '${"alliance-target-app" /* TargetApp */}'.`
760
605
  },
761
- [10003]: {
762
- httpCode: HttpStatus.BAD_REQUEST,
763
- message: `Request missing header '${AllianceHeaders.TargetWorkspace}'.`
606
+ [10003 /* NoTargetWorkspaceHeader */]: {
607
+ statusCode: 400,
608
+ msg: `Request missing header '${"alliance-target-workspace" /* TargetWorkspace */}'.`
764
609
  },
765
- [10004]: {
766
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
767
- message: "App manifests missing in cache."
610
+ [10014 /* NoTargetUrlHeader */]: {
611
+ statusCode: 400,
612
+ msg: `Request missing header '${"alliance-target-url" /* TargetUrl */}'.`
768
613
  },
769
- [10005]: {
770
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
771
- message: "No dev session in memory cache."
614
+ [10004 /* NoManifestsInCache */]: {
615
+ statusCode: 500,
616
+ msg: "App manifests missing in cache."
772
617
  },
773
- [10006]: {
774
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
775
- message: "Could not find manifest for app '{{appSlug}}'."
618
+ [10005 /* NoDevSessionInCache */]: {
619
+ statusCode: 500,
620
+ msg: "No dev session in memory cache."
776
621
  },
777
- [10007]: {
778
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
779
- message: "No request context."
622
+ [10015 /* NoSessionInRedisCache */]: {
623
+ statusCode: 401,
624
+ msg: "Could not find user session in Redis server."
780
625
  },
781
- [10008]: {
782
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
783
- message: "No user in request context."
626
+ [10006 /* NoManifest */]: {
627
+ statusCode: 500,
628
+ msg: "Could not find manifest for app '{{appSlug}}'."
784
629
  },
785
- [10009]: {
786
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
787
- message: "No app in request context."
630
+ [10007 /* NoRequestContext */]: {
631
+ statusCode: 500,
632
+ msg: "No request context."
788
633
  },
789
- [10010]: {
790
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
791
- message: "No workspace in request context."
634
+ [10008 /* NoUserInRequestContext */]: {
635
+ statusCode: 500,
636
+ msg: "No user in request context."
792
637
  },
793
- [10012]: {
794
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
795
- message: "No user permissions in request context."
638
+ [10009 /* NoAppInRequestContext */]: {
639
+ statusCode: 500,
640
+ msg: "No app in request context."
796
641
  },
797
- [10013]: {
798
- httpCode: HttpStatus.FORBIDDEN,
799
- message: "User does not have access to the current workspace."
642
+ [10010 /* NoWorkspaceInRequestContext */]: {
643
+ statusCode: 500,
644
+ msg: "No workspace in request context."
800
645
  },
801
- // databases
802
- [11e3]: {
803
- httpCode: HttpStatus.UNAUTHORIZED,
804
- message: "No public key available to decode JWT."
646
+ [10012 /* NoUserPermissionsInRequestContext */]: {
647
+ statusCode: 500,
648
+ msg: "No user permissions in request context."
805
649
  },
806
- [11001]: {
807
- httpCode: HttpStatus.UNAUTHORIZED,
808
- message: "No authorization header found."
650
+ [10013 /* WorkspacePermissionDenied */]: {
651
+ statusCode: 403,
652
+ msg: "User does not have access to the current workspace."
809
653
  },
810
- [11002]: {
811
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
812
- message: "Error storing file."
654
+ [11e3 /* NoPublicKey */]: {
655
+ statusCode: 401,
656
+ msg: "No public key available to decode JWT."
813
657
  },
814
- [11003]: {
815
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
816
- message: "Error reading file."
658
+ [11001 /* NoAuthHeader */]: {
659
+ statusCode: 401,
660
+ msg: "No authorization header found."
817
661
  },
818
- [11004]: {
819
- httpCode: HttpStatus.INTERNAL_SERVER_ERROR,
820
- message: "Missing database record."
662
+ [11002 /* FailedFileUpload */]: {
663
+ statusCode: 500,
664
+ msg: "Something went wrong when trying to upload a file to the S3 storage."
821
665
  },
822
- [11005]: {
823
- httpCode: HttpStatus.CONFLICT,
824
- message: "Field has to be unique."
666
+ [11003 /* FailedFileDownload */]: {
667
+ statusCode: 500,
668
+ msg: "Something went wrong when trying to download a file to the S3 storage."
825
669
  },
826
- // portal
827
- [12e3]: {
828
- httpCode: HttpStatus.UNAUTHORIZED,
829
- message: "No object id found in user claims."
670
+ [12e3 /* NoObjectId */]: {
671
+ statusCode: 401,
672
+ msg: "No object id found in user claims."
830
673
  }
831
674
  };
832
675
 
833
- // src/exceptions/alliance-gql.exception.ts
834
- function parseTemplates(message, variables) {
835
- return Object.entries(variables).reduce((acc, [key, value]) => {
836
- return acc.replaceAll(`{{${key}}}`, value);
837
- }, message);
838
- }
839
- __name(parseTemplates, "parseTemplates");
840
- var AllianceGqlException = class extends GraphQLError {
841
- static {
842
- __name(this, "AllianceGqlException");
843
- }
844
- info;
845
- code;
846
- constructor(code, variables = {}, extensions) {
847
- const { message } = allianceErrors[code];
848
- super(parseTemplates(message, variables), {
849
- extensions
850
- });
851
- this.code = code;
852
- this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${code}`;
676
+ // src/errors/errors.ts
677
+ var AllianceError = class extends Error {
678
+ constructor(errorCode, variables = {}) {
679
+ const { msg, statusCode } = errors[errorCode];
680
+ const message = parseTemplates(msg, variables);
681
+ super(message);
682
+ this.errorCode = errorCode;
683
+ this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${this.errorCode}`;
684
+ this.message = message;
685
+ this.statusCode = statusCode;
853
686
  }
854
687
  };
855
- function parseTemplates2(message, variables) {
688
+ function parseTemplates(message, variables) {
856
689
  return Object.entries(variables).reduce((acc, [key, value]) => {
857
690
  return acc.replaceAll(`{{${key}}}`, value);
858
691
  }, message);
859
692
  }
860
- __name(parseTemplates2, "parseTemplates");
861
- var AllianceException = class extends HttpException {
862
- static {
863
- __name(this, "AllianceException");
864
- }
865
- info;
866
- code;
867
- constructor(code, variables = {}) {
868
- const { message, httpCode } = allianceErrors[code];
869
- super(parseTemplates2(message, variables), httpCode);
870
- this.code = code;
871
- this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${code}`;
872
- }
873
- };
874
- function _ts_decorate(decorators, target, key, desc) {
875
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
876
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
877
- r = Reflect.decorate(decorators, target, key, desc);
878
- else
879
- for (var i = decorators.length - 1; i >= 0; i--)
880
- if (d = decorators[i])
881
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
882
- return c > 3 && r && Object.defineProperty(target, key, r), r;
883
- }
884
- __name(_ts_decorate, "_ts_decorate");
885
- var AllianceExceptionFilter = class AllianceExceptionFilter2 {
886
- static {
887
- __name(this, "AllianceExceptionFilter");
888
- }
889
- catch(exception, host) {
890
- const ctx = host.switchToHttp();
891
- const response = ctx.getResponse();
892
- const status = exception.getStatus();
893
- response.status && response.status(status).json({
894
- httpCode: status,
895
- code: exception.code,
896
- info: exception.info,
897
- message: exception.message
898
- });
899
- }
900
- };
901
- AllianceExceptionFilter = _ts_decorate([
902
- Catch(AllianceException)
903
- ], AllianceExceptionFilter);
904
- function _ts_decorate2(decorators, target, key, desc) {
905
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
906
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
907
- r = Reflect.decorate(decorators, target, key, desc);
908
- else
909
- for (var i = decorators.length - 1; i >= 0; i--)
910
- if (d = decorators[i])
911
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
912
- return c > 3 && r && Object.defineProperty(target, key, r), r;
913
- }
914
- __name(_ts_decorate2, "_ts_decorate");
915
- function _ts_metadata(k, v) {
916
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
917
- return Reflect.metadata(k, v);
918
- }
919
- __name(_ts_metadata, "_ts_metadata");
920
- var RedisHealthIndicator = class RedisHealthIndicator2 extends HealthIndicator {
921
- static {
922
- __name(this, "RedisHealthIndicator");
923
- }
924
- configService;
925
- constructor(configService) {
926
- super();
927
- this.configService = configService;
928
- }
929
- async isHealthy() {
930
- try {
931
- const client = await this.getRedisClient();
932
- await client.ping();
933
- } catch {
934
- return this.getStatus("redis", false);
935
- }
936
- return this.getStatus("redis", true);
937
- }
938
- async getRedisClient() {
939
- const redisClient = createClient({
940
- url: this.configService.getOrThrow(SharedConfigKeys.RedisHost),
941
- password: this.configService.get(SharedConfigKeys.RedisPassword)
693
+ function requestErrorHandler(logger) {
694
+ return (err, req, res, _next) => {
695
+ const error = {
696
+ cause: err.cause,
697
+ message: err.message,
698
+ status: err.status || err.statusCode || err.code,
699
+ info: err.info
700
+ };
701
+ logger.error("error when processing request", {
702
+ url: req.url,
703
+ body: req.body,
704
+ error
942
705
  });
943
- await redisClient.connect();
944
- return redisClient;
945
- }
946
- };
947
- RedisHealthIndicator = _ts_decorate2([
948
- Injectable(),
949
- _ts_metadata("design:type", Function),
950
- _ts_metadata("design:paramtypes", [
951
- typeof ConfigService === "undefined" ? Object : ConfigService
952
- ])
953
- ], RedisHealthIndicator);
954
- function _ts_decorate3(decorators, target, key, desc) {
955
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
956
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
957
- r = Reflect.decorate(decorators, target, key, desc);
958
- else
959
- for (var i = decorators.length - 1; i >= 0; i--)
960
- if (d = decorators[i])
961
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
962
- return c > 3 && r && Object.defineProperty(target, key, r), r;
963
- }
964
- __name(_ts_decorate3, "_ts_decorate");
965
- function _ts_metadata2(k, v) {
966
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
967
- return Reflect.metadata(k, v);
968
- }
969
- __name(_ts_metadata2, "_ts_metadata");
970
- function _ts_param(paramIndex, decorator) {
971
- return function(target, key) {
972
- decorator(target, key, paramIndex);
706
+ return res.status(error.status).json(error);
973
707
  };
974
708
  }
975
- __name(_ts_param, "_ts_param");
976
- var LoggerService = class LoggerService2 {
977
- static {
978
- __name(this, "LoggerService");
979
- }
980
- logger;
981
- constructor(logger) {
982
- this.logger = logger;
983
- this.log = this.logFn("info");
984
- this.trace = this.logFn("trace");
985
- this.debug = this.logFn("debug");
986
- this.info = this.logFn("info");
987
- this.warn = this.logFn("warn");
988
- this.error = this.logFn("error");
989
- this.fatal = this.logFn("fatal");
990
- }
991
- logFn(type) {
992
- return (msg, context = {}) => {
993
- return this.logger[type]({
994
- ...context,
995
- msg
996
- });
997
- };
998
- }
999
- log;
1000
- trace;
1001
- debug;
1002
- info;
1003
- warn;
1004
- error;
1005
- fatal;
1006
- };
1007
- LoggerService = _ts_decorate3([
1008
- Injectable(),
1009
- _ts_param(0, InjectPinoLogger()),
1010
- _ts_metadata2("design:type", Function),
1011
- _ts_metadata2("design:paramtypes", [
1012
- typeof PinoLogger === "undefined" ? Object : PinoLogger
1013
- ])
1014
- ], LoggerService);
1015
-
1016
- // src/logging/logging.module.ts
1017
- function _ts_decorate4(decorators, target, key, desc) {
1018
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1019
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1020
- r = Reflect.decorate(decorators, target, key, desc);
1021
- else
1022
- for (var i = decorators.length - 1; i >= 0; i--)
1023
- if (d = decorators[i])
1024
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1025
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1026
- }
1027
- __name(_ts_decorate4, "_ts_decorate");
1028
- var LoggerModule = class LoggerModule2 {
1029
- static {
1030
- __name(this, "LoggerModule");
1031
- }
1032
- static forRoot({ logLevel, redact = true } = {}) {
1033
- return {
1034
- module: LoggerModule2,
1035
- controllers: [],
1036
- imports: [
1037
- LoggerModule$1.forRootAsync({
1038
- imports: [
1039
- ConfigModule
1040
- ],
1041
- inject: [
1042
- ConfigService
1043
- ],
1044
- useFactory: async (configService) => ({
1045
- pinoHttp: {
1046
- level: logLevel || configService.get(SharedConfigKeys.ServiceLogLevel) || "silent",
1047
- redact: redact ? [
1048
- "authorization",
1049
- "headers.authorization",
1050
- "req.headers.authorization",
1051
- "res.headers.authorization",
1052
- "req.headers.cookie",
1053
- 'res.headers["set-cookie"]'
1054
- ] : []
1055
- }
1056
- })
1057
- })
1058
- ],
1059
- global: true,
1060
- providers: [
1061
- LoggerService
1062
- ],
1063
- exports: []
1064
- };
1065
- }
1066
- };
1067
- LoggerModule = _ts_decorate4([
1068
- Module({
1069
- providers: [
1070
- LoggerService
1071
- ],
1072
- exports: [
1073
- LoggerService
1074
- ]
1075
- })
1076
- ], LoggerModule);
1077
- function slugify(name) {
1078
- return _slugify(name, {
1079
- strict: true,
1080
- replacement: "-",
1081
- lower: true
1082
- });
1083
- }
1084
- __name(slugify, "slugify");
1085
709
 
1086
- export { AllianceException, AllianceExceptionFilter, AllianceGqlException, AllianceHeaders, DatabasesErrorCodes, GatewayErrorCodes, LoggerModule, LoggerService, PortalErrorCodes, RedisHealthIndicator, SharedConfigKeys, authMiddleware, createBearerToken, createPublicDistributionFiles, createSystemUserToken, getAppManifests, getPrivateKey, slugify, zBooleanEnum, zNonEmptyString, zSharedConfig };
710
+ export { AllianceError, AllianceHeaders, DataErrorCode, GatewayErrorCode, createBearerToken, createLogger, createPublicDistributionFiles, createSystemUserToken, getPrivateKey, requestErrorHandler, requestLoggerHandler, slugify, zBooleanEnum, zNonEmptyString, zSharedConfig };
1087
711
  //# sourceMappingURL=out.js.map
1088
712
  //# sourceMappingURL=index.js.map