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

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,5 @@
1
+ {
2
+ "files.trimTrailingWhitespace": true,
3
+ "files.insertFinalNewline": true,
4
+ "files.eol": "\n"
5
+ }
package/package.json CHANGED
@@ -1,18 +1,23 @@
1
1
  {
2
2
  "name": "@simpleview/sv-auth-client",
3
- "version": "4.4.6-0",
3
+ "version": "4.6.1",
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
+ "@simpleview/express-async-handler": "1.0.2",
8
9
  "graphql": "14.2.1",
9
10
  "graphql-tools": "4.0.4",
10
11
  "jsonwebtoken": "8.5.1"
11
12
  },
12
13
  "devDependencies": {
13
14
  "@simpleview/mochalib": "1.0.1",
15
+ "@simpleview/assertlib": "1.2.0",
16
+ "apollo-server": "2.21.2",
17
+ "cookie": "0.5.0",
18
+ "cookie-session": "2.0.0",
14
19
  "mocha": "5.2.0",
15
- "apollo-server": "2.21.2"
20
+ "supertest": "6.2.4"
16
21
  },
17
22
  "main": "src/index.js",
18
23
  "browser": "src/browser.js",
@@ -18,7 +18,7 @@ function getDirectiveCheckPerm({ name, graphUrl }) {
18
18
  if (directiveArgs.sv === true && context.user.sv !== true) {
19
19
  throw new Error("User is not authorized to access this resource (ERR: 1005).");
20
20
  }
21
-
21
+
22
22
  // check if the resolver requires specific permissions
23
23
  if (directiveArgs.perms !== undefined) {
24
24
  const allowed = context.user.can(directiveArgs.perms);
@@ -58,7 +58,7 @@ function getDirectiveCheckPerm({ name, graphUrl }) {
58
58
 
59
59
  context.user.permissionObjBindings = bindings.permissionObj;
60
60
  }
61
-
61
+
62
62
  return await resolve.call(this, parent, args, context, info);
63
63
  }
64
64
  }
@@ -83,4 +83,4 @@ function getDirectiveCheckPerm({ name, graphUrl }) {
83
83
  };
84
84
  }
85
85
 
86
- module.exports = getDirectiveCheckPerm;
86
+ module.exports = getDirectiveCheckPerm;
@@ -6,7 +6,7 @@ const AuthClient = require("./AuthClient");
6
6
 
7
7
  function getDirectiveGetUser({ name, graphUrl }){
8
8
  const authClient = new AuthClient({ graphUrl });
9
-
9
+
10
10
  class DirectiveGetUser extends SchemaDirectiveVisitor {
11
11
  visitFieldDefinition(field) {
12
12
  const { resolve = defaultFieldResolver } = field;
@@ -50,4 +50,4 @@ function getDirectiveGetUser({ name, graphUrl }){
50
50
  }
51
51
  }
52
52
 
53
- module.exports = getDirectiveGetUser;
53
+ module.exports = getDirectiveGetUser;
@@ -1,88 +1,160 @@
1
+ //@ts-check
1
2
  const { decode } = require("jsonwebtoken");
3
+ const { asyncWrap } = require("@simpleview/express-async-handler");
2
4
 
3
5
  const {
4
6
  oauth2CreateLoginUrl,
7
+ oauth2CreateLogoutUrl,
5
8
  oauth2CreateRandomKey,
6
- oauth2Token
9
+ oauth2GetTokens,
10
+ oauth2GetTokensFromRefresh
7
11
  } = require("../src/oauth2");
8
12
 
9
- const {
10
- asyncWrapper
11
- } = require("../src/utils");
12
-
13
13
  class Oauth2Express {
14
- constructor({ authUrl = "https://auth.simpleviewinc.com/", client_id, callbackPath = "/oauth2/callback/", logoutPath = "/logout/", createParams }) {
14
+ /**
15
+ * @param {object} args
16
+ * @param {string} args.authUrl - URL to use for Auth
17
+ * @param {string} args.client_id - Your registered client_id declared at the same Auth.
18
+ * @param {string} [args.callbackPath] - The callback path on your express app that will handle the callback from Auth.
19
+ * @param {string} [args.logoutPath] - The logout path on your express app that will handle logging the user out and sending them back to the login screen.
20
+ * @param {import("./types").CreateParams} [args.createParams] - Transforms a request object into an object with "product", "account_id", and/or "account_name" for using within auth.
21
+ * @param {string} [args.sessionKey] - Key to store the declared session
22
+ */
23
+ constructor({
24
+ authUrl = "https://auth.simpleviewinc.com/",
25
+ client_id,
26
+ callbackPath = "/oauth2/callback/",
27
+ logoutPath = "/logout/",
28
+ createParams,
29
+ sessionKey = "session"
30
+ }) {
15
31
  const validUrls = [
16
32
  "https://auth.simpleviewinc.com/",
17
33
  "https://auth.dev.simpleviewinc.com/",
18
34
  "https://auth.qa.simpleviewinc.com/",
19
35
  "https://auth.kube.simpleview.io/"
20
36
  ]
21
-
37
+
22
38
  if (validUrls.indexOf(authUrl) === -1 && !/http[^.]+.ui-service.default.svc.cluster.local/.test(authUrl)) {
23
39
  throw new Error("authUrl must be one of " + validUrls.join(", "));
24
40
  }
25
-
41
+
26
42
  if (!client_id) {
27
43
  throw new Error("client_id is required.")
28
44
  }
29
45
 
30
- Object.assign(this, {
31
- authUrl,
32
- client_id,
33
- callbackPath,
34
- logoutPath,
35
- createParams
36
- });
46
+ this.authUrl = authUrl;
47
+ this.client_id = client_id;
48
+ this.callbackPath = callbackPath;
49
+ this.logoutPath = logoutPath;
50
+ this.createParams = createParams;
51
+ this.sessionKey = sessionKey;
37
52
 
38
- this.middleware = asyncWrapper(middleware.bind(this));
39
- this.callback = asyncWrapper(callback.bind(this));
40
- this.logout = asyncWrapper(logout.bind(this));
53
+ this.middleware = asyncWrap(middleware.bind(this));
54
+ this.callback = asyncWrap(callback.bind(this));
55
+ this.logout = asyncWrap(logout.bind(this));
56
+ }
57
+ /**
58
+ * Apply callback and logout middleware to the application
59
+ * @param {import("express").Application} app
60
+ */
61
+ applyMiddleware(app) {
62
+ app.get(this.callbackPath, this.callback);
63
+ app.get(this.logoutPath, this.logout);
41
64
  }
42
-
43
65
  }
44
66
 
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
- }
67
+ /**
68
+ * @this {Oauth2Express}
69
+ * @param {import("express").Request} req
70
+ * @param {import("express").Response} res
71
+ * @param {import("express").NextFunction} next
72
+ */
73
+ async function middleware(req, res, next) {
74
+ const session = req[this.sessionKey];
75
+ /**
76
+ * @type {import("./types").UnknownSession}
77
+ */
78
+ const oauth2 = session?.oauth2;
79
+
80
+ // If we don't have a token or a refresh_token than we need to redirect to Auth to log the user in
81
+ if (!oauth2 || oauth2.type === "initial") {
82
+ if (req.method !== "GET") {
83
+ throw new Error("User is not authorized to access this resource.");
84
+ }
85
+
86
+ /** @type {import("./types").InitialSession} */
87
+ const newAuth = {
88
+ type: "initial",
89
+ state: oauth2CreateRandomKey(),
90
+ code_verifier: oauth2CreateRandomKey()
91
+ }
92
+
93
+ req[this.sessionKey].oauth2 = newAuth;
53
94
 
54
- if (!req.session?.token || !req.session?.refresh_token) {
55
- req.session.state = oauth2CreateRandomKey();
95
+ const { protocol, hostname, originalUrl } = req;
56
96
 
57
- req.session.code_verifier = oauth2CreateRandomKey();
58
-
59
- const { protocol, hostname, originalUrl, session } = req;
97
+ const redirect_uri = new URL(`${protocol}://${hostname}${this.callbackPath}`);
98
+ redirect_uri.searchParams.set("redirectUrl", `${protocol}://${hostname}${originalUrl}`);
60
99
 
61
100
  const loginUrl = oauth2CreateLoginUrl({
62
101
  authUrl: this.authUrl,
63
102
  client_id: this.client_id,
64
- redirect_uri: `${protocol}://${hostname}${this.callbackPath}`,
65
- redirectUrl: `${protocol}://${hostname}${originalUrl}`,
103
+ redirect_uri: redirect_uri.toString(),
66
104
  sv_auth_params: this.createParams && this.createParams(req),
67
- state: session.state,
68
- code_verifier: session.code_verifier
105
+ state: newAuth.state,
106
+ code_verifier: newAuth.code_verifier
69
107
  });
70
-
108
+
71
109
  return res.redirect(302, loginUrl);
72
110
  }
73
111
 
112
+ if (oauth2.type === "logged_in") {
113
+ // If the token is older than 1 day we refresh
114
+ if (Date.now() - oauth2.token_created > 1000 * 60 * 60 * 24) {
115
+ const result = await oauth2GetTokensFromRefresh({
116
+ authUrl: this.authUrl,
117
+ refresh_token: oauth2.refresh_token
118
+ });
119
+
120
+ oauth2.token = result.token;
121
+ oauth2.refresh_token = result.refresh_token;
122
+ oauth2.token_created = Date.now();
123
+ }
124
+ }
125
+
74
126
  return next();
75
127
  }
76
128
 
77
-
129
+ /**
130
+ * @this {Oauth2Express}
131
+ * @param {import("express").Request} req
132
+ * @param {import("express").Response} res
133
+ */
78
134
  async function callback(req, res) {
79
- const { state, code, redirectUrl, error, error_description } = req.query;
135
+ const {
136
+ state,
137
+ code,
138
+ redirectUrl,
139
+ error,
140
+ error_description
141
+ } = req.query;
80
142
 
81
143
  if (error) {
82
144
  throw new Error(`${error}${error_description ? ": " + error_description : ""}`);
83
145
  }
84
146
 
85
- if (req.session.state !== state) {
147
+ const session = req[this.sessionKey];
148
+ /**
149
+ * @type {import("./types").InitialSession}
150
+ */
151
+ const oauth2 = session?.oauth2;
152
+
153
+ if (!oauth2 || !oauth2.code_verifier || !oauth2.state) {
154
+ throw new Error("Session does not exist.");
155
+ }
156
+
157
+ if (session.oauth2.state !== state) {
86
158
  throw new Error("State returned does not match stored state.");
87
159
  }
88
160
 
@@ -98,42 +170,46 @@ async function callback(req, res) {
98
170
 
99
171
  const redirect_uri = `${protocol}://${hostname}${originalUrl}`;
100
172
 
101
- const { token, refresh_token } = await oauth2Token({
173
+ const { token, refresh_token } = await oauth2GetTokens({
102
174
  authUrl: this.authUrl,
103
- grant_type: "authorization_code",
104
175
  client_id: this.client_id,
105
176
  redirect_uri,
106
177
  code,
107
- code_verifier: req.session.code_verifier
178
+ code_verifier: session.oauth2.code_verifier
108
179
  });
109
180
 
110
- req.session.token = token;
111
- req.session.refresh_token = refresh_token;
112
- req.session.user = decode(token);
181
+ /** @type {import("./types").LoggedInSession} */
182
+ const newSession = {
183
+ type: "logged_in",
184
+ created: Date.now(),
185
+ token_created: Date.now(),
186
+ token,
187
+ refresh_token,
188
+ email: /** @type {object} */ (decode(token)).email
189
+ }
190
+ session.oauth2 = newSession;
113
191
 
114
- return res.redirect(302, redirectUrl);
192
+ return res.redirect(302, /** @type {string} */ (redirectUrl));
115
193
  }
116
194
 
195
+ /**
196
+ * @this {Oauth2Express}
197
+ * @param {import("express").Request} req
198
+ * @param {import("express").Response} res
199
+ */
117
200
  function logout(req, res) {
118
- req.session = null;
119
-
120
- const { protocol, hostname } = req;
201
+ delete req[this.sessionKey].oauth2;
121
202
 
122
- const redirectUrl = `${protocol}://${hostname}/`;
123
-
124
- let svAuthParams;
125
- if (this.createParams) {
126
- svAuthParams = this.createParams(req);
127
- }
203
+ const { protocol, hostname, query } = req;
204
+ const redirectUrl = /** @type {string} */ (query.redirectUrl) ?? `${protocol}://${hostname}/`
128
205
 
129
- const params = new URLSearchParams({
130
- redirectUrl,
131
- ...svAuthParams
206
+ const logoutUrl = oauth2CreateLogoutUrl({
207
+ authUrl: this.authUrl,
208
+ redirect_uri: redirectUrl,
209
+ sv_auth_params: this.createParams && this.createParams(req),
132
210
  });
133
211
 
134
- const authParams = new URLSearchParams({ redirectUrl: `${this.authUrl}?${params.toString()}` });
135
-
136
- return res.redirect(`${this.authUrl}logout/?${authParams.toString()}`);
212
+ return res.redirect(302, logoutUrl);
137
213
  }
138
214
 
139
- module.exports = Oauth2Express;
215
+ module.exports = Oauth2Express;
package/src/oauth2.js CHANGED
@@ -1,4 +1,4 @@
1
- const { URLSearchParams } = require("url");
1
+ //@ts-check
2
2
  const { request : axios } = require("axios");
3
3
  const { createHash, randomBytes } = require("crypto");
4
4
 
@@ -8,14 +8,30 @@ function oauth2CreateKeyHash(key) {
8
8
  return createHash("sha256").update(key).digest("base64");
9
9
  }
10
10
 
11
- function oauth2CreateLoginUrl({ authUrl = liveAuthUrl, client_id, redirect_uri, redirectUrl, sv_auth_params, state, code_verifier }) {
12
- const redirectParams = new URLSearchParams({ redirectUrl });
13
-
11
+ /**
12
+ * Generate a login URL
13
+ * @param {object} args
14
+ * @param {string} args.authUrl - URL of Auth
15
+ * @param {string} args.client_id - Registered client_id
16
+ * @param {string} args.redirect_uri - The URL auth will redirect to to handle oauth2 verification
17
+ * @param {object} args.sv_auth_params - Params to append to the login request such as product, account_name, account_id
18
+ * @param {string} args.state - Unique state key to identify this transaction
19
+ * @param {string} args.code_verifier - Code verifier used to generate code_challenge
20
+ * @returns {string}
21
+ */
22
+ function oauth2CreateLoginUrl({
23
+ authUrl = liveAuthUrl,
24
+ client_id,
25
+ redirect_uri,
26
+ sv_auth_params,
27
+ state,
28
+ code_verifier
29
+ }) {
14
30
  const params = new URLSearchParams({
15
31
  response_type: "code",
16
32
  code_challenge_method: "S256",
17
33
  client_id,
18
- redirect_uri: `${redirect_uri}?${redirectParams.toString()}`,
34
+ redirect_uri,
19
35
  state,
20
36
  code_challenge: oauth2CreateKeyHash(code_verifier)
21
37
  });
@@ -27,17 +43,64 @@ function oauth2CreateLoginUrl({ authUrl = liveAuthUrl, client_id, redirect_uri,
27
43
  return `${authUrl}oauth2/login/?${params.toString()}`;
28
44
  }
29
45
 
46
+ /**
47
+ * Generates a logout URL
48
+ * @param {object} args
49
+ * @param {string} args.authUrl - URL of Auth
50
+ * @param {string} args.redirect_uri - The URL auth will redirect after login
51
+ * @param {object} args.sv_auth_params - Params to append to the login request such as product, account_name, account_id
52
+ * @returns {string}
53
+ */
54
+ function oauth2CreateLogoutUrl({
55
+ authUrl = liveAuthUrl,
56
+ redirect_uri,
57
+ sv_auth_params = {}
58
+ }) {
59
+ const url = new URL(`${authUrl}logout/`);
60
+ url.searchParams.set("redirectUrl", redirect_uri);
61
+
62
+ for (const [key, value] of Object.entries(sv_auth_params)) {
63
+ url.searchParams.set(key, value);
64
+ }
65
+
66
+ return url.toString();
67
+ }
68
+
69
+ /**
70
+ * Generate an oauth2 random identifier
71
+ */
30
72
  function oauth2CreateRandomKey() {
31
73
  return randomBytes(32).toString("hex");
32
74
  }
33
75
 
34
- async function oauth2Token({ authUrl = liveAuthUrl, ...params }) {
35
- const rtn = await axios({
36
- url: `${authUrl}oauth2/token/`,
37
- method: "POST",
38
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
39
- data: new URLSearchParams(params).toString()
40
- });
76
+ /**
77
+ * Internal function to retreive tokens from the server
78
+ * @param {object} args
79
+ * @param {string} args.authUrl - URL of Auth
80
+ * @param {object} args.params - Params to add to the request
81
+ * @returns {Promise<{ token: string, refresh_token: string }>}
82
+ */
83
+ async function _oauth2GetTokens({
84
+ authUrl = liveAuthUrl,
85
+ params
86
+ }) {
87
+ let rtn;
88
+ try {
89
+ rtn = await axios({
90
+ url: `${authUrl}oauth2/token/`,
91
+ method: "POST",
92
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
93
+ data: new URLSearchParams(params).toString()
94
+ });
95
+ } catch (e) {
96
+ if (e.response?.data?.error) {
97
+ const errData = e.response.data;
98
+ const terms = [errData.error, errData.error_description];
99
+ throw new Error(`Auth Error: ${terms.filter(val => val).join(", ")}`);
100
+ }
101
+
102
+ throw new Error(`Auth Error: ${e.message}`);
103
+ }
41
104
 
42
105
  return {
43
106
  token: rtn.data.access_token,
@@ -45,9 +108,43 @@ async function oauth2Token({ authUrl = liveAuthUrl, ...params }) {
45
108
  }
46
109
  }
47
110
 
111
+ async function oauth2GetTokens({
112
+ authUrl,
113
+ client_id,
114
+ redirect_uri,
115
+ code,
116
+ code_verifier
117
+ }) {
118
+ return _oauth2GetTokens({
119
+ authUrl,
120
+ params: {
121
+ client_id,
122
+ grant_type: "authorization_code",
123
+ redirect_uri,
124
+ code,
125
+ code_verifier
126
+ }
127
+ })
128
+ }
129
+
130
+ async function oauth2GetTokensFromRefresh({
131
+ authUrl,
132
+ refresh_token
133
+ }) {
134
+ return _oauth2GetTokens({
135
+ authUrl,
136
+ params: {
137
+ grant_type: "refresh_token",
138
+ refresh_token
139
+ }
140
+ });
141
+ }
142
+
48
143
  module.exports = {
49
144
  oauth2CreateKeyHash,
50
145
  oauth2CreateLoginUrl,
146
+ oauth2CreateLogoutUrl,
51
147
  oauth2CreateRandomKey,
52
- oauth2Token
53
- }
148
+ oauth2GetTokens,
149
+ oauth2GetTokensFromRefresh
150
+ }
package/src/types.ts CHANGED
@@ -1,7 +1,36 @@
1
+ import { Request } from "express";
2
+
1
3
  export interface ObjectBindingsPermissionObj {
2
4
  [key: string]: true | ObjectBindingsPermissionObjPerm
3
5
  }
4
6
 
5
7
  export interface ObjectBindingsPermissionObjPerm {
6
8
  [key: string]: string[]
7
- }
9
+ }
10
+
11
+ export interface CreateParams {
12
+ (req: Request): {
13
+ product?: string
14
+ account_name?: string
15
+ acct_id?: string
16
+ }
17
+ }
18
+
19
+ export type UnknownSession = InitialSession | LoggedInSession | undefined
20
+
21
+ export interface InitialSession {
22
+ type: "initial"
23
+ code_verifier: string
24
+ state: string
25
+ }
26
+
27
+ export interface LoggedInSession {
28
+ type: "logged_in"
29
+ /** The time the session was created */
30
+ created: number
31
+ /** The time the token was created */
32
+ token_created: number
33
+ token: string
34
+ refresh_token: string
35
+ email: string
36
+ }
package/src/utils.js CHANGED
@@ -1,19 +1,3 @@
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
-
17
1
  /**
18
2
  * Return what objects a user has this permission for the given node type
19
3
  * @param {string} perm
@@ -38,5 +22,4 @@ function canIds(perm, node_type, bindings = {}) {
38
22
  return nodeData;
39
23
  }
40
24
 
41
- module.exports.asyncWrapper = asyncWrapper;
42
25
  module.exports.canIds = canIds;