@nsshunt/stsoauth2plugin 0.1.44 → 0.1.45

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,587 +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
- default :
160
- throw new Error(`Command: [${auth2ListenerMessage.command}'] not found.`);
161
- }
162
- }
163
- }
164
-
165
- #ProcessCommand = async (auth2ListenerMessage: IOauth2ListenerMessage, response: any) => {
166
- const messageResponse: IOauth2ListenerMessageResponse = {
167
- messageId: auth2ListenerMessage.messageId,
168
- command: auth2ListenerMessage.command,
169
- payload: response
170
- }
171
-
172
- debug(`STSOAuth2Worker:ProcessCommand:#oauthWorkerPort: [${JSON.stringify(this.#oauthWorkerPort)}]`);
173
- debug(this);
174
-
175
- this.#oauthWorkerPort.postMessage(messageResponse);
176
- }
177
-
178
- #RestoreSession = async (): Promise<boolean> => {
179
- //@@ attempt to get from client storage first
180
-
181
- let restoredSessionData: ITokenResponse = null;
182
- restoredSessionData = this.#clientSessionStore.get(this.#STORAGE_SESSION_KEY);
183
- if (restoredSessionData !== null) {
184
- console.log('Session restored from client storage.');
185
- if (this.#aic) {
186
- this.#aic.UpdateInstrument('m', { LogMessage: 'Session restored from client storage.' });
187
- }
188
- this.#LogMessage('Session restored from client storage.')
189
- } else {
190
- const url = `${this.#options.brokerendpoint}:${this.#options.brokerport}${this.#options.brokerapiroot}/session`;
191
- console.log('RestoreSession');
192
- console.log(url);
193
- if (this.#aic) {
194
- this.#aic.UpdateInstrument('m', { LogMessage: 'RestoreSession' });
195
- this.#aic.UpdateInstrument('m', { LogMessage: url });
196
- }
197
- this.#LogMessage('RestoreSession.');
198
- this.#LogMessage(url);
199
- try {
200
- const retVal = await axios({
201
- method: "post",
202
- url: url,
203
- data: {
204
- [OAuth2ParameterType.CLIENT_ID]: this.#options.client_id,
205
- [OAuth2ParameterType.SCOPE]: this.#options.scope,
206
- [OAuth2ParameterType.REDIRECT_URI]: this.#options.redirect_uri,
207
- [OAuth2ParameterType.AUDIENCE]: this.#options.audience
208
- },
209
- withCredentials: true, // Ensure cookies are passed to the service
210
- timeout: this.#options.timeout,
211
- });
212
- if (retVal.data.status === StatusCodes.OK) {
213
- restoredSessionData = retVal.data.detail;
214
- this.#clientSessionStore.set(this.#STORAGE_SESSION_KEY, restoredSessionData);
215
- console.log('Session restored from server side cookie.');
216
- //this.#store.commit('stsOAuth2SDK/SessionData', restoredSessionData);
217
- } else {
218
- //@@ handle error better
219
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
220
- console.log('Could not restore previous session:-');
221
- console.log(JSON.stringify(retVal.data));
222
- }
223
- } catch (error) {
224
- //@@ handle error better
225
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
226
- console.log('Could not restore previous session (error state):-');
227
- console.log(error);
228
- console.log(JSON.stringify(error));
229
- }
230
- }
231
-
232
- //@@ must only use in-memory for this ...
233
- //this.#store.commit('stsOAuth2SDK/SessionData', restoredSessionData);
234
- if (restoredSessionData !== null) {
235
- this.#HandleAuthenticateEvent(restoredSessionData.id_token);
236
- console.log('Refreshing tokens ...');
237
- return this.#RefreshToken();
238
- } else {
239
- this.#HandleAuthenticateEvent(null);
240
- return false;
241
- }
242
- }
243
-
244
- #Authorize = async (): Promise<JSONObject> => {
245
- console.log('Authorize ...');
246
-
247
- /* MS Example
248
- --------------
249
- https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
250
- client_id=6731de76-14a6-49ae-97bc-6eba6914391e
251
- &response_type=code
252
- &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
253
- &response_mode=query
254
- &scope=offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read%20api%3A%2F%2F
255
- &state=12345
256
- &code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
257
- &code_challenge_method=S256
258
-
259
- Successful Response
260
-
261
- GET http://localhost?
262
- code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...
263
- &state=12345
264
-
265
- Error Response
266
- GET http://localhost?
267
- error=access_denied
268
- &error_description=the+user+canceled+the+authentication
269
-
270
- << Hybrid Flow >>
271
-
272
- https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
273
- client_id=6731de76-14a6-49ae-97bc-6eba6914391e
274
- &response_type=code%20id_token
275
- &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
276
- &response_mode=fragment
277
- &scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
278
- &state=12345
279
- &nonce=abcde
280
- &code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
281
- &code_challenge_method=S256
282
-
283
- Successful Response
284
-
285
- GET https://login.microsoftonline.com/common/oauth2/nativeclient#
286
- code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...
287
- &id_token=eYj...
288
- &state=12345
289
-
290
- Notes:
291
- The nonce is included as a claim inside the returned id_token
292
- Ref: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
293
- */
294
-
295
- const client_id = this.#options.client_id;
296
- const nonce = this.#cUtils.CreateRandomString();
297
- const response_type = [ AuthorizeOptionsResponseType.CODE ]
298
- const redirect_uri = this.#options.redirect_uri;
299
- const response_mode = AuthorizeOptionsResponseMode.QUERY
300
- const scope = this.#options.scope
301
- const state = this.#cUtils.CreateRandomString();
302
- const code_verifier = this.#cUtils.CreateRandomString();
303
- const code_challenge = await this.#cUtils.DigestMessage(code_verifier);
304
- const code_challenge_method = 'S256';
305
- //let audience = this.#options.AUDIENCE;
306
-
307
- const authorizeOptions: IAuthorizeOptions = {
308
- client_id,
309
- nonce,
310
- response_type,
311
- redirect_uri,
312
- response_mode,
313
- scope,
314
- state,
315
- code_challenge,
316
- code_challenge_method
317
- }
318
-
319
- const url = `${this.#options.authorizeendpoint}:${this.#options.authorizeport}${this.#options.authorizeapiroot}?${this.#qParams.CreateQueryParams(authorizeOptions)}`;
320
-
321
- console.log(url);
322
-
323
- // Now add the code_verifier to the transaction data
324
- authorizeOptions.code_verifier = code_verifier; //@@ Is this is the only thing required across the transaction ?
325
-
326
- console.log(`Authorize:authorizeOptions: [${JSON.stringify(authorizeOptions)}]`);
327
-
328
- return {
329
- url,
330
- authorizeOptions
331
- }
332
- //window.location.assign(url);
333
- //@@ this may need to be a message back to the plugin to re-direct
334
- //window.location.replace(url);
335
- }
336
-
337
- #HandleRedirect = async (payload: any): Promise<boolean> => {
338
- const queryVars: IAuthorizeResponse | IAuthorizeErrorResponse = payload.queryVars;
339
- const authorizeOptions: IAuthorizeOptions = payload.authorizeOptions
340
-
341
- console.log('HandleRedirect');
342
- // We have been re-direct back here from the /authorize end-point
343
- console.log(`HandleRedirect:Query Vars: [${JSON.stringify(queryVars)}]`);
344
-
345
- if (queryVars[OAuth2ParameterType.CODE]) {
346
- const response: IAuthorizeResponse = queryVars as IAuthorizeResponse;
347
-
348
- console.log(`authorizeOptions from transaction state: [${JSON.stringify(authorizeOptions)}]`);
349
-
350
- const redirectState = response.state;
351
- const authorizeOptionsState = authorizeOptions.state;
352
-
353
- if (authorizeOptionsState.localeCompare(redirectState) === 0) {
354
- console.log('redirected state (from queryVars) matched previously saved transaction authorizeOptions state'); // green
355
-
356
- return await this.#GetToken(authorizeOptions, response);
357
- } else {
358
- console.log('redirected state (from queryVars) did NOT match previously saved transaction authorizeOptions state'); // red
359
- this.#HandleErrorEvent({message: 'State un-matched'});
360
- return false;
361
- }
362
- } else if (queryVars[OAuth2ParameterType.ERROR]) {
363
- const response: IAuthorizeErrorResponse = queryVars as IAuthorizeErrorResponse;
364
- //@@ pass error back to parent thread (to the plugin) as a message
365
- const error = response.error;
366
- const errorDescription = response.error_description;
367
- this.#HandleErrorEvent({message: 'State un-matched'});
368
- return false;
369
- } else {
370
- // Invalid redirect query params
371
- const error = 'Invalid redirect query params'; //@@ fix
372
- const errorDescription = 'Invalid redirect query params description'; //@@ fix
373
- this.#HandleErrorEvent({message: 'State un-matched'});
374
- return false;
375
- }
376
- }
377
-
378
- /*
379
- client_id=6731de76-14a6-49ae-97bc-6eba6914391e
380
- &scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
381
- &code=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq3n8b2JRLk4OxVXr...
382
- &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
383
- &grant_type=authorization_code
384
- &code_verifier=ThisIsntRandomButItNeedsToBe43CharactersLong
385
- &client_secret=JqQX2PNo9bpM0uEihUPzyrh // NOTE: Only required for web apps. This secret needs to be URL-Encoded.
386
-
387
- Successful Response
388
- {
389
- "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
390
- "token_type": "Bearer",
391
- "expires_in": 3599,
392
- "scope": "https%3A%2F%2Fgraph.microsoft.com%2Fmail.read",
393
- "refresh_token": "AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4...",
394
- "id_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctOD...",
395
- }
396
- */
397
-
398
- // Get access_token, refresh_token and id_token using OAuth2 Authorization Code Flow
399
- #GetTokenFromBroker = async (authorizationCodeFlowParameters: IAuthorizationCodeFlowParameters | IRefreshFlowParameters): Promise<boolean> => {
400
- console.log("#GetTokenFromBroker");
401
-
402
- this.#clientSessionStore.remove(this.#STORAGE_SESSION_KEY);
403
-
404
- const url = `${this.#options.brokerendpoint}:${this.#options.brokerport}${this.#options.brokerapiroot}/token`;
405
- console.log(`#GetTokenFromBroker:url = [${url}]`);
406
- console.log(authorizationCodeFlowParameters);
407
-
408
- try {
409
- const retVal = await axios({
410
- method: "post",
411
- url: url,
412
- data: authorizationCodeFlowParameters,
413
- withCredentials: true, // Ensure cookies are passed to the service
414
- timeout: this.#options.timeout
415
- });
416
- console.log(`retVal: ${JSON.stringify(retVal)}`);
417
-
418
- if (retVal.status === StatusCodes.OK) {
419
- console.log('Storing tokens...');
420
- const tokenResponse: ITokenResponse = retVal.data as ITokenResponse;
421
- //this.#store.commit('stsOAuth2SDK/SessionData', tokenResponse);
422
- this.#HandleAuthenticateEvent(tokenResponse.id_token);
423
- this.#clientSessionStore.set(this.#STORAGE_SESSION_KEY, tokenResponse);
424
- return true;
425
- } else if (retVal.status === StatusCodes.UNAUTHORIZED) {
426
- console.log('NOT Storing tokens...');
427
- console.log(retVal.status);
428
-
429
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
430
- this.#HandleAuthenticateEvent(null);
431
-
432
- const response: ITokenErrorResponse = retVal.data as ITokenErrorResponse;
433
-
434
- //@@ store response in state
435
- //@@ go to error page ??
436
- return false;
437
-
438
- } else {
439
- // General error
440
- console.log('NOT Storing tokens...');
441
- console.log(retVal.status);
442
-
443
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
444
- this.#HandleAuthenticateEvent(null);
445
-
446
- console.log('Could not obtain access_token from token end-point:-');
447
- console.log(JSON.stringify(retVal.data));
448
- //@@ store error in state to show in error page
449
- return false;
450
- }
451
- } catch (error) {
452
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
453
- this.#HandleAuthenticateEvent(null);
454
- //console.log('Could not restore previous session (error state):-');
455
- console.log(error);
456
- console.log(JSON.stringify(error));
457
-
458
- //@@ store error in state to show in error page
459
-
460
- return false;
461
- }
462
- }
463
-
464
- // Get access_token, refresh_token and id_token using OAuth2 Authorization Code Flow
465
- #GetToken = async (authorizeOptions: IAuthorizeOptions, authorizeResponse: IAuthorizeResponse): Promise<boolean> => {
466
- console.log("#GetToken");
467
- console.log(authorizeResponse);
468
-
469
- this.#clientSessionStore.set(this.#STORAGE_SESSION_KEY, null);
470
-
471
- const authorizationCodeFlowParameters: IAuthorizationCodeFlowParameters = {
472
- client_id: this.#options.client_id,
473
- scope: this.#options.scope,
474
- code: authorizeResponse.code,
475
- redirect_uri: this.#options.redirect_uri,
476
- grant_type: OAuthGrantTypes.AUTHORIZATION_CODE,
477
- code_verifier: authorizeOptions.code_verifier
478
- }
479
-
480
- return this.#GetTokenFromBroker(authorizationCodeFlowParameters);
481
- }
482
-
483
- /*
484
- // Line breaks for legibility only
485
-
486
- POST /{tenant}/oauth2/v2.0/token HTTP/1.1
487
- Host: https://login.microsoftonline.com
488
- Content-Type: application/x-www-form-urlencoded
489
-
490
- client_id=535fb089-9ff3-47b6-9bfb-4f1264799865
491
- &scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
492
- &refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
493
- &grant_type=refresh_token
494
- &client_secret=sampleCredentia1s // NOTE: Only required for web apps. This secret needs to be URL-Encoded
495
-
496
- Error Response
497
- {
498
- "error": "invalid_scope",
499
- "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",
500
- "error_codes": [
501
- 70011
502
- ],
503
- "timestamp": "2016-01-09 02:02:12Z",
504
- "trace_id": "255d1aef-8c98-452f-ac51-23d051240864",
505
- "correlation_id": "fb3d2015-bc17-4bb9-bb85-30c5cf1aaaa7"
506
- }
507
- */
508
-
509
- #RefreshToken = async (): Promise<boolean> => {
510
- // Get access_token, refresh_token and id_token using OAuth2 Authorization Code Flow
511
- console.log("RefreshToken");
512
-
513
- //let currentSessionData = this.#store.getters['stsOAuth2SDK/SessionData'];
514
- const currentSessionData: ITokenResponse = this.#clientSessionStore.get(this.#STORAGE_SESSION_KEY);
515
- if (currentSessionData) {
516
- const refreshFlowParameters: IRefreshFlowParameters = {
517
- client_id: this.#options.client_id,
518
- scope: this.#options.scope,
519
- refresh_token: currentSessionData.refresh_token,
520
- grant_type: OAuthGrantTypes.REFRESH_TOKEN
521
- }
522
-
523
- return this.#GetTokenFromBroker(refreshFlowParameters);
524
- } else {
525
- // show error
526
- //@@ no valid session exists for refresh
527
- return false;
528
- }
529
- }
530
-
531
- // call broker to logout
532
- // broker to logout of server
533
- // delete cookie
534
- // clear session storage
535
- // clear all state from $store
536
- #Logout = async (): Promise<boolean> => {
537
- console.log('Logout');
538
- const url = `${this.#options.brokerendpoint}:${this.#options.brokerport}${this.#options.brokerapiroot}/logout`;
539
- console.log(url);
540
-
541
- const currentSessionData: ITokenResponse = this.#clientSessionStore.get(this.#STORAGE_SESSION_KEY);
542
- const refresh_token = currentSessionData.refresh_token;
543
- console.log(refresh_token);
544
-
545
- const decodedRefreshToken: JSONObject = jwt_decode<JSONObject>(refresh_token);
546
- console.log(decodedRefreshToken);
547
- const sessionId = decodedRefreshToken.sts_session;
548
- console.log(sessionId);
549
-
550
- this.#clientSessionStore.remove(this.#STORAGE_SESSION_KEY);
551
- //this.#store.commit('stsOAuth2SDK/SessionData', null);
552
- this.#HandleAuthenticateEvent(null);
553
-
554
- try {
555
- const retVal = await axios({
556
- method: "post",
557
- url: url,
558
- data: {
559
- sessionId
560
- },
561
- withCredentials: true, // Ensure cookies are passed to the service
562
- timeout: this.#options.timeout,
563
- });
564
- if (retVal.data.status === StatusCodes.OK) {
565
- return true;
566
- } else {
567
- console.log('Error during logout (server side)');
568
- console.log(JSON.stringify(retVal.data));
569
- return false;
570
- }
571
- } catch (error) {
572
- console.log('Error during logout (server side)');
573
- console.log(error);
574
- console.log(JSON.stringify(error));
575
- return false;
576
- }
577
- }
578
- }
579
- /*
580
- let oAuth2Worker: STSOAuth2Worker = null;
581
-
582
- onmessage = async function(data: MessageEvent)
583
- {
584
- const workerPort = data.data as MessagePort;
585
- oAuth2Worker = new STSOAuth2Worker(workerPort);
586
- }
587
- */
package/tsconfig.json DELETED
@@ -1,32 +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
- "lib": [
20
- // Should target at least ES2016 in Vue 3
21
- // Support for newer versions of language built-ins are
22
- // left for the users to include, because that would require:
23
- // - either the project doesn't need to support older versions of browsers;
24
- // - or the project has properly included the necessary polyfills.
25
- "ES2016",
26
- "DOM",
27
- "DOM.Iterable",
28
- "webworker"
29
- // No `ScriptHost` because Vue 3 dropped support for IE
30
- ],
31
- }
32
- }
package/vite.config.ts DELETED
@@ -1,62 +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.argv': [ process.cwd() ], //@@ only required because of colors - delete ...
16
- 'process.env': { ...process.env },
17
- // Define process properties used by various imports
18
- 'process.pid': 0,
19
- 'process.stdout': null,
20
- 'process.stderr': null,
21
- 'process.platform': null
22
- },
23
- resolve: {
24
- alias: {
25
- //'@': path.resolve(__dirname, 'src'),
26
- '@': fileURLToPath(new URL('./src', import.meta.url))
27
- },
28
- },
29
-
30
- build: {
31
- lib: {
32
- entry: path.resolve(__dirname, 'src/index.ts'),
33
- name: 'stsoauth2plugin',
34
- formats: ['es'],
35
- fileName: (format) => `stsoauth2plugin.${format}.js`
36
- },
37
- /*
38
- rollupOptions: {
39
- output: {
40
- manualChunks: {
41
- stsoauth2plugin: ['@nsshunt/stsoauth2plugin'],
42
- stsinstrumentation: ['@nsshunt/stsinstrumentation'],
43
- stsmodels: ['@nsshunt/stsmodels'],
44
- stspublisherserver: ['@nsshunt/stspublisherserver'],
45
- stsutils: ['@nsshunt/stsutils'],
46
- axios: ['axios'],
47
- jwtdecode: ['jwt-decode']
48
- }
49
- }
50
- }
51
- */
52
- },
53
-
54
- base: '/',
55
-
56
- worker: {
57
- format: 'es'
58
- }
59
-
60
- });
61
- }
62
-