@telia-ace/alliance-internal-node-utilities 1.0.4-next.0 → 1.0.4-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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @telia-ace/alliance-internal-node-utilities
2
2
 
3
+ ## 1.0.4-next.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 3b53cfc: Add current users email to the gateway JWT bearer token.
8
+
3
9
  ## 1.0.4-next.0
4
10
 
5
11
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -258,6 +258,7 @@ function createBearerToken({ privateKey, aud, sub, name, user, workspace }) {
258
258
  sub,
259
259
  name,
260
260
  "https://alliance.teliacompany.net/user_type": user.type,
261
+ "https://alliance.teliacompany.net/user_email": user.email,
261
262
  "https://alliance.teliacompany.net/user_privileges": user.permissions,
262
263
  "https://alliance.teliacompany.net/workspace": workspace.slug,
263
264
  "https://alliance.teliacompany.net/workspace_name": workspace.name,
@@ -286,7 +287,8 @@ function createSystemUserToken(configService) {
286
287
  },
287
288
  user: {
288
289
  type: "system",
289
- permissions: []
290
+ permissions: [],
291
+ email: "system"
290
292
  },
291
293
  privateKey: getPrivateKey(configService)
292
294
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/connect-redis@7.1.0_express-session@1.17.3/node_modules/connect-redis/dist/esm/index.js","../src/auth/auth.middleware.ts","../src/constants/config.ts","../src/constants/headers.ts","../src/auth/tokens.ts","../src/distribution/create-public-files.ts","../src/distribution/cookie-policy.ts","../src/distribution/json-schemas.ts","../src/distribution/pkg-json.ts","../src/get-app-manifests.ts","../src/exceptions/alliance-gql.exception.ts","../src/exceptions/codes.ts","../src/exceptions/alliance.exception.ts","../src/exceptions/exception.filter.ts","../src/logging/logging.module.ts","../src/logging/logging.service.ts","../src/slugify.ts"],"names":["LoggerErrorInterceptor","Store","noop","_err","_data","RedisStore","constructor","opts","prefix","scanCount","serializer","JSON","ttl","disableTTL","disableTouch","client","normalizeClient","isRedis","get","key","set","val","EX","del","expire","mget","keys","mGet","scanIterator","match","count","MATCH","COUNT","c","xs","scan","sid","cb","data","parse","err","sess","_getTTL","stringify","destroy","touch","clear","_getAllKeys","length","ids","len","map","k","substring","all","results","reduce","acc","raw","idx","id","push","cookie","expires","ms","Number","Date","now","Math","ceil","pattern","auth","createClient","SharedConfigKeys","AllianceHeaders","authMiddleware","configService","baseURL","clientSecret","clientID","authRequired","authorizationParams","afterCallback","issuerBaseURL","sessionCookiePath","store","redisHostUrl","RedisHost","redisClient","url","getOrThrow","password","RedisPassword","connect","catch","console","error","secret","AuthCookieSecret","session","name","AuthCookieName","path","routes","callback","sign","createBearerToken","privateKey","aud","sub","user","workspace","jwt","iss","type","permissions","slug","expiresIn","algorithm","getPrivateKey","JwtPrivateKey","createSystemUserToken","validate","existsSync","mkdirSync","writeFileSync","resolve","generateCookiePolicyHtml","appManifests","cookiePolicyTableRows","appName","manifest","storage","value","Object","entries","tableRow","createCookiePolicyTableRow","cookiePolicyHtml","replace","join","claimEntry","rows","category","purpose","lifespan","readFileSync","getJsonSchemas","frameworkDistDirPath","process","cwd","appConfigSchemaPath","appManifestSchemaPath","appConfigSchemaFile","toString","appManifestSchemaFile","appConfig","appManifest","rmSync","createTempModuleAndImport","moduleString","fileName","file","importedModule","force","getAppManifests","apps","moduleStringParts","manifestImportVariables","packageName","manifestImportVariable","indexOf","result","default","getPkgJson","packageJson","pkgJsonFile","getManifests","pkgJson","alliance","Error","manifestArray","curr","PUBLIC_DIR_NAME","MANIFESTS_FILE_NAME","COOKIE_POLICY_FILE_NAME","APP_CONFIG_SCHEMA_FILE_NAME","APP_MANIFEST_SCHEMA_FILE_NAME","createPublicDistributionFiles","manifests","schemas","validationResult","errors","e","publicDirPath","manifestsFilePath","cookiePolicyFilePath","appConfigSchemaFilePath","appManifestSchemaFilePath","GraphQLError","HttpStatus","GatewayErrorCodes","DatabasesErrorCodes","PortalErrorCodes","allianceErrors","httpCode","UNAUTHORIZED","message","BAD_REQUEST","TargetApp","TargetWorkspace","INTERNAL_SERVER_ERROR","FORBIDDEN","CONFLICT","parseTemplates","variables","replaceAll","AllianceGqlException","info","code","extensions","HttpException","AllianceException","Catch","AllianceExceptionFilter","exception","host","ctx","switchToHttp","response","getResponse","status","getStatus","json","Module","ConfigModule","ConfigService","LoggerModule","PinoModule","Injectable","PinoLogger","InjectPinoLogger","LoggerService","logger","log","args","trace","debug","warn","fatal","forRoot","logLevel","redact","module","controllers","imports","forRootAsync","inject","useFactory","pinoHttp","level","ServiceLogLevel","global","providers","exports","_slugify","slugify","strict","replacement","lower"],"mappings":";;;;AAAA,SAASA,8BAA8B;;;ACAvC,SAASC,aAAa;AACtB,IAAMC,OAAO,wBAACC,MAAMC,UAAAA;AAAY,GAAnB;AACb,IAAMC,aAAN,MAAMA,oBAAmBJ,MAAAA;EAFzB,OAEyBA;;;EACrBK,YAAYC,MAAM;AACd,UAAK;AACL,SAAKC,SAASD,KAAKC,UAAU,OAAO,UAAUD,KAAKC;AACnD,SAAKC,YAAYF,KAAKE,aAAa;AACnC,SAAKC,aAAaH,KAAKG,cAAcC;AACrC,SAAKC,MAAML,KAAKK,OAAO;AACvB,SAAKC,aAAaN,KAAKM,cAAc;AACrC,SAAKC,eAAeP,KAAKO,gBAAgB;AACzC,SAAKC,SAAS,KAAKC,gBAAgBT,KAAKQ,MAAM;EAClD;;EAEAC,gBAAgBD,QAAQ;AACpB,QAAIE,UAAU,kBAAkBF;AAChC,WAAO;MACHG,KAAK,CAACC,QAAQJ,OAAOG,IAAIC,GAAAA;MACzBC,KAAK,CAACD,KAAKE,KAAKT,QAAAA;AACZ,YAAIA,KAAK;AACL,iBAAOK,UACDF,OAAOK,IAAID,KAAKE,KAAK;YAAEC,IAAIV;UAAI,CAAA,IAC/BG,OAAOK,IAAID,KAAKE,KAAK,MAAMT,GAAAA;QACrC;AACA,eAAOG,OAAOK,IAAID,KAAKE,GAA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;SAC5DrJ,QAA6B,IAAIqJ,SAAS,KAAKF,OAAOnJ,MAAK,GAAIqJ,IAAAA;SAC/DI,QAA6B,IAAIJ,SAAS,KAAKF,OAAOM,MAAK,GAAIJ,IAAAA;EAPO;EACtED;EACAE;EACAC;EACA7B;EACA8B;EACAxJ;EACAyJ;AACJ;AATaP,gBAAAA,cAAAA;EADZH,WAAAA;EAEgBE,UAAAA,GAAAA,iBAAAA,CAAAA;;;WAA4C,eAAA,cAAA,SAAA;;GADhDC,aAAAA;;;;;;;;;;;;;;ADYb,IAAaL,eAAN,MAAAA,cAAA;SAAA;;;EACH,OAAOa,QAAQ,EAAEC,UAAUC,SAAS,KAAI,IAAqB,CAAC,GAAkB;AAC5E,WAAO;MACHC,QAAQhB;MACRiB,aAAa,CAAA;MACbC,SAAS;QACLjB,WAAWkB,aAAa;UACpBD,SAAS;YAACpB;;UACVsB,QAAQ;YAACrB;;UACTsB,YAAY,OAAOtL,mBAAkC;YACjDuL,UAAU;cACNC,OACIT,YACA/K,cAAc1D,IAAYuD,iBAAiB4L,eAAe,KAC1D;cACJT,QAAQA,SACF;gBACI;gBACA;gBACA;gBACA;kBAEJ,CAAA;YACV;UACJ;QACJ,CAAA;;MAEJU,QAAQ;MACRC,WAAW;QAACrB;;MACZsB,SAAS,CAAA;IACb;EACJ;AACJ;AAhCa3B,eAAAA,cAAAA;EAJZH,OAAO;IACJ6B,WAAW;MAACrB;;IACZsB,SAAS;MAACtB;;EACd,CAAA;GACaL,YAAAA;;;AEjBb,OAAO4B,cAAc;AAEd,SAASC,QAAQtK,MAAY;AAChC,SAAOqK,SAASrK,MAAM;IAAEuK,QAAQ;IAAMC,aAAa;IAAKC,OAAO;EAAK,CAAA;AACxE;AAFgBH","sourcesContent":["export { LoggerErrorInterceptor } from 'nestjs-pino';\nexport { authMiddleware, createBearerToken, createSystemUserToken, getPrivateKey } from './auth';\nexport { AllianceHeaders, SharedConfigKeys } from './constants';\nexport { createPublicDistributionFiles } from './distribution';\nexport {\n AllianceException,\n AllianceExceptionFilter,\n AllianceGqlException,\n DatabasesErrorCodes,\n GatewayErrorCodes,\n PortalErrorCodes,\n} from './exceptions';\nexport { getAppManifests } from './get-app-manifests';\nexport { LoggerModule, LoggerService } from './logging';\nexport { slugify } from './slugify';\n","import { Store } from \"express-session\";\nconst noop = (_err, _data) => { };\nclass RedisStore extends Store {\n constructor(opts) {\n super();\n this.prefix = opts.prefix == null ? \"sess:\" : opts.prefix;\n this.scanCount = opts.scanCount || 100;\n this.serializer = opts.serializer || JSON;\n this.ttl = opts.ttl || 86400; // One day in seconds.\n this.disableTTL = opts.disableTTL || false;\n this.disableTouch = opts.disableTouch || false;\n this.client = this.normalizeClient(opts.client);\n }\n // Create a redis and ioredis compatible client\n normalizeClient(client) {\n let isRedis = \"scanIterator\" in client;\n return {\n get: (key) => client.get(key),\n set: (key, val, ttl) => {\n if (ttl) {\n return isRedis\n ? client.set(key, val, { EX: ttl })\n : client.set(key, val, \"EX\", ttl);\n }\n return client.set(key, val);\n },\n del: (key) => client.del(key),\n expire: (key, ttl) => client.expire(key, ttl),\n mget: (keys) => (isRedis ? client.mGet(keys) : client.mget(keys)),\n scanIterator: (match, count) => {\n if (isRedis)\n return client.scanIterator({ MATCH: match, COUNT: count });\n // ioredis impl.\n return (async function* () {\n let [c, xs] = await client.scan(\"0\", \"MATCH\", match, \"COUNT\", count);\n for (let key of xs)\n yield key;\n while (c !== \"0\") {\n ;\n [c, xs] = await client.scan(c, \"MATCH\", match, \"COUNT\", count);\n for (let key of xs)\n yield key;\n }\n })();\n },\n };\n }\n async get(sid, cb = noop) {\n let key = this.prefix + sid;\n try {\n let data = await this.client.get(key);\n if (!data)\n return cb();\n return cb(null, await this.serializer.parse(data));\n }\n catch (err) {\n return cb(err);\n }\n }\n async set(sid, sess, cb = noop) {\n let key = this.prefix + sid;\n let ttl = this._getTTL(sess);\n try {\n let val = this.serializer.stringify(sess);\n if (ttl > 0) {\n if (this.disableTTL)\n await this.client.set(key, val);\n else\n await this.client.set(key, val, ttl);\n return cb();\n }\n else {\n return this.destroy(sid, cb);\n }\n }\n catch (err) {\n return cb(err);\n }\n }\n async touch(sid, sess, cb = noop) {\n let key = this.prefix + sid;\n if (this.disableTouch || this.disableTTL)\n return cb();\n try {\n await this.client.expire(key, this._getTTL(sess));\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async destroy(sid, cb = noop) {\n let key = this.prefix + sid;\n try {\n await this.client.del([key]);\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async clear(cb = noop) {\n try {\n let keys = await this._getAllKeys();\n if (!keys.length)\n return cb();\n await this.client.del(keys);\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async length(cb = noop) {\n try {\n let keys = await this._getAllKeys();\n return cb(null, keys.length);\n }\n catch (err) {\n return cb(err);\n }\n }\n async ids(cb = noop) {\n let len = this.prefix.length;\n try {\n let keys = await this._getAllKeys();\n return cb(null, keys.map((k) => k.substring(len)));\n }\n catch (err) {\n return cb(err);\n }\n }\n async all(cb = noop) {\n let len = this.prefix.length;\n try {\n let keys = await this._getAllKeys();\n if (keys.length === 0)\n return cb(null, []);\n let data = await this.client.mget(keys);\n let results = data.reduce((acc, raw, idx) => {\n if (!raw)\n return acc;\n let sess = this.serializer.parse(raw);\n sess.id = keys[idx].substring(len);\n acc.push(sess);\n return acc;\n }, []);\n return cb(null, results);\n }\n catch (err) {\n return cb(err);\n }\n }\n _getTTL(sess) {\n if (typeof this.ttl === \"function\") {\n return this.ttl(sess);\n }\n let ttl;\n if (sess && sess.cookie && sess.cookie.expires) {\n let ms = Number(new Date(sess.cookie.expires)) - Date.now();\n ttl = Math.ceil(ms / 1000);\n }\n else {\n ttl = this.ttl;\n }\n return ttl;\n }\n async _getAllKeys() {\n let pattern = this.prefix + \"*\";\n let keys = [];\n for await (let key of this.client.scanIterator(pattern, this.scanCount)) {\n keys.push(key);\n }\n return keys;\n }\n}\nexport default RedisStore;\n","import type { ConfigService } from '@nestjs/config';\nimport RedisStore from 'connect-redis';\nimport type { RequestHandler } from 'express';\nimport {\n type ConfigParams,\n type CookieConfigParams,\n type SessionStore,\n auth,\n} from 'express-openid-connect';\nimport { createClient } from 'redis';\n\nimport { SharedConfigKeys } from '@/constants';\n\ntype Settings = {\n baseURL?: ConfigParams['baseURL'];\n clientID?: ConfigParams['clientID'];\n clientSecret?: ConfigParams['clientSecret'];\n authRequired?: ConfigParams['authRequired'];\n authorizationParams?: ConfigParams['authorizationParams'];\n afterCallback?: ConfigParams['afterCallback'];\n issuerBaseURL?: ConfigParams['issuerBaseURL'];\n sessionCookiePath?: CookieConfigParams['path'];\n};\n\nexport function authMiddleware(\n configService: ConfigService,\n {\n baseURL = 'https://127.0.0.1',\n clientSecret,\n clientID = ' ',\n authRequired = true,\n authorizationParams = {},\n afterCallback,\n issuerBaseURL = 'https://127.0.0.1',\n sessionCookiePath,\n }: Settings = {},\n): RequestHandler {\n let store: SessionStore | RedisStore | undefined;\n const redisHostUrl = configService.get<string>(SharedConfigKeys.RedisHost);\n if (redisHostUrl) {\n const redisClient = createClient({\n url: configService.getOrThrow<string>(SharedConfigKeys.RedisHost),\n password: configService.get<string>(SharedConfigKeys.RedisPassword),\n });\n\n redisClient.connect().catch(console.error);\n\n store = new RedisStore({\n client: redisClient,\n });\n }\n\n return auth({\n baseURL,\n clientSecret,\n clientID,\n authRequired,\n authorizationParams,\n afterCallback,\n issuerBaseURL,\n secret: configService.getOrThrow<string>(SharedConfigKeys.AuthCookieSecret),\n session: {\n name: configService.getOrThrow<string>(SharedConfigKeys.AuthCookieName),\n // @ts-ignore\n store,\n cookie: {\n path: sessionCookiePath,\n },\n },\n routes: {\n callback: '/signin-oidc',\n },\n });\n}\n","export enum SharedConfigKeys {\n AuthCookieName = 'AUTH_COOKIE_NAME',\n AuthCookieSecret = 'AUTH_COOKIE_SECRET',\n DbEndpoint = 'DB_ENDPOINT',\n JwtPrivateKey = 'JWT_PRIVATE_KEY',\n ServiceLogLevel = 'SERVICE_LOG_LEVEL',\n ServicePort = 'SERVICE_PORT',\n RedisHost = 'REDIS_HOST',\n RedisPassword = 'REDIS_PASSWORD',\n}\n","export enum AllianceHeaders {\n TargetUrl = 'alliance-target-url',\n TargetApp = 'alliance-target-app',\n TargetWorkspace = 'alliance-target-workspace',\n}\n","import type { ConfigService } from '@nestjs/config';\nimport { sign } from 'jsonwebtoken';\n\nimport { SharedConfigKeys } from '@/constants';\n\ntype BearerTokenSettings = {\n privateKey: string;\n aud: string;\n sub: string;\n name: string;\n user: {\n type: string;\n permissions: string[];\n };\n workspace: { name: string; slug: string };\n};\n\nexport function createBearerToken({\n privateKey,\n aud,\n sub,\n name,\n user,\n workspace,\n}: BearerTokenSettings) {\n const jwt = sign(\n {\n iss: 'Alliance',\n aud,\n sub,\n name,\n 'https://alliance.teliacompany.net/user_type': user.type,\n 'https://alliance.teliacompany.net/user_privileges': user.permissions,\n 'https://alliance.teliacompany.net/workspace': workspace.slug,\n 'https://alliance.teliacompany.net/workspace_name': workspace.name,\n 'https://alliance.teliacompany.net/tenant': workspace.slug,\n 'https://alliance.teliacompany.net/tenant_name': workspace.name,\n },\n privateKey,\n {\n expiresIn: '1h',\n algorithm: 'RS256',\n },\n );\n\n return `Bearer ${jwt}`;\n}\n\nexport function getPrivateKey(configService: ConfigService) {\n const privateKey = configService.getOrThrow<string>(SharedConfigKeys.JwtPrivateKey);\n\n return '-----BEGIN RSA PRIVATE KEY-----\\n' + privateKey + '\\n-----END RSA PRIVATE KEY-----';\n}\n\nexport function createSystemUserToken(configService: ConfigService) {\n return createBearerToken({\n aud: 'system',\n sub: 'system',\n name: 'system',\n workspace: {\n slug: 'system',\n name: 'system',\n },\n user: {\n type: 'system',\n permissions: [],\n },\n privateKey: getPrivateKey(configService),\n });\n}\n","import { validate } from 'jsonschema';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { generateCookiePolicyHtml } from './cookie-policy';\nimport { getJsonSchemas } from './json-schemas';\nimport { getManifests, getPkgJson } from './pkg-json';\n\nconst PUBLIC_DIR_NAME = 'public';\nconst MANIFESTS_FILE_NAME = 'manifests.json';\nconst COOKIE_POLICY_FILE_NAME = 'cookie-policy.html';\nconst APP_CONFIG_SCHEMA_FILE_NAME = 'config.schema.json';\nconst APP_MANIFEST_SCHEMA_FILE_NAME = 'manifest.schema.json';\n\nexport async function createPublicDistributionFiles() {\n const pkgJson = getPkgJson();\n const manifests = await getManifests(pkgJson);\n const schemas = getJsonSchemas();\n\n // Validate all app schemas\n for (const appName in manifests) {\n const manifest = manifests[appName];\n\n const validationResult = validate(manifest, schemas.appManifest);\n\n if (validationResult.errors.length) {\n const errors = validationResult.errors.map((e) => JSON.stringify(e, null, 2));\n throw new Error(\n `Validation of app manifest for app '${appName}' failed with the following errors:\\n${errors.join(\n '\\n',\n )}`,\n );\n }\n }\n\n // Make sure public dir exists\n const publicDirPath = resolve(process.cwd(), PUBLIC_DIR_NAME);\n if (!existsSync(publicDirPath)) {\n mkdirSync(publicDirPath);\n }\n\n // Create manifests file\n const manifestsFilePath = resolve(publicDirPath, MANIFESTS_FILE_NAME);\n writeFileSync(manifestsFilePath, JSON.stringify(manifests));\n\n // Create cookie policy document\n const cookiePolicyFilePath = resolve(publicDirPath, COOKIE_POLICY_FILE_NAME);\n writeFileSync(cookiePolicyFilePath, generateCookiePolicyHtml(manifests));\n\n // Create JSON schema files\n const appConfigSchemaFilePath = resolve(publicDirPath, APP_CONFIG_SCHEMA_FILE_NAME);\n const appManifestSchemaFilePath = resolve(publicDirPath, APP_MANIFEST_SCHEMA_FILE_NAME);\n writeFileSync(appConfigSchemaFilePath, JSON.stringify(schemas.appConfig));\n writeFileSync(appManifestSchemaFilePath, JSON.stringify(schemas.appManifest));\n}\n","import type { LooseObject } from '@/types';\n\nexport function generateCookiePolicyHtml(appManifests: LooseObject) {\n const cookiePolicyTableRows: string[] = [];\n\n for (const appName in appManifests) {\n const manifest = appManifests[appName];\n if (!manifest.storage) {\n continue;\n }\n\n for (const [key, value] of Object.entries(manifest.storage)) {\n const tableRow = createCookiePolicyTableRow(key, value as LooseObject);\n cookiePolicyTableRows.push(tableRow);\n }\n }\n\n return cookiePolicyHtml.replace('{APP_COOKIES}', cookiePolicyTableRows.join(''));\n}\n\nfunction createCookiePolicyTableRow(key: string, claimEntry: LooseObject) {\n const rows = ['<tr>'];\n const { category, purpose, lifespan } = claimEntry;\n rows.push(`<td>${key}</td>`);\n rows.push(`<td>${category}</td>`);\n rows.push(`<td>${purpose}</td>`);\n rows.push(`<td>${lifespan}</td>`);\n rows.push('</tr>');\n return rows.join('');\n}\n\nconst cookiePolicyHtml = `\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>ACE Alliance - Cookie Policy</title>\n <link\n rel=\"icon\"\n href=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAGcElEQVRYha2Xe4xUVx3HP7/fPTOzDLO7sw8RlzWlZEtp2dCy0qIVWltKU/UPDZH6ijXWEK2odPcPa2qbhpi2kSa7blSStsFUjNq0lWCMaVMx8rAm22IJMJRHCqFC6BJ22eEx+5p7z88/7sywC7uwgCe5mXsz5/y+j/M753eOcJ2tK5sDyBrME2gBmkBq43/tnMERgXdAjrbn518yXq4RNA3cB/J54HNiMhfEicm4oAYghmHexN4Dew5k01giUybQlc1h0CbI9zC+Imi9mCAIYhoHsnI4KcNjYoDhxWPxsxFY1Z5vHQVwVwSu3Qdid4E8rSb3i6mqKYwBjpWX1V/QZBiYYWIIiifCw8Mm/vS7L/W237FqJno58M5srgmxP4npjsAHDwTeaeAdagGBdwQWoBYgFqCmqGlMqvTE3+U+ipbeE+ngB42Lde6kDnRmcwisAHlBfdBYCYxStp3y7xjTJ51RA0XxgGCkasQFSfkW8NQlBDqzORVYK6ZPqAU6ThUyqd0TN7mQDRZ/CULzvVVeRO68x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rpz89P+30bz4QmdltHvvXQpARKJB5R0w0XSvL4cjwV+FnLU+HiZ2tUpxtbf9Tnj20vOJPo2fZ8688u7n3pmdB42Yt/xUuESVQ+yVJexZNtVmbQ2JYIH9zcGC5/pd71Hxjxm5f1cnzboDPx7xs8M9G4CSV1ZnOZICE7GNXbKweTMU7EA6USoemeVLhgTYame1Nu4MBI2PN0ng+3DDovIZFG5w37bEe+dc+UCQC8/ZtjzX07i/88saU4J8yLXiAhaCC+fn7Sz/7iNFq+mqZ6TuD6do+Gu7vPcuQvBRf62LlIQ2/Y1zvyra9OhnPZSf1g58k5I6ftDSnqnNFTaOACqmclfP0tSa3KBjrc5/2Hbwz7Q38ocHLniDM8XjxeIrxG3rA16vXXj529dVKMK2bVL2fkmhrmJ/9cPy91Z2ZGwhMqQx95TudC8gdCZx4obbMVAhqNGvaoCr99bKD1svGntK4647vg84J8X021PBXlK5gJGJWr11GDb3fkW7dPJfaUi3539iARxSUCz4AsERMVpHwDxMTyhq0HftGRbz071bhXfeooXVJvBR4EbgSGgR6Bt9qvArjc/gfZzPoCTDB+AgAAAABJRU5ErkJggg==\"\n />\n <style>\n @charset \"UTF-8\";\n @import 'https://cdn.voca.teliacompany.com/fonts/TeliaSansV10/TeliaSans.css';\n @import 'https://fonts.googleapis.com/css?family=Reenie+Beanie';\n\n body {\n font-family: TeliaSans, Helvetica, Arial, Lucida Grande, sans-serif;\n }\n\n body > div {\n max-width: 1000px;\n margin: 0 auto;\n padding: 0 40px 40px;\n }\n </style>\n </head>\n\n <body>\n <div>\n <h1>Cookie Policy</h1>\n <p>\n On our websites, we use cookies and other similar technologies. You can choose\n whether you want to allow our websites to store cookies on your computer or not. You\n can change your choices at any time.\n </p>\n\n <h2>Your consent is required</h2>\n <p>\n You choose whether you want to accept cookies on your device or not. Your consent is\n required for the use of cookies, but not for such cookies that are necessary to\n enable the service that you as a user have requested. If you do not accept our use\n of cookies, or if you have previously approved our use and have changed your mind,\n you can return to your cookie settings at any time and change your choices. You do\n this by clicking on the cookie button/link. You may also need to change the settings\n in your browser and manually delete cookies to clear your device of previously\n stored cookies.\n </p>\n\n <h2>What are cookies?</h2>\n <p>\n A cookie is a small text file that is stored on your computer by the web browser\n while browsing a website. When we refer to cookies (“cookies”) in this policy, other\n similar technologies and tools that retrieve and store information in your browser,\n and in some cases forward such information to third parties, in a manner similar to\n cookies. Examples are pixels, local storage, session storage and fingerprinting.\n </p>\n <p>\n The websites will “remember” and “recognize” you. This can be done by placing\n cookies in three different ways;\n </p>\n <ul>\n <li>The session ends, ie until you close the window in your browser.</li>\n <li>\n Time-limited, ie the cookie has a predetermined lifespan. The time may vary\n between different cookies.\n </li>\n <li>\n Until further notice, ie the information remains until you choose to delete it\n yourself. This applies to local storage.\n </li>\n </ul>\n <p>You can always go into your browser and delete already stored cookies yourself.</p>\n\n <h3>Third Party Cookies</h3>\n <p>\n We use third-party cookies on our websites. Third-party cookies are stored by\n someone other than the person responsible for the website, in this case by a company\n other than Telia.\n </p>\n <p>\n Telia uses external platforms to communicate digitally, these include the Google\n Marketing Platform and others. The platforms use both first- and third-party cookies\n as well as similar techniques to advertise and follow up the results of the\n advertising.\n </p>\n <p>\n A third-party cookie can be used by several websites to understand and track how you\n browse between different websites. Telia receives information from these cookies,\n but the information can also be used for other purposes determined by third parties.\n Third-party cookies found on our website are covered by each third-party privacy\n policy. Feel free to read these to understand what other purposes the information\n can be used for. Links are in our Cookie Table.\n </p>\n <p>\n For information about which third-party cookies are used on our websites, see our\n Cookie Table. For more information on how Telia handles personal data in connection\n with transfers to third parties, read our Privacy Policy.\n </p>\n\n <h2>Cookies on our websites</h2>\n <p>\n In order for you to have better control over which cookies are used on the websites,\n and thus be able to more easily decide how cookies should be used when you visit our\n websites, we have identified four different categories of cookies. These categories\n are defined based on the purposes for the use of the cookies.\n </p>\n <p>\n In our Cookie Table, you can also see which category each cookie belongs to, for\n what purposes it is used and for how long it is active.\n </p>\n <p>\n We have identified the following four categories of cookies. All categories contain\n cookies which means that data is shared with third parties.\n </p>\n\n <h3>Necessary</h3>\n <p>\n These cookies are needed for our app to work in a secure and correct way. Necessary\n cookies enable you to use our app and us to provide the service you request.\n Necessary cookies make basic functions of the app possible, for example, identifying\n you when you log into My Telia, detecting repeated failed login attempts,\n identifying where you are in the buying process and remembering the items put into\n your shopping basket.\n </p>\n\n <h3>Functionality</h3>\n <p>\n These cookies let us to enable some useful functionalities to make the user\n experience better, for example, to remember your login details and settings.\n </p>\n\n <h3>Analytics</h3>\n <p>\n These cookies give us information about how you use our app and allow us to improve\n the user experience.\n </p>\n\n <h3>Marketing</h3>\n <p>\n These cookies help us and our partners to display personalized and relevant ads\n based on your browsing behavior on our website and in our app, even when you later\n visit other (third parties’) websites. These cookies are used to evaluate the\n effectiveness of our marketingcampaigns, as well as for targeted marketing and\n profiling, regardless of which device(s) you have used. Information collected for\n this purpose may also be combined with other customer and traffic data we have about\n you, if you have given your consent that we may use your traffic data for marketing\n purpose and have not objected to the use of your customer data for marketing\n purposes.\n </p>\n\n <h2>Manage settings</h2>\n <p>\n We save your cookie consent for 12 months. Then we will ask you again. Please note\n that some cookies have a lifespan that exceeds these 12 months. You may therefore\n need to change the settings in your browser and manually delete all cookies.\n </p>\n <p>\n More information on how to turn off cookies can be found in the instructions for\n your browser.\n </p>\n <ul>\n <li>\n <a\n href=\"https://support.google.com/accounts/answer/61416?co=GENIE.Platform%3DDesktop&amp;hl=en\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Google Chrome</a\n >\n </li>\n <li>\n <a\n href=\"https://privacy.microsoft.com/en-us/windows-10-microsoft-edge-and-privacy\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Microsoft Edge</a\n >\n </li>\n <li>\n <a\n href=\"https://support.mozilla.org/en-US/kb/enable-and-disable-cookies-website-preferences\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Mozilla Firefox</a\n >\n </li>\n <li>\n <a\n href=\"https://support.microsoft.com/en-gb/help/17442/windows-internet-explorer-delete-manage-cookies\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Microsoft Internet Explorer</a\n >\n </li>\n <li>\n <a\n href=\"https://www.opera.com/help/tutorials/security/privacy/\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Opera</a\n >\n </li>\n <li>\n <a\n href=\"https://support.apple.com/guide/safari/manage-cookies-and-website-data-sfri11471/mac\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Apple Safari</a\n >\n </li>\n </ul>\n\n <h3>Do Not Track-signals</h3>\n <p>\n If you have chosen to turn on the Do Not Track function in your browser, we will not\n automatically place cookies for marketing on your device. You make other choices in\n your cookie settings.\n </p>\n\n <h3>If you block cookies</h3>\n <p>\n If you choose not to accept our use of cookies, the functionality and performance of\n our websites may deteriorate as certain functions are dependent on cookies. A\n blocking of cookies can therefore mean that the websites’ services do not work as\n they should.\n </p>\n\n <h3>Your security with us</h3>\n <p>\n If you want to read more about your rights and how we protect your privacy, go to\n our privacy policy for\n <a\n href=\"https://www.telia.se/dam/jcr:df2eeb83-50ce-4383-89fc-0613f7615796/Integritetspolicy-privatkunder.pdf\"\n >private customers</a\n >\n (C2B) or\n <a\n href=\"https://www.telia.se/dam/jcr:95b2b4a5-82ca-436b-90e0-873e0a864118/Telia-integritetspolicy-foretag.pdf\"\n >corporate customers</a\n >\n (B2B). You are always welcome to contact us at\n <a href=\"mailto:dpo-se@teliacompany.com\">dpo-se@teliacompany.com</a> if you have any\n questions.\n </p>\n <p>Our cookie policy may change in the future.</p>\n <p>\n More information about cookies can be found at the Swedish Post and Telecom\n Authority (PTS).\n </p>\n\n <h2>Our Cookie Table</h2>\n <p>\n Below, you will find a list of the cookies and similar technologies that we use on\n this website. These cookies are stored on your device by us.\n </p>\n <table>\n <thead>\n <tr>\n <th>Cookie</th>\n <th>Category</th>\n <th>Purpose</th>\n <th>Lifespan</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>alliance-session-v1</td>\n <td>necessary</td>\n <td>Contains the authenticated user.</td>\n <td>1 day</td>\n </tr>\n {APP_COOKIES}\n </tbody>\n </table>\n <style>\n table {\n width: 100%;\n border: 1px solid rgba(0, 0, 0, 0.15);\n }\n th, td {\n text-align: left;\n padding: 3px;\n }\n </style>\n </div>\n </body>\n</html>\n`;\n","import type { Schema } from 'jsonschema';\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\ntype JsonSchemas = {\n appConfig: Schema;\n appManifest: Schema;\n};\n\nexport function getJsonSchemas(): JsonSchemas {\n const frameworkDistDirPath = resolve(\n process.cwd(),\n 'node_modules',\n '@telia-ace/alliance-framework',\n 'dist',\n );\n const appConfigSchemaPath = resolve(frameworkDistDirPath, 'config.schema.json');\n const appManifestSchemaPath = resolve(frameworkDistDirPath, 'manifest.schema.json');\n const appConfigSchemaFile = readFileSync(appConfigSchemaPath).toString();\n const appManifestSchemaFile = readFileSync(appManifestSchemaPath).toString();\n const appConfig = JSON.parse(appConfigSchemaFile);\n const appManifest = JSON.parse(appManifestSchemaFile);\n\n return {\n appConfig,\n appManifest,\n };\n}\n","import { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { getAppManifests } from '@/get-app-manifests';\nimport type { LooseObject } from '@/types';\n\ntype PkgJson = LooseObject & {\n name: string;\n version: string;\n};\n\nexport type AlliancePortalDistPkgJson = PkgJson & {\n alliance?: {\n apps?: string[];\n };\n};\n\nexport function getPkgJson(): AlliancePortalDistPkgJson {\n const packageJson = resolve(process.cwd(), 'package.json');\n const pkgJsonFile = readFileSync(packageJson).toString();\n return JSON.parse(pkgJsonFile);\n}\n\nexport async function getManifests(pkgJson: AlliancePortalDistPkgJson) {\n if (!pkgJson || !pkgJson.alliance || !pkgJson.alliance.apps) {\n throw new Error('Alliance apps not defined in package.json.');\n }\n\n const manifestArray = await getAppManifests(pkgJson.alliance.apps);\n\n return manifestArray.reduce((acc, curr: LooseObject) => {\n acc[curr.name] = curr;\n\n return acc;\n }, {});\n}\n","import { rmSync, writeFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport type { LooseObject } from './types';\n\nasync function createTempModuleAndImport<T>(moduleString: string, fileName: string): Promise<T> {\n const file = resolve(process.cwd(), `${fileName}.mjs`);\n writeFileSync(file, moduleString);\n const importedModule = await import(`file:///${file}`);\n rmSync(file, { force: true });\n return importedModule;\n}\n\n// Creates a temporary ES module and imports app manifests for all requested apps\n// This reusable utility can access all node modules available in the directory where it is ran\nexport async function getAppManifests(apps: string[]): Promise<LooseObject[]> {\n const moduleStringParts = [];\n const manifestImportVariables = [];\n\n for (const packageName of apps) {\n const manifestImportVariable = `app${apps.indexOf(packageName)}`;\n manifestImportVariables.push(manifestImportVariable);\n moduleStringParts.push(`import ${manifestImportVariable} from '${packageName}/manifest';`);\n }\n\n moduleStringParts.push(`export default [${manifestImportVariables.join(', ')}];`);\n\n const result = await createTempModuleAndImport<{ default: LooseObject[] }>(\n moduleStringParts.join('\\n'),\n 'app-manifests',\n );\n\n return result.default;\n}\n","import { GraphQLError } from 'graphql';\n\nimport { type ErrorCodes, allianceErrors } from './codes';\n\nfunction parseTemplates(message: string, variables: Record<string, string>) {\n return Object.entries(variables).reduce((acc, [key, value]) => {\n return acc.replaceAll(`{{${key}}}`, value);\n }, message);\n}\n\nexport class AllianceGqlException extends GraphQLError {\n public info: string;\n public code: ErrorCodes;\n constructor(code: ErrorCodes, variables: Record<string, string> = {}, extensions?: any) {\n const { message } = allianceErrors[code];\n\n super(parseTemplates(message, variables), {\n extensions,\n });\n\n this.code = code;\n this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${code}`;\n }\n}\n","import { HttpStatus } from '@nestjs/common';\n\nimport { AllianceHeaders } from '@/constants';\n\nexport enum GatewayErrorCodes {\n NoObjectId = 10001,\n NoTargetAppHeader = 10002,\n NoTargetWorkspaceHeader = 10003,\n NoManifestsInCache = 10004,\n NoDevSessionInCache = 10005,\n NoManifest = 10006,\n NoRequestContext = 10007,\n NoUserInRequestContext = 10008,\n NoAppInRequestContext = 10009,\n NoWorkspaceInRequestContext = 10010,\n NoUserPermissionsInRequestContext = 10012,\n WorkspacePermissionDenied = 10013,\n}\n\nexport enum DatabasesErrorCodes {\n NoPublicKey = 11000,\n NoAuthHeader = 11001,\n FailedFileStore = 11002,\n FailedFileRead = 11003,\n NoRecord = 11004,\n UniqueConstrain = 11005,\n}\n\nexport enum PortalErrorCodes {\n NoObjectId = 12000,\n}\n\nexport type ErrorCodes = GatewayErrorCodes | DatabasesErrorCodes | PortalErrorCodes;\n\ntype AllianceErrors = {\n [key in ErrorCodes]: {\n httpCode: HttpStatus;\n message: string;\n };\n};\n\nexport const allianceErrors: AllianceErrors = {\n // gateway\n [GatewayErrorCodes.NoObjectId]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No object id available on authenticated user.',\n },\n [GatewayErrorCodes.NoTargetAppHeader]: {\n httpCode: HttpStatus.BAD_REQUEST,\n message: `Request missing header '${AllianceHeaders.TargetApp}'.`,\n },\n [GatewayErrorCodes.NoTargetWorkspaceHeader]: {\n httpCode: HttpStatus.BAD_REQUEST,\n message: `Request missing header '${AllianceHeaders.TargetWorkspace}'.`,\n },\n [GatewayErrorCodes.NoManifestsInCache]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'App manifests missing in cache.',\n },\n [GatewayErrorCodes.NoDevSessionInCache]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No dev session in memory cache.',\n },\n [GatewayErrorCodes.NoManifest]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: \"Could not find manifest for app '{{appSlug}}'.\",\n },\n [GatewayErrorCodes.NoRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No request context.',\n },\n [GatewayErrorCodes.NoUserInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No user in request context.',\n },\n [GatewayErrorCodes.NoAppInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No app in request context.',\n },\n [GatewayErrorCodes.NoWorkspaceInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No workspace in request context.',\n },\n [GatewayErrorCodes.NoUserPermissionsInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No user permissions in request context.',\n },\n [GatewayErrorCodes.WorkspacePermissionDenied]: {\n httpCode: HttpStatus.FORBIDDEN,\n message: 'User does not have access to the current workspace.',\n },\n\n // databases\n [DatabasesErrorCodes.NoPublicKey]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No public key available to decode JWT.',\n },\n [DatabasesErrorCodes.NoAuthHeader]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No authorization header found.',\n },\n [DatabasesErrorCodes.FailedFileStore]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Error storing file.',\n },\n [DatabasesErrorCodes.FailedFileRead]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Error reading file.',\n },\n [DatabasesErrorCodes.NoRecord]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Missing database record.',\n },\n [DatabasesErrorCodes.UniqueConstrain]: {\n httpCode: HttpStatus.CONFLICT,\n message: 'Field has to be unique.',\n },\n\n // portal\n [PortalErrorCodes.NoObjectId]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No object id found in user claims.',\n },\n};\n","import { HttpException } from '@nestjs/common';\n\nimport { type ErrorCodes, allianceErrors } from './codes';\n\nfunction parseTemplates(message: string, variables: Record<string, string>) {\n return Object.entries(variables).reduce((acc, [key, value]) => {\n return acc.replaceAll(`{{${key}}}`, value);\n }, message);\n}\n\nexport class AllianceException extends HttpException {\n public info: string;\n public code: ErrorCodes;\n constructor(code: ErrorCodes, variables: Record<string, string> = {}) {\n const { message, httpCode } = allianceErrors[code];\n\n super(parseTemplates(message, variables), httpCode);\n\n this.code = code;\n this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${code}`;\n }\n}\n","import { type ArgumentsHost, Catch, type ExceptionFilter } from '@nestjs/common';\nimport type { Response } from 'express';\n\nimport { AllianceException } from './alliance.exception';\n\n@Catch(AllianceException)\nexport class AllianceExceptionFilter implements ExceptionFilter {\n catch(exception: AllianceException, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<Response>();\n const status = exception.getStatus();\n\n response.status &&\n response.status(status).json({\n httpCode: status,\n code: exception.code,\n info: exception.info,\n message: exception.message,\n });\n }\n}\n","import { type DynamicModule, Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { LoggerModule as PinoModule } from 'nestjs-pino';\n\nimport { SharedConfigKeys } from '@/constants';\n\nimport { LoggerService } from './logging.service';\n\ntype ModuleSettings = {\n logLevel?: string;\n redact?: boolean;\n};\n\n@Module({\n providers: [LoggerService],\n exports: [LoggerService],\n})\nexport class LoggerModule {\n static forRoot({ logLevel, redact = true }: ModuleSettings = {}): DynamicModule {\n return {\n module: LoggerModule,\n controllers: [],\n imports: [\n PinoModule.forRootAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => ({\n pinoHttp: {\n level:\n logLevel ||\n configService.get<string>(SharedConfigKeys.ServiceLogLevel) ||\n 'silent',\n redact: redact\n ? [\n 'authorization',\n 'headers.authorization',\n 'req.headers.authorization',\n 'res.headers.authorization',\n ]\n : [],\n },\n }),\n }),\n ],\n global: true,\n providers: [LoggerService],\n exports: [],\n };\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport { PinoLogger } from 'nestjs-pino';\nimport { InjectPinoLogger } from 'nestjs-pino';\n\n@Injectable()\nexport class LoggerService {\n constructor(@InjectPinoLogger() private readonly logger: PinoLogger) {}\n log: PinoLogger['info'] = (...args) => this.logger.info(...args);\n trace: PinoLogger['trace'] = (...args) => this.logger.trace(...args);\n debug: PinoLogger['debug'] = (...args) => this.logger.debug(...args);\n info: PinoLogger['info'] = (...args) => this.logger.info(...args);\n warn: PinoLogger['warn'] = (...args) => this.logger.warn(...args);\n error: PinoLogger['error'] = (...args) => this.logger.error(...args);\n fatal: PinoLogger['fatal'] = (...args) => this.logger.fatal(...args);\n}\n","import _slugify from 'slugify';\n\nexport function slugify(name: string) {\n return _slugify(name, { strict: true, replacement: '-', lower: true });\n}\n"]}
1
+ {"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/connect-redis@7.1.0_express-session@1.17.3/node_modules/connect-redis/dist/esm/index.js","../src/auth/auth.middleware.ts","../src/constants/config.ts","../src/constants/headers.ts","../src/auth/tokens.ts","../src/distribution/create-public-files.ts","../src/distribution/cookie-policy.ts","../src/distribution/json-schemas.ts","../src/distribution/pkg-json.ts","../src/get-app-manifests.ts","../src/exceptions/alliance-gql.exception.ts","../src/exceptions/codes.ts","../src/exceptions/alliance.exception.ts","../src/exceptions/exception.filter.ts","../src/logging/logging.module.ts","../src/logging/logging.service.ts","../src/slugify.ts"],"names":["LoggerErrorInterceptor","Store","noop","_err","_data","RedisStore","constructor","opts","prefix","scanCount","serializer","JSON","ttl","disableTTL","disableTouch","client","normalizeClient","isRedis","get","key","set","val","EX","del","expire","mget","keys","mGet","scanIterator","match","count","MATCH","COUNT","c","xs","scan","sid","cb","data","parse","err","sess","_getTTL","stringify","destroy","touch","clear","_getAllKeys","length","ids","len","map","k","substring","all","results","reduce","acc","raw","idx","id","push","cookie","expires","ms","Number","Date","now","Math","ceil","pattern","auth","createClient","SharedConfigKeys","AllianceHeaders","authMiddleware","configService","baseURL","clientSecret","clientID","authRequired","authorizationParams","afterCallback","issuerBaseURL","sessionCookiePath","store","redisHostUrl","RedisHost","redisClient","url","getOrThrow","password","RedisPassword","connect","catch","console","error","secret","AuthCookieSecret","session","name","AuthCookieName","path","routes","callback","sign","createBearerToken","privateKey","aud","sub","user","workspace","jwt","iss","type","email","permissions","slug","expiresIn","algorithm","getPrivateKey","JwtPrivateKey","createSystemUserToken","validate","existsSync","mkdirSync","writeFileSync","resolve","generateCookiePolicyHtml","appManifests","cookiePolicyTableRows","appName","manifest","storage","value","Object","entries","tableRow","createCookiePolicyTableRow","cookiePolicyHtml","replace","join","claimEntry","rows","category","purpose","lifespan","readFileSync","getJsonSchemas","frameworkDistDirPath","process","cwd","appConfigSchemaPath","appManifestSchemaPath","appConfigSchemaFile","toString","appManifestSchemaFile","appConfig","appManifest","rmSync","createTempModuleAndImport","moduleString","fileName","file","importedModule","force","getAppManifests","apps","moduleStringParts","manifestImportVariables","packageName","manifestImportVariable","indexOf","result","default","getPkgJson","packageJson","pkgJsonFile","getManifests","pkgJson","alliance","Error","manifestArray","curr","PUBLIC_DIR_NAME","MANIFESTS_FILE_NAME","COOKIE_POLICY_FILE_NAME","APP_CONFIG_SCHEMA_FILE_NAME","APP_MANIFEST_SCHEMA_FILE_NAME","createPublicDistributionFiles","manifests","schemas","validationResult","errors","e","publicDirPath","manifestsFilePath","cookiePolicyFilePath","appConfigSchemaFilePath","appManifestSchemaFilePath","GraphQLError","HttpStatus","GatewayErrorCodes","DatabasesErrorCodes","PortalErrorCodes","allianceErrors","httpCode","UNAUTHORIZED","message","BAD_REQUEST","TargetApp","TargetWorkspace","INTERNAL_SERVER_ERROR","FORBIDDEN","CONFLICT","parseTemplates","variables","replaceAll","AllianceGqlException","info","code","extensions","HttpException","AllianceException","Catch","AllianceExceptionFilter","exception","host","ctx","switchToHttp","response","getResponse","status","getStatus","json","Module","ConfigModule","ConfigService","LoggerModule","PinoModule","Injectable","PinoLogger","InjectPinoLogger","LoggerService","logger","log","args","trace","debug","warn","fatal","forRoot","logLevel","redact","module","controllers","imports","forRootAsync","inject","useFactory","pinoHttp","level","ServiceLogLevel","global","providers","exports","_slugify","slugify","strict","replacement","lower"],"mappings":";;;;AAAA,SAASA,8BAA8B;;;ACAvC,SAASC,aAAa;AACtB,IAAMC,OAAO,wBAACC,MAAMC,UAAAA;AAAY,GAAnB;AACb,IA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S;QACLjB,WAAWkB,aAAa;UACpBD,SAAS;YAACpB;;UACVsB,QAAQ;YAACrB;;UACTsB,YAAY,OAAOvL,mBAAkC;YACjDwL,UAAU;cACNC,OACIT,YACAhL,cAAc1D,IAAYuD,iBAAiB6L,eAAe,KAC1D;cACJT,QAAQA,SACF;gBACI;gBACA;gBACA;gBACA;kBAEJ,CAAA;YACV;UACJ;QACJ,CAAA;;MAEJU,QAAQ;MACRC,WAAW;QAACrB;;MACZsB,SAAS,CAAA;IACb;EACJ;AACJ;AAhCa3B,eAAAA,cAAAA;EAJZH,OAAO;IACJ6B,WAAW;MAACrB;;IACZsB,SAAS;MAACtB;;EACd,CAAA;GACaL,YAAAA;;;AEjBb,OAAO4B,cAAc;AAEd,SAASC,QAAQvK,MAAY;AAChC,SAAOsK,SAAStK,MAAM;IAAEwK,QAAQ;IAAMC,aAAa;IAAKC,OAAO;EAAK,CAAA;AACxE;AAFgBH","sourcesContent":["export { LoggerErrorInterceptor } from 'nestjs-pino';\nexport { authMiddleware, createBearerToken, createSystemUserToken, getPrivateKey } from './auth';\nexport { AllianceHeaders, SharedConfigKeys } from './constants';\nexport { createPublicDistributionFiles } from './distribution';\nexport {\n AllianceException,\n AllianceExceptionFilter,\n AllianceGqlException,\n DatabasesErrorCodes,\n GatewayErrorCodes,\n PortalErrorCodes,\n} from './exceptions';\nexport { getAppManifests } from './get-app-manifests';\nexport { LoggerModule, LoggerService } from './logging';\nexport { slugify } from './slugify';\n","import { Store } from \"express-session\";\nconst noop = (_err, _data) => { };\nclass RedisStore extends Store {\n constructor(opts) {\n super();\n this.prefix = opts.prefix == null ? \"sess:\" : opts.prefix;\n this.scanCount = opts.scanCount || 100;\n this.serializer = opts.serializer || JSON;\n this.ttl = opts.ttl || 86400; // One day in seconds.\n this.disableTTL = opts.disableTTL || false;\n this.disableTouch = opts.disableTouch || false;\n this.client = this.normalizeClient(opts.client);\n }\n // Create a redis and ioredis compatible client\n normalizeClient(client) {\n let isRedis = \"scanIterator\" in client;\n return {\n get: (key) => client.get(key),\n set: (key, val, ttl) => {\n if (ttl) {\n return isRedis\n ? client.set(key, val, { EX: ttl })\n : client.set(key, val, \"EX\", ttl);\n }\n return client.set(key, val);\n },\n del: (key) => client.del(key),\n expire: (key, ttl) => client.expire(key, ttl),\n mget: (keys) => (isRedis ? client.mGet(keys) : client.mget(keys)),\n scanIterator: (match, count) => {\n if (isRedis)\n return client.scanIterator({ MATCH: match, COUNT: count });\n // ioredis impl.\n return (async function* () {\n let [c, xs] = await client.scan(\"0\", \"MATCH\", match, \"COUNT\", count);\n for (let key of xs)\n yield key;\n while (c !== \"0\") {\n ;\n [c, xs] = await client.scan(c, \"MATCH\", match, \"COUNT\", count);\n for (let key of xs)\n yield key;\n }\n })();\n },\n };\n }\n async get(sid, cb = noop) {\n let key = this.prefix + sid;\n try {\n let data = await this.client.get(key);\n if (!data)\n return cb();\n return cb(null, await this.serializer.parse(data));\n }\n catch (err) {\n return cb(err);\n }\n }\n async set(sid, sess, cb = noop) {\n let key = this.prefix + sid;\n let ttl = this._getTTL(sess);\n try {\n let val = this.serializer.stringify(sess);\n if (ttl > 0) {\n if (this.disableTTL)\n await this.client.set(key, val);\n else\n await this.client.set(key, val, ttl);\n return cb();\n }\n else {\n return this.destroy(sid, cb);\n }\n }\n catch (err) {\n return cb(err);\n }\n }\n async touch(sid, sess, cb = noop) {\n let key = this.prefix + sid;\n if (this.disableTouch || this.disableTTL)\n return cb();\n try {\n await this.client.expire(key, this._getTTL(sess));\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async destroy(sid, cb = noop) {\n let key = this.prefix + sid;\n try {\n await this.client.del([key]);\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async clear(cb = noop) {\n try {\n let keys = await this._getAllKeys();\n if (!keys.length)\n return cb();\n await this.client.del(keys);\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async length(cb = noop) {\n try {\n let keys = await this._getAllKeys();\n return cb(null, keys.length);\n }\n catch (err) {\n return cb(err);\n }\n }\n async ids(cb = noop) {\n let len = this.prefix.length;\n try {\n let keys = await this._getAllKeys();\n return cb(null, keys.map((k) => k.substring(len)));\n }\n catch (err) {\n return cb(err);\n }\n }\n async all(cb = noop) {\n let len = this.prefix.length;\n try {\n let keys = await this._getAllKeys();\n if (keys.length === 0)\n return cb(null, []);\n let data = await this.client.mget(keys);\n let results = data.reduce((acc, raw, idx) => {\n if (!raw)\n return acc;\n let sess = this.serializer.parse(raw);\n sess.id = keys[idx].substring(len);\n acc.push(sess);\n return acc;\n }, []);\n return cb(null, results);\n }\n catch (err) {\n return cb(err);\n }\n }\n _getTTL(sess) {\n if (typeof this.ttl === \"function\") {\n return this.ttl(sess);\n }\n let ttl;\n if (sess && sess.cookie && sess.cookie.expires) {\n let ms = Number(new Date(sess.cookie.expires)) - Date.now();\n ttl = Math.ceil(ms / 1000);\n }\n else {\n ttl = this.ttl;\n }\n return ttl;\n }\n async _getAllKeys() {\n let pattern = this.prefix + \"*\";\n let keys = [];\n for await (let key of this.client.scanIterator(pattern, this.scanCount)) {\n keys.push(key);\n }\n return keys;\n }\n}\nexport default RedisStore;\n","import type { ConfigService } from '@nestjs/config';\nimport RedisStore from 'connect-redis';\nimport type { RequestHandler } from 'express';\nimport {\n type ConfigParams,\n type CookieConfigParams,\n type SessionStore,\n auth,\n} from 'express-openid-connect';\nimport { createClient } from 'redis';\n\nimport { SharedConfigKeys } from '@/constants';\n\ntype Settings = {\n baseURL?: ConfigParams['baseURL'];\n clientID?: ConfigParams['clientID'];\n clientSecret?: ConfigParams['clientSecret'];\n authRequired?: ConfigParams['authRequired'];\n authorizationParams?: ConfigParams['authorizationParams'];\n afterCallback?: ConfigParams['afterCallback'];\n issuerBaseURL?: ConfigParams['issuerBaseURL'];\n sessionCookiePath?: CookieConfigParams['path'];\n};\n\nexport function authMiddleware(\n configService: ConfigService,\n {\n baseURL = 'https://127.0.0.1',\n clientSecret,\n clientID = ' ',\n authRequired = true,\n authorizationParams = {},\n afterCallback,\n issuerBaseURL = 'https://127.0.0.1',\n sessionCookiePath,\n }: Settings = {},\n): RequestHandler {\n let store: SessionStore | RedisStore | undefined;\n const redisHostUrl = configService.get<string>(SharedConfigKeys.RedisHost);\n if (redisHostUrl) {\n const redisClient = createClient({\n url: configService.getOrThrow<string>(SharedConfigKeys.RedisHost),\n password: configService.get<string>(SharedConfigKeys.RedisPassword),\n });\n\n redisClient.connect().catch(console.error);\n\n store = new RedisStore({\n client: redisClient,\n });\n }\n\n return auth({\n baseURL,\n clientSecret,\n clientID,\n authRequired,\n authorizationParams,\n afterCallback,\n issuerBaseURL,\n secret: configService.getOrThrow<string>(SharedConfigKeys.AuthCookieSecret),\n session: {\n name: configService.getOrThrow<string>(SharedConfigKeys.AuthCookieName),\n // @ts-ignore\n store,\n cookie: {\n path: sessionCookiePath,\n },\n },\n routes: {\n callback: '/signin-oidc',\n },\n });\n}\n","export enum SharedConfigKeys {\n AuthCookieName = 'AUTH_COOKIE_NAME',\n AuthCookieSecret = 'AUTH_COOKIE_SECRET',\n DbEndpoint = 'DB_ENDPOINT',\n JwtPrivateKey = 'JWT_PRIVATE_KEY',\n ServiceLogLevel = 'SERVICE_LOG_LEVEL',\n ServicePort = 'SERVICE_PORT',\n RedisHost = 'REDIS_HOST',\n RedisPassword = 'REDIS_PASSWORD',\n}\n","export enum AllianceHeaders {\n TargetUrl = 'alliance-target-url',\n TargetApp = 'alliance-target-app',\n TargetWorkspace = 'alliance-target-workspace',\n}\n","import type { ConfigService } from '@nestjs/config';\nimport { sign } from 'jsonwebtoken';\n\nimport { SharedConfigKeys } from '@/constants';\n\ntype BearerTokenSettings = {\n privateKey: string;\n aud: string;\n sub: string;\n name: string;\n user: {\n type: string;\n permissions: string[];\n email: string;\n };\n workspace: { name: string; slug: string };\n};\n\nexport function createBearerToken({\n privateKey,\n aud,\n sub,\n name,\n user,\n workspace,\n}: BearerTokenSettings) {\n const jwt = sign(\n {\n iss: 'Alliance',\n aud,\n sub,\n name,\n 'https://alliance.teliacompany.net/user_type': user.type,\n 'https://alliance.teliacompany.net/user_email': user.email,\n 'https://alliance.teliacompany.net/user_privileges': user.permissions,\n 'https://alliance.teliacompany.net/workspace': workspace.slug,\n 'https://alliance.teliacompany.net/workspace_name': workspace.name,\n 'https://alliance.teliacompany.net/tenant': workspace.slug,\n 'https://alliance.teliacompany.net/tenant_name': workspace.name,\n },\n privateKey,\n {\n expiresIn: '1h',\n algorithm: 'RS256',\n },\n );\n\n return `Bearer ${jwt}`;\n}\n\nexport function getPrivateKey(configService: ConfigService) {\n const privateKey = configService.getOrThrow<string>(SharedConfigKeys.JwtPrivateKey);\n\n return '-----BEGIN RSA PRIVATE KEY-----\\n' + privateKey + '\\n-----END RSA PRIVATE KEY-----';\n}\n\nexport function createSystemUserToken(configService: ConfigService) {\n return createBearerToken({\n aud: 'system',\n sub: 'system',\n name: 'system',\n workspace: {\n slug: 'system',\n name: 'system',\n },\n user: {\n type: 'system',\n permissions: [],\n email: 'system',\n },\n privateKey: getPrivateKey(configService),\n });\n}\n","import { validate } from 'jsonschema';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { generateCookiePolicyHtml } from './cookie-policy';\nimport { getJsonSchemas } from './json-schemas';\nimport { getManifests, getPkgJson } from './pkg-json';\n\nconst PUBLIC_DIR_NAME = 'public';\nconst MANIFESTS_FILE_NAME = 'manifests.json';\nconst COOKIE_POLICY_FILE_NAME = 'cookie-policy.html';\nconst APP_CONFIG_SCHEMA_FILE_NAME = 'config.schema.json';\nconst APP_MANIFEST_SCHEMA_FILE_NAME = 'manifest.schema.json';\n\nexport async function createPublicDistributionFiles() {\n const pkgJson = getPkgJson();\n const manifests = await getManifests(pkgJson);\n const schemas = getJsonSchemas();\n\n // Validate all app schemas\n for (const appName in manifests) {\n const manifest = manifests[appName];\n\n const validationResult = validate(manifest, schemas.appManifest);\n\n if (validationResult.errors.length) {\n const errors = validationResult.errors.map((e) => JSON.stringify(e, null, 2));\n throw new Error(\n `Validation of app manifest for app '${appName}' failed with the following errors:\\n${errors.join(\n '\\n',\n )}`,\n );\n }\n }\n\n // Make sure public dir exists\n const publicDirPath = resolve(process.cwd(), PUBLIC_DIR_NAME);\n if (!existsSync(publicDirPath)) {\n mkdirSync(publicDirPath);\n }\n\n // Create manifests file\n const manifestsFilePath = resolve(publicDirPath, MANIFESTS_FILE_NAME);\n writeFileSync(manifestsFilePath, JSON.stringify(manifests));\n\n // Create cookie policy document\n const cookiePolicyFilePath = resolve(publicDirPath, COOKIE_POLICY_FILE_NAME);\n writeFileSync(cookiePolicyFilePath, generateCookiePolicyHtml(manifests));\n\n // Create JSON schema files\n const appConfigSchemaFilePath = resolve(publicDirPath, APP_CONFIG_SCHEMA_FILE_NAME);\n const appManifestSchemaFilePath = resolve(publicDirPath, APP_MANIFEST_SCHEMA_FILE_NAME);\n writeFileSync(appConfigSchemaFilePath, JSON.stringify(schemas.appConfig));\n writeFileSync(appManifestSchemaFilePath, JSON.stringify(schemas.appManifest));\n}\n","import type { LooseObject } from '@/types';\n\nexport function generateCookiePolicyHtml(appManifests: LooseObject) {\n const cookiePolicyTableRows: string[] = [];\n\n for (const appName in appManifests) {\n const manifest = appManifests[appName];\n if (!manifest.storage) {\n continue;\n }\n\n for (const [key, value] of Object.entries(manifest.storage)) {\n const tableRow = createCookiePolicyTableRow(key, value as LooseObject);\n cookiePolicyTableRows.push(tableRow);\n }\n }\n\n return cookiePolicyHtml.replace('{APP_COOKIES}', cookiePolicyTableRows.join(''));\n}\n\nfunction createCookiePolicyTableRow(key: string, claimEntry: LooseObject) {\n const rows = ['<tr>'];\n const { category, purpose, lifespan } = claimEntry;\n rows.push(`<td>${key}</td>`);\n rows.push(`<td>${category}</td>`);\n rows.push(`<td>${purpose}</td>`);\n rows.push(`<td>${lifespan}</td>`);\n rows.push('</tr>');\n return rows.join('');\n}\n\nconst cookiePolicyHtml = `\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>ACE Alliance - Cookie Policy</title>\n <link\n rel=\"icon\"\n href=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAGcElEQVRYha2Xe4xUVx3HP7/fPTOzDLO7sw8RlzWlZEtp2dCy0qIVWltKU/UPDZH6ijXWEK2odPcPa2qbhpi2kSa7blSStsFUjNq0lWCMaVMx8rAm22IJMJRHCqFC6BJ22eEx+5p7z88/7sywC7uwgCe5mXsz5/y+j/M753eOcJ2tK5sDyBrME2gBmkBq43/tnMERgXdAjrbn518yXq4RNA3cB/J54HNiMhfEicm4oAYghmHexN4Dew5k01giUybQlc1h0CbI9zC+Imi9mCAIYhoHsnI4KcNjYoDhxWPxsxFY1Z5vHQVwVwSu3Qdid4E8rSb3i6mqKYwBjpWX1V/QZBiYYWIIiifCw8Mm/vS7L/W237FqJno58M5srgmxP4npjsAHDwTeaeAdagGBdwQWoBYgFqCmqGlMqvTE3+U+ipbeE+ngB42Lde6kDnRmcwisAHlBfdBYCYxStp3y7xjTJ51RA0XxgGCkasQFSfkW8NQlBDqzORVYK6ZPqAU6ThUyqd0TN7mQDRZ/CULzvVVeRO68xIGubE6BbjH9oVqA+thaQccpvjLwRDTit2RG/fxVGR3sLc4ELuRAV90+gJ/G4K4EHpRs1wr7qwW/uH36uaxPzwz0xNZhHUfAzJZgsjZWrqXEiTP9WlRP1Bb+pCacs2KaCwvmD/5+cLhCoCubU0G61QJXyWYkVv9/Av/UEzVh2+PVDmDPr875ob4oD6UcMLhfTdqU8dket+sDD6rwS7vrfMs30i4qRhzfMhwe3FhwQG+FgMDKytIyKe1o1zffZlB3swvve7mehgVJZ95zatdouG31gHpvoHYUwHVmc4AsqoCXYK9HtzhYsDoTLnqyRl1a1QxOvjMavrmyT4sFr6hhsA/AZUbqKKTy9ZfCXhuFpntS4WfWZWloTcTTa8bh14fCrY/2a3E4UlOLt2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Xj529dVKMK2bVL2fkmhrmJ/9cPy91Z2ZGwhMqQx95TudC8gdCZx4obbMVAhqNGvaoCr99bKD1svGntK4647vg84J8X021PBXlK5gJGJWr11GDb3fkW7dPJfaUi3539iARxSUCz4AsERMVpHwDxMTyhq0HftGRbz071bhXfeooXVJvBR4EbgSGgR6Bt9qvArjc/gfZzPoCTDB+AgAAAABJRU5ErkJggg==\"\n />\n <style>\n @charset \"UTF-8\";\n @import 'https://cdn.voca.teliacompany.com/fonts/TeliaSansV10/TeliaSans.css';\n @import 'https://fonts.googleapis.com/css?family=Reenie+Beanie';\n\n body {\n font-family: TeliaSans, Helvetica, Arial, Lucida Grande, sans-serif;\n }\n\n body > div {\n max-width: 1000px;\n margin: 0 auto;\n padding: 0 40px 40px;\n }\n </style>\n </head>\n\n <body>\n <div>\n <h1>Cookie Policy</h1>\n <p>\n On our websites, we use cookies and other similar technologies. You can choose\n whether you want to allow our websites to store cookies on your computer or not. You\n can change your choices at any time.\n </p>\n\n <h2>Your consent is required</h2>\n <p>\n You choose whether you want to accept cookies on your device or not. Your consent is\n required for the use of cookies, but not for such cookies that are necessary to\n enable the service that you as a user have requested. If you do not accept our use\n of cookies, or if you have previously approved our use and have changed your mind,\n you can return to your cookie settings at any time and change your choices. You do\n this by clicking on the cookie button/link. You may also need to change the settings\n in your browser and manually delete cookies to clear your device of previously\n stored cookies.\n </p>\n\n <h2>What are cookies?</h2>\n <p>\n A cookie is a small text file that is stored on your computer by the web browser\n while browsing a website. When we refer to cookies (“cookies”) in this policy, other\n similar technologies and tools that retrieve and store information in your browser,\n and in some cases forward such information to third parties, in a manner similar to\n cookies. Examples are pixels, local storage, session storage and fingerprinting.\n </p>\n <p>\n The websites will “remember” and “recognize” you. This can be done by placing\n cookies in three different ways;\n </p>\n <ul>\n <li>The session ends, ie until you close the window in your browser.</li>\n <li>\n Time-limited, ie the cookie has a predetermined lifespan. The time may vary\n between different cookies.\n </li>\n <li>\n Until further notice, ie the information remains until you choose to delete it\n yourself. This applies to local storage.\n </li>\n </ul>\n <p>You can always go into your browser and delete already stored cookies yourself.</p>\n\n <h3>Third Party Cookies</h3>\n <p>\n We use third-party cookies on our websites. Third-party cookies are stored by\n someone other than the person responsible for the website, in this case by a company\n other than Telia.\n </p>\n <p>\n Telia uses external platforms to communicate digitally, these include the Google\n Marketing Platform and others. The platforms use both first- and third-party cookies\n as well as similar techniques to advertise and follow up the results of the\n advertising.\n </p>\n <p>\n A third-party cookie can be used by several websites to understand and track how you\n browse between different websites. Telia receives information from these cookies,\n but the information can also be used for other purposes determined by third parties.\n Third-party cookies found on our website are covered by each third-party privacy\n policy. Feel free to read these to understand what other purposes the information\n can be used for. Links are in our Cookie Table.\n </p>\n <p>\n For information about which third-party cookies are used on our websites, see our\n Cookie Table. For more information on how Telia handles personal data in connection\n with transfers to third parties, read our Privacy Policy.\n </p>\n\n <h2>Cookies on our websites</h2>\n <p>\n In order for you to have better control over which cookies are used on the websites,\n and thus be able to more easily decide how cookies should be used when you visit our\n websites, we have identified four different categories of cookies. These categories\n are defined based on the purposes for the use of the cookies.\n </p>\n <p>\n In our Cookie Table, you can also see which category each cookie belongs to, for\n what purposes it is used and for how long it is active.\n </p>\n <p>\n We have identified the following four categories of cookies. All categories contain\n cookies which means that data is shared with third parties.\n </p>\n\n <h3>Necessary</h3>\n <p>\n These cookies are needed for our app to work in a secure and correct way. Necessary\n cookies enable you to use our app and us to provide the service you request.\n Necessary cookies make basic functions of the app possible, for example, identifying\n you when you log into My Telia, detecting repeated failed login attempts,\n identifying where you are in the buying process and remembering the items put into\n your shopping basket.\n </p>\n\n <h3>Functionality</h3>\n <p>\n These cookies let us to enable some useful functionalities to make the user\n experience better, for example, to remember your login details and settings.\n </p>\n\n <h3>Analytics</h3>\n <p>\n These cookies give us information about how you use our app and allow us to improve\n the user experience.\n </p>\n\n <h3>Marketing</h3>\n <p>\n These cookies help us and our partners to display personalized and relevant ads\n based on your browsing behavior on our website and in our app, even when you later\n visit other (third parties’) websites. These cookies are used to evaluate the\n effectiveness of our marketingcampaigns, as well as for targeted marketing and\n profiling, regardless of which device(s) you have used. Information collected for\n this purpose may also be combined with other customer and traffic data we have about\n you, if you have given your consent that we may use your traffic data for marketing\n purpose and have not objected to the use of your customer data for marketing\n purposes.\n </p>\n\n <h2>Manage settings</h2>\n <p>\n We save your cookie consent for 12 months. Then we will ask you again. Please note\n that some cookies have a lifespan that exceeds these 12 months. You may therefore\n need to change the settings in your browser and manually delete all cookies.\n </p>\n <p>\n More information on how to turn off cookies can be found in the instructions for\n your browser.\n </p>\n <ul>\n <li>\n <a\n href=\"https://support.google.com/accounts/answer/61416?co=GENIE.Platform%3DDesktop&amp;hl=en\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Google Chrome</a\n >\n </li>\n <li>\n <a\n href=\"https://privacy.microsoft.com/en-us/windows-10-microsoft-edge-and-privacy\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Microsoft Edge</a\n >\n </li>\n <li>\n <a\n href=\"https://support.mozilla.org/en-US/kb/enable-and-disable-cookies-website-preferences\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Mozilla Firefox</a\n >\n </li>\n <li>\n <a\n href=\"https://support.microsoft.com/en-gb/help/17442/windows-internet-explorer-delete-manage-cookies\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Microsoft Internet Explorer</a\n >\n </li>\n <li>\n <a\n href=\"https://www.opera.com/help/tutorials/security/privacy/\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Opera</a\n >\n </li>\n <li>\n <a\n href=\"https://support.apple.com/guide/safari/manage-cookies-and-website-data-sfri11471/mac\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Apple Safari</a\n >\n </li>\n </ul>\n\n <h3>Do Not Track-signals</h3>\n <p>\n If you have chosen to turn on the Do Not Track function in your browser, we will not\n automatically place cookies for marketing on your device. You make other choices in\n your cookie settings.\n </p>\n\n <h3>If you block cookies</h3>\n <p>\n If you choose not to accept our use of cookies, the functionality and performance of\n our websites may deteriorate as certain functions are dependent on cookies. A\n blocking of cookies can therefore mean that the websites’ services do not work as\n they should.\n </p>\n\n <h3>Your security with us</h3>\n <p>\n If you want to read more about your rights and how we protect your privacy, go to\n our privacy policy for\n <a\n href=\"https://www.telia.se/dam/jcr:df2eeb83-50ce-4383-89fc-0613f7615796/Integritetspolicy-privatkunder.pdf\"\n >private customers</a\n >\n (C2B) or\n <a\n href=\"https://www.telia.se/dam/jcr:95b2b4a5-82ca-436b-90e0-873e0a864118/Telia-integritetspolicy-foretag.pdf\"\n >corporate customers</a\n >\n (B2B). You are always welcome to contact us at\n <a href=\"mailto:dpo-se@teliacompany.com\">dpo-se@teliacompany.com</a> if you have any\n questions.\n </p>\n <p>Our cookie policy may change in the future.</p>\n <p>\n More information about cookies can be found at the Swedish Post and Telecom\n Authority (PTS).\n </p>\n\n <h2>Our Cookie Table</h2>\n <p>\n Below, you will find a list of the cookies and similar technologies that we use on\n this website. These cookies are stored on your device by us.\n </p>\n <table>\n <thead>\n <tr>\n <th>Cookie</th>\n <th>Category</th>\n <th>Purpose</th>\n <th>Lifespan</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>alliance-session-v1</td>\n <td>necessary</td>\n <td>Contains the authenticated user.</td>\n <td>1 day</td>\n </tr>\n {APP_COOKIES}\n </tbody>\n </table>\n <style>\n table {\n width: 100%;\n border: 1px solid rgba(0, 0, 0, 0.15);\n }\n th, td {\n text-align: left;\n padding: 3px;\n }\n </style>\n </div>\n </body>\n</html>\n`;\n","import type { Schema } from 'jsonschema';\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\ntype JsonSchemas = {\n appConfig: Schema;\n appManifest: Schema;\n};\n\nexport function getJsonSchemas(): JsonSchemas {\n const frameworkDistDirPath = resolve(\n process.cwd(),\n 'node_modules',\n '@telia-ace/alliance-framework',\n 'dist',\n );\n const appConfigSchemaPath = resolve(frameworkDistDirPath, 'config.schema.json');\n const appManifestSchemaPath = resolve(frameworkDistDirPath, 'manifest.schema.json');\n const appConfigSchemaFile = readFileSync(appConfigSchemaPath).toString();\n const appManifestSchemaFile = readFileSync(appManifestSchemaPath).toString();\n const appConfig = JSON.parse(appConfigSchemaFile);\n const appManifest = JSON.parse(appManifestSchemaFile);\n\n return {\n appConfig,\n appManifest,\n };\n}\n","import { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { getAppManifests } from '@/get-app-manifests';\nimport type { LooseObject } from '@/types';\n\ntype PkgJson = LooseObject & {\n name: string;\n version: string;\n};\n\nexport type AlliancePortalDistPkgJson = PkgJson & {\n alliance?: {\n apps?: string[];\n };\n};\n\nexport function getPkgJson(): AlliancePortalDistPkgJson {\n const packageJson = resolve(process.cwd(), 'package.json');\n const pkgJsonFile = readFileSync(packageJson).toString();\n return JSON.parse(pkgJsonFile);\n}\n\nexport async function getManifests(pkgJson: AlliancePortalDistPkgJson) {\n if (!pkgJson || !pkgJson.alliance || !pkgJson.alliance.apps) {\n throw new Error('Alliance apps not defined in package.json.');\n }\n\n const manifestArray = await getAppManifests(pkgJson.alliance.apps);\n\n return manifestArray.reduce((acc, curr: LooseObject) => {\n acc[curr.name] = curr;\n\n return acc;\n }, {});\n}\n","import { rmSync, writeFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport type { LooseObject } from './types';\n\nasync function createTempModuleAndImport<T>(moduleString: string, fileName: string): Promise<T> {\n const file = resolve(process.cwd(), `${fileName}.mjs`);\n writeFileSync(file, moduleString);\n const importedModule = await import(`file:///${file}`);\n rmSync(file, { force: true });\n return importedModule;\n}\n\n// Creates a temporary ES module and imports app manifests for all requested apps\n// This reusable utility can access all node modules available in the directory where it is ran\nexport async function getAppManifests(apps: string[]): Promise<LooseObject[]> {\n const moduleStringParts = [];\n const manifestImportVariables = [];\n\n for (const packageName of apps) {\n const manifestImportVariable = `app${apps.indexOf(packageName)}`;\n manifestImportVariables.push(manifestImportVariable);\n moduleStringParts.push(`import ${manifestImportVariable} from '${packageName}/manifest';`);\n }\n\n moduleStringParts.push(`export default [${manifestImportVariables.join(', ')}];`);\n\n const result = await createTempModuleAndImport<{ default: LooseObject[] }>(\n moduleStringParts.join('\\n'),\n 'app-manifests',\n );\n\n return result.default;\n}\n","import { GraphQLError } from 'graphql';\n\nimport { type ErrorCodes, allianceErrors } from './codes';\n\nfunction parseTemplates(message: string, variables: Record<string, string>) {\n return Object.entries(variables).reduce((acc, [key, value]) => {\n return acc.replaceAll(`{{${key}}}`, value);\n }, message);\n}\n\nexport class AllianceGqlException extends GraphQLError {\n public info: string;\n public code: ErrorCodes;\n constructor(code: ErrorCodes, variables: Record<string, string> = {}, extensions?: any) {\n const { message } = allianceErrors[code];\n\n super(parseTemplates(message, variables), {\n extensions,\n });\n\n this.code = code;\n this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${code}`;\n }\n}\n","import { HttpStatus } from '@nestjs/common';\n\nimport { AllianceHeaders } from '@/constants';\n\nexport enum GatewayErrorCodes {\n NoObjectId = 10001,\n NoTargetAppHeader = 10002,\n NoTargetWorkspaceHeader = 10003,\n NoManifestsInCache = 10004,\n NoDevSessionInCache = 10005,\n NoManifest = 10006,\n NoRequestContext = 10007,\n NoUserInRequestContext = 10008,\n NoAppInRequestContext = 10009,\n NoWorkspaceInRequestContext = 10010,\n NoUserPermissionsInRequestContext = 10012,\n WorkspacePermissionDenied = 10013,\n}\n\nexport enum DatabasesErrorCodes {\n NoPublicKey = 11000,\n NoAuthHeader = 11001,\n FailedFileStore = 11002,\n FailedFileRead = 11003,\n NoRecord = 11004,\n UniqueConstrain = 11005,\n}\n\nexport enum PortalErrorCodes {\n NoObjectId = 12000,\n}\n\nexport type ErrorCodes = GatewayErrorCodes | DatabasesErrorCodes | PortalErrorCodes;\n\ntype AllianceErrors = {\n [key in ErrorCodes]: {\n httpCode: HttpStatus;\n message: string;\n };\n};\n\nexport const allianceErrors: AllianceErrors = {\n // gateway\n [GatewayErrorCodes.NoObjectId]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No object id available on authenticated user.',\n },\n [GatewayErrorCodes.NoTargetAppHeader]: {\n httpCode: HttpStatus.BAD_REQUEST,\n message: `Request missing header '${AllianceHeaders.TargetApp}'.`,\n },\n [GatewayErrorCodes.NoTargetWorkspaceHeader]: {\n httpCode: HttpStatus.BAD_REQUEST,\n message: `Request missing header '${AllianceHeaders.TargetWorkspace}'.`,\n },\n [GatewayErrorCodes.NoManifestsInCache]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'App manifests missing in cache.',\n },\n [GatewayErrorCodes.NoDevSessionInCache]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No dev session in memory cache.',\n },\n [GatewayErrorCodes.NoManifest]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: \"Could not find manifest for app '{{appSlug}}'.\",\n },\n [GatewayErrorCodes.NoRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No request context.',\n },\n [GatewayErrorCodes.NoUserInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No user in request context.',\n },\n [GatewayErrorCodes.NoAppInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No app in request context.',\n },\n [GatewayErrorCodes.NoWorkspaceInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No workspace in request context.',\n },\n [GatewayErrorCodes.NoUserPermissionsInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No user permissions in request context.',\n },\n [GatewayErrorCodes.WorkspacePermissionDenied]: {\n httpCode: HttpStatus.FORBIDDEN,\n message: 'User does not have access to the current workspace.',\n },\n\n // databases\n [DatabasesErrorCodes.NoPublicKey]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No public key available to decode JWT.',\n },\n [DatabasesErrorCodes.NoAuthHeader]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No authorization header found.',\n },\n [DatabasesErrorCodes.FailedFileStore]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Error storing file.',\n },\n [DatabasesErrorCodes.FailedFileRead]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Error reading file.',\n },\n [DatabasesErrorCodes.NoRecord]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Missing database record.',\n },\n [DatabasesErrorCodes.UniqueConstrain]: {\n httpCode: HttpStatus.CONFLICT,\n message: 'Field has to be unique.',\n },\n\n // portal\n [PortalErrorCodes.NoObjectId]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No object id found in user claims.',\n },\n};\n","import { HttpException } from '@nestjs/common';\n\nimport { type ErrorCodes, allianceErrors } from './codes';\n\nfunction parseTemplates(message: string, variables: Record<string, string>) {\n return Object.entries(variables).reduce((acc, [key, value]) => {\n return acc.replaceAll(`{{${key}}}`, value);\n }, message);\n}\n\nexport class AllianceException extends HttpException {\n public info: string;\n public code: ErrorCodes;\n constructor(code: ErrorCodes, variables: Record<string, string> = {}) {\n const { message, httpCode } = allianceErrors[code];\n\n super(parseTemplates(message, variables), httpCode);\n\n this.code = code;\n this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${code}`;\n }\n}\n","import { type ArgumentsHost, Catch, type ExceptionFilter } from '@nestjs/common';\nimport type { Response } from 'express';\n\nimport { AllianceException } from './alliance.exception';\n\n@Catch(AllianceException)\nexport class AllianceExceptionFilter implements ExceptionFilter {\n catch(exception: AllianceException, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<Response>();\n const status = exception.getStatus();\n\n response.status &&\n response.status(status).json({\n httpCode: status,\n code: exception.code,\n info: exception.info,\n message: exception.message,\n });\n }\n}\n","import { type DynamicModule, Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { LoggerModule as PinoModule } from 'nestjs-pino';\n\nimport { SharedConfigKeys } from '@/constants';\n\nimport { LoggerService } from './logging.service';\n\ntype ModuleSettings = {\n logLevel?: string;\n redact?: boolean;\n};\n\n@Module({\n providers: [LoggerService],\n exports: [LoggerService],\n})\nexport class LoggerModule {\n static forRoot({ logLevel, redact = true }: ModuleSettings = {}): DynamicModule {\n return {\n module: LoggerModule,\n controllers: [],\n imports: [\n PinoModule.forRootAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => ({\n pinoHttp: {\n level:\n logLevel ||\n configService.get<string>(SharedConfigKeys.ServiceLogLevel) ||\n 'silent',\n redact: redact\n ? [\n 'authorization',\n 'headers.authorization',\n 'req.headers.authorization',\n 'res.headers.authorization',\n ]\n : [],\n },\n }),\n }),\n ],\n global: true,\n providers: [LoggerService],\n exports: [],\n };\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport { PinoLogger } from 'nestjs-pino';\nimport { InjectPinoLogger } from 'nestjs-pino';\n\n@Injectable()\nexport class LoggerService {\n constructor(@InjectPinoLogger() private readonly logger: PinoLogger) {}\n log: PinoLogger['info'] = (...args) => this.logger.info(...args);\n trace: PinoLogger['trace'] = (...args) => this.logger.trace(...args);\n debug: PinoLogger['debug'] = (...args) => this.logger.debug(...args);\n info: PinoLogger['info'] = (...args) => this.logger.info(...args);\n warn: PinoLogger['warn'] = (...args) => this.logger.warn(...args);\n error: PinoLogger['error'] = (...args) => this.logger.error(...args);\n fatal: PinoLogger['fatal'] = (...args) => this.logger.fatal(...args);\n}\n","import _slugify from 'slugify';\n\nexport function slugify(name: string) {\n return _slugify(name, { strict: true, replacement: '-', lower: true });\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -26,6 +26,7 @@ type BearerTokenSettings = {
26
26
  user: {
27
27
  type: string;
28
28
  permissions: string[];
29
+ email: string;
29
30
  };
30
31
  workspace: {
31
32
  name: string;
package/dist/index.d.ts CHANGED
@@ -26,6 +26,7 @@ type BearerTokenSettings = {
26
26
  user: {
27
27
  type: string;
28
28
  permissions: string[];
29
+ email: string;
29
30
  };
30
31
  workspace: {
31
32
  name: string;
package/dist/index.js CHANGED
@@ -253,6 +253,7 @@ function createBearerToken({ privateKey, aud, sub, name, user, workspace }) {
253
253
  sub,
254
254
  name,
255
255
  "https://alliance.teliacompany.net/user_type": user.type,
256
+ "https://alliance.teliacompany.net/user_email": user.email,
256
257
  "https://alliance.teliacompany.net/user_privileges": user.permissions,
257
258
  "https://alliance.teliacompany.net/workspace": workspace.slug,
258
259
  "https://alliance.teliacompany.net/workspace_name": workspace.name,
@@ -281,7 +282,8 @@ function createSystemUserToken(configService) {
281
282
  },
282
283
  user: {
283
284
  type: "system",
284
- permissions: []
285
+ permissions: [],
286
+ email: "system"
285
287
  },
286
288
  privateKey: getPrivateKey(configService)
287
289
  });
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/connect-redis@7.1.0_express-session@1.17.3/node_modules/connect-redis/dist/esm/index.js","../src/auth/auth.middleware.ts","../src/constants/config.ts","../src/constants/headers.ts","../src/auth/tokens.ts","../src/distribution/create-public-files.ts","../src/distribution/cookie-policy.ts","../src/distribution/json-schemas.ts","../src/distribution/pkg-json.ts","../src/get-app-manifests.ts","../src/exceptions/alliance-gql.exception.ts","../src/exceptions/codes.ts","../src/exceptions/alliance.exception.ts","../src/exceptions/exception.filter.ts","../src/logging/logging.module.ts","../src/logging/logging.service.ts","../src/slugify.ts"],"names":["LoggerErrorInterceptor","Store","noop","_err","_data","RedisStore","constructor","opts","prefix","scanCount","serializer","JSON","ttl","disableTTL","disableTouch","client","normalizeClient","isRedis","get","key","set","val","EX","del","expire","mget","keys","mGet","scanIterator","match","count","MATCH","COUNT","c","xs","scan","sid","cb","data","parse","err","sess","_getTTL","stringify","destroy","touch","clear","_getAllKeys","length","ids","len","map","k","substring","all","results","reduce","acc","raw","idx","id","push","cookie","expires","ms","Number","Date","now","Math","ceil","pattern","auth","createClient","SharedConfigKeys","AllianceHeaders","authMiddleware","configService","baseURL","clientSecret","clientID","authRequired","authorizationParams","afterCallback","issuerBaseURL","sessionCookiePath","store","redisHostUrl","RedisHost","redisClient","url","getOrThrow","password","RedisPassword","connect","catch","console","error","secret","AuthCookieSecret","session","name","AuthCookieName","path","routes","callback","sign","createBearerToken","privateKey","aud","sub","user","workspace","jwt","iss","type","permissions","slug","expiresIn","algorithm","getPrivateKey","JwtPrivateKey","createSystemUserToken","validate","existsSync","mkdirSync","writeFileSync","resolve","generateCookiePolicyHtml","appManifests","cookiePolicyTableRows","appName","manifest","storage","value","Object","entries","tableRow","createCookiePolicyTableRow","cookiePolicyHtml","replace","join","claimEntry","rows","category","purpose","lifespan","readFileSync","getJsonSchemas","frameworkDistDirPath","process","cwd","appConfigSchemaPath","appManifestSchemaPath","appConfigSchemaFile","toString","appManifestSchemaFile","appConfig","appManifest","rmSync","createTempModuleAndImport","moduleString","fileName","file","importedModule","force","getAppManifests","apps","moduleStringParts","manifestImportVariables","packageName","manifestImportVariable","indexOf","result","default","getPkgJson","packageJson","pkgJsonFile","getManifests","pkgJson","alliance","Error","manifestArray","curr","PUBLIC_DIR_NAME","MANIFESTS_FILE_NAME","COOKIE_POLICY_FILE_NAME","APP_CONFIG_SCHEMA_FILE_NAME","APP_MANIFEST_SCHEMA_FILE_NAME","createPublicDistributionFiles","manifests","schemas","validationResult","errors","e","publicDirPath","manifestsFilePath","cookiePolicyFilePath","appConfigSchemaFilePath","appManifestSchemaFilePath","GraphQLError","HttpStatus","GatewayErrorCodes","DatabasesErrorCodes","PortalErrorCodes","allianceErrors","httpCode","UNAUTHORIZED","message","BAD_REQUEST","TargetApp","TargetWorkspace","INTERNAL_SERVER_ERROR","FORBIDDEN","CONFLICT","parseTemplates","variables","replaceAll","AllianceGqlException","info","code","extensions","HttpException","AllianceException","Catch","AllianceExceptionFilter","exception","host","ctx","switchToHttp","response","getResponse","status","getStatus","json","Module","ConfigModule","ConfigService","LoggerModule","PinoModule","Injectable","PinoLogger","InjectPinoLogger","LoggerService","logger","log","args","trace","debug","warn","fatal","forRoot","logLevel","redact","module","controllers","imports","forRootAsync","inject","useFactory","pinoHttp","level","ServiceLogLevel","global","providers","exports","_slugify","slugify","strict","replacement","lower"],"mappings":";;;;AAAA,SAASA,8BAA8B;;;ACAvC,SAASC,aAAa;AACtB,IAAMC,OAAO,wBAACC,MAAMC,UAAAA;AAAY,GAAnB;AACb,IAAMC,aAAN,MAAMA,oBAAmBJ,MAAAA;EAFzB,OAEyBA;;;EACrBK,YAAYC,MAAM;AACd,UAAK;AACL,SAAKC,SAASD,KAAKC,UAAU,OAAO,UAAUD,KAAKC;AACnD,SAAKC,YAAYF,KAAKE,aAAa;AACnC,SAAKC,aAAaH,KAAKG,cAAcC;AACrC,SAAKC,MAAML,KAAKK,OAAO;AACvB,SAAKC,aAAaN,KAAKM,cAAc;AACrC,SAAKC,eAAeP,KAAKO,gBAAgB;AACzC,SAAKC,SAAS,KAAKC,gBAAgBT,KAAKQ,MAAM;EAClD;;EAEAC,gBAAgBD,QAAQ;AACpB,QAAIE,UAAU,kBAAkBF;AAChC,WAAO;MACHG,KAAK,CAACC,QAAQJ,OAAOG,IAAIC,GAAAA;MACzBC,KAAK,CAACD,KAAKE,KAAKT,QAAAA;AACZ,YAAIA,KAAK;AACL,iBAAOK,UACDF,OAAOK,IAAID,KAAKE,KAAK;YAAEC,IAAIV;UAAI,CAAA,IAC/BG,OAAOK,IAAID,KAAKE,KAAK,MAAMT,GAAAA;QACrC;AACA,eAAOG,OAAOK,IAAID,KAAKE,GAAAA;MAC3B;MACAE,KAAK,CAACJ,QAAQJ,OAAOQ,IAAIJ,GAAAA;MACzBK,QAAQ,CAACL,KAAKP,QAAQG,OAAOS,OAAOL,KAAKP,GAAAA;MACzCa,MAAM,CAACC,SAAUT,UAAUF,OAAOY,KAAKD,IAAAA,IAAQX,OAAOU,KAAKC,IAAAA;MAC3DE,cAAc,CAACC,OAAOC,UAAA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E,UAAAA,GAAAA,iBAAAA,CAAAA;;;WAA4C,eAAA,cAAA,SAAA;;GADhDC,aAAAA;;;;;;;;;;;;;;ADYb,IAAaL,eAAN,MAAAA,cAAA;SAAA;;;EACH,OAAOa,QAAQ,EAAEC,UAAUC,SAAS,KAAI,IAAqB,CAAC,GAAkB;AAC5E,WAAO;MACHC,QAAQhB;MACRiB,aAAa,CAAA;MACbC,SAAS;QACLjB,WAAWkB,aAAa;UACpBD,SAAS;YAACpB;;UACVsB,QAAQ;YAACrB;;UACTsB,YAAY,OAAOtL,mBAAkC;YACjDuL,UAAU;cACNC,OACIT,YACA/K,cAAc1D,IAAYuD,iBAAiB4L,eAAe,KAC1D;cACJT,QAAQA,SACF;gBACI;gBACA;gBACA;gBACA;kBAEJ,CAAA;YACV;UACJ;QACJ,CAAA;;MAEJU,QAAQ;MACRC,WAAW;QAACrB;;MACZsB,SAAS,CAAA;IACb;EACJ;AACJ;AAhCa3B,eAAAA,cAAAA;EAJZH,OAAO;IACJ6B,WAAW;MAACrB;;IACZsB,SAAS;MAACtB;;EACd,CAAA;GACaL,YAAAA;;;AEjBb,OAAO4B,cAAc;AAEd,SAASC,QAAQtK,MAAY;AAChC,SAAOqK,SAASrK,MAAM;IAAEuK,QAAQ;IAAMC,aAAa;IAAKC,OAAO;EAAK,CAAA;AACxE;AAFgBH","sourcesContent":["export { LoggerErrorInterceptor } from 'nestjs-pino';\nexport { authMiddleware, createBearerToken, createSystemUserToken, getPrivateKey } from './auth';\nexport { AllianceHeaders, SharedConfigKeys } from './constants';\nexport { createPublicDistributionFiles } from './distribution';\nexport {\n AllianceException,\n AllianceExceptionFilter,\n AllianceGqlException,\n DatabasesErrorCodes,\n GatewayErrorCodes,\n PortalErrorCodes,\n} from './exceptions';\nexport { getAppManifests } from './get-app-manifests';\nexport { LoggerModule, LoggerService } from './logging';\nexport { slugify } from './slugify';\n","import { Store } from \"express-session\";\nconst noop = (_err, _data) => { };\nclass RedisStore extends Store {\n constructor(opts) {\n super();\n this.prefix = opts.prefix == null ? \"sess:\" : opts.prefix;\n this.scanCount = opts.scanCount || 100;\n this.serializer = opts.serializer || JSON;\n this.ttl = opts.ttl || 86400; // One day in seconds.\n this.disableTTL = opts.disableTTL || false;\n this.disableTouch = opts.disableTouch || false;\n this.client = this.normalizeClient(opts.client);\n }\n // Create a redis and ioredis compatible client\n normalizeClient(client) {\n let isRedis = \"scanIterator\" in client;\n return {\n get: (key) => client.get(key),\n set: (key, val, ttl) => {\n if (ttl) {\n return isRedis\n ? client.set(key, val, { EX: ttl })\n : client.set(key, val, \"EX\", ttl);\n }\n return client.set(key, val);\n },\n del: (key) => client.del(key),\n expire: (key, ttl) => client.expire(key, ttl),\n mget: (keys) => (isRedis ? client.mGet(keys) : client.mget(keys)),\n scanIterator: (match, count) => {\n if (isRedis)\n return client.scanIterator({ MATCH: match, COUNT: count });\n // ioredis impl.\n return (async function* () {\n let [c, xs] = await client.scan(\"0\", \"MATCH\", match, \"COUNT\", count);\n for (let key of xs)\n yield key;\n while (c !== \"0\") {\n ;\n [c, xs] = await client.scan(c, \"MATCH\", match, \"COUNT\", count);\n for (let key of xs)\n yield key;\n }\n })();\n },\n };\n }\n async get(sid, cb = noop) {\n let key = this.prefix + sid;\n try {\n let data = await this.client.get(key);\n if (!data)\n return cb();\n return cb(null, await this.serializer.parse(data));\n }\n catch (err) {\n return cb(err);\n }\n }\n async set(sid, sess, cb = noop) {\n let key = this.prefix + sid;\n let ttl = this._getTTL(sess);\n try {\n let val = this.serializer.stringify(sess);\n if (ttl > 0) {\n if (this.disableTTL)\n await this.client.set(key, val);\n else\n await this.client.set(key, val, ttl);\n return cb();\n }\n else {\n return this.destroy(sid, cb);\n }\n }\n catch (err) {\n return cb(err);\n }\n }\n async touch(sid, sess, cb = noop) {\n let key = this.prefix + sid;\n if (this.disableTouch || this.disableTTL)\n return cb();\n try {\n await this.client.expire(key, this._getTTL(sess));\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async destroy(sid, cb = noop) {\n let key = this.prefix + sid;\n try {\n await this.client.del([key]);\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async clear(cb = noop) {\n try {\n let keys = await this._getAllKeys();\n if (!keys.length)\n return cb();\n await this.client.del(keys);\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async length(cb = noop) {\n try {\n let keys = await this._getAllKeys();\n return cb(null, keys.length);\n }\n catch (err) {\n return cb(err);\n }\n }\n async ids(cb = noop) {\n let len = this.prefix.length;\n try {\n let keys = await this._getAllKeys();\n return cb(null, keys.map((k) => k.substring(len)));\n }\n catch (err) {\n return cb(err);\n }\n }\n async all(cb = noop) {\n let len = this.prefix.length;\n try {\n let keys = await this._getAllKeys();\n if (keys.length === 0)\n return cb(null, []);\n let data = await this.client.mget(keys);\n let results = data.reduce((acc, raw, idx) => {\n if (!raw)\n return acc;\n let sess = this.serializer.parse(raw);\n sess.id = keys[idx].substring(len);\n acc.push(sess);\n return acc;\n }, []);\n return cb(null, results);\n }\n catch (err) {\n return cb(err);\n }\n }\n _getTTL(sess) {\n if (typeof this.ttl === \"function\") {\n return this.ttl(sess);\n }\n let ttl;\n if (sess && sess.cookie && sess.cookie.expires) {\n let ms = Number(new Date(sess.cookie.expires)) - Date.now();\n ttl = Math.ceil(ms / 1000);\n }\n else {\n ttl = this.ttl;\n }\n return ttl;\n }\n async _getAllKeys() {\n let pattern = this.prefix + \"*\";\n let keys = [];\n for await (let key of this.client.scanIterator(pattern, this.scanCount)) {\n keys.push(key);\n }\n return keys;\n }\n}\nexport default RedisStore;\n","import type { ConfigService } from '@nestjs/config';\nimport RedisStore from 'connect-redis';\nimport type { RequestHandler } from 'express';\nimport {\n type ConfigParams,\n type CookieConfigParams,\n type SessionStore,\n auth,\n} from 'express-openid-connect';\nimport { createClient } from 'redis';\n\nimport { SharedConfigKeys } from '@/constants';\n\ntype Settings = {\n baseURL?: ConfigParams['baseURL'];\n clientID?: ConfigParams['clientID'];\n clientSecret?: ConfigParams['clientSecret'];\n authRequired?: ConfigParams['authRequired'];\n authorizationParams?: ConfigParams['authorizationParams'];\n afterCallback?: ConfigParams['afterCallback'];\n issuerBaseURL?: ConfigParams['issuerBaseURL'];\n sessionCookiePath?: CookieConfigParams['path'];\n};\n\nexport function authMiddleware(\n configService: ConfigService,\n {\n baseURL = 'https://127.0.0.1',\n clientSecret,\n clientID = ' ',\n authRequired = true,\n authorizationParams = {},\n afterCallback,\n issuerBaseURL = 'https://127.0.0.1',\n sessionCookiePath,\n }: Settings = {},\n): RequestHandler {\n let store: SessionStore | RedisStore | undefined;\n const redisHostUrl = configService.get<string>(SharedConfigKeys.RedisHost);\n if (redisHostUrl) {\n const redisClient = createClient({\n url: configService.getOrThrow<string>(SharedConfigKeys.RedisHost),\n password: configService.get<string>(SharedConfigKeys.RedisPassword),\n });\n\n redisClient.connect().catch(console.error);\n\n store = new RedisStore({\n client: redisClient,\n });\n }\n\n return auth({\n baseURL,\n clientSecret,\n clientID,\n authRequired,\n authorizationParams,\n afterCallback,\n issuerBaseURL,\n secret: configService.getOrThrow<string>(SharedConfigKeys.AuthCookieSecret),\n session: {\n name: configService.getOrThrow<string>(SharedConfigKeys.AuthCookieName),\n // @ts-ignore\n store,\n cookie: {\n path: sessionCookiePath,\n },\n },\n routes: {\n callback: '/signin-oidc',\n },\n });\n}\n","export enum SharedConfigKeys {\n AuthCookieName = 'AUTH_COOKIE_NAME',\n AuthCookieSecret = 'AUTH_COOKIE_SECRET',\n DbEndpoint = 'DB_ENDPOINT',\n JwtPrivateKey = 'JWT_PRIVATE_KEY',\n ServiceLogLevel = 'SERVICE_LOG_LEVEL',\n ServicePort = 'SERVICE_PORT',\n RedisHost = 'REDIS_HOST',\n RedisPassword = 'REDIS_PASSWORD',\n}\n","export enum AllianceHeaders {\n TargetUrl = 'alliance-target-url',\n TargetApp = 'alliance-target-app',\n TargetWorkspace = 'alliance-target-workspace',\n}\n","import type { ConfigService } from '@nestjs/config';\nimport { sign } from 'jsonwebtoken';\n\nimport { SharedConfigKeys } from '@/constants';\n\ntype BearerTokenSettings = {\n privateKey: string;\n aud: string;\n sub: string;\n name: string;\n user: {\n type: string;\n permissions: string[];\n };\n workspace: { name: string; slug: string };\n};\n\nexport function createBearerToken({\n privateKey,\n aud,\n sub,\n name,\n user,\n workspace,\n}: BearerTokenSettings) {\n const jwt = sign(\n {\n iss: 'Alliance',\n aud,\n sub,\n name,\n 'https://alliance.teliacompany.net/user_type': user.type,\n 'https://alliance.teliacompany.net/user_privileges': user.permissions,\n 'https://alliance.teliacompany.net/workspace': workspace.slug,\n 'https://alliance.teliacompany.net/workspace_name': workspace.name,\n 'https://alliance.teliacompany.net/tenant': workspace.slug,\n 'https://alliance.teliacompany.net/tenant_name': workspace.name,\n },\n privateKey,\n {\n expiresIn: '1h',\n algorithm: 'RS256',\n },\n );\n\n return `Bearer ${jwt}`;\n}\n\nexport function getPrivateKey(configService: ConfigService) {\n const privateKey = configService.getOrThrow<string>(SharedConfigKeys.JwtPrivateKey);\n\n return '-----BEGIN RSA PRIVATE KEY-----\\n' + privateKey + '\\n-----END RSA PRIVATE KEY-----';\n}\n\nexport function createSystemUserToken(configService: ConfigService) {\n return createBearerToken({\n aud: 'system',\n sub: 'system',\n name: 'system',\n workspace: {\n slug: 'system',\n name: 'system',\n },\n user: {\n type: 'system',\n permissions: [],\n },\n privateKey: getPrivateKey(configService),\n });\n}\n","import { validate } from 'jsonschema';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { generateCookiePolicyHtml } from './cookie-policy';\nimport { getJsonSchemas } from './json-schemas';\nimport { getManifests, getPkgJson } from './pkg-json';\n\nconst PUBLIC_DIR_NAME = 'public';\nconst MANIFESTS_FILE_NAME = 'manifests.json';\nconst COOKIE_POLICY_FILE_NAME = 'cookie-policy.html';\nconst APP_CONFIG_SCHEMA_FILE_NAME = 'config.schema.json';\nconst APP_MANIFEST_SCHEMA_FILE_NAME = 'manifest.schema.json';\n\nexport async function createPublicDistributionFiles() {\n const pkgJson = getPkgJson();\n const manifests = await getManifests(pkgJson);\n const schemas = getJsonSchemas();\n\n // Validate all app schemas\n for (const appName in manifests) {\n const manifest = manifests[appName];\n\n const validationResult = validate(manifest, schemas.appManifest);\n\n if (validationResult.errors.length) {\n const errors = validationResult.errors.map((e) => JSON.stringify(e, null, 2));\n throw new Error(\n `Validation of app manifest for app '${appName}' failed with the following errors:\\n${errors.join(\n '\\n',\n )}`,\n );\n }\n }\n\n // Make sure public dir exists\n const publicDirPath = resolve(process.cwd(), PUBLIC_DIR_NAME);\n if (!existsSync(publicDirPath)) {\n mkdirSync(publicDirPath);\n }\n\n // Create manifests file\n const manifestsFilePath = resolve(publicDirPath, MANIFESTS_FILE_NAME);\n writeFileSync(manifestsFilePath, JSON.stringify(manifests));\n\n // Create cookie policy document\n const cookiePolicyFilePath = resolve(publicDirPath, COOKIE_POLICY_FILE_NAME);\n writeFileSync(cookiePolicyFilePath, generateCookiePolicyHtml(manifests));\n\n // Create JSON schema files\n const appConfigSchemaFilePath = resolve(publicDirPath, APP_CONFIG_SCHEMA_FILE_NAME);\n const appManifestSchemaFilePath = resolve(publicDirPath, APP_MANIFEST_SCHEMA_FILE_NAME);\n writeFileSync(appConfigSchemaFilePath, JSON.stringify(schemas.appConfig));\n writeFileSync(appManifestSchemaFilePath, JSON.stringify(schemas.appManifest));\n}\n","import type { LooseObject } from '@/types';\n\nexport function generateCookiePolicyHtml(appManifests: LooseObject) {\n const cookiePolicyTableRows: string[] = [];\n\n for (const appName in appManifests) {\n const manifest = appManifests[appName];\n if (!manifest.storage) {\n continue;\n }\n\n for (const [key, value] of Object.entries(manifest.storage)) {\n const tableRow = createCookiePolicyTableRow(key, value as LooseObject);\n cookiePolicyTableRows.push(tableRow);\n }\n }\n\n return cookiePolicyHtml.replace('{APP_COOKIES}', cookiePolicyTableRows.join(''));\n}\n\nfunction createCookiePolicyTableRow(key: string, claimEntry: LooseObject) {\n const rows = ['<tr>'];\n const { category, purpose, lifespan } = claimEntry;\n rows.push(`<td>${key}</td>`);\n rows.push(`<td>${category}</td>`);\n rows.push(`<td>${purpose}</td>`);\n rows.push(`<td>${lifespan}</td>`);\n rows.push('</tr>');\n return rows.join('');\n}\n\nconst cookiePolicyHtml = `\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>ACE Alliance - Cookie Policy</title>\n <link\n rel=\"icon\"\n href=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAGcElEQVRYha2Xe4xUVx3HP7/fPTOzDLO7sw8RlzWlZEtp2dCy0qIVWltKU/UPDZH6ijXWEK2odPcPa2qbhpi2kSa7blSStsFUjNq0lWCMaVMx8rAm22IJMJRHCqFC6BJ22eEx+5p7z88/7sywC7uwgCe5mXsz5/y+j/M753eOcJ2tK5sDyBrME2gBmkBq43/tnMERgXdAjrbn518yXq4RNA3cB/J54HNiMhfEicm4oAYghmHexN4Dew5k01giUybQlc1h0CbI9zC+Imi9mCAIYhoHsnI4KcNjYoDhxWPxsxFY1Z5vHQVwVwSu3Qdid4E8rSb3i6mqKYwBjpWX1V/QZBiYYWIIiifCw8Mm/vS7L/W237FqJno58M5srgmxP4npjsAHDwTeaeAdagGBdwQWoBYgFqCmqGlMqvTE3+U+ipbeE+ngB42Lde6kDnRmcwisAHlBfdBYCYxStp3y7xjTJ51RA0XxgGCkasQFSfkW8NQlBDqzORVYK6ZPqAU6ThUyqd0TN7mQDRZ/CULzvVVeRO68xIGubE6BbjH9oVqA+thaQccpvjLwRDTit2RG/fxVGR3sLc4ELuRAV90+gJ/G4K4EHpRs1wr7qwW/uH36uaxPzwz0xNZhHUfAzJZgsjZWrqXEiTP9WlRP1Bb+pCacs2KaCwvmD/5+cLhCoCubU0G61QJXyWYkVv9/Av/UEzVh2+PVDmDPr875ob4oD6UcMLhfTdqU8dket+sDD6rwS7vrfM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FG5w37bEe+dc+UCQC8/ZtjzX07i/88saU4J8yLXiAhaCC+fn7Sz/7iNFq+mqZ6TuD6do+Gu7vPcuQvBRf62LlIQ2/Y1zvyra9OhnPZSf1g58k5I6ftDSnqnNFTaOACqmclfP0tSa3KBjrc5/2Hbwz7Q38ocHLniDM8XjxeIrxG3rA16vXXj529dVKMK2bVL2fkmhrmJ/9cPy91Z2ZGwhMqQx95TudC8gdCZx4obbMVAhqNGvaoCr99bKD1svGntK4647vg84J8X021PBXlK5gJGJWr11GDb3fkW7dPJfaUi3539iARxSUCz4AsERMVpHwDxMTyhq0HftGRbz071bhXfeooXVJvBR4EbgSGgR6Bt9qvArjc/gfZzPoCTDB+AgAAAABJRU5ErkJggg==\"\n />\n <style>\n @charset \"UTF-8\";\n @import 'https://cdn.voca.teliacompany.com/fonts/TeliaSansV10/TeliaSans.css';\n @import 'https://fonts.googleapis.com/css?family=Reenie+Beanie';\n\n body {\n font-family: TeliaSans, Helvetica, Arial, Lucida Grande, sans-serif;\n }\n\n body > div {\n max-width: 1000px;\n margin: 0 auto;\n padding: 0 40px 40px;\n }\n </style>\n </head>\n\n <body>\n <div>\n <h1>Cookie Policy</h1>\n <p>\n On our websites, we use cookies and other similar technologies. You can choose\n whether you want to allow our websites to store cookies on your computer or not. You\n can change your choices at any time.\n </p>\n\n <h2>Your consent is required</h2>\n <p>\n You choose whether you want to accept cookies on your device or not. Your consent is\n required for the use of cookies, but not for such cookies that are necessary to\n enable the service that you as a user have requested. If you do not accept our use\n of cookies, or if you have previously approved our use and have changed your mind,\n you can return to your cookie settings at any time and change your choices. You do\n this by clicking on the cookie button/link. You may also need to change the settings\n in your browser and manually delete cookies to clear your device of previously\n stored cookies.\n </p>\n\n <h2>What are cookies?</h2>\n <p>\n A cookie is a small text file that is stored on your computer by the web browser\n while browsing a website. When we refer to cookies (“cookies”) in this policy, other\n similar technologies and tools that retrieve and store information in your browser,\n and in some cases forward such information to third parties, in a manner similar to\n cookies. Examples are pixels, local storage, session storage and fingerprinting.\n </p>\n <p>\n The websites will “remember” and “recognize” you. This can be done by placing\n cookies in three different ways;\n </p>\n <ul>\n <li>The session ends, ie until you close the window in your browser.</li>\n <li>\n Time-limited, ie the cookie has a predetermined lifespan. The time may vary\n between different cookies.\n </li>\n <li>\n Until further notice, ie the information remains until you choose to delete it\n yourself. This applies to local storage.\n </li>\n </ul>\n <p>You can always go into your browser and delete already stored cookies yourself.</p>\n\n <h3>Third Party Cookies</h3>\n <p>\n We use third-party cookies on our websites. Third-party cookies are stored by\n someone other than the person responsible for the website, in this case by a company\n other than Telia.\n </p>\n <p>\n Telia uses external platforms to communicate digitally, these include the Google\n Marketing Platform and others. The platforms use both first- and third-party cookies\n as well as similar techniques to advertise and follow up the results of the\n advertising.\n </p>\n <p>\n A third-party cookie can be used by several websites to understand and track how you\n browse between different websites. Telia receives information from these cookies,\n but the information can also be used for other purposes determined by third parties.\n Third-party cookies found on our website are covered by each third-party privacy\n policy. Feel free to read these to understand what other purposes the information\n can be used for. Links are in our Cookie Table.\n </p>\n <p>\n For information about which third-party cookies are used on our websites, see our\n Cookie Table. For more information on how Telia handles personal data in connection\n with transfers to third parties, read our Privacy Policy.\n </p>\n\n <h2>Cookies on our websites</h2>\n <p>\n In order for you to have better control over which cookies are used on the websites,\n and thus be able to more easily decide how cookies should be used when you visit our\n websites, we have identified four different categories of cookies. These categories\n are defined based on the purposes for the use of the cookies.\n </p>\n <p>\n In our Cookie Table, you can also see which category each cookie belongs to, for\n what purposes it is used and for how long it is active.\n </p>\n <p>\n We have identified the following four categories of cookies. All categories contain\n cookies which means that data is shared with third parties.\n </p>\n\n <h3>Necessary</h3>\n <p>\n These cookies are needed for our app to work in a secure and correct way. Necessary\n cookies enable you to use our app and us to provide the service you request.\n Necessary cookies make basic functions of the app possible, for example, identifying\n you when you log into My Telia, detecting repeated failed login attempts,\n identifying where you are in the buying process and remembering the items put into\n your shopping basket.\n </p>\n\n <h3>Functionality</h3>\n <p>\n These cookies let us to enable some useful functionalities to make the user\n experience better, for example, to remember your login details and settings.\n </p>\n\n <h3>Analytics</h3>\n <p>\n These cookies give us information about how you use our app and allow us to improve\n the user experience.\n </p>\n\n <h3>Marketing</h3>\n <p>\n These cookies help us and our partners to display personalized and relevant ads\n based on your browsing behavior on our website and in our app, even when you later\n visit other (third parties’) websites. These cookies are used to evaluate the\n effectiveness of our marketingcampaigns, as well as for targeted marketing and\n profiling, regardless of which device(s) you have used. Information collected for\n this purpose may also be combined with other customer and traffic data we have about\n you, if you have given your consent that we may use your traffic data for marketing\n purpose and have not objected to the use of your customer data for marketing\n purposes.\n </p>\n\n <h2>Manage settings</h2>\n <p>\n We save your cookie consent for 12 months. Then we will ask you again. Please note\n that some cookies have a lifespan that exceeds these 12 months. You may therefore\n need to change the settings in your browser and manually delete all cookies.\n </p>\n <p>\n More information on how to turn off cookies can be found in the instructions for\n your browser.\n </p>\n <ul>\n <li>\n <a\n href=\"https://support.google.com/accounts/answer/61416?co=GENIE.Platform%3DDesktop&amp;hl=en\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Google Chrome</a\n >\n </li>\n <li>\n <a\n href=\"https://privacy.microsoft.com/en-us/windows-10-microsoft-edge-and-privacy\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Microsoft Edge</a\n >\n </li>\n <li>\n <a\n href=\"https://support.mozilla.org/en-US/kb/enable-and-disable-cookies-website-preferences\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Mozilla Firefox</a\n >\n </li>\n <li>\n <a\n href=\"https://support.microsoft.com/en-gb/help/17442/windows-internet-explorer-delete-manage-cookies\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Microsoft Internet Explorer</a\n >\n </li>\n <li>\n <a\n href=\"https://www.opera.com/help/tutorials/security/privacy/\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Opera</a\n >\n </li>\n <li>\n <a\n href=\"https://support.apple.com/guide/safari/manage-cookies-and-website-data-sfri11471/mac\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Apple Safari</a\n >\n </li>\n </ul>\n\n <h3>Do Not Track-signals</h3>\n <p>\n If you have chosen to turn on the Do Not Track function in your browser, we will not\n automatically place cookies for marketing on your device. You make other choices in\n your cookie settings.\n </p>\n\n <h3>If you block cookies</h3>\n <p>\n If you choose not to accept our use of cookies, the functionality and performance of\n our websites may deteriorate as certain functions are dependent on cookies. A\n blocking of cookies can therefore mean that the websites’ services do not work as\n they should.\n </p>\n\n <h3>Your security with us</h3>\n <p>\n If you want to read more about your rights and how we protect your privacy, go to\n our privacy policy for\n <a\n href=\"https://www.telia.se/dam/jcr:df2eeb83-50ce-4383-89fc-0613f7615796/Integritetspolicy-privatkunder.pdf\"\n >private customers</a\n >\n (C2B) or\n <a\n href=\"https://www.telia.se/dam/jcr:95b2b4a5-82ca-436b-90e0-873e0a864118/Telia-integritetspolicy-foretag.pdf\"\n >corporate customers</a\n >\n (B2B). You are always welcome to contact us at\n <a href=\"mailto:dpo-se@teliacompany.com\">dpo-se@teliacompany.com</a> if you have any\n questions.\n </p>\n <p>Our cookie policy may change in the future.</p>\n <p>\n More information about cookies can be found at the Swedish Post and Telecom\n Authority (PTS).\n </p>\n\n <h2>Our Cookie Table</h2>\n <p>\n Below, you will find a list of the cookies and similar technologies that we use on\n this website. These cookies are stored on your device by us.\n </p>\n <table>\n <thead>\n <tr>\n <th>Cookie</th>\n <th>Category</th>\n <th>Purpose</th>\n <th>Lifespan</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>alliance-session-v1</td>\n <td>necessary</td>\n <td>Contains the authenticated user.</td>\n <td>1 day</td>\n </tr>\n {APP_COOKIES}\n </tbody>\n </table>\n <style>\n table {\n width: 100%;\n border: 1px solid rgba(0, 0, 0, 0.15);\n }\n th, td {\n text-align: left;\n padding: 3px;\n }\n </style>\n </div>\n </body>\n</html>\n`;\n","import type { Schema } from 'jsonschema';\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\ntype JsonSchemas = {\n appConfig: Schema;\n appManifest: Schema;\n};\n\nexport function getJsonSchemas(): JsonSchemas {\n const frameworkDistDirPath = resolve(\n process.cwd(),\n 'node_modules',\n '@telia-ace/alliance-framework',\n 'dist',\n );\n const appConfigSchemaPath = resolve(frameworkDistDirPath, 'config.schema.json');\n const appManifestSchemaPath = resolve(frameworkDistDirPath, 'manifest.schema.json');\n const appConfigSchemaFile = readFileSync(appConfigSchemaPath).toString();\n const appManifestSchemaFile = readFileSync(appManifestSchemaPath).toString();\n const appConfig = JSON.parse(appConfigSchemaFile);\n const appManifest = JSON.parse(appManifestSchemaFile);\n\n return {\n appConfig,\n appManifest,\n };\n}\n","import { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { getAppManifests } from '@/get-app-manifests';\nimport type { LooseObject } from '@/types';\n\ntype PkgJson = LooseObject & {\n name: string;\n version: string;\n};\n\nexport type AlliancePortalDistPkgJson = PkgJson & {\n alliance?: {\n apps?: string[];\n };\n};\n\nexport function getPkgJson(): AlliancePortalDistPkgJson {\n const packageJson = resolve(process.cwd(), 'package.json');\n const pkgJsonFile = readFileSync(packageJson).toString();\n return JSON.parse(pkgJsonFile);\n}\n\nexport async function getManifests(pkgJson: AlliancePortalDistPkgJson) {\n if (!pkgJson || !pkgJson.alliance || !pkgJson.alliance.apps) {\n throw new Error('Alliance apps not defined in package.json.');\n }\n\n const manifestArray = await getAppManifests(pkgJson.alliance.apps);\n\n return manifestArray.reduce((acc, curr: LooseObject) => {\n acc[curr.name] = curr;\n\n return acc;\n }, {});\n}\n","import { rmSync, writeFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport type { LooseObject } from './types';\n\nasync function createTempModuleAndImport<T>(moduleString: string, fileName: string): Promise<T> {\n const file = resolve(process.cwd(), `${fileName}.mjs`);\n writeFileSync(file, moduleString);\n const importedModule = await import(`file:///${file}`);\n rmSync(file, { force: true });\n return importedModule;\n}\n\n// Creates a temporary ES module and imports app manifests for all requested apps\n// This reusable utility can access all node modules available in the directory where it is ran\nexport async function getAppManifests(apps: string[]): Promise<LooseObject[]> {\n const moduleStringParts = [];\n const manifestImportVariables = [];\n\n for (const packageName of apps) {\n const manifestImportVariable = `app${apps.indexOf(packageName)}`;\n manifestImportVariables.push(manifestImportVariable);\n moduleStringParts.push(`import ${manifestImportVariable} from '${packageName}/manifest';`);\n }\n\n moduleStringParts.push(`export default [${manifestImportVariables.join(', ')}];`);\n\n const result = await createTempModuleAndImport<{ default: LooseObject[] }>(\n moduleStringParts.join('\\n'),\n 'app-manifests',\n );\n\n return result.default;\n}\n","import { GraphQLError } from 'graphql';\n\nimport { type ErrorCodes, allianceErrors } from './codes';\n\nfunction parseTemplates(message: string, variables: Record<string, string>) {\n return Object.entries(variables).reduce((acc, [key, value]) => {\n return acc.replaceAll(`{{${key}}}`, value);\n }, message);\n}\n\nexport class AllianceGqlException extends GraphQLError {\n public info: string;\n public code: ErrorCodes;\n constructor(code: ErrorCodes, variables: Record<string, string> = {}, extensions?: any) {\n const { message } = allianceErrors[code];\n\n super(parseTemplates(message, variables), {\n extensions,\n });\n\n this.code = code;\n this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${code}`;\n }\n}\n","import { HttpStatus } from '@nestjs/common';\n\nimport { AllianceHeaders } from '@/constants';\n\nexport enum GatewayErrorCodes {\n NoObjectId = 10001,\n NoTargetAppHeader = 10002,\n NoTargetWorkspaceHeader = 10003,\n NoManifestsInCache = 10004,\n NoDevSessionInCache = 10005,\n NoManifest = 10006,\n NoRequestContext = 10007,\n NoUserInRequestContext = 10008,\n NoAppInRequestContext = 10009,\n NoWorkspaceInRequestContext = 10010,\n NoUserPermissionsInRequestContext = 10012,\n WorkspacePermissionDenied = 10013,\n}\n\nexport enum DatabasesErrorCodes {\n NoPublicKey = 11000,\n NoAuthHeader = 11001,\n FailedFileStore = 11002,\n FailedFileRead = 11003,\n NoRecord = 11004,\n UniqueConstrain = 11005,\n}\n\nexport enum PortalErrorCodes {\n NoObjectId = 12000,\n}\n\nexport type ErrorCodes = GatewayErrorCodes | DatabasesErrorCodes | PortalErrorCodes;\n\ntype AllianceErrors = {\n [key in ErrorCodes]: {\n httpCode: HttpStatus;\n message: string;\n };\n};\n\nexport const allianceErrors: AllianceErrors = {\n // gateway\n [GatewayErrorCodes.NoObjectId]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No object id available on authenticated user.',\n },\n [GatewayErrorCodes.NoTargetAppHeader]: {\n httpCode: HttpStatus.BAD_REQUEST,\n message: `Request missing header '${AllianceHeaders.TargetApp}'.`,\n },\n [GatewayErrorCodes.NoTargetWorkspaceHeader]: {\n httpCode: HttpStatus.BAD_REQUEST,\n message: `Request missing header '${AllianceHeaders.TargetWorkspace}'.`,\n },\n [GatewayErrorCodes.NoManifestsInCache]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'App manifests missing in cache.',\n },\n [GatewayErrorCodes.NoDevSessionInCache]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No dev session in memory cache.',\n },\n [GatewayErrorCodes.NoManifest]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: \"Could not find manifest for app '{{appSlug}}'.\",\n },\n [GatewayErrorCodes.NoRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No request context.',\n },\n [GatewayErrorCodes.NoUserInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No user in request context.',\n },\n [GatewayErrorCodes.NoAppInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No app in request context.',\n },\n [GatewayErrorCodes.NoWorkspaceInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No workspace in request context.',\n },\n [GatewayErrorCodes.NoUserPermissionsInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No user permissions in request context.',\n },\n [GatewayErrorCodes.WorkspacePermissionDenied]: {\n httpCode: HttpStatus.FORBIDDEN,\n message: 'User does not have access to the current workspace.',\n },\n\n // databases\n [DatabasesErrorCodes.NoPublicKey]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No public key available to decode JWT.',\n },\n [DatabasesErrorCodes.NoAuthHeader]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No authorization header found.',\n },\n [DatabasesErrorCodes.FailedFileStore]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Error storing file.',\n },\n [DatabasesErrorCodes.FailedFileRead]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Error reading file.',\n },\n [DatabasesErrorCodes.NoRecord]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Missing database record.',\n },\n [DatabasesErrorCodes.UniqueConstrain]: {\n httpCode: HttpStatus.CONFLICT,\n message: 'Field has to be unique.',\n },\n\n // portal\n [PortalErrorCodes.NoObjectId]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No object id found in user claims.',\n },\n};\n","import { HttpException } from '@nestjs/common';\n\nimport { type ErrorCodes, allianceErrors } from './codes';\n\nfunction parseTemplates(message: string, variables: Record<string, string>) {\n return Object.entries(variables).reduce((acc, [key, value]) => {\n return acc.replaceAll(`{{${key}}}`, value);\n }, message);\n}\n\nexport class AllianceException extends HttpException {\n public info: string;\n public code: ErrorCodes;\n constructor(code: ErrorCodes, variables: Record<string, string> = {}) {\n const { message, httpCode } = allianceErrors[code];\n\n super(parseTemplates(message, variables), httpCode);\n\n this.code = code;\n this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${code}`;\n }\n}\n","import { type ArgumentsHost, Catch, type ExceptionFilter } from '@nestjs/common';\nimport type { Response } from 'express';\n\nimport { AllianceException } from './alliance.exception';\n\n@Catch(AllianceException)\nexport class AllianceExceptionFilter implements ExceptionFilter {\n catch(exception: AllianceException, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<Response>();\n const status = exception.getStatus();\n\n response.status &&\n response.status(status).json({\n httpCode: status,\n code: exception.code,\n info: exception.info,\n message: exception.message,\n });\n }\n}\n","import { type DynamicModule, Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { LoggerModule as PinoModule } from 'nestjs-pino';\n\nimport { SharedConfigKeys } from '@/constants';\n\nimport { LoggerService } from './logging.service';\n\ntype ModuleSettings = {\n logLevel?: string;\n redact?: boolean;\n};\n\n@Module({\n providers: [LoggerService],\n exports: [LoggerService],\n})\nexport class LoggerModule {\n static forRoot({ logLevel, redact = true }: ModuleSettings = {}): DynamicModule {\n return {\n module: LoggerModule,\n controllers: [],\n imports: [\n PinoModule.forRootAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => ({\n pinoHttp: {\n level:\n logLevel ||\n configService.get<string>(SharedConfigKeys.ServiceLogLevel) ||\n 'silent',\n redact: redact\n ? [\n 'authorization',\n 'headers.authorization',\n 'req.headers.authorization',\n 'res.headers.authorization',\n ]\n : [],\n },\n }),\n }),\n ],\n global: true,\n providers: [LoggerService],\n exports: [],\n };\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport { PinoLogger } from 'nestjs-pino';\nimport { InjectPinoLogger } from 'nestjs-pino';\n\n@Injectable()\nexport class LoggerService {\n constructor(@InjectPinoLogger() private readonly logger: PinoLogger) {}\n log: PinoLogger['info'] = (...args) => this.logger.info(...args);\n trace: PinoLogger['trace'] = (...args) => this.logger.trace(...args);\n debug: PinoLogger['debug'] = (...args) => this.logger.debug(...args);\n info: PinoLogger['info'] = (...args) => this.logger.info(...args);\n warn: PinoLogger['warn'] = (...args) => this.logger.warn(...args);\n error: PinoLogger['error'] = (...args) => this.logger.error(...args);\n fatal: PinoLogger['fatal'] = (...args) => this.logger.fatal(...args);\n}\n","import _slugify from 'slugify';\n\nexport function slugify(name: string) {\n return _slugify(name, { strict: true, replacement: '-', lower: true });\n}\n"]}
1
+ {"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/connect-redis@7.1.0_express-session@1.17.3/node_modules/connect-redis/dist/esm/index.js","../src/auth/auth.middleware.ts","../src/constants/config.ts","../src/constants/headers.ts","../src/auth/tokens.ts","../src/distribution/create-public-files.ts","../src/distribution/cookie-policy.ts","../src/distribution/json-schemas.ts","../src/distribution/pkg-json.ts","../src/get-app-manifests.ts","../src/exceptions/alliance-gql.exception.ts","../src/exceptions/codes.ts","../src/exceptions/alliance.exception.ts","../src/exceptions/exception.filter.ts","../src/logging/logging.module.ts","../src/logging/logging.service.ts","../src/slugify.ts"],"names":["LoggerErrorInterceptor","Store","noop","_err","_data","RedisStore","constructor","opts","prefix","scanCount","serializer","JSON","ttl","disableTTL","disableTouch","client","normalizeClient","isRedis","get","key","set","val","EX","del","expire","mget","keys","mGet","scanIterator","match","count","MATCH","COUNT","c","xs","scan","sid","cb","data","parse","err","sess","_getTTL","stringify","destroy","touch","clear","_getAllKeys","length","ids","len","map","k","substring","all","results","reduce","acc","raw","idx","id","push","cookie","expires","ms","Number","Date","now","Math","ceil","pattern","auth","createClient","SharedConfigKeys","AllianceHeaders","authMiddleware","configService","baseURL","clientSecret","clientID","authRequired","authorizationParams","afterCallback","issuerBaseURL","sessionCookiePath","store","redisHostUrl","RedisHost","redisClient","url","getOrThrow","password","RedisPassword","connect","catch","console","error","secret","AuthCookieSecret","session","name","AuthCookieName","path","routes","callback","sign","createBearerToken","privateKey","aud","sub","user","workspace","jwt","iss","type","email","permissions","slug","expiresIn","algorithm","getPrivateKey","JwtPrivateKey","createSystemUserToken","validate","existsSync","mkdirSync","writeFileSync","resolve","generateCookiePolicyHtml","appManifests","cookiePolicyTableRows","appName","manifest","storage","value","Object","entries","tableRow","createCookiePolicyTableRow","cookiePolicyHtml","replace","join","claimEntry","rows","category","purpose","lifespan","readFileSync","getJsonSchemas","frameworkDistDirPath","process","cwd","appConfigSchemaPath","appManifestSchemaPath","appConfigSchemaFile","toString","appManifestSchemaFile","appConfig","appManifest","rmSync","createTempModuleAndImport","moduleString","fileName","file","importedModule","force","getAppManifests","apps","moduleStringParts","manifestImportVariables","packageName","manifestImportVariable","indexOf","result","default","getPkgJson","packageJson","pkgJsonFile","getManifests","pkgJson","alliance","Error","manifestArray","curr","PUBLIC_DIR_NAME","MANIFESTS_FILE_NAME","COOKIE_POLICY_FILE_NAME","APP_CONFIG_SCHEMA_FILE_NAME","APP_MANIFEST_SCHEMA_FILE_NAME","createPublicDistributionFiles","manifests","schemas","validationResult","errors","e","publicDirPath","manifestsFilePath","cookiePolicyFilePath","appConfigSchemaFilePath","appManifestSchemaFilePath","GraphQLError","HttpStatus","GatewayErrorCodes","DatabasesErrorCodes","PortalErrorCodes","allianceErrors","httpCode","UNAUTHORIZED","message","BAD_REQUEST","TargetApp","TargetWorkspace","INTERNAL_SERVER_ERROR","FORBIDDEN","CONFLICT","parseTemplates","variables","replaceAll","AllianceGqlException","info","code","extensions","HttpException","AllianceException","Catch","AllianceExceptionFilter","exception","host","ctx","switchToHttp","response","getResponse","status","getStatus","json","Module","ConfigModule","ConfigService","LoggerModule","PinoModule","Injectable","PinoLogger","InjectPinoLogger","LoggerService","logger","log","args","trace","debug","warn","fatal","forRoot","logLevel","redact","module","controllers","imports","forRootAsync","inject","useFactory","pinoHttp","level","ServiceLogLevel","global","providers","exports","_slugify","slugify","strict","replacement","lower"],"mappings":";;;;AAAA,SAASA,8BAA8B;;;ACAvC,SAASC,aAAa;AACtB,IAAMC,OAAO,wBAACC,MAAMC,UAAAA;AAAY,GAAnB;AACb,IAAMC,aAAN,MAAMA,oBAAmBJ,MAAAA;EAFzB,OAEyBA;;;EACrBK,YAAYC,MAAM;AACd,UAAK;AACL,SAAKC,SAASD,KAAKC,UAAU,OAAO,UAAUD,KAAKC;AACnD,SAAKC,YAAYF,KAAKE,aAAa;AACnC,SAAKC,aAAaH,KAAKG,cAAcC;AACrC,SAAKC,MAAML,KAAKK,OAAO;AACvB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J,CAAA;;MAEJU,QAAQ;MACRC,WAAW;QAACrB;;MACZsB,SAAS,CAAA;IACb;EACJ;AACJ;AAhCa3B,eAAAA,cAAAA;EAJZH,OAAO;IACJ6B,WAAW;MAACrB;;IACZsB,SAAS;MAACtB;;EACd,CAAA;GACaL,YAAAA;;;AEjBb,OAAO4B,cAAc;AAEd,SAASC,QAAQvK,MAAY;AAChC,SAAOsK,SAAStK,MAAM;IAAEwK,QAAQ;IAAMC,aAAa;IAAKC,OAAO;EAAK,CAAA;AACxE;AAFgBH","sourcesContent":["export { LoggerErrorInterceptor } from 'nestjs-pino';\nexport { authMiddleware, createBearerToken, createSystemUserToken, getPrivateKey } from './auth';\nexport { AllianceHeaders, SharedConfigKeys } from './constants';\nexport { createPublicDistributionFiles } from './distribution';\nexport {\n AllianceException,\n AllianceExceptionFilter,\n AllianceGqlException,\n DatabasesErrorCodes,\n GatewayErrorCodes,\n PortalErrorCodes,\n} from './exceptions';\nexport { getAppManifests } from './get-app-manifests';\nexport { LoggerModule, LoggerService } from './logging';\nexport { slugify } from './slugify';\n","import { Store } from \"express-session\";\nconst noop = (_err, _data) => { };\nclass RedisStore extends Store {\n constructor(opts) {\n super();\n this.prefix = opts.prefix == null ? \"sess:\" : opts.prefix;\n this.scanCount = opts.scanCount || 100;\n this.serializer = opts.serializer || JSON;\n this.ttl = opts.ttl || 86400; // One day in seconds.\n this.disableTTL = opts.disableTTL || false;\n this.disableTouch = opts.disableTouch || false;\n this.client = this.normalizeClient(opts.client);\n }\n // Create a redis and ioredis compatible client\n normalizeClient(client) {\n let isRedis = \"scanIterator\" in client;\n return {\n get: (key) => client.get(key),\n set: (key, val, ttl) => {\n if (ttl) {\n return isRedis\n ? client.set(key, val, { EX: ttl })\n : client.set(key, val, \"EX\", ttl);\n }\n return client.set(key, val);\n },\n del: (key) => client.del(key),\n expire: (key, ttl) => client.expire(key, ttl),\n mget: (keys) => (isRedis ? client.mGet(keys) : client.mget(keys)),\n scanIterator: (match, count) => {\n if (isRedis)\n return client.scanIterator({ MATCH: match, COUNT: count });\n // ioredis impl.\n return (async function* () {\n let [c, xs] = await client.scan(\"0\", \"MATCH\", match, \"COUNT\", count);\n for (let key of xs)\n yield key;\n while (c !== \"0\") {\n ;\n [c, xs] = await client.scan(c, \"MATCH\", match, \"COUNT\", count);\n for (let key of xs)\n yield key;\n }\n })();\n },\n };\n }\n async get(sid, cb = noop) {\n let key = this.prefix + sid;\n try {\n let data = await this.client.get(key);\n if (!data)\n return cb();\n return cb(null, await this.serializer.parse(data));\n }\n catch (err) {\n return cb(err);\n }\n }\n async set(sid, sess, cb = noop) {\n let key = this.prefix + sid;\n let ttl = this._getTTL(sess);\n try {\n let val = this.serializer.stringify(sess);\n if (ttl > 0) {\n if (this.disableTTL)\n await this.client.set(key, val);\n else\n await this.client.set(key, val, ttl);\n return cb();\n }\n else {\n return this.destroy(sid, cb);\n }\n }\n catch (err) {\n return cb(err);\n }\n }\n async touch(sid, sess, cb = noop) {\n let key = this.prefix + sid;\n if (this.disableTouch || this.disableTTL)\n return cb();\n try {\n await this.client.expire(key, this._getTTL(sess));\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async destroy(sid, cb = noop) {\n let key = this.prefix + sid;\n try {\n await this.client.del([key]);\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async clear(cb = noop) {\n try {\n let keys = await this._getAllKeys();\n if (!keys.length)\n return cb();\n await this.client.del(keys);\n return cb();\n }\n catch (err) {\n return cb(err);\n }\n }\n async length(cb = noop) {\n try {\n let keys = await this._getAllKeys();\n return cb(null, keys.length);\n }\n catch (err) {\n return cb(err);\n }\n }\n async ids(cb = noop) {\n let len = this.prefix.length;\n try {\n let keys = await this._getAllKeys();\n return cb(null, keys.map((k) => k.substring(len)));\n }\n catch (err) {\n return cb(err);\n }\n }\n async all(cb = noop) {\n let len = this.prefix.length;\n try {\n let keys = await this._getAllKeys();\n if (keys.length === 0)\n return cb(null, []);\n let data = await this.client.mget(keys);\n let results = data.reduce((acc, raw, idx) => {\n if (!raw)\n return acc;\n let sess = this.serializer.parse(raw);\n sess.id = keys[idx].substring(len);\n acc.push(sess);\n return acc;\n }, []);\n return cb(null, results);\n }\n catch (err) {\n return cb(err);\n }\n }\n _getTTL(sess) {\n if (typeof this.ttl === \"function\") {\n return this.ttl(sess);\n }\n let ttl;\n if (sess && sess.cookie && sess.cookie.expires) {\n let ms = Number(new Date(sess.cookie.expires)) - Date.now();\n ttl = Math.ceil(ms / 1000);\n }\n else {\n ttl = this.ttl;\n }\n return ttl;\n }\n async _getAllKeys() {\n let pattern = this.prefix + \"*\";\n let keys = [];\n for await (let key of this.client.scanIterator(pattern, this.scanCount)) {\n keys.push(key);\n }\n return keys;\n }\n}\nexport default RedisStore;\n","import type { ConfigService } from '@nestjs/config';\nimport RedisStore from 'connect-redis';\nimport type { RequestHandler } from 'express';\nimport {\n type ConfigParams,\n type CookieConfigParams,\n type SessionStore,\n auth,\n} from 'express-openid-connect';\nimport { createClient } from 'redis';\n\nimport { SharedConfigKeys } from '@/constants';\n\ntype Settings = {\n baseURL?: ConfigParams['baseURL'];\n clientID?: ConfigParams['clientID'];\n clientSecret?: ConfigParams['clientSecret'];\n authRequired?: ConfigParams['authRequired'];\n authorizationParams?: ConfigParams['authorizationParams'];\n afterCallback?: ConfigParams['afterCallback'];\n issuerBaseURL?: ConfigParams['issuerBaseURL'];\n sessionCookiePath?: CookieConfigParams['path'];\n};\n\nexport function authMiddleware(\n configService: ConfigService,\n {\n baseURL = 'https://127.0.0.1',\n clientSecret,\n clientID = ' ',\n authRequired = true,\n authorizationParams = {},\n afterCallback,\n issuerBaseURL = 'https://127.0.0.1',\n sessionCookiePath,\n }: Settings = {},\n): RequestHandler {\n let store: SessionStore | RedisStore | undefined;\n const redisHostUrl = configService.get<string>(SharedConfigKeys.RedisHost);\n if (redisHostUrl) {\n const redisClient = createClient({\n url: configService.getOrThrow<string>(SharedConfigKeys.RedisHost),\n password: configService.get<string>(SharedConfigKeys.RedisPassword),\n });\n\n redisClient.connect().catch(console.error);\n\n store = new RedisStore({\n client: redisClient,\n });\n }\n\n return auth({\n baseURL,\n clientSecret,\n clientID,\n authRequired,\n authorizationParams,\n afterCallback,\n issuerBaseURL,\n secret: configService.getOrThrow<string>(SharedConfigKeys.AuthCookieSecret),\n session: {\n name: configService.getOrThrow<string>(SharedConfigKeys.AuthCookieName),\n // @ts-ignore\n store,\n cookie: {\n path: sessionCookiePath,\n },\n },\n routes: {\n callback: '/signin-oidc',\n },\n });\n}\n","export enum SharedConfigKeys {\n AuthCookieName = 'AUTH_COOKIE_NAME',\n AuthCookieSecret = 'AUTH_COOKIE_SECRET',\n DbEndpoint = 'DB_ENDPOINT',\n JwtPrivateKey = 'JWT_PRIVATE_KEY',\n ServiceLogLevel = 'SERVICE_LOG_LEVEL',\n ServicePort = 'SERVICE_PORT',\n RedisHost = 'REDIS_HOST',\n RedisPassword = 'REDIS_PASSWORD',\n}\n","export enum AllianceHeaders {\n TargetUrl = 'alliance-target-url',\n TargetApp = 'alliance-target-app',\n TargetWorkspace = 'alliance-target-workspace',\n}\n","import type { ConfigService } from '@nestjs/config';\nimport { sign } from 'jsonwebtoken';\n\nimport { SharedConfigKeys } from '@/constants';\n\ntype BearerTokenSettings = {\n privateKey: string;\n aud: string;\n sub: string;\n name: string;\n user: {\n type: string;\n permissions: string[];\n email: string;\n };\n workspace: { name: string; slug: string };\n};\n\nexport function createBearerToken({\n privateKey,\n aud,\n sub,\n name,\n user,\n workspace,\n}: BearerTokenSettings) {\n const jwt = sign(\n {\n iss: 'Alliance',\n aud,\n sub,\n name,\n 'https://alliance.teliacompany.net/user_type': user.type,\n 'https://alliance.teliacompany.net/user_email': user.email,\n 'https://alliance.teliacompany.net/user_privileges': user.permissions,\n 'https://alliance.teliacompany.net/workspace': workspace.slug,\n 'https://alliance.teliacompany.net/workspace_name': workspace.name,\n 'https://alliance.teliacompany.net/tenant': workspace.slug,\n 'https://alliance.teliacompany.net/tenant_name': workspace.name,\n },\n privateKey,\n {\n expiresIn: '1h',\n algorithm: 'RS256',\n },\n );\n\n return `Bearer ${jwt}`;\n}\n\nexport function getPrivateKey(configService: ConfigService) {\n const privateKey = configService.getOrThrow<string>(SharedConfigKeys.JwtPrivateKey);\n\n return '-----BEGIN RSA PRIVATE KEY-----\\n' + privateKey + '\\n-----END RSA PRIVATE KEY-----';\n}\n\nexport function createSystemUserToken(configService: ConfigService) {\n return createBearerToken({\n aud: 'system',\n sub: 'system',\n name: 'system',\n workspace: {\n slug: 'system',\n name: 'system',\n },\n user: {\n type: 'system',\n permissions: [],\n email: 'system',\n },\n privateKey: getPrivateKey(configService),\n });\n}\n","import { validate } from 'jsonschema';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { generateCookiePolicyHtml } from './cookie-policy';\nimport { getJsonSchemas } from './json-schemas';\nimport { getManifests, getPkgJson } from './pkg-json';\n\nconst PUBLIC_DIR_NAME = 'public';\nconst MANIFESTS_FILE_NAME = 'manifests.json';\nconst COOKIE_POLICY_FILE_NAME = 'cookie-policy.html';\nconst APP_CONFIG_SCHEMA_FILE_NAME = 'config.schema.json';\nconst APP_MANIFEST_SCHEMA_FILE_NAME = 'manifest.schema.json';\n\nexport async function createPublicDistributionFiles() {\n const pkgJson = getPkgJson();\n const manifests = await getManifests(pkgJson);\n const schemas = getJsonSchemas();\n\n // Validate all app schemas\n for (const appName in manifests) {\n const manifest = manifests[appName];\n\n const validationResult = validate(manifest, schemas.appManifest);\n\n if (validationResult.errors.length) {\n const errors = validationResult.errors.map((e) => JSON.stringify(e, null, 2));\n throw new Error(\n `Validation of app manifest for app '${appName}' failed with the following errors:\\n${errors.join(\n '\\n',\n )}`,\n );\n }\n }\n\n // Make sure public dir exists\n const publicDirPath = resolve(process.cwd(), PUBLIC_DIR_NAME);\n if (!existsSync(publicDirPath)) {\n mkdirSync(publicDirPath);\n }\n\n // Create manifests file\n const manifestsFilePath = resolve(publicDirPath, MANIFESTS_FILE_NAME);\n writeFileSync(manifestsFilePath, JSON.stringify(manifests));\n\n // Create cookie policy document\n const cookiePolicyFilePath = resolve(publicDirPath, COOKIE_POLICY_FILE_NAME);\n writeFileSync(cookiePolicyFilePath, generateCookiePolicyHtml(manifests));\n\n // Create JSON schema files\n const appConfigSchemaFilePath = resolve(publicDirPath, APP_CONFIG_SCHEMA_FILE_NAME);\n const appManifestSchemaFilePath = resolve(publicDirPath, APP_MANIFEST_SCHEMA_FILE_NAME);\n writeFileSync(appConfigSchemaFilePath, JSON.stringify(schemas.appConfig));\n writeFileSync(appManifestSchemaFilePath, JSON.stringify(schemas.appManifest));\n}\n","import type { LooseObject } from '@/types';\n\nexport function generateCookiePolicyHtml(appManifests: LooseObject) {\n const cookiePolicyTableRows: string[] = [];\n\n for (const appName in appManifests) {\n const manifest = appManifests[appName];\n if (!manifest.storage) {\n continue;\n }\n\n for (const [key, value] of Object.entries(manifest.storage)) {\n const tableRow = createCookiePolicyTableRow(key, value as LooseObject);\n cookiePolicyTableRows.push(tableRow);\n }\n }\n\n return cookiePolicyHtml.replace('{APP_COOKIES}', cookiePolicyTableRows.join(''));\n}\n\nfunction createCookiePolicyTableRow(key: string, claimEntry: LooseObject) {\n const rows = ['<tr>'];\n const { category, purpose, lifespan } = claimEntry;\n rows.push(`<td>${key}</td>`);\n rows.push(`<td>${category}</td>`);\n rows.push(`<td>${purpose}</td>`);\n rows.push(`<td>${lifespan}</td>`);\n rows.push('</tr>');\n return rows.join('');\n}\n\nconst cookiePolicyHtml = `\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>ACE Alliance - Cookie Policy</title>\n <link\n rel=\"icon\"\n href=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAGcElEQVRYha2Xe4xUVx3HP7/fPTOzDLO7sw8RlzWlZEtp2dCy0qIVWltKU/U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\"\n />\n <style>\n @charset \"UTF-8\";\n @import 'https://cdn.voca.teliacompany.com/fonts/TeliaSansV10/TeliaSans.css';\n @import 'https://fonts.googleapis.com/css?family=Reenie+Beanie';\n\n body {\n font-family: TeliaSans, Helvetica, Arial, Lucida Grande, sans-serif;\n }\n\n body > div {\n max-width: 1000px;\n margin: 0 auto;\n padding: 0 40px 40px;\n }\n </style>\n </head>\n\n <body>\n <div>\n <h1>Cookie Policy</h1>\n <p>\n On our websites, we use cookies and other similar technologies. You can choose\n whether you want to allow our websites to store cookies on your computer or not. You\n can change your choices at any time.\n </p>\n\n <h2>Your consent is required</h2>\n <p>\n You choose whether you want to accept cookies on your device or not. Your consent is\n required for the use of cookies, but not for such cookies that are necessary to\n enable the service that you as a user have requested. If you do not accept our use\n of cookies, or if you have previously approved our use and have changed your mind,\n you can return to your cookie settings at any time and change your choices. You do\n this by clicking on the cookie button/link. You may also need to change the settings\n in your browser and manually delete cookies to clear your device of previously\n stored cookies.\n </p>\n\n <h2>What are cookies?</h2>\n <p>\n A cookie is a small text file that is stored on your computer by the web browser\n while browsing a website. When we refer to cookies (“cookies”) in this policy, other\n similar technologies and tools that retrieve and store information in your browser,\n and in some cases forward such information to third parties, in a manner similar to\n cookies. Examples are pixels, local storage, session storage and fingerprinting.\n </p>\n <p>\n The websites will “remember” and “recognize” you. This can be done by placing\n cookies in three different ways;\n </p>\n <ul>\n <li>The session ends, ie until you close the window in your browser.</li>\n <li>\n Time-limited, ie the cookie has a predetermined lifespan. The time may vary\n between different cookies.\n </li>\n <li>\n Until further notice, ie the information remains until you choose to delete it\n yourself. This applies to local storage.\n </li>\n </ul>\n <p>You can always go into your browser and delete already stored cookies yourself.</p>\n\n <h3>Third Party Cookies</h3>\n <p>\n We use third-party cookies on our websites. Third-party cookies are stored by\n someone other than the person responsible for the website, in this case by a company\n other than Telia.\n </p>\n <p>\n Telia uses external platforms to communicate digitally, these include the Google\n Marketing Platform and others. The platforms use both first- and third-party cookies\n as well as similar techniques to advertise and follow up the results of the\n advertising.\n </p>\n <p>\n A third-party cookie can be used by several websites to understand and track how you\n browse between different websites. Telia receives information from these cookies,\n but the information can also be used for other purposes determined by third parties.\n Third-party cookies found on our website are covered by each third-party privacy\n policy. Feel free to read these to understand what other purposes the information\n can be used for. Links are in our Cookie Table.\n </p>\n <p>\n For information about which third-party cookies are used on our websites, see our\n Cookie Table. For more information on how Telia handles personal data in connection\n with transfers to third parties, read our Privacy Policy.\n </p>\n\n <h2>Cookies on our websites</h2>\n <p>\n In order for you to have better control over which cookies are used on the websites,\n and thus be able to more easily decide how cookies should be used when you visit our\n websites, we have identified four different categories of cookies. These categories\n are defined based on the purposes for the use of the cookies.\n </p>\n <p>\n In our Cookie Table, you can also see which category each cookie belongs to, for\n what purposes it is used and for how long it is active.\n </p>\n <p>\n We have identified the following four categories of cookies. All categories contain\n cookies which means that data is shared with third parties.\n </p>\n\n <h3>Necessary</h3>\n <p>\n These cookies are needed for our app to work in a secure and correct way. Necessary\n cookies enable you to use our app and us to provide the service you request.\n Necessary cookies make basic functions of the app possible, for example, identifying\n you when you log into My Telia, detecting repeated failed login attempts,\n identifying where you are in the buying process and remembering the items put into\n your shopping basket.\n </p>\n\n <h3>Functionality</h3>\n <p>\n These cookies let us to enable some useful functionalities to make the user\n experience better, for example, to remember your login details and settings.\n </p>\n\n <h3>Analytics</h3>\n <p>\n These cookies give us information about how you use our app and allow us to improve\n the user experience.\n </p>\n\n <h3>Marketing</h3>\n <p>\n These cookies help us and our partners to display personalized and relevant ads\n based on your browsing behavior on our website and in our app, even when you later\n visit other (third parties’) websites. These cookies are used to evaluate the\n effectiveness of our marketingcampaigns, as well as for targeted marketing and\n profiling, regardless of which device(s) you have used. Information collected for\n this purpose may also be combined with other customer and traffic data we have about\n you, if you have given your consent that we may use your traffic data for marketing\n purpose and have not objected to the use of your customer data for marketing\n purposes.\n </p>\n\n <h2>Manage settings</h2>\n <p>\n We save your cookie consent for 12 months. Then we will ask you again. Please note\n that some cookies have a lifespan that exceeds these 12 months. You may therefore\n need to change the settings in your browser and manually delete all cookies.\n </p>\n <p>\n More information on how to turn off cookies can be found in the instructions for\n your browser.\n </p>\n <ul>\n <li>\n <a\n href=\"https://support.google.com/accounts/answer/61416?co=GENIE.Platform%3DDesktop&amp;hl=en\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Google Chrome</a\n >\n </li>\n <li>\n <a\n href=\"https://privacy.microsoft.com/en-us/windows-10-microsoft-edge-and-privacy\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Microsoft Edge</a\n >\n </li>\n <li>\n <a\n href=\"https://support.mozilla.org/en-US/kb/enable-and-disable-cookies-website-preferences\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Mozilla Firefox</a\n >\n </li>\n <li>\n <a\n href=\"https://support.microsoft.com/en-gb/help/17442/windows-internet-explorer-delete-manage-cookies\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Microsoft Internet Explorer</a\n >\n </li>\n <li>\n <a\n href=\"https://www.opera.com/help/tutorials/security/privacy/\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Opera</a\n >\n </li>\n <li>\n <a\n href=\"https://support.apple.com/guide/safari/manage-cookies-and-website-data-sfri11471/mac\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >Apple Safari</a\n >\n </li>\n </ul>\n\n <h3>Do Not Track-signals</h3>\n <p>\n If you have chosen to turn on the Do Not Track function in your browser, we will not\n automatically place cookies for marketing on your device. You make other choices in\n your cookie settings.\n </p>\n\n <h3>If you block cookies</h3>\n <p>\n If you choose not to accept our use of cookies, the functionality and performance of\n our websites may deteriorate as certain functions are dependent on cookies. A\n blocking of cookies can therefore mean that the websites’ services do not work as\n they should.\n </p>\n\n <h3>Your security with us</h3>\n <p>\n If you want to read more about your rights and how we protect your privacy, go to\n our privacy policy for\n <a\n href=\"https://www.telia.se/dam/jcr:df2eeb83-50ce-4383-89fc-0613f7615796/Integritetspolicy-privatkunder.pdf\"\n >private customers</a\n >\n (C2B) or\n <a\n href=\"https://www.telia.se/dam/jcr:95b2b4a5-82ca-436b-90e0-873e0a864118/Telia-integritetspolicy-foretag.pdf\"\n >corporate customers</a\n >\n (B2B). You are always welcome to contact us at\n <a href=\"mailto:dpo-se@teliacompany.com\">dpo-se@teliacompany.com</a> if you have any\n questions.\n </p>\n <p>Our cookie policy may change in the future.</p>\n <p>\n More information about cookies can be found at the Swedish Post and Telecom\n Authority (PTS).\n </p>\n\n <h2>Our Cookie Table</h2>\n <p>\n Below, you will find a list of the cookies and similar technologies that we use on\n this website. These cookies are stored on your device by us.\n </p>\n <table>\n <thead>\n <tr>\n <th>Cookie</th>\n <th>Category</th>\n <th>Purpose</th>\n <th>Lifespan</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>alliance-session-v1</td>\n <td>necessary</td>\n <td>Contains the authenticated user.</td>\n <td>1 day</td>\n </tr>\n {APP_COOKIES}\n </tbody>\n </table>\n <style>\n table {\n width: 100%;\n border: 1px solid rgba(0, 0, 0, 0.15);\n }\n th, td {\n text-align: left;\n padding: 3px;\n }\n </style>\n </div>\n </body>\n</html>\n`;\n","import type { Schema } from 'jsonschema';\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\ntype JsonSchemas = {\n appConfig: Schema;\n appManifest: Schema;\n};\n\nexport function getJsonSchemas(): JsonSchemas {\n const frameworkDistDirPath = resolve(\n process.cwd(),\n 'node_modules',\n '@telia-ace/alliance-framework',\n 'dist',\n );\n const appConfigSchemaPath = resolve(frameworkDistDirPath, 'config.schema.json');\n const appManifestSchemaPath = resolve(frameworkDistDirPath, 'manifest.schema.json');\n const appConfigSchemaFile = readFileSync(appConfigSchemaPath).toString();\n const appManifestSchemaFile = readFileSync(appManifestSchemaPath).toString();\n const appConfig = JSON.parse(appConfigSchemaFile);\n const appManifest = JSON.parse(appManifestSchemaFile);\n\n return {\n appConfig,\n appManifest,\n };\n}\n","import { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport { getAppManifests } from '@/get-app-manifests';\nimport type { LooseObject } from '@/types';\n\ntype PkgJson = LooseObject & {\n name: string;\n version: string;\n};\n\nexport type AlliancePortalDistPkgJson = PkgJson & {\n alliance?: {\n apps?: string[];\n };\n};\n\nexport function getPkgJson(): AlliancePortalDistPkgJson {\n const packageJson = resolve(process.cwd(), 'package.json');\n const pkgJsonFile = readFileSync(packageJson).toString();\n return JSON.parse(pkgJsonFile);\n}\n\nexport async function getManifests(pkgJson: AlliancePortalDistPkgJson) {\n if (!pkgJson || !pkgJson.alliance || !pkgJson.alliance.apps) {\n throw new Error('Alliance apps not defined in package.json.');\n }\n\n const manifestArray = await getAppManifests(pkgJson.alliance.apps);\n\n return manifestArray.reduce((acc, curr: LooseObject) => {\n acc[curr.name] = curr;\n\n return acc;\n }, {});\n}\n","import { rmSync, writeFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport type { LooseObject } from './types';\n\nasync function createTempModuleAndImport<T>(moduleString: string, fileName: string): Promise<T> {\n const file = resolve(process.cwd(), `${fileName}.mjs`);\n writeFileSync(file, moduleString);\n const importedModule = await import(`file:///${file}`);\n rmSync(file, { force: true });\n return importedModule;\n}\n\n// Creates a temporary ES module and imports app manifests for all requested apps\n// This reusable utility can access all node modules available in the directory where it is ran\nexport async function getAppManifests(apps: string[]): Promise<LooseObject[]> {\n const moduleStringParts = [];\n const manifestImportVariables = [];\n\n for (const packageName of apps) {\n const manifestImportVariable = `app${apps.indexOf(packageName)}`;\n manifestImportVariables.push(manifestImportVariable);\n moduleStringParts.push(`import ${manifestImportVariable} from '${packageName}/manifest';`);\n }\n\n moduleStringParts.push(`export default [${manifestImportVariables.join(', ')}];`);\n\n const result = await createTempModuleAndImport<{ default: LooseObject[] }>(\n moduleStringParts.join('\\n'),\n 'app-manifests',\n );\n\n return result.default;\n}\n","import { GraphQLError } from 'graphql';\n\nimport { type ErrorCodes, allianceErrors } from './codes';\n\nfunction parseTemplates(message: string, variables: Record<string, string>) {\n return Object.entries(variables).reduce((acc, [key, value]) => {\n return acc.replaceAll(`{{${key}}}`, value);\n }, message);\n}\n\nexport class AllianceGqlException extends GraphQLError {\n public info: string;\n public code: ErrorCodes;\n constructor(code: ErrorCodes, variables: Record<string, string> = {}, extensions?: any) {\n const { message } = allianceErrors[code];\n\n super(parseTemplates(message, variables), {\n extensions,\n });\n\n this.code = code;\n this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${code}`;\n }\n}\n","import { HttpStatus } from '@nestjs/common';\n\nimport { AllianceHeaders } from '@/constants';\n\nexport enum GatewayErrorCodes {\n NoObjectId = 10001,\n NoTargetAppHeader = 10002,\n NoTargetWorkspaceHeader = 10003,\n NoManifestsInCache = 10004,\n NoDevSessionInCache = 10005,\n NoManifest = 10006,\n NoRequestContext = 10007,\n NoUserInRequestContext = 10008,\n NoAppInRequestContext = 10009,\n NoWorkspaceInRequestContext = 10010,\n NoUserPermissionsInRequestContext = 10012,\n WorkspacePermissionDenied = 10013,\n}\n\nexport enum DatabasesErrorCodes {\n NoPublicKey = 11000,\n NoAuthHeader = 11001,\n FailedFileStore = 11002,\n FailedFileRead = 11003,\n NoRecord = 11004,\n UniqueConstrain = 11005,\n}\n\nexport enum PortalErrorCodes {\n NoObjectId = 12000,\n}\n\nexport type ErrorCodes = GatewayErrorCodes | DatabasesErrorCodes | PortalErrorCodes;\n\ntype AllianceErrors = {\n [key in ErrorCodes]: {\n httpCode: HttpStatus;\n message: string;\n };\n};\n\nexport const allianceErrors: AllianceErrors = {\n // gateway\n [GatewayErrorCodes.NoObjectId]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No object id available on authenticated user.',\n },\n [GatewayErrorCodes.NoTargetAppHeader]: {\n httpCode: HttpStatus.BAD_REQUEST,\n message: `Request missing header '${AllianceHeaders.TargetApp}'.`,\n },\n [GatewayErrorCodes.NoTargetWorkspaceHeader]: {\n httpCode: HttpStatus.BAD_REQUEST,\n message: `Request missing header '${AllianceHeaders.TargetWorkspace}'.`,\n },\n [GatewayErrorCodes.NoManifestsInCache]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'App manifests missing in cache.',\n },\n [GatewayErrorCodes.NoDevSessionInCache]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No dev session in memory cache.',\n },\n [GatewayErrorCodes.NoManifest]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: \"Could not find manifest for app '{{appSlug}}'.\",\n },\n [GatewayErrorCodes.NoRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No request context.',\n },\n [GatewayErrorCodes.NoUserInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No user in request context.',\n },\n [GatewayErrorCodes.NoAppInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No app in request context.',\n },\n [GatewayErrorCodes.NoWorkspaceInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No workspace in request context.',\n },\n [GatewayErrorCodes.NoUserPermissionsInRequestContext]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'No user permissions in request context.',\n },\n [GatewayErrorCodes.WorkspacePermissionDenied]: {\n httpCode: HttpStatus.FORBIDDEN,\n message: 'User does not have access to the current workspace.',\n },\n\n // databases\n [DatabasesErrorCodes.NoPublicKey]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No public key available to decode JWT.',\n },\n [DatabasesErrorCodes.NoAuthHeader]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No authorization header found.',\n },\n [DatabasesErrorCodes.FailedFileStore]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Error storing file.',\n },\n [DatabasesErrorCodes.FailedFileRead]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Error reading file.',\n },\n [DatabasesErrorCodes.NoRecord]: {\n httpCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Missing database record.',\n },\n [DatabasesErrorCodes.UniqueConstrain]: {\n httpCode: HttpStatus.CONFLICT,\n message: 'Field has to be unique.',\n },\n\n // portal\n [PortalErrorCodes.NoObjectId]: {\n httpCode: HttpStatus.UNAUTHORIZED,\n message: 'No object id found in user claims.',\n },\n};\n","import { HttpException } from '@nestjs/common';\n\nimport { type ErrorCodes, allianceErrors } from './codes';\n\nfunction parseTemplates(message: string, variables: Record<string, string>) {\n return Object.entries(variables).reduce((acc, [key, value]) => {\n return acc.replaceAll(`{{${key}}}`, value);\n }, message);\n}\n\nexport class AllianceException extends HttpException {\n public info: string;\n public code: ErrorCodes;\n constructor(code: ErrorCodes, variables: Record<string, string> = {}) {\n const { message, httpCode } = allianceErrors[code];\n\n super(parseTemplates(message, variables), httpCode);\n\n this.code = code;\n this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${code}`;\n }\n}\n","import { type ArgumentsHost, Catch, type ExceptionFilter } from '@nestjs/common';\nimport type { Response } from 'express';\n\nimport { AllianceException } from './alliance.exception';\n\n@Catch(AllianceException)\nexport class AllianceExceptionFilter implements ExceptionFilter {\n catch(exception: AllianceException, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<Response>();\n const status = exception.getStatus();\n\n response.status &&\n response.status(status).json({\n httpCode: status,\n code: exception.code,\n info: exception.info,\n message: exception.message,\n });\n }\n}\n","import { type DynamicModule, Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { LoggerModule as PinoModule } from 'nestjs-pino';\n\nimport { SharedConfigKeys } from '@/constants';\n\nimport { LoggerService } from './logging.service';\n\ntype ModuleSettings = {\n logLevel?: string;\n redact?: boolean;\n};\n\n@Module({\n providers: [LoggerService],\n exports: [LoggerService],\n})\nexport class LoggerModule {\n static forRoot({ logLevel, redact = true }: ModuleSettings = {}): DynamicModule {\n return {\n module: LoggerModule,\n controllers: [],\n imports: [\n PinoModule.forRootAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => ({\n pinoHttp: {\n level:\n logLevel ||\n configService.get<string>(SharedConfigKeys.ServiceLogLevel) ||\n 'silent',\n redact: redact\n ? [\n 'authorization',\n 'headers.authorization',\n 'req.headers.authorization',\n 'res.headers.authorization',\n ]\n : [],\n },\n }),\n }),\n ],\n global: true,\n providers: [LoggerService],\n exports: [],\n };\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport { PinoLogger } from 'nestjs-pino';\nimport { InjectPinoLogger } from 'nestjs-pino';\n\n@Injectable()\nexport class LoggerService {\n constructor(@InjectPinoLogger() private readonly logger: PinoLogger) {}\n log: PinoLogger['info'] = (...args) => this.logger.info(...args);\n trace: PinoLogger['trace'] = (...args) => this.logger.trace(...args);\n debug: PinoLogger['debug'] = (...args) => this.logger.debug(...args);\n info: PinoLogger['info'] = (...args) => this.logger.info(...args);\n warn: PinoLogger['warn'] = (...args) => this.logger.warn(...args);\n error: PinoLogger['error'] = (...args) => this.logger.error(...args);\n fatal: PinoLogger['fatal'] = (...args) => this.logger.fatal(...args);\n}\n","import _slugify from 'slugify';\n\nexport function slugify(name: string) {\n return _slugify(name, { strict: true, replacement: '-', lower: true });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telia-ace/alliance-internal-node-utilities",
3
- "version": "1.0.4-next.0",
3
+ "version": "1.0.4-next.1",
4
4
  "description": "Utilities used internally by packages developed by team Alliance.",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "author": "Telia Company AB",