@nsshunt/stsoauth2plugin 0.1.65 → 0.1.68

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,437 +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, ISTSOAuth2WorkerMessage, StsOauth2WorkerFactory } from './stsoauth2types'
12
-
13
- import { IStsStorage, ClientStorageType, ClientStorageFactory } from './stsStorage'
14
-
15
- import { Gauge, InstrumentBaseTelemetry } from '@nsshunt/stsinstrumentation'
16
-
17
- import jwt_decode from "jwt-decode";
18
-
19
- import { createPinia, defineStore } from 'pinia'
20
- import piniaPersist from 'pinia-plugin-persist'
21
-
22
- // STS Client SDK for SPAs
23
- export class STSOAuth2Manager {
24
- #storageManager = null;
25
- #router: any = null;
26
- #store = null;
27
- #cUtils = new CryptoUtils();
28
- #qParams = new QueryParams();
29
- #STORAGE_AUTHORIZE_OPTIONS_KEY = 'authorize_options.stsmda.com.au';
30
- #STORAGE_SESSION_KEY = 'session.stsmda.com.au';
31
- #aic = null;
32
- #options: ISTSOAuth2ManagerOptions = null;
33
- #messages: Record<number, IOauth2ListenerMessage> = { };
34
- #oauth2ManagerPort: MessagePort;
35
- #messageId = 0;
36
- #messageHandlers: Record<number, any> = { }; // keyed by messageId
37
- #messageTimeout = 1000;
38
- #worker: Worker = null;
39
- #transactionStore: IStsStorage<IAuthorizeOptions> = null; // Transient transaction data used to establish a session via OAuth2 authorize handshake
40
- #auth2Store = null;
41
-
42
- constructor(app, options: ISTSOAuth2ManagerOptions) {
43
- this.#options = options;
44
- this.#storageManager = app.config.globalProperties.$sts.storage;
45
- this.#store = app.config.globalProperties.$store;
46
- this.#aic = app.config.globalProperties.$sts.aic.PrimaryPublishInstrumentController;
47
- this.#router = app.config.globalProperties.$router;
48
-
49
- // Use session storage for the transient nature of the OAuth2 authorize handshake. Once completed, the storage will be removed.
50
- this.#transactionStore = new ClientStorageFactory<IAuthorizeOptions>({clientStorageType: ClientStorageType.SESSION_STORAGE}).GetStorage();
51
-
52
- this.#worker = this.#options.workerFactory();
53
-
54
- this.#worker.onmessage = (data: MessageEvent) => {
55
- console.log(`this.#worker.onmessage = [${data}]`); // green
56
- };
57
-
58
- this.#worker.onerror = function(error) {
59
- console.log(`this.#worker.onerror = [${JSON.stringify(error)}]`); // green
60
- };
61
-
62
- const {
63
- port1: oauth2ManagerPort, // process message port
64
- port2: oauth2WorkerPort // collector message port
65
- } = new MessageChannel();
66
- this.#oauth2ManagerPort = oauth2ManagerPort;
67
-
68
- const workerMessage: ISTSOAuth2WorkerMessage = {
69
- workerPort: oauth2WorkerPort,
70
- options: this.#options.workerOptions
71
- }
72
-
73
- this.#worker.postMessage(workerMessage, [ oauth2WorkerPort ]);
74
-
75
- this.#oauth2ManagerPort.onmessage = (data: MessageEvent) => {
76
- this.#ProcessMessageResponse(data);
77
- }
78
-
79
- this.#SetupStoreNamespace();
80
-
81
- this.#SetupPiniaStoreNamespace();
82
-
83
- this.#SetupRoute(app, this.#router);
84
- }
85
-
86
- #ProcessMessageResponse = (data: MessageEvent) => {
87
- const messageResponse: IOauth2ListenerMessageResponse = data.data as IOauth2ListenerMessageResponse;
88
- if (messageResponse.messageId === -1) {
89
- // unsolicted message
90
- switch (messageResponse.command) {
91
- case IOauth2ListenerCommand.AUTHENTICATE_EVENT :
92
- this.#HandleAuthenticateEvent(messageResponse.payload as string);
93
- break;
94
- case IOauth2ListenerCommand.ERROR :
95
- this.#HandleErrorEvent(messageResponse.payload as JSONObject);
96
- break;
97
- case IOauth2ListenerCommand.LOG :
98
- this.#HandleLogEvent(messageResponse.payload as string);
99
- break;
100
- case IOauth2ListenerCommand.UPDATE_INSTRUMENT :
101
- this.#HandleUpdateInstrumentEvent(messageResponse.payload.instrumentName, messageResponse.payload.telemetry);
102
- break;
103
- default :
104
- throw new Error(`ProcessMessageResponse command [${messageResponse.command}] not valid.`);
105
- }
106
- } else {
107
- const callBack = this.#messageHandlers[messageResponse.messageId];
108
- if (callBack) {
109
- callBack(messageResponse);
110
- } else {
111
- throw new Error(`Message: [${messageResponse.messageId}] does not exists in callBacks.`);
112
- }
113
- }
114
- }
115
-
116
- #PostMessage = (message: IOauth2ListenerMessage): Promise<IOauth2ListenerMessageResponse> => {
117
- message.messageId = this.#messageId++;
118
-
119
- return new Promise<IOauth2ListenerMessageResponse>((resolve, reject) => {
120
- // Setup message timeout
121
- const timeout: NodeJS.Timeout = setTimeout(() => {
122
- delete this.#messageHandlers[message.messageId];
123
- reject(`Message: [${message.messageId}] timeout error after: [${this.#messageTimeout}] ms.`);
124
- }, this.#messageTimeout);
125
-
126
- // Setup message callback based on messageId
127
- this.#messageHandlers[message.messageId] = (response: IOauth2ListenerMessageResponse) => {
128
- clearTimeout(timeout);
129
- delete this.#messageHandlers[message.messageId];
130
- resolve(response);
131
- }
132
-
133
- // Send the message
134
- this.#oauth2ManagerPort.postMessage(message);
135
- });
136
- }
137
-
138
- #HandleLogEvent = (message: string): void => {
139
- if (this.#aic) {
140
- this.#aic.LogEx(message);
141
- }
142
- debug(message);
143
- }
144
-
145
- // UpdateInstrument = (instrumentName: Gauge, telemetry: InstrumentBaseTelemetry): void => {
146
- #HandleUpdateInstrumentEvent = (instrumentName: Gauge, telemetry: InstrumentBaseTelemetry): void => {
147
- if (this.#aic) {
148
- this.#aic.UpdateInstrument(instrumentName, telemetry);
149
- }
150
- }
151
-
152
- // Will come from message channel
153
- #HandleErrorEvent = (error: JSONObject): void => {
154
- this.#store.commit('AuthorizeError', { // Authorize applications store
155
- message: error
156
- });
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
- //@@ new version here
171
- this.#auth2Store.UpdateSessionData(id_token);
172
- }
173
-
174
- #SetupRoute = (app, router) => {
175
- router.beforeEach(async (to, from) => {
176
- const store = app.config.globalProperties.$store;
177
- const sts = app.config.globalProperties.$sts;
178
-
179
- debug(`beforeEach: from: [${from.path}], to: [${to.path}]`); // gray
180
- if (store.getters['stsOAuth2SDK/LoggedIn'] === false) {
181
- console.log(`Not logged in`);
182
- // Not logged in
183
- if (to.path.localeCompare('/authorize') === 0) {
184
- console.log(`to = /authorize`);
185
- return true;
186
- } else if (to.path.localeCompare('/consent') === 0) {
187
- // Need to check if we are in the correct state, if not - drop back to the start of the process
188
- if (typeof store.getters.Session.sessionId !== 'undefined') {
189
- return true;
190
- }
191
- }
192
- if (to.path.localeCompare('/logout') === 0) {
193
- return true;
194
- }
195
- if (to.path.localeCompare('/error') === 0) {
196
- return true;
197
- }
198
- if (to.path.localeCompare('/logout') === 0) {
199
- return true;
200
- }
201
-
202
- const str = to.query;
203
- // Check if this route is from a redirect from the authorization server
204
- if (str[OAuth2ParameterType.CODE] || str[OAuth2ParameterType.ERROR]) {
205
-
206
- console.log(`#SetupRout:str = [${str}]`);
207
-
208
- const retVal: boolean = await sts.om.HandleRedirect(str);
209
- if (retVal) {
210
- // Success
211
- setTimeout(() => {
212
- window.history.replaceState(
213
- {},
214
- document.title,
215
- window.location.origin + '/');
216
- }, 0);
217
- return true;
218
- } else {
219
- // Error
220
- //@@ need the error data here - or use the vuex store ?
221
- this.#router.replace('/error'); //@@ was push
222
-
223
- //@@ should replaceState be used as in above?
224
- return false;
225
- }
226
- }
227
-
228
- const sessionRestored = await sts.om.RestoreSession();
229
- console.log(`#SetupRoute:sessionRestored [${sessionRestored}]`);
230
-
231
- if (sessionRestored !== true) {
232
- console.log('Session not restored - Need to Authorize');
233
- sts.om.Authorize();
234
- return false;
235
- } else {
236
- return '/';
237
- //router.replace({ path: '/' })
238
- }
239
- } else {
240
- // Prevent pages if already logged in
241
- if (to.path.localeCompare('/consent') === 0) {
242
- return '/';
243
- /*
244
- router.replace({ path: '/' })
245
- return false;
246
- */
247
- }
248
- if (to.path.localeCompare('/authorize') === 0) {
249
- router.replace({ path: '/' })
250
- return false;
251
- }
252
- if (to.path.localeCompare('/logout') === 0) {
253
- router.replace({ path: '/' })
254
- return false;
255
- }
256
- return true;
257
-
258
- /*
259
- if (to.path.localeCompare('/') === 0) {
260
- // In case press the back button in the browser shows previous query string params, replace them ...
261
- setTimeout(() => {
262
- window.history.replaceState(
263
- {},
264
- document.title,
265
- window.location.origin + '/');
266
- }, 0);
267
- return true;
268
- }
269
- */
270
- }
271
- })
272
- }
273
-
274
- // Replace with pinia
275
- // https://pinia.vuejs.org/
276
- // https://seb-l.github.io/pinia-plugin-persist/
277
- #SetupStoreNamespace = () => {
278
- this.#store.registerModule('stsOAuth2SDK', {
279
- namespaced: true,
280
-
281
- state () {
282
- return {
283
- // STS Client SDK options. These are parameters initiated by the client SPA and used for the end-to-end transaction processing.
284
- //authorizeOptions: { },
285
-
286
- sessionData: { },
287
- }
288
- },
289
-
290
- getters: {
291
- SessionData (state) {
292
- return state.sessionData;
293
- },
294
- LoggedIn (state) {
295
- if (typeof state.sessionData === 'undefined') {
296
- return false;
297
- }
298
- if (state.sessionData === null) {
299
- return false;
300
- }
301
- return true;
302
- },
303
- UserDetails (state) {
304
- //if (state.sessionData && state.sessionData.id_token) {
305
- if (state.sessionData) {
306
- const id_token = state.sessionData;
307
- const decodedIdToken = jwt_decode(id_token);
308
- return decodedIdToken;
309
- } else {
310
- return null;
311
- }
312
- }
313
- },
314
-
315
- mutations: {
316
- SessionData (state, sessionData) {
317
- state.sessionData = sessionData;
318
- console.log(`commit [sessionData]: ${JSON.stringify(sessionData)}`)
319
- },
320
- }
321
- }, { preserveState: true });
322
- }
323
-
324
- // Replace with pinia
325
- // https://pinia.vuejs.org/
326
- // https://seb-l.github.io/pinia-plugin-persist/
327
- #SetupPiniaStoreNamespace = () => {
328
- const store = defineStore('__pin_stsOAuth2SDK', {
329
- state: () => {
330
- return {
331
- sessionData: { }
332
- }
333
- },
334
- actions: {
335
- UpdateSessionData(newState) {
336
- this.sessionData = newState;
337
- }
338
- },
339
- getters: {
340
- SessionData: (state) => {
341
- return state.sessionData;
342
- },
343
- LoggedIn: (state) => {
344
- if (typeof state.sessionData === 'undefined') {
345
- return false;
346
- }
347
- if (state.sessionData === null) {
348
- return false;
349
- }
350
- return true;
351
- },
352
- UserDetails: (state) => {
353
- //if (state.sessionData && state.sessionData.id_token) {
354
- if (state.sessionData) {
355
- const id_token = state.sessionData;
356
- const decodedIdToken = jwt_decode(id_token);
357
- return decodedIdToken;
358
- } else {
359
- return null;
360
- }
361
- }
362
- },
363
- persist: {
364
- enabled: true
365
- },
366
- });
367
-
368
- this.#auth2Store = store();
369
- console.log(`================================= Pinia store setup`);
370
- console.log(this.#auth2Store);
371
- }
372
-
373
- RestoreSession = async(): Promise<boolean> => {
374
- try {
375
- const response: IOauth2ListenerMessageResponse = await this.#PostMessage({ command: IOauth2ListenerCommand.RESTORE_SESSION });
376
- return response.payload;
377
- } catch (error) {
378
- console.log(`RestoreSession Error: ${error}`); //red
379
- return false;
380
- }
381
- }
382
-
383
- Authorize = async (): Promise<void> => {
384
- try {
385
- const response: IOauth2ListenerMessageResponse = await this.#PostMessage({ command: IOauth2ListenerCommand.AUTHORIZE });
386
- this.#transactionStore.set(this.#STORAGE_AUTHORIZE_OPTIONS_KEY, response.payload.authorizeOptions);
387
- const url = response.payload.url;
388
- window.location.replace(url);
389
- } catch (error) {
390
- console.log(`Authorize Error: ${error}`); // red
391
- }
392
- }
393
-
394
- HandleRedirect = async (queryVars: JSONObject): Promise<boolean> => {
395
- try {
396
- let response: IOauth2ListenerMessageResponse = null;
397
- if (queryVars[OAuth2ParameterType.CODE]) {
398
-
399
- const authorizeOptions: IAuthorizeOptions = this.#transactionStore.get(this.#STORAGE_AUTHORIZE_OPTIONS_KEY) as IAuthorizeOptions;
400
- this.#transactionStore.remove(this.#STORAGE_AUTHORIZE_OPTIONS_KEY);
401
-
402
- response = await this.#PostMessage({ command: IOauth2ListenerCommand.HANDLE_REDIRECT, payload: {
403
- queryVars: queryVars as IAuthorizeResponse,
404
- authorizeOptions
405
- }});
406
- } else {
407
- response = await this.#PostMessage({ command: IOauth2ListenerCommand.HANDLE_REDIRECT, payload: queryVars as IAuthorizeErrorResponse });
408
- }
409
- return response.payload;
410
- } catch (error) {
411
- console.log(`HandleRedirect Error: ${error}`); // red
412
- return false;
413
- }
414
- }
415
-
416
- Logout = async (): Promise<boolean> => {
417
- try {
418
- const response: IOauth2ListenerMessageResponse = await this.#PostMessage({ command: IOauth2ListenerCommand.LOGOUT });
419
- return response.payload;
420
- } catch (error) {
421
- console.log(`Logout Error: ${error}`); // red
422
- return false;
423
- }
424
- }
425
-
426
- /*
427
- GetIDToken = async (): Promise<string> => {
428
- try {
429
- const response: IOauth2ListenerMessageResponse = await this.#PostMessage({ command: IOauth2ListenerCommand.ID_TOKEN });
430
- return response.payload;
431
- } catch (error) {
432
- console.log(`Logout Error: ${error}`); // red
433
- return null;
434
- }
435
- }
436
- */
437
- }
@@ -1,134 +0,0 @@
1
- export enum AuthorizeOptionsResponseType {
2
- CODE = 'code',
3
- ID_TOKEN = 'id_token',
4
- TOKEN = 'token'
5
- }
6
-
7
- export enum AuthorizeOptionsResponseMode {
8
- QUERY = 'query',
9
- FRAGMENT = 'fragment',
10
- FORM_POST = 'form_post'
11
- }
12
-
13
- // https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
14
- export interface IAuthorizeOptions {
15
- client_id: string,
16
- nonce: string,
17
- response_type: AuthorizeOptionsResponseType[], // Must include: 'code' and may include: 'id_token' and/or 'token'
18
- redirect_uri: string,
19
- response_mode: AuthorizeOptionsResponseMode
20
- scope: string, // A space-separated list of scopes that you want the user to consent to. For the /authorize leg of the request, this parameter can cover multiple resources. This value allows your app to get consent for multiple web APIs you want to call.
21
- state: string, // Client application state (if required)
22
- code_challenge: string,
23
- code_challenge_method: string, //@@ enum S256
24
- code_verifier?: string
25
- }
26
-
27
- export interface IAuthorizeResponse {
28
- state: string, // state passed to authorize end-point
29
- code: string // authorization code
30
- }
31
-
32
- export interface IAuthorizeErrorResponse {
33
- error: string,
34
- error_description: string
35
- }
36
-
37
- export enum OAuthGrantTypes {
38
- CLIENT_CREDENTIALS = 'client_credentials',
39
- AUTHORIZATION_CODE = 'authorization_code',
40
- REFRESH_TOKEN = 'refresh_token'
41
- }
42
-
43
- export interface IAuthorizationCodeFlowParameters {
44
- client_id: string,
45
- scope: string,
46
- code: string,
47
- redirect_uri: string, // URI
48
- grant_type: OAuthGrantTypes, // 'authorization_code', //@@ need enum
49
- code_verifier: string
50
- }
51
-
52
- export interface IRefreshFlowParameters {
53
- client_id: string,
54
- scope: string,
55
- refresh_token: string, // JWT
56
- grant_type: OAuthGrantTypes // 'refresh_token' //@@ enum
57
- }
58
-
59
- export interface ITokenResponse {
60
- access_token: string, // JWT
61
- token_type: string, //@@ "Bearer" only
62
- expires_in: number,
63
- scope: string,
64
- refresh_token: string, // JWT
65
- id_token: string, // JWT
66
- }
67
-
68
- export interface ITokenErrorResponse {
69
- error: string,
70
- error_description: string,
71
- error_codes: number[],
72
- timestamp: number
73
- details: unknown //@@ STS attribute ?
74
- //"trace_id": "255d1aef-8c98-452f-ac51-23d051240864", //@@ MS attribute
75
- //"correlation_id": "fb3d2015-bc17-4bb9-bb85-30c5cf1aaaa7" //@@ MS attribute
76
- }
77
-
78
- export type AuthenticateEvent = (id_token: string) => void;
79
-
80
- // ---------------
81
-
82
- export enum IOauth2ListenerCommand {
83
- RESTORE_SESSION = 'RestoreSession',
84
- AUTHORIZE = 'Authorize',
85
- HANDLE_REDIRECT = 'HandleRedirect',
86
- LOGOUT = 'Logout',
87
- AUTHENTICATE_EVENT = 'AuthenticateEvent',
88
- ERROR = 'Error',
89
- LOG = '__LOG',
90
- UPDATE_INSTRUMENT = '__UPDATE_INSTRUMENT',
91
- ID_TOKEN = '__ID_TOKEN'
92
- }
93
-
94
- export interface IOauth2ListenerMessage {
95
- messageId?: number
96
- command: IOauth2ListenerCommand
97
- payload?: any
98
- }
99
-
100
- export interface IOauth2ListenerMessageResponse {
101
- messageId: number
102
- command: IOauth2ListenerCommand
103
- payload: any
104
- }
105
-
106
- export type StsOauth2WorkerFactory = () => Worker
107
-
108
- export interface ISTSOAuth2WorkerOptions {
109
- client_id: string
110
- scope: string
111
- redirect_uri: string
112
- audience: string
113
-
114
- brokerendpoint: string
115
- brokerport: string
116
- brokerapiroot: string
117
-
118
- authorizeendpoint: string
119
- authorizeport: string
120
- authorizeapiroot: string
121
-
122
- timeout: number
123
- }
124
-
125
- export interface ISTSOAuth2ManagerOptions {
126
- authenticateEvent?: AuthenticateEvent
127
- workerFactory?: StsOauth2WorkerFactory
128
- workerOptions: ISTSOAuth2WorkerOptions
129
- }
130
-
131
- export interface ISTSOAuth2WorkerMessage {
132
- workerPort: MessagePort,
133
- options: ISTSOAuth2WorkerOptions
134
- }