@telia-ace/alliance-portal 1.0.7-next.4 → 1.0.7-next.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @telia-ace/alliance-portal
2
2
 
3
+ ## 1.0.7-next.5
4
+
5
+ ### Patch Changes
6
+
7
+ - 17d7be4: Move health check endpoint to `/-/health`.
8
+ - 17d7be4: Add 404 page for non existant Workspaces.
9
+ - 17d7be4: Add support for `LANDING_PAGE` environment variable to display a landing page on the portal instance root.
10
+ - 17d7be4: Respond with correct status code in endpoints.
11
+ - 17d7be4: Add current Workspace name to Customer Portal page title.
12
+ - 17d7be4: Include `skipGroupClaimCheck` environment variable value in trace log when user signs in.
13
+ - 17d7be4: Ensure unnecessary files aren't copied into Docker images.
14
+ - 17d7be4: Replace `ORIGIN_AS_ROOT_URL` with `ROOT_URL_SUB_PATH` to configure what sub path a Portal will be hosted on.
15
+ - Updated dependencies [17d7be4]
16
+ - Updated dependencies [17d7be4]
17
+ - @telia-ace/alliance-internal-node-utilities@1.0.4-next.4
18
+
3
19
  ## 1.0.7-next.4
4
20
 
5
21
  ### Patch Changes
@@ -1,176 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:all[name]})}_export(exports,{GlobalFrameworkVariables:function(){return GlobalFrameworkVariables},createAppController:function(){return createAppController}});const _axios=require("@nestjs/axios");const _common=require("@nestjs/common");const _config=require("@nestjs/config");const _terminus=require("@nestjs/terminus");const _allianceinternalnodeutilities=require("@telia-ace/alliance-internal-node-utilities");const _express=require("express");const _graphqlrequest=require("graphql-request");const _config1=require("./config");const _graphql=require("./graphql");function _ts_decorate(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r}function _ts_metadata(k,v){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(k,v)}function _ts_param(paramIndex,decorator){return function(target,key){decorator(target,key,paramIndex)}}function createAppController(){const environmentWorkspace=process.env[_config1.ConfigKeys.Workspace];let AppController=class AppController{signin(){}favicon(){return""}health(){return this.healthService.check([()=>this.redisHealthCheck.isHealthy()])}async cookiePolicy(){const{data}=await this.httpService.axiosRef.get(this.wpPolicyUrl);return data}async index(req,workspaceParam){let userHasAccess=false;try{const objectId=req?.oidc?.user?.sub;const{user}=await (0,_graphqlrequest.request)(this.configService.getOrThrow(_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint),_graphql.GetUserDocument,{objectId,workspaceSlug:environmentWorkspace||workspaceParam},{authorization:(0,_allianceinternalnodeutilities.createSystemUserToken)(this.configService)});userHasAccess=!!user.id}catch{}if(!userHasAccess){return htmlTemplate(unauthorizedPortalBody())}this.logger.info("opening portal",{user:req.oidc.user,workspaceSlug:environmentWorkspace||workspaceParam});return htmlTemplate(this.portalBody({excludeTag:!!req.query["wp-tag"]||!!req.query["wp-version"],workspaceSlug:environmentWorkspace||workspaceParam}))}portalBody({excludeTag,workspaceSlug}){const opts=excludeTag?{}:{tag:this.wpTag};const environmentCustomer=this.configService.get(_config1.ConfigKeys.Customer);let rootUrl=`window.origin + '/${workspaceSlug}'`;if(this.configService.get(_config1.ConfigKeys.OriginAsRootUrl)){rootUrl="window.origin"}else if(environmentCustomer){rootUrl=`window.origin + '/${environmentCustomer}/${workspaceSlug}'`}return`
2
- <script>
3
- window.${"__ALLIANCE_RUNTIME_ROOT_URL"} = ${rootUrl};
4
- window.${"__ALLIANCE_WORKSPACE"} = '${workspaceSlug}';
5
- window.${"__ALLIANCE_CUSTOMER"} = ${environmentCustomer?`'${environmentCustomer}'`:"undefined"};
6
- </script>
7
-
8
- <script>
9
- /* WEBPROVISIONS */
10
- !function(e,n){var o=n||{},c=document,t=window,s=function(n,o){e+=(e.indexOf("?")>-1?"&":"?")+encodeURIComponent(n)+"="
11
- +encodeURIComponent(o)},i=/[?&]{1}(wp[^=]*)=([^&#]*)/g,r=c.getElementsByTagName("script")[0],p=c.createElement("script");p.type="module";e=e+"/index.js";
12
- for(t.webprovisions=t.webprovisions||{_c:[],configure:function(){t.webprovisions._c.push(arguments)}};matches=i.exec(t.location.search);)
13
- s(matches[1],matches[2]);Object.keys(o).forEach((function(e){s("wp-"+e,o[e])})),p.async=!0,p.src=e,r.parentNode.insertBefore(p,r)}
14
- /**
15
- * Configure the implementation by specifying a remote endpoint with optional arguments.
16
- * url - The url to the remote endpoint for the implementation.
17
- * args - Object containing optional arguments for the implementation.
18
- */
19
- ("${this.wpUrl}", ${JSON.stringify(opts)})
20
- </script>
21
-
22
- ${loader}
23
- `}constructor(logger,configService,httpService,healthService,redisHealthCheck){this.logger=logger;this.configService=configService;this.httpService=httpService;this.healthService=healthService;this.redisHealthCheck=redisHealthCheck;this.wpUrl=this.configService.getOrThrow(_config1.ConfigKeys.WebprovisionsDistributionUrl);this.wpPolicyUrl=this.configService.get(_config1.ConfigKeys.WebprovisionsDistributionCookiePolicyUrl)||`${this.wpUrl}/cookie-policy.html`;this.wpTag=this.configService.get(_config1.ConfigKeys.WebprovisionsTag)}};_ts_decorate([(0,_common.Get)("/signin-oidc"),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[])],AppController.prototype,"signin",null);_ts_decorate([(0,_common.Get)("/favicon*"),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[])],AppController.prototype,"favicon",null);_ts_decorate([(0,_common.Get)("/health"),(0,_terminus.HealthCheck)(),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[])],AppController.prototype,"health",null);_ts_decorate([(0,_common.Get)(environmentWorkspace?"/cookie-policy":"/:workspace/cookie-policy"),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[])],AppController.prototype,"cookiePolicy",null);_ts_decorate([(0,_common.Get)(environmentWorkspace?"/*":"/:workspace*"),_ts_param(0,(0,_common.Req)()),_ts_param(1,(0,_common.Param)("workspace")),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[typeof _express.Request==="undefined"?Object:_express.Request,String])],AppController.prototype,"index",null);AppController=_ts_decorate([(0,_common.Controller)(),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[typeof _allianceinternalnodeutilities.LoggerService==="undefined"?Object:_allianceinternalnodeutilities.LoggerService,typeof _config.ConfigService==="undefined"?Object:_config.ConfigService,typeof _axios.HttpService==="undefined"?Object:_axios.HttpService,typeof _terminus.HealthCheckService==="undefined"?Object:_terminus.HealthCheckService,typeof _allianceinternalnodeutilities.RedisHealthIndicator==="undefined"?Object:_allianceinternalnodeutilities.RedisHealthIndicator])],AppController);return AppController}var GlobalFrameworkVariables;(function(GlobalFrameworkVariables){GlobalFrameworkVariables["RuntimeRootUrl"]="__ALLIANCE_RUNTIME_ROOT_URL";GlobalFrameworkVariables["Workspace"]="__ALLIANCE_WORKSPACE";GlobalFrameworkVariables["Customer"]="__ALLIANCE_CUSTOMER"})(GlobalFrameworkVariables||(GlobalFrameworkVariables={}));const loader=`
24
- <style>
25
- .alliance-portal-loader-wrapper {
26
- position: fixed;
27
- inset: 0;
28
- display: flex;
29
- justify-content: center;
30
- align-items: center;
31
- }
32
- .alliance-portal-loader {
33
- display: inline-block;
34
- position: relative;
35
- width: 80px;
36
- height: 80px;
37
- }
38
- .alliance-portal-loader div {
39
- animation: alliance-portal-loader 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
40
- transform-origin: 40px 40px;
41
- }
42
- .alliance-portal-loader div:after {
43
- content: ' ';
44
- display: block;
45
- position: absolute;
46
- width: 7px;
47
- height: 7px;
48
- border-radius: 50%;
49
- background: #29003e;
50
- margin: -4px 0 0 -4px;
51
- }
52
- .alliance-portal-loader div:nth-child(1) {
53
- animation-delay: -0.036s;
54
- }
55
- .alliance-portal-loader div:nth-child(1):after {
56
- top: 63px;
57
- left: 63px;
58
- }
59
- .alliance-portal-loader div:nth-child(2) {
60
- animation-delay: -0.072s;
61
- }
62
- .alliance-portal-loader div:nth-child(2):after {
63
- top: 68px;
64
- left: 56px;
65
- }
66
- .alliance-portal-loader div:nth-child(3) {
67
- animation-delay: -0.108s;
68
- }
69
- .alliance-portal-loader div:nth-child(3):after {
70
- top: 71px;
71
- left: 48px;
72
- }
73
- .alliance-portal-loader div:nth-child(4) {
74
- animation-delay: -0.144s;
75
- }
76
- .alliance-portal-loader div:nth-child(4):after {
77
- top: 72px;
78
- left: 40px;
79
- }
80
- .alliance-portal-loader div:nth-child(5) {
81
- animation-delay: -0.18s;
82
- }
83
- .alliance-portal-loader div:nth-child(5):after {
84
- top: 71px;
85
- left: 32px;
86
- }
87
- .alliance-portal-loader div:nth-child(6) {
88
- animation-delay: -0.216s;
89
- }
90
- .alliance-portal-loader div:nth-child(6):after {
91
- top: 68px;
92
- left: 24px;
93
- }
94
- .alliance-portal-loader div:nth-child(7) {
95
- animation-delay: -0.252s;
96
- }
97
- .alliance-portal-loader div:nth-child(7):after {
98
- top: 63px;
99
- left: 17px;
100
- }
101
- .alliance-portal-loader div:nth-child(8) {
102
- animation-delay: -0.288s;
103
- }
104
- .alliance-portal-loader div:nth-child(8):after {
105
- top: 56px;
106
- left: 12px;
107
- }
108
- @keyframes alliance-portal-loader {
109
- 0% {
110
- transform: rotate(0deg);
111
- }
112
- 100% {
113
- transform: rotate(360deg);
114
- }
115
- }
116
- </style>
117
- <div class="alliance-portal-loader-wrapper">
118
- <div class="alliance-portal-loader">
119
- <div></div>
120
- <div></div>
121
- <div></div>
122
- <div></div>
123
- <div></div>
124
- <div></div>
125
- <div></div>
126
- <div></div>
127
- </div>
128
- </div>
129
- `;function unauthorizedPortalBody(){return`
130
- <div class="unauthorized">
131
- <h1>401</h1>
132
- <p>You don't have permission to access this workspace.</p>
133
- </div>
134
- <style>
135
- @import 'https://cdn.voca.teliacompany.com/fonts/TeliaSansV10/TeliaSans.css';
136
- .unauthorized {
137
- position: absolute;
138
- inset: 0;
139
- display: flex;
140
- flex-direction: column;
141
- gap: 1em;
142
- justify-content: center;
143
- align-items: center;
144
- }
145
-
146
- h1 {
147
- font-family: TeliaSansHeading, TeliaSans, HelveticaNeue, Helvetica, Arial, sans-serif;
148
- color: #e4175c;
149
- font-size: 4em;
150
- margin: 0;
151
- }
152
-
153
- p {
154
- font-family: TeliaSans, Helvetica, Arial, Lucida Grande, sans-serif;
155
- font-size: 2em;
156
- margin: 0;
157
- }
158
- </style>
159
- `}function htmlTemplate(body){return`
160
- <!DOCTYPE html>
161
- <html lang="en">
162
-
163
- <head>
164
- <meta charset="UTF-8" />
165
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
166
- <title>Alliance Portal</title>
167
- <link rel="icon"
168
- href="data:image/png;base64,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" />
169
- </head>
170
-
171
- <body>
172
- ${body}
173
- </body>
174
-
175
- </html>
176
- `}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"createAppController",{enumerable:true,get:function(){return createAppController}});const _axios=require("@nestjs/axios");const _common=require("@nestjs/common");const _config=require("@nestjs/config");const _terminus=require("@nestjs/terminus");const _allianceinternalnodeutilities=require("@telia-ace/alliance-internal-node-utilities");const _express=require("express");const _graphqlrequest=require("graphql-request");const _config1=require("./config");const _graphql=require("./graphql");const _html=require("./html");const _responses=require("./responses");function _ts_decorate(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r}function _ts_metadata(k,v){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(k,v)}function _ts_param(paramIndex,decorator){return function(target,key){decorator(target,key,paramIndex)}}function createAppController(){const environmentWorkspace=process.env[_config1.ConfigKeys.Workspace];let AppController=class AppController{async signin(){}async favicon(){return""}async health(){return this.healthService.check([()=>this.redisHealthCheck.isHealthy()])}async cookiePolicy(){const{data}=await this.httpService.axiosRef.get(this.wpPolicyUrl);return data}async index(req,res,workspaceParam){return this.portal(req,res,environmentWorkspace||workspaceParam)}async workspace(_1,res,_2){return res.status(_common.HttpStatus.NOT_FOUND).send("Not Available")}async portal(req,res,workspaceSlug){let existingWorkspace=null;try{const{workspace}=await (0,_graphqlrequest.request)(this.configService.getOrThrow(_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint),_graphql.GetWorkspaceDocument,{slug:workspaceSlug},{authorization:(0,_allianceinternalnodeutilities.createSystemUserToken)(this.configService)});existingWorkspace=workspace}catch(error){if(error?.code==="ECONNREFUSED"){return(0,_responses.dbError)(res)}}if(!existingWorkspace){return(0,_responses.workspaceNotFoundError)(res,workspaceSlug)}let userHasAccess=false;try{const objectId=req?.oidc?.user?.sub;const{user}=await (0,_graphqlrequest.request)(this.configService.getOrThrow(_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint),_graphql.GetUserDocument,{objectId,workspaceSlug},{authorization:(0,_allianceinternalnodeutilities.createSystemUserToken)(this.configService)});userHasAccess=!!user.id}catch{}if(!userHasAccess){return(0,_responses.unauthorizedError)(res,workspaceSlug)}this.logger.info("opening portal",{user:req.oidc.user,workspaceSlug});return(0,_responses.ok)(res,(0,_html.htmlTemplate)(existingWorkspace.slug==="system"?"ACE Enterprise Portal":`ACE Customer Portal - ${existingWorkspace.name}`,(0,_html.loaderHtml)(),(0,_html.globalVariables)(this.configService,workspaceSlug),(0,_html.embedScript)(this.wpUrl,!!req.query["wp-tag"]||!!req.query["wp-version"]?{}:{tag:this.wpTag})))}constructor(logger,configService,httpService,healthService,redisHealthCheck){this.logger=logger;this.configService=configService;this.httpService=httpService;this.healthService=healthService;this.redisHealthCheck=redisHealthCheck;this.wpUrl=this.configService.getOrThrow(_config1.ConfigKeys.WebprovisionsDistributionUrl);this.wpPolicyUrl=this.configService.get(_config1.ConfigKeys.WebprovisionsDistributionCookiePolicyUrl)||`${this.wpUrl}/cookie-policy.html`;this.wpTag=this.configService.get(_config1.ConfigKeys.WebprovisionsTag)}};_ts_decorate([(0,_common.Get)("/signin-oidc"),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[])],AppController.prototype,"signin",null);_ts_decorate([(0,_common.Get)("/favicon*"),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[])],AppController.prototype,"favicon",null);_ts_decorate([(0,_common.Get)(["/-/health","/:workspace/-/health"]),(0,_terminus.HealthCheck)(),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[])],AppController.prototype,"health",null);_ts_decorate([(0,_common.Get)(environmentWorkspace?"/cookie-policy":"/:workspace/cookie-policy"),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[])],AppController.prototype,"cookiePolicy",null);_ts_decorate([(0,_common.Get)(environmentWorkspace?"/*":"/:workspace*"),_ts_param(0,(0,_common.Req)()),_ts_param(1,(0,_common.Res)()),_ts_param(2,(0,_common.Param)("workspace")),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[typeof _express.Request==="undefined"?Object:_express.Request,typeof _express.Response==="undefined"?Object:_express.Response,String])],AppController.prototype,"index",null);_ts_decorate([_ts_param(0,(0,_common.Req)()),_ts_param(1,(0,_common.Res)()),_ts_param(2,(0,_common.Param)("workspace")),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[typeof _express.Request==="undefined"?Object:_express.Request,typeof _express.Response==="undefined"?Object:_express.Response,String])],AppController.prototype,"workspace",null);AppController=_ts_decorate([(0,_common.Controller)(),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[typeof _allianceinternalnodeutilities.LoggerService==="undefined"?Object:_allianceinternalnodeutilities.LoggerService,typeof _config.ConfigService==="undefined"?Object:_config.ConfigService,typeof _axios.HttpService==="undefined"?Object:_axios.HttpService,typeof _terminus.HealthCheckService==="undefined"?Object:_terminus.HealthCheckService,typeof _allianceinternalnodeutilities.RedisHealthIndicator==="undefined"?Object:_allianceinternalnodeutilities.RedisHealthIndicator])],AppController);if(!process.env[_config1.ConfigKeys.LandingPage]||process.env[_config1.ConfigKeys.LandingPage]==="true"){let AppControllerWithLandingPage=class AppControllerWithLandingPage extends AppController{async health(){return super.health()}async index(_,res){return(0,_responses.ok)(res,(0,_html.htmlTemplate)("ACE Customer Portal - Landing Page",(0,_html.loaderHtml)(),(0,_html.embedScript)("https://embed.webprovisions.io/resource/alliance/landing-page")))}async workspace(req,res,workspaceParam){return super.index(req,res,workspaceParam)}};_ts_decorate([(0,_common.Get)(["/-/health","/:workspace/-/health"]),(0,_terminus.HealthCheck)(),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[])],AppControllerWithLandingPage.prototype,"health",null);_ts_decorate([(0,_common.Get)("/"),_ts_param(0,(0,_common.Req)()),_ts_param(1,(0,_common.Res)()),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[typeof _express.Request==="undefined"?Object:_express.Request,typeof _express.Response==="undefined"?Object:_express.Response])],AppControllerWithLandingPage.prototype,"index",null);_ts_decorate([(0,_common.Get)("/:workspace*"),_ts_param(0,(0,_common.Req)()),_ts_param(1,(0,_common.Res)()),_ts_param(2,(0,_common.Param)("workspace")),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[typeof _express.Request==="undefined"?Object:_express.Request,typeof _express.Response==="undefined"?Object:_express.Response,String])],AppControllerWithLandingPage.prototype,"workspace",null);AppControllerWithLandingPage=_ts_decorate([(0,_common.Controller)()],AppControllerWithLandingPage);return AppControllerWithLandingPage}return AppController}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});const _axios=require("@nestjs/axios");const _config=require("@nestjs/config");const _terminus=require("@nestjs/terminus");const _testing=require("@nestjs/testing");const _allianceinternalnodeutilities=require("@telia-ace/alliance-internal-node-utilities");const _vitest=require("vitest");const _config1=require("./config");function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interop_require_wildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={__proto__:null};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}_vitest.vi.mock("graphql-request",async()=>{return{request:_vitest.vi.fn().mockImplementation(async(_1,_2,{objectId})=>{if(objectId==="has-access"){return{user:{id:objectId}}}return})}});(0,_vitest.describe)("AppController",()=>{const cfg={[_config1.ConfigKeys.AuthAuthority]:"test authority",[_config1.ConfigKeys.AuthClientSecret]:"test client secret",[_config1.ConfigKeys.AuthClientId]:"test client id",[_config1.ConfigKeys.ServiceBaseUrl]:"http://base-url",[_config1.ConfigKeys.WebprovisionsDistributionUrl]:"http://localhost:1234/distribution",[_config1.ConfigKeys.WebprovisionsDistributionCookiePolicyUrl]:"http://localhost:1234/cookie-policy.html",[_config1.ConfigKeys.WebprovisionsTag]:"the-tag",[_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint]:"http://localhost:1234/mocked-db"};let mock;async function setupMock(override={}){_vitest.vi.unstubAllEnvs();const{GlobalFrameworkVariables,createAppController}=await Promise.resolve().then(()=>_interop_require_wildcard(require("./app.controller")));for(const[key,value]of Object.entries({...cfg,...override})){if(value){_vitest.vi.stubEnv(key,value.toString())}}const AppController=createAppController();const module=await _testing.Test.createTestingModule({controllers:[AppController],providers:[_allianceinternalnodeutilities.RedisHealthIndicator],imports:[_config.ConfigModule.forRoot({isGlobal:true,validate:_config1.zConfig.parse,ignoreEnvFile:true}),_terminus.TerminusModule,_allianceinternalnodeutilities.LoggerModule.forRoot(),_axios.HttpModule]}).compile();return{ctrl:module.get(AppController),module,GlobalFrameworkVariables}}(0,_vitest.beforeEach)(async()=>{mock=await setupMock()});(0,_vitest.afterEach)(async()=>{await mock.module.close()});(0,_vitest.it)("defines ctrl",()=>{(0,_vitest.expect)(mock.ctrl).toBeDefined()});(0,_vitest.describe)("cookiePolicy",()=>{(0,_vitest.it)("fetches using configured cookie policy url",async()=>{const http=mock.module.get(_axios.HttpService);const spy=_vitest.vi.spyOn(http.axiosRef,"get").mockResolvedValue({});await mock.ctrl.cookiePolicy();(0,_vitest.expect)(spy).toHaveBeenCalledWith("http://localhost:1234/cookie-policy.html")});(0,_vitest.it)("fetches using {WEBPROVISIONS_DISTRIBUTION_URL}/cookie-policy.html by default",async()=>{mock=await setupMock({[_config1.ConfigKeys.WebprovisionsDistributionCookiePolicyUrl]:undefined});const http=mock.module.get(_axios.HttpService);const spy=_vitest.vi.spyOn(http.axiosRef,"get").mockResolvedValue({});await mock.ctrl.cookiePolicy();(0,_vitest.expect)(spy).toHaveBeenCalledWith("http://localhost:1234/distribution/cookie-policy.html")})});(0,_vitest.describe)("health",()=>{(0,_vitest.it)("it calls health service check",async()=>{const health=mock.module.get(_terminus.HealthCheckService);const spy=_vitest.vi.spyOn(health,"check").mockResolvedValue({status:"ok",details:{}});await mock.ctrl.health();(0,_vitest.expect)(spy).toHaveBeenCalled()})});(0,_vitest.describe)("index",async()=>{function mockReq({objectId,query={}}){return{oidc:{user:{sub:objectId}},query}}(0,_vitest.afterEach)(()=>{_vitest.vi.clearAllMocks()});(0,_vitest.it)("calls graphql",async()=>{const{request}=await Promise.resolve().then(()=>_interop_require_wildcard(require("graphql-request")));await mock.ctrl.index(mockReq({objectId:"guid"}),"system");(0,_vitest.expect)(request).toHaveBeenCalledOnce();const[dbEndpoint,_,queryArgs]=request.mock.lastCall;(0,_vitest.expect)(dbEndpoint).toBe("http://localhost:1234/mocked-db");(0,_vitest.expect)(queryArgs).toEqual({objectId:"guid",workspaceSlug:"system"})});(0,_vitest.describe)("portal html",()=>{(0,_vitest.it)("returns portal for authorized user",async()=>{const result=await mock.ctrl.index(mockReq({objectId:"has-access"}),"");(0,_vitest.expect)(result).toContain("http://localhost:1234/distribution")});(0,_vitest.it)("returns unauthorized for unauthorized user",async()=>{const result=await mock.ctrl.index(mockReq({objectId:"does-not-have-access"}),"");(0,_vitest.expect)(result).toContain("unauthorized");(0,_vitest.expect)(result).toContain(401)});(0,_vitest.describe)("global framework variables",()=>{(0,_vitest.it)("sets correct variables with default config",async()=>{const result=await mock.ctrl.index(mockReq({objectId:"has-access"}),"the-workspace");(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.RuntimeRootUrl} = window.origin + '/the-workspace';`);(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.Workspace} = 'the-workspace';`);(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.Customer} = undefined;`)});(0,_vitest.it)("sets correct variables with workspace specified",async()=>{mock=await setupMock({[_config1.ConfigKeys.Workspace]:"static-ws"});const result=await mock.ctrl.index(mockReq({objectId:"has-access"}),"the-workspace");(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.RuntimeRootUrl} = window.origin + '/static-ws';`);(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.Workspace} = 'static-ws';`);(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.Customer} = undefined;`)});(0,_vitest.it)("sets correct variables with customer and workspace specified",async()=>{mock=await setupMock({[_config1.ConfigKeys.Customer]:"static-customer",[_config1.ConfigKeys.Workspace]:"static-ws"});const result=await mock.ctrl.index(mockReq({objectId:"has-access"}),"the-workspace");(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.RuntimeRootUrl} = window.origin + '/static-customer/static-ws';`);(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.Workspace} = 'static-ws';`);(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.Customer} = 'static-customer';`)});(0,_vitest.it)("sets correct variables with origin as root specified",async()=>{mock=await setupMock({[_config1.ConfigKeys.Customer]:"static-customer",[_config1.ConfigKeys.Workspace]:"static-ws",[_config1.ConfigKeys.OriginAsRootUrl]:true});const result=await mock.ctrl.index(mockReq({objectId:"has-access"}),"the-workspace");(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.RuntimeRootUrl} = window.origin;`);(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.Workspace} = 'static-ws';`);(0,_vitest.expect)(result).toContain(`window.${mock.GlobalFrameworkVariables.Customer} = 'static-customer';`)})})});(0,_vitest.describe)("webprovisions tags",()=>{(0,_vitest.it)("adds webprovisions tag if configured",async()=>{const result=await mock.ctrl.index(mockReq({objectId:"has-access"}),"");(0,_vitest.expect)(result).toContain('{"tag":"the-tag"}')});(0,_vitest.it)("does not add webprovisions tag if not configured",async()=>{mock=await setupMock({[_config1.ConfigKeys.WebprovisionsTag]:undefined});const result=await mock.ctrl.index(mockReq({objectId:"has-access"}),"");(0,_vitest.expect)(result).toContain("{}")});(0,_vitest.it)("does not add configured webprovisions tag when wp query strings are present",async()=>{const withTagQuery=await mock.ctrl.index(mockReq({objectId:"has-access",query:{"wp-tag":"some-tag"}}),"");(0,_vitest.expect)(withTagQuery).not.toContain('{"tag":"the-tag"}');const withVersionQuery=await mock.ctrl.index(mockReq({objectId:"has-access",query:{"wp-version":"some-version"}}),"");(0,_vitest.expect)(withVersionQuery).not.toContain('{"tag":"the-tag"}')})})})});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});const _axios=require("@nestjs/axios");const _config=require("@nestjs/config");const _terminus=require("@nestjs/terminus");const _testing=require("@nestjs/testing");const _allianceinternalnodeutilities=require("@telia-ace/alliance-internal-node-utilities");const _vitest=require("vitest");const _config1=require("./config");const _graphql=require("./graphql");function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interop_require_wildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={__proto__:null};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}_vitest.vi.mock("graphql-request",async()=>{return{request:_vitest.vi.fn().mockImplementation(async(_1,_2,{slug,objectId})=>{if(objectId==="has-access"){return{user:{id:objectId}}}if(slug==="exists"){return{workspace:{slug,name:"Exists"}}}if(slug==="system"){return{workspace:{slug,name:"System"}}}return})}});(0,_vitest.describe)("AppController",()=>{const cfg={[_config1.ConfigKeys.AuthAuthority]:"test authority",[_config1.ConfigKeys.AuthClientSecret]:"test client secret",[_config1.ConfigKeys.AuthClientId]:"test client id",[_config1.ConfigKeys.ServiceBaseUrl]:"http://base-url",[_config1.ConfigKeys.WebprovisionsDistributionUrl]:"http://localhost:1234/distribution",[_config1.ConfigKeys.WebprovisionsDistributionCookiePolicyUrl]:"http://localhost:1234/cookie-policy.html",[_config1.ConfigKeys.WebprovisionsTag]:"the-tag",[_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint]:"http://localhost:1234/mocked-db"};let mock;async function setupMock(override={}){_vitest.vi.unstubAllEnvs();const{createAppController}=await Promise.resolve().then(()=>_interop_require_wildcard(require("./app.controller")));for(const[key,value]of Object.entries({...cfg,...override})){if(value){_vitest.vi.stubEnv(key,value)}}const AppController=createAppController();const module=await _testing.Test.createTestingModule({controllers:[AppController],providers:[_allianceinternalnodeutilities.RedisHealthIndicator],imports:[_config.ConfigModule.forRoot({isGlobal:true,validate:_config1.zConfig.parse,ignoreEnvFile:true}),_terminus.TerminusModule,_allianceinternalnodeutilities.LoggerModule.forRoot({logLevel:"silent"}),_axios.HttpModule]}).compile();return{ctrl:module.get(AppController),module}}(0,_vitest.beforeEach)(async()=>{mock=await setupMock()});(0,_vitest.afterEach)(async()=>{await mock.module.close()});(0,_vitest.it)("defines ctrl",()=>{(0,_vitest.expect)(mock.ctrl).toBeDefined()});(0,_vitest.describe)("cookiePolicy",()=>{(0,_vitest.it)("fetches using configured cookie policy url",async()=>{const http=mock.module.get(_axios.HttpService);const spy=_vitest.vi.spyOn(http.axiosRef,"get").mockResolvedValue({});await mock.ctrl.cookiePolicy();(0,_vitest.expect)(spy).toHaveBeenCalledWith("http://localhost:1234/cookie-policy.html")});(0,_vitest.it)("fetches using {WEBPROVISIONS_DISTRIBUTION_URL}/cookie-policy.html by default",async()=>{mock=await setupMock({[_config1.ConfigKeys.WebprovisionsDistributionCookiePolicyUrl]:undefined});const http=mock.module.get(_axios.HttpService);const spy=_vitest.vi.spyOn(http.axiosRef,"get").mockResolvedValue({});await mock.ctrl.cookiePolicy();(0,_vitest.expect)(spy).toHaveBeenCalledWith("http://localhost:1234/distribution/cookie-policy.html")})});(0,_vitest.describe)("health",()=>{(0,_vitest.it)("it calls health service check",async()=>{const health=mock.module.get(_terminus.HealthCheckService);const spy=_vitest.vi.spyOn(health,"check").mockResolvedValue({status:"ok",details:{}});await mock.ctrl.health();(0,_vitest.expect)(spy).toHaveBeenCalled()})});(0,_vitest.describe)("portal",async()=>{function mockReqRes({objectId,query={}}){const req={oidc:{user:{sub:objectId}},query};const res={statusCode:0,status:code=>{res.statusCode=code;return res},send:r=>r};return[req,res]}(0,_vitest.afterEach)(()=>{_vitest.vi.clearAllMocks()});(0,_vitest.it)("calls graphql",async()=>{const{request}=await Promise.resolve().then(()=>_interop_require_wildcard(require("graphql-request")));const[req,res]=mockReqRes({objectId:"guid"});await mock.ctrl.portal(req,res,"exists");(0,_vitest.expect)(request).toHaveBeenCalledTimes(2);const[firstCall,secondCall]=request.mock.calls;const[firstUrl,firstDocument,firstArgs]=firstCall;const[_,secondDocument,secondArgs]=secondCall;(0,_vitest.expect)(firstUrl).toBe("http://localhost:1234/mocked-db");(0,_vitest.expect)(firstDocument).toEqual(_graphql.GetWorkspaceDocument);(0,_vitest.expect)(firstArgs).toEqual({slug:"exists"});(0,_vitest.expect)(secondDocument).toEqual(_graphql.GetUserDocument);(0,_vitest.expect)(secondArgs).toEqual({objectId:"guid",workspaceSlug:"exists"})});(0,_vitest.it)("returns 200 for authorized user",async()=>{const[req,res]=mockReqRes({objectId:"has-access"});const result=await mock.ctrl.portal(req,res,"exists");(0,_vitest.expect)(result).toContain("http://localhost:1234/distribution");(0,_vitest.expect)(res.statusCode).toBe(200)});(0,_vitest.it)("returns 401 for unauthorized user",async()=>{const[req,res]=mockReqRes({objectId:"does-not-have-access"});const result=await mock.ctrl.portal(req,res,"exists");(0,_vitest.expect)(result).toContain("You don't have permission to access Workspace");(0,_vitest.expect)(res.statusCode).toBe(401)});(0,_vitest.it)("returns 404 for non existant workspace",async()=>{const[req,res]=mockReqRes({objectId:"does-not-have-access"});const result=await mock.ctrl.portal(req,res,"doesnt-exist");(0,_vitest.expect)(result).toContain("The Workspace 'doesnt-exist' does not exist");(0,_vitest.expect)(res.statusCode).toBe(404)});(0,_vitest.describe)("web page title",()=>{(0,_vitest.it)("correct for regular workspace",async()=>{const[req,res]=mockReqRes({objectId:"has-access"});const result=await mock.ctrl.portal(req,res,"exists");(0,_vitest.expect)(result).toContain("<title>ACE Customer Portal - Exists</title>")});(0,_vitest.it)("correct for system",async()=>{const[req,res]=mockReqRes({objectId:"has-access"});const result=await mock.ctrl.portal(req,res,"system");(0,_vitest.expect)(result).toContain("<title>ACE Enterprise Portal</title>")})});(0,_vitest.describe)("webprovisions tags",()=>{(0,_vitest.it)("adds webprovisions tag if configured",async()=>{const[req,res]=mockReqRes({objectId:"has-access"});const result=await mock.ctrl.portal(req,res,"exists");(0,_vitest.expect)(result).toContain('{"tag":"the-tag"}')});(0,_vitest.it)("does not add webprovisions tag if not configured",async()=>{mock=await setupMock({[_config1.ConfigKeys.WebprovisionsTag]:undefined});const[req,res]=mockReqRes({objectId:"has-access"});const result=await mock.ctrl.portal(req,res,"exists");(0,_vitest.expect)(result).toContain("{}")});(0,_vitest.it)("does not add configured webprovisions tag when wp query strings are present",async()=>{let[req,res]=mockReqRes({objectId:"has-access",query:{"wp-tag":"some-tag"}});const withTagQuery=await mock.ctrl.portal(req,res,"exists");(0,_vitest.expect)(withTagQuery).not.toContain('{"tag":"the-tag"}');[req,res]=mockReqRes({objectId:"has-access",query:{"wp-version":"some-version"}});const withVersionQuery=await mock.ctrl.portal(req,res,"exists");(0,_vitest.expect)(withVersionQuery).not.toContain('{"tag":"the-tag"}')})});(0,_vitest.describe)("landing page",()=>{(0,_vitest.it)("returns landing page on url root by default",async()=>{const[req,res]=mockReqRes({objectId:"has-access"});const result=await mock.ctrl.index(req,res,"exists");(0,_vitest.expect)(result).toContain("https://embed.webprovisions.io/resource/alliance/landing-page")});(0,_vitest.it)("returns portal with landing page set to false",async()=>{mock=await setupMock({[_config1.ConfigKeys.LandingPage]:"false"});const[req,res]=mockReqRes({objectId:"has-access"});const result=await mock.ctrl.portal(req,res,"exists");(0,_vitest.expect)(result).toContain("http://localhost:1234/distribution")})})})});
package/dist/auth.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"auth",{enumerable:true,get:function(){return auth}});const _allianceinternalnodeutilities=require("@telia-ace/alliance-internal-node-utilities");const _graphqlrequest=require("graphql-request");const _jose=require("jose");const _config=require("./config");const _graphql=require("./graphql");function auth(configService,logger){const middleware=(0,_allianceinternalnodeutilities.authMiddleware)(configService,{baseURL:configService.getOrThrow(_config.ConfigKeys.ServiceBaseUrl).replace("{{port}}",configService.getOrThrow(_allianceinternalnodeutilities.SharedConfigKeys.ServicePort)),clientSecret:configService.getOrThrow(_config.ConfigKeys.AuthClientSecret),clientID:configService.getOrThrow(_config.ConfigKeys.AuthClientId),authorizationParams:{response_type:configService.getOrThrow(_config.ConfigKeys.AuthResponseType),scope:configService.getOrThrow(_config.ConfigKeys.AuthScopes)},sessionCookiePath:configService.get(_config.ConfigKeys.AuthCookiePath),issuerBaseURL:`${configService.getOrThrow(_config.ConfigKeys.AuthAuthority)}/.well-known/openid-configuration`,async afterCallback(_,__,session){const claims=(0,_jose.decodeJwt)(session.id_token);const user={displayName:claims.name||"Empty displayName",email:claims.email||claims.emails[0]||"Empty email",objectId:claims.sub||claims.oid};logger.trace("decoded JWT and mapped claims to user, getting or creating user in database",{claims,user});try{await (0,_graphqlrequest.request)(configService.getOrThrow(_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint),_graphql.GetOrCreateUserDocument,{input:user},{authorization:(0,_allianceinternalnodeutilities.createSystemUserToken)(configService)});logger.trace("added user to database, if it did not already exist")}catch{}if(!configService.get(_config.ConfigKeys.AuthSkipGroupClaimCheck)){const type=hasEnterpriseAdminRole(claims)?"system-admin":"user";logger.trace("updating user type according to user claims",{type});try{await (0,_graphqlrequest.request)(configService.getOrThrow(_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint),_graphql.SetUserTypeDocument,{input:{objectId:user.objectId,type}},{authorization:(0,_allianceinternalnodeutilities.createSystemUserToken)(configService)});logger.trace("user type updated")}catch{}}return session}});return(req,res,next)=>{if(req.url.startsWith("/health")){return next()}return middleware(req,res,next)}}function hasEnterpriseAdminRole(claims){if(!claims.groups){return false}const aceEnterpriseAdminRoleId="PROD_ACE_Enterprise_Admins";return claims.groups.includes(aceEnterpriseAdminRoleId)}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:all[name]})}_export(exports,{afterCallbackHandler:function(){return afterCallbackHandler},auth:function(){return auth}});const _allianceinternalnodeutilities=require("@telia-ace/alliance-internal-node-utilities");const _graphqlrequest=require("graphql-request");const _jose=require("jose");const _config=require("./config");const _graphql=require("./graphql");function auth(configService,logger){const middleware=(0,_allianceinternalnodeutilities.authMiddleware)(configService,{baseURL:configService.getOrThrow(_config.ConfigKeys.ServiceBaseUrl).replace("{{port}}",configService.getOrThrow(_allianceinternalnodeutilities.SharedConfigKeys.ServicePort)),clientSecret:configService.getOrThrow(_config.ConfigKeys.AuthClientSecret),clientID:configService.getOrThrow(_config.ConfigKeys.AuthClientId),authorizationParams:{response_type:configService.getOrThrow(_config.ConfigKeys.AuthResponseType),scope:configService.getOrThrow(_config.ConfigKeys.AuthScopes)},sessionCookiePath:configService.get(_config.ConfigKeys.AuthCookiePath),issuerBaseURL:`${configService.getOrThrow(_config.ConfigKeys.AuthAuthority)}/.well-known/openid-configuration`,afterCallback:afterCallbackHandler(configService,logger)});const landingPage=configService.getOrThrow(_config.ConfigKeys.LandingPage);return(req,res,next)=>{if(req.path.endsWith("/-/health")){return next()}if(landingPage&&req.path==="/"){return next()}return middleware(req,res,next)}}function afterCallbackHandler(configService,logger){return async(_,__,session)=>{const claims=(0,_jose.decodeJwt)(session.id_token);const user={displayName:claims.name||"Empty displayName",email:claims.email||claims.emails[0]||"Empty email",objectId:claims.sub||claims.oid};const skipGroupClaimCheck=configService.getOrThrow(_config.ConfigKeys.AuthSkipGroupClaimCheck);logger.trace("decoded JWT and mapped claims to user, getting or creating user in database, setting user type if configured to",{claims,user,skipGroupClaimCheck});try{await (0,_graphqlrequest.request)(configService.getOrThrow(_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint),_graphql.GetOrCreateUserDocument,{input:user},{authorization:(0,_allianceinternalnodeutilities.createSystemUserToken)(configService)});logger.trace("added user to database, if it did not already exist")}catch{}if(!skipGroupClaimCheck){const type=hasEnterpriseAdminRole(claims)?"system-admin":"user";logger.trace("updating user type according to user claims",{type});try{await (0,_graphqlrequest.request)(configService.getOrThrow(_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint),_graphql.SetUserTypeDocument,{input:{objectId:user.objectId,type}},{authorization:(0,_allianceinternalnodeutilities.createSystemUserToken)(configService)});logger.trace("user type updated")}catch{}}return session}}function hasEnterpriseAdminRole(claims){if(!claims.groups){return false}const aceEnterpriseAdminRoleId="PROD_ACE_Enterprise_Admins";return claims.groups.includes(aceEnterpriseAdminRoleId)}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});const _config=require("@nestjs/config");const _testing=require("@nestjs/testing");const _allianceinternalnodeutilities=require("@telia-ace/alliance-internal-node-utilities");const _vitest=require("vitest");const _config1=require("./config");const _graphql=require("./graphql");function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interop_require_wildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={__proto__:null};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}_vitest.vi.mock("graphql-request",async()=>{return{request:_vitest.vi.fn()}});_vitest.vi.mock("jose",async()=>{return{decodeJwt:_vitest.vi.fn().mockImplementation(t=>{return{name:"test name",email:"test email",sub:"test sub",groups:t.includes("system-admin")?["PROD_ACE_Enterprise_Admins"]:[]}})}});(0,_vitest.describe)("afterCallback",()=>{const cfg={AUTH_AUTHORITY:"test authority",AUTH_CLIENT_SECRET:"test client secret",AUTH_CLIENT_ID:"test client id",SERVICE_BASE_URL:"http://base-url",WEBPROVISIONS_DISTRIBUTION_URL:"http://localhost:1234/distribution",WEBPROVISIONS_DISTRIBUTION_COOKIE_POLICY_URL:"http://localhost:1234/cookie-policy.html",WEBPROVISIONS_TAG:"the-tag",DB_ENDPOINT:"http://localhost:1234/mocked-db"};let mock;async function setupMock(override={}){_vitest.vi.unstubAllEnvs();for(const[key,value]of Object.entries({...cfg,...override})){if(value){_vitest.vi.stubEnv(key,value)}}const module=await _testing.Test.createTestingModule({imports:[_config.ConfigModule.forRoot({isGlobal:true,validate:_config1.zConfig.parse,ignoreEnvFile:true})]}).compile();const configService=module.get(_config.ConfigService);const{afterCallbackHandler}=await Promise.resolve().then(()=>_interop_require_wildcard(require("./auth")));return{afterCallback:afterCallbackHandler(module.get(_config.ConfigService),{log:_vitest.vi.fn(),trace:_vitest.vi.fn(),debug:_vitest.vi.fn(),info:_vitest.vi.fn(),warn:_vitest.vi.fn(),error:_vitest.vi.fn(),fatal:_vitest.vi.fn()}),configService}}(0,_vitest.beforeEach)(async()=>{mock=await setupMock()});(0,_vitest.afterEach)(()=>{_vitest.vi.clearAllMocks()});async function getMockedGQLRequest(){const{request}=await Promise.resolve().then(()=>_interop_require_wildcard(require("graphql-request")));return{request,calls:request.mock.calls.map(c=>({url:c[0],document:c[1],args:c[2]}))}}(0,_vitest.it)("calls getOrCreateUser and setUserType graphql endpoints",async()=>{await mock.afterCallback({},{},{id_token:"asdf"},{});const{request,calls}=await getMockedGQLRequest();(0,_vitest.expect)(request).toHaveBeenCalledTimes(2);(0,_vitest.expect)(calls[0].url).toBe(mock.configService.get(_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint));(0,_vitest.expect)(calls[0].document).toEqual(_graphql.GetOrCreateUserDocument);(0,_vitest.expect)(calls[0].args).toEqual({input:{displayName:"test name",email:"test email",objectId:"test sub"}});(0,_vitest.expect)(calls[1].url).toBe(mock.configService.get(_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint));(0,_vitest.expect)(calls[1].document).toEqual(_graphql.SetUserTypeDocument);(0,_vitest.expect)(calls[1].args).toEqual({input:{type:"user",objectId:"test sub"}})});(0,_vitest.it)("calls setUserType with system-admin with correct claims",async()=>{await mock.afterCallback({},{},{id_token:"system-admin"},{});const{request,calls}=await getMockedGQLRequest();(0,_vitest.expect)(request).toHaveBeenCalledTimes(2);(0,_vitest.expect)(calls[1].document).toEqual(_graphql.SetUserTypeDocument);(0,_vitest.expect)(calls[1].args).toEqual({input:{type:"system-admin",objectId:"test sub"}})});(0,_vitest.it)("does not call setUserType if configured not to",async()=>{mock=await setupMock({AUTH_SKIP_GROUP_CLAIM_CHECK:"true"});await mock.afterCallback({},{},{id_token:"asdf"},{});const{request,calls}=await getMockedGQLRequest();(0,_vitest.expect)(request).toHaveBeenCalledOnce();(0,_vitest.expect)(calls[0].document).not.toEqual(_graphql.SetUserTypeDocument)})});
package/dist/config.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:all[name]})}_export(exports,{ConfigKeys:function(){return ConfigKeys},zConfig:function(){return zConfig}});const _allianceinternalnodeutilities=require("@telia-ace/alliance-internal-node-utilities");var ConfigKeys;(function(ConfigKeys){ConfigKeys["AuthScopes"]="AUTH_SCOPES";ConfigKeys["AuthAuthority"]="AUTH_AUTHORITY";ConfigKeys["AuthClientSecret"]="AUTH_CLIENT_SECRET";ConfigKeys["AuthClientId"]="AUTH_CLIENT_ID";ConfigKeys["AuthResponseType"]="AUTH_RESPONSE_TYPE";ConfigKeys["AuthSkipGroupClaimCheck"]="AUTH_SKIP_GROUP_CLAIM_CHECK";ConfigKeys["AuthCookiePath"]="AUTH_COOKIE_PATH";ConfigKeys["ServiceBaseUrl"]="SERVICE_BASE_URL";ConfigKeys["WebprovisionsTag"]="WEBPROVISIONS_TAG";ConfigKeys["WebprovisionsDistributionUrl"]="WEBPROVISIONS_DISTRIBUTION_URL";ConfigKeys["WebprovisionsDistributionCookiePolicyUrl"]="WEBPROVISIONS_DISTRIBUTION_COOKIE_POLICY_URL";ConfigKeys["Customer"]="CUSTOMER";ConfigKeys["Workspace"]="WORKSPACE";ConfigKeys["OriginAsRootUrl"]="ORIGIN_AS_ROOT_URL"})(ConfigKeys||(ConfigKeys={}));const zConfig=_allianceinternalnodeutilities.zSharedConfig.extend({["AUTH_SCOPES"]:_allianceinternalnodeutilities.zNonEmptyString.default("openid"),["AUTH_AUTHORITY"]:_allianceinternalnodeutilities.zNonEmptyString,["AUTH_CLIENT_SECRET"]:_allianceinternalnodeutilities.zNonEmptyString,["AUTH_CLIENT_ID"]:_allianceinternalnodeutilities.zNonEmptyString,["AUTH_RESPONSE_TYPE"]:_allianceinternalnodeutilities.zNonEmptyString.default("code"),["AUTH_SKIP_GROUP_CLAIM_CHECK"]:_allianceinternalnodeutilities.zBooleanEnum.default("false"),["AUTH_COOKIE_PATH"]:_allianceinternalnodeutilities.zNonEmptyString.optional(),["SERVICE_BASE_URL"]:_allianceinternalnodeutilities.zNonEmptyString,["WEBPROVISIONS_TAG"]:_allianceinternalnodeutilities.zNonEmptyString.optional(),["WEBPROVISIONS_DISTRIBUTION_URL"]:_allianceinternalnodeutilities.zNonEmptyString,["WEBPROVISIONS_DISTRIBUTION_COOKIE_POLICY_URL"]:_allianceinternalnodeutilities.zNonEmptyString.optional(),["CUSTOMER"]:_allianceinternalnodeutilities.zNonEmptyString.optional(),["WORKSPACE"]:_allianceinternalnodeutilities.zNonEmptyString.optional(),["ORIGIN_AS_ROOT_URL"]:_allianceinternalnodeutilities.zBooleanEnum.default("false")});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:all[name]})}_export(exports,{ConfigKeys:function(){return ConfigKeys},zConfig:function(){return zConfig}});const _allianceinternalnodeutilities=require("@telia-ace/alliance-internal-node-utilities");const _zod=require("zod");var ConfigKeys;(function(ConfigKeys){ConfigKeys["AuthScopes"]="AUTH_SCOPES";ConfigKeys["AuthAuthority"]="AUTH_AUTHORITY";ConfigKeys["AuthClientSecret"]="AUTH_CLIENT_SECRET";ConfigKeys["AuthClientId"]="AUTH_CLIENT_ID";ConfigKeys["AuthResponseType"]="AUTH_RESPONSE_TYPE";ConfigKeys["AuthSkipGroupClaimCheck"]="AUTH_SKIP_GROUP_CLAIM_CHECK";ConfigKeys["AuthCookiePath"]="AUTH_COOKIE_PATH";ConfigKeys["ServiceBaseUrl"]="SERVICE_BASE_URL";ConfigKeys["WebprovisionsTag"]="WEBPROVISIONS_TAG";ConfigKeys["WebprovisionsDistributionUrl"]="WEBPROVISIONS_DISTRIBUTION_URL";ConfigKeys["WebprovisionsDistributionCookiePolicyUrl"]="WEBPROVISIONS_DISTRIBUTION_COOKIE_POLICY_URL";ConfigKeys["Customer"]="CUSTOMER";ConfigKeys["Workspace"]="WORKSPACE";ConfigKeys["RootUrlSubPath"]="ROOT_URL_SUB_PATH";ConfigKeys["LandingPage"]="LANDING_PAGE"})(ConfigKeys||(ConfigKeys={}));const zConfig=_allianceinternalnodeutilities.zSharedConfig.extend({["AUTH_SCOPES"]:_allianceinternalnodeutilities.zNonEmptyString.default("openid"),["AUTH_AUTHORITY"]:_allianceinternalnodeutilities.zNonEmptyString,["AUTH_CLIENT_SECRET"]:_allianceinternalnodeutilities.zNonEmptyString,["AUTH_CLIENT_ID"]:_allianceinternalnodeutilities.zNonEmptyString,["AUTH_RESPONSE_TYPE"]:_allianceinternalnodeutilities.zNonEmptyString.default("code"),["AUTH_SKIP_GROUP_CLAIM_CHECK"]:_allianceinternalnodeutilities.zBooleanEnum.default("false"),["AUTH_COOKIE_PATH"]:_allianceinternalnodeutilities.zNonEmptyString.optional(),["SERVICE_BASE_URL"]:_allianceinternalnodeutilities.zNonEmptyString,["WEBPROVISIONS_TAG"]:_allianceinternalnodeutilities.zNonEmptyString.optional(),["WEBPROVISIONS_DISTRIBUTION_URL"]:_allianceinternalnodeutilities.zNonEmptyString,["WEBPROVISIONS_DISTRIBUTION_COOKIE_POLICY_URL"]:_allianceinternalnodeutilities.zNonEmptyString.optional(),["CUSTOMER"]:_allianceinternalnodeutilities.zNonEmptyString.optional(),["WORKSPACE"]:_allianceinternalnodeutilities.zNonEmptyString.optional(),["ROOT_URL_SUB_PATH"]:_zod.z.string().default("/{{workspace}}"),["LANDING_PAGE"]:_allianceinternalnodeutilities.zBooleanEnum.default("true")});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:all[name]})}_export(exports,{GetOrCreateUserDocument:function(){return GetOrCreateUserDocument},GetUserDocument:function(){return GetUserDocument},SetUserTypeDocument:function(){return SetUserTypeDocument}});const GetOrCreateUserDocument={"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GetOrCreateUser"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"GetOrCreateUserInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getOrCreateUser"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"objectId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}}]}}]};const SetUserTypeDocument={"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SetUserType"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SetUserTypeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"setUserType"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]};const GetUserDocument={"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetUser"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"objectId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceSlug"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"objectId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"objectId"}}},{"kind":"Argument","name":{"kind":"Name","value":"workspaceSlug"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceSlug"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:all[name]})}_export(exports,{GetOrCreateUserDocument:function(){return GetOrCreateUserDocument},GetUserDocument:function(){return GetUserDocument},GetWorkspaceDocument:function(){return GetWorkspaceDocument},SetUserTypeDocument:function(){return SetUserTypeDocument}});const GetOrCreateUserDocument={"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GetOrCreateUser"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"GetOrCreateUserInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getOrCreateUser"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"objectId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}}]}}]};const SetUserTypeDocument={"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SetUserType"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SetUserTypeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"setUserType"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]};const GetUserDocument={"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetUser"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"objectId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceSlug"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"objectId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"objectId"}}},{"kind":"Argument","name":{"kind":"Name","value":"workspaceSlug"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceSlug"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]};const GetWorkspaceDocument={"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetWorkspace"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"slug"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspace"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"slug"},"value":{"kind":"Variable","name":{"kind":"Name","value":"slug"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"slug"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]};
package/dist/html.js ADDED
@@ -0,0 +1,174 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:all[name]})}_export(exports,{GlobalFrameworkVariables:function(){return GlobalFrameworkVariables},embedScript:function(){return embedScript},errorBody:function(){return errorBody},globalVariables:function(){return globalVariables},htmlTemplate:function(){return htmlTemplate},loaderHtml:function(){return loaderHtml}});const _config=require("./config");var GlobalFrameworkVariables;(function(GlobalFrameworkVariables){GlobalFrameworkVariables["RuntimeRootUrl"]="__ALLIANCE_RUNTIME_ROOT_URL";GlobalFrameworkVariables["Workspace"]="__ALLIANCE_WORKSPACE";GlobalFrameworkVariables["Customer"]="__ALLIANCE_CUSTOMER"})(GlobalFrameworkVariables||(GlobalFrameworkVariables={}));function errorBody(code,message){return`
2
+ <div class="error">
3
+ <h1>${code}</h1>
4
+ <p>${message}</p>
5
+ </div>
6
+ <style>
7
+ @import 'https://cdn.voca.teliacompany.com/fonts/TeliaSansV10/TeliaSans.css';
8
+ .error {
9
+ position: absolute;
10
+ inset: 0;
11
+ display: flex;
12
+ flex-direction: column;
13
+ gap: 1em;
14
+ justify-content: center;
15
+ align-items: center;
16
+ }
17
+
18
+ h1 {
19
+ font-family: TeliaSansHeading, TeliaSans, HelveticaNeue, Helvetica, Arial, sans-serif;
20
+ color: #e4175c;
21
+ font-size: 4em;
22
+ margin: 0;
23
+ }
24
+
25
+ p {
26
+ font-family: TeliaSans, Helvetica, Arial, Lucida Grande, sans-serif;
27
+ font-size: 2em;
28
+ margin: 0;
29
+ }
30
+ </style>
31
+ `}function htmlTemplate(title,...htmlParts){return`
32
+ <!DOCTYPE html>
33
+ <html lang="en">
34
+
35
+ <head>
36
+ <meta charset="UTF-8" />
37
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
38
+ <title>${title}</title>
39
+ <link rel="icon"
40
+ 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/2a3E4UlOLt2jYCeCGE+cBBuPhdk2gZjDjjmS46KkampelnEhMPhwy3/PkGb/vhXPO4zGJ60KyTo5nPpk8wg5wPz57M13Z3PuGzRtTxEovV3BBoXlZKrytvZqmpSknKhVCJ3tGwu2rBxjYHzrEymUZw9Py0LQtD6yb7aG8CoR/mNgKs1LHEomJ4M2M9McDf9PX0n7eI9OpbXEVxQCFE5F/d+0Zf+iPgy7e/GPDjVj9rGXJcO7D6b+yLu7vABavrd10/O8jz5/cFqXNFBGr1HYzQ0SoviEIm5dXceOXpvGJpSkNEjJuGy+ciPzu7nN+/4aCRkM2vsaUrM/coH7ed9Ond3WffbPyF8CxQ/1Y5F8b/C9fHthlFPvFB05JNzqtvSnBxxYmmN4UVCwe60b/7mK4d/15Dr82qH50fHkva/fiSc00v/SlGr97fX79ytdb1owjAHDwX71tVbWuJ9OQdMl0gmTKESQUVWGsxQDD/ZE/snnIH/xdgVP/KU5yqCnBi2f6bPF3b6jxe17Mhx9sKizsyLceKPeqDP7bF/rfa2xLvHrLN6sfmr08o0GDqAaCIYRD3g/sD/1Hb49w7K1hev89otEoTi6To+V5n3l3Mryru1r3vpjn8KbCZjU5MLbfuBCd2VyzIHsTgauZ3pAkkXIanScc6Tf1RfRiJyYHN4Iq/O2PZ/zc71Rpz89P+30bz4QmdltHvvXQpARKJB5R0w0XSvL4cjwV+FnLU+HiZ2tUpxtbf9Tnj20vOJPo2fZ8688u7n3pmdB42Yt/xUuESVQ+yVJexZNtVmbQ2JYIH9zcGC5/pd71Hxjxm5f1cnzboDPx7xs8M9G4CSV1ZnOZICE7GNXbKweTMU7EA6USoemeVLhgTYame1Nu4MBI2PN0ng+3DDovIZFG5w37bEe+dc+UCQC8/ZtjzX07i/88saU4J8yLXiAhaCC+fn7Sz/7iNFq+mqZ6TuD6do+Gu7vPcuQvBRf62LlIQ2/Y1zvyra9OhnPZSf1g58k5I6ftDSnqnNFTaOACqmclfP0tSa3KBjrc5/2Hbwz7Q38ocHLniDM8XjxeIrxG3rA16vXXj529dVKMK2bVL2fkmhrmJ/9cPy91Z2ZGwhMqQx95TudC8gdCZx4obbMVAhqNGvaoCr99bKD1svGntK4647vg84J8X021PBXlK5gJGJWr11GDb3fkW7dPJfaUi3539iARxSUCz4AsERMVpHwDxMTyhq0HftGRbz071bhXfeooXVJvBR4EbgSGgR6Bt9qvArjc/gfZzPoCTDB+AgAAAABJRU5ErkJggg==" />
41
+ </head>
42
+
43
+ <body>
44
+ ${htmlParts.join("")}
45
+ </body>
46
+
47
+ </html>
48
+ `}function embedScript(url,opts={}){return`
49
+ <script>
50
+ /* WEBPROVISIONS */
51
+ !function(e,n){var o=n||{},c=document,t=window,s=function(n,o){e+=(e.indexOf("?")>-1?"&":"?")+encodeURIComponent(n)+"="
52
+ +encodeURIComponent(o)},i=/[?&]{1}(wp[^=]*)=([^&#]*)/g,r=c.getElementsByTagName("script")[0],p=c.createElement("script");p.type="module";e=e+"/index.js";
53
+ for(t.webprovisions=t.webprovisions||{_c:[],configure:function(){t.webprovisions._c.push(arguments)}};matches=i.exec(t.location.search);)
54
+ s(matches[1],matches[2]);Object.keys(o).forEach((function(e){s("wp-"+e,o[e])})),p.async=!0,p.src=e,r.parentNode.insertBefore(p,r)}
55
+ /**
56
+ * Configure the implementation by specifying a remote endpoint with optional arguments.
57
+ * url - The url to the remote endpoint for the implementation.
58
+ * args - Object containing optional arguments for the implementation.
59
+ */
60
+ ("${url}", ${JSON.stringify(opts)})
61
+ </script>
62
+ `}function loaderHtml(){return`
63
+ <style>
64
+ .alliance-portal-loader-wrapper {
65
+ position: fixed;
66
+ inset: 0;
67
+ display: flex;
68
+ justify-content: center;
69
+ align-items: center;
70
+ }
71
+ .alliance-portal-loader {
72
+ display: inline-block;
73
+ position: relative;
74
+ width: 80px;
75
+ height: 80px;
76
+ }
77
+ .alliance-portal-loader div {
78
+ animation: alliance-portal-loader 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
79
+ transform-origin: 40px 40px;
80
+ }
81
+ .alliance-portal-loader div:after {
82
+ content: ' ';
83
+ display: block;
84
+ position: absolute;
85
+ width: 7px;
86
+ height: 7px;
87
+ border-radius: 50%;
88
+ background: #29003e;
89
+ margin: -4px 0 0 -4px;
90
+ }
91
+ .alliance-portal-loader div:nth-child(1) {
92
+ animation-delay: -0.036s;
93
+ }
94
+ .alliance-portal-loader div:nth-child(1):after {
95
+ top: 63px;
96
+ left: 63px;
97
+ }
98
+ .alliance-portal-loader div:nth-child(2) {
99
+ animation-delay: -0.072s;
100
+ }
101
+ .alliance-portal-loader div:nth-child(2):after {
102
+ top: 68px;
103
+ left: 56px;
104
+ }
105
+ .alliance-portal-loader div:nth-child(3) {
106
+ animation-delay: -0.108s;
107
+ }
108
+ .alliance-portal-loader div:nth-child(3):after {
109
+ top: 71px;
110
+ left: 48px;
111
+ }
112
+ .alliance-portal-loader div:nth-child(4) {
113
+ animation-delay: -0.144s;
114
+ }
115
+ .alliance-portal-loader div:nth-child(4):after {
116
+ top: 72px;
117
+ left: 40px;
118
+ }
119
+ .alliance-portal-loader div:nth-child(5) {
120
+ animation-delay: -0.18s;
121
+ }
122
+ .alliance-portal-loader div:nth-child(5):after {
123
+ top: 71px;
124
+ left: 32px;
125
+ }
126
+ .alliance-portal-loader div:nth-child(6) {
127
+ animation-delay: -0.216s;
128
+ }
129
+ .alliance-portal-loader div:nth-child(6):after {
130
+ top: 68px;
131
+ left: 24px;
132
+ }
133
+ .alliance-portal-loader div:nth-child(7) {
134
+ animation-delay: -0.252s;
135
+ }
136
+ .alliance-portal-loader div:nth-child(7):after {
137
+ top: 63px;
138
+ left: 17px;
139
+ }
140
+ .alliance-portal-loader div:nth-child(8) {
141
+ animation-delay: -0.288s;
142
+ }
143
+ .alliance-portal-loader div:nth-child(8):after {
144
+ top: 56px;
145
+ left: 12px;
146
+ }
147
+ @keyframes alliance-portal-loader {
148
+ 0% {
149
+ transform: rotate(0deg);
150
+ }
151
+ 100% {
152
+ transform: rotate(360deg);
153
+ }
154
+ }
155
+ </style>
156
+ <div class="alliance-portal-loader-wrapper">
157
+ <div class="alliance-portal-loader">
158
+ <div></div>
159
+ <div></div>
160
+ <div></div>
161
+ <div></div>
162
+ <div></div>
163
+ <div></div>
164
+ <div></div>
165
+ <div></div>
166
+ </div>
167
+ </div>
168
+ `}function globalVariables(configService,workspaceSlug){const environmentCustomer=configService.get(_config.ConfigKeys.Customer);const rootUrlSubPath=configService.getOrThrow(_config.ConfigKeys.RootUrlSubPath);const rootUrl=rootUrlSubPath==="/"?"window.origin":`window.origin + '${rootUrlSubPath.replace("{{customer}}",environmentCustomer||"").replace("{{workspace}}",workspaceSlug)}'`;return`
169
+ <script>
170
+ window.${"__ALLIANCE_RUNTIME_ROOT_URL"} = ${rootUrl};
171
+ window.${"__ALLIANCE_WORKSPACE"} = '${workspaceSlug}';
172
+ window.${"__ALLIANCE_CUSTOMER"} = ${environmentCustomer?`'${environmentCustomer}'`:"undefined"};
173
+ </script>
174
+ `}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});const _config=require("@nestjs/config");const _testing=require("@nestjs/testing");const _allianceinternalnodeutilities=require("@telia-ace/alliance-internal-node-utilities");const _vitest=require("vitest");const _config1=require("./config");const _html=require("./html");(0,_vitest.describe)("html utilities",()=>{const cfg={[_config1.ConfigKeys.AuthAuthority]:"test authority",[_config1.ConfigKeys.AuthClientSecret]:"test client secret",[_config1.ConfigKeys.AuthClientId]:"test client id",[_config1.ConfigKeys.ServiceBaseUrl]:"http://base-url",[_config1.ConfigKeys.WebprovisionsDistributionUrl]:"http://localhost:1234/distribution",[_config1.ConfigKeys.WebprovisionsDistributionCookiePolicyUrl]:"http://localhost:1234/cookie-policy.html",[_config1.ConfigKeys.WebprovisionsTag]:"the-tag",[_allianceinternalnodeutilities.SharedConfigKeys.DbEndpoint]:"http://localhost:1234/mocked-db"};let mock;async function setupMock(override={}){_vitest.vi.unstubAllEnvs();for(const[key,value]of Object.entries({...cfg,...override})){if(value){_vitest.vi.stubEnv(key,value)}}const module=await _testing.Test.createTestingModule({imports:[_config.ConfigModule.forRoot({isGlobal:true,validate:_config1.zConfig.parse,ignoreEnvFile:true})]}).compile();return module.get(_config.ConfigService)}(0,_vitest.beforeEach)(async()=>{mock=await setupMock()});(0,_vitest.describe)("globalVariables",()=>{(0,_vitest.it)("with default config",async()=>{const result=(0,_html.globalVariables)(mock,"the-workspace");(0,_vitest.expect)(result).toContain(`window.${_html.GlobalFrameworkVariables.RuntimeRootUrl} = window.origin + '/the-workspace';`);(0,_vitest.expect)(result).toContain(`window.${_html.GlobalFrameworkVariables.Workspace} = 'the-workspace';`);(0,_vitest.expect)(result).toContain(`window.${_html.GlobalFrameworkVariables.Customer} = undefined;`)});(0,_vitest.it)("with customer and workspace specified",async()=>{mock=await setupMock({[_config1.ConfigKeys.Customer]:"the-customer"});const result=(0,_html.globalVariables)(mock,"the-workspace");(0,_vitest.expect)(result).toContain(`window.${_html.GlobalFrameworkVariables.Workspace} = 'the-workspace';`);(0,_vitest.expect)(result).toContain(`window.${_html.GlobalFrameworkVariables.Customer} = 'the-customer';`)});(0,_vitest.describe)("root url sub path",()=>{(0,_vitest.it)("with /",async()=>{mock=await setupMock({[_config1.ConfigKeys.RootUrlSubPath]:"/"});const result=(0,_html.globalVariables)(mock,"the-workspace");(0,_vitest.expect)(result).toContain(`window.${_html.GlobalFrameworkVariables.RuntimeRootUrl} = window.origin;`)});(0,_vitest.it)("with /{{workspace}}",async()=>{mock=await setupMock({[_config1.ConfigKeys.RootUrlSubPath]:"/{{workspace}}"});const result=(0,_html.globalVariables)(mock,"the-workspace");(0,_vitest.expect)(result).toContain(`window.${_html.GlobalFrameworkVariables.RuntimeRootUrl} = window.origin + '/the-workspace';`)});(0,_vitest.it)("with /{{customer}}/{{workspace}}",async()=>{mock=await setupMock({[_config1.ConfigKeys.Customer]:"somecustomer",[_config1.ConfigKeys.RootUrlSubPath]:"/{{customer}}/{{workspace}}"});const result=(0,_html.globalVariables)(mock,"dynamicws");(0,_vitest.expect)(result).toContain(`window.${_html.GlobalFrameworkVariables.RuntimeRootUrl} = window.origin + '/somecustomer/dynamicws';`)})})});(0,_vitest.describe)("htmlTemplate",()=>{(0,_vitest.it)("returns correct title",()=>{const result=(0,_html.htmlTemplate)("some title");(0,_vitest.expect)(result).toContain("<title>some title</title>")})})});
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:all[name]})}_export(exports,{dbError:function(){return dbError},ok:function(){return ok},unauthorizedError:function(){return unauthorizedError},workspaceNotFoundError:function(){return workspaceNotFoundError}});const _common=require("@nestjs/common");const _html=require("./html");function dbError(res){return error(res,_common.HttpStatus.INTERNAL_SERVER_ERROR,"Error when contacting database.")}function unauthorizedError(res,workspaceSlug){return error(res,_common.HttpStatus.UNAUTHORIZED,`You don't have permission to access Workspace '${workspaceSlug}'.`)}function workspaceNotFoundError(res,workspaceSlug){return error(res,_common.HttpStatus.NOT_FOUND,`The Workspace '${workspaceSlug}' does not exist.`)}function error(res,code,msg){return res.status(code).send((0,_html.htmlTemplate)(`ACE Portal - ${code}`,(0,_html.errorBody)(code,msg)))}function ok(res,content){return res.status(_common.HttpStatus.OK).send(content)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telia-ace/alliance-portal",
3
- "version": "1.0.7-next.4",
3
+ "version": "1.0.7-next.5",
4
4
  "description": "ACE Alliance portal",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "author": "Telia Company AB",
@@ -19,7 +19,7 @@
19
19
  "@nestjs/core": "^10.2.7",
20
20
  "@nestjs/platform-express": "^10.2.7",
21
21
  "@nestjs/terminus": "^10.1.1",
22
- "@telia-ace/alliance-internal-node-utilities": "1.0.4-next.3",
22
+ "@telia-ace/alliance-internal-node-utilities": "1.0.4-next.4",
23
23
  "dotenv": "^16.3.1",
24
24
  "express": "^4.18.2",
25
25
  "graphql": "^16.8.1",