@nsshunt/stsappframework 3.0.103 → 3.0.105

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.
Files changed (140) hide show
  1. package/dist/authutilsnode.js +6 -7
  2. package/dist/authutilsnode.js.map +1 -1
  3. package/dist/influxdb/influxDBManager.js +16 -17
  4. package/dist/influxdb/influxDBManager.js.map +1 -1
  5. package/dist/influxdb/influxDBManagerAgent.js +9 -13
  6. package/dist/influxdb/influxDBManagerAgent.js.map +1 -1
  7. package/dist/influxdb/influxDBManagerBase.js +2 -6
  8. package/dist/influxdb/influxDBManagerBase.js.map +1 -1
  9. package/dist/influxdb/influxDBManagerService.js +10 -14
  10. package/dist/influxdb/influxDBManagerService.js.map +1 -1
  11. package/dist/instrumentationsubscriber.js +11 -15
  12. package/dist/instrumentationsubscriber.js.map +1 -1
  13. package/dist/kafka/IMKafkaManager.js +2 -6
  14. package/dist/kafka/IMKafkaManager.js.map +1 -1
  15. package/dist/kafkatesting/produce.js +1 -5
  16. package/dist/kafkatesting/produce.js.map +1 -1
  17. package/dist/masterprocessbase.js +19 -20
  18. package/dist/masterprocessbase.js.map +1 -1
  19. package/dist/processbase.js +8 -10
  20. package/dist/processbase.js.map +1 -1
  21. package/dist/server.js +1 -1
  22. package/dist/server.js.map +1 -1
  23. package/dist/singleprocessbase.js +3 -4
  24. package/dist/singleprocessbase.js.map +1 -1
  25. package/dist/tcpclient/app2.js +2 -2
  26. package/dist/tcpserver/appmaster.js +39 -16
  27. package/dist/tcpserver/appmaster.js.map +1 -1
  28. package/dist/workerprocessbase.js +3 -4
  29. package/dist/workerprocessbase.js.map +1 -1
  30. package/package.json +7 -7
  31. package/src/authutilsnode.ts +8 -10
  32. package/src/influxdb/influxDBManager.ts +16 -18
  33. package/src/influxdb/influxDBManagerAgent.ts +9 -11
  34. package/src/influxdb/influxDBManagerBase.ts +2 -4
  35. package/src/influxdb/influxDBManagerService.ts +10 -12
  36. package/src/instrumentationsubscriber.ts +11 -14
  37. package/src/kafka/IMKafkaManager.ts +2 -4
  38. package/src/kafkatesting/produce.ts +1 -3
  39. package/src/masterprocessbase.ts +32 -24
  40. package/src/processbase.ts +7 -11
  41. package/src/server.ts +1 -1
  42. package/src/singleprocessbase.ts +3 -5
  43. package/src/tcpclient/app2.ts +2 -2
  44. package/src/tcpserver/appmaster.ts +39 -17
  45. package/src/workerprocessbase.ts +3 -5
  46. package/types/authutilsnode.d.ts.map +1 -1
  47. package/types/influxdb/influxDBManager.d.ts.map +1 -1
  48. package/types/influxdb/influxDBManagerAgent.d.ts.map +1 -1
  49. package/types/influxdb/influxDBManagerBase.d.ts.map +1 -1
  50. package/types/influxdb/influxDBManagerService.d.ts.map +1 -1
  51. package/types/instrumentationsubscriber.d.ts.map +1 -1
  52. package/types/kafka/IMKafkaManager.d.ts.map +1 -1
  53. package/types/masterprocessbase.d.ts.map +1 -1
  54. package/types/processbase.d.ts +2 -2
  55. package/types/processbase.d.ts.map +1 -1
  56. package/types/singleprocessbase.d.ts.map +1 -1
  57. package/types/tcpserver/appmaster.d.ts.map +1 -1
  58. package/types/workerprocessbase.d.ts.map +1 -1
  59. package/src_new/authDefs.ts +0 -37
  60. package/src_new/authutilsnode.ts +0 -375
  61. package/src_new/commonTypes.ts +0 -239
  62. package/src_new/index.ts +0 -22
  63. package/src_new/influxdb/influxDBManager.ts +0 -972
  64. package/src_new/influxdb/influxDBManagerAgent.ts +0 -316
  65. package/src_new/influxdb/influxDBManagerBase.ts +0 -111
  66. package/src_new/influxdb/influxDBManagerService.ts +0 -375
  67. package/src_new/instrumentationsubscriber.ts +0 -286
  68. package/src_new/kafka/IMKafkaManager.ts +0 -154
  69. package/src_new/kafka/kafkaconsumer.ts +0 -82
  70. package/src_new/kafka/kafkamanager.ts +0 -186
  71. package/src_new/kafka/kafkaproducer.ts +0 -58
  72. package/src_new/kafkatesting/config.ts +0 -10
  73. package/src_new/kafkatesting/consume.ts +0 -116
  74. package/src_new/kafkatesting/produce.ts +0 -155
  75. package/src_new/masterprocessbase.ts +0 -590
  76. package/src_new/middleware/serverNetworkMiddleware.ts +0 -240
  77. package/src_new/network.ts +0 -36
  78. package/src_new/processbase.ts +0 -413
  79. package/src_new/processoptions.ts +0 -164
  80. package/src_new/publishertransports/publishTransportDirect.ts +0 -45
  81. package/src_new/publishertransports/publishTransportUtils.ts +0 -53
  82. package/src_new/server.ts +0 -141
  83. package/src_new/serverprocessbase.ts +0 -393
  84. package/src_new/singleprocessbase.ts +0 -123
  85. package/src_new/socketIoServerHelper.ts +0 -177
  86. package/src_new/stscontrollerbase.ts +0 -15
  87. package/src_new/stslatencycontroller.ts +0 -27
  88. package/src_new/stslatencyroute.ts +0 -16
  89. package/src_new/stsrouterbase.ts +0 -22
  90. package/src_new/tcpclient/app.ts +0 -19
  91. package/src_new/tcpclient/app2.ts +0 -56
  92. package/src_new/tcpserver/app.ts +0 -11
  93. package/src_new/tcpserver/appConfig.ts +0 -65
  94. package/src_new/tcpserver/appmaster.ts +0 -522
  95. package/src_new/validation/errors.ts +0 -6
  96. package/src_new/webworkertesting/app.ts +0 -49
  97. package/src_new/webworkertesting/worker.ts +0 -24
  98. package/src_new/workerprocessbase.test.ts +0 -47
  99. package/src_new/workerprocessbase.ts +0 -187
  100. package/src_working/authDefs.ts +0 -37
  101. package/src_working/authutilsnode.ts +0 -373
  102. package/src_working/commonTypes.ts +0 -239
  103. package/src_working/index.ts +0 -22
  104. package/src_working/influxdb/influxDBManager.ts +0 -970
  105. package/src_working/influxdb/influxDBManagerAgent.ts +0 -314
  106. package/src_working/influxdb/influxDBManagerBase.ts +0 -109
  107. package/src_working/influxdb/influxDBManagerService.ts +0 -373
  108. package/src_working/instrumentationsubscriber.ts +0 -283
  109. package/src_working/kafka/IMKafkaManager.ts +0 -152
  110. package/src_working/kafka/kafkaconsumer.ts +0 -82
  111. package/src_working/kafka/kafkamanager.ts +0 -186
  112. package/src_working/kafka/kafkaproducer.ts +0 -58
  113. package/src_working/kafkatesting/config.ts +0 -10
  114. package/src_working/kafkatesting/consume.ts +0 -116
  115. package/src_working/kafkatesting/produce.ts +0 -153
  116. package/src_working/masterprocessbase.ts +0 -598
  117. package/src_working/middleware/serverNetworkMiddleware.ts +0 -240
  118. package/src_working/network.ts +0 -36
  119. package/src_working/processbase.ts +0 -411
  120. package/src_working/processoptions.ts +0 -164
  121. package/src_working/publishertransports/publishTransportDirect.ts +0 -45
  122. package/src_working/publishertransports/publishTransportUtils.ts +0 -53
  123. package/src_working/server.ts +0 -141
  124. package/src_working/serverprocessbase.ts +0 -393
  125. package/src_working/singleprocessbase.ts +0 -121
  126. package/src_working/socketIoServerHelper.ts +0 -177
  127. package/src_working/stscontrollerbase.ts +0 -15
  128. package/src_working/stslatencycontroller.ts +0 -27
  129. package/src_working/stslatencyroute.ts +0 -16
  130. package/src_working/stsrouterbase.ts +0 -22
  131. package/src_working/tcpclient/app.ts +0 -19
  132. package/src_working/tcpclient/app2.ts +0 -56
  133. package/src_working/tcpserver/app.ts +0 -11
  134. package/src_working/tcpserver/appConfig.ts +0 -65
  135. package/src_working/tcpserver/appmaster.ts +0 -544
  136. package/src_working/validation/errors.ts +0 -6
  137. package/src_working/webworkertesting/app.ts +0 -49
  138. package/src_working/webworkertesting/worker.ts +0 -24
  139. package/src_working/workerprocessbase.test.ts +0 -47
  140. package/src_working/workerprocessbase.ts +0 -185
@@ -1,187 +0,0 @@
1
- /* eslint @typescript-eslint/no-explicit-any: 0 */ // --> OFF
2
- import debugModule from 'debug'
3
- const debug = debugModule(`proc:${process.pid}`);
4
-
5
- import chalk from 'chalk';
6
-
7
- import { Gauge, InstrumentGaugeTelemetry } from '@nsshunt/stsinstrumentation'
8
- import { JSONObject } from '@nsshunt/stsutils'
9
- import { ProcessOptions } from './processoptions'
10
- import { IPCMessage, IPCMessages, IPCMessagePayload, IPCMessageCommand, IWorkerProcessBase } from './commonTypes'
11
- import { STSExpressServer } from './server';
12
- import { ServerProcessBase } from './serverprocessbase'
13
-
14
- import { v4 as uuidv4 } from 'uuid';
15
-
16
- import colors from 'colors'
17
-
18
- /**
19
- * todo
20
- * @typedef {Object} options - todo
21
- * @property {boolean} [wssServer=false] - Create a web socket server on this worker instance
22
- */
23
- export class WorkerProcessBase extends ServerProcessBase implements IWorkerProcessBase
24
- {
25
- #inFlightMessage: IPCMessages = { }
26
- #requestResponseMessageTimeout = 2000; //@@ config
27
-
28
- constructor(options: ProcessOptions) {
29
- super(options);
30
- }
31
-
32
- WorkerStarted() {
33
- return null;
34
- }
35
-
36
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars
37
- ReceivedMessageFromMaster(msg: any) {
38
- // Override in subclass if required
39
- }
40
-
41
- override CollectAdditionalTelemetry(): void {
42
- this.httpServer.getConnections((error: any, count: any) => {
43
- //@@this.instruments[Gauge.CONNECTION_COUNT_GAUGE].val = count;
44
- this.UpdateInstrument(Gauge.CONNECTION_COUNT_GAUGE, {
45
- val: count
46
- } as InstrumentGaugeTelemetry);
47
- });
48
- }
49
-
50
- #SendMessageToParentProcess = (message: IPCMessagePayload): Promise<JSONObject> => {
51
- return new Promise((resolve, reject) => {
52
- if (this.#inFlightMessage[message.id]) {
53
- reject(`Message with id: [${message.id}] already exists within the Request/Response record structure`);
54
- } else {
55
- this.#inFlightMessage[message.id] = {
56
- iPCMessagePayload: { ...message },
57
- cb: () => {
58
- const detail: JSONObject = this.#inFlightMessage[message.id].iPCMessagePayload.responseDetail as JSONObject
59
- clearTimeout(this.#inFlightMessage[message.id].timeout);
60
- setTimeout(() => {
61
- delete this.#inFlightMessage[message.id];
62
- }, 0).unref();
63
- debug(chalk.green(`Resolving response message with id: [${message.id}] from parent process via IPC. Details: [${JSON.stringify(this.#inFlightMessage[message.id].iPCMessagePayload)}]`));
64
- resolve(detail);
65
- },
66
- timeout: setTimeout(() => {
67
- setTimeout(() => {
68
- delete this.#inFlightMessage[message.id];
69
- }, 0).unref();
70
- debug(chalk.red(`Timeout has occurred after: [${this.#requestResponseMessageTimeout}]ms with message id: [${message.id}]. Details: [${JSON.stringify(this.#inFlightMessage[message.id].iPCMessagePayload)}]`));
71
- reject('Did not receive response form parent process.');
72
- }, this.#requestResponseMessageTimeout) // max message timeout allowed
73
- }
74
- debug(`Sending message with id: [${message.id}] to parent process via IPC. Details: [${JSON.stringify(this.#inFlightMessage[message.id].iPCMessagePayload)}]`.yellow);
75
- (process as any).send(message);
76
- }
77
- });
78
- }
79
-
80
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
- AddWorker = async (options: any): Promise<string> => {
82
- const workerResponse: JSONObject = await this.#SendMessageToParentProcess({
83
- requestResponse: true,
84
- id: uuidv4(),
85
- command: IPCMessageCommand.AddWorker,
86
- requestDetail: {
87
- options
88
- }
89
- });
90
- return workerResponse.workerId;
91
- }
92
-
93
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
94
- DeleteWorker = async (workerId: string, options: any): Promise<JSONObject> => {
95
- const workerResponse: JSONObject = await this.#SendMessageToParentProcess({
96
- requestResponse: true,
97
- id: uuidv4(),
98
- command: IPCMessageCommand.DeleteWorker,
99
- requestDetail: {
100
- options,
101
- workerId
102
- }
103
- });
104
- return workerResponse;
105
- }
106
-
107
- ProcessTerminating = async (): Promise<void> => {
108
- return;
109
- }
110
-
111
- SetupServer = async () =>
112
- {
113
- this.SetupInstrumentation();
114
- setTimeout(() => {
115
- this.SetupServerEx();
116
- }, 100);
117
- }
118
-
119
- SetupServerEx = async () => {
120
- this.ProcessStartup();
121
-
122
- if (this.options.expressServerRouteFactory || this.options.expressServerRouteStaticFactory) {
123
- this.expressServer = new STSExpressServer(this.options, this);
124
- }
125
-
126
- this.LogEx(`Worker instance starting. Service instance Id: [${this.options.serviceInstanceId}]`);
127
-
128
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
129
- process.on('message', async (msg: any) => {
130
- if (msg.requestResponse) {
131
- const iPCMessagePayload: IPCMessagePayload = msg as IPCMessagePayload;
132
- if (iPCMessagePayload.id) {
133
- if (this.#inFlightMessage[iPCMessagePayload.id]) {
134
- const responseMessage: IPCMessage = this.#inFlightMessage[iPCMessagePayload.id];
135
- responseMessage.iPCMessagePayload.responseDetail = { ...iPCMessagePayload.responseDetail }
136
- responseMessage.cb();
137
- } else {
138
- throw new Error(`Could not find Request/Response message with id: [${iPCMessagePayload.id}]`);
139
- }
140
- } else {
141
- throw new Error(`Message does not have id attribute. [${JSON.stringify(iPCMessagePayload)}]`);
142
- }
143
- return;
144
- }
145
- if (msg.command) //@@ constants
146
- {
147
- switch (msg.command)
148
- {
149
- case 'Terminate' :
150
- this.LogEx((`Received ` + colors.bold(`Terminate`.italic) + ` message from master thread`).gray);
151
- await this.Terminate(true, false); // Don't kill the child process here, the master will take care of that ...
152
- break;
153
- case 'TerminateAndKill' :
154
- this.LogEx((`Received ` + colors.bold(`Terminate`.italic) + ` message from master thread`).gray);
155
- await this.Terminate(true, true);
156
- break;
157
- case 'Message' :
158
- //this.LogEx((`Received ` + colors.bold(`Message`.italic) + ` message from master thread`).gray);
159
- this.ReceivedMessageFromMaster(msg.data);
160
- break;
161
- case 'Response' : // General response to a req/response interaction
162
- msg.details
163
- }
164
- }
165
- });
166
-
167
- // Signal Codes
168
- // https://en.wikipedia.org/wiki/Signal_(IPC)
169
- process.on('SIGTERM', async () =>
170
- {
171
- this.LogEx(`SIGTERM signal received for worker: ${process.pid}`);
172
- await this.Terminate(true, true);
173
- });
174
-
175
- process.on('SIGINT', async () =>
176
- {
177
- this.LogEx(`SIGINT signal received for worker: ${process.pid}`);
178
- await this.Terminate(true, true);
179
- });
180
-
181
- await this.SetupSTSServer();
182
-
183
- this.WorkerStarted();
184
-
185
- this.LogEx(chalk.green(`Worker process:${process.pid} started`));
186
- };
187
- }
@@ -1,37 +0,0 @@
1
- export enum Permission {
2
- STS_GLOBAL_ADMIN_PERMISSION = "STSGlobalAdminPermission",
3
-
4
- STSREST01_CREATE_PERMISSION = "STSREST01CreatePermission",
5
- STSREST01_READ_PERMISSION = "STSREST01ReadPermission",
6
- STSREST01_UPDATE_PERMISSION = "STSREST01UpdatePermission",
7
- STSREST01_DELETE_PERMISSION = "STSREST01DeletePermission",
8
-
9
- STSAUTH_LOGIN_PERMISSION = "STSAuthLoginPermission",
10
- STSAUTH_CREATE_PERMISSION = "STSAuthCreatePermission",
11
- STSAUTH_READ_PERMISSION = "STSAuthReadPermission",
12
- STSAUTH_UPDATE_PERMISSION = "STSAuthUpdatePermission",
13
- STSAUTH_DELETE_PERMISSION = "STSAuthDeletePermission",
14
-
15
- STSUITERMINAL_EXECUTE = "STSUITerminalExecute",
16
-
17
- STSCLI_EXECUTE = "STSCLIExecute",
18
-
19
- STSUIWEBAPP_EXECUTE = "STSUIWebAppExecute",
20
-
21
- STSUSERAGENTRUNNER_EXECUTE = "STSUserAgentRunnerExecute",
22
-
23
- STSINSTRUMENTMANAGER_CREATE_PERMISSION = "STSInstrumentManagerCreatePermission",
24
- STSINSTRUMENTMANAGER_READ_PERMISSION = "STSInstrumentManagerReadPermission",
25
- STSINSTRUMENTMANAGER_UPDATE_PERMISSION = "STSInstrumentManagerUpdatePermission",
26
- STSINSTRUMENTMANAGER_DELETE_PERMISSION = "STSInstrumentManagerDeletePermission",
27
-
28
- STSTESTORCHESTRATOR_CREATE_PERMISSION = "STSTestOrchestratorCreatePermission",
29
- STSTESTORCHESTRATOR_READ_PERMISSION = "STSTestOrchestratorReadPermission",
30
- STSTESTORCHESTRATOR_UPDATE_PERMISSION = "STSTestOrchestratorUpdatePermission",
31
- STSTESTORCHESTRATOR_DELETE_PERMISSION = "STSTestOrchestratorDeletePermission",
32
-
33
- STSTESTRUNNER_CREATE_PERMISSION = "STSTestRunnerCreatePermission",
34
- STSTESTRUNNER_READ_PERMISSION = "STSTestRunnerReadPermission",
35
- STSTESTRUNNER_UPDATE_PERMISSION = "STSTestRunnerUpdatePermission",
36
- STSTESTRUNNER_DELETE_PERMISSION = "STSTestRunnerDeletePermission"
37
- }
@@ -1,373 +0,0 @@
1
- import tough from 'tough-cookie';
2
- import https from 'https'
3
- import jwt from 'jsonwebtoken';
4
- import { jwtDecode } from "jwt-decode";
5
- import jwksClient from 'jwks-rsa';
6
-
7
- import axios from 'axios';
8
-
9
- import { $Options } from '@nsshunt/stsconfig'
10
- const goptions = $Options()
11
-
12
- import debugModule from 'debug'
13
-
14
- import { GetErrorPayload, JSONObject } from '@nsshunt/stsutils'
15
-
16
- import { AppFrameworkErrorCode } from './validation/errors'
17
-
18
- import { StatusCodes } from 'http-status-codes';
19
-
20
- export interface IAuthUtilsNodeOptions {
21
- permissions: string[]
22
- }
23
-
24
- /*
25
- export enum STSClientID {
26
- STSRest01Service = 'KgSyRECcvnJwwOZqf7GPqUw508sx7VBFEbDC0iP4oeY=',
27
- STSAuthService = 'q6a9F0kksXDDcrsCUKRwHKDnTNh7yZfxCShAgIJqfGg=',
28
- STSUITerminal = 'U0E4c4cuRKlBsGo7OhOl3qTkoNGFBXjORUS/T4R4xyA=',
29
- STSCLI = 'EcCpnQOIQFizAnWphlFJ4tSylosgVnwKTSNtgwuL2tw=',
30
- STSUIWebApp = 'lww8Je8n2P0OI/KEfJ+4p/bqsk8uE/noeq13tl4zlQ0=',
31
- XXSTSUserAgentRunnerX = 'y1h2nNr1BzTVPIzNmP/f041uxbnyZYTJeF/5GcwRCtw=',
32
- STSInstrumentManagerService = 'l8u2E912eR44ZYRHUkSBCCnDOXxQqYOPahDVQzYowrw=',
33
- STSTestOrchestratorService = 'CU1sVlS6vsEe3O3VvNzKFdBnQd9pQ83w9RyVx/7tJfc=',
34
- STSTestRunnerNode = 'aX9dJbsT06V1G4j06xEIQ/rZ2CDlpzggU58aLtZ8fzE=',
35
- STSBrokerService = 'TRppBuvxcjL7jrY9lCASJ5st8JpU8WlhAUAWoX/KKQ4=',
36
- STSTestingService = '4Mtb3ABdSzZvSz4T51HPJhT14znVnqVDRFiZsvDNAOg=',
37
- XXSTSAuthenticateSPAXX = 'v4qBrds3Autl/i86xT+5z0K53kJ/2hHTfxNo0QO/0Jk=',
38
- STSTestRunnerAgentSPA = 'yDbklCH3awzDNuHICuco9mjDqhdzCa8m7w/UE9Opexc=',
39
- STSClientApp01SPA = 'FDX/CPyDb3m6d9G2k+wDX8Uvey+yCkllaT4EuEt4QyU=',
40
- PowerPlatformCustomConnectorSPA = 'fcdcebb5-d154-4699-b99d-87d29e5e148f'
41
- }
42
- */
43
-
44
- export class AuthUtilsNode
45
- {
46
- #cookiejar: tough.CookieJar;
47
- #httpsAgent: https.Agent | null = null;
48
- #debug = debugModule(`proc:${process.pid}:AuthUtilsNode`);
49
- // Regular expression to match the origin
50
- #originRegex = /^(api:\/\/\w+)/;
51
-
52
- constructor() {
53
- this.#cookiejar = new tough.CookieJar();
54
- }
55
-
56
- #GetHttpsAgent = () =>
57
- {
58
- if (this.#httpsAgent === null) {
59
- // https://nodejs.org/api/http.html#class-httpagent
60
- this.#httpsAgent = new https.Agent({
61
- keepAlive: goptions.keepAlive,
62
- maxSockets: goptions.maxSockets,
63
- maxTotalSockets: goptions.maxTotalSockets,
64
- maxFreeSockets: goptions.maxFreeSockets,
65
- timeout: goptions.timeout,
66
- rejectUnauthorized: false
67
- });
68
- }
69
- return this.#httpsAgent;
70
- }
71
-
72
- VerifyRequestMiddlewareFactory(options: IAuthUtilsNodeOptions) {
73
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
74
- return async function(req: any, res: any, next: any) {
75
- if (options.permissions) {
76
- const scopes = req.auth.scope.split(' ');
77
- const requiredPermissions = [ ];
78
- for (let i=0; i < options.permissions.length; i++) {
79
- const permission = options.permissions[i];
80
- if (!scopes.includes(permission)) {
81
- requiredPermissions.push(permission);
82
- }
83
- }
84
- if (requiredPermissions.length > 0) {
85
- const errorPayload = GetErrorPayload(AppFrameworkErrorCode.APPFRAMEWORK_MISSING_PERMISSION, requiredPermissions);
86
- res.status(StatusCodes.UNAUTHORIZED).send( { status: StatusCodes.UNAUTHORIZED, error: errorPayload });
87
- return;
88
- }
89
- }
90
- next();
91
- }
92
- }
93
- /*
94
- let cookies = await this.GetCookiesFromJar();
95
- const valid = this.#ValidateCookies(cookies);
96
- if (valid) {
97
- next();
98
- } else {
99
- const error = { }; //@@
100
- const invalidToken = false; //@@
101
- if (invalidToken)
102
- {
103
- res.status(StatusCodes.UNAUTHORIZED).send( { status: StatusCodes.UNAUTHORIZED, error: 'Invalid Token', detail: error } );
104
- } else{
105
- res.status(StatusCodes.INTERNAL_SERVER_ERROR).send( { status: StatusCodes.INTERNAL_SERVER_ERROR, error: 'Operation was not successful', detail: error } );
106
- }
107
- }
108
- */
109
-
110
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
111
- async verifyRequestMiddleware(req: any, res: any, next: any)
112
- {
113
- next();
114
- /*
115
-
116
- let cookies = await this.GetCookiesFromJar();
117
-
118
- const valid = this.#ValidateCookies(cookies);
119
-
120
- if (valid) {
121
- next();
122
- } else {
123
- const error = { }; //@@
124
- const invalidToken = false; //@@
125
- if (invalidToken)
126
- {
127
- res.status(StatusCodes.UNAUTHORIZED).send( { status: StatusCodes.UNAUTHORIZED, error: 'Invalid Token', detail: error } );
128
- } else{
129
- res.status(StatusCodes.INTERNAL_SERVER_ERROR).send( { status: StatusCodes.INTERNAL_SERVER_ERROR, error: 'Operation was not successful', detail: error } );
130
- }
131
- }
132
- */
133
- }
134
-
135
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
136
- SetCookiesToJar = async (headers: Record<string, any>, endpoint: string): Promise<tough.Cookie[]> =>
137
- {
138
- if (headers['set-cookie']) {
139
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
140
- headers['set-cookie'].map((headerCookie: any) => {
141
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
142
- const cookie: any = tough.Cookie.parse(headerCookie);
143
- this.#cookiejar.setCookieSync(cookie, endpoint);
144
- });
145
- } else {
146
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
147
- const cookie: any = tough.Cookie.parse(headers['set-cookie']);
148
- this.#cookiejar.setCookieSync(cookie, endpoint);
149
- }
150
-
151
- return this.#cookiejar.getCookies(endpoint);
152
- };
153
-
154
- GetCookiesFromJar = async (endpoint: string): Promise<tough.Cookie[]> =>
155
- {
156
- return this.#cookiejar.getCookies(endpoint);
157
- };
158
-
159
- ValidateJWT = async (token: string, audience: string, endpoint?: string): Promise<string> => {
160
- const jwksClientUri = (endpoint
161
- ? `${endpoint}${goptions.asoauthapiroot}${goptions.asjwksjsonpath}`
162
- : `${goptions.asendpoint}:${goptions.asport}${goptions.asoauthapiroot}${goptions.asjwksjsonpath}`);
163
-
164
- const jwks = jwksClient({
165
- cache: true, //@@ all config items
166
- cacheMaxEntries: 5, // Default value
167
- cacheMaxAge: 600000, // Defaults to 10m
168
- rateLimit: true,
169
- jwksRequestsPerMinute: 10, // Default value
170
- jwksUri: jwksClientUri,
171
- timeout: 30000, //@@ config
172
- requestAgent: this.#GetHttpsAgent()
173
- });
174
-
175
- // Use decode to get the kid
176
- const decodedRefreshToken = jwtDecode<JSONObject>(token, { header: true });
177
- const kid = decodedRefreshToken.kid;
178
-
179
- const key = await jwks.getSigningKey(kid);
180
- const signingKey = key.getPublicKey();
181
-
182
- const verifyOptions = {
183
- issuer: 'https://stsmda.com.au/stsauth/',
184
- //subject: s,
185
- audience: audience,
186
- //expiresIn: 600, // 10 minutes
187
- algorithm: ["RS256"] // RSASSA [ "RS256", "RS384", "RS512" ]
188
- };
189
-
190
- return jwt.verify(token, signingKey, verifyOptions) as string;
191
- }
192
-
193
- // Function to extract the origin from a URI
194
- ExtractOrigin = (uri: string) => {
195
- const match = uri.match(this.#originRegex);
196
- return match ? match[1] : null;
197
- }
198
-
199
- /**
200
- *
201
- * @param clientId
202
- * @param authClientSecret
203
- * @param scope space seperate list of fully qualifed required scopes (i.e. api://<<api id>>/<<resource>>.<<permission>>). Note the scopes must all be for the same client api.
204
- * @param endPoint
205
- * @returns
206
- */
207
- GetAPITokenFromAuthServerUsingScope = async (clientId: string, authClientSecret: string, scope: string, endPoint?: string): Promise<string> => {
208
- try {
209
- const scopes = scope.split(' ');
210
- let origin: string | null = null;
211
- scopes.forEach((s) => {
212
- if (!origin) {
213
- origin = this.ExtractOrigin(s);
214
- if (!origin) {
215
- throw new Error(`Scope: [${scope}] not in required format. Must use (space seperated) api://<client id>[/<resource>.<permission>].`);
216
- }
217
- } else {
218
- const nextOrigin: string | null = this.ExtractOrigin(s);
219
- if (!nextOrigin) {
220
- throw new Error(`Scope: [${scope}] not in required format. Must use (space seperated) api://<client id>[/<resource>.<permission>].`);
221
- } else {
222
- if (origin.localeCompare(nextOrigin) !== 0) {
223
- throw new Error(`Scope: [${scope}] not all from the same client API. All scopes must come from the same client API.`);
224
- }
225
- }
226
- }
227
- });
228
-
229
- const headers = { 'Content-Type': 'application/json'};
230
- const payload = { //@@ make a type
231
- client_id: clientId, // The service calling this method
232
- client_secret: authClientSecret, // Auth service client secret
233
- //client_secret: goptions.brokerclientsecret, // Broker service client secret
234
- scope: scope, // required API
235
- //@@ remove audience
236
- //@@ need scope to be the API identifier
237
- grant_type: "client_credentials"
238
- }
239
- const url = (endPoint
240
- ? `${endPoint}${goptions.asoauthapiroot}/token`
241
- : `${goptions.asendpoint}:${goptions.asport}${goptions.asoauthapiroot}/token`);
242
- const retVal = await axios({
243
- url
244
- ,method: 'post'
245
- ,data: payload
246
- ,headers: headers
247
- ,httpsAgent: this.#GetHttpsAgent()
248
- });
249
-
250
- if (retVal.status) {
251
- if (retVal.status !== 200) {
252
- // Just provide a warning here
253
- this.#debug(`Error (AuthUtilsNode:GetAPITokenFromServer): Invalid response from server: [${retVal.status}]`.magenta);
254
- }
255
- } else {
256
- const msg = `Error (AuthUtilsNode:GetAPITokenFromServer:No retVal.status)`.red
257
- this.#debug(msg);
258
- throw new Error(msg);
259
- }
260
- if (retVal.data) {
261
- if (retVal.data.access_token) {
262
- return retVal.data.access_token as string;
263
- } else {
264
- const msg = `Error (AuthUtilsNode:GetAPITokenFromServer:No retVal.data.access_token)`.red
265
- this.#debug(msg);
266
- throw new Error(msg);
267
- }
268
- } else {
269
- const msg = `Error (AuthUtilsNode:GetAPITokenFromServer:No retVal.data)`.red
270
- this.#debug(msg);
271
- throw new Error(msg);
272
- }
273
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
274
- } catch (error: any) {
275
- this.#debug(`Error (AuthUtilsNode:GetAPITokenFromServer:catch): ${error}`.red);
276
- if (error.response && error.response.data) {
277
- this.#debug(`Details: [${JSON.stringify(error.response.data)}]`.red);
278
- }
279
- throw error;
280
- }
281
- }
282
-
283
- /*
284
- #getHttpsAgent = () =>
285
- {
286
- if (this.#httpsAgent === null) {
287
- // https://nodejs.org/api/http.html#class-httpagent
288
- this.#httpsAgent = new https.Agent({
289
- keepAlive: goptions.keepAlive,
290
- maxSockets: goptions.maxSockets,
291
- maxTotalSockets: goptions.maxTotalSockets,
292
- maxFreeSockets: goptions.maxFreeSockets,
293
- timeout: goptions.timeout,
294
- rejectUnauthorized: goptions.isProduction // Allows self signed certs in non production mode(s)
295
- });
296
- }
297
- return this.#httpsAgent;
298
- }
299
-
300
- Login = async (opts) =>
301
- {
302
- const { authendpoint, authUserName, authUserEMail, authUserPassword, defaultTimeout, publishDebug } = opts;
303
- try {
304
- const processStart = performance.now();
305
- let duration = '';
306
- let loginData = null;
307
- const payload = { name: authUserName, password: authUserPassword, email: authUserEMail }
308
- const retVal = await axios({
309
- url: `${authendpoint}/login`
310
- ,method: 'post'
311
- ,data: payload
312
- ,timeout: defaultTimeout
313
- ,httpsAgent: this.#getHttpsAgent()
314
- // Use below if using a socket endpoint
315
- //,socketPath: '/var/run/sts/stsrest01.sock'
316
- });
317
- duration = (performance.now() - processStart).toFixed(4);
318
- if (publishDebug) debug(`AuthUtilsNode.LoginNode request duration: [${duration}]`);
319
- loginData = retVal.data.detail;
320
-
321
-
322
- if (retVal.headers['set-cookie'] instanceof Array) {
323
- this.#cookies = retVal.headers['set-cookie'].map(cookie.parse);
324
- } else {
325
- this.#cookies = [cookie.parse(retVal.headers['set-cookie'])];
326
- }
327
-
328
- //await this.SetCookiesToJar(retVal.headers);
329
-
330
- return loginData;
331
- } catch (error)
332
- {
333
- if (publishDebug) debug(`Error (AuthUtilsNode:LoginNode): ${error}`.red);
334
- throw error;
335
- }
336
- }
337
-
338
- // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
339
- // axios.get('some api url', {withCredentials: true});
340
- // https://medium.com/@adityasrivast/handling-cookies-with-axios-872790241a9b
341
- // https://www.codegrepper.com/code-examples/javascript/axios+send+cookies
342
- // http only cookies
343
- RefreshSessionToken = async (opts) =>
344
- {
345
- const { authendpoint, defaultTimeout, publishDebug } = opts;
346
- try {
347
- const processStart = performance.now();
348
- let duration = '';
349
- let loginData = null;
350
- const cookies = await this.GetCookiesFromJar();
351
- const retVal = await axios({
352
- url: `${authendpoint}/refreshtoken`
353
- ,method: 'post'
354
- ,headers: {
355
- Cookie: cookies
356
- }
357
- ,timeout: defaultTimeout
358
- ,httpsAgent: this.#httpsAgent,
359
- // Use below for socket connections
360
- //,socketPath: '/var/run/sts/stsrest01.sock'
361
- });
362
- duration = (performance.now() - processStart).toFixed(4);
363
- if (publishDebug) debug(`AuthUtilsNode.RefreshAuthTokenBrowser request duration: [${duration}]`);
364
- loginData = retVal.data.detail;
365
- await this.SetCookiesToJar(retVal.headers);
366
- return loginData;
367
- } catch (error) {
368
- if (publishDebug) debug(`Error (AuthUtilsNode:RefreshAuthTokenBrowser): ${error}`.red);
369
- throw error;
370
- }
371
- }
372
- */
373
- }