@nsshunt/stsoauth2plugin 0.1.35 → 0.1.38

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.
@@ -1,48 +0,0 @@
1
- // https://github.com/auth0/auth0-spa-js/blob/1de6427f81a8c5b005e9b6d10b9efb1e73542528/static/index.html
2
- // https://stackoverflow.com/questions/12446317/change-url-without-redirecting-using-javascript
3
- class QueryParams {
4
- DecodeQueryParams = (params) => {
5
- const retObj = { };
6
- const arr = Object.keys(params)
7
- .filter(k => typeof params[k] !== 'undefined')
8
- .map(k => {
9
- retObj[decodeURIComponent(k)] = decodeURIComponent(params[k]);
10
- });
11
- return retObj;
12
- }
13
-
14
- CreateQueryParams = (params) => {
15
- return Object.keys(params)
16
- .filter(k => typeof params[k] !== 'undefined')
17
- .map(k => {
18
- if (Array.isArray(params[k])) {
19
- return encodeURIComponent(k) + '=' + encodeURIComponent(params[k].join(' '))
20
- } else {
21
- return encodeURIComponent(k) + '=' + encodeURIComponent(params[k])
22
- }
23
- })
24
- .join('&');
25
- }
26
-
27
- _GetQueryParams = (param) => {
28
- let retVal = { };
29
- const uri = param.split("?");
30
- if (uri.length == 2) {
31
- const vars = uri[1].split("&");
32
- const getVars = {};
33
- let tmp = "";
34
- vars.forEach(function (v) {
35
- tmp = v.split("=");
36
- if (tmp.length == 2) getVars[tmp[0]] = tmp[1];
37
- });
38
- retVal = this.DecodeQueryParams(getVars);
39
- }
40
- return retVal;
41
- }
42
-
43
- GetQueryParams = () => {
44
- return this._GetQueryParams(window.location.href);
45
- }
46
- }
47
-
48
- export default QueryParams;
package/src/index.test.ts DELETED
@@ -1,10 +0,0 @@
1
-
2
- describe("Test Latency Controller", () =>
3
- {
4
- test('Testing Module', async () =>
5
- {
6
- expect.assertions(1);
7
- expect(1).toEqual(1);
8
- });
9
- });
10
-
package/src/index.ts DELETED
@@ -1,12 +0,0 @@
1
- import { STSOAuth2Manager } from './stsoauth2manager'
2
-
3
- export * from './stsoauth2types'
4
- export * from './stsoauth2manager'
5
- export * from './stsoauth2worker'
6
-
7
- export const STSOAuth2ManagerPlugin = {
8
- install: (app, router) => {
9
- const om = new STSOAuth2Manager(app, router);
10
- app.config.globalProperties.$sts.om = om;
11
- }
12
- }
package/src/stsStorage.ts DELETED
@@ -1,158 +0,0 @@
1
- import Debug from "debug";
2
- const debug = Debug(`proc:${process.pid}:storage.ts`);
3
-
4
- import * as Cookies from 'es-cookie';
5
- import { JSONObject } from "@nsshunt/stsutils";
6
-
7
- export interface IStsStorage<T> {
8
- get(key: string): T
9
- set(key: string, value: T, options?: JSONObject): void
10
- remove(key: string): void
11
- }
12
-
13
- export enum ClientStorageType {
14
- LOCAL_STORAGE = 'LocalStorage', //@@ todo
15
- SESSION_STORAGE = 'SessionStorage',
16
- COOKIE_STORAGE = 'CookieStorage',
17
- MEMORY_STORAGE = 'MemoryStorage' //@@ todo
18
- }
19
-
20
- class CookieStorage<T> implements IStsStorage<T>
21
- {
22
- get = (key: string): T => {
23
- const raw = Cookies.get(key);
24
- if (raw) {
25
- return JSON.parse(raw);
26
- } else {
27
- return null;
28
- }
29
- }
30
-
31
- set = (key: string, value: T, options: JSONObject = { }) => {
32
- let cookieAttributes: Cookies.CookieAttributes = { };
33
- if ('https:' === window.location.protocol) {
34
- cookieAttributes = {
35
- secure: true,
36
- sameSite: 'none'
37
- };
38
- }
39
-
40
- if (options && options.daysUntilExpire) {
41
- cookieAttributes.expires = options.daysUntilExpire;
42
- } else {
43
- cookieAttributes.expires = 1;
44
- }
45
- debug(`CookieStorage.set: key: ${key}, value: [${value}]`);
46
- Cookies.set(key, JSON.stringify(value), cookieAttributes);
47
- }
48
-
49
- remove = (key: string): void => {
50
- Cookies.remove(key);
51
- }
52
- }
53
-
54
- class SessionStorage<T> implements IStsStorage<T>
55
- {
56
- get = (key: string): T => {
57
- const value: string = sessionStorage.getItem(key);
58
- if (typeof value === 'undefined') {
59
- return null;
60
- }
61
- if (value === null) {
62
- return null;
63
- }
64
- return JSON.parse(value);
65
- }
66
-
67
- set = (key: string, value: T): void => {
68
- debug(`SessionStorage.set: key: ${key}, value: [${value}]`);
69
- sessionStorage.setItem(key, JSON.stringify(value));
70
- }
71
-
72
- remove = (key: string): void => {
73
- sessionStorage.removeItem(key);
74
- }
75
- }
76
-
77
- class LocalStorage<T> implements IStsStorage<T>
78
- {
79
- get = (key: string): T => {
80
- const value: string = localStorage.getItem(key);
81
- if (typeof value === 'undefined') {
82
- return null;
83
- }
84
- if (value === null) {
85
- return null;
86
- }
87
- return JSON.parse(value);
88
- }
89
-
90
- set = (key: string, value: T): void => {
91
- debug(`LocalStorage.set: key: ${key}, value: [${value}]`);
92
- localStorage.setItem(key, JSON.stringify(value));
93
- }
94
-
95
- remove = (key: string): void => {
96
- localStorage.removeItem(key);
97
- }
98
- }
99
-
100
- class MemoryStorage<T> implements IStsStorage<T>
101
- {
102
- #store: Record<string, T> = { };
103
-
104
- get = (key: string): T => {
105
- const value: T = this.#store[key];
106
- if (typeof value === 'undefined') {
107
- return null;
108
- }
109
- if (value === null) {
110
- return null;
111
- }
112
- return value;
113
- }
114
-
115
- set = (key: string, value: T): void => {
116
- debug(`MemoryStorage.set: key: ${key}, value: [${value}]`);
117
- this.#store[key] = value;
118
- }
119
-
120
- remove = (key: string): void => {
121
- delete this.#store[key];
122
- }
123
- }
124
-
125
- export class ClientStorageOptions {
126
- clientStorageType: ClientStorageType = ClientStorageType.MEMORY_STORAGE;
127
- storageOptions?: JSONObject
128
- }
129
-
130
- export class ClientStorageFactory<T>
131
- {
132
- #storage = null;
133
-
134
- constructor(options: ClientStorageOptions) {
135
- switch (options.clientStorageType) {
136
- case ClientStorageType.SESSION_STORAGE :
137
- this.#storage = new SessionStorage<T>();
138
- break;
139
- case ClientStorageType.LOCAL_STORAGE :
140
- this.#storage = new LocalStorage<T>();
141
- break;
142
- case ClientStorageType.COOKIE_STORAGE :
143
- this.#storage = new CookieStorage<T>();
144
- break;
145
- case ClientStorageType.MEMORY_STORAGE :
146
- this.#storage = new MemoryStorage<T>();
147
- break;
148
- default:
149
- throw new Error(`Unknown [${options.clientStorageType}] storage type.`);
150
- }
151
- return;
152
- }
153
-
154
- GetStorage(): IStsStorage<T>
155
- {
156
- return this.#storage;
157
- }
158
- }
@@ -1,373 +0,0 @@
1
- import Debug from "debug";
2
- const debug = Debug(`proc:${process.pid}:stsoauth2manager.ts`);
3
-
4
- import { JSONObject, OAuth2ParameterType } from '@nsshunt/stsutils';
5
-
6
- import CryptoUtils from './Utils/CryptoUtils'
7
- import QueryParams from './Utils/QueryParams';
8
-
9
- import { IAuthorizeOptions, IAuthorizeResponse, IAuthorizeErrorResponse, AuthenticateEvent,
10
- ISTSOAuth2ManagerOptions, IOauth2ListenerMessage, IOauth2ListenerMessageResponse,
11
- IOauth2ListenerCommand } from './stsoauth2types'
12
-
13
- import { IStsStorage, ClientStorageType, ClientStorageFactory } from './stsStorage'
14
-
15
- import { Gauge, InstrumentBaseTelemetry } from '@nsshunt/stsinstrumentation'
16
-
17
- //import createPersistedState from "vuex-persistedstate"; // https://www.npmjs.com/package/vuex-persistedstate
18
- import jwt_decode from "jwt-decode";
19
- //import { transformWithEsbuild } from "vite";
20
-
21
- // STS Client SDK for SPAs
22
- export class STSOAuth2Manager {
23
- #storageManager = null;
24
- #router: any = null;
25
- #store = null;
26
- #cUtils = new CryptoUtils();
27
- #qParams = new QueryParams();
28
- #STORAGE_AUTHORIZE_OPTIONS_KEY = 'authorize_options.stsmda.com.au';
29
- #STORAGE_SESSION_KEY = 'session.stsmda.com.au';
30
- #aic = null;
31
- #options: ISTSOAuth2ManagerOptions = null;
32
- #messages: Record<number, IOauth2ListenerMessage> = { };
33
- #oauth2ManagerPort: MessagePort;
34
- #messageId = 0;
35
- #messageHandlers: Record<number, any> = { }; // keyed by messageId
36
- #messageTimeout = 1000;
37
- #worker: Worker = null;
38
- #transactionStore: IStsStorage<IAuthorizeOptions> = null; // Transient transaction data used to establish a session via OAuth2 authorize handshake
39
-
40
- constructor(app, options: ISTSOAuth2ManagerOptions) {
41
- this.#options = options;
42
- this.#storageManager = app.config.globalProperties.$sts.storage;
43
- this.#store = app.config.globalProperties.$store;
44
- this.#aic = app.config.globalProperties.$sts.aic.PrimaryPublishInstrumentController;
45
- this.#router = app.config.globalProperties.$router;
46
-
47
- // Use session storage for the transient nature of the OAuth2 authorize handshake. Once completed, the storage will be removed.
48
- this.#transactionStore = new ClientStorageFactory<IAuthorizeOptions>({clientStorageType: ClientStorageType.SESSION_STORAGE}).GetStorage();
49
-
50
- /*
51
- if (this.#options.workerFactory) {
52
- this.#worker = this.#options.workerFactory();
53
- } else {
54
- this.#worker = new Worker(new URL('./stsoauth2worker.ts', import.meta.url), {
55
- type: 'module'
56
- });
57
- }
58
- */
59
-
60
- this.#worker = this.#options.workerFactory();
61
-
62
- this.#worker.onmessage = (data: MessageEvent) => {
63
- console.log(`this.#worker.onmessage = [${data}]`); // green
64
- };
65
-
66
- this.#worker.onerror = function(error) {
67
- console.log(`this.#worker.onerror = [${JSON.stringify(error)}]`); // green
68
- };
69
-
70
- const {
71
- port1: oauth2ManagerPort, // process message port
72
- port2: oauth2WorkerPort // collector message port
73
- } = new MessageChannel();
74
- this.#oauth2ManagerPort = oauth2ManagerPort;
75
-
76
- this.#worker.postMessage(oauth2WorkerPort, [ oauth2WorkerPort ]);
77
-
78
- this.#oauth2ManagerPort.onmessage = (data: MessageEvent) => {
79
- this.#ProcessMessageResponse(data);
80
- }
81
-
82
-
83
- this.#SetupStoreNamespace();
84
- this.#SetupRoute(app, options.router);
85
- }
86
-
87
- #ProcessMessageResponse = (data: MessageEvent) => {
88
- const messageResponse: IOauth2ListenerMessageResponse = data.data as IOauth2ListenerMessageResponse;
89
- if (messageResponse.messageId === -1) {
90
- // unsolicted message
91
- switch (messageResponse.command) {
92
- case IOauth2ListenerCommand.AUTHENTICATE_EVENT :
93
- this.#HandleAuthenticateEvent(messageResponse.payload as string);
94
- break;
95
- case IOauth2ListenerCommand.ERROR :
96
- this.#HandleErrorEvent(messageResponse.payload as JSONObject);
97
- break;
98
- case IOauth2ListenerCommand.LOG :
99
- this.#HandleLogEvent(messageResponse.payload as string);
100
- break;
101
- case IOauth2ListenerCommand.UPDATE_INSTRUMENT :
102
- this.#HandleUpdateInstrumentEvent(messageResponse.payload.instrumentName, messageResponse.payload.telemetry);
103
- break;
104
- default :
105
- throw new Error(`ProcessMessageResponse command [${messageResponse.command}] not valid.`);
106
- }
107
- } else {
108
- const callBack = this.#messageHandlers[messageResponse.messageId];
109
- if (callBack) {
110
- callBack(messageResponse);
111
- } else {
112
- throw new Error(`Message: [${messageResponse.messageId}] does not exists in callBacks.`);
113
- }
114
- }
115
- }
116
-
117
- #PostMessage = (message: IOauth2ListenerMessage): Promise<IOauth2ListenerMessageResponse> => {
118
- message.messageId = this.#messageId++;
119
-
120
- return new Promise<IOauth2ListenerMessageResponse>((resolve, reject) => {
121
- // Setup message timeout
122
- const timeout: NodeJS.Timeout = setTimeout(() => {
123
- delete this.#messageHandlers[message.messageId];
124
- reject(`Message: [${message.messageId}] timeout error after: [${this.#messageTimeout}] ms.`);
125
- }, this.#messageTimeout);
126
-
127
- // Setup message callback based on messageId
128
- this.#messageHandlers[message.messageId] = (response: IOauth2ListenerMessageResponse) => {
129
- clearTimeout(timeout);
130
- delete this.#messageHandlers[message.messageId];
131
- resolve(response);
132
- }
133
-
134
- // Send the message
135
- this.#oauth2ManagerPort.postMessage(message);
136
- });
137
- }
138
-
139
- #HandleLogEvent = (message: string): void => {
140
- if (this.#aic) {
141
- this.#aic.LogEx(message);
142
- }
143
- debug(message);
144
- }
145
-
146
- // UpdateInstrument = (instrumentName: Gauge, telemetry: InstrumentBaseTelemetry): void => {
147
- #HandleUpdateInstrumentEvent = (instrumentName: Gauge, telemetry: InstrumentBaseTelemetry): void => {
148
- if (this.#aic) {
149
- this.#aic.UpdateInstrument(instrumentName, telemetry);
150
- }
151
- }
152
-
153
- // Will come from message channel
154
- #HandleErrorEvent = (error: JSONObject): void => {
155
- this.#store.commit('AuthorizeError', {
156
- message: error
157
- });
158
- // plugin to do this ...
159
- setTimeout(() => {
160
- this.#router.replace('/error'); //@@ was push
161
- }, 0);
162
- }
163
-
164
- #HandleAuthenticateEvent: AuthenticateEvent = (id_token: string): void => {
165
- if (this.#options.authenticateEvent) {
166
- this.#options.authenticateEvent(id_token);
167
- }
168
- this.#store.commit('stsOAuth2SDK/SessionData', id_token);
169
- }
170
-
171
- #SetupRoute = (app, router) => {
172
- router.beforeEach(async (to, from) => {
173
- const store = app.config.globalProperties.$store;
174
- const sts = app.config.globalProperties.$sts;
175
-
176
- debug(`beforeEach: from: [${from.path}], to: [${to.path}]`); // gray
177
- if (store.getters['stsOAuth2SDK/LoggedIn'] === false) {
178
- console.log(`Not logged in`);
179
- // Not logged in
180
- if (to.path.localeCompare('/authorize') === 0) {
181
- console.log(`to = /authorize`);
182
- return true;
183
- } else if (to.path.localeCompare('/consent') === 0) {
184
- // Need to check if we are in the correct state, if not - drop back to the start of the process
185
- if (typeof store.getters.Session.sessionId !== 'undefined') {
186
- return true;
187
- }
188
- }
189
- if (to.path.localeCompare('/logout') === 0) {
190
- return true;
191
- }
192
- if (to.path.localeCompare('/error') === 0) {
193
- return true;
194
- }
195
- if (to.path.localeCompare('/logout') === 0) {
196
- return true;
197
- }
198
-
199
- const str = to.query;
200
- // Check if this route is from a redirect from the authorization server
201
- if (str[OAuth2ParameterType.CODE] || str[OAuth2ParameterType.ERROR]) {
202
-
203
- console.log(`#SetupRout:str = [${str}]`);
204
-
205
- const retVal: boolean = await sts.om.HandleRedirect(str);
206
- if (retVal) {
207
- // Success
208
- setTimeout(() => {
209
- window.history.replaceState(
210
- {},
211
- document.title,
212
- window.location.origin + '/');
213
- }, 0);
214
- return true;
215
- } else {
216
- // Error
217
- //@@ need the error data here - or use the vuex store ?
218
- this.#router.replace('/error'); //@@ was push
219
-
220
- //@@ should replaceState be used as in above?
221
- return false;
222
- }
223
- }
224
-
225
- const sessionRestored = await sts.om.RestoreSession();
226
- console.log(`#SetupRoute:sessionRestored [${sessionRestored}]`);
227
-
228
- if (sessionRestored !== true) {
229
- console.log('Session not restored - Need to Authorize');
230
- sts.om.Authorize();
231
- return false;
232
- } else {
233
- return '/';
234
- //router.replace({ path: '/' })
235
- }
236
- } else {
237
- // Prevent pages if already logged in
238
- if (to.path.localeCompare('/consent') === 0) {
239
- return '/';
240
- /*
241
- router.replace({ path: '/' })
242
- return false;
243
- */
244
- }
245
- if (to.path.localeCompare('/authorize') === 0) {
246
- router.replace({ path: '/' })
247
- return false;
248
- }
249
- if (to.path.localeCompare('/logout') === 0) {
250
- router.replace({ path: '/' })
251
- return false;
252
- }
253
- return true;
254
-
255
- /*
256
- if (to.path.localeCompare('/') === 0) {
257
- // In case press the back button in the browser shows previous query string params, replace them ...
258
- setTimeout(() => {
259
- window.history.replaceState(
260
- {},
261
- document.title,
262
- window.location.origin + '/');
263
- }, 0);
264
- return true;
265
- }
266
- */
267
- }
268
- })
269
- }
270
-
271
- // Replace with pinia
272
- // https://pinia.vuejs.org/
273
- // https://seb-l.github.io/pinia-plugin-persist/
274
- #SetupStoreNamespace = () => {
275
- this.#store.registerModule('stsOAuth2SDK', {
276
- namespaced: true,
277
-
278
- state () {
279
- return {
280
- // STS Client SDK options. These are parameters initiated by the client SPA and used for the end-to-end transaction processing.
281
- //authorizeOptions: { },
282
-
283
- sessionData: { },
284
- }
285
- },
286
-
287
- getters: {
288
- SessionData (state) {
289
- return state.sessionData;
290
- },
291
- LoggedIn (state) {
292
- if (typeof state.sessionData === 'undefined') {
293
- return false;
294
- }
295
- if (state.sessionData === null) {
296
- return false;
297
- }
298
- return true;
299
- },
300
- UserDetails (state) {
301
- //if (state.sessionData && state.sessionData.id_token) {
302
- if (state.sessionData) {
303
- const id_token = state.sessionData;
304
- const decodedIdToken = jwt_decode(id_token);
305
- return decodedIdToken;
306
- } else {
307
- return null;
308
- }
309
- }
310
- },
311
-
312
- mutations: {
313
- SessionData (state, sessionData) {
314
- state.sessionData = sessionData;
315
- console.log(`commit [sessionData]: ${JSON.stringify(sessionData)}`)
316
- },
317
- }
318
- }, { preserveState: true });
319
- }
320
-
321
- RestoreSession = async(): Promise<boolean> => {
322
- try {
323
- const response: IOauth2ListenerMessageResponse = await this.#PostMessage({ command: IOauth2ListenerCommand.RESTORE_SESSION });
324
- return response.payload;
325
- } catch (error) {
326
- console.log(`RestoreSession Error: ${error}`); //red
327
- return false;
328
- }
329
- }
330
-
331
- Authorize = async (): Promise<void> => {
332
- try {
333
- const response: IOauth2ListenerMessageResponse = await this.#PostMessage({ command: IOauth2ListenerCommand.AUTHORIZE });
334
- this.#transactionStore.set(this.#STORAGE_AUTHORIZE_OPTIONS_KEY, response.payload.authorizeOptions);
335
- const url = response.payload.url;
336
- window.location.replace(url);
337
- } catch (error) {
338
- console.log(`Authorize Error: ${error}`); // red
339
- }
340
- }
341
-
342
- HandleRedirect = async (queryVars: JSONObject): Promise<boolean> => {
343
- try {
344
- let response: IOauth2ListenerMessageResponse = null;
345
- if (queryVars[OAuth2ParameterType.CODE]) {
346
-
347
- const authorizeOptions: IAuthorizeOptions = this.#transactionStore.get(this.#STORAGE_AUTHORIZE_OPTIONS_KEY) as IAuthorizeOptions;
348
- this.#transactionStore.remove(this.#STORAGE_AUTHORIZE_OPTIONS_KEY);
349
-
350
- response = await this.#PostMessage({ command: IOauth2ListenerCommand.HANDLE_REDIRECT, payload: {
351
- queryVars: queryVars as IAuthorizeResponse,
352
- authorizeOptions
353
- }});
354
- } else {
355
- response = await this.#PostMessage({ command: IOauth2ListenerCommand.HANDLE_REDIRECT, payload: queryVars as IAuthorizeErrorResponse });
356
- }
357
- return response.payload;
358
- } catch (error) {
359
- console.log(`HandleRedirect Error: ${error}`); // red
360
- return false;
361
- }
362
- }
363
-
364
- Logout = async (): Promise<boolean> => {
365
- try {
366
- const response: IOauth2ListenerMessageResponse = await this.#PostMessage({ command: IOauth2ListenerCommand.LOGOUT });
367
- return response.payload;
368
- } catch (error) {
369
- console.log(`Logout Error: ${error}`); // red
370
- return false;
371
- }
372
- }
373
- }