@nsshunt/stsutils 1.4.0 → 1.5.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.
@@ -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)(`AuthUtils.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 (AuthUtils: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)(`AuthUtils.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 (AuthUtils: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.4.0",
3
+ "version": "1.5.5",
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",
@@ -34,6 +34,7 @@
34
34
  "colors": "^1.4.0",
35
35
  "debug": "^4.3.3",
36
36
  "express": "^4.17.1",
37
- "jsonwebtoken": "^8.5.1"
37
+ "jsonwebtoken": "^8.5.1",
38
+ "tough-cookie": "^4.0.0"
38
39
  }
39
40
  }
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,110 +0,0 @@
1
- const jwt = require('jsonwebtoken');
2
- const { status } = require('./status');
3
- const fs = require('fs');
4
- const goptions = require('@nsshunt/stsconfig').$options;
5
-
6
- class AuthUtils
7
- {
8
- #privateKey = null;
9
- #publicKey = null;
10
-
11
- constructor()
12
- {
13
- // On-line key generators
14
- // http://travistidwell.com/jsencrypt/demo/
15
- // https://www.csfieldguide.org.nz/en/interactives/rsa-key-generator/
16
- // https://jwt.io/
17
-
18
- // This code is for development / non-prod purposes only.
19
- // For production, the keys to come from a secrets store.
20
- this.#privateKey = fs.readFileSync(goptions.asprivatekeypath, 'utf8');
21
- this.#publicKey = fs.readFileSync(goptions.aspublickeypath, 'utf8');
22
- }
23
-
24
- get privateKey()
25
- {
26
- return this.#privateKey;
27
- }
28
-
29
- get publicKey()
30
- {
31
- return this.#publicKey;
32
- }
33
-
34
- /*
35
- // Source;
36
- // https://github.com/auth0/jwt-decode/issues/53
37
- #assertAlive(decoded)
38
- {
39
- const now = Date.now().valueOf() / 1000
40
- if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
41
- throw new Error(`token expired: ${JSON.stringify(decoded)}`)
42
- }
43
- if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
44
- throw new Error(`token not yet valid: ${JSON.stringify(decoded)}`)
45
- }
46
- }
47
-
48
- #tokenTimeLeft(decoded)
49
- {
50
- const now = Date.now().valueOf() / 1000;
51
- return now - decoded.exp;
52
- }
53
- */
54
-
55
- async verifyRequestMiddleware(req, res, next)
56
- {
57
- try
58
- {
59
- let authHeader = req.header('Authorization');
60
- if (authHeader === undefined)
61
- {
62
- res.status(status.unauthorized).send( { status: status.unauthorized, error: 'Token not preset', detail: { message: 'The Authorization header not provided.' } } );
63
- return;
64
- }
65
- let authType = authHeader.split(' ')[0];
66
- let token = authHeader.split(' ')[1];
67
-
68
- if (authType !== 'Bearer')
69
- {
70
- res.status(status.unauthorized).send( { status: status.unauthorized, error: 'Token not preset', detail: { message: 'The Authorization type provided is not Bearer.' } } );
71
- return;
72
- }
73
-
74
- let i = 'STS';
75
- //let s = user.id;
76
- //let a = user.email;
77
-
78
- let verifyOptions =
79
- {
80
- issuer: i,
81
- //subject: s,
82
- //audience: a,
83
- //expiresIn: 600, // 10 minutes
84
- algorithm: ["RS256"] // RSASSA [ "RS256", "RS384", "RS512" ]
85
- };
86
-
87
- let retVal = jwt.verify(token, this.#publicKey, verifyOptions);
88
-
89
- req.stsuser = {
90
- email: retVal.user.email,
91
- userid: retVal.user.id,
92
- isadmin: false,
93
- firstname: retVal.user.name,
94
- lastname: 'NA'
95
- };
96
-
97
- next();
98
- } catch (error)
99
- {
100
- if (error instanceof jwt.JsonWebTokenError)
101
- {
102
- res.status(status.unauthorized).send( { status: status.unauthorized, error: 'Invalid Token', detail: error } );
103
- } else{
104
- res.status(status.error).send( { status: status.error, error: 'Operation was not successful', detail: error } );
105
- }
106
- }
107
- }
108
- }
109
-
110
- 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 };