@telia-ace/alliance-internal-node-utilities 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { z } from 'zod';
2
- import { AppManifest } from '@telia-ace/alliance-framework/manifest';
3
- import { StorageValue, Storage } from 'unstorage';
4
2
  import { RequestHandler, ErrorRequestHandler } from 'express';
3
+ import { TransportTargetOptions } from 'pino';
4
+ import { StorageValue, Storage } from 'unstorage';
5
+ import { AppManifest } from '@telia-ace/alliance-framework/manifest';
5
6
 
6
7
  type BearerTokenSettings = {
7
8
  privateKey: string;
@@ -17,6 +18,10 @@ type BearerTokenSettings = {
17
18
  name: string;
18
19
  slug: string;
19
20
  };
21
+ organization: {
22
+ name: string;
23
+ slug: string;
24
+ };
20
25
  expiration?: string;
21
26
  };
22
27
  declare const zKeyConfig: z.ZodObject<Pick<{
@@ -29,6 +34,7 @@ declare const zKeyConfig: z.ZodObject<Pick<{
29
34
  SERVICE_PORT: z.ZodDefault<z.ZodEffects<z.ZodString, number, string>>;
30
35
  REDIS_HOST: z.ZodString;
31
36
  REDIS_PASSWORD: z.ZodOptional<z.ZodString>;
37
+ COMMON_DOMAIN: z.ZodDefault<z.ZodEffects<z.ZodEnum<["true", "false"]>, boolean, "true" | "false">>;
32
38
  }, "JWT_PRIVATE_KEY" | "JWT_PUBLIC_CSP_KEY">, "strip", z.ZodTypeAny, {
33
39
  JWT_PRIVATE_KEY: string;
34
40
  JWT_PUBLIC_CSP_KEY: string;
@@ -36,7 +42,7 @@ declare const zKeyConfig: z.ZodObject<Pick<{
36
42
  JWT_PRIVATE_KEY?: string | undefined;
37
43
  JWT_PUBLIC_CSP_KEY?: string | undefined;
38
44
  }>;
39
- declare function createBearerToken({ privateKey, aud, sub, name, user, workspace, expiration, }: BearerTokenSettings): string;
45
+ declare function createBearerToken({ privateKey, aud, sub, name, user, workspace, organization, expiration, }: BearerTokenSettings): string;
40
46
  type BearerTokenContent = {
41
47
  iss: 'Alliance';
42
48
  aud: string;
@@ -47,6 +53,7 @@ type BearerTokenContent = {
47
53
  'https://alliance.teliacompany.net/user_privileges': string[];
48
54
  'https://alliance.teliacompany.net/workspace': string;
49
55
  'https://alliance.teliacompany.net/workspace_name': string;
56
+ 'https://alliance.teliacompany.net/organization': string;
50
57
  };
51
58
  declare function getPrivateKey(config: Pick<z.infer<typeof zKeyConfig>, 'JWT_PRIVATE_KEY'>): string;
52
59
  declare function createSystemUserToken(config: Pick<z.infer<typeof zKeyConfig>, 'JWT_PRIVATE_KEY'>): string;
@@ -113,6 +120,12 @@ declare const zSharedConfig: z.ZodObject<{
113
120
  * Optional
114
121
  */
115
122
  REDIS_PASSWORD: z.ZodOptional<z.ZodString>;
123
+ /**
124
+ * Whether the service should use common domain as workspace and user handling instead of legacy
125
+ *
126
+ * Optional, defaults to "false"
127
+ */
128
+ COMMON_DOMAIN: z.ZodDefault<z.ZodEffects<z.ZodEnum<["true", "false"]>, boolean, "true" | "false">>;
116
129
  }, "strip", z.ZodTypeAny, {
117
130
  AUTH_COOKIE_NAME: string;
118
131
  AUTH_COOKIE_SECRET: string;
@@ -122,6 +135,7 @@ declare const zSharedConfig: z.ZodObject<{
122
135
  SERVICE_LOG_LEVEL: "silent" | "fatal" | "error" | "warn" | "info" | "debug" | "trace";
123
136
  SERVICE_PORT: number;
124
137
  REDIS_HOST: string;
138
+ COMMON_DOMAIN: boolean;
125
139
  REDIS_PASSWORD?: string | undefined;
126
140
  }, {
127
141
  DB_ENDPOINT: string;
@@ -133,12 +147,14 @@ declare const zSharedConfig: z.ZodObject<{
133
147
  SERVICE_LOG_LEVEL?: "silent" | "fatal" | "error" | "warn" | "info" | "debug" | "trace" | undefined;
134
148
  SERVICE_PORT?: string | undefined;
135
149
  REDIS_PASSWORD?: string | undefined;
150
+ COMMON_DOMAIN?: "true" | "false" | undefined;
136
151
  }>;
137
152
 
138
153
  declare enum AllianceHeaders {
139
154
  TargetUrl = "alliance-target-url",
140
155
  TargetApp = "alliance-target-app",
141
- TargetWorkspace = "alliance-target-workspace"
156
+ TargetWorkspace = "alliance-target-workspace",
157
+ TargetOrganization = "alliance-target-organization"
142
158
  }
143
159
 
144
160
  declare function createIndexHtml(apps: AppImportInfo[]): string;
@@ -148,9 +164,29 @@ type AppImportInfo = {
148
164
  manifestImportPath: string;
149
165
  };
150
166
 
151
- declare function getAppManifests(apps: string[]): Promise<AppManifest[]>;
152
-
153
- declare function slugify(value: string, replacement?: string): string;
167
+ declare enum GatewayErrorCode {
168
+ NoObjectId = 10001,
169
+ NoTargetAppHeader = 10002,
170
+ NoTargetWorkspaceHeader = 10003,
171
+ NoManifest = 10006,
172
+ NoRequestContext = 10007,
173
+ NoUserInRequestContext = 10008,
174
+ NoAppInRequestContext = 10009,
175
+ NoWorkspaceInRequestContext = 10010,
176
+ NoUserPermissionsInRequestContext = 10012,
177
+ WorkspacePermissionDenied = 10013,
178
+ NoTargetUrlHeader = 10014,
179
+ NoSessionInRedisCache = 10015,
180
+ ProhibitedTargetDomain = 10016
181
+ }
182
+ declare enum DataErrorCode {
183
+ NoPublicKey = 11000,
184
+ NoAuthHeader = 11001
185
+ }
186
+ declare enum PortalErrorCode {
187
+ NoObjectId = 12000
188
+ }
189
+ type ErrorCode = GatewayErrorCode | DataErrorCode | PortalErrorCode;
154
190
 
155
191
  type LogFn = (msg: string, obj?: any) => void;
156
192
  type PartialConfig = Pick<z.infer<typeof zSharedConfig>, 'SERVICE_LOG_LEVEL'>;
@@ -165,7 +201,18 @@ type Logger = {
165
201
  child(): Logger;
166
202
  level: PartialConfig['SERVICE_LOG_LEVEL'];
167
203
  };
168
- declare function createLogger(config: PartialConfig): {
204
+ declare function createPrettyLogger(config: PartialConfig): {
205
+ fatal: LogFn;
206
+ error: LogFn;
207
+ warn: LogFn;
208
+ info: LogFn;
209
+ debug: LogFn;
210
+ trace: LogFn;
211
+ silent: LogFn;
212
+ child: () => any;
213
+ level: "silent" | "fatal" | "error" | "warn" | "info" | "debug" | "trace";
214
+ };
215
+ declare function createLogger(config: PartialConfig, transport?: TransportTargetOptions): {
169
216
  fatal: LogFn;
170
217
  error: LogFn;
171
218
  warn: LogFn;
@@ -178,37 +225,6 @@ declare function createLogger(config: PartialConfig): {
178
225
  };
179
226
  declare function requestLoggerHandler(logger: Logger): RequestHandler;
180
227
 
181
- declare function createFileStorage<T extends StorageValue = StorageValue>({ prefix, logger, }: {
182
- prefix: string;
183
- logger: Logger;
184
- }): Storage<T>;
185
-
186
- declare enum GatewayErrorCode {
187
- NoObjectId = 10001,
188
- NoTargetAppHeader = 10002,
189
- NoTargetWorkspaceHeader = 10003,
190
- NoManifest = 10006,
191
- NoRequestContext = 10007,
192
- NoUserInRequestContext = 10008,
193
- NoAppInRequestContext = 10009,
194
- NoWorkspaceInRequestContext = 10010,
195
- NoUserPermissionsInRequestContext = 10012,
196
- WorkspacePermissionDenied = 10013,
197
- NoTargetUrlHeader = 10014,
198
- NoSessionInRedisCache = 10015,
199
- ProhibitedTargetDomain = 10016
200
- }
201
- declare enum DataErrorCode {
202
- NoPublicKey = 11000,
203
- NoAuthHeader = 11001,
204
- FailedFileUpload = 11002,
205
- FailedFileDownload = 11003
206
- }
207
- declare enum PortalErrorCode {
208
- NoObjectId = 12000
209
- }
210
- type ErrorCode = GatewayErrorCode | DataErrorCode | PortalErrorCode;
211
-
212
228
  declare class AllianceError extends Error {
213
229
  errorCode: ErrorCode;
214
230
  info: string;
@@ -217,4 +233,13 @@ declare class AllianceError extends Error {
217
233
  }
218
234
  declare function requestErrorHandler(logger: Logger): ErrorRequestHandler;
219
235
 
220
- export { AllianceError, AllianceHeaders, type AppImportInfo, type BearerTokenContent, DataErrorCode, GatewayErrorCode, type Logger, type PublicKeys, createBearerToken, createFileStorage, createIndexHtml, createLogger, createPublicKeys, createSystemUserToken, getAppManifests, getCleanPublicKey, getPrivateKey, requestErrorHandler, requestLoggerHandler, slugify, zBooleanEnum, zNonEmptyString, zSharedConfig };
236
+ declare function createFileStorage<T extends StorageValue = StorageValue>({ prefix, logger, }: {
237
+ prefix: string;
238
+ logger: Logger;
239
+ }): Storage<T>;
240
+
241
+ declare function getAppManifests(apps: string[]): Promise<AppManifest[]>;
242
+
243
+ declare function slugify(value: string, replacement?: string): string;
244
+
245
+ export { AllianceError, AllianceHeaders, type AppImportInfo, type BearerTokenContent, DataErrorCode, GatewayErrorCode, type Logger, type PublicKeys, createBearerToken, createFileStorage, createIndexHtml, createLogger, createPrettyLogger, createPublicKeys, createSystemUserToken, getAppManifests, getCleanPublicKey, getPrivateKey, requestErrorHandler, requestLoggerHandler, slugify, zBooleanEnum, zNonEmptyString, zSharedConfig };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as E,b as ue,c as ce,d as le}from"./chunk-UNKGNXJ3.js";import"./chunk-26VIM55J.js";import"./chunk-JG7V63GM.js";import pe from"jsonwebtoken";import{createPublicKey as fe}from"node:crypto";var me=E.enum(["true","false"]).transform(e=>e==="true"),y=E.string().min(1),T=E.object({AUTH_COOKIE_NAME:y.default("alliance-auth"),AUTH_COOKIE_SECRET:y.default("zlLZBlk7wt8lypP5lA4D"),DB_ENDPOINT:y,JWT_PRIVATE_KEY:y.default("MIIEogIBAAKCAQEAsGqOzjnfQtCYlDqhgGAnKuJOCiPt2WpCmL1Cs+SLBQlyoNn6LT8BJ6ZRj8t/vK8Sw0p51Uq/3k0tazh7bLGkWNMBLY3BqFiNRMMnCqHJfvGIUi/itNXNe2kbP7H3rbyQTu4O7yH/ZAMitdpF2KLucVRlFxrQ/ggZjxwEGso4JUnCwmAnoKct/uupKz9Y2PMTr00WWN79aPfD4LcKi570VJqBT3ISSucdwFLYNqnOkQnEa8O8xbthQhiI0k1GGJT+GCQcATUPeEbaCFXonOrJm+CyuMmQWYLFF3NbE5NllU1jz9PYHzp2hAgAx8WGeretTvpEA1dE2gvXNESGbQ8FxQIDAQABAoIBAAjTJmud1348eGAfLV8CRaij2MAxxenJ9/ozVXfcPIa2+fCelsuBSv8pwbYODvNoVT7xpcs2nwccGI6JgnBl09EhqlMWCT7w7GLT2aBy3A/T6JF76xJICQGzDfWPYygMtlyhv0YqZDUjjFlJHun+/ysqIUMY81AR0FLUAEc6yw41ChcdSvTgIqBM9f5PsBRK7zOgdW1vcVQiZbf2Vqr+7wTJ+6b9A4rWnnAqesGDXqYupx3UJEu3x0wRNQB8FeiG9iJrw4cyD9SmM95doTyKosQ2PWWnUO1NMgmWCR/mWcKZAUcfZUpnQ8rz75WAWept8ZIOOdha8UZ1B/kw3EsVdEECgYEA3iN0BRUqMN0J69bazvlNOWtI+Chc1lYMt/tZ4p78pIJpAZvc3rQ9lAp6JvOEno2IglULA4I+ZLUmpz+lfu7XxKMNOI3cnG7WdiGbiIlwOSwuxzeO1FJqhtnc0U6mNkIjptV8b2etj8U2/SXAC3CC8XgsawAj9A/I7awlCL3NXdECgYEAy07gun3rcd3Y0ISmd3+SbAn/MbGf8uRLcfSc2ls9B6m3pXj25prXJWIrB6DyGuL/HQmHzffQkOeXmwFGHFXyiIFOIITX4z8b9lMnavgUZoPDY+ZFsxp6I7vMn75AetB8wYXpOFFeCG/Ck/VSIYP7oAN8kLw8EHdOuNbZYbu34bUCgYBYd14ZOBiZZS4yUlrJ2tc6atOgoNJ4OcTO8LcXXaHYEmenUF9iAf4UGygSoyDJ1CvtW9kLCK+4g7xlFx/dsVkU4qq9PyIA2tNmMHQ0qCedXU8z35huTnRGSDV81gmzyhtQsezgoTWp8Cy6HHKjG6fKasWlx2SKKk8m+Eu3c396QQKBgBMY2asq4M7VU+RiUXCwHwTe+4Wjda7PGvcdTw6Du3vYyVNVxXtr2AG+8uPIjnVQFT6ZApSqToEOAAOjXv6SZDHGU5xiXhUOfIXq0a0OmHv4rIXZv3pPZmGs5k+rA0uGAfH7riiIHBkWxmQ3ivty9lPVgAHobIvvaQmbxNeVVnRxAoGAUzUmcBiUAiODfjulrpYvWG0tCn5B//yk7g1Tm3Chrh9huA1qGEN3jDoqSsTd5k4Yi5foyAZt5ORgoiUVm4IsfS56aoxIco1CtFG3zeMQRy4uKzTsvUTOdsJ4RlQdjNwpngXR44VL0WelgCDqTqJwn5ubzPvuIHuTj3cBpmJCjOo="),JWT_PUBLIC_CSP_KEY:E.string().min(1).default("BgIAAACkAABSU0ExAAgAAAEAAQDFBQ9thkQ01wvaRFcDRPpOrbd6hsXHAAiEdjof2NPPY02VZZMTW3MXxYJZkMm4suCbyeqc6FUI2kZ4DzUBHCQY/pQYRk3SiBhCYbvFvMNrxAmRzqk22FLAHedKEnJPgZpU9J6LCrfgw/do/d5YFk2vE/PYWD8rqev+LaegJ2DCwkklOMoaBByPGQj+0BoXZVRx7qLYRdq1IgNk/yHvDu5OkLyt97E/G2l7zdW04i9SiPF+yaEKJ8NEjViowY0tAdNYpLFsezhrLU3ev0rVeUrDEq+8f8uPUaYnAT8t+tmgcgkFi+SzQr2YQmrZ7SMKTuIqJ2CAoTqUmNBC3znOjmqw"),SERVICE_LOG_LEVEL:E.enum(["silent","fatal","error","warn","info","debug","trace"]).default("trace"),SERVICE_PORT:y.transform(Number).default("3000"),REDIS_HOST:y,REDIS_PASSWORD:y.optional()});var K=(u=>(u.TargetUrl="alliance-target-url",u.TargetApp="alliance-target-app",u.TargetWorkspace="alliance-target-workspace",u))(K||{});var Xe=T.pick({JWT_PRIVATE_KEY:!0,JWT_PUBLIC_CSP_KEY:!0});function j({privateKey:e,aud:t,sub:n,name:u,user:c,workspace:m,expiration:g="1h"}){return`Bearer ${pe.sign({iss:"Alliance",aud:t,sub:n,name:u,"https://alliance.teliacompany.net/user_type":c.type,"https://alliance.teliacompany.net/user_email":c.email,"https://alliance.teliacompany.net/user_privileges":c.permissions,"https://alliance.teliacompany.net/workspace":m.slug,"https://alliance.teliacompany.net/workspace_name":m.name,"https://alliance.teliacompany.net/tenant":m.slug,"https://alliance.teliacompany.net/tenant_name":m.name},e,{expiresIn:g,algorithm:"RS256"})}`}function L(e){return`-----BEGIN RSA PRIVATE KEY-----
1
+ import{a as E,b as ce,c as me,d as le}from"./chunk-EBHULZEM.js";import"./chunk-26VIM55J.js";import"./chunk-JG7V63GM.js";import{createPublicKey as pe}from"node:crypto";import ge from"jsonwebtoken";var j=E.enum(["true","false"]).transform(e=>e==="true"),h=E.string().min(1),S=E.object({AUTH_COOKIE_NAME:h.default("alliance-auth"),AUTH_COOKIE_SECRET:h.default("zlLZBlk7wt8lypP5lA4D"),DB_ENDPOINT:h,JWT_PRIVATE_KEY:h.default("MIIEogIBAAKCAQEAsGqOzjnfQtCYlDqhgGAnKuJOCiPt2WpCmL1Cs+SLBQlyoNn6LT8BJ6ZRj8t/vK8Sw0p51Uq/3k0tazh7bLGkWNMBLY3BqFiNRMMnCqHJfvGIUi/itNXNe2kbP7H3rbyQTu4O7yH/ZAMitdpF2KLucVRlFxrQ/ggZjxwEGso4JUnCwmAnoKct/uupKz9Y2PMTr00WWN79aPfD4LcKi570VJqBT3ISSucdwFLYNqnOkQnEa8O8xbthQhiI0k1GGJT+GCQcATUPeEbaCFXonOrJm+CyuMmQWYLFF3NbE5NllU1jz9PYHzp2hAgAx8WGeretTvpEA1dE2gvXNESGbQ8FxQIDAQABAoIBAAjTJmud1348eGAfLV8CRaij2MAxxenJ9/ozVXfcPIa2+fCelsuBSv8pwbYODvNoVT7xpcs2nwccGI6JgnBl09EhqlMWCT7w7GLT2aBy3A/T6JF76xJICQGzDfWPYygMtlyhv0YqZDUjjFlJHun+/ysqIUMY81AR0FLUAEc6yw41ChcdSvTgIqBM9f5PsBRK7zOgdW1vcVQiZbf2Vqr+7wTJ+6b9A4rWnnAqesGDXqYupx3UJEu3x0wRNQB8FeiG9iJrw4cyD9SmM95doTyKosQ2PWWnUO1NMgmWCR/mWcKZAUcfZUpnQ8rz75WAWept8ZIOOdha8UZ1B/kw3EsVdEECgYEA3iN0BRUqMN0J69bazvlNOWtI+Chc1lYMt/tZ4p78pIJpAZvc3rQ9lAp6JvOEno2IglULA4I+ZLUmpz+lfu7XxKMNOI3cnG7WdiGbiIlwOSwuxzeO1FJqhtnc0U6mNkIjptV8b2etj8U2/SXAC3CC8XgsawAj9A/I7awlCL3NXdECgYEAy07gun3rcd3Y0ISmd3+SbAn/MbGf8uRLcfSc2ls9B6m3pXj25prXJWIrB6DyGuL/HQmHzffQkOeXmwFGHFXyiIFOIITX4z8b9lMnavgUZoPDY+ZFsxp6I7vMn75AetB8wYXpOFFeCG/Ck/VSIYP7oAN8kLw8EHdOuNbZYbu34bUCgYBYd14ZOBiZZS4yUlrJ2tc6atOgoNJ4OcTO8LcXXaHYEmenUF9iAf4UGygSoyDJ1CvtW9kLCK+4g7xlFx/dsVkU4qq9PyIA2tNmMHQ0qCedXU8z35huTnRGSDV81gmzyhtQsezgoTWp8Cy6HHKjG6fKasWlx2SKKk8m+Eu3c396QQKBgBMY2asq4M7VU+RiUXCwHwTe+4Wjda7PGvcdTw6Du3vYyVNVxXtr2AG+8uPIjnVQFT6ZApSqToEOAAOjXv6SZDHGU5xiXhUOfIXq0a0OmHv4rIXZv3pPZmGs5k+rA0uGAfH7riiIHBkWxmQ3ivty9lPVgAHobIvvaQmbxNeVVnRxAoGAUzUmcBiUAiODfjulrpYvWG0tCn5B//yk7g1Tm3Chrh9huA1qGEN3jDoqSsTd5k4Yi5foyAZt5ORgoiUVm4IsfS56aoxIco1CtFG3zeMQRy4uKzTsvUTOdsJ4RlQdjNwpngXR44VL0WelgCDqTqJwn5ubzPvuIHuTj3cBpmJCjOo="),JWT_PUBLIC_CSP_KEY:E.string().min(1).default("BgIAAACkAABSU0ExAAgAAAEAAQDFBQ9thkQ01wvaRFcDRPpOrbd6hsXHAAiEdjof2NPPY02VZZMTW3MXxYJZkMm4suCbyeqc6FUI2kZ4DzUBHCQY/pQYRk3SiBhCYbvFvMNrxAmRzqk22FLAHedKEnJPgZpU9J6LCrfgw/do/d5YFk2vE/PYWD8rqev+LaegJ2DCwkklOMoaBByPGQj+0BoXZVRx7qLYRdq1IgNk/yHvDu5OkLyt97E/G2l7zdW04i9SiPF+yaEKJ8NEjViowY0tAdNYpLFsezhrLU3ev0rVeUrDEq+8f8uPUaYnAT8t+tmgcgkFi+SzQr2YQmrZ7SMKTuIqJ2CAoTqUmNBC3znOjmqw"),SERVICE_LOG_LEVEL:E.enum(["silent","fatal","error","warn","info","debug","trace"]).default("trace"),SERVICE_PORT:h.transform(Number).default("3000"),REDIS_HOST:h,REDIS_PASSWORD:h.optional(),COMMON_DOMAIN:j.default("false")});var K=(m=>(m.TargetUrl="alliance-target-url",m.TargetApp="alliance-target-app",m.TargetWorkspace="alliance-target-workspace",m.TargetOrganization="alliance-target-organization",m))(K||{});var $e=S.pick({JWT_PRIVATE_KEY:!0,JWT_PUBLIC_CSP_KEY:!0});function V({privateKey:e,aud:t,sub:n,name:u,user:m,workspace:l,organization:f,expiration:y="1h"}){return`Bearer ${ge.sign({iss:"Alliance",aud:t,sub:n,name:u,"https://alliance.teliacompany.net/user_type":m.type,"https://alliance.teliacompany.net/user_email":m.email,"https://alliance.teliacompany.net/user_privileges":m.permissions,"https://alliance.teliacompany.net/workspace":l.slug,"https://alliance.teliacompany.net/workspace_name":l.name,"https://alliance.teliacompany.net/tenant":l.slug,"https://alliance.teliacompany.net/tenant_name":l.name,"https://alliance.teliacompany.net/organization":f.slug},e,{expiresIn:y,algorithm:"RS256"})}`}function L(e){return`-----BEGIN RSA PRIVATE KEY-----
2
2
  `+e.JWT_PRIVATE_KEY+`
3
- -----END RSA PRIVATE KEY-----`}function ge(e){return j({aud:"system",sub:"system",name:"system",workspace:{slug:"system",name:"system"},user:{type:"system",permissions:[],email:"system"},privateKey:L(e)})}function de(e){let t=L(e),n=fe(t);return{pkcs:n.export({type:"pkcs1",format:"pem"}).toString().trim(),spki:n.export({type:"spki",format:"pem"}).toString().trim(),csp:e.JWT_PUBLIC_CSP_KEY}}function ye(e,t){return t[e].replace("-----BEGIN RSA PUBLIC KEY-----","").replace("-----END RSA PUBLIC KEY-----","").replace("-----BEGIN PUBLIC KEY-----","").replace("-----END PUBLIC KEY-----","").trim().replaceAll(`
4
- `,"")}import{homedir as Oe,tmpdir as ze}from"node:os";import{resolve as Fe}from"node:path";var he=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,Ie=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,ve=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function we(e,t){if(e==="__proto__"||e==="constructor"&&t&&typeof t=="object"&&"prototype"in t){Ee(e);return}return t}function Ee(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}function C(e,t={}){if(typeof e!="string")return e;let n=e.trim();if(e[0]==='"'&&e.at(-1)==='"'&&!e.includes("\\"))return n.slice(1,-1);if(n.length<=9){let u=n.toLowerCase();if(u==="true")return!0;if(u==="false")return!1;if(u==="undefined")return;if(u==="null")return null;if(u==="nan")return Number.NaN;if(u==="infinity")return Number.POSITIVE_INFINITY;if(u==="-infinity")return Number.NEGATIVE_INFINITY}if(!ve.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(he.test(e)||Ie.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,we)}return JSON.parse(e)}catch(u){if(t.strict)throw u;return e}}function xe(e){return!e||typeof e.then!="function"?Promise.resolve(e):e}function p(e,...t){try{return xe(e(...t))}catch(n){return Promise.reject(n)}}function Ce(e){let t=typeof e;return e===null||t!=="object"&&t!=="function"}function Ae(e){let t=Object.getPrototypeOf(e);return!t||t.isPrototypeOf(Object)}function A(e){if(Ce(e))return String(e);if(Ae(e)||Array.isArray(e))return JSON.stringify(e);if(typeof e.toJSON=="function")return A(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function M(){if(typeof Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}var b="base64:";function V(e){if(typeof e=="string")return e;M();let t=Buffer.from(e).toString("base64");return b+t}function Y(e){return typeof e!="string"||!e.startsWith(b)?e:(M(),Buffer.from(e.slice(b.length),"base64"))}var Se=["hasItem","getItem","getItemRaw","setItem","setItemRaw","removeItem","getMeta","setMeta","removeMeta","getKeys","clear","mount","unmount"];function B(e,t){if(t=x(t),!t)return e;let n={...e};for(let u of Se)n[u]=(c="",...m)=>e[u](t+c,...m);return n.getKeys=(u="",...c)=>e.getKeys(t+u,...c).then(m=>m.map(g=>g.slice(t.length))),n}function f(e){return e?e.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function D(...e){return f(e.join(":"))}function x(e){return e=f(e),e?e+":":""}var Re="memory",Ne=()=>{let e=new Map;return{name:Re,options:{},hasItem(t){return e.has(t)},getItem(t){return e.get(t)??null},getItemRaw(t){return e.get(t)??null},setItem(t,n){e.set(t,n)},setItemRaw(t,n){e.set(t,n)},removeItem(t){e.delete(t)},getKeys(){return Array.from(e.keys())},clear(){e.clear()},dispose(){e.clear()}}};function Q(e={}){let t={mounts:{"":e.driver||Ne()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=r=>{for(let o of t.mountpoints)if(r.startsWith(o))return{base:o,relativeKey:r.slice(o.length),driver:t.mounts[o]};return{base:"",relativeKey:r,driver:t.mounts[""]}},u=(r,o)=>t.mountpoints.filter(s=>s.startsWith(r)||o&&r.startsWith(s)).map(s=>({relativeBase:r.length>s.length?r.slice(s.length):void 0,mountpoint:s,driver:t.mounts[s]})),c=(r,o)=>{if(t.watching){o=f(o);for(let s of t.watchListeners)s(r,o)}},m=async()=>{if(!t.watching){t.watching=!0;for(let r in t.mounts)t.unwatch[r]=await J(t.mounts[r],c,r)}},g=async()=>{if(t.watching){for(let r in t.unwatch)await t.unwatch[r]();t.unwatch={},t.watching=!1}},h=(r,o,s)=>{let a=new Map,i=l=>{let d=a.get(l.base);return d||(d={driver:l.driver,base:l.base,items:[]},a.set(l.base,d)),d};for(let l of r){let d=typeof l=="string",R=f(d?l:l.key),I=d?void 0:l.value,P=d||!l.options?o:{...o,...l.options},W=n(R);i(W).items.push({key:R,value:I,relativeKey:W.relativeKey,options:P})}return Promise.all([...a.values()].map(l=>s(l))).then(l=>l.flat())},S={hasItem(r,o={}){r=f(r);let{relativeKey:s,driver:a}=n(r);return p(a.hasItem,s,o)},getItem(r,o={}){r=f(r);let{relativeKey:s,driver:a}=n(r);return p(a.getItem,s,o).then(i=>C(i))},getItems(r,o){return h(r,o,s=>s.driver.getItems?p(s.driver.getItems,s.items.map(a=>({key:a.relativeKey,options:a.options})),o).then(a=>a.map(i=>({key:D(s.base,i.key),value:C(i.value)}))):Promise.all(s.items.map(a=>p(s.driver.getItem,a.relativeKey,a.options).then(i=>({key:a.key,value:C(i)})))))},getItemRaw(r,o={}){r=f(r);let{relativeKey:s,driver:a}=n(r);return a.getItemRaw?p(a.getItemRaw,s,o):p(a.getItem,s,o).then(i=>Y(i))},async setItem(r,o,s={}){if(o===void 0)return S.removeItem(r);r=f(r);let{relativeKey:a,driver:i}=n(r);i.setItem&&(await p(i.setItem,a,A(o),s),i.watch||c("update",r))},async setItems(r,o){await h(r,o,async s=>{s.driver.setItems&&await p(s.driver.setItems,s.items.map(a=>({key:a.relativeKey,value:A(a.value),options:a.options})),o),s.driver.setItem&&await Promise.all(s.items.map(a=>p(s.driver.setItem,a.relativeKey,A(a.value),a.options)))})},async setItemRaw(r,o,s={}){if(o===void 0)return S.removeItem(r,s);r=f(r);let{relativeKey:a,driver:i}=n(r);if(i.setItemRaw)await p(i.setItemRaw,a,o,s);else if(i.setItem)await p(i.setItem,a,V(o),s);else return;i.watch||c("update",r)},async removeItem(r,o={}){typeof o=="boolean"&&(o={removeMeta:o}),r=f(r);let{relativeKey:s,driver:a}=n(r);a.removeItem&&(await p(a.removeItem,s,o),(o.removeMeta||o.removeMata)&&await p(a.removeItem,s+"$",o),a.watch||c("remove",r))},async getMeta(r,o={}){typeof o=="boolean"&&(o={nativeOnly:o}),r=f(r);let{relativeKey:s,driver:a}=n(r),i=Object.create(null);if(a.getMeta&&Object.assign(i,await p(a.getMeta,s,o)),!o.nativeOnly){let l=await p(a.getItem,s+"$",o).then(d=>C(d));l&&typeof l=="object"&&(typeof l.atime=="string"&&(l.atime=new Date(l.atime)),typeof l.mtime=="string"&&(l.mtime=new Date(l.mtime)),Object.assign(i,l))}return i},setMeta(r,o,s={}){return this.setItem(r+"$",o,s)},removeMeta(r,o={}){return this.removeItem(r+"$",o)},async getKeys(r,o={}){r=x(r);let s=u(r,!0),a=[],i=[];for(let l of s){let R=(await p(l.driver.getKeys,l.relativeBase,o)).map(I=>l.mountpoint+f(I)).filter(I=>!a.some(P=>I.startsWith(P)));i.push(...R),a=[l.mountpoint,...a.filter(I=>!I.startsWith(l.mountpoint))]}return r?i.filter(l=>l.startsWith(r)&&!l.endsWith("$")):i.filter(l=>!l.endsWith("$"))},async clear(r,o={}){r=x(r),await Promise.all(u(r,!1).map(async s=>{if(s.driver.clear)return p(s.driver.clear,s.relativeBase,o);if(s.driver.removeItem){let a=await s.driver.getKeys(s.relativeBase||"",o);return Promise.all(a.map(i=>s.driver.removeItem(i,o)))}}))},async dispose(){await Promise.all(Object.values(t.mounts).map(r=>H(r)))},async watch(r){return await m(),t.watchListeners.push(r),async()=>{t.watchListeners=t.watchListeners.filter(o=>o!==r),t.watchListeners.length===0&&await g()}},async unwatch(){t.watchListeners=[],await g()},mount(r,o){if(r=x(r),r&&t.mounts[r])throw new Error(`already mounted at ${r}`);return r&&(t.mountpoints.push(r),t.mountpoints.sort((s,a)=>a.length-s.length)),t.mounts[r]=o,t.watching&&Promise.resolve(J(o,c,r)).then(s=>{t.unwatch[r]=s}).catch(console.error),S},async unmount(r,o=!0){r=x(r),!(!r||!t.mounts[r])&&(t.watching&&r in t.unwatch&&(t.unwatch[r](),delete t.unwatch[r]),o&&await H(t.mounts[r]),t.mountpoints=t.mountpoints.filter(s=>s!==r),delete t.mounts[r])},getMount(r=""){r=f(r)+":";let o=n(r);return{driver:o.driver,base:o.base}},getMounts(r="",o={}){return r=f(r),u(r,o.parents).map(a=>({driver:a.driver,base:a.mountpoint}))}};return S}function J(e,t,n){return e.watch?e.watch((u,c)=>t(u,n+c)):()=>{}}async function H(e){typeof e.dispose=="function"&&await p(e.dispose)}import{existsSync as Te,promises as Ke}from"fs";import{resolve as Le,join as be}from"path";function N(e,t,n){return new Error(`[unstorage] [${e}] ${t}`,n)}function G(e,t){return Array.isArray(t)?N(e,`Missing some of the required options ${t.map(n=>"`"+n+"`").join(", ")}`):N(e,`Missing required option \`${t}\`.`)}import{existsSync as Pe,promises as v}from"fs";import{resolve as X,dirname as $}from"path";function O(e){return e.code==="ENOENT"||e.code==="EISDIR"?null:e}function Z(e){return e.code==="EEXIST"?null:e}async function z(e,t,n){return await re($(e)),v.writeFile(e,t,n)}function F(e,t){return v.readFile(e,t).catch(O)}function ee(e){return v.unlink(e).catch(O)}function te(e){return v.readdir(e,{withFileTypes:!0}).catch(O).then(t=>t||[])}async function re(e){Pe(e)||(await re($(e)).catch(Z),await v.mkdir(e).catch(Z))}async function q(e,t){if(t&&t(e))return[];let n=await te(e),u=[];return await Promise.all(n.map(async c=>{let m=X(e,c.name);if(c.isDirectory()){let g=await q(m,t);u.push(...g.map(h=>c.name+"/"+h))}else t&&t(c.name)||u.push(c.name)})),u}async function _(e){let t=await te(e);await Promise.all(t.map(n=>{let u=X(e,n.name);return n.isDirectory()?_(u).then(()=>v.rmdir(u)):v.unlink(u)}))}var Be=/\.\.\:|\.\.$/,k="fs-lite",ne=(e={})=>{if(!e.base)throw G(k,"base");e.base=Le(e.base);let t=n=>{if(Be.test(n))throw N(k,`Invalid key: ${JSON.stringify(n)}. It should not contain .. segments`);return be(e.base,n.replace(/:/g,"/"))};return{name:k,options:e,hasItem(n){return Te(t(n))},getItem(n){return F(t(n),"utf8")},getItemRaw(n){return F(t(n))},async getMeta(n){let{atime:u,mtime:c,size:m,birthtime:g,ctime:h}=await Ke.stat(t(n)).catch(()=>({}));return{atime:u,mtime:c,size:m,birthtime:g,ctime:h}},setItem(n,u){if(!e.readOnly)return z(t(n),u,"utf8")},setItemRaw(n,u){if(!e.readOnly)return z(t(n),u)},removeItem(n){if(!e.readOnly)return ee(t(n))},getKeys(){return q(t("."),e.ignore)},async clear(){e.readOnly||e.noClear||await _(t("."))}}};function qe({prefix:e,logger:t}){return B(Q({driver:ne({base:_e({logger:t})})}),e)}function _e({logger:e}){let t="";try{t=Oe()}catch(n){e.error("could not use homedir, trying tmpdir",{error:n?.message})}if(!t)try{t=ze()}catch(n){e.error("could not use tmpdir, trying process.cwd",{error:n?.message})}if(!t)try{t=process.cwd()}catch(n){e.error("could not use process.cwd, exiting",{error:n?.message}),process.exit(1)}return Fe(t,".alliance")}import ke from"pino";function w(e){return t=>(n,u)=>e[t]({...u,msg:n})}function oe(e){let t=ke({level:e.SERVICE_LOG_LEVEL,redact:["authorization","headers.authorization","req.headers.authorization","res.headers.authorization","req.headers.cookie",'res.headers["set-cookie"]']});return{fatal:w(t)("fatal"),error:w(t)("error"),warn:w(t)("warn"),info:w(t)("info"),debug:w(t)("debug"),trace:w(t)("trace"),silent:w(t)("silent"),child:()=>oe(e),level:e.SERVICE_LOG_LEVEL}}function Ue(e){return(t,n,u)=>(e.trace("received request",{url:t.url,params:t.params,query:t.query,body:t.body}),u())}var se=(i=>(i[i.NoObjectId=10001]="NoObjectId",i[i.NoTargetAppHeader=10002]="NoTargetAppHeader",i[i.NoTargetWorkspaceHeader=10003]="NoTargetWorkspaceHeader",i[i.NoManifest=10006]="NoManifest",i[i.NoRequestContext=10007]="NoRequestContext",i[i.NoUserInRequestContext=10008]="NoUserInRequestContext",i[i.NoAppInRequestContext=10009]="NoAppInRequestContext",i[i.NoWorkspaceInRequestContext=10010]="NoWorkspaceInRequestContext",i[i.NoUserPermissionsInRequestContext=10012]="NoUserPermissionsInRequestContext",i[i.WorkspacePermissionDenied=10013]="WorkspacePermissionDenied",i[i.NoTargetUrlHeader=10014]="NoTargetUrlHeader",i[i.NoSessionInRedisCache=10015]="NoSessionInRedisCache",i[i.ProhibitedTargetDomain=10016]="ProhibitedTargetDomain",i))(se||{}),ie=(c=>(c[c.NoPublicKey=11e3]="NoPublicKey",c[c.NoAuthHeader=11001]="NoAuthHeader",c[c.FailedFileUpload=11002]="FailedFileUpload",c[c.FailedFileDownload=11003]="FailedFileDownload",c))(ie||{});var ae={10001:{statusCode:401,msg:"No object id available on authenticated user."},10002:{statusCode:400,msg:"Request missing header 'alliance-target-app'."},10003:{statusCode:400,msg:"Request missing header 'alliance-target-workspace'."},10014:{statusCode:400,msg:"Request missing header 'alliance-target-url'."},10015:{statusCode:401,msg:"Could not find user session in Redis server."},10006:{statusCode:500,msg:"Could not find manifest for app '{{appSlug}}'."},10007:{statusCode:500,msg:"No request context."},10008:{statusCode:500,msg:"No user in request context."},10009:{statusCode:500,msg:"No app in request context."},10010:{statusCode:500,msg:"No workspace in request context."},10012:{statusCode:500,msg:"No user permissions in request context."},10013:{statusCode:403,msg:"User does not have access to the current workspace."},10016:{statusCode:403,msg:"Request prohibited - REQUEST_DOMAIN_WHITE_LIST does not contain '{{domain}}'."},11e3:{statusCode:401,msg:"No public key available to decode JWT."},11001:{statusCode:401,msg:"No authorization header found."},11002:{statusCode:500,msg:"Something went wrong when trying to upload a file to the S3 storage."},11003:{statusCode:500,msg:"Something went wrong when trying to download a file to the S3 storage."},12e3:{statusCode:401,msg:"No object id found in user claims."}};var U=class extends Error{constructor(n,u={}){let{msg:c,statusCode:m}=ae[n],g=We(c,u);super(g);this.errorCode=n;this.message=g,this.statusCode=m,this.info=`https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${this.errorCode}`}info;statusCode};function We(e,t){return Object.entries(t).reduce((n,[u,c])=>n.replaceAll(`{{${u}}}`,c),e)}function je(e){return(t,n,u,c)=>{let m={cause:t.cause,message:t.message,status:t.status||t.statusCode||t.code,info:t.info};return e.error("error when processing request",{url:n.url,body:n.body,error:m}),u.status(m.status).json(m)}}export{U as AllianceError,K as AllianceHeaders,ie as DataErrorCode,se as GatewayErrorCode,j as createBearerToken,qe as createFileStorage,ce as createIndexHtml,oe as createLogger,de as createPublicKeys,ge as createSystemUserToken,le as getAppManifests,ye as getCleanPublicKey,L as getPrivateKey,je as requestErrorHandler,Ue as requestLoggerHandler,ue as slugify,me as zBooleanEnum,y as zNonEmptyString,T as zSharedConfig};
3
+ -----END RSA PRIVATE KEY-----`}function fe(e){return V({aud:"system",sub:"system",name:"system",workspace:{slug:"system",name:"system"},organization:{slug:"system",name:"system"},user:{type:"system",permissions:[],email:"system"},privateKey:L(e)})}function de(e){let t=L(e),n=pe(t);return{pkcs:n.export({type:"pkcs1",format:"pem"}).toString().trim(),spki:n.export({type:"spki",format:"pem"}).toString().trim(),csp:e.JWT_PUBLIC_CSP_KEY}}function ye(e,t){return t[e].replace("-----BEGIN RSA PUBLIC KEY-----","").replace("-----END RSA PUBLIC KEY-----","").replace("-----BEGIN PUBLIC KEY-----","").replace("-----END PUBLIC KEY-----","").trim().replaceAll(`
4
+ `,"")}var Y=(i=>(i[i.NoObjectId=10001]="NoObjectId",i[i.NoTargetAppHeader=10002]="NoTargetAppHeader",i[i.NoTargetWorkspaceHeader=10003]="NoTargetWorkspaceHeader",i[i.NoManifest=10006]="NoManifest",i[i.NoRequestContext=10007]="NoRequestContext",i[i.NoUserInRequestContext=10008]="NoUserInRequestContext",i[i.NoAppInRequestContext=10009]="NoAppInRequestContext",i[i.NoWorkspaceInRequestContext=10010]="NoWorkspaceInRequestContext",i[i.NoUserPermissionsInRequestContext=10012]="NoUserPermissionsInRequestContext",i[i.WorkspacePermissionDenied=10013]="WorkspacePermissionDenied",i[i.NoTargetUrlHeader=10014]="NoTargetUrlHeader",i[i.NoSessionInRedisCache=10015]="NoSessionInRedisCache",i[i.ProhibitedTargetDomain=10016]="ProhibitedTargetDomain",i))(Y||{}),D=(n=>(n[n.NoPublicKey=11e3]="NoPublicKey",n[n.NoAuthHeader=11001]="NoAuthHeader",n))(D||{});var J={10001:{statusCode:401,msg:"No object id available on authenticated user."},10002:{statusCode:400,msg:"Request missing header 'alliance-target-app'."},10003:{statusCode:400,msg:"Request missing header 'alliance-target-workspace'."},10014:{statusCode:400,msg:"Request missing header 'alliance-target-url'."},10015:{statusCode:401,msg:"Could not find user session in Redis server."},10006:{statusCode:500,msg:"Could not find manifest for app '{{appSlug}}'."},10007:{statusCode:500,msg:"No request context."},10008:{statusCode:500,msg:"No user in request context."},10009:{statusCode:500,msg:"No app in request context."},10010:{statusCode:500,msg:"No workspace in request context."},10012:{statusCode:500,msg:"No user permissions in request context."},10013:{statusCode:403,msg:"User does not have access to the current workspace."},10016:{statusCode:403,msg:"Request prohibited - REQUEST_DOMAIN_WHITE_LIST does not contain '{{domain}}'."},11e3:{statusCode:401,msg:"No public key available to decode JWT."},11001:{statusCode:401,msg:"No authorization header found."},12e3:{statusCode:401,msg:"No object id found in user claims."}};var O=class extends Error{constructor(n,u={}){let{msg:m,statusCode:l}=J[n],f=he(m,u);super(f);this.errorCode=n;this.message=f,this.statusCode=l,this.info=`https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${this.errorCode}`}info;statusCode};function he(e,t){return Object.entries(t).reduce((n,[u,m])=>n.replaceAll(`{{${u}}}`,m),e)}function Ie(e){return(t,n,u,m)=>{let l={cause:t.cause,message:t.message,status:t.status||t.statusCode||t.code,info:t.info};return e.error("error when processing request",{url:n.url,body:n.body,error:l}),u.status(l.status).json(l)}}import{homedir as _e,tmpdir as qe}from"node:os";import{resolve as ke}from"node:path";var ve=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,we=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,Ee=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Ce(e,t){if(e==="__proto__"||e==="constructor"&&t&&typeof t=="object"&&"prototype"in t){xe(e);return}return t}function xe(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}function A(e,t={}){if(typeof e!="string")return e;let n=e.trim();if(e[0]==='"'&&e.at(-1)==='"'&&!e.includes("\\"))return n.slice(1,-1);if(n.length<=9){let u=n.toLowerCase();if(u==="true")return!0;if(u==="false")return!1;if(u==="undefined")return;if(u==="null")return null;if(u==="nan")return Number.NaN;if(u==="infinity")return Number.POSITIVE_INFINITY;if(u==="-infinity")return Number.NEGATIVE_INFINITY}if(!Ee.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(ve.test(e)||we.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,Ce)}return JSON.parse(e)}catch(u){if(t.strict)throw u;return e}}function Ae(e){return!e||typeof e.then!="function"?Promise.resolve(e):e}function p(e,...t){try{return Ae(e(...t))}catch(n){return Promise.reject(n)}}function Pe(e){let t=typeof e;return e===null||t!=="object"&&t!=="function"}function Ne(e){let t=Object.getPrototypeOf(e);return!t||t.isPrototypeOf(Object)}function P(e){if(Pe(e))return String(e);if(Ne(e)||Array.isArray(e))return JSON.stringify(e);if(typeof e.toJSON=="function")return P(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function H(){if(typeof Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}var z="base64:";function Q(e){if(typeof e=="string")return e;H();let t=Buffer.from(e).toString("base64");return z+t}function G(e){return typeof e!="string"||!e.startsWith(z)?e:(H(),Buffer.from(e.slice(z.length),"base64"))}var Re=["hasItem","getItem","getItemRaw","setItem","setItemRaw","removeItem","getMeta","setMeta","removeMeta","getKeys","clear","mount","unmount"];function b(e,t){if(t=C(t),!t)return e;let n={...e};for(let u of Re)n[u]=(m="",...l)=>e[u](t+m,...l);return n.getKeys=(u="",...m)=>e.getKeys(t+u,...m).then(l=>l.map(f=>f.slice(t.length))),n}function g(e){return e?e.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function Z(...e){return g(e.join(":"))}function C(e){return e=g(e),e?e+":":""}var Te="memory",Se=()=>{let e=new Map;return{name:Te,options:{},hasItem(t){return e.has(t)},getItem(t){return e.get(t)??null},getItemRaw(t){return e.get(t)??null},setItem(t,n){e.set(t,n)},setItemRaw(t,n){e.set(t,n)},removeItem(t){e.delete(t)},getKeys(){return Array.from(e.keys())},clear(){e.clear()},dispose(){e.clear()}}};function ee(e={}){let t={mounts:{"":e.driver||Se()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=r=>{for(let o of t.mountpoints)if(r.startsWith(o))return{base:o,relativeKey:r.slice(o.length),driver:t.mounts[o]};return{base:"",relativeKey:r,driver:t.mounts[""]}},u=(r,o)=>t.mountpoints.filter(s=>s.startsWith(r)||o&&r.startsWith(s)).map(s=>({relativeBase:r.length>s.length?r.slice(s.length):void 0,mountpoint:s,driver:t.mounts[s]})),m=(r,o)=>{if(t.watching){o=g(o);for(let s of t.watchListeners)s(r,o)}},l=async()=>{if(!t.watching){t.watching=!0;for(let r in t.mounts)t.unwatch[r]=await X(t.mounts[r],m,r)}},f=async()=>{if(t.watching){for(let r in t.unwatch)await t.unwatch[r]();t.unwatch={},t.watching=!1}},y=(r,o,s)=>{let a=new Map,i=c=>{let d=a.get(c.base);return d||(d={driver:c.driver,base:c.base,items:[]},a.set(c.base,d)),d};for(let c of r){let d=typeof c=="string",N=g(d?c:c.key),I=d?void 0:c.value,T=d||!c.options?o:{...o,...c.options},W=n(N);i(W).items.push({key:N,value:I,relativeKey:W.relativeKey,options:T})}return Promise.all([...a.values()].map(c=>s(c))).then(c=>c.flat())},x={hasItem(r,o={}){r=g(r);let{relativeKey:s,driver:a}=n(r);return p(a.hasItem,s,o)},getItem(r,o={}){r=g(r);let{relativeKey:s,driver:a}=n(r);return p(a.getItem,s,o).then(i=>A(i))},getItems(r,o){return y(r,o,s=>s.driver.getItems?p(s.driver.getItems,s.items.map(a=>({key:a.relativeKey,options:a.options})),o).then(a=>a.map(i=>({key:Z(s.base,i.key),value:A(i.value)}))):Promise.all(s.items.map(a=>p(s.driver.getItem,a.relativeKey,a.options).then(i=>({key:a.key,value:A(i)})))))},getItemRaw(r,o={}){r=g(r);let{relativeKey:s,driver:a}=n(r);return a.getItemRaw?p(a.getItemRaw,s,o):p(a.getItem,s,o).then(i=>G(i))},async setItem(r,o,s={}){if(o===void 0)return x.removeItem(r);r=g(r);let{relativeKey:a,driver:i}=n(r);i.setItem&&(await p(i.setItem,a,P(o),s),i.watch||m("update",r))},async setItems(r,o){await y(r,o,async s=>{s.driver.setItems&&await p(s.driver.setItems,s.items.map(a=>({key:a.relativeKey,value:P(a.value),options:a.options})),o),s.driver.setItem&&await Promise.all(s.items.map(a=>p(s.driver.setItem,a.relativeKey,P(a.value),a.options)))})},async setItemRaw(r,o,s={}){if(o===void 0)return x.removeItem(r,s);r=g(r);let{relativeKey:a,driver:i}=n(r);if(i.setItemRaw)await p(i.setItemRaw,a,o,s);else if(i.setItem)await p(i.setItem,a,Q(o),s);else return;i.watch||m("update",r)},async removeItem(r,o={}){typeof o=="boolean"&&(o={removeMeta:o}),r=g(r);let{relativeKey:s,driver:a}=n(r);a.removeItem&&(await p(a.removeItem,s,o),(o.removeMeta||o.removeMata)&&await p(a.removeItem,s+"$",o),a.watch||m("remove",r))},async getMeta(r,o={}){typeof o=="boolean"&&(o={nativeOnly:o}),r=g(r);let{relativeKey:s,driver:a}=n(r),i=Object.create(null);if(a.getMeta&&Object.assign(i,await p(a.getMeta,s,o)),!o.nativeOnly){let c=await p(a.getItem,s+"$",o).then(d=>A(d));c&&typeof c=="object"&&(typeof c.atime=="string"&&(c.atime=new Date(c.atime)),typeof c.mtime=="string"&&(c.mtime=new Date(c.mtime)),Object.assign(i,c))}return i},setMeta(r,o,s={}){return this.setItem(r+"$",o,s)},removeMeta(r,o={}){return this.removeItem(r+"$",o)},async getKeys(r,o={}){r=C(r);let s=u(r,!0),a=[],i=[];for(let c of s){let N=(await p(c.driver.getKeys,c.relativeBase,o)).map(I=>c.mountpoint+g(I)).filter(I=>!a.some(T=>I.startsWith(T)));i.push(...N),a=[c.mountpoint,...a.filter(I=>!I.startsWith(c.mountpoint))]}return r?i.filter(c=>c.startsWith(r)&&!c.endsWith("$")):i.filter(c=>!c.endsWith("$"))},async clear(r,o={}){r=C(r),await Promise.all(u(r,!1).map(async s=>{if(s.driver.clear)return p(s.driver.clear,s.relativeBase,o);if(s.driver.removeItem){let a=await s.driver.getKeys(s.relativeBase||"",o);return Promise.all(a.map(i=>s.driver.removeItem(i,o)))}}))},async dispose(){await Promise.all(Object.values(t.mounts).map(r=>$(r)))},async watch(r){return await l(),t.watchListeners.push(r),async()=>{t.watchListeners=t.watchListeners.filter(o=>o!==r),t.watchListeners.length===0&&await f()}},async unwatch(){t.watchListeners=[],await f()},mount(r,o){if(r=C(r),r&&t.mounts[r])throw new Error(`already mounted at ${r}`);return r&&(t.mountpoints.push(r),t.mountpoints.sort((s,a)=>a.length-s.length)),t.mounts[r]=o,t.watching&&Promise.resolve(X(o,m,r)).then(s=>{t.unwatch[r]=s}).catch(console.error),x},async unmount(r,o=!0){r=C(r),!(!r||!t.mounts[r])&&(t.watching&&r in t.unwatch&&(t.unwatch[r](),delete t.unwatch[r]),o&&await $(t.mounts[r]),t.mountpoints=t.mountpoints.filter(s=>s!==r),delete t.mounts[r])},getMount(r=""){r=g(r)+":";let o=n(r);return{driver:o.driver,base:o.base}},getMounts(r="",o={}){return r=g(r),u(r,o.parents).map(a=>({driver:a.driver,base:a.mountpoint}))}};return x}function X(e,t,n){return e.watch?e.watch((u,m)=>t(u,n+m)):()=>{}}async function $(e){typeof e.dispose=="function"&&await p(e.dispose)}import{existsSync as Le,promises as Oe}from"fs";import{resolve as ze,join as be}from"path";function R(e,t,n){return new Error(`[unstorage] [${e}] ${t}`,n)}function te(e,t){return Array.isArray(t)?R(e,`Missing some of the required options ${t.map(n=>"`"+n+"`").join(", ")}`):R(e,`Missing required option \`${t}\`.`)}import{existsSync as Ke,promises as v}from"fs";import{resolve as ne,dirname as oe}from"path";function B(e){return e.code==="ENOENT"||e.code==="EISDIR"?null:e}function re(e){return e.code==="EEXIST"?null:e}async function _(e,t,n){return await ae(oe(e)),v.writeFile(e,t,n)}function q(e,t){return v.readFile(e,t).catch(B)}function se(e){return v.unlink(e).catch(B)}function ie(e){return v.readdir(e,{withFileTypes:!0}).catch(B).then(t=>t||[])}async function ae(e){Ke(e)||(await ae(oe(e)).catch(re),await v.mkdir(e).catch(re))}async function k(e,t){if(t&&t(e))return[];let n=await ie(e),u=[];return await Promise.all(n.map(async m=>{let l=ne(e,m.name);if(m.isDirectory()){let f=await k(l,t);u.push(...f.map(y=>m.name+"/"+y))}else t&&t(m.name)||u.push(m.name)})),u}async function U(e){let t=await ie(e);await Promise.all(t.map(n=>{let u=ne(e,n.name);return n.isDirectory()?U(u).then(()=>v.rmdir(u)):v.unlink(u)}))}var Be=/\.\.\:|\.\.$/,F="fs-lite",ue=(e={})=>{if(!e.base)throw te(F,"base");e.base=ze(e.base);let t=n=>{if(Be.test(n))throw R(F,`Invalid key: ${JSON.stringify(n)}. It should not contain .. segments`);return be(e.base,n.replace(/:/g,"/"))};return{name:F,options:e,hasItem(n){return Le(t(n))},getItem(n){return q(t(n),"utf8")},getItemRaw(n){return q(t(n))},async getMeta(n){let{atime:u,mtime:m,size:l,birthtime:f,ctime:y}=await Oe.stat(t(n)).catch(()=>({}));return{atime:u,mtime:m,size:l,birthtime:f,ctime:y}},setItem(n,u){if(!e.readOnly)return _(t(n),u,"utf8")},setItemRaw(n,u){if(!e.readOnly)return _(t(n),u)},removeItem(n){if(!e.readOnly)return se(t(n))},getKeys(){return k(t("."),e.ignore)},async clear(){e.readOnly||e.noClear||await U(t("."))}}};function Ue({prefix:e,logger:t}){return b(ee({driver:ue({base:Fe({logger:t})})}),e)}function Fe({logger:e}){let t="";try{t=_e()}catch(n){e.error("could not use homedir, trying tmpdir",{error:n?.message})}if(!t)try{t=qe()}catch(n){e.error("could not use tmpdir, trying process.cwd",{error:n?.message})}if(!t)try{t=process.cwd()}catch(n){e.error("could not use process.cwd, exiting",{error:n?.message}),process.exit(1)}return ke(t,".alliance")}import Me from"pino";function w(e){return t=>(n,u)=>e[t]({...u,msg:n})}function We(e){return M(e,{target:"pino-pretty",options:{colorize:!0,ignore:"time,pid,hostname",messageFormat:"{msg}"}})}function M(e,t){let n=Me({level:e.SERVICE_LOG_LEVEL,redact:["authorization","headers.authorization","req.headers.authorization","res.headers.authorization","req.headers.cookie",'res.headers["set-cookie"]'],transport:t});return{fatal:w(n)("fatal"),error:w(n)("error"),warn:w(n)("warn"),info:w(n)("info"),debug:w(n)("debug"),trace:w(n)("trace"),silent:w(n)("silent"),child:()=>M(e),level:e.SERVICE_LOG_LEVEL}}function je(e){return(t,n,u)=>(e.trace("received request",{url:t.url,params:t.params,query:t.query,body:t.body}),u())}export{O as AllianceError,K as AllianceHeaders,D as DataErrorCode,Y as GatewayErrorCode,V as createBearerToken,Ue as createFileStorage,me as createIndexHtml,M as createLogger,We as createPrettyLogger,de as createPublicKeys,fe as createSystemUserToken,le as getAppManifests,ye as getCleanPublicKey,L as getPrivateKey,Ie as requestErrorHandler,je as requestLoggerHandler,ce as slugify,j as zBooleanEnum,h as zNonEmptyString,S as zSharedConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telia-ace/alliance-internal-node-utilities",
3
- "version": "1.1.0",
3
+ "version": "1.1.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",
@@ -24,7 +24,8 @@
24
24
  "pino": "^8.16.2"
25
25
  },
26
26
  "devDependencies": {
27
- "@telia-ace/alliance-framework": "^1.1.0"
27
+ "pino-pretty": "^10.3.1",
28
+ "@telia-ace/alliance-framework": "^1.1.2"
28
29
  },
29
30
  "publishConfig": {
30
31
  "access": "public"