@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,595 +0,0 @@
1
- import Debug from "debug";
2
- const debug = Debug(`proc:${process.pid}:stsoauth2worker.ts`);
3
-
4
- //import 'colors'
5
-
6
- import axios from "axios";
7
-
8
- import { JSONObject, OAuth2ParameterType } from '@nsshunt/stsutils';
9
-
10
- import CryptoUtils from './Utils/CryptoUtils'
11
- import QueryParams from './Utils/QueryParams'
12
-
13
- import jwt_decode from "jwt-decode"
14
-
15
- import { IStsStorage, ClientStorageType, ClientStorageFactory } from './stsStorage'
16
-
17
- import { StatusCodes } from 'http-status-codes'
18
-
19
- import { AuthorizeOptionsResponseType, AuthorizeOptionsResponseMode, IAuthorizationCodeFlowParameters, IRefreshFlowParameters,
20
- IAuthorizeOptions, ITokenResponse, IAuthorizeResponse, IAuthorizeErrorResponse, ITokenErrorResponse, OAuthGrantTypes, AuthenticateEvent,
21
- IOauth2ListenerMessage, IOauth2ListenerCommand, IOauth2ListenerMessageResponse, ISTSOAuth2WorkerOptions } from './stsoauth2types'
22
-
23
- import { Gauge, InstrumentBaseTelemetry, InstrumentLogTelemetry, InstrumentGaugeTelemetry } from '@nsshunt/stsinstrumentation'
24
-
25
- const CreateRandomString = (size = 43) => {
26
- const randomValues = Array.from(self.crypto.getRandomValues(new Uint8Array(size)))
27
- const b64 = window.btoa(String.fromCharCode(...randomValues));
28
- return b64;
29
- //return randomValues.toString('base64');
30
- }
31
-
32
- // STS Client SDK for SPAs
33
- export class STSOAuth2Worker {
34
- //#storageManager = null;
35
- #clientSessionStore: IStsStorage<ITokenResponse> = null; // In memory tokens while the client is logged in
36
- #cUtils = new CryptoUtils();
37
- #qParams = new QueryParams();
38
- #STORAGE_SESSION_KEY = 'session.stsmda.com.au';
39
- #aic = null;
40
- #oauthWorkerPort: MessagePort = null;
41
- #options: ISTSOAuth2WorkerOptions = null;
42
-
43
- constructor(workerPort: MessagePort, options: ISTSOAuth2WorkerOptions) {
44
- //this.#store = app.config.globalProperties.$store;
45
- this.#options = options;
46
-
47
- debug(`STSOAuth2Worker:constructor:#options: [${JSON.stringify(this.#options)}]`);
48
-
49
- // In memory storage for OAuth2 tokens for our valid session
50
- this.#clientSessionStore = new ClientStorageFactory<ITokenResponse>({clientStorageType: ClientStorageType.MEMORY_STORAGE}).GetStorage();
51
-
52
- //@@ needs to be sent the instrument manager controller port
53
- //@@this.#aic = app.config.globalProperties.$sts.aic.PrimaryPublishInstrumentController;
54
-
55
- //this.#handleAuthenticateEvent = handleAuthenticateEvent;
56
-
57
- this.#oauthWorkerPort = workerPort;
58
-
59
- debug(`STSOAuth2Worker:constructor:#oauthWorkerPort: [${JSON.stringify(this.#oauthWorkerPort)}]`);
60
-
61
- this.SetupListener();
62
-
63
- setInterval(() => {
64
- this.#UpdateInstrument(Gauge.LOGGER, {
65
- LogMessage: `--> [${Date.now().toString()}] <--`
66
- } as InstrumentLogTelemetry);
67
-
68
- this.#UpdateInstrument(Gauge.REQUEST_COUNT_GAUGE, {
69
- Inc: 1
70
- } as InstrumentGaugeTelemetry);
71
-
72
- this.#UpdateInstrument(Gauge.AUTHENTICATION_COUNT_GAUGE, {
73
- Inc: 1
74
- } as InstrumentGaugeTelemetry);
75
- }, 1000);
76
- }
77
-
78
- // Attempt to restore a previous session using the STSBroker
79
- /*
80
- { parameterType: OAuth2ParameterType.CLIENT_ID, errorType: authErrorType.CLIENT_ID_MISMATCH },
81
- { parameterType: OAuth2ParameterType.SCOPE, errorType: authErrorType.SCOPE_MISMATCH }
82
- { parameterType: OAuth2ParameterType.REDIRECT_URI, errorType: authErrorType.REDIRECT_URI_MISMATCH },
83
- { parameterType: OAuth2ParameterType.AUDIENCE, errorType: authErrorType.SCOPE_MISMATCH }
84
-
85
- Successful Response
86
- {
87
- "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
88
- "token_type": "Bearer",
89
- "expires_in": 3599,
90
- "scope": "https%3A%2F%2Fgraph.microsoft.com%2Fmail.read",
91
- "refresh_token": "AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4...",
92
- "id_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctOD...",
93
- }
94
-
95
- Error Response
96
- {
97
- "error": "invalid_scope",
98
- "error_description": "AADSTS70011: The provided value for the input parameter 'scope' is not valid. The scope https://foo.microsoft.com/mail.read is not valid.\r\nTrace ID: 255d1aef-8c98-452f-ac51-23d051240864\r\nCorrelation ID: fb3d2015-bc17-4bb9-bb85-30c5cf1aaaa7\r\nTimestamp: 2016-01-09 02:02:12Z",
99
- "error_codes": [
100
- 70011
101
- ],
102
- "timestamp": "2016-01-09 02:02:12Z",
103
- }
104
-
105
-
106
- */
107
-
108
- #HandleAuthenticateEvent = (id_token: string) => {
109
- const message: IOauth2ListenerMessage = {
110
- messageId: -1, // un-solicited message
111
- command: IOauth2ListenerCommand.AUTHENTICATE_EVENT
112
- }
113
- this.#ProcessCommand(message, id_token);
114
- }
115
-
116
- #HandleErrorEvent = (error: any) => {
117
- const message: IOauth2ListenerMessage = {
118
- messageId: -1, // un-solicited message
119
- command: IOauth2ListenerCommand.ERROR
120
- }
121
- this.#ProcessCommand(message, error);
122
- }
123
-
124
- #LogMessage = (messageToSend: string) => {
125
- const message: IOauth2ListenerMessage = {
126
- messageId: -1, // un-solicited message
127
- command: IOauth2ListenerCommand.LOG
128
- }
129
- this.#ProcessCommand(message, messageToSend);
130
- }
131
-
132
- #UpdateInstrument = (instrumentName: Gauge, telemetry: InstrumentBaseTelemetry): void => {
133
- const message: IOauth2ListenerMessage = {
134
- messageId: -1, // un-solicited message
135
- command: IOauth2ListenerCommand.UPDATE_INSTRUMENT
136
- }
137
- this.#ProcessCommand(message, {
138
- instrumentName,
139
- telemetry
140
- });
141
- }
142
-
143
- SetupListener = () => {
144
- this.#oauthWorkerPort.onmessage = async (data: MessageEvent) => {
145
- const auth2ListenerMessage: IOauth2ListenerMessage = data.data as IOauth2ListenerMessage;
146
- switch (auth2ListenerMessage.command) {
147
- case IOauth2ListenerCommand.RESTORE_SESSION :
148
- this.#ProcessCommand(auth2ListenerMessage, await this.#RestoreSession());
149
- break;
150
- case IOauth2ListenerCommand.AUTHORIZE :
151
- this.#ProcessCommand(auth2ListenerMessage, await this.#Authorize());
152
- break;
153
- case IOauth2ListenerCommand.HANDLE_REDIRECT :
154
- this.#ProcessCommand(auth2ListenerMessage, await this.#HandleRedirect(auth2ListenerMessage.payload));
155
- break;
156
- case IOauth2ListenerCommand.LOGOUT :
157
- this.#ProcessCommand(auth2ListenerMessage, await this.#Logout());
158
- break;
159
- /*
160
- case IOauth2ListenerCommand.ID_TOKEN :
161
- this.#ProcessCommand(auth2ListenerMessage, await this.#GetIDToken());
162
- break;
163
- */
164
- default :
165
- throw new Error(`Command: [${auth2ListenerMessage.command}'] not found.`);
166
- }
167
- }
168
- }
169
-
170
- /*
171
- #GetIDToken = async(): Promise<string> => {
172
- return '-- ID Token --';
173
- }
174
- */
175
-
176
- #ProcessCommand = async (auth2ListenerMessage: IOauth2ListenerMessage, response: any) => {
177
- const messageResponse: IOauth2ListenerMessageResponse = {
178
- messageId: auth2ListenerMessage.messageId,
179
- command: auth2ListenerMessage.command,
180
- payload: response
181
- }
182
-
183
- this.#oauthWorkerPort.postMessage(messageResponse);
184
- }
185
-
186
- #RestoreSession = async (): Promise<boolean> => {
187
- //@@ attempt to get from client storage first
188
-
189
- let restoredSessionData: ITokenResponse = null;
190
- restoredSessionData = this.#clientSessionStore.get(this.#STORAGE_SESSION_KEY);
191
- if (restoredSessionData !== null) {
192
- console.log('Session restored from client storage.');
193
- if (this.#aic) {
194
- this.#aic.UpdateInstrument('m', { LogMessage: 'Session restored from client storage.' });
195
- }
196
- this.#LogMessage('Session restored from client storage.')
197
- } else {
198
- const url = `${this.#options.brokerendpoint}:${this.#options.brokerport}${this.#options.brokerapiroot}/session`;
199
- console.log('RestoreSession');
200
- console.log(url);
201
- if (this.#aic) {
202
- this.#aic.UpdateInstrument('m', { LogMessage: 'RestoreSession' });
203
- this.#aic.UpdateInstrument('m', { LogMessage: url });
204
- }
205
- this.#LogMessage('RestoreSession.');
206
- this.#LogMessage(url);
207
- try {
208
- const retVal = await axios({
209
- method: "post",
210
- url: url,
211
- data: {
212
- [OAuth2ParameterType.CLIENT_ID]: this.#options.client_id,
213
- [OAuth2ParameterType.SCOPE]: this.#options.scope,
214
- [OAuth2ParameterType.REDIRECT_URI]: this.#options.redirect_uri,
215
- [OAuth2ParameterType.AUDIENCE]: this.#options.audience
216
- },
217
- withCredentials: true, // Ensure cookies are passed to the service
218
- timeout: this.#options.timeout,
219
- });
220
- if (retVal.data.status === StatusCodes.OK) {
221
- restoredSessionData = retVal.data.detail;
222
- this.#clientSessionStore.set(this.#STORAGE_SESSION_KEY, restoredSessionData);
223
- console.log('Session restored from server side cookie.');
224
- //this.#store.commit('stsOAuth2SDK/SessionData', restoredSessionData);
225
- } else {
226
- //@@ handle error better
227
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
228
- console.log('Could not restore previous session:-');
229
- console.log(JSON.stringify(retVal.data));
230
- }
231
- } catch (error) {
232
- //@@ handle error better
233
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
234
- console.log('Could not restore previous session (error state):-');
235
- console.log(error);
236
- console.log(JSON.stringify(error));
237
- }
238
- }
239
-
240
- //@@ must only use in-memory for this ...
241
- //this.#store.commit('stsOAuth2SDK/SessionData', restoredSessionData);
242
- if (restoredSessionData !== null) {
243
- this.#HandleAuthenticateEvent(restoredSessionData.id_token);
244
- console.log('Refreshing tokens ...');
245
- return this.#RefreshToken();
246
- } else {
247
- this.#HandleAuthenticateEvent(null);
248
- return false;
249
- }
250
- }
251
-
252
- #Authorize = async (): Promise<JSONObject> => {
253
- console.log('Authorize ...');
254
-
255
- /* MS Example
256
- --------------
257
- https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
258
- client_id=6731de76-14a6-49ae-97bc-6eba6914391e
259
- &response_type=code
260
- &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
261
- &response_mode=query
262
- &scope=offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read%20api%3A%2F%2F
263
- &state=12345
264
- &code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
265
- &code_challenge_method=S256
266
-
267
- Successful Response
268
-
269
- GET http://localhost?
270
- code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...
271
- &state=12345
272
-
273
- Error Response
274
- GET http://localhost?
275
- error=access_denied
276
- &error_description=the+user+canceled+the+authentication
277
-
278
- << Hybrid Flow >>
279
-
280
- https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
281
- client_id=6731de76-14a6-49ae-97bc-6eba6914391e
282
- &response_type=code%20id_token
283
- &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
284
- &response_mode=fragment
285
- &scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
286
- &state=12345
287
- &nonce=abcde
288
- &code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
289
- &code_challenge_method=S256
290
-
291
- Successful Response
292
-
293
- GET https://login.microsoftonline.com/common/oauth2/nativeclient#
294
- code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...
295
- &id_token=eYj...
296
- &state=12345
297
-
298
- Notes:
299
- The nonce is included as a claim inside the returned id_token
300
- Ref: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
301
- */
302
-
303
- const client_id = this.#options.client_id;
304
- const nonce = this.#cUtils.CreateRandomString();
305
- const response_type = [ AuthorizeOptionsResponseType.CODE ]
306
- const redirect_uri = this.#options.redirect_uri;
307
- const response_mode = AuthorizeOptionsResponseMode.QUERY
308
- const scope = this.#options.scope
309
- const state = this.#cUtils.CreateRandomString();
310
- const code_verifier = this.#cUtils.CreateRandomString();
311
- const code_challenge = await this.#cUtils.DigestMessage(code_verifier);
312
- const code_challenge_method = 'S256';
313
- //let audience = this.#options.AUDIENCE;
314
-
315
- const authorizeOptions: IAuthorizeOptions = {
316
- client_id,
317
- nonce,
318
- response_type,
319
- redirect_uri,
320
- response_mode,
321
- scope,
322
- state,
323
- code_challenge,
324
- code_challenge_method
325
- }
326
-
327
- const url = `${this.#options.authorizeendpoint}:${this.#options.authorizeport}${this.#options.authorizeapiroot}?${this.#qParams.CreateQueryParams(authorizeOptions)}`;
328
-
329
- console.log(url);
330
-
331
- // Now add the code_verifier to the transaction data
332
- authorizeOptions.code_verifier = code_verifier; //@@ Is this is the only thing required across the transaction ?
333
-
334
- console.log(`Authorize:authorizeOptions: [${JSON.stringify(authorizeOptions)}]`);
335
-
336
- return {
337
- url,
338
- authorizeOptions
339
- }
340
- //window.location.assign(url);
341
- //@@ this may need to be a message back to the plugin to re-direct
342
- //window.location.replace(url);
343
- }
344
-
345
- #HandleRedirect = async (payload: any): Promise<boolean> => {
346
- const queryVars: IAuthorizeResponse | IAuthorizeErrorResponse = payload.queryVars;
347
- const authorizeOptions: IAuthorizeOptions = payload.authorizeOptions
348
-
349
- console.log('HandleRedirect');
350
- // We have been re-direct back here from the /authorize end-point
351
- console.log(`HandleRedirect:Query Vars: [${JSON.stringify(queryVars)}]`);
352
-
353
- if (queryVars[OAuth2ParameterType.CODE]) {
354
- const response: IAuthorizeResponse = queryVars as IAuthorizeResponse;
355
-
356
- console.log(`authorizeOptions from transaction state: [${JSON.stringify(authorizeOptions)}]`);
357
-
358
- const redirectState = response.state;
359
- const authorizeOptionsState = authorizeOptions.state;
360
-
361
- if (authorizeOptionsState.localeCompare(redirectState) === 0) {
362
- console.log('redirected state (from queryVars) matched previously saved transaction authorizeOptions state'); // green
363
-
364
- return await this.#GetToken(authorizeOptions, response);
365
- } else {
366
- console.log('redirected state (from queryVars) did NOT match previously saved transaction authorizeOptions state'); // red
367
- this.#HandleErrorEvent({message: 'State un-matched'});
368
- return false;
369
- }
370
- } else if (queryVars[OAuth2ParameterType.ERROR]) {
371
- const response: IAuthorizeErrorResponse = queryVars as IAuthorizeErrorResponse;
372
- //@@ pass error back to parent thread (to the plugin) as a message
373
- const error = response.error;
374
- const errorDescription = response.error_description;
375
- this.#HandleErrorEvent({message: 'State un-matched'});
376
- return false;
377
- } else {
378
- // Invalid redirect query params
379
- const error = 'Invalid redirect query params'; //@@ fix
380
- const errorDescription = 'Invalid redirect query params description'; //@@ fix
381
- this.#HandleErrorEvent({message: 'State un-matched'});
382
- return false;
383
- }
384
- }
385
-
386
- /*
387
- client_id=6731de76-14a6-49ae-97bc-6eba6914391e
388
- &scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
389
- &code=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq3n8b2JRLk4OxVXr...
390
- &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
391
- &grant_type=authorization_code
392
- &code_verifier=ThisIsntRandomButItNeedsToBe43CharactersLong
393
- &client_secret=JqQX2PNo9bpM0uEihUPzyrh // NOTE: Only required for web apps. This secret needs to be URL-Encoded.
394
-
395
- Successful Response
396
- {
397
- "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
398
- "token_type": "Bearer",
399
- "expires_in": 3599,
400
- "scope": "https%3A%2F%2Fgraph.microsoft.com%2Fmail.read",
401
- "refresh_token": "AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4...",
402
- "id_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctOD...",
403
- }
404
- */
405
-
406
- // Get access_token, refresh_token and id_token using OAuth2 Authorization Code Flow
407
- #GetTokenFromBroker = async (authorizationCodeFlowParameters: IAuthorizationCodeFlowParameters | IRefreshFlowParameters): Promise<boolean> => {
408
- console.log("#GetTokenFromBroker");
409
-
410
- this.#clientSessionStore.remove(this.#STORAGE_SESSION_KEY);
411
-
412
- const url = `${this.#options.brokerendpoint}:${this.#options.brokerport}${this.#options.brokerapiroot}/token`;
413
- console.log(`#GetTokenFromBroker:url = [${url}]`);
414
- console.log(authorizationCodeFlowParameters);
415
-
416
- try {
417
- const retVal = await axios({
418
- method: "post",
419
- url: url,
420
- data: authorizationCodeFlowParameters,
421
- withCredentials: true, // Ensure cookies are passed to the service
422
- timeout: this.#options.timeout
423
- });
424
- console.log(`retVal: ${JSON.stringify(retVal)}`);
425
-
426
- if (retVal.status === StatusCodes.OK) {
427
- console.log('Storing tokens...');
428
- const tokenResponse: ITokenResponse = retVal.data as ITokenResponse;
429
- //this.#store.commit('stsOAuth2SDK/SessionData', tokenResponse);
430
- this.#HandleAuthenticateEvent(tokenResponse.id_token);
431
- this.#clientSessionStore.set(this.#STORAGE_SESSION_KEY, tokenResponse);
432
- return true;
433
- } else if (retVal.status === StatusCodes.UNAUTHORIZED) {
434
- console.log('NOT Storing tokens...');
435
- console.log(retVal.status);
436
-
437
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
438
- this.#HandleAuthenticateEvent(null);
439
-
440
- const response: ITokenErrorResponse = retVal.data as ITokenErrorResponse;
441
-
442
- //@@ store response in state
443
- //@@ go to error page ??
444
- return false;
445
-
446
- } else {
447
- // General error
448
- console.log('NOT Storing tokens...');
449
- console.log(retVal.status);
450
-
451
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
452
- this.#HandleAuthenticateEvent(null);
453
-
454
- console.log('Could not obtain access_token from token end-point:-');
455
- console.log(JSON.stringify(retVal.data));
456
- //@@ store error in state to show in error page
457
- return false;
458
- }
459
- } catch (error) {
460
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
461
- this.#HandleAuthenticateEvent(null);
462
- //console.log('Could not restore previous session (error state):-');
463
- console.log(error);
464
- console.log(JSON.stringify(error));
465
-
466
- //@@ store error in state to show in error page
467
-
468
- return false;
469
- }
470
- }
471
-
472
- // Get access_token, refresh_token and id_token using OAuth2 Authorization Code Flow
473
- #GetToken = async (authorizeOptions: IAuthorizeOptions, authorizeResponse: IAuthorizeResponse): Promise<boolean> => {
474
- console.log("#GetToken");
475
- console.log(authorizeResponse);
476
-
477
- this.#clientSessionStore.set(this.#STORAGE_SESSION_KEY, null);
478
-
479
- const authorizationCodeFlowParameters: IAuthorizationCodeFlowParameters = {
480
- client_id: this.#options.client_id,
481
- scope: this.#options.scope,
482
- code: authorizeResponse.code,
483
- redirect_uri: this.#options.redirect_uri,
484
- grant_type: OAuthGrantTypes.AUTHORIZATION_CODE,
485
- code_verifier: authorizeOptions.code_verifier
486
- }
487
-
488
- return this.#GetTokenFromBroker(authorizationCodeFlowParameters);
489
- }
490
-
491
- /*
492
- // Line breaks for legibility only
493
-
494
- POST /{tenant}/oauth2/v2.0/token HTTP/1.1
495
- Host: https://login.microsoftonline.com
496
- Content-Type: application/x-www-form-urlencoded
497
-
498
- client_id=535fb089-9ff3-47b6-9bfb-4f1264799865
499
- &scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
500
- &refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
501
- &grant_type=refresh_token
502
- &client_secret=sampleCredentia1s // NOTE: Only required for web apps. This secret needs to be URL-Encoded
503
-
504
- Error Response
505
- {
506
- "error": "invalid_scope",
507
- "error_description": "AADSTS70011: The provided value for the input parameter 'scope' is not valid. The scope https://foo.microsoft.com/mail.read is not valid.\r\nTrace ID: 255d1aef-8c98-452f-ac51-23d051240864\r\nCorrelation ID: fb3d2015-bc17-4bb9-bb85-30c5cf1aaaa7\r\nTimestamp: 2016-01-09 02:02:12Z",
508
- "error_codes": [
509
- 70011
510
- ],
511
- "timestamp": "2016-01-09 02:02:12Z",
512
- "trace_id": "255d1aef-8c98-452f-ac51-23d051240864",
513
- "correlation_id": "fb3d2015-bc17-4bb9-bb85-30c5cf1aaaa7"
514
- }
515
- */
516
-
517
- #RefreshToken = async (): Promise<boolean> => {
518
- // Get access_token, refresh_token and id_token using OAuth2 Authorization Code Flow
519
- console.log("RefreshToken");
520
-
521
- //let currentSessionData = this.#store.getters['stsOAuth2SDK/SessionData'];
522
- const currentSessionData: ITokenResponse = this.#clientSessionStore.get(this.#STORAGE_SESSION_KEY);
523
- if (currentSessionData) {
524
- const refreshFlowParameters: IRefreshFlowParameters = {
525
- client_id: this.#options.client_id,
526
- scope: this.#options.scope,
527
- refresh_token: currentSessionData.refresh_token,
528
- grant_type: OAuthGrantTypes.REFRESH_TOKEN
529
- }
530
-
531
- return this.#GetTokenFromBroker(refreshFlowParameters);
532
- } else {
533
- // show error
534
- //@@ no valid session exists for refresh
535
- return false;
536
- }
537
- }
538
-
539
- // call broker to logout
540
- // broker to logout of server
541
- // delete cookie
542
- // clear session storage
543
- // clear all state from $store
544
- #Logout = async (): Promise<boolean> => {
545
- console.log('Logout');
546
- const url = `${this.#options.brokerendpoint}:${this.#options.brokerport}${this.#options.brokerapiroot}/logout`;
547
- console.log(url);
548
-
549
- const currentSessionData: ITokenResponse = this.#clientSessionStore.get(this.#STORAGE_SESSION_KEY);
550
- const refresh_token = currentSessionData.refresh_token;
551
- console.log(refresh_token);
552
-
553
- const decodedRefreshToken: JSONObject = jwt_decode<JSONObject>(refresh_token);
554
- console.log(decodedRefreshToken);
555
- const sessionId = decodedRefreshToken.sts_session;
556
- console.log(sessionId);
557
-
558
- this.#clientSessionStore.remove(this.#STORAGE_SESSION_KEY);
559
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
560
- this.#HandleAuthenticateEvent(null);
561
-
562
- try {
563
- const retVal = await axios({
564
- method: "post",
565
- url: url,
566
- data: {
567
- sessionId
568
- },
569
- withCredentials: true, // Ensure cookies are passed to the service
570
- timeout: this.#options.timeout,
571
- });
572
- if (retVal.data.status === StatusCodes.OK) {
573
- return true;
574
- } else {
575
- console.log('Error during logout (server side)');
576
- console.log(JSON.stringify(retVal.data));
577
- return false;
578
- }
579
- } catch (error) {
580
- console.log('Error during logout (server side)');
581
- console.log(error);
582
- console.log(JSON.stringify(error));
583
- return false;
584
- }
585
- }
586
- }
587
- /*
588
- let oAuth2Worker: STSOAuth2Worker = null;
589
-
590
- onmessage = async function(data: MessageEvent)
591
- {
592
- const workerPort = data.data as MessagePort;
593
- oAuth2Worker = new STSOAuth2Worker(workerPort);
594
- }
595
- */
package/tsconfig.json DELETED
@@ -1,34 +0,0 @@
1
- {
2
- "extends": "@tsconfig/node18/tsconfig.json",
3
- "include": ["src/**/*" ],
4
- "exclude": ["node_modules", "**/node_modules/**/*", "**/*.spec.ts"],
5
- "compilerOptions": {
6
- "module": "esnext",
7
- "target": "es2021",
8
- "moduleResolution": "node",
9
- "sourceMap": true,
10
- "outDir": "dist",
11
- "allowJs": true,
12
- "declaration": true,
13
- "declarationDir": "./types",
14
- "declarationMap": true,
15
-
16
- "noImplicitAny": false,
17
- "strictNullChecks": false,
18
-
19
- //"types": ["vite/client"], // https://vitejs.dev/guide/assets.html#explicit-url-imports https://vitejs.dev/guide/features.html#client-types
20
-
21
- "lib": [
22
- // Should target at least ES2016 in Vue 3
23
- // Support for newer versions of language built-ins are
24
- // left for the users to include, because that would require:
25
- // - either the project doesn't need to support older versions of browsers;
26
- // - or the project has properly included the necessary polyfills.
27
- "ES2016",
28
- "DOM",
29
- "DOM.Iterable",
30
- "webworker"
31
- // No `ScriptHost` because Vue 3 dropped support for IE
32
- ],
33
- }
34
- }
package/vite.config.ts DELETED
@@ -1,63 +0,0 @@
1
- import { fileURLToPath, URL } from 'url'
2
-
3
- import { defineConfig } from 'vite'
4
- import path from 'path'
5
- import fs from 'fs';
6
-
7
- // https://vitejs.dev/config/
8
- export default ({ mode }) => {
9
- //export default defineConfig({
10
- //process.env = {...process.env, ...loadEnv(mode, process.cwd())};
11
- // https://github.com/vitejs/vite/issues/1930
12
-
13
- return defineConfig({
14
- define: {
15
- 'process': { },
16
- 'process.argv': [ process.cwd() ], //@@ only required because of colors - delete ...
17
- 'process.env': { ...process.env },
18
- // Define process properties used by various imports
19
- 'process.pid': 0,
20
- 'process.stdout': null,
21
- 'process.stderr': null,
22
- 'process.platform': null
23
- },
24
- resolve: {
25
- alias: {
26
- //'@': path.resolve(__dirname, 'src'),
27
- '@': fileURLToPath(new URL('./src', import.meta.url))
28
- },
29
- },
30
-
31
- build: {
32
- lib: {
33
- entry: path.resolve(__dirname, 'src/index.ts'),
34
- name: 'stsoauth2plugin',
35
- formats: ['es'],
36
- fileName: (format) => `stsoauth2plugin.${format}.js`
37
- },
38
- /*
39
- rollupOptions: {
40
- output: {
41
- manualChunks: {
42
- stsoauth2plugin: ['@nsshunt/stsoauth2plugin'],
43
- stsinstrumentation: ['@nsshunt/stsinstrumentation'],
44
- stsmodels: ['@nsshunt/stsmodels'],
45
- stspublisherserver: ['@nsshunt/stspublisherserver'],
46
- stsutils: ['@nsshunt/stsutils'],
47
- axios: ['axios'],
48
- jwtdecode: ['jwt-decode']
49
- }
50
- }
51
- }
52
- */
53
- },
54
-
55
- base: '/',
56
-
57
- worker: {
58
- format: 'es'
59
- }
60
-
61
- });
62
- }
63
-