@nsshunt/stsdevtools 1.0.67 → 1.0.69

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.
@@ -1,14 +1,3 @@
1
- var __defProp = Object.defineProperty;
2
- var __typeError = (msg) => {
3
- throw TypeError(msg);
4
- };
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
8
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
9
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
- var _regexURLSafeStringComponent, _regexSTSBase64, _regexJWT, _network, _databaseContainer, _stsAuthContainer, _stsRest01Container, _ioRedisContainer, _stsFhirContainer, _ioRedisMessageProcessorUrl, _authEndpoint, _authPort, _authHost, _rest01Host, _rest01Port, _rest01Endpoint, _fhirHost, _fhirPort, _fhirEndpoint;
12
1
  import { expect } from "vitest";
13
2
  import chalk from "chalk";
14
3
  import * as tough from "tough-cookie";
@@ -20,343 +9,328 @@ import { defaultLogger, AgentManager, STSAxiosConfig, Sleep } from "@nsshunt/sts
20
9
  import http from "node:http";
21
10
  import https from "node:https";
22
11
  class TestHelper {
12
+ //#regexBase64URL = /^[A-Za-z0-9_-]+$/ // Base64URL - https://base64.guru/standards/base64url
13
+ #regexURLSafeStringComponent = /[-a-zA-Z0-9@:%._+~#=]{1,256}/;
14
+ // URL safe string component
15
+ //#regexBase64 = /(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?/ // Base64 - https://stackoverflow.com/questions/475074/regex-to-parse-or-validate-base64-data
16
+ #regexSTSBase64 = /SES_(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?/;
17
+ // Base64
18
+ #regexJWT = /[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+/;
19
+ // JWT (Base64URL.Base64URL.Base64URL)
20
+ #network;
21
+ #databaseContainer;
22
+ #stsAuthContainer;
23
+ #stsRest01Container;
24
+ #ioRedisContainer;
25
+ #stsFhirContainer;
26
+ #ioRedisMessageProcessorUrl = "";
27
+ #authEndpoint = "";
28
+ #authPort = "";
29
+ #authHost = "";
30
+ #rest01Host = "";
31
+ #rest01Port = "";
32
+ #rest01Endpoint = "";
33
+ #fhirHost = "";
34
+ #fhirPort = "";
35
+ #fhirEndpoint = "";
23
36
  constructor() {
24
- //#regexBase64URL = /^[A-Za-z0-9_-]+$/ // Base64URL - https://base64.guru/standards/base64url
25
- __privateAdd(this, _regexURLSafeStringComponent, /[-a-zA-Z0-9@:%._+~#=]{1,256}/);
26
- // URL safe string component
27
- //#regexBase64 = /(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?/ // Base64 - https://stackoverflow.com/questions/475074/regex-to-parse-or-validate-base64-data
28
- __privateAdd(this, _regexSTSBase64, /SES_(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?/);
29
- // Base64
30
- __privateAdd(this, _regexJWT, /[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+/);
31
- // JWT (Base64URL.Base64URL.Base64URL)
32
- __privateAdd(this, _network);
33
- __privateAdd(this, _databaseContainer);
34
- __privateAdd(this, _stsAuthContainer);
35
- __privateAdd(this, _stsRest01Container);
36
- __privateAdd(this, _ioRedisContainer);
37
- __privateAdd(this, _stsFhirContainer);
38
- __privateAdd(this, _ioRedisMessageProcessorUrl, "");
39
- __privateAdd(this, _authEndpoint, "");
40
- __privateAdd(this, _authPort, "");
41
- __privateAdd(this, _authHost, "");
42
- __privateAdd(this, _rest01Host, "");
43
- __privateAdd(this, _rest01Port, "");
44
- __privateAdd(this, _rest01Endpoint, "");
45
- __privateAdd(this, _fhirHost, "");
46
- __privateAdd(this, _fhirPort, "");
47
- __privateAdd(this, _fhirEndpoint, "");
48
- __publicField(this, "StartNetwork", async () => {
49
- __privateSet(this, _network, await new Network().start());
50
- });
51
- __publicField(this, "StopNetwork", async () => {
52
- await __privateGet(this, _network).stop();
53
- });
54
- __publicField(this, "CreateRandomString", () => {
55
- const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";
56
- let random = "";
57
- const randomValues = Array.from(crypto.getRandomValues(new Uint8Array(43)));
58
- randomValues.forEach((v) => random += charset[v % charset.length]);
59
- return random;
60
- });
61
- __publicField(this, "Login", async (username, password) => {
62
- const client_id = process.env.CLIENT_ID;
63
- const nonce = crypto.randomBytes(43).toString("base64");
64
- const response_type = "code";
65
- const redirect_uri = process.env.REDIRECT_URI;
66
- const response_mode = "query";
67
- const scope = process.env.SCOPE;
68
- const state = crypto.randomBytes(43).toString("base64");
69
- const code_verifier = this.CreateRandomString();
70
- const code_challenge = crypto.createHash("sha256").update(code_verifier).digest("base64");
71
- const code_challenge_method = "S256";
72
- const authoriseOptions = {
73
- email: username,
74
- password,
75
- client_id,
76
- nonce,
77
- response_type,
78
- redirect_uri,
79
- response_mode,
80
- scope,
81
- state,
82
- code_challenge,
83
- code_challenge_method
84
- };
85
- const url = `${__privateGet(this, _authEndpoint)}${goptions.asapiroot}/login`;
86
- console.log(`Login ---------------------------------------------------------------------------`);
87
- console.log(`url: [${url}]`);
88
- console.log(`authoriseOptions: [${JSON.stringify(authoriseOptions)}]`);
89
- const agentManager = new AgentManager({
90
- httpAgentFactory(options) {
91
- return new http.Agent(options);
92
- },
93
- httpsAgentFactory(options) {
94
- return new https.Agent(options);
95
- }
96
- });
97
- const retVal = await axios(new STSAxiosConfig(url, "post").withDefaultHeaders().withData(authoriseOptions).withAgentManager(agentManager).config);
98
- return retVal;
99
- });
100
- /*
101
- GetAuthServerAPITokenFromServer = async (): Promise<string> => {
102
- return await this.#authUtilsNode.GetAPITokenFromAuthServer(STSClientID.STSTestingService,
103
- "eN9u0mHZLGWZrdnE1zit2vL6xwUFW466sTZcbkXDml5KWxlvKaZ1uiOZmA==",
104
- goptions.asapiidentifier, this.#authEndpoint)
105
- }
106
- */
107
- __publicField(this, "StartDatabase", async () => {
108
- __privateSet(this, _databaseContainer, await new GenericContainer("postgres").withExposedPorts(5432).withEnvironment({
109
- POSTGRES_PASSWORD: "postgres"
110
- //UV_THREADPOOL_SIZE: "64"
111
- }).withNetwork(__privateGet(this, _network)).withNetworkAliases("database").start());
112
- const httpPort = __privateGet(this, _databaseContainer).getMappedPort(5432);
113
- const host = __privateGet(this, _databaseContainer).getHost();
114
- const networkIpAddress = __privateGet(this, _databaseContainer).getIpAddress(__privateGet(this, _network).getName());
115
- process.env.DB_HOST = `${host}:${httpPort}`;
116
- $ResetOptions();
117
- this.LogDebugMessage(chalk.green(`httpPort: [${httpPort}]`));
118
- this.LogDebugMessage(chalk.green(`host: [${host}]`));
119
- this.LogDebugMessage(chalk.green(`networkIpAddress: [${networkIpAddress}]`));
120
- this.LogDebugMessage(chalk.green(`connectionString: [${goptions.connectionString}]`));
121
- this.LogDebugMessage(chalk.green(`defaultDatabaseConnectionString: [${goptions.defaultDatabaseConnectionString}]`));
122
- });
123
- __publicField(this, "StopDatabase", async () => {
124
- if (__privateGet(this, _databaseContainer)) {
125
- await __privateGet(this, _databaseContainer).stop();
126
- this.LogDebugMessage(chalk.yellow(`Used the following parameters for the database during testing:`));
127
- this.LogDebugMessage(chalk.yellow(`connectionString: [${goptions.connectionString}]`));
128
- this.LogDebugMessage(chalk.yellow(`defaultDatabaseConnectionString: [${goptions.defaultDatabaseConnectionString}]`));
129
- }
130
- });
131
- // Note: .withCopyFilesToContainer and .withCopyContentToContainer have a defect in that Jest will not close. A file handle/stream is left open
132
- // within the underlying code.
133
- __publicField(this, "InitializeDatabase", async () => {
134
- const stsAuthContainerInit = await new GenericContainer("serza/stsauth:latest").withEnvironment({
135
- DB_USER: "postgres",
136
- DB_PASSWORD: "postgres",
137
- DB_HOST: "database:5432",
138
- // "192.168.14.101",
139
- POOL_SIZE: "50",
140
- MAX_CPU: "2",
141
- DEBUG: "proc*",
142
- HTTPS_SERVER_KEY_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.key",
143
- HTTPS_SERVER_CERT_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.cert",
144
- AS_ENDPOINT: "https://stscore.stsmda.org"
145
- }).withCommand(["node", "dist/app", "create"]).withNetwork(__privateGet(this, _network)).withNetworkAliases("stsauthrunnerinit").withWaitStrategy(Wait.forLogMessage(`User registered: {"status":200,"detail":{"id":"USR_STSGlobalAdminUser@stsmda.com","name":"STSGlobalAdminUser@stsmda.com","email":"STSGlobalAdminUser@stsmda.com","roles":[]}}`)).start();
146
- await Sleep(500);
147
- await stsAuthContainerInit.stop();
148
- });
149
- __publicField(this, "StartRedis", async () => {
150
- __privateSet(this, _ioRedisContainer, await new GenericContainer("redis/redis-stack-server").withEnvironment({
151
- REDIS_ARGS: '--save "" --appendonly no'
152
- }).withExposedPorts(6379).withNetwork(__privateGet(this, _network)).withNetworkAliases("redisstackserver").start());
153
- __privateSet(this, _ioRedisMessageProcessorUrl, `redis://${__privateGet(this, _ioRedisContainer).getHost()}:${__privateGet(this, _ioRedisContainer).getMappedPort(6379)}`);
154
- await Sleep(2e3);
155
- this.LogDebugMessage(chalk.green(`redis/redis-stack-server Started. Server Details: ioRedisMessageProcessorUrl: [${__privateGet(this, _ioRedisMessageProcessorUrl)}]`));
156
- });
157
- __publicField(this, "StopRedis", async () => {
158
- await __privateGet(this, _ioRedisContainer).stop();
159
- await Sleep(200);
160
- });
161
- __publicField(this, "StartAuthService", async () => {
162
- __privateSet(this, _stsAuthContainer, await new GenericContainer("serza/stsauth:latest").withExposedPorts(3002).withEnvironment({
163
- DB_USER: "postgres",
164
- DB_PASSWORD: "postgres",
165
- DB_HOST: "database:5432",
166
- POOL_SIZE: "50",
167
- MAX_CPU: "2",
168
- DEBUG: "proc*",
169
- HTTPS_SERVER_KEY_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.key",
170
- HTTPS_SERVER_CERT_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.cert",
171
- AS_ENDPOINT: "https://stscore.stsmda.org",
172
- IM_REDIS_MESSAGE_PROCESSOR_URL: "redis://redisstackserver:6379"
173
- }).withNetwork(__privateGet(this, _network)).withNetworkAliases("stsauthrunner").withWaitStrategy(Wait.forHttp("/stsauth/v1.0/latency", 3002).usingTls().allowInsecure()).start());
174
- const httpAuthPort = __privateGet(this, _stsAuthContainer).getMappedPort(3002);
175
- await Sleep(200);
176
- __privateSet(this, _authHost, "https://localhost");
177
- __privateSet(this, _authPort, httpAuthPort);
178
- __privateSet(this, _authEndpoint, `${__privateGet(this, _authHost)}:${__privateGet(this, _authPort)}`);
179
- this.LogDebugMessage(chalk.green(`STSAuth Started. Server Details: Host: [${__privateGet(this, _authHost)}], Port: [${__privateGet(this, _authPort)}]`));
180
- });
181
- __publicField(this, "StartFhirService", async () => {
182
- __privateSet(this, _stsFhirContainer, await new GenericContainer("serza/stsfhir:latest").withExposedPorts(3005).withEnvironment({
183
- DB_USER: "postgres",
184
- DB_PASSWORD: "postgres",
185
- DB_HOST: "database:5432",
186
- POOL_SIZE: "50",
187
- MAX_CPU: "2",
188
- DEBUG: "proc*",
189
- HTTPS_SERVER_KEY_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.key",
190
- HTTPS_SERVER_CERT_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.cert",
191
- AS_ENDPOINT: "https://stsauthrunner",
192
- AS_HOST_PORT: "3002",
193
- AS_PORT: "3002",
194
- IM_REDIS_MESSAGE_PROCESSOR_URL: "redis://redisstackserver:6379",
195
- SOCKET_IO_REDIS_ADAPTOR_URL: "redis://redisstackserver:6379",
196
- STSFHIR_PORT: "3005",
197
- STSFHIR_HOST_PORT: "3005",
198
- STSFHIR_ENDPOINT: "https://stsfhirserver",
199
- // "https://stscore.stsmda.org",
200
- UV_THREADPOOL_SIZE: "64",
201
- FORCE_COLOR: "3"
202
- //node dist/app usedb postgresResources
203
- }).withNetwork(__privateGet(this, _network)).withNetworkAliases("stsfhirserver").start());
204
- __privateGet(this, _stsFhirContainer).logs().then((stream) => {
205
- stream.on("data", (line) => process.stdout.write(line.toString())).on("err", (line) => process.stderr.write(line.toString())).on("end", () => console.log("Stream ended."));
206
- });
207
- const httpFhirPort = __privateGet(this, _stsFhirContainer).getMappedPort(3005);
208
- await Sleep(200);
209
- __privateSet(this, _fhirHost, "https://localhost");
210
- __privateSet(this, _fhirPort, httpFhirPort);
211
- __privateSet(this, _fhirEndpoint, `${__privateGet(this, _fhirHost)}:${__privateGet(this, _fhirPort)}`);
212
- this.LogDebugMessage(chalk.green(`STSFhir Started. Server Details: Host: [${__privateGet(this, _fhirHost)}], Port: [${__privateGet(this, _fhirPort)}]`));
213
- });
214
- __publicField(this, "StopAuthService", async () => {
215
- if (__privateGet(this, _stsAuthContainer)) {
216
- await __privateGet(this, _stsAuthContainer).stop();
217
- await Sleep(200);
218
- }
219
- });
220
- __publicField(this, "StopRest01Service", async () => {
221
- if (__privateGet(this, _stsRest01Container)) {
222
- await __privateGet(this, _stsRest01Container).stop();
223
- await Sleep(200);
224
- }
225
- });
226
- __publicField(this, "StopFhirService", async () => {
227
- if (__privateGet(this, _stsFhirContainer)) {
228
- await __privateGet(this, _stsFhirContainer).stop();
229
- await Sleep(200);
230
- }
231
- });
232
- __publicField(this, "TestLoginAndVerify", async () => {
233
- expect.assertions(4);
234
- console.log(`TestLoginAndVerify:1`);
235
- const retVal = await this.Login("user01@stsmda.com.au", "user01password");
236
- expect(retVal.status).toEqual(200);
237
- console.log(`TestLoginAndVerify:2`);
238
- this.LogDebugMessage(chalk.red(`${JSON.stringify(retVal.data)}`));
239
- this.LogDebugMessage(chalk.magenta(`${JSON.stringify(retVal.headers)}`));
240
- this.LogDebugMessage(chalk.yellow(`${JSON.stringify(retVal.headers["set-cookie"])}`));
241
- const cookies = retVal.headers["set-cookie"];
242
- this.LogDebugMessage(chalk.yellow(`${cookies[0]}`));
243
- this.LogDebugMessage(chalk.green(`${JSON.stringify(tough.Cookie.parse(cookies[0]))}`));
244
- console.log(`TestLoginAndVerify:3`);
245
- const cookie = tough.Cookie.parse(cookies[0]);
246
- console.log(`TestLoginAndVerify:4`);
247
- const desiredCookieResultAxios = {
248
- key: "consent_cookie",
249
- value: expect.stringMatching(__privateGet(this, _regexURLSafeStringComponent)),
250
- path: "/",
251
- secure: true,
252
- httpOnly: true,
253
- sameSite: "strict"
254
- };
255
- const cookieResult = JSON.parse(JSON.stringify(cookie));
256
- expect(cookieResult).toMatchObject(desiredCookieResultAxios);
257
- console.log(`TestLoginAndVerify:5`);
258
- const cookieExpireDate = new Date(cookie.expires);
259
- expect(cookieExpireDate.getTime()).toBeGreaterThan((/* @__PURE__ */ new Date()).getTime());
260
- const consentRequired = process.env.CONSENT_REQUIRED.split(" ").sort();
261
- retVal.data.detail.consentRequired = retVal.data.detail.consentRequired.sort();
262
- console.log(`TestLoginAndVerify:6`);
263
- const desiredResult = {
264
- sessionId: expect.stringMatching(__privateGet(this, _regexSTSBase64)),
265
- id_token: expect.stringMatching(__privateGet(this, _regexJWT)),
266
- consentRequired
267
- };
268
- console.log(`TestLoginAndVerify:7`);
269
- expect(retVal.data.detail).toMatchObject(desiredResult);
270
- console.log(`TestLoginAndVerify:9`);
271
- });
272
- __publicField(this, "StartRest01Service", async () => {
273
- __privateSet(this, _stsRest01Container, await new GenericContainer("serza/stsrest01:latest").withExposedPorts(3003).withEnvironment({
274
- DB_USER: "postgres",
275
- DB_PASSWORD: "postgres",
276
- DB_HOST: "database:5432",
277
- POOL_SIZE: "50",
278
- MAX_CPU: "2",
279
- DEBUG: "proc*",
280
- HTTPS_SERVER_KEY_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.key",
281
- HTTPS_SERVER_CERT_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.cert",
282
- //AS_ENDPOINT: "https://stscore.stsmda.org",
283
- AS_ENDPOINT: "https://stsauthrunner",
284
- // this.authHost,
285
- //AS_ENDPOINT: 'https://localhost', // this.authHost,
286
- AS_HOST_PORT: "3002",
287
- AS_PORT: "3002",
288
- IM_REDIS_MESSAGE_PROCESSOR_URL: "redis://redisstackserver:6379"
289
- //AS_HOST_PORT: this.authPort,
290
- //AS_PORT: this.authPort,
291
- //REST01_PORT: '3003',
292
- //REST01_HOST_PORT: '3003',
293
- //REST01_ENDPOINT: 'https://localhost' // 'https://stscore.stsmda.org'
294
- }).withNetwork(__privateGet(this, _network)).withNetworkAliases("rest01").withWaitStrategy(Wait.forHttp("/stsrest01/v1/latency", 3003).usingTls().allowInsecure()).start());
295
- const httpRest01Port = __privateGet(this, _stsRest01Container).getMappedPort(3003);
296
- await Sleep(200);
297
- __privateSet(this, _rest01Host, "https://localhost");
298
- __privateSet(this, _rest01Port, httpRest01Port);
299
- __privateSet(this, _rest01Endpoint, `${__privateGet(this, _rest01Host)}:${__privateGet(this, _rest01Port)}`);
300
- this.LogDebugMessage(chalk.green(`STSRest01 Started. Server Details: Host: [${this.rest01Host}], Port: [${this.rest01Port}]`));
301
- });
302
- __privateSet(this, _authEndpoint, "https://localhost:3002");
37
+ this.#authEndpoint = "https://localhost:3002";
303
38
  }
304
39
  LogDebugMessage(message) {
305
40
  defaultLogger.debug(message);
306
41
  }
42
+ StartNetwork = async () => {
43
+ this.#network = await new Network().start();
44
+ };
45
+ StopNetwork = async () => {
46
+ if (this.#network) {
47
+ await this.#network.stop();
48
+ }
49
+ };
307
50
  get network() {
308
- return __privateGet(this, _network);
51
+ return this.#network;
309
52
  }
310
53
  get authPort() {
311
- return __privateGet(this, _authPort);
54
+ return this.#authPort;
312
55
  }
313
56
  get authHost() {
314
- return __privateGet(this, _authHost);
57
+ return this.#authHost;
315
58
  }
316
59
  get authEndpoint() {
317
- return __privateGet(this, _authEndpoint);
60
+ return this.#authEndpoint;
318
61
  }
319
62
  get rest01Port() {
320
- return __privateGet(this, _rest01Port);
63
+ return this.#rest01Port;
321
64
  }
322
65
  get rest01Host() {
323
- return __privateGet(this, _rest01Host);
66
+ return this.#rest01Host;
324
67
  }
325
68
  get rest01Endpoint() {
326
- return __privateGet(this, _rest01Endpoint);
69
+ return this.#rest01Endpoint;
327
70
  }
328
71
  get fhirPort() {
329
- return __privateGet(this, _fhirPort);
72
+ return this.#fhirPort;
330
73
  }
331
74
  get fhirHost() {
332
- return __privateGet(this, _fhirHost);
75
+ return this.#fhirHost;
333
76
  }
334
77
  get fhirEndpoint() {
335
- return __privateGet(this, _fhirEndpoint);
78
+ return this.#fhirEndpoint;
336
79
  }
337
80
  get ioRedisMessageProcessorUrl() {
338
- return __privateGet(this, _ioRedisMessageProcessorUrl);
81
+ return this.#ioRedisMessageProcessorUrl;
82
+ }
83
+ CreateRandomString = () => {
84
+ const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";
85
+ let random = "";
86
+ const randomValues = Array.from(crypto.getRandomValues(new Uint8Array(43)));
87
+ randomValues.forEach((v) => random += charset[v % charset.length]);
88
+ return random;
89
+ };
90
+ Login = async (username, password) => {
91
+ const client_id = process.env.CLIENT_ID;
92
+ const nonce = crypto.randomBytes(43).toString("base64");
93
+ const response_type = "code";
94
+ const redirect_uri = process.env.REDIRECT_URI;
95
+ const response_mode = "query";
96
+ const scope = process.env.SCOPE;
97
+ const state = crypto.randomBytes(43).toString("base64");
98
+ const code_verifier = this.CreateRandomString();
99
+ const code_challenge = crypto.createHash("sha256").update(code_verifier).digest("base64");
100
+ const code_challenge_method = "S256";
101
+ const authoriseOptions = {
102
+ email: username,
103
+ password,
104
+ client_id,
105
+ nonce,
106
+ response_type,
107
+ redirect_uri,
108
+ response_mode,
109
+ scope,
110
+ state,
111
+ code_challenge,
112
+ code_challenge_method
113
+ };
114
+ const url = `${this.#authEndpoint}${goptions.asapiroot}/login`;
115
+ console.log(`Login ---------------------------------------------------------------------------`);
116
+ console.log(`url: [${url}]`);
117
+ console.log(`authoriseOptions: [${JSON.stringify(authoriseOptions)}]`);
118
+ const agentManager = new AgentManager({
119
+ httpAgentFactory(options) {
120
+ return new http.Agent(options);
121
+ },
122
+ httpsAgentFactory(options) {
123
+ return new https.Agent(options);
124
+ }
125
+ });
126
+ const retVal = await axios(new STSAxiosConfig(url, "post").withDefaultHeaders().withData(authoriseOptions).withAgentManager(agentManager).config);
127
+ return retVal;
128
+ };
129
+ /*
130
+ GetAuthServerAPITokenFromServer = async (): Promise<string> => {
131
+ return await this.#authUtilsNode.GetAPITokenFromAuthServer(STSClientID.STSTestingService,
132
+ "eN9u0mHZLGWZrdnE1zit2vL6xwUFW466sTZcbkXDml5KWxlvKaZ1uiOZmA==",
133
+ goptions.asapiidentifier, this.#authEndpoint)
339
134
  }
135
+ */
136
+ StartDatabase = async () => {
137
+ this.#databaseContainer = await new GenericContainer("postgres").withExposedPorts(5432).withEnvironment({
138
+ POSTGRES_PASSWORD: "postgres"
139
+ //UV_THREADPOOL_SIZE: "64"
140
+ }).withNetwork(this.#network).withNetworkAliases("database").start();
141
+ const httpPort = this.#databaseContainer.getMappedPort(5432);
142
+ const host = this.#databaseContainer.getHost();
143
+ const networkIpAddress = this.#databaseContainer.getIpAddress(this.#network.getName());
144
+ process.env.DB_HOST = `${host}:${httpPort}`;
145
+ $ResetOptions();
146
+ this.LogDebugMessage(chalk.green(`httpPort: [${httpPort}]`));
147
+ this.LogDebugMessage(chalk.green(`host: [${host}]`));
148
+ this.LogDebugMessage(chalk.green(`networkIpAddress: [${networkIpAddress}]`));
149
+ this.LogDebugMessage(chalk.green(`connectionString: [${goptions.connectionString}]`));
150
+ this.LogDebugMessage(chalk.green(`defaultDatabaseConnectionString: [${goptions.defaultDatabaseConnectionString}]`));
151
+ };
152
+ StopDatabase = async () => {
153
+ if (this.#databaseContainer) {
154
+ await this.#databaseContainer.stop();
155
+ this.LogDebugMessage(chalk.yellow(`Used the following parameters for the database during testing:`));
156
+ this.LogDebugMessage(chalk.yellow(`connectionString: [${goptions.connectionString}]`));
157
+ this.LogDebugMessage(chalk.yellow(`defaultDatabaseConnectionString: [${goptions.defaultDatabaseConnectionString}]`));
158
+ }
159
+ };
160
+ // Note: .withCopyFilesToContainer and .withCopyContentToContainer have a defect in that Jest will not close. A file handle/stream is left open
161
+ // within the underlying code.
162
+ InitializeDatabase = async () => {
163
+ const stsAuthContainerInit = await new GenericContainer("serza/stsauth:latest").withEnvironment({
164
+ DB_USER: "postgres",
165
+ DB_PASSWORD: "postgres",
166
+ DB_HOST: "database:5432",
167
+ // "192.168.14.101",
168
+ POOL_SIZE: "50",
169
+ MAX_CPU: "2",
170
+ DEBUG: "proc*",
171
+ HTTPS_SERVER_KEY_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.key",
172
+ HTTPS_SERVER_CERT_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.cert",
173
+ AS_ENDPOINT: "https://stscore.stsmda.org"
174
+ }).withCommand(["node", "dist/app", "create"]).withNetwork(this.#network).withNetworkAliases("stsauthrunnerinit").withWaitStrategy(Wait.forLogMessage(`User registered: {"status":200,"detail":{"id":"USR_STSGlobalAdminUser@stsmda.com","name":"STSGlobalAdminUser@stsmda.com","email":"STSGlobalAdminUser@stsmda.com","roles":[]}}`)).start();
175
+ await Sleep(500);
176
+ await stsAuthContainerInit.stop();
177
+ };
178
+ StartRedis = async () => {
179
+ this.#ioRedisContainer = await new GenericContainer("redis/redis-stack-server").withEnvironment({
180
+ REDIS_ARGS: '--save "" --appendonly no'
181
+ }).withExposedPorts(6379).withNetwork(this.#network).withNetworkAliases("redisstackserver").start();
182
+ this.#ioRedisMessageProcessorUrl = `redis://${this.#ioRedisContainer.getHost()}:${this.#ioRedisContainer.getMappedPort(6379)}`;
183
+ await Sleep(2e3);
184
+ this.LogDebugMessage(chalk.green(`redis/redis-stack-server Started. Server Details: ioRedisMessageProcessorUrl: [${this.#ioRedisMessageProcessorUrl}]`));
185
+ };
186
+ StopRedis = async () => {
187
+ if (this.#ioRedisContainer) {
188
+ await this.#ioRedisContainer.stop();
189
+ await Sleep(200);
190
+ }
191
+ };
192
+ StartAuthService = async () => {
193
+ this.#stsAuthContainer = await new GenericContainer("serza/stsauth:latest").withExposedPorts(3002).withEnvironment({
194
+ DB_USER: "postgres",
195
+ DB_PASSWORD: "postgres",
196
+ DB_HOST: "database:5432",
197
+ POOL_SIZE: "50",
198
+ MAX_CPU: "2",
199
+ DEBUG: "proc*",
200
+ HTTPS_SERVER_KEY_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.key",
201
+ HTTPS_SERVER_CERT_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.cert",
202
+ AS_ENDPOINT: "https://stscore.stsmda.org",
203
+ IM_REDIS_MESSAGE_PROCESSOR_URL: "redis://redisstackserver:6379"
204
+ }).withNetwork(this.#network).withNetworkAliases("stsauthrunner").withWaitStrategy(Wait.forHttp("/stsauth/v1.0/latency", 3002).usingTls().allowInsecure()).start();
205
+ const httpAuthPort = this.#stsAuthContainer.getMappedPort(3002);
206
+ await Sleep(200);
207
+ this.#authHost = "https://localhost";
208
+ this.#authPort = httpAuthPort;
209
+ this.#authEndpoint = `${this.#authHost}:${this.#authPort}`;
210
+ this.LogDebugMessage(chalk.green(`STSAuth Started. Server Details: Host: [${this.#authHost}], Port: [${this.#authPort}]`));
211
+ };
212
+ StartFhirService = async () => {
213
+ this.#stsFhirContainer = await new GenericContainer("serza/stsfhir:latest").withExposedPorts(3005).withEnvironment({
214
+ DB_USER: "postgres",
215
+ DB_PASSWORD: "postgres",
216
+ DB_HOST: "database:5432",
217
+ POOL_SIZE: "50",
218
+ MAX_CPU: "2",
219
+ DEBUG: "proc*",
220
+ HTTPS_SERVER_KEY_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.key",
221
+ HTTPS_SERVER_CERT_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.cert",
222
+ AS_ENDPOINT: "https://stsauthrunner",
223
+ AS_HOST_PORT: "3002",
224
+ AS_PORT: "3002",
225
+ IM_REDIS_MESSAGE_PROCESSOR_URL: "redis://redisstackserver:6379",
226
+ SOCKET_IO_REDIS_ADAPTOR_URL: "redis://redisstackserver:6379",
227
+ STSFHIR_PORT: "3005",
228
+ STSFHIR_HOST_PORT: "3005",
229
+ STSFHIR_ENDPOINT: "https://stsfhirserver",
230
+ // "https://stscore.stsmda.org",
231
+ UV_THREADPOOL_SIZE: "64",
232
+ FORCE_COLOR: "3"
233
+ //node dist/app usedb postgresResources
234
+ }).withNetwork(this.#network).withNetworkAliases("stsfhirserver").start();
235
+ this.#stsFhirContainer.logs().then((stream) => {
236
+ stream.on("data", (line) => process.stdout.write(line.toString())).on("err", (line) => process.stderr.write(line.toString())).on("end", () => console.log("Stream ended."));
237
+ });
238
+ const httpFhirPort = this.#stsFhirContainer.getMappedPort(3005);
239
+ await Sleep(200);
240
+ this.#fhirHost = "https://localhost";
241
+ this.#fhirPort = httpFhirPort;
242
+ this.#fhirEndpoint = `${this.#fhirHost}:${this.#fhirPort}`;
243
+ this.LogDebugMessage(chalk.green(`STSFhir Started. Server Details: Host: [${this.#fhirHost}], Port: [${this.#fhirPort}]`));
244
+ };
245
+ StopAuthService = async () => {
246
+ if (this.#stsAuthContainer) {
247
+ await this.#stsAuthContainer.stop();
248
+ await Sleep(200);
249
+ }
250
+ };
251
+ StopRest01Service = async () => {
252
+ if (this.#stsRest01Container) {
253
+ await this.#stsRest01Container.stop();
254
+ await Sleep(200);
255
+ }
256
+ };
257
+ StopFhirService = async () => {
258
+ if (this.#stsFhirContainer) {
259
+ await this.#stsFhirContainer.stop();
260
+ await Sleep(200);
261
+ }
262
+ };
263
+ TestLoginAndVerify = async () => {
264
+ expect.assertions(4);
265
+ console.log(`TestLoginAndVerify:1`);
266
+ const retVal = await this.Login("user01@stsmda.com.au", "user01password");
267
+ expect(retVal.status).toEqual(200);
268
+ console.log(`TestLoginAndVerify:2`);
269
+ this.LogDebugMessage(chalk.red(`${JSON.stringify(retVal.data)}`));
270
+ this.LogDebugMessage(chalk.magenta(`${JSON.stringify(retVal.headers)}`));
271
+ this.LogDebugMessage(chalk.yellow(`${JSON.stringify(retVal.headers["set-cookie"])}`));
272
+ const cookies = retVal.headers["set-cookie"];
273
+ this.LogDebugMessage(chalk.yellow(`${cookies[0]}`));
274
+ this.LogDebugMessage(chalk.green(`${JSON.stringify(tough.Cookie.parse(cookies[0]))}`));
275
+ console.log(`TestLoginAndVerify:3`);
276
+ const cookie = tough.Cookie.parse(cookies[0]);
277
+ console.log(`TestLoginAndVerify:4`);
278
+ const desiredCookieResultAxios = {
279
+ key: "consent_cookie",
280
+ value: expect.stringMatching(this.#regexURLSafeStringComponent),
281
+ path: "/",
282
+ secure: true,
283
+ httpOnly: true,
284
+ sameSite: "strict"
285
+ };
286
+ const cookieResult = JSON.parse(JSON.stringify(cookie));
287
+ expect(cookieResult).toMatchObject(desiredCookieResultAxios);
288
+ console.log(`TestLoginAndVerify:5`);
289
+ const cookieExpireDate = new Date(cookie.expires);
290
+ expect(cookieExpireDate.getTime()).toBeGreaterThan((/* @__PURE__ */ new Date()).getTime());
291
+ const consentRequired = process.env.CONSENT_REQUIRED.split(" ").sort();
292
+ retVal.data.detail.consentRequired = retVal.data.detail.consentRequired.sort();
293
+ console.log(`TestLoginAndVerify:6`);
294
+ const desiredResult = {
295
+ sessionId: expect.stringMatching(this.#regexSTSBase64),
296
+ id_token: expect.stringMatching(this.#regexJWT),
297
+ consentRequired
298
+ };
299
+ console.log(`TestLoginAndVerify:7`);
300
+ expect(retVal.data.detail).toMatchObject(desiredResult);
301
+ console.log(`TestLoginAndVerify:9`);
302
+ };
303
+ StartRest01Service = async () => {
304
+ this.#stsRest01Container = await new GenericContainer("serza/stsrest01:latest").withExposedPorts(3003).withEnvironment({
305
+ DB_USER: "postgres",
306
+ DB_PASSWORD: "postgres",
307
+ DB_HOST: "database:5432",
308
+ POOL_SIZE: "50",
309
+ MAX_CPU: "2",
310
+ DEBUG: "proc*",
311
+ HTTPS_SERVER_KEY_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.key",
312
+ HTTPS_SERVER_CERT_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.cert",
313
+ //AS_ENDPOINT: "https://stscore.stsmda.org",
314
+ AS_ENDPOINT: "https://stsauthrunner",
315
+ // this.authHost,
316
+ //AS_ENDPOINT: 'https://localhost', // this.authHost,
317
+ AS_HOST_PORT: "3002",
318
+ AS_PORT: "3002",
319
+ IM_REDIS_MESSAGE_PROCESSOR_URL: "redis://redisstackserver:6379"
320
+ //AS_HOST_PORT: this.authPort,
321
+ //AS_PORT: this.authPort,
322
+ //REST01_PORT: '3003',
323
+ //REST01_HOST_PORT: '3003',
324
+ //REST01_ENDPOINT: 'https://localhost' // 'https://stscore.stsmda.org'
325
+ }).withNetwork(this.#network).withNetworkAliases("rest01").withWaitStrategy(Wait.forHttp("/stsrest01/v1/latency", 3003).usingTls().allowInsecure()).start();
326
+ const httpRest01Port = this.#stsRest01Container.getMappedPort(3003);
327
+ await Sleep(200);
328
+ this.#rest01Host = "https://localhost";
329
+ this.#rest01Port = httpRest01Port;
330
+ this.#rest01Endpoint = `${this.#rest01Host}:${this.#rest01Port}`;
331
+ this.LogDebugMessage(chalk.green(`STSRest01 Started. Server Details: Host: [${this.rest01Host}], Port: [${this.rest01Port}]`));
332
+ };
340
333
  }
341
- _regexURLSafeStringComponent = new WeakMap();
342
- _regexSTSBase64 = new WeakMap();
343
- _regexJWT = new WeakMap();
344
- _network = new WeakMap();
345
- _databaseContainer = new WeakMap();
346
- _stsAuthContainer = new WeakMap();
347
- _stsRest01Container = new WeakMap();
348
- _ioRedisContainer = new WeakMap();
349
- _stsFhirContainer = new WeakMap();
350
- _ioRedisMessageProcessorUrl = new WeakMap();
351
- _authEndpoint = new WeakMap();
352
- _authPort = new WeakMap();
353
- _authHost = new WeakMap();
354
- _rest01Host = new WeakMap();
355
- _rest01Port = new WeakMap();
356
- _rest01Endpoint = new WeakMap();
357
- _fhirHost = new WeakMap();
358
- _fhirPort = new WeakMap();
359
- _fhirEndpoint = new WeakMap();
360
334
  export {
361
335
  TestHelper
362
336
  };