@nsshunt/stsoauth2plugin 0.1.52 → 0.1.56

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