@nsshunt/stsutils 1.5.0 → 1.5.6

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.
@@ -0,0 +1,87 @@
1
+ const debug = require('debug')(`stsutils`);
2
+ const colors = require('colors');
3
+ const axios = require('axios');
4
+
5
+ class AuthUtilsBrowser
6
+ {
7
+ constructor()
8
+ {
9
+
10
+ }
11
+
12
+ #GetDurationColour(duration)
13
+ {
14
+ if (duration > 250) {
15
+ return colors.red;
16
+ } else if (duration > 150) {
17
+ return colors.magenta;
18
+ } else if (duration > 50) {
19
+ return colors.blue;
20
+ } else if (duration > 10) {
21
+ return colors.green;
22
+ } else {
23
+ return colors.black;
24
+ }
25
+ }
26
+
27
+ LoginBrowser = async (options) => {
28
+ const { authendpoint, authUserName, authUserEMail, authUserPassword, defaultTimeout, publishDebug } = options;
29
+ try {
30
+ let processStart = performance.now();
31
+ let duration = 0;
32
+ let accessToken = null;
33
+ let payload = { name: authUserName, password: authUserPassword, email: authUserEMail }
34
+ let retVal = await axios({
35
+ url: `${authendpoint}/login`
36
+ ,method: 'post'
37
+ ,data: payload
38
+ ,timeout: defaultTimeout
39
+ });
40
+ duration = (performance.now() - processStart).toFixed(4);
41
+ if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtilsBrowser.LoginBrowser request duration: [${duration}]`));
42
+ accessToken = retVal.data.detail.token;
43
+ return {
44
+ accessToken: accessToken,
45
+ duration: duration
46
+ }
47
+ } catch (error) {
48
+ if (publishDebug) debug(`Error (AuthUtilsBrowser:LoginBrowser): ${error}`.red);
49
+ throw error;
50
+ }
51
+ };
52
+
53
+ // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
54
+ // axios.get('some api url', {withCredentials: true});
55
+ // https://medium.com/@adityasrivast/handling-cookies-with-axios-872790241a9b
56
+ // https://www.codegrepper.com/code-examples/javascript/axios+send+cookies
57
+ // http only cookies
58
+ RefreshAuthTokenBrowser = async (options) => {
59
+ const { authendpoint, defaultTimeout, publishDebug } = options;
60
+ try {
61
+ let processStart = performance.now();
62
+ let duration = 0;
63
+ let accessToken = null;
64
+ // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
65
+ // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
66
+ // axios.get('some api url', {withCredentials: true});
67
+ let retVal = await axios({
68
+ url: `${authendpoint}/refreshtoken`
69
+ ,method: 'post'
70
+ ,timeout: defaultTimeout
71
+ ,withCredentials: true
72
+ });
73
+ duration = (performance.now() - processStart).toFixed(4);
74
+ if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtilsBrowser.RefreshAuthTokenBrowser request duration: [${duration}]`));
75
+ accessToken = retVal.data.detail.token;
76
+ return {
77
+ accessToken: accessToken,
78
+ duration: duration
79
+ }
80
+ } catch (error) {
81
+ if (publishDebug) debug(`Error (AuthUtilsBrowser:RefreshAuthTokenBrowser): ${error}`.red);
82
+ throw error;
83
+ }
84
+ }
85
+ }
86
+
87
+ module.exports = AuthUtilsBrowser;
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ let sleep = require('./sleep.js');
2
+ let status = require('./status.js');
3
+ const AuthUtilsBrowser = require('./authutilsbrowser.js');
4
+ const STSOptionsBase = require('./stsoptionsbase.js');
5
+
6
+ module.exports = { sleep, status, STSOptionsBase, AuthUtilsBrowser };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@nsshunt/stsutils",
3
- "version": "1.5.0",
3
+ "version": "1.5.6",
4
4
  "description": "",
5
- "main": "stsutils.js",
5
+ "main": "index.js",
6
6
  "scripts": {
7
7
  "lint": "eslint . --ext js,jsx,ts,tsx --fix",
8
8
  "test": "jest --detectOpenHandles --no-cache",
package/stsoptionsbase.js CHANGED
@@ -21,4 +21,4 @@ class STSOptionsBase
21
21
  }
22
22
  }
23
23
 
24
- module.exports = { STSOptionsBase };
24
+ module.exports = STSOptionsBase;
package/authutils.js DELETED
@@ -1,293 +0,0 @@
1
- const debug = require('debug')(`stsutils`);
2
- const jwt = require('jsonwebtoken');
3
- const { status } = require('./status');
4
- const fs = require('fs');
5
- const goptions = require('@nsshunt/stsconfig').$options;
6
- const tough = require('tough-cookie');
7
- const Cookie = tough.Cookie;
8
- const cookiejar = new tough.CookieJar();
9
- const colors = require('colors');
10
- const axios = require('axios');
11
- const http = require('http');
12
-
13
- class AuthUtils
14
- {
15
- #privateKey = null;
16
- #publicKey = null;
17
- #httpAgent = null;
18
-
19
- constructor()
20
- {
21
- // On-line key generators
22
- // http://travistidwell.com/jsencrypt/demo/
23
- // https://www.csfieldguide.org.nz/en/interactives/rsa-key-generator/
24
- // https://jwt.io/
25
-
26
- // This code is for development / non-prod purposes only.
27
- // For production, the keys to come from a secrets store.
28
- this.#privateKey = fs.readFileSync(goptions.asprivatekeypath, 'utf8');
29
- this.#publicKey = fs.readFileSync(goptions.aspublickeypath, 'utf8');
30
- }
31
-
32
- get privateKey()
33
- {
34
- return this.#privateKey;
35
- }
36
-
37
- get publicKey()
38
- {
39
- return this.#publicKey;
40
- }
41
-
42
- /*
43
- // Source;
44
- // https://github.com/auth0/jwt-decode/issues/53
45
- #assertAlive(decoded)
46
- {
47
- const now = Date.now().valueOf() / 1000
48
- if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
49
- throw new Error(`token expired: ${JSON.stringify(decoded)}`)
50
- }
51
- if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
52
- throw new Error(`token not yet valid: ${JSON.stringify(decoded)}`)
53
- }
54
- }
55
-
56
- #tokenTimeLeft(decoded)
57
- {
58
- const now = Date.now().valueOf() / 1000;
59
- return now - decoded.exp;
60
- }
61
- */
62
-
63
- async verifyRequestMiddleware(req, res, next)
64
- {
65
- try
66
- {
67
- let authHeader = req.header('Authorization');
68
- if (authHeader === undefined)
69
- {
70
- res.status(status.unauthorized).send( { status: status.unauthorized, error: 'Token not preset', detail: { message: 'The Authorization header not provided.' } } );
71
- return;
72
- }
73
- let authType = authHeader.split(' ')[0];
74
- let token = authHeader.split(' ')[1];
75
-
76
- if (authType !== 'Bearer')
77
- {
78
- res.status(status.unauthorized).send( { status: status.unauthorized, error: 'Token not preset', detail: { message: 'The Authorization type provided is not Bearer.' } } );
79
- return;
80
- }
81
-
82
- let i = 'STS';
83
- //let s = user.id;
84
- //let a = user.email;
85
-
86
- let verifyOptions =
87
- {
88
- issuer: i,
89
- //subject: s,
90
- //audience: a,
91
- //expiresIn: 600, // 10 minutes
92
- algorithm: ["RS256"] // RSASSA [ "RS256", "RS384", "RS512" ]
93
- };
94
-
95
- let retVal = jwt.verify(token, this.#publicKey, verifyOptions);
96
-
97
- req.stsuser = {
98
- email: retVal.user.email,
99
- userid: retVal.user.id,
100
- isadmin: false,
101
- firstname: retVal.user.name,
102
- lastname: 'NA'
103
- };
104
-
105
- next();
106
- } catch (error)
107
- {
108
- if (error instanceof jwt.JsonWebTokenError)
109
- {
110
- res.status(status.unauthorized).send( { status: status.unauthorized, error: 'Invalid Token', detail: error } );
111
- } else{
112
- res.status(status.error).send( { status: status.error, error: 'Operation was not successful', detail: error } );
113
- }
114
- }
115
- }
116
-
117
- #GetDurationColour(duration)
118
- {
119
- if (duration > 250) {
120
- return colors.red;
121
- } else if (duration > 150) {
122
- return colors.magenta;
123
- } else if (duration > 50) {
124
- return colors.blue;
125
- } else if (duration > 10) {
126
- return colors.green;
127
- } else {
128
- return colors.black;
129
- }
130
- }
131
-
132
- LoginBrowser = async (options) => {
133
- const { authendpoint, authUserName, authUserEMail, authUserPassword, defaultTimeout, publishDebug } = options;
134
- try {
135
- let processStart = performance.now();
136
- let duration = 0;
137
- let accessToken = null;
138
- let payload = { name: authUserName, password: authUserPassword, email: authUserEMail }
139
- let retVal = await axios({
140
- url: `${authendpoint}/login`
141
- ,method: 'post'
142
- ,data: payload
143
- ,timeout: defaultTimeout
144
- });
145
- duration = (performance.now() - processStart).toFixed(4);
146
- if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtils.LoginBrowser request duration: [${duration}]`));
147
- accessToken = retVal.data.detail.token;
148
- return {
149
- accessToken: accessToken,
150
- duration: duration
151
- }
152
- } catch (error) {
153
- if (publishDebug) debug(`Error (AuthUtils:LoginBrowser): ${error}`.red);
154
- throw error;
155
- }
156
- };
157
-
158
- // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
159
- // axios.get('some api url', {withCredentials: true});
160
- // https://medium.com/@adityasrivast/handling-cookies-with-axios-872790241a9b
161
- // https://www.codegrepper.com/code-examples/javascript/axios+send+cookies
162
- // http only cookies
163
- RefreshAuthTokenBrowser = async (options) => {
164
- const { authendpoint, defaultTimeout, publishDebug } = options;
165
- try {
166
- let processStart = performance.now();
167
- let duration = 0;
168
- let accessToken = null;
169
- // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
170
- // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
171
- // axios.get('some api url', {withCredentials: true});
172
- let retVal = await axios({
173
- url: `${authendpoint}/refreshtoken`
174
- ,method: 'post'
175
- ,timeout: defaultTimeout
176
- ,withCredentials: true
177
- });
178
- duration = (performance.now() - processStart).toFixed(4);
179
- if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtils.RefreshAuthTokenBrowser request duration: [${duration}]`));
180
- accessToken = retVal.data.detail.token;
181
- return {
182
- accessToken: accessToken,
183
- duration: duration
184
- }
185
- } catch (error) {
186
- if (publishDebug) debug(`Error (AuthUtils:RefreshAuthTokenBrowser): ${error}`.red);
187
- throw error;
188
- }
189
- }
190
-
191
- #setCookiesToJar = (authendpoint, headers) =>
192
- {
193
- let cookies = null;
194
- if (headers['set-cookie'] instanceof Array)
195
- cookies = headers['set-cookie'].map(Cookie.parse);
196
- else
197
- cookies = [Cookie.parse(headers['set-cookie'])];
198
-
199
- return cookiejar.setCookie(cookies[0], `${authendpoint}`);
200
- };
201
-
202
- #getCookiesFromJar = (authendpoint) =>
203
- {
204
- return cookiejar.getCookies(`${authendpoint}`);
205
- };
206
-
207
- #getHttpAgent = () =>
208
- {
209
- if (this.#httpAgent === null) {
210
- // https://nodejs.org/api/http.html#class-httpagent
211
- this.#httpAgent = new http.Agent({
212
- keepAlive: true,
213
- maxSockets: 10,
214
- maxTotalSockets: 10,
215
- maxFreeSockets: 10,
216
- timeout: 5000
217
- });
218
- }
219
- return this.#httpAgent;
220
- }
221
-
222
- LoginNode = async (options) =>
223
- {
224
- const { authendpoint, authUserName, authUserEMail, authUserPassword, defaultTimeout, publishDebug } = options;
225
- try {
226
- let processStart = performance.now();
227
- let duration = 0;
228
- let accessToken = null;
229
- let payload = { name: authUserName, password: authUserPassword, email: authUserEMail }
230
- let retVal = await axios({
231
- url: `${authendpoint}/login`
232
- ,method: 'post'
233
- ,data: payload
234
- ,timeout: defaultTimeout
235
- ,httpAgent: this.#getHttpAgent()
236
- // Use below if using a socket endpoint
237
- //,socketPath: '/var/run/sts/stsrest01.sock'
238
- });
239
- duration = (performance.now() - processStart).toFixed(4);
240
- if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtils.LoginNode request duration: [${duration}]`));
241
- accessToken = retVal.data.detail.token;
242
- await this.#setCookiesToJar(authendpoint, retVal.headers);
243
- return {
244
- accessToken: accessToken,
245
- duration: duration
246
- }
247
- } catch (error)
248
- {
249
- if (publishDebug) debug(`Error (AuthUtils:LoginNode): ${error}`.red);
250
- throw error;
251
- }
252
- }
253
-
254
- // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
255
- // axios.get('some api url', {withCredentials: true});
256
- // https://medium.com/@adityasrivast/handling-cookies-with-axios-872790241a9b
257
- // https://www.codegrepper.com/code-examples/javascript/axios+send+cookies
258
- // http only cookies
259
- RefreshAuthTokenNode = async (options) =>
260
- {
261
- const { authendpoint, defaultTimeout, publishDebug } = options;
262
- try {
263
- let processStart = performance.now();
264
- let duration = 0;
265
- let accessToken = null;
266
- let cookies = await this.#getCookiesFromJar(authendpoint);
267
- let retVal = await axios({
268
- url: `${authendpoint}/refreshtoken`
269
- ,method: 'post'
270
- ,headers: {
271
- Cookie: cookies
272
- }
273
- ,timeout: defaultTimeout
274
- ,httpAgent: this.#httpAgent,
275
- // Use below for socket connections
276
- //,socketPath: '/var/run/sts/stsrest01.sock'
277
- });
278
- duration = (performance.now() - processStart).toFixed(4);
279
- if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtils.RefreshAuthTokenBrowser request duration: [${duration}]`));
280
- accessToken = retVal.data.detail.token;
281
- await this.#setCookiesToJar(authendpoint, retVal.headers);
282
- return {
283
- accessToken: accessToken,
284
- duration: duration
285
- }
286
- } catch (error) {
287
- if (publishDebug) debug(`Error (AuthUtils:RefreshAuthTokenBrowser): ${error}`.red);
288
- throw error;
289
- }
290
- }
291
- }
292
-
293
- module.exports = { AuthUtils };
package/log.js DELETED
@@ -1,33 +0,0 @@
1
- const cluster = require('cluster');
2
- const colors = require('colors');
3
- const debug = require('debug')(`proc:${process.pid}`);
4
-
5
- /**
6
- * Default styles :-
7
- * Worker messages - green
8
- * Master messages - cyan + bold
9
- * IPC Messages - grey. The message command itself will be bold.
10
- * Signals - yellow (e.g. SIGINT or SIGTERM etc.
11
- * @param {*} instruments
12
- * @returns
13
- */
14
- module.exports = (appName, instruments) =>
15
- {
16
- return (msg) =>
17
- {
18
- let prefix = '';
19
- let col = null;
20
-
21
- if (cluster.isMaster)
22
- {
23
- prefix = 'M';
24
- col = colors.bold.cyan;
25
- } else {
26
- prefix = 'W';
27
- col = colors.green;
28
- }
29
- let msgEx = col(`${prefix}(${process.pid}) [${appName}]: ${msg}`);
30
- debug(msgEx);
31
- instruments.logger.LogMessage(msgEx);
32
- };
33
- };
package/network.js DELETED
@@ -1,37 +0,0 @@
1
- const os = require('os');
2
-
3
- const GetNetworkInterfaces = () =>
4
- {
5
- const nets = os.networkInterfaces();
6
- let results = { };
7
- for (const name of Object.keys(nets)) {
8
- for (const net of nets[name]) {
9
- // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
10
- if (net.family === 'IPv4' && !net.internal) {
11
- if (!results[name]) {
12
- results[name] = [];
13
- }
14
- results[name].push(net.address);
15
- }
16
- }
17
- }
18
- return results;
19
- };
20
-
21
- const GetFirstNetworkInterface = () =>
22
- {
23
- let nics = GetNetworkInterfaces();
24
- let hostaddr = null;
25
- for (let nic in nics)
26
- {
27
- let val = nics[nic];
28
- if (val.length > 0)
29
- {
30
- hostaddr = val[0];
31
- break;
32
- }
33
- }
34
- return hostaddr;
35
- }
36
-
37
- module.exports = { GetNetworkInterfaces, GetFirstNetworkInterface }
package/stsrouterbase.js DELETED
@@ -1,21 +0,0 @@
1
- const express = require('express');
2
-
3
- const { STSOptionsBase } = require('./stsoptionsbase.js');
4
-
5
- class STSRouterBase extends STSOptionsBase
6
- {
7
- #router = null;
8
-
9
- constructor(options)
10
- {
11
- super(options);
12
- this.#router = express.Router();
13
- }
14
-
15
- get Router()
16
- {
17
- return this.#router;
18
- }
19
- }
20
-
21
- module.exports = { STSRouterBase };
package/stsutils.js DELETED
@@ -1,9 +0,0 @@
1
- let sleep = require('./sleep.js');
2
- let status = require('./status.js');
3
- let network = require('./network.js');
4
- let authutils = require('./authutils.js');
5
- let stsoptionsbase = require('./stsoptionsbase.js');
6
- let stsrouterbase = require('./stsrouterbase.js');
7
- let log = require('./log.js');
8
-
9
- module.exports = { sleep, status, network, authutils, stsoptionsbase, stsrouterbase, log };