@nsshunt/stsoauth2plugin 0.1.38 → 0.1.39

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,373 @@
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
+ }
@@ -0,0 +1,111 @@
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
+ }
92
+
93
+ export interface IOauth2ListenerMessage {
94
+ messageId?: number
95
+ command: IOauth2ListenerCommand
96
+ payload?: any
97
+ }
98
+
99
+ export interface IOauth2ListenerMessageResponse {
100
+ messageId: number
101
+ command: IOauth2ListenerCommand
102
+ payload: any
103
+ }
104
+
105
+ export type StsOauth2WorkerFactory = () => Worker
106
+
107
+ export interface ISTSOAuth2ManagerOptions {
108
+ router: any
109
+ authenticateEvent?: AuthenticateEvent
110
+ workerFactory?: StsOauth2WorkerFactory
111
+ }