@pega/auth 0.2.24 → 0.2.25

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,5 +1,17 @@
1
1
  // This file wraps various calls related to logging in, logging out, etc.
2
2
  // that use the auth.html/auth.js to do the work of logging in via OAuth 2.0.
3
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
6
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
7
+ };
8
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
9
+ if (kind === "m") throw new TypeError("Private method is not writable");
10
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
11
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
12
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
13
+ };
14
+ var _AuthManager_instances, _AuthManager_ssKeyPrefix, _AuthManager_pegaAuth, _AuthManager_ssKeyConfigInfo, _AuthManager_ssKeySessionInfo, _AuthManager_ssKeyTokenInfo, _AuthManager_ssKeyState, _AuthManager_authConfig, _AuthManager_authDynState, _AuthManager_authHeader, _AuthManager_customTokenParamsCB, _AuthManager_bOAuthCustom, _AuthManager_tokenInfo, _AuthManager_userInfo, _AuthManager_usePASS, _AuthManager_beforeUnloadAdded, _AuthManager_tokenStorage, _AuthManager_transform, _AuthManager_foldSpot, _AuthManager_loadUserinfo, _AuthManager_loginProps, _AuthManager_promiseInitialize, _AuthManager_transformAndParse, _AuthManager_getStorage, _AuthManager_setStorage, _AuthManager_calcFoldSpot, _AuthManager_transformer, _AuthManager_doUnloadUpdates, _AuthManager_doBeforeUnload, _AuthManager_doPageHide, _AuthManager_loadState, _AuthManager_doOnLoad, _AuthManager_doAuthDynStateChanged, _AuthManager_initialize, _AuthManager_constellationInit, _AuthManager_customConstellationInit, _AuthManager_fireTokenAvailable, _AuthManager_processTokenOnLogin, _AuthManager_doCustomTokenParamsCB, _AuthManager_updateLoginStatus, _AuthManager_authFullReauth, _AuthManager_authTokenUpdated;
3
15
  // It utilizes a JS Class and private members to protect any sensitive tokens
4
16
  // and token obfuscation routines
5
17
  import { PegaAuth } from '../oauth-client/auth.js';
@@ -7,157 +19,112 @@ import { isEmptyObject } from './common-utils.js';
7
19
  import { getSdkConfig, SdkConfigAccess } from './config_access.js';
8
20
  // Meant to be a singleton...only one instance per page
9
21
  class AuthManager {
10
- #ssKeyPrefix = 'rs';
11
- iOSDevice = false;
12
- // will store the PegaAuth (OAuth 2.0 client library) instance
13
- #pegaAuth = null;
14
- #ssKeyConfigInfo = '';
15
- #ssKeySessionInfo = '';
16
- #ssKeyTokenInfo = '';
17
- #ssKeyState = `${this.#ssKeyPrefix}State`;
18
- #authConfig = {};
19
- #authDynState = {};
20
- #authHeader = null;
21
- #customTokenParamsCB = null;
22
- // state that should be persisted across loads
23
- state = { usePopup: false, noInitialRedirect: false, locale: null };
24
- // # of properties within initial state object
25
- stateKeysCount = 3;
26
- bC11NBootstrapInProgress = false;
27
- bCustomAuth = false;
28
- #bOAuthCustom = false;
29
- #tokenInfo;
30
- #userInfo;
31
- onLoadDone = false;
32
- msReauthStart = null;
33
- initInProgress = false;
34
- isLoggedIn = false;
35
- // Whether to pass a session storage key or structure to auth library
36
- #usePASS = false;
37
- #beforeUnloadAdded = false;
38
- #tokenStorage = 'temp';
39
- #transform = true;
40
- #foldSpot = 2;
41
- // Whether to load and cache user info as part of login
42
- #loadUserinfo = false;
43
- // Keep loginProps passed to loginIfNecessary
44
- #loginProps = null;
45
- // Promise for Initialization of PegaAuth and resolution callback
46
- #promiseInitialize = null;
47
22
  constructor() {
23
+ _AuthManager_instances.add(this);
24
+ _AuthManager_ssKeyPrefix.set(this, 'rs');
25
+ Object.defineProperty(this, "iOSDevice", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: false
30
+ });
31
+ // will store the PegaAuth (OAuth 2.0 client library) instance
32
+ _AuthManager_pegaAuth.set(this, null);
33
+ _AuthManager_ssKeyConfigInfo.set(this, '');
34
+ _AuthManager_ssKeySessionInfo.set(this, '');
35
+ _AuthManager_ssKeyTokenInfo.set(this, '');
36
+ _AuthManager_ssKeyState.set(this, `${__classPrivateFieldGet(this, _AuthManager_ssKeyPrefix, "f")}State`);
37
+ _AuthManager_authConfig.set(this, {});
38
+ _AuthManager_authDynState.set(this, {});
39
+ _AuthManager_authHeader.set(this, null);
40
+ _AuthManager_customTokenParamsCB.set(this, null);
41
+ // state that should be persisted across loads
42
+ Object.defineProperty(this, "state", {
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true,
46
+ value: { usePopup: false, noInitialRedirect: false, locale: null }
47
+ });
48
+ // # of properties within initial state object
49
+ Object.defineProperty(this, "stateKeysCount", {
50
+ enumerable: true,
51
+ configurable: true,
52
+ writable: true,
53
+ value: 3
54
+ });
55
+ Object.defineProperty(this, "bC11NBootstrapInProgress", {
56
+ enumerable: true,
57
+ configurable: true,
58
+ writable: true,
59
+ value: false
60
+ });
61
+ Object.defineProperty(this, "bCustomAuth", {
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true,
65
+ value: false
66
+ });
67
+ _AuthManager_bOAuthCustom.set(this, false);
68
+ _AuthManager_tokenInfo.set(this, void 0);
69
+ _AuthManager_userInfo.set(this, void 0);
70
+ Object.defineProperty(this, "onLoadDone", {
71
+ enumerable: true,
72
+ configurable: true,
73
+ writable: true,
74
+ value: false
75
+ });
76
+ Object.defineProperty(this, "msReauthStart", {
77
+ enumerable: true,
78
+ configurable: true,
79
+ writable: true,
80
+ value: null
81
+ });
82
+ Object.defineProperty(this, "initInProgress", {
83
+ enumerable: true,
84
+ configurable: true,
85
+ writable: true,
86
+ value: false
87
+ });
88
+ Object.defineProperty(this, "isLoggedIn", {
89
+ enumerable: true,
90
+ configurable: true,
91
+ writable: true,
92
+ value: false
93
+ });
94
+ // Whether to pass a session storage key or structure to auth library
95
+ _AuthManager_usePASS.set(this, false);
96
+ _AuthManager_beforeUnloadAdded.set(this, false);
97
+ _AuthManager_tokenStorage.set(this, 'temp');
98
+ _AuthManager_transform.set(this, true);
99
+ _AuthManager_foldSpot.set(this, 2);
100
+ // Whether to load and cache user info as part of login
101
+ _AuthManager_loadUserinfo.set(this, false);
102
+ // Keep loginProps passed to loginIfNecessary
103
+ _AuthManager_loginProps.set(this, null);
104
+ // Promise for Initialization of PegaAuth and resolution callback
105
+ _AuthManager_promiseInitialize.set(this, null);
48
106
  // Auth Manager specific state is saved within session storage as important in redirect and popup window scenarios
49
- this.#loadState();
107
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_loadState).call(this);
50
108
  this.iOSDevice = /iPad|iPhone|iPod/.test(navigator.userAgent);
51
109
  }
52
- #transformAndParse(ssKey, ssItem, bForce = false) {
53
- let obj = {};
54
- try {
55
- obj = JSON.parse(this.#transformer(ssKey, ssItem, false, bForce));
56
- }
57
- catch (e) {
58
- // fall thru and return empty object
59
- }
60
- return obj;
61
- }
62
- // helper routine to retrieve JSON object stored in a session storage key
63
- // a 2nd optional arg can also retrieve an individual attribute
64
- #getStorage(ssKey, sAttrib = null) {
65
- let ssItem = ssKey ? window.sessionStorage.getItem(ssKey) : null;
66
- let obj = {};
67
- if (this.#loginProps?.altStateStorage &&
68
- !this.isLoggedIn &&
69
- !ssItem &&
70
- (ssKey === this.#ssKeyState || ssKey === this.#ssKeySessionInfo)) {
71
- ssItem = window.localStorage.getItem(ssKey);
72
- }
73
- if (ssItem) {
74
- try {
75
- obj = JSON.parse(ssItem);
76
- }
77
- catch (e) {
78
- obj = this.#transformAndParse(ssKey, ssItem, true);
79
- }
80
- }
81
- return sAttrib ? obj[sAttrib] : obj;
82
- }
83
- // helper routine to set storage to the passed in JSON
84
- #setStorage(ssKey, obj, bVerify = false) {
85
- try {
86
- // Set storage only if obj is not empty, else delete the storage
87
- if (!obj || isEmptyObject(obj)) {
88
- window.sessionStorage.removeItem(ssKey);
89
- }
90
- else {
91
- // const bClear = (ssKey === this.#ssKeyState || ssKey === this.#ssKeySessionInfo);
92
- const bClear = false;
93
- const sValue = bClear
94
- ? JSON.stringify(obj)
95
- : this.#transformer(ssKey, JSON.stringify(obj), true);
96
- window.sessionStorage.setItem(ssKey, sValue);
97
- if (bVerify) {
98
- const sStored = window.sessionStorage.getItem(ssKey);
99
- if (sStored !== sValue) {
100
- // eslint-disable-next-line no-console
101
- console.error(`Failed to properly write sessionStorage (${ssKey})`);
102
- }
103
- }
104
- if (this.#loginProps?.altStateStorage &&
105
- !this.isLoggedIn &&
106
- (ssKey === this.#ssKeyState || ssKey === this.#ssKeySessionInfo)) {
107
- window.localStorage.setItem(ssKey, sValue);
108
- }
109
- }
110
- }
111
- catch (e) {
112
- // eslint-disable-next-line no-console
113
- console.error(`Exception ${e} on attempted write of sessionStorage (${ssKey})`);
114
- }
115
- }
116
- #calcFoldSpot(s) {
117
- const nOffset = 1;
118
- const sChar = s.length > nOffset ? s.charAt(nOffset) : '2';
119
- const nSpot = parseInt(sChar, 10);
120
- this.#foldSpot = Number.isNaN(nSpot) ? 2 : (nSpot % 4) + 2;
121
- }
122
- // helper function to encode storage
123
- #transformer(ssKey, s, bIn, bForce = false) {
124
- const bTransform = bForce || this.#transform;
125
- const fnFold = (x) => {
126
- const nLen = x.length;
127
- const nExtra = nLen % this.#foldSpot;
128
- const nOffset = Math.floor(nLen / this.#foldSpot) + nExtra;
129
- const nRem = x.length - nOffset;
130
- return x.substring(bIn ? nOffset : nRem) + x.substring(0, bIn ? nOffset : nRem);
131
- };
132
- const bTknInfo = ssKey === this.#ssKeyTokenInfo;
133
- if (bTknInfo && !bIn && bTransform) {
134
- s = window.atob(fnFold(s));
135
- }
136
- // eslint-disable-next-line no-nested-ternary
137
- let result = bTransform ? (bIn ? window.btoa(s) : window.atob(s)) : s;
138
- if (bTknInfo && bIn && bTransform) {
139
- result = fnFold(window.btoa(result));
140
- }
141
- return result;
142
- }
143
110
  // Setter for authHeader (no getter)
144
111
  set authHeader(value) {
145
- this.#authHeader = value;
112
+ __classPrivateFieldSet(this, _AuthManager_authHeader, value, "f");
146
113
  // setAuthorizationHeader method not available til 8.8 so do safety check
147
114
  if (window.PCore?.getAuthUtils().setAuthorizationHeader) {
148
115
  const authHdr = value === null ? '' : value;
149
116
  window.PCore.getAuthUtils().setAuthorizationHeader(authHdr);
150
117
  }
151
- this.#updateLoginStatus();
118
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_updateLoginStatus).call(this);
152
119
  }
153
120
  // Setter for customTokenParamsCB
154
121
  set customTokenParamsCB(fn) {
155
- this.#customTokenParamsCB = fn;
122
+ __classPrivateFieldSet(this, _AuthManager_customTokenParamsCB, fn, "f");
156
123
  }
157
124
  // Setter/getter for appName
158
125
  set appName(appName) {
159
126
  this.state.appName = appName;
160
- this.#setStorage(this.#ssKeyState, this.state);
127
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyState, "f"), this.state);
161
128
  }
162
129
  get appName() {
163
130
  return this.state.appName;
@@ -165,7 +132,7 @@ class AuthManager {
165
132
  // Setter/getter for usePopupForRestOfSession
166
133
  set usePopupForRestOfSession(usePopup) {
167
134
  this.state.usePopup = usePopup;
168
- this.#setStorage(this.#ssKeyState, this.state);
135
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyState, "f"), this.state);
169
136
  }
170
137
  get usePopupForRestOfSession() {
171
138
  return this.state.usePopup;
@@ -176,7 +143,7 @@ class AuthManager {
176
143
  this.usePopupForRestOfSession = true;
177
144
  }
178
145
  this.state.noInitialRedirect = bNoInitialRedirect;
179
- this.#setStorage(this.#ssKeyState, this.state);
146
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyState, "f"), this.state);
180
147
  }
181
148
  get noInitialRedirect() {
182
149
  return this.state.noInitialRedirect || false;
@@ -184,7 +151,7 @@ class AuthManager {
184
151
  // Setter/getter for locale (override)
185
152
  set locale(localeOverride) {
186
153
  this.state.locale = localeOverride;
187
- this.#setStorage(this.#ssKeyState, this.state);
154
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyState, "f"), this.state);
188
155
  }
189
156
  get locale() {
190
157
  return this.state.locale;
@@ -197,7 +164,7 @@ class AuthManager {
197
164
  else if (this.msReauthStart) {
198
165
  delete this.msReauthStart;
199
166
  }
200
- this.#setStorage(this.#ssKeyState, this.state);
167
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyState, "f"), this.state);
201
168
  }
202
169
  get reauthStart() {
203
170
  return this.msReauthStart || 0;
@@ -206,22 +173,22 @@ class AuthManager {
206
173
  set keySuffix(s) {
207
174
  this.state.sfx = s || undefined;
208
175
  if (s) {
209
- this.#setStorage(this.#ssKeyState, this.state);
176
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyState, "f"), this.state);
210
177
  // To make it a bit more obtuse reverse the string and use that as the actual suffix
211
178
  const sSfx = s.split('').reverse().join('');
212
- this.#ssKeyConfigInfo = `${this.#ssKeyPrefix}CI_${sSfx}`;
213
- this.#ssKeySessionInfo = `${this.#ssKeyPrefix}SI_${sSfx}`;
214
- this.#ssKeyTokenInfo = `${this.#ssKeyPrefix}TI_${sSfx}`;
215
- this.#calcFoldSpot(sSfx);
179
+ __classPrivateFieldSet(this, _AuthManager_ssKeyConfigInfo, `${__classPrivateFieldGet(this, _AuthManager_ssKeyPrefix, "f")}CI_${sSfx}`, "f");
180
+ __classPrivateFieldSet(this, _AuthManager_ssKeySessionInfo, `${__classPrivateFieldGet(this, _AuthManager_ssKeyPrefix, "f")}SI_${sSfx}`, "f");
181
+ __classPrivateFieldSet(this, _AuthManager_ssKeyTokenInfo, `${__classPrivateFieldGet(this, _AuthManager_ssKeyPrefix, "f")}TI_${sSfx}`, "f");
182
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_calcFoldSpot).call(this, sSfx);
216
183
  }
217
184
  else {
218
- sessionStorage.removeItem(this.#ssKeyTokenInfo);
219
- sessionStorage.removeItem(this.#ssKeyConfigInfo);
220
- sessionStorage.removeItem(this.#ssKeySessionInfo);
221
- sessionStorage.removeItem(this.#ssKeyState);
222
- this.#ssKeyConfigInfo = '';
223
- this.#ssKeySessionInfo = '';
224
- this.#ssKeyTokenInfo = '';
185
+ sessionStorage.removeItem(__classPrivateFieldGet(this, _AuthManager_ssKeyTokenInfo, "f"));
186
+ sessionStorage.removeItem(__classPrivateFieldGet(this, _AuthManager_ssKeyConfigInfo, "f"));
187
+ sessionStorage.removeItem(__classPrivateFieldGet(this, _AuthManager_ssKeySessionInfo, "f"));
188
+ sessionStorage.removeItem(__classPrivateFieldGet(this, _AuthManager_ssKeyState, "f"));
189
+ __classPrivateFieldSet(this, _AuthManager_ssKeyConfigInfo, '', "f");
190
+ __classPrivateFieldSet(this, _AuthManager_ssKeySessionInfo, '', "f");
191
+ __classPrivateFieldSet(this, _AuthManager_ssKeyTokenInfo, '', "f");
225
192
  }
226
193
  }
227
194
  /**
@@ -229,443 +196,25 @@ class AuthManager {
229
196
  */
230
197
  clear(bFullReauth = false) {
231
198
  if (!this.bCustomAuth) {
232
- this.#authHeader = null;
199
+ __classPrivateFieldSet(this, _AuthManager_authHeader, null, "f");
233
200
  }
234
201
  // Clear any established auth tokens
235
- this.#tokenInfo = null;
236
- sessionStorage.removeItem(this.#ssKeyTokenInfo);
202
+ __classPrivateFieldSet(this, _AuthManager_tokenInfo, null, "f");
203
+ sessionStorage.removeItem(__classPrivateFieldGet(this, _AuthManager_ssKeyTokenInfo, "f"));
237
204
  this.isLoggedIn = false;
238
205
  // reset the initial redirect as well by using this setter
239
206
  this.usePopupForRestOfSession = bFullReauth;
240
207
  if (!bFullReauth) {
241
- if (!this.#usePASS) {
242
- this.#authConfig = {};
243
- this.#authDynState = {};
208
+ if (!__classPrivateFieldGet(this, _AuthManager_usePASS, "f")) {
209
+ __classPrivateFieldSet(this, _AuthManager_authConfig, {}, "f");
210
+ __classPrivateFieldSet(this, _AuthManager_authDynState, {}, "f");
244
211
  }
245
212
  // keySuffix setter has cleanup logic
246
213
  this.keySuffix = '';
247
214
  }
248
215
  }
249
- // Found beforeunload to not work well on iOS browsers, and pagehide to work better
250
- // However also seeing some scenario like navigating to a different page on Chrome & Firefox only invoking beforeunload
251
- // Chrome, Firefox, Safari browsers sequence on page reload: beforeunload, pagehide, visibilitychange
252
- // visibilitychange is fired whenever a tab is made visible and when it is hidden
253
- #doUnloadUpdates() {
254
- // Safari and particularly Safari on mobile devices doesn't seem to load this on first main redirect or
255
- // reliably, so have moved to having PegaAuth manage writing all state props to session storage
256
- this.#setStorage(this.#ssKeyState, this.state);
257
- this.#setStorage(this.#ssKeySessionInfo, this.#authDynState);
258
- // If tokenStorage was always, token would already be there
259
- if (this.#tokenStorage === 'temp') {
260
- this.#setStorage(this.#ssKeyTokenInfo, this.#tokenInfo);
261
- }
262
- }
263
- #doBeforeUnload() {
264
- this.#doUnloadUpdates();
265
- }
266
- #doPageHide() {
267
- this.#doUnloadUpdates();
268
- }
269
- #loadState() {
270
- // Note: State storage key doesn't have a client id associated with it
271
- const oState = this.#getStorage(this.#ssKeyState);
272
- if (oState) {
273
- Object.assign(this.state, oState);
274
- if (this.state.sfx) {
275
- // Setter sets up the ssKey values as well
276
- this.keySuffix = this.state.sfx;
277
- }
278
- }
279
- }
280
- // This is only called from initialize after #ssKey values are setup
281
- #doOnLoad() {
282
- if (!this.onLoadDone) {
283
- // This authConfig state doesn't collide with other calculated static state...so load it first
284
- // Note: transform setting will have already been loaded into #authConfig at this point
285
- this.#authDynState = this.#getStorage(this.#ssKeySessionInfo);
286
- this.#tokenInfo = this.#getStorage(this.#ssKeyTokenInfo);
287
- if (this.#tokenStorage !== 'always') {
288
- sessionStorage.removeItem(this.#ssKeyTokenInfo);
289
- // Finding on iOS browsers the pageHide event is sometimes not happening causing failed redirects.
290
- if (!this.iOSDevice) {
291
- sessionStorage.removeItem(this.#ssKeySessionInfo);
292
- }
293
- }
294
- this.onLoadDone = true;
295
- }
296
- }
297
- // Callback when auth dynamic state has changed. Decide whether to persisting it based on
298
- // config settings
299
- #doAuthDynStateChanged() {
300
- // If tokenStorage is setup for always then always persist the auth dynamic state as well
301
- if (this.#tokenStorage === 'always' || this.iOSDevice) {
302
- this.#setStorage(this.#ssKeySessionInfo, this.#authDynState);
303
- }
304
- }
305
- /**
306
- * Initialize OAuth config structure members and create authMgr instance (if necessary)
307
- * bNew - governs whether to create new sessionStorage or load existing one
308
- */
309
- async #initialize(bNew = false) {
310
- if (!bNew && this.#promiseInitialize) {
311
- return this.#promiseInitialize;
312
- }
313
- this.#promiseInitialize = new Promise(resolve => {
314
- /* if (!this.initInProgress && (bNew || isEmptyObject(this.#authConfig) || !this.#pegaAuth)) { */
315
- this.initInProgress = true;
316
- getSdkConfig().then(sdkConfig => {
317
- const sdkConfigAuth = sdkConfig.authConfig;
318
- const sdkConfigServer = sdkConfig.serverConfig;
319
- const serverType = sdkConfigServer.serverType || 'infinity';
320
- const bInfinity = serverType === 'infinity';
321
- let pegaUrl = bInfinity
322
- ? sdkConfigServer.infinityRestServerUrl
323
- : sdkConfigServer.launchpadRestServerUrl;
324
- // Expecting boolean true/false or undefined
325
- const secureCookie = !!sdkConfigAuth.secureCookie;
326
- const bNoInitialRedirect = this.noInitialRedirect;
327
- const appAliasSeg = sdkConfigServer.appAlias ? `app/${sdkConfigServer.appAlias}/` : '';
328
- // Construct default OAuth endpoints (if not explicitly specified)
329
- if (pegaUrl) {
330
- // Cope with trailing slash being present
331
- if (!pegaUrl.endsWith('/')) {
332
- pegaUrl += '/';
333
- }
334
- if (!sdkConfigAuth.authorize) {
335
- sdkConfigAuth.authorize = bInfinity
336
- ? `${pegaUrl}PRRestService/oauth2/v1/authorize`
337
- : `${pegaUrl}uas/oauth/authorize`;
338
- }
339
- const infinityOAuth2Url = bInfinity
340
- ? pegaUrl + (secureCookie && appAliasSeg ? `${appAliasSeg}api/` : 'PRRestService/')
341
- : '';
342
- if (!sdkConfigAuth.token) {
343
- sdkConfigAuth.token = bInfinity
344
- ? `${infinityOAuth2Url}oauth2/v1/token`
345
- : `${pegaUrl}uas/oauth/token`;
346
- }
347
- if (!sdkConfigAuth.revoke) {
348
- // Launchpad still does not have a revoke endpoint
349
- sdkConfigAuth.revoke = bInfinity ? `${infinityOAuth2Url}oauth2/v1/revoke` : '';
350
- }
351
- if (!sdkConfigAuth.redirectUri) {
352
- sdkConfigAuth.redirectUri = `${window.location.origin}${window.location.pathname}`;
353
- }
354
- if (!sdkConfigAuth.userinfo) {
355
- sdkConfigAuth.userinfo = bInfinity
356
- ? `${pegaUrl}${appAliasSeg}api/oauthclients/v1/userinfo/JSON`
357
- : '';
358
- }
359
- }
360
- // Auth service alias
361
- if (!sdkConfigAuth.authService) {
362
- sdkConfigAuth.authService = 'pega';
363
- }
364
- // mashupAuthService provides way to have a different auth service for embedded
365
- if (!sdkConfigAuth.mashupAuthService) {
366
- sdkConfigAuth.mashupAuthService = sdkConfigAuth.authService;
367
- }
368
- // Construct path to auth.html (used for case when not doing a main window redirect)
369
- let sNoMainRedirectUri = sdkConfigAuth.redirectUri;
370
- const nLastPathSep = sNoMainRedirectUri.lastIndexOf('/');
371
- sNoMainRedirectUri =
372
- nLastPathSep !== -1
373
- ? `${sNoMainRedirectUri.substring(0, nLastPathSep + 1)}auth.html`
374
- : `${sNoMainRedirectUri}/auth.html`;
375
- const portalGrantType = sdkConfigAuth.portalGrantType || 'authCode';
376
- const mashupGrantType = sdkConfigAuth.mashupGrantType || 'authCode';
377
- // Some grant types are only available with confidential registrations and require a client secret
378
- const clientSecret = bNoInitialRedirect
379
- ? sdkConfigAuth.mashupClientSecret
380
- : sdkConfigAuth.portalClientSecret;
381
- const pegaAuthConfig = {
382
- serverType,
383
- clientId: bNoInitialRedirect
384
- ? sdkConfigAuth.mashupClientId
385
- : sdkConfigAuth.portalClientId,
386
- grantType: bNoInitialRedirect ? mashupGrantType : portalGrantType,
387
- tokenUri: sdkConfigAuth.token,
388
- revokeUri: sdkConfigAuth.revoke,
389
- userinfoUri: sdkConfigAuth.userinfo,
390
- authService: bNoInitialRedirect
391
- ? sdkConfigAuth.mashupAuthService
392
- : sdkConfigAuth.authService,
393
- appAlias: sdkConfigServer.appAlias || '',
394
- useLocking: true
395
- };
396
- if (clientSecret) {
397
- pegaAuthConfig.clientSecret = clientSecret;
398
- }
399
- if (serverType === 'launchpad' && pegaAuthConfig.grantType === 'authCode') {
400
- pegaAuthConfig.noPKCE = true;
401
- }
402
- // Invoke keySuffix setter
403
- // Was using pegaAuthConfig.clientId as key but more secure to just use a random string as getting
404
- // both a clientId and the refresh token could yield a new access token.
405
- // Suffix is so we might in future move to an array of suffixes based on the appName, so might store
406
- // both portal and embedded tokens/session info at same time
407
- if (!this.state?.sfx) {
408
- // Just using a random number to make the suffix unique on each session
409
- this.keySuffix = `${Math.ceil(Math.random() * 100000000)}`;
410
- }
411
- this.#authConfig.transform =
412
- sdkConfigAuth.transform !== undefined ? sdkConfigAuth.transform : this.#transform;
413
- // Using property in class as authConfig may be empty at times
414
- this.#transform = this.#authConfig.transform;
415
- if (sdkConfigAuth.tokenStorage !== undefined) {
416
- this.#tokenStorage = sdkConfigAuth.tokenStorage;
417
- }
418
- if (sdkConfigAuth.secureCookie) {
419
- this.#authConfig.secureCookie = true;
420
- }
421
- // Get latest state once client ids, transform and tokenStorage have been established
422
- this.#doOnLoad();
423
- // If no clientId is specified assume not OAuth but custom auth
424
- if (pegaAuthConfig.grantType === 'none' || !pegaAuthConfig.clientId) {
425
- this.bCustomAuth = true;
426
- return;
427
- }
428
- // For some OAuth grant type scenarios we opt to pass the Orchestration Engine just an authHeader as
429
- // service broker doesn't have proper support for dealing with refreshing or revoking these:
430
- // * customBearer (except when secureCookie being used)
431
- // * confidential grant types (ones with clientSecret)
432
- // (With 25.1 orchestration engine does support this if client_secret is specified on bootstrap)
433
- this.#bOAuthCustom =
434
- (pegaAuthConfig.grantType === 'customBearer' && !secureCookie) || clientSecret;
435
- if (pegaAuthConfig.grantType === 'authCode') {
436
- const authCodeProps = {
437
- authorizeUri: sdkConfigAuth.authorize,
438
- // If we have already specified a redirect on the authorize redirect, we need to continue to use that
439
- // on token endpoint
440
- redirectUri: bNoInitialRedirect || this.usePopupForRestOfSession
441
- ? sNoMainRedirectUri
442
- : sdkConfigAuth.redirectUri
443
- };
444
- if ('silentTimeout' in sdkConfigAuth) {
445
- authCodeProps.silentTimeout = sdkConfigAuth.silentTimeout;
446
- }
447
- if (bNoInitialRedirect &&
448
- pegaAuthConfig.authService === 'pega' &&
449
- sdkConfigAuth.mashupUserIdentifier &&
450
- sdkConfigAuth.mashupPassword) {
451
- authCodeProps.userIdentifier = sdkConfigAuth.mashupUserIdentifier;
452
- authCodeProps.password = sdkConfigAuth.mashupPassword;
453
- }
454
- if ('iframeLoginUI' in sdkConfigAuth) {
455
- authCodeProps.iframeLoginUI =
456
- sdkConfigAuth.iframeLoginUI.toString().toLowerCase() === 'true';
457
- }
458
- Object.assign(pegaAuthConfig, authCodeProps);
459
- }
460
- else if (pegaAuthConfig.grantType === 'passwordCreds') {
461
- pegaAuthConfig.userIdentifier = sdkConfigAuth.mashupUserIdentifier;
462
- pegaAuthConfig.password = sdkConfigAuth.mashupPassword;
463
- }
464
- Object.assign(this.#authConfig, pegaAuthConfig);
465
- // Add beforeunload and page hide handlers to write out key properties that we want to survive a
466
- // browser reload
467
- if (!this.#beforeUnloadAdded && (!this.#usePASS || this.#tokenStorage !== 'always')) {
468
- window.addEventListener('beforeunload', this.#doBeforeUnload.bind(this));
469
- window.addEventListener('pagehide', this.#doPageHide.bind(this));
470
- this.#beforeUnloadAdded = true;
471
- }
472
- // Initialize PegaAuth OAuth 2.0 client library
473
- if (this.#usePASS) {
474
- this.#setStorage(this.#ssKeyConfigInfo, this.#authConfig);
475
- this.#setStorage(this.#ssKeySessionInfo, this.#authDynState);
476
- this.#pegaAuth = new PegaAuth(this.#ssKeyConfigInfo, this.#ssKeySessionInfo);
477
- }
478
- else {
479
- this.#authConfig.fnDynStateChangedCB = this.#doAuthDynStateChanged.bind(this);
480
- this.#pegaAuth = new PegaAuth(this.#authConfig, this.#authDynState);
481
- }
482
- this.initInProgress = false;
483
- resolve(this.#pegaAuth);
484
- });
485
- });
486
- return this.#promiseInitialize;
487
- }
488
- /**
489
- * Initiate the process to get the Constellation bootstrap shell loaded and initialized
490
- * @param {Object} tokenInfo
491
- * @param {Function} authTokenUpdated - callback invoked when Constellation JS Engine silently updates
492
- * an expired access_token
493
- * @param {Function} fnReauth - callback invoked when a full or custom reauth is needed
494
- */
495
- #constellationInit(tokenInfo, authTokenUpdated, fnReauth) {
496
- const constellationBootConfig = {};
497
- const sdkConfigServer = SdkConfigAccess.getSdkConfigServer();
498
- const sdkConfigAuth = SdkConfigAccess.getSdkConfigAuth();
499
- const authConfig = this.#authConfig;
500
- // Set up constellationConfig with data that bootstrapWithAuthHeader expects
501
- constellationBootConfig.customRendering = true;
502
- constellationBootConfig.restServerUrl = sdkConfigServer.infinityRestServerUrl;
503
- // NOTE: Needs a trailing slash! So add one if not provided
504
- if (!sdkConfigServer.sdkContentServerUrl.endsWith('/')) {
505
- sdkConfigServer.sdkContentServerUrl = `${sdkConfigServer.sdkContentServerUrl}/`;
506
- }
507
- constellationBootConfig.staticContentServerUrl = `${sdkConfigServer.sdkContentServerUrl}constellation/`;
508
- if (!constellationBootConfig.staticContentServerUrl.endsWith('/')) {
509
- constellationBootConfig.staticContentServerUrl = `${constellationBootConfig.staticContentServerUrl}/`;
510
- }
511
- // If appAlias specified, use it
512
- if (sdkConfigServer.appAlias) {
513
- constellationBootConfig.appAlias = sdkConfigServer.appAlias;
514
- }
515
- // Determine whether to send credentials with DX API transactions
516
- if (sdkConfigAuth.customCookies) {
517
- constellationBootConfig.customCookies = true;
518
- }
519
- if (this.#bOAuthCustom || !tokenInfo) {
520
- if (tokenInfo) {
521
- this.#authHeader = `${tokenInfo.token_type} ${tokenInfo.access_token}`;
522
- }
523
- if (this.#authHeader) {
524
- constellationBootConfig.authorizationHeader = this.#authHeader;
525
- }
526
- }
527
- else {
528
- // Pass in auth info to Constellation
529
- constellationBootConfig.authInfo = {
530
- authType: 'OAuth2.0',
531
- tokenInfo,
532
- // Set whether we want constellation to try to do a full re-Auth or not ()
533
- // true doesn't seem to be working in SDK scenario so always passing false for now
534
- popupReauth: false /* !this.noInitialRedirect */,
535
- client_id: authConfig.clientId,
536
- client_secret: authConfig.clientSecret,
537
- authentication_service: authConfig.authService,
538
- redirect_uri: authConfig.redirectUri,
539
- endPoints: {
540
- authorize: authConfig.authorizeUri,
541
- token: authConfig.tokenUri,
542
- revoke: authConfig.revokeUri
543
- },
544
- secureCookie: authConfig.secureCookie,
545
- onTokenRetrieval: authTokenUpdated
546
- };
547
- }
548
- // Turn off dynamic load components (should be able to do it here instead of after load?)
549
- constellationBootConfig.dynamicLoadComponents = false;
550
- // Set envType if appropriate
551
- if (authConfig.serverType === 'launchpad') {
552
- constellationBootConfig.envType = 'LAUNCHPAD';
553
- }
554
- // Set locale override if specified
555
- const localeOverride = this.locale;
556
- if (localeOverride) {
557
- constellationBootConfig.locale = localeOverride;
558
- }
559
- // Set additional headers if specified
560
- const additionalHeaders = this.#loginProps.additionalHeaders;
561
- if (additionalHeaders) {
562
- constellationBootConfig.additionalHeaders = additionalHeaders;
563
- }
564
- if (this.bC11NBootstrapInProgress) {
565
- return;
566
- }
567
- this.bC11NBootstrapInProgress = true;
568
- // Note that staticContentServerUrl already ends with a slash (see above), so no slash added.
569
- // In order to have this import succeed needed to use the webpackIgnore magic comment tag.
570
- // See: https://webpack.js.org/api/module-methods/
571
- import(
572
- /* webpackIgnore: true */ `${constellationBootConfig.staticContentServerUrl}bootstrap-shell.js?v=${Date.now()}`).then(bootstrapShell => {
573
- // NOTE: once this callback is done, we lose the ability to access loadMashup.
574
- // So, create a reference to it
575
- window.myLoadMashup = bootstrapShell.loadMashup;
576
- window.myLoadPortal = bootstrapShell.loadPortal;
577
- window.myLoadDefaultPortal = bootstrapShell.loadDefaultPortal;
578
- bootstrapShell
579
- .bootstrapWithAuthHeader(constellationBootConfig, 'pega-root')
580
- .then(() => {
581
- // eslint-disable-next-line no-console
582
- console.log('ConstellationJS bootstrap successful!');
583
- this.bC11NBootstrapInProgress = false;
584
- // Setup listener for the reauth event
585
- if (!this.#bOAuthCustom && tokenInfo) {
586
- PCore.getPubSubUtils().subscribe(PCore.getConstants().PUB_SUB_EVENTS.EVENT_FULL_REAUTH, fnReauth, 'authFullReauth');
587
- }
588
- else {
589
- // customReauth event introduced with 8.8
590
- const sEvent = PCore.getConstants().PUB_SUB_EVENTS.EVENT_CUSTOM_REAUTH;
591
- if (sEvent) {
592
- PCore.getPubSubUtils().subscribe(sEvent, fnReauth, 'doReauth');
593
- }
594
- }
595
- // Fire SdkConstellationReady event so bridge and app route can do expected post PCore initializations
596
- const event = new CustomEvent('SdkConstellationReady', {});
597
- document.dispatchEvent(event);
598
- })
599
- .catch(e => {
600
- // Assume error caught is because token is not valid and attempt a full reauth
601
- // eslint-disable-next-line no-console
602
- console.error(`ConstellationJS bootstrap failed. ${e}`);
603
- this.bC11NBootstrapInProgress = false;
604
- fnReauth();
605
- });
606
- });
607
- /* Ends here */
608
- }
609
- #customConstellationInit(fnReauth) {
610
- this.#constellationInit(null, null, fnReauth);
611
- }
612
- #fireTokenAvailable(token, bLoadC11N = true) {
613
- if (!token) {
614
- // This is used on page reload to load the token from sessionStorage and carry on
615
- token = this.#tokenInfo;
616
- if (!token) {
617
- return;
618
- }
619
- }
620
- this.#tokenInfo = token;
621
- if (this.#tokenStorage === 'always') {
622
- this.#setStorage(this.#ssKeyTokenInfo, this.#tokenInfo);
623
- }
624
- this.#updateLoginStatus();
625
- // this.isLoggedIn is getting updated in updateLoginStatus
626
- this.isLoggedIn = true;
627
- this.usePopupForRestOfSession = true;
628
- if (!window.PCore && bLoadC11N) {
629
- this.#constellationInit(token, this.#authTokenUpdated.bind(this), this.#authFullReauth.bind(this));
630
- }
631
- /*
632
- // Create and dispatch the SdkLoggedIn event to trigger constellationInit
633
- const event = new CustomEvent('SdkLoggedIn', { detail: { authConfig, tokenInfo: token } });
634
- document.dispatchEvent(event);
635
- */
636
- }
637
- #processTokenOnLogin(token, bLoadC11N = true) {
638
- this.#tokenInfo = token;
639
- if (this.#tokenStorage === 'always') {
640
- this.#setStorage(this.#ssKeyTokenInfo, this.#tokenInfo);
641
- }
642
- if (this.#bOAuthCustom) {
643
- // authHeader setter will also set #authHeader and invoke getAuthUtils().setAuthorizationHeader
644
- this.authHeader = `${token.token_type} ${token.access_token}`;
645
- }
646
- if (window.PCore && !this.#authHeader) {
647
- PCore.getAuthUtils().setTokens(token);
648
- }
649
- else {
650
- this.#fireTokenAvailable(token, bLoadC11N);
651
- }
652
- }
653
- #doCustomTokenParamsCB() {
654
- if (this.#authConfig.grantType === 'customBearer' && this.#customTokenParamsCB) {
655
- try {
656
- const customTokenParams = this.#customTokenParamsCB();
657
- if (customTokenParams) {
658
- this.#authConfig.customTokenParams = customTokenParams;
659
- }
660
- }
661
- catch (e) {
662
- // eslint-disable-next-line no-console
663
- console.error(`Error on customTokenParams callback. ${e}`);
664
- }
665
- }
666
- }
667
216
  updateRedirectUri(sRedirectUri) {
668
- this.#authConfig.redirectUri = sRedirectUri;
217
+ __classPrivateFieldGet(this, _AuthManager_authConfig, "f").redirectUri = sRedirectUri;
669
218
  }
670
219
  /**
671
220
  * Get available portals which supports SDK
@@ -681,9 +230,9 @@ class AuthManager {
681
230
  const appAlias = serverConfig.appAlias;
682
231
  const appAliasPath = appAlias ? `/app/${appAlias}` : '';
683
232
  const arExcludedPortals = serverConfig.excludePortals;
684
- const additionalHeaders = this.#loginProps.additionalHeaders || {};
685
- const oHeaders = this.#authHeader
686
- ? { Authorization: this.#authHeader, ...additionalHeaders }
233
+ const additionalHeaders = __classPrivateFieldGet(this, _AuthManager_loginProps, "f").additionalHeaders || {};
234
+ const oHeaders = __classPrivateFieldGet(this, _AuthManager_authHeader, "f")
235
+ ? { Authorization: __classPrivateFieldGet(this, _AuthManager_authHeader, "f"), ...additionalHeaders }
687
236
  : additionalHeaders;
688
237
  const headers = {
689
238
  'Content-Type': 'application/json',
@@ -694,7 +243,7 @@ class AuthManager {
694
243
  return fetch(`${serverUrl}${appAliasPath}/api/v1/data/${dataPageName}`, {
695
244
  method: 'GET',
696
245
  headers,
697
- credentials: this.#authConfig.secureCookie ? 'include' : 'omit'
246
+ credentials: __classPrivateFieldGet(this, _AuthManager_authConfig, "f").secureCookie ? 'include' : 'omit'
698
247
  })
699
248
  .then(response => {
700
249
  if (response.ok && response.status === 200) {
@@ -735,66 +284,27 @@ class AuthManager {
735
284
  });
736
285
  });
737
286
  }
738
- #updateLoginStatus() {
739
- if (!this.#authHeader && this.#tokenInfo?.access_token) {
740
- // Use setter to set this securely
741
- this.authHeader = `${this.#tokenInfo.token_type} ${this.#tokenInfo.access_token}`;
742
- }
743
- this.isLoggedIn =
744
- !!(this.#authHeader && this.#authHeader.length > 0) ||
745
- (this.#authConfig.secureCookie && Object.keys(this.#tokenInfo || {}).length > 0);
746
- }
747
- // Initiate a full OAuth re-authorization (any refresh token has also expired).
748
- #authFullReauth() {
749
- const bHandleHere = true; // Other alternative is to raise an event and have someone else handle it
750
- if (this.reauthStart) {
751
- const reauthIgnoreInterval = 300000; // 5 minutes
752
- const currTime = Date.now();
753
- const bReauthInProgress = currTime - this.reauthStart <= reauthIgnoreInterval;
754
- if (bReauthInProgress) {
755
- return;
756
- }
757
- }
758
- if (bHandleHere) {
759
- // Don't want to do a full clear of authMgr as will loose state props (like sessionIndex). Rather just clear the tokens
760
- this.clear(true);
761
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
762
- login(true);
763
- }
764
- else {
765
- // Fire the SdkFullReauth event to indicate a new token is needed (PCore.getAuthUtils.setTokens method
766
- // should be used to communicate the new token to Constellation JS Engine.
767
- const event = new CustomEvent('SdkFullReauth', {
768
- detail: this.#processTokenOnLogin.bind(this)
769
- });
770
- document.dispatchEvent(event);
771
- }
772
- }
773
- // Passive update where just session storage is updated so can be used on a window refresh
774
- #authTokenUpdated(tokenInfo) {
775
- this.#tokenInfo = tokenInfo;
776
- }
777
287
  // TODO: Cope with 401 and refresh token if possible (or just hope that it succeeds during login)
778
288
  /**
779
289
  * Retrieve UserInfo for current authentication service
780
290
  */
781
291
  getUserInfo() {
782
- if (this.#userInfo) {
783
- return this.#userInfo;
292
+ if (__classPrivateFieldGet(this, _AuthManager_userInfo, "f")) {
293
+ return __classPrivateFieldGet(this, _AuthManager_userInfo, "f");
784
294
  }
785
- return this.#initialize(false).then(aMgr => {
786
- return aMgr.getUserinfo(this.#tokenInfo.access_token).then(data => {
787
- this.#userInfo = data;
788
- return this.#userInfo;
295
+ return __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_initialize).call(this, false).then(aMgr => {
296
+ return aMgr.getUserinfo(__classPrivateFieldGet(this, _AuthManager_tokenInfo, "f").access_token).then(data => {
297
+ __classPrivateFieldSet(this, _AuthManager_userInfo, data, "f");
298
+ return __classPrivateFieldGet(this, _AuthManager_userInfo, "f");
789
299
  });
790
300
  });
791
301
  }
792
302
  login(bFullReauth = false) {
793
303
  if (this.bCustomAuth)
794
304
  return;
795
- this.#initialize(!bFullReauth).then(aMgr => {
305
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_initialize).call(this, !bFullReauth).then(aMgr => {
796
306
  const sdkConfigAuth = SdkConfigAccess.getSdkConfigAuth();
797
- if (this.#authConfig.grantType === 'authCode') {
307
+ if (__classPrivateFieldGet(this, _AuthManager_authConfig, "f").grantType === 'authCode') {
798
308
  const bMainRedirect = !this.noInitialRedirect;
799
309
  let sRedirectUri = sdkConfigAuth.redirectUri;
800
310
  // If initial main redirect is OK, redirect to main page, otherwise will authorize in a popup window
@@ -815,12 +325,12 @@ class AuthManager {
815
325
  this.updateRedirectUri(sRedirectUri);
816
326
  }
817
327
  return new Promise((resolve, reject) => {
818
- this.#doCustomTokenParamsCB();
328
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_doCustomTokenParamsCB).call(this);
819
329
  aMgr
820
330
  .login()
821
331
  .then(token => {
822
- this.#processTokenOnLogin(token);
823
- if (this.#loadUserinfo) {
332
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_processTokenOnLogin).call(this, token);
333
+ if (__classPrivateFieldGet(this, _AuthManager_loadUserinfo, "f")) {
824
334
  this.getUserInfo();
825
335
  }
826
336
  resolve(token.access_token);
@@ -841,17 +351,17 @@ class AuthManager {
841
351
  const state = urlParams.get('state');
842
352
  // If state should also match before accepting code
843
353
  if (code) {
844
- this.#initialize(false).then(aMgr => {
354
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_initialize).call(this, false).then(aMgr => {
845
355
  if (aMgr.checkStateMatch(state)) {
846
356
  aMgr.getToken(code).then(token => {
847
357
  // Remove any altStateStorage
848
- if (this.#loginProps?.altStateStorage) {
849
- window.localStorage.removeItem(this.#ssKeySessionInfo);
850
- window.localStorage.removeItem(this.#ssKeyState);
358
+ if (__classPrivateFieldGet(this, _AuthManager_loginProps, "f")?.altStateStorage) {
359
+ window.localStorage.removeItem(__classPrivateFieldGet(this, _AuthManager_ssKeySessionInfo, "f"));
360
+ window.localStorage.removeItem(__classPrivateFieldGet(this, _AuthManager_ssKeyState, "f"));
851
361
  }
852
362
  if (token && token.token_type) {
853
- this.#processTokenOnLogin(token, false);
854
- if (this.#loadUserinfo) {
363
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_processTokenOnLogin).call(this, token, false);
364
+ if (__classPrivateFieldGet(this, _AuthManager_loadUserinfo, "f")) {
855
365
  this.getUserInfo();
856
366
  }
857
367
  if (fnLoggedInCB) {
@@ -877,14 +387,14 @@ class AuthManager {
877
387
  }
878
388
  loginIfNecessary(loginProps) {
879
389
  const { appName, deferLogin, redirectDoneCB, locale } = loginProps;
880
- this.#loginProps = { ...loginProps };
390
+ __classPrivateFieldSet(this, _AuthManager_loginProps, { ...loginProps }, "f");
881
391
  const noMainRedirect = !loginProps.mainRedirect;
882
392
  // We need to load state before making any decisions. If appName is not there
883
393
  // and this is not the first time load...suspect something is wrong and we need to reload
884
394
  if (Object.keys(this.state).length <= this.stateKeysCount || !this.appName) {
885
395
  // Once appName is defined it should exceed this count. If not there should be no
886
396
  // harm trying once more
887
- this.#loadState();
397
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_loadState).call(this);
888
398
  }
889
399
  // If no initial redirect status of page changed...clear AuthMgr
890
400
  const currNoMainRedirect = this.noInitialRedirect;
@@ -903,9 +413,9 @@ class AuthManager {
903
413
  }
904
414
  // If custom auth no need to do any OAuth logic
905
415
  if (this.bCustomAuth) {
906
- this.#updateLoginStatus();
416
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_updateLoginStatus).call(this);
907
417
  if (!window.PCore) {
908
- this.#customConstellationInit(() => {
418
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_customConstellationInit).call(this, () => {
909
419
  // Fire the SdkCustomReauth event to indicate a new authHeader is needed. Event listener should invoke sdkSetAuthHeader
910
420
  // to communicate the new token to sdk (and Constellation JS Engine)
911
421
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
@@ -934,7 +444,7 @@ class AuthManager {
934
444
  window.location.replace(window.location.pathname);
935
445
  };
936
446
  // INC-B43979 had strange case where sessionStorage was empty after redirects
937
- if (!this.state.sfx && !this.#loginProps?.altStateStorage) {
447
+ if (!this.state.sfx && !__classPrivateFieldGet(this, _AuthManager_loginProps, "f")?.altStateStorage) {
938
448
  // Reload the page to trigger another login. Invoking login method here instead didn't
939
449
  // resolve the issue in client environment.
940
450
  this.clear();
@@ -943,11 +453,11 @@ class AuthManager {
943
453
  return this.authRedirectCallback(window.location.href, redirectDoneCB || cbDefault);
944
454
  }
945
455
  if (!deferLogin) {
946
- return this.#initialize(false).then(() => {
947
- this.#updateLoginStatus();
456
+ return __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_initialize).call(this, false).then(() => {
457
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_updateLoginStatus).call(this);
948
458
  if (this.isLoggedIn) {
949
- this.#fireTokenAvailable(this.#tokenInfo);
950
- if (this.#loadUserinfo) {
459
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_fireTokenAvailable).call(this, __classPrivateFieldGet(this, _AuthManager_tokenInfo, "f"));
460
+ if (__classPrivateFieldGet(this, _AuthManager_loadUserinfo, "f")) {
951
461
  this.getUserInfo();
952
462
  }
953
463
  }
@@ -958,10 +468,10 @@ class AuthManager {
958
468
  }
959
469
  }
960
470
  logout() {
961
- if (this.#beforeUnloadAdded) {
962
- window.removeEventListener('beforeunload', this.#doBeforeUnload.bind(this));
963
- window.removeEventListener('pagehide', this.#doPageHide.bind(this));
964
- this.#beforeUnloadAdded = false;
471
+ if (__classPrivateFieldGet(this, _AuthManager_beforeUnloadAdded, "f")) {
472
+ window.removeEventListener('beforeunload', __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_doBeforeUnload).bind(this));
473
+ window.removeEventListener('pagehide', __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_doPageHide).bind(this));
474
+ __classPrivateFieldSet(this, _AuthManager_beforeUnloadAdded, false, "f");
965
475
  }
966
476
  return new Promise(resolve => {
967
477
  const fnClearAndResolve = () => {
@@ -975,8 +485,8 @@ class AuthManager {
975
485
  return;
976
486
  }
977
487
  // For secure cookie there will not be an access_token so just check for token_type
978
- if (this.#tokenInfo && this.#tokenInfo.token_type) {
979
- if (window.PCore && !this.#bOAuthCustom) {
488
+ if (__classPrivateFieldGet(this, _AuthManager_tokenInfo, "f") && __classPrivateFieldGet(this, _AuthManager_tokenInfo, "f").token_type) {
489
+ if (window.PCore && !__classPrivateFieldGet(this, _AuthManager_bOAuthCustom, "f")) {
980
490
  window.PCore.getAuthUtils()
981
491
  .revokeTokens()
982
492
  .catch(err => {
@@ -988,11 +498,11 @@ class AuthManager {
988
498
  });
989
499
  }
990
500
  else {
991
- this.#initialize(false).then(aMgr => {
501
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_initialize).call(this, false).then(aMgr => {
992
502
  aMgr
993
- .revokeTokens(this.#authConfig.secureCookie ? 'cookie' : this.#tokenInfo.access_token, this.#authConfig.secureCookie && this.#tokenInfo.is_refresh_token_enabled
503
+ .revokeTokens(__classPrivateFieldGet(this, _AuthManager_authConfig, "f").secureCookie ? 'cookie' : __classPrivateFieldGet(this, _AuthManager_tokenInfo, "f").access_token, __classPrivateFieldGet(this, _AuthManager_authConfig, "f").secureCookie && __classPrivateFieldGet(this, _AuthManager_tokenInfo, "f").is_refresh_token_enabled
994
504
  ? 'cookie'
995
- : this.#tokenInfo.refresh_token)
505
+ : __classPrivateFieldGet(this, _AuthManager_tokenInfo, "f").refresh_token)
996
506
  .then(() => {
997
507
  // Go to finally
998
508
  })
@@ -1008,6 +518,515 @@ class AuthManager {
1008
518
  });
1009
519
  }
1010
520
  }
521
+ _AuthManager_ssKeyPrefix = new WeakMap(), _AuthManager_pegaAuth = new WeakMap(), _AuthManager_ssKeyConfigInfo = new WeakMap(), _AuthManager_ssKeySessionInfo = new WeakMap(), _AuthManager_ssKeyTokenInfo = new WeakMap(), _AuthManager_ssKeyState = new WeakMap(), _AuthManager_authConfig = new WeakMap(), _AuthManager_authDynState = new WeakMap(), _AuthManager_authHeader = new WeakMap(), _AuthManager_customTokenParamsCB = new WeakMap(), _AuthManager_bOAuthCustom = new WeakMap(), _AuthManager_tokenInfo = new WeakMap(), _AuthManager_userInfo = new WeakMap(), _AuthManager_usePASS = new WeakMap(), _AuthManager_beforeUnloadAdded = new WeakMap(), _AuthManager_tokenStorage = new WeakMap(), _AuthManager_transform = new WeakMap(), _AuthManager_foldSpot = new WeakMap(), _AuthManager_loadUserinfo = new WeakMap(), _AuthManager_loginProps = new WeakMap(), _AuthManager_promiseInitialize = new WeakMap(), _AuthManager_instances = new WeakSet(), _AuthManager_transformAndParse = function _AuthManager_transformAndParse(ssKey, ssItem, bForce = false) {
522
+ let obj = {};
523
+ try {
524
+ obj = JSON.parse(__classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_transformer).call(this, ssKey, ssItem, false, bForce));
525
+ }
526
+ catch (e) {
527
+ // fall thru and return empty object
528
+ }
529
+ return obj;
530
+ }, _AuthManager_getStorage = function _AuthManager_getStorage(ssKey, sAttrib = null) {
531
+ let ssItem = ssKey ? window.sessionStorage.getItem(ssKey) : null;
532
+ let obj = {};
533
+ if (__classPrivateFieldGet(this, _AuthManager_loginProps, "f")?.altStateStorage &&
534
+ !this.isLoggedIn &&
535
+ !ssItem &&
536
+ (ssKey === __classPrivateFieldGet(this, _AuthManager_ssKeyState, "f") || ssKey === __classPrivateFieldGet(this, _AuthManager_ssKeySessionInfo, "f"))) {
537
+ ssItem = window.localStorage.getItem(ssKey);
538
+ }
539
+ if (ssItem) {
540
+ try {
541
+ obj = JSON.parse(ssItem);
542
+ }
543
+ catch (e) {
544
+ obj = __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_transformAndParse).call(this, ssKey, ssItem, true);
545
+ }
546
+ }
547
+ return sAttrib ? obj[sAttrib] : obj;
548
+ }, _AuthManager_setStorage = function _AuthManager_setStorage(ssKey, obj, bVerify = false) {
549
+ try {
550
+ // Set storage only if obj is not empty, else delete the storage
551
+ if (!obj || isEmptyObject(obj)) {
552
+ window.sessionStorage.removeItem(ssKey);
553
+ }
554
+ else {
555
+ // const bClear = (ssKey === this.#ssKeyState || ssKey === this.#ssKeySessionInfo);
556
+ const bClear = false;
557
+ const sValue = bClear
558
+ ? JSON.stringify(obj)
559
+ : __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_transformer).call(this, ssKey, JSON.stringify(obj), true);
560
+ window.sessionStorage.setItem(ssKey, sValue);
561
+ if (bVerify) {
562
+ const sStored = window.sessionStorage.getItem(ssKey);
563
+ if (sStored !== sValue) {
564
+ // eslint-disable-next-line no-console
565
+ console.error(`Failed to properly write sessionStorage (${ssKey})`);
566
+ }
567
+ }
568
+ if (__classPrivateFieldGet(this, _AuthManager_loginProps, "f")?.altStateStorage &&
569
+ !this.isLoggedIn &&
570
+ (ssKey === __classPrivateFieldGet(this, _AuthManager_ssKeyState, "f") || ssKey === __classPrivateFieldGet(this, _AuthManager_ssKeySessionInfo, "f"))) {
571
+ window.localStorage.setItem(ssKey, sValue);
572
+ }
573
+ }
574
+ }
575
+ catch (e) {
576
+ // eslint-disable-next-line no-console
577
+ console.error(`Exception ${e} on attempted write of sessionStorage (${ssKey})`);
578
+ }
579
+ }, _AuthManager_calcFoldSpot = function _AuthManager_calcFoldSpot(s) {
580
+ const nOffset = 1;
581
+ const sChar = s.length > nOffset ? s.charAt(nOffset) : '2';
582
+ const nSpot = parseInt(sChar, 10);
583
+ __classPrivateFieldSet(this, _AuthManager_foldSpot, Number.isNaN(nSpot) ? 2 : (nSpot % 4) + 2, "f");
584
+ }, _AuthManager_transformer = function _AuthManager_transformer(ssKey, s, bIn, bForce = false) {
585
+ const bTransform = bForce || __classPrivateFieldGet(this, _AuthManager_transform, "f");
586
+ const fnFold = (x) => {
587
+ const nLen = x.length;
588
+ const nExtra = nLen % __classPrivateFieldGet(this, _AuthManager_foldSpot, "f");
589
+ const nOffset = Math.floor(nLen / __classPrivateFieldGet(this, _AuthManager_foldSpot, "f")) + nExtra;
590
+ const nRem = x.length - nOffset;
591
+ return x.substring(bIn ? nOffset : nRem) + x.substring(0, bIn ? nOffset : nRem);
592
+ };
593
+ const bTknInfo = ssKey === __classPrivateFieldGet(this, _AuthManager_ssKeyTokenInfo, "f");
594
+ if (bTknInfo && !bIn && bTransform) {
595
+ s = window.atob(fnFold(s));
596
+ }
597
+ // eslint-disable-next-line no-nested-ternary
598
+ let result = bTransform ? (bIn ? window.btoa(s) : window.atob(s)) : s;
599
+ if (bTknInfo && bIn && bTransform) {
600
+ result = fnFold(window.btoa(result));
601
+ }
602
+ return result;
603
+ }, _AuthManager_doUnloadUpdates = function _AuthManager_doUnloadUpdates() {
604
+ // Safari and particularly Safari on mobile devices doesn't seem to load this on first main redirect or
605
+ // reliably, so have moved to having PegaAuth manage writing all state props to session storage
606
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyState, "f"), this.state);
607
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeySessionInfo, "f"), __classPrivateFieldGet(this, _AuthManager_authDynState, "f"));
608
+ // If tokenStorage was always, token would already be there
609
+ if (__classPrivateFieldGet(this, _AuthManager_tokenStorage, "f") === 'temp') {
610
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyTokenInfo, "f"), __classPrivateFieldGet(this, _AuthManager_tokenInfo, "f"));
611
+ }
612
+ }, _AuthManager_doBeforeUnload = function _AuthManager_doBeforeUnload() {
613
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_doUnloadUpdates).call(this);
614
+ }, _AuthManager_doPageHide = function _AuthManager_doPageHide() {
615
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_doUnloadUpdates).call(this);
616
+ }, _AuthManager_loadState = function _AuthManager_loadState() {
617
+ // Note: State storage key doesn't have a client id associated with it
618
+ const oState = __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_getStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyState, "f"));
619
+ if (oState) {
620
+ Object.assign(this.state, oState);
621
+ if (this.state.sfx) {
622
+ // Setter sets up the ssKey values as well
623
+ this.keySuffix = this.state.sfx;
624
+ }
625
+ }
626
+ }, _AuthManager_doOnLoad = function _AuthManager_doOnLoad() {
627
+ if (!this.onLoadDone) {
628
+ // This authConfig state doesn't collide with other calculated static state...so load it first
629
+ // Note: transform setting will have already been loaded into #authConfig at this point
630
+ __classPrivateFieldSet(this, _AuthManager_authDynState, __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_getStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeySessionInfo, "f")), "f");
631
+ __classPrivateFieldSet(this, _AuthManager_tokenInfo, __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_getStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyTokenInfo, "f")), "f");
632
+ if (__classPrivateFieldGet(this, _AuthManager_tokenStorage, "f") !== 'always') {
633
+ sessionStorage.removeItem(__classPrivateFieldGet(this, _AuthManager_ssKeyTokenInfo, "f"));
634
+ // Finding on iOS browsers the pageHide event is sometimes not happening causing failed redirects.
635
+ if (!this.iOSDevice) {
636
+ sessionStorage.removeItem(__classPrivateFieldGet(this, _AuthManager_ssKeySessionInfo, "f"));
637
+ }
638
+ }
639
+ this.onLoadDone = true;
640
+ }
641
+ }, _AuthManager_doAuthDynStateChanged = function _AuthManager_doAuthDynStateChanged() {
642
+ // If tokenStorage is setup for always then always persist the auth dynamic state as well
643
+ if (__classPrivateFieldGet(this, _AuthManager_tokenStorage, "f") === 'always' || this.iOSDevice) {
644
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeySessionInfo, "f"), __classPrivateFieldGet(this, _AuthManager_authDynState, "f"));
645
+ }
646
+ }, _AuthManager_initialize =
647
+ /**
648
+ * Initialize OAuth config structure members and create authMgr instance (if necessary)
649
+ * bNew - governs whether to create new sessionStorage or load existing one
650
+ */
651
+ async function _AuthManager_initialize(bNew = false) {
652
+ if (!bNew && __classPrivateFieldGet(this, _AuthManager_promiseInitialize, "f")) {
653
+ return __classPrivateFieldGet(this, _AuthManager_promiseInitialize, "f");
654
+ }
655
+ __classPrivateFieldSet(this, _AuthManager_promiseInitialize, new Promise(resolve => {
656
+ /* if (!this.initInProgress && (bNew || isEmptyObject(this.#authConfig) || !this.#pegaAuth)) { */
657
+ this.initInProgress = true;
658
+ getSdkConfig().then(sdkConfig => {
659
+ const sdkConfigAuth = sdkConfig.authConfig;
660
+ const sdkConfigServer = sdkConfig.serverConfig;
661
+ const serverType = sdkConfigServer.serverType || 'infinity';
662
+ const bInfinity = serverType === 'infinity';
663
+ let pegaUrl = bInfinity
664
+ ? sdkConfigServer.infinityRestServerUrl
665
+ : sdkConfigServer.launchpadRestServerUrl;
666
+ // Expecting boolean true/false or undefined
667
+ const secureCookie = !!sdkConfigAuth.secureCookie;
668
+ const bNoInitialRedirect = this.noInitialRedirect;
669
+ const appAliasSeg = sdkConfigServer.appAlias ? `app/${sdkConfigServer.appAlias}/` : '';
670
+ // Construct default OAuth endpoints (if not explicitly specified)
671
+ if (pegaUrl) {
672
+ // Cope with trailing slash being present
673
+ if (!pegaUrl.endsWith('/')) {
674
+ pegaUrl += '/';
675
+ }
676
+ if (!sdkConfigAuth.authorize) {
677
+ sdkConfigAuth.authorize = bInfinity
678
+ ? `${pegaUrl}PRRestService/oauth2/v1/authorize`
679
+ : `${pegaUrl}uas/oauth/authorize`;
680
+ }
681
+ const infinityOAuth2Url = bInfinity
682
+ ? pegaUrl + (secureCookie && appAliasSeg ? `${appAliasSeg}api/` : 'PRRestService/')
683
+ : '';
684
+ if (!sdkConfigAuth.token) {
685
+ sdkConfigAuth.token = bInfinity
686
+ ? `${infinityOAuth2Url}oauth2/v1/token`
687
+ : `${pegaUrl}uas/oauth/token`;
688
+ }
689
+ if (!sdkConfigAuth.revoke) {
690
+ // Launchpad still does not have a revoke endpoint
691
+ sdkConfigAuth.revoke = bInfinity ? `${infinityOAuth2Url}oauth2/v1/revoke` : '';
692
+ }
693
+ if (!sdkConfigAuth.redirectUri) {
694
+ sdkConfigAuth.redirectUri = `${window.location.origin}${window.location.pathname}`;
695
+ }
696
+ if (!sdkConfigAuth.userinfo) {
697
+ sdkConfigAuth.userinfo = bInfinity
698
+ ? `${pegaUrl}${appAliasSeg}api/oauthclients/v1/userinfo/JSON`
699
+ : '';
700
+ }
701
+ }
702
+ // Auth service alias
703
+ if (!sdkConfigAuth.authService) {
704
+ sdkConfigAuth.authService = 'pega';
705
+ }
706
+ // mashupAuthService provides way to have a different auth service for embedded
707
+ if (!sdkConfigAuth.mashupAuthService) {
708
+ sdkConfigAuth.mashupAuthService = sdkConfigAuth.authService;
709
+ }
710
+ // Construct path to auth.html (used for case when not doing a main window redirect)
711
+ let sNoMainRedirectUri = sdkConfigAuth.redirectUri;
712
+ const nLastPathSep = sNoMainRedirectUri.lastIndexOf('/');
713
+ sNoMainRedirectUri =
714
+ nLastPathSep !== -1
715
+ ? `${sNoMainRedirectUri.substring(0, nLastPathSep + 1)}auth.html`
716
+ : `${sNoMainRedirectUri}/auth.html`;
717
+ const portalGrantType = sdkConfigAuth.portalGrantType || 'authCode';
718
+ const mashupGrantType = sdkConfigAuth.mashupGrantType || 'authCode';
719
+ // Some grant types are only available with confidential registrations and require a client secret
720
+ const clientSecret = bNoInitialRedirect
721
+ ? sdkConfigAuth.mashupClientSecret
722
+ : sdkConfigAuth.portalClientSecret;
723
+ const pegaAuthConfig = {
724
+ serverType,
725
+ clientId: bNoInitialRedirect
726
+ ? sdkConfigAuth.mashupClientId
727
+ : sdkConfigAuth.portalClientId,
728
+ grantType: bNoInitialRedirect ? mashupGrantType : portalGrantType,
729
+ tokenUri: sdkConfigAuth.token,
730
+ revokeUri: sdkConfigAuth.revoke,
731
+ userinfoUri: sdkConfigAuth.userinfo,
732
+ authService: bNoInitialRedirect
733
+ ? sdkConfigAuth.mashupAuthService
734
+ : sdkConfigAuth.authService,
735
+ appAlias: sdkConfigServer.appAlias || '',
736
+ useLocking: true
737
+ };
738
+ if (clientSecret) {
739
+ pegaAuthConfig.clientSecret = clientSecret;
740
+ }
741
+ if (serverType === 'launchpad' && pegaAuthConfig.grantType === 'authCode') {
742
+ pegaAuthConfig.noPKCE = true;
743
+ }
744
+ // Invoke keySuffix setter
745
+ // Was using pegaAuthConfig.clientId as key but more secure to just use a random string as getting
746
+ // both a clientId and the refresh token could yield a new access token.
747
+ // Suffix is so we might in future move to an array of suffixes based on the appName, so might store
748
+ // both portal and embedded tokens/session info at same time
749
+ if (!this.state?.sfx) {
750
+ // Just using a random number to make the suffix unique on each session
751
+ this.keySuffix = `${Math.ceil(Math.random() * 100000000)}`;
752
+ }
753
+ __classPrivateFieldGet(this, _AuthManager_authConfig, "f").transform =
754
+ sdkConfigAuth.transform !== undefined ? sdkConfigAuth.transform : __classPrivateFieldGet(this, _AuthManager_transform, "f");
755
+ // Using property in class as authConfig may be empty at times
756
+ __classPrivateFieldSet(this, _AuthManager_transform, __classPrivateFieldGet(this, _AuthManager_authConfig, "f").transform, "f");
757
+ if (sdkConfigAuth.tokenStorage !== undefined) {
758
+ __classPrivateFieldSet(this, _AuthManager_tokenStorage, sdkConfigAuth.tokenStorage, "f");
759
+ }
760
+ if (sdkConfigAuth.secureCookie) {
761
+ __classPrivateFieldGet(this, _AuthManager_authConfig, "f").secureCookie = true;
762
+ }
763
+ // Get latest state once client ids, transform and tokenStorage have been established
764
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_doOnLoad).call(this);
765
+ // If no clientId is specified assume not OAuth but custom auth
766
+ if (pegaAuthConfig.grantType === 'none' || !pegaAuthConfig.clientId) {
767
+ this.bCustomAuth = true;
768
+ return;
769
+ }
770
+ // For some OAuth grant type scenarios we opt to pass the Orchestration Engine just an authHeader as
771
+ // service broker doesn't have proper support for dealing with refreshing or revoking these:
772
+ // * customBearer (except when secureCookie being used)
773
+ // * confidential grant types (ones with clientSecret)
774
+ // (With 25.1 orchestration engine does support this if client_secret is specified on bootstrap)
775
+ __classPrivateFieldSet(this, _AuthManager_bOAuthCustom, (pegaAuthConfig.grantType === 'customBearer' && !secureCookie) || clientSecret, "f");
776
+ if (pegaAuthConfig.grantType === 'authCode') {
777
+ const authCodeProps = {
778
+ authorizeUri: sdkConfigAuth.authorize,
779
+ // If we have already specified a redirect on the authorize redirect, we need to continue to use that
780
+ // on token endpoint
781
+ redirectUri: bNoInitialRedirect || this.usePopupForRestOfSession
782
+ ? sNoMainRedirectUri
783
+ : sdkConfigAuth.redirectUri
784
+ };
785
+ if ('silentTimeout' in sdkConfigAuth) {
786
+ authCodeProps.silentTimeout = sdkConfigAuth.silentTimeout;
787
+ }
788
+ if (bNoInitialRedirect &&
789
+ pegaAuthConfig.authService === 'pega' &&
790
+ sdkConfigAuth.mashupUserIdentifier &&
791
+ sdkConfigAuth.mashupPassword) {
792
+ authCodeProps.userIdentifier = sdkConfigAuth.mashupUserIdentifier;
793
+ authCodeProps.password = sdkConfigAuth.mashupPassword;
794
+ }
795
+ if ('iframeLoginUI' in sdkConfigAuth) {
796
+ authCodeProps.iframeLoginUI =
797
+ sdkConfigAuth.iframeLoginUI.toString().toLowerCase() === 'true';
798
+ }
799
+ Object.assign(pegaAuthConfig, authCodeProps);
800
+ }
801
+ else if (pegaAuthConfig.grantType === 'passwordCreds') {
802
+ pegaAuthConfig.userIdentifier = sdkConfigAuth.mashupUserIdentifier;
803
+ pegaAuthConfig.password = sdkConfigAuth.mashupPassword;
804
+ }
805
+ Object.assign(__classPrivateFieldGet(this, _AuthManager_authConfig, "f"), pegaAuthConfig);
806
+ // Add beforeunload and page hide handlers to write out key properties that we want to survive a
807
+ // browser reload
808
+ if (!__classPrivateFieldGet(this, _AuthManager_beforeUnloadAdded, "f") && (!__classPrivateFieldGet(this, _AuthManager_usePASS, "f") || __classPrivateFieldGet(this, _AuthManager_tokenStorage, "f") !== 'always')) {
809
+ window.addEventListener('beforeunload', __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_doBeforeUnload).bind(this));
810
+ window.addEventListener('pagehide', __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_doPageHide).bind(this));
811
+ __classPrivateFieldSet(this, _AuthManager_beforeUnloadAdded, true, "f");
812
+ }
813
+ // Initialize PegaAuth OAuth 2.0 client library
814
+ if (__classPrivateFieldGet(this, _AuthManager_usePASS, "f")) {
815
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyConfigInfo, "f"), __classPrivateFieldGet(this, _AuthManager_authConfig, "f"));
816
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeySessionInfo, "f"), __classPrivateFieldGet(this, _AuthManager_authDynState, "f"));
817
+ __classPrivateFieldSet(this, _AuthManager_pegaAuth, new PegaAuth(__classPrivateFieldGet(this, _AuthManager_ssKeyConfigInfo, "f"), __classPrivateFieldGet(this, _AuthManager_ssKeySessionInfo, "f")), "f");
818
+ }
819
+ else {
820
+ __classPrivateFieldGet(this, _AuthManager_authConfig, "f").fnDynStateChangedCB = __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_doAuthDynStateChanged).bind(this);
821
+ __classPrivateFieldSet(this, _AuthManager_pegaAuth, new PegaAuth(__classPrivateFieldGet(this, _AuthManager_authConfig, "f"), __classPrivateFieldGet(this, _AuthManager_authDynState, "f")), "f");
822
+ }
823
+ this.initInProgress = false;
824
+ resolve(__classPrivateFieldGet(this, _AuthManager_pegaAuth, "f"));
825
+ });
826
+ }), "f");
827
+ return __classPrivateFieldGet(this, _AuthManager_promiseInitialize, "f");
828
+ }, _AuthManager_constellationInit = function _AuthManager_constellationInit(tokenInfo, authTokenUpdated, fnReauth) {
829
+ const constellationBootConfig = {};
830
+ const sdkConfigServer = SdkConfigAccess.getSdkConfigServer();
831
+ const sdkConfigAuth = SdkConfigAccess.getSdkConfigAuth();
832
+ const authConfig = __classPrivateFieldGet(this, _AuthManager_authConfig, "f");
833
+ // Set up constellationConfig with data that bootstrapWithAuthHeader expects
834
+ constellationBootConfig.customRendering = true;
835
+ constellationBootConfig.restServerUrl = sdkConfigServer.infinityRestServerUrl;
836
+ // NOTE: Needs a trailing slash! So add one if not provided
837
+ if (!sdkConfigServer.sdkContentServerUrl.endsWith('/')) {
838
+ sdkConfigServer.sdkContentServerUrl = `${sdkConfigServer.sdkContentServerUrl}/`;
839
+ }
840
+ constellationBootConfig.staticContentServerUrl = `${sdkConfigServer.sdkContentServerUrl}constellation/`;
841
+ if (!constellationBootConfig.staticContentServerUrl.endsWith('/')) {
842
+ constellationBootConfig.staticContentServerUrl = `${constellationBootConfig.staticContentServerUrl}/`;
843
+ }
844
+ // If appAlias specified, use it
845
+ if (sdkConfigServer.appAlias) {
846
+ constellationBootConfig.appAlias = sdkConfigServer.appAlias;
847
+ }
848
+ // Determine whether to send credentials with DX API transactions
849
+ if (sdkConfigAuth.customCookies) {
850
+ constellationBootConfig.customCookies = true;
851
+ }
852
+ if (__classPrivateFieldGet(this, _AuthManager_bOAuthCustom, "f") || !tokenInfo) {
853
+ if (tokenInfo) {
854
+ __classPrivateFieldSet(this, _AuthManager_authHeader, `${tokenInfo.token_type} ${tokenInfo.access_token}`, "f");
855
+ }
856
+ if (__classPrivateFieldGet(this, _AuthManager_authHeader, "f")) {
857
+ constellationBootConfig.authorizationHeader = __classPrivateFieldGet(this, _AuthManager_authHeader, "f");
858
+ }
859
+ }
860
+ else {
861
+ // Pass in auth info to Constellation
862
+ constellationBootConfig.authInfo = {
863
+ authType: 'OAuth2.0',
864
+ tokenInfo,
865
+ // Set whether we want constellation to try to do a full re-Auth or not ()
866
+ // true doesn't seem to be working in SDK scenario so always passing false for now
867
+ popupReauth: false /* !this.noInitialRedirect */,
868
+ client_id: authConfig.clientId,
869
+ client_secret: authConfig.clientSecret,
870
+ authentication_service: authConfig.authService,
871
+ redirect_uri: authConfig.redirectUri,
872
+ endPoints: {
873
+ authorize: authConfig.authorizeUri,
874
+ token: authConfig.tokenUri,
875
+ revoke: authConfig.revokeUri
876
+ },
877
+ secureCookie: authConfig.secureCookie,
878
+ onTokenRetrieval: authTokenUpdated
879
+ };
880
+ }
881
+ // Turn off dynamic load components (should be able to do it here instead of after load?)
882
+ constellationBootConfig.dynamicLoadComponents = false;
883
+ // Set envType if appropriate
884
+ if (authConfig.serverType === 'launchpad') {
885
+ constellationBootConfig.envType = 'LAUNCHPAD';
886
+ }
887
+ // Set locale override if specified
888
+ const localeOverride = this.locale;
889
+ if (localeOverride) {
890
+ constellationBootConfig.locale = localeOverride;
891
+ }
892
+ // Set additional headers if specified
893
+ const additionalHeaders = __classPrivateFieldGet(this, _AuthManager_loginProps, "f").additionalHeaders;
894
+ if (additionalHeaders) {
895
+ constellationBootConfig.additionalHeaders = additionalHeaders;
896
+ }
897
+ if (this.bC11NBootstrapInProgress) {
898
+ return;
899
+ }
900
+ this.bC11NBootstrapInProgress = true;
901
+ // Note that staticContentServerUrl already ends with a slash (see above), so no slash added.
902
+ // In order to have this import succeed needed to use the webpackIgnore magic comment tag.
903
+ // See: https://webpack.js.org/api/module-methods/
904
+ import(
905
+ /* webpackIgnore: true */ `${constellationBootConfig.staticContentServerUrl}bootstrap-shell.js?v=${Date.now()}`).then(bootstrapShell => {
906
+ // NOTE: once this callback is done, we lose the ability to access loadMashup.
907
+ // So, create a reference to it
908
+ window.myLoadMashup = bootstrapShell.loadMashup;
909
+ window.myLoadPortal = bootstrapShell.loadPortal;
910
+ window.myLoadDefaultPortal = bootstrapShell.loadDefaultPortal;
911
+ bootstrapShell
912
+ .bootstrapWithAuthHeader(constellationBootConfig, 'pega-root')
913
+ .then(() => {
914
+ // eslint-disable-next-line no-console
915
+ console.log('ConstellationJS bootstrap successful!');
916
+ this.bC11NBootstrapInProgress = false;
917
+ // Setup listener for the reauth event
918
+ if (!__classPrivateFieldGet(this, _AuthManager_bOAuthCustom, "f") && tokenInfo) {
919
+ PCore.getPubSubUtils().subscribe(PCore.getConstants().PUB_SUB_EVENTS.EVENT_FULL_REAUTH, fnReauth, 'authFullReauth');
920
+ }
921
+ else {
922
+ // customReauth event introduced with 8.8
923
+ const sEvent = PCore.getConstants().PUB_SUB_EVENTS.EVENT_CUSTOM_REAUTH;
924
+ if (sEvent) {
925
+ PCore.getPubSubUtils().subscribe(sEvent, fnReauth, 'doReauth');
926
+ }
927
+ }
928
+ // Fire SdkConstellationReady event so bridge and app route can do expected post PCore initializations
929
+ const event = new CustomEvent('SdkConstellationReady', {});
930
+ document.dispatchEvent(event);
931
+ })
932
+ .catch(e => {
933
+ // Assume error caught is because token is not valid and attempt a full reauth
934
+ // eslint-disable-next-line no-console
935
+ console.error(`ConstellationJS bootstrap failed. ${e}`);
936
+ this.bC11NBootstrapInProgress = false;
937
+ fnReauth();
938
+ });
939
+ });
940
+ /* Ends here */
941
+ }, _AuthManager_customConstellationInit = function _AuthManager_customConstellationInit(fnReauth) {
942
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_constellationInit).call(this, null, null, fnReauth);
943
+ }, _AuthManager_fireTokenAvailable = function _AuthManager_fireTokenAvailable(token, bLoadC11N = true) {
944
+ if (!token) {
945
+ // This is used on page reload to load the token from sessionStorage and carry on
946
+ token = __classPrivateFieldGet(this, _AuthManager_tokenInfo, "f");
947
+ if (!token) {
948
+ return;
949
+ }
950
+ }
951
+ __classPrivateFieldSet(this, _AuthManager_tokenInfo, token, "f");
952
+ if (__classPrivateFieldGet(this, _AuthManager_tokenStorage, "f") === 'always') {
953
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyTokenInfo, "f"), __classPrivateFieldGet(this, _AuthManager_tokenInfo, "f"));
954
+ }
955
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_updateLoginStatus).call(this);
956
+ // this.isLoggedIn is getting updated in updateLoginStatus
957
+ this.isLoggedIn = true;
958
+ this.usePopupForRestOfSession = true;
959
+ if (!window.PCore && bLoadC11N) {
960
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_constellationInit).call(this, token, __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_authTokenUpdated).bind(this), __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_authFullReauth).bind(this));
961
+ }
962
+ /*
963
+ // Create and dispatch the SdkLoggedIn event to trigger constellationInit
964
+ const event = new CustomEvent('SdkLoggedIn', { detail: { authConfig, tokenInfo: token } });
965
+ document.dispatchEvent(event);
966
+ */
967
+ }, _AuthManager_processTokenOnLogin = function _AuthManager_processTokenOnLogin(token, bLoadC11N = true) {
968
+ __classPrivateFieldSet(this, _AuthManager_tokenInfo, token, "f");
969
+ if (__classPrivateFieldGet(this, _AuthManager_tokenStorage, "f") === 'always') {
970
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_setStorage).call(this, __classPrivateFieldGet(this, _AuthManager_ssKeyTokenInfo, "f"), __classPrivateFieldGet(this, _AuthManager_tokenInfo, "f"));
971
+ }
972
+ if (__classPrivateFieldGet(this, _AuthManager_bOAuthCustom, "f")) {
973
+ // authHeader setter will also set #authHeader and invoke getAuthUtils().setAuthorizationHeader
974
+ this.authHeader = `${token.token_type} ${token.access_token}`;
975
+ }
976
+ if (window.PCore && !__classPrivateFieldGet(this, _AuthManager_authHeader, "f")) {
977
+ PCore.getAuthUtils().setTokens(token);
978
+ }
979
+ else {
980
+ __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_fireTokenAvailable).call(this, token, bLoadC11N);
981
+ }
982
+ }, _AuthManager_doCustomTokenParamsCB = function _AuthManager_doCustomTokenParamsCB() {
983
+ if (__classPrivateFieldGet(this, _AuthManager_authConfig, "f").grantType === 'customBearer' && __classPrivateFieldGet(this, _AuthManager_customTokenParamsCB, "f")) {
984
+ try {
985
+ const customTokenParams = __classPrivateFieldGet(this, _AuthManager_customTokenParamsCB, "f").call(this);
986
+ if (customTokenParams) {
987
+ __classPrivateFieldGet(this, _AuthManager_authConfig, "f").customTokenParams = customTokenParams;
988
+ }
989
+ }
990
+ catch (e) {
991
+ // eslint-disable-next-line no-console
992
+ console.error(`Error on customTokenParams callback. ${e}`);
993
+ }
994
+ }
995
+ }, _AuthManager_updateLoginStatus = function _AuthManager_updateLoginStatus() {
996
+ if (!__classPrivateFieldGet(this, _AuthManager_authHeader, "f") && __classPrivateFieldGet(this, _AuthManager_tokenInfo, "f")?.access_token) {
997
+ // Use setter to set this securely
998
+ this.authHeader = `${__classPrivateFieldGet(this, _AuthManager_tokenInfo, "f").token_type} ${__classPrivateFieldGet(this, _AuthManager_tokenInfo, "f").access_token}`;
999
+ }
1000
+ this.isLoggedIn =
1001
+ !!(__classPrivateFieldGet(this, _AuthManager_authHeader, "f") && __classPrivateFieldGet(this, _AuthManager_authHeader, "f").length > 0) ||
1002
+ (__classPrivateFieldGet(this, _AuthManager_authConfig, "f").secureCookie && Object.keys(__classPrivateFieldGet(this, _AuthManager_tokenInfo, "f") || {}).length > 0);
1003
+ }, _AuthManager_authFullReauth = function _AuthManager_authFullReauth() {
1004
+ const bHandleHere = true; // Other alternative is to raise an event and have someone else handle it
1005
+ if (this.reauthStart) {
1006
+ const reauthIgnoreInterval = 300000; // 5 minutes
1007
+ const currTime = Date.now();
1008
+ const bReauthInProgress = currTime - this.reauthStart <= reauthIgnoreInterval;
1009
+ if (bReauthInProgress) {
1010
+ return;
1011
+ }
1012
+ }
1013
+ if (bHandleHere) {
1014
+ // Don't want to do a full clear of authMgr as will loose state props (like sessionIndex). Rather just clear the tokens
1015
+ this.clear(true);
1016
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
1017
+ login(true);
1018
+ }
1019
+ else {
1020
+ // Fire the SdkFullReauth event to indicate a new token is needed (PCore.getAuthUtils.setTokens method
1021
+ // should be used to communicate the new token to Constellation JS Engine.
1022
+ const event = new CustomEvent('SdkFullReauth', {
1023
+ detail: __classPrivateFieldGet(this, _AuthManager_instances, "m", _AuthManager_processTokenOnLogin).bind(this)
1024
+ });
1025
+ document.dispatchEvent(event);
1026
+ }
1027
+ }, _AuthManager_authTokenUpdated = function _AuthManager_authTokenUpdated(tokenInfo) {
1028
+ __classPrivateFieldSet(this, _AuthManager_tokenInfo, tokenInfo, "f");
1029
+ };
1011
1030
  const gAuthMgr = new AuthManager();
1012
1031
  // TODO: Cope with 401 and refresh token if possible (or just hope that it succeeds during login)
1013
1032
  /**