@simpleview/sv-auth-client 4.4.5-0 → 4.4.6-0

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/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@simpleview/sv-auth-client",
3
- "version": "4.4.5-0",
3
+ "version": "4.4.6-0",
4
4
  "description": "Client for communicating with sv-auth",
5
5
  "author": "Owen Allen <owenallenaz@gmail.com>",
6
6
  "dependencies": {
7
7
  "@simpleview/sv-graphql-client": ">=1.3.0",
8
8
  "graphql": "14.2.1",
9
- "graphql-tools": "4.0.4"
9
+ "graphql-tools": "4.0.4",
10
+ "jsonwebtoken": "8.5.1"
10
11
  },
11
12
  "devDependencies": {
12
13
  "@simpleview/mochalib": "1.0.1",
@@ -0,0 +1,139 @@
1
+ const { decode } = require("jsonwebtoken");
2
+
3
+ const {
4
+ oauth2CreateLoginUrl,
5
+ oauth2CreateRandomKey,
6
+ oauth2Token
7
+ } = require("../src/oauth2");
8
+
9
+ const {
10
+ asyncWrapper
11
+ } = require("../src/utils");
12
+
13
+ class Oauth2Express {
14
+ constructor({ authUrl = "https://auth.simpleviewinc.com/", client_id, callbackPath = "/oauth2/callback/", logoutPath = "/logout/", createParams }) {
15
+ const validUrls = [
16
+ "https://auth.simpleviewinc.com/",
17
+ "https://auth.dev.simpleviewinc.com/",
18
+ "https://auth.qa.simpleviewinc.com/",
19
+ "https://auth.kube.simpleview.io/"
20
+ ]
21
+
22
+ if (validUrls.indexOf(authUrl) === -1 && !/http[^.]+.ui-service.default.svc.cluster.local/.test(authUrl)) {
23
+ throw new Error("authUrl must be one of " + validUrls.join(", "));
24
+ }
25
+
26
+ if (!client_id) {
27
+ throw new Error("client_id is required.")
28
+ }
29
+
30
+ Object.assign(this, {
31
+ authUrl,
32
+ client_id,
33
+ callbackPath,
34
+ logoutPath,
35
+ createParams
36
+ });
37
+
38
+ this.middleware = asyncWrapper(middleware.bind(this));
39
+ this.callback = asyncWrapper(callback.bind(this));
40
+ this.logout = asyncWrapper(logout.bind(this));
41
+ }
42
+
43
+ }
44
+
45
+ async function middleware (req, res, next) {
46
+ if (req.session?.user?.exp - Date.now() / 1000 < 60 * 10) {
47
+ return oauth2Token({
48
+ authUrl: this.authUrl,
49
+ grant_type: "refresh_token",
50
+ refresh_token: req.session.refresh_token
51
+ });
52
+ }
53
+
54
+ if (!req.session?.token || !req.session?.refresh_token) {
55
+ req.session.state = oauth2CreateRandomKey();
56
+
57
+ req.session.code_verifier = oauth2CreateRandomKey();
58
+
59
+ const { protocol, hostname, originalUrl, session } = req;
60
+
61
+ const loginUrl = oauth2CreateLoginUrl({
62
+ authUrl: this.authUrl,
63
+ client_id: this.client_id,
64
+ redirect_uri: `${protocol}://${hostname}${this.callbackPath}`,
65
+ redirectUrl: `${protocol}://${hostname}${originalUrl}`,
66
+ sv_auth_params: this.createParams && this.createParams(req),
67
+ state: session.state,
68
+ code_verifier: session.code_verifier
69
+ });
70
+
71
+ return res.redirect(302, loginUrl);
72
+ }
73
+
74
+ return next();
75
+ }
76
+
77
+
78
+ async function callback(req, res) {
79
+ const { state, code, redirectUrl, error, error_description } = req.query;
80
+
81
+ if (error) {
82
+ throw new Error(`${error}${error_description ? ": " + error_description : ""}`);
83
+ }
84
+
85
+ if (req.session.state !== state) {
86
+ throw new Error("State returned does not match stored state.");
87
+ }
88
+
89
+ if (!code) {
90
+ throw new Error("No code is present on the query string.");
91
+ }
92
+
93
+ if (!redirectUrl) {
94
+ throw new Error("No redirectUrl is present on the query string.");
95
+ }
96
+
97
+ const { protocol, hostname, originalUrl } = req;
98
+
99
+ const redirect_uri = `${protocol}://${hostname}${originalUrl}`;
100
+
101
+ const { token, refresh_token } = await oauth2Token({
102
+ authUrl: this.authUrl,
103
+ grant_type: "authorization_code",
104
+ client_id: this.client_id,
105
+ redirect_uri,
106
+ code,
107
+ code_verifier: req.session.code_verifier
108
+ });
109
+
110
+ req.session.token = token;
111
+ req.session.refresh_token = refresh_token;
112
+ req.session.user = decode(token);
113
+
114
+ return res.redirect(302, redirectUrl);
115
+ }
116
+
117
+ function logout(req, res) {
118
+ req.session = null;
119
+
120
+ const { protocol, hostname } = req;
121
+
122
+ const redirectUrl = `${protocol}://${hostname}/`;
123
+
124
+ let svAuthParams;
125
+ if (this.createParams) {
126
+ svAuthParams = this.createParams(req);
127
+ }
128
+
129
+ const params = new URLSearchParams({
130
+ redirectUrl,
131
+ ...svAuthParams
132
+ });
133
+
134
+ const authParams = new URLSearchParams({ redirectUrl: `${this.authUrl}?${params.toString()}` });
135
+
136
+ return res.redirect(`${this.authUrl}logout/?${authParams.toString()}`);
137
+ }
138
+
139
+ module.exports = Oauth2Express;
package/src/index.js CHANGED
@@ -5,6 +5,7 @@ const {
5
5
  const getDirectiveCheckPerm = require("./DirectiveCheckPerm");
6
6
  const getDirectiveGetUser = require("./DirectiveGetUser");
7
7
  const oauth2 = require("./oauth2");
8
+ const Oauth2Express = require("./Oauth2Express");
8
9
 
9
10
  module.exports = {
10
11
  ...browser,
@@ -12,4 +13,5 @@ module.exports = {
12
13
  getDirectiveCheckPerm,
13
14
  getDirectiveGetUser,
14
15
  ...oauth2,
16
+ Oauth2Express
15
17
  }
package/src/oauth2.js CHANGED
@@ -2,41 +2,13 @@ const { URLSearchParams } = require("url");
2
2
  const { request : axios } = require("axios");
3
3
  const { createHash, randomBytes } = require("crypto");
4
4
 
5
- const { validateAuthUrl } = require("../src/utils");
6
-
7
5
  const liveAuthUrl = "https://auth.simpleviewinc.com/";
8
6
 
9
- async function oauth2AuthorizeCode({ authUrl = liveAuthUrl, client_id, redirect_uri, code, code_verifier }) {
10
- validateAuthUrl(authUrl);
11
-
12
- const params = new URLSearchParams({
13
- grant_type: "authorization_code",
14
- client_id,
15
- redirect_uri,
16
- code,
17
- code_verifier
18
- });
19
-
20
- const rtn = await axios({
21
- url: `${authUrl}oauth2/token/`,
22
- method: "POST",
23
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
24
- data: params.toString()
25
- });
26
-
27
- return {
28
- token: rtn.data.access_token,
29
- refresh_token: rtn.data.refresh_token
30
- }
31
- }
32
-
33
7
  function oauth2CreateKeyHash(key) {
34
8
  return createHash("sha256").update(key).digest("base64");
35
9
  }
36
10
 
37
11
  function oauth2CreateLoginUrl({ authUrl = liveAuthUrl, client_id, redirect_uri, redirectUrl, sv_auth_params, state, code_verifier }) {
38
- validateAuthUrl(authUrl);
39
-
40
12
  const redirectParams = new URLSearchParams({ redirectUrl });
41
13
 
42
14
  const params = new URLSearchParams({
@@ -45,10 +17,13 @@ function oauth2CreateLoginUrl({ authUrl = liveAuthUrl, client_id, redirect_uri,
45
17
  client_id,
46
18
  redirect_uri: `${redirect_uri}?${redirectParams.toString()}`,
47
19
  state,
48
- code_challenge: oauth2CreateKeyHash(code_verifier),
49
- sv_auth_params: JSON.stringify(sv_auth_params)
20
+ code_challenge: oauth2CreateKeyHash(code_verifier)
50
21
  });
51
22
 
23
+ if (sv_auth_params) {
24
+ params.set("sv_auth_params", JSON.stringify(sv_auth_params));
25
+ }
26
+
52
27
  return `${authUrl}oauth2/login/?${params.toString()}`;
53
28
  }
54
29
 
@@ -56,19 +31,12 @@ function oauth2CreateRandomKey() {
56
31
  return randomBytes(32).toString("hex");
57
32
  }
58
33
 
59
- async function oauth2GetNewTokens({ authUrl = liveAuthUrl, refresh_token }) {
60
- validateAuthUrl(authUrl);
61
-
62
- const params = new URLSearchParams({
63
- grant_type: "refresh_token",
64
- refresh_token
65
- });
66
-
34
+ async function oauth2Token({ authUrl = liveAuthUrl, ...params }) {
67
35
  const rtn = await axios({
68
36
  url: `${authUrl}oauth2/token/`,
69
37
  method: "POST",
70
38
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
71
- data: params.toString()
39
+ data: new URLSearchParams(params).toString()
72
40
  });
73
41
 
74
42
  return {
@@ -77,63 +45,9 @@ async function oauth2GetNewTokens({ authUrl = liveAuthUrl, refresh_token }) {
77
45
  }
78
46
  }
79
47
 
80
- async function oauth2GetToken({ authUrl = liveAuthUrl, client_id, req, res }) {
81
- validateAuthUrl(authUrl);
82
-
83
- const { state, code, redirectUrl } = req.query;
84
-
85
- const { protocol, hostname, originalUrl } = req;
86
-
87
- const redirect_uri = `${protocol}://${hostname}${originalUrl}`;
88
- if (req.session.state !== state) {
89
- throw new Error("State returned does not match stored state.");
90
- }
91
-
92
- const { token, refresh_token } = await oauth2AuthorizeCode({ authUrl, client_id, redirect_uri, code, code_verifier: req.session.code_verifier });
93
-
94
- req.session.token = token;
95
- req.session.refresh_token = refresh_token;
96
-
97
- return res.redirect(302, redirectUrl);
98
- }
99
-
100
- function oauth2Login({ authUrl = liveAuthUrl, client_id, redirect_uri, sv_auth_params, req, res }) {
101
- validateAuthUrl(authUrl);
102
-
103
- req.session.state = oauth2CreateRandomKey();
104
-
105
- req.session.code_verifier = oauth2CreateRandomKey();
106
-
107
- const { protocol, hostname, originalUrl, session } = req;
108
-
109
- const redirectUrl = `${protocol}://${hostname}${originalUrl}`;
110
-
111
- const loginUrl = oauth2CreateLoginUrl({ authUrl, client_id, redirect_uri, redirectUrl, sv_auth_params, state: session.state, code_verifier: session.code_verifier });
112
-
113
- return res.redirect(302, loginUrl);
114
- }
115
-
116
- async function oauth2RefreshToken({ authUrl = liveAuthUrl, req }) {
117
- validateAuthUrl(authUrl);
118
-
119
- const { token, refresh_token } = await oauth2GetNewTokens({
120
- authUrl,
121
- refresh_token: req.session.refresh_token
122
- });
123
-
124
- req.session.token = token;
125
- req.session.refresh_token = refresh_token;
126
-
127
- return;
128
- }
129
-
130
48
  module.exports = {
131
- oauth2AuthorizeCode,
132
49
  oauth2CreateKeyHash,
133
50
  oauth2CreateLoginUrl,
134
51
  oauth2CreateRandomKey,
135
- oauth2GetToken,
136
- oauth2GetNewTokens,
137
- oauth2Login,
138
- oauth2RefreshToken
52
+ oauth2Token
139
53
  }
package/src/utils.js CHANGED
@@ -1,3 +1,19 @@
1
+ /**
2
+ * This function ensures that thrown errors from an async express handler are caught and properly passed on to next().
3
+ * @param {import("./definitions").AsyncHandler} fn
4
+ * */
5
+ const asyncWrapper = function(fn) {
6
+ const handler = async function(req, res, next) {
7
+ try {
8
+ await fn(req, res, next);
9
+ } catch (e) {
10
+ next(e);
11
+ }
12
+ }
13
+
14
+ return handler;
15
+ }
16
+
1
17
  /**
2
18
  * Return what objects a user has this permission for the given node type
3
19
  * @param {string} perm
@@ -22,20 +38,5 @@ function canIds(perm, node_type, bindings = {}) {
22
38
  return nodeData;
23
39
  }
24
40
 
25
- function validateAuthUrl(authUrl) {
26
- const validUrls = [
27
- "https://auth.simpleviewinc.com/",
28
- "https://auth.dev.simpleviewinc.com/",
29
- "https://auth.qa.simpleviewinc.com/",
30
- "https://auth.kube.simpleview.io/"
31
- ]
32
-
33
- if (validUrls.indexOf(authUrl) === -1 && !/http[^.]+.ui-service.default.svc.cluster.local/.test(authUrl)) {
34
- throw new Error("authUrl must be one of " + validUrls.join(", "));
35
- }
36
-
37
- return true;
38
- }
39
-
40
- module.exports.canIds = canIds;
41
- module.exports.validateAuthUrl = validateAuthUrl;
41
+ module.exports.asyncWrapper = asyncWrapper;
42
+ module.exports.canIds = canIds;