@pega/react-sdk-overrides 8.23.11-debug2 → 8.23.11-debug3
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.
- package/LICENSE +201 -0
- package/lib/helpers/auth.js +852 -415
- package/package.json +1 -1
package/lib/helpers/auth.js
CHANGED
|
@@ -1,492 +1,929 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
/* eslint-disable no-undef */
|
|
2
|
+
export class PegaAuth {
|
|
3
|
+
// The properties within config structure are expected to be more static config values that are then
|
|
4
|
+
// used to properly make various OAuth endpoint calls.
|
|
5
|
+
#config = null;
|
|
6
|
+
// Any dynamic state is stored separately in its own structure. If a sessionStorage key is passed in
|
|
7
|
+
// without a Dynamic State key.
|
|
8
|
+
#dynState = {};
|
|
9
|
+
// Current properties within dynState structure:
|
|
10
|
+
// codeVerifier, state, sessionIndex, sessionIndexAttempts, acRedirectUri, silentAuthFailed
|
|
11
|
+
|
|
12
|
+
constructor(ssKeyConfig, ssKeyDynState = '') {
|
|
13
|
+
if (typeof ssKeyConfig === 'string') {
|
|
14
|
+
this.ssKeyConfig = ssKeyConfig;
|
|
15
|
+
this.ssKeyDynState = ssKeyDynState || `${ssKeyConfig}_DS`;
|
|
16
|
+
this.#reloadConfig();
|
|
17
|
+
} else {
|
|
18
|
+
// object with config structure is passed in
|
|
19
|
+
this.#config = ssKeyConfig;
|
|
20
|
+
this.#dynState = ssKeyDynState || {};
|
|
21
|
+
}
|
|
22
|
+
this.urlencoded = 'application/x-www-form-urlencoded';
|
|
23
|
+
this.tokenError = 'Token endpoint error';
|
|
24
|
+
this.isNode = typeof window === 'undefined';
|
|
25
|
+
|
|
26
|
+
// For isNode path the below attributes are initialized on first method invocation
|
|
27
|
+
if (!this.isNode) {
|
|
28
|
+
this.crypto = window.crypto;
|
|
29
|
+
this.subtle = window.crypto.subtle;
|
|
30
|
+
}
|
|
31
|
+
if (Object.keys(this.#config).length > 0) {
|
|
32
|
+
if (!this.#config.serverType) {
|
|
33
|
+
this.#config.serverType = 'infinity';
|
|
34
|
+
}
|
|
35
|
+
} else {
|
|
36
|
+
throw new Error('invalid config settings');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
8
39
|
|
|
9
|
-
|
|
10
|
-
const
|
|
40
|
+
#reloadSS(ssKey) {
|
|
41
|
+
const sItem = window.sessionStorage.getItem(ssKey);
|
|
11
42
|
let obj = {};
|
|
12
|
-
if(
|
|
43
|
+
if (sItem) {
|
|
44
|
+
try {
|
|
45
|
+
obj = JSON.parse(sItem);
|
|
46
|
+
} catch (e) {
|
|
13
47
|
try {
|
|
14
|
-
|
|
15
|
-
} catch (
|
|
16
|
-
|
|
17
|
-
obj = JSON.parse(window.atob(peConfig));
|
|
18
|
-
} catch(e2) {
|
|
19
|
-
obj = {};
|
|
20
|
-
}
|
|
48
|
+
obj = JSON.parse(atob(sItem));
|
|
49
|
+
} catch (err) {
|
|
50
|
+
obj = {};
|
|
21
51
|
}
|
|
52
|
+
}
|
|
22
53
|
}
|
|
54
|
+
if (ssKey === this.ssKeyConfig) {
|
|
55
|
+
this.#config = sItem ? obj : {};
|
|
56
|
+
} else {
|
|
57
|
+
this.#dynState = sItem ? obj : {};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
23
60
|
|
|
24
|
-
|
|
25
|
-
|
|
61
|
+
#reloadConfig() {
|
|
62
|
+
if (this.ssKeyConfig) {
|
|
63
|
+
this.#reloadSS(this.ssKeyConfig);
|
|
64
|
+
}
|
|
65
|
+
if (this.ssKeyDynState) {
|
|
66
|
+
this.#reloadSS(this.ssKeyDynState);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
26
69
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
70
|
+
#updateConfig() {
|
|
71
|
+
// transform must occur unless it is explicitly disabled
|
|
72
|
+
const transform = this.#config.transform !== false;
|
|
73
|
+
// May not need to write out Config info all the time, but there is a scenario where a
|
|
74
|
+
// non obfuscated value is passed in and then it needs to be obfuscated
|
|
75
|
+
if (this.ssKeyConfig) {
|
|
76
|
+
const sConfig = JSON.stringify(this.#config);
|
|
77
|
+
window.sessionStorage.setItem(this.ssKeyConfig, transform ? btoa(sConfig) : sConfig);
|
|
78
|
+
}
|
|
79
|
+
if (this.ssKeyDynState) {
|
|
80
|
+
const sDynState = JSON.stringify(this.#dynState);
|
|
81
|
+
window.sessionStorage.setItem(this.ssKeyDynState, transform ? btoa(sDynState) : sDynState);
|
|
82
|
+
}
|
|
83
|
+
if (this.#config.fnDynStateChangedCB) {
|
|
84
|
+
this.#config.fnDynStateChangedCB();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
31
87
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
88
|
+
async #importSingleLib(libName, libProp, bLoadAlways = false) {
|
|
89
|
+
if (!bLoadAlways && typeof (this.isNode ? global : window)[libProp] !== 'undefined') {
|
|
90
|
+
this[libProp] = (this.isNode ? global : window)[libProp];
|
|
91
|
+
return this[libProp];
|
|
92
|
+
}
|
|
93
|
+
// Needed to explicitly make import argument a string by using template literals to fix a compile
|
|
94
|
+
// error: Critical dependency: the request of a dependency is an expression
|
|
95
|
+
return import(/* webpackIgnore: true */ `${libName}`)
|
|
96
|
+
.then((mod) => {
|
|
97
|
+
this[libProp] = mod.default;
|
|
98
|
+
})
|
|
99
|
+
.catch((e) => {
|
|
100
|
+
// eslint-disable-next-line no-console
|
|
101
|
+
console.error(`Library ${libName} failed to load. ${e}`);
|
|
102
|
+
throw e;
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async #importNodeLibs() {
|
|
107
|
+
// Also current assumption is using Node 18 or better
|
|
108
|
+
// With 18.3 there is now a native fetch (but may want to force use of node-fetch)
|
|
109
|
+
const useNodeFetch = !!this.#config.useNodeFetch;
|
|
110
|
+
|
|
111
|
+
return Promise.all([
|
|
112
|
+
this.#importSingleLib('node-fetch', 'fetch', useNodeFetch),
|
|
113
|
+
this.#importSingleLib('open', 'open'),
|
|
114
|
+
this.#importSingleLib('node:crypto', 'crypto', true),
|
|
115
|
+
this.#importSingleLib('node:https', 'https'),
|
|
116
|
+
this.#importSingleLib('node:http', 'http'),
|
|
117
|
+
this.#importSingleLib('node:fs', 'fs')
|
|
118
|
+
]).then(() => {
|
|
119
|
+
this.subtle = this.crypto?.subtle || this.crypto.webcrypto.subtle;
|
|
120
|
+
if ((typeof fetch === 'undefined' || useNodeFetch) && this.fetch) {
|
|
121
|
+
/* eslint-disable-next-line no-global-assign */
|
|
122
|
+
fetch = this.fetch;
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// For PKCE the authorize includes a code_challenge & code_challenge_method as well
|
|
128
|
+
async #buildAuthorizeUrl(state) {
|
|
129
|
+
const {
|
|
130
|
+
serverType,
|
|
131
|
+
clientId,
|
|
132
|
+
redirectUri,
|
|
133
|
+
authorizeUri,
|
|
134
|
+
userinfoUri,
|
|
135
|
+
authService,
|
|
136
|
+
appAlias,
|
|
137
|
+
userIdentifier,
|
|
138
|
+
password,
|
|
139
|
+
noPKCE,
|
|
140
|
+
isolationId
|
|
141
|
+
} = this.#config;
|
|
142
|
+
const { sessionIndex } = this.#dynState;
|
|
143
|
+
const bInfinity = serverType === 'infinity';
|
|
144
|
+
|
|
145
|
+
if (!noPKCE) {
|
|
146
|
+
// Generate random string of 64 chars for verifier. RFC 7636 says from 43-128 chars
|
|
147
|
+
const buf = new Uint8Array(64);
|
|
148
|
+
this.crypto.getRandomValues(buf);
|
|
149
|
+
this.#dynState.codeVerifier = this.#base64UrlSafeEncode(buf);
|
|
150
|
+
}
|
|
36
151
|
|
|
37
|
-
// Generate random string of 64 chars for verifier. RFC 7636 says from 43-128 chars
|
|
38
|
-
let buf = new Uint8Array(64);
|
|
39
|
-
window.crypto.getRandomValues(buf);
|
|
40
|
-
this.config.codeVerifier = this.#base64UrlSafeEncode(buf);
|
|
41
152
|
// If sessionIndex exists then increment attempts count (we will stop sending session_index after two failures)
|
|
42
|
-
|
|
43
|
-
|
|
153
|
+
// With Infinity '24 we can now properly detect a invalid_session_index error, but can't for earlier versions
|
|
154
|
+
if (sessionIndex) {
|
|
155
|
+
this.#dynState.sessionIndexAttempts += 1;
|
|
44
156
|
}
|
|
157
|
+
|
|
158
|
+
// We use state to verify that the received code is for the right authorize transaction
|
|
159
|
+
this.#dynState.state = `${state || ''}.${this.#getRandomString(32)}`;
|
|
160
|
+
|
|
161
|
+
// The same redirectUri needs to be provided to token endpoint, so save this away incase redirectUri is
|
|
162
|
+
// adjusted for next authorize
|
|
163
|
+
this.#dynState.acRedirectUri = redirectUri;
|
|
164
|
+
|
|
45
165
|
// Persist codeVerifier in session storage so it survives the redirects that are to follow
|
|
46
166
|
this.#updateConfig();
|
|
47
167
|
|
|
48
|
-
if( !state ) {
|
|
49
|
-
// Calc random state variable
|
|
50
|
-
buf = new Uint8Array(32);
|
|
51
|
-
window.crypto.getRandomValues(buf);
|
|
52
|
-
state = this.#base64UrlSafeEncode(buf);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
168
|
// Trim alias to include just the real alias piece
|
|
56
|
-
const
|
|
169
|
+
const additionalScope =
|
|
170
|
+
(userinfoUri ? '+profile' : '') + (appAlias ? `+app.alias.${appAlias.replace(/^app\//, '')}` : '');
|
|
171
|
+
const scope = bInfinity ? `openid+email${additionalScope}` : 'user_info';
|
|
57
172
|
|
|
58
173
|
// Add explicit creds if specified to try to avoid login popup
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
174
|
+
const authServiceArg = authService ? `&authentication_service=${encodeURIComponent(authService)}` : '';
|
|
175
|
+
const sessionIndexArg =
|
|
176
|
+
sessionIndex && this.#dynState.sessionIndexAttempts < 3 ? `&session_index=${sessionIndex}` : '';
|
|
177
|
+
const userIdentifierArg = userIdentifier ? `&UserIdentifier=${encodeURIComponent(userIdentifier)}` : '';
|
|
178
|
+
const passwordArg = password && userIdentifier ? `&Password=${encodeURIComponent(atob(password))}` : '';
|
|
179
|
+
const isolationIdArg = !bInfinity && isolationId ? `&isolationID=${isolationId}` : '';
|
|
180
|
+
const moreAuthArgs = bInfinity
|
|
181
|
+
? `&enable_psyncId=true&cookies=none${authServiceArg}${sessionIndexArg}${userIdentifierArg}${passwordArg}`
|
|
182
|
+
: isolationIdArg;
|
|
183
|
+
|
|
184
|
+
let pkceArgs = '';
|
|
185
|
+
if (!noPKCE) {
|
|
186
|
+
const cc = await this.#getCodeChallenge(this.#dynState.codeVerifier);
|
|
187
|
+
pkceArgs = `&code_challenge=${cc}&code_challenge_method=S256`;
|
|
188
|
+
}
|
|
189
|
+
return `${authorizeUri}?client_id=${clientId}&response_type=code&redirect_uri=${redirectUri}&scope=${scope}&state=${encodeURIComponent(
|
|
190
|
+
this.#dynState.state
|
|
191
|
+
)}${pkceArgs}${moreAuthArgs}`;
|
|
192
|
+
}
|
|
71
193
|
|
|
72
|
-
|
|
194
|
+
async login() {
|
|
195
|
+
if (this.isNode && !this.crypto) {
|
|
196
|
+
// Deferring dynamic loading of node libraries til this first method to avoid doing this in constructor
|
|
197
|
+
await this.#importNodeLibs();
|
|
198
|
+
}
|
|
199
|
+
const { grantType, noPKCE } = this.#config;
|
|
200
|
+
if (grantType && grantType !== 'authCode') {
|
|
201
|
+
return this.getToken();
|
|
202
|
+
}
|
|
203
|
+
// Make sure browser in a secure context, else PKCE will fail
|
|
204
|
+
if (!this.isNode && !noPKCE && !window.isSecureContext) {
|
|
205
|
+
throw new Error(
|
|
206
|
+
`Authorization code grant flow failed due to insecure browser context at ${window.location.origin}. Use localhost or https.`
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
return this.#authCodeStart();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// authCode login issues the authorize endpoint transaction and deals with redirects
|
|
213
|
+
async #authCodeStart() {
|
|
73
214
|
const fnGetRedirectUriOrigin = () => {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
215
|
+
const redirectUri = this.#config.redirectUri;
|
|
216
|
+
const nRootOffset = redirectUri.indexOf('//');
|
|
217
|
+
const nFirstPathOffset = nRootOffset !== -1 ? redirectUri.indexOf('/', nRootOffset + 2) : -1;
|
|
218
|
+
return nFirstPathOffset !== -1 ? redirectUri.substring(0, nFirstPathOffset) : redirectUri;
|
|
78
219
|
};
|
|
79
220
|
|
|
80
221
|
const redirectOrigin = fnGetRedirectUriOrigin();
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
222
|
+
const startState = this.isNode ? '' : btoa(window.location.origin);
|
|
223
|
+
|
|
224
|
+
return new Promise((resolve, reject) => {
|
|
225
|
+
let theUrl = null; // holds the crafted authorize url
|
|
226
|
+
|
|
227
|
+
let myWindow = null; // popup or iframe
|
|
228
|
+
let elIframe = null;
|
|
229
|
+
let elCloseBtn = null;
|
|
230
|
+
const iframeTimeout = this.#config.silentTimeout !== undefined ? this.#config.silentTimeout : 5000;
|
|
231
|
+
let bWinIframe = true;
|
|
232
|
+
let tmrAuthComplete = null;
|
|
233
|
+
let checkWindowClosed = null;
|
|
234
|
+
let bDisablePromptNone = false;
|
|
235
|
+
const myWinOnLoad = () => {
|
|
236
|
+
try {
|
|
237
|
+
if (bWinIframe) {
|
|
238
|
+
elIframe.contentWindow.postMessage({ type: 'PegaAuth' }, redirectOrigin);
|
|
239
|
+
} else {
|
|
240
|
+
myWindow.postMessage({ type: 'PegaAuth' }, redirectOrigin);
|
|
241
|
+
}
|
|
242
|
+
} catch (e) {
|
|
243
|
+
// Exception trying to postMessage on load (perhaps should console.warn)
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
const fnSetSilentAuthFailed = (bSet) => {
|
|
247
|
+
this.#dynState.silentAuthFailed = bSet;
|
|
248
|
+
this.#updateConfig();
|
|
249
|
+
};
|
|
250
|
+
/* eslint-disable prefer-promise-reject-errors */
|
|
251
|
+
const fnOpenPopup = () => {
|
|
252
|
+
if (this.#config.noPopups) {
|
|
253
|
+
return reject('no-popups');
|
|
254
|
+
}
|
|
255
|
+
// Since displaying a visible window, clear the silent auth failed flag
|
|
256
|
+
fnSetSilentAuthFailed(false);
|
|
257
|
+
myWindow = (this.isNode ? this.open : window.open)(theUrl, '_blank', 'width=700,height=500,left=200,top=100');
|
|
258
|
+
if (!myWindow) {
|
|
259
|
+
// Blocked by popup-blocker
|
|
260
|
+
return reject('blocked');
|
|
261
|
+
}
|
|
262
|
+
checkWindowClosed = setInterval(() => {
|
|
263
|
+
if (myWindow.closed) {
|
|
264
|
+
clearInterval(checkWindowClosed);
|
|
265
|
+
reject('closed');
|
|
266
|
+
}
|
|
267
|
+
}, 500);
|
|
268
|
+
if (!this.isNode) {
|
|
269
|
+
try {
|
|
270
|
+
myWindow.addEventListener('load', myWinOnLoad, true);
|
|
271
|
+
} catch (e) {
|
|
272
|
+
// Exception trying to add onload handler to opened window
|
|
273
|
+
// eslint-disable-next-line no-console
|
|
274
|
+
console.error(`Error adding event listener on popup window: ${e}`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
/* eslint-enable prefer-promise-reject-errors */
|
|
280
|
+
const fnCloseIframe = () => {
|
|
281
|
+
elIframe.parentNode.removeChild(elIframe);
|
|
282
|
+
elCloseBtn.parentNode.removeChild(elCloseBtn);
|
|
283
|
+
elIframe = null;
|
|
284
|
+
elCloseBtn = null;
|
|
285
|
+
bWinIframe = false;
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
const fnCloseAndReject = () => {
|
|
289
|
+
fnCloseIframe();
|
|
290
|
+
/* eslint-disable-next-line prefer-promise-reject-errors */
|
|
291
|
+
reject('closed');
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
const fnAuthMessageReceiver = (event) => {
|
|
295
|
+
// Check origin to make sure it is the redirect origin
|
|
296
|
+
if (event.origin !== redirectOrigin) {
|
|
297
|
+
if (event.data?.type === 'PegaAuth') {
|
|
298
|
+
// eslint-disable-next-line no-console
|
|
299
|
+
console.error(
|
|
300
|
+
`Authorization code grant flow error: Unexpected origin: ${event.origin} ... expecting: ${redirectOrigin}`
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if (!event.data || !event.data.type || event.data.type !== 'PegaAuth') return;
|
|
306
|
+
const aArgs = ['code', 'state', 'error', 'errorDesc'];
|
|
307
|
+
const aValues = [];
|
|
308
|
+
for (let i = 0; i < aArgs.length; i += 1) {
|
|
309
|
+
const arg = aArgs[i];
|
|
310
|
+
aValues[arg] = event.data[arg] ? event.data[arg].toString() : null;
|
|
311
|
+
}
|
|
312
|
+
const { code, state, error, errorDesc } = aValues;
|
|
313
|
+
if (error) {
|
|
314
|
+
// eslint-disable-next-line no-console
|
|
315
|
+
console.error(`Authorization code grant flow error (${error}): ${errorDesc}`);
|
|
316
|
+
}
|
|
317
|
+
if (code && state !== this.#dynState.state) {
|
|
318
|
+
// eslint-disable-next-line no-console
|
|
319
|
+
console.error(
|
|
320
|
+
`Authorization code transfer error: state mismatch: ${state} ... expecting: ${this.#dynState.state}`
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
if (error || (code && state === this.#dynState.state)) {
|
|
324
|
+
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
|
325
|
+
fnGetTokenAndFinish(code, error, errorDesc);
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
const fnEnableMessageReceiver = (bEnable) => {
|
|
330
|
+
if (bEnable) {
|
|
331
|
+
window.addEventListener('message', fnAuthMessageReceiver, false);
|
|
332
|
+
window.authCodeCallback = (code, state, error, errorDesc) => {
|
|
333
|
+
if (error) {
|
|
334
|
+
// eslint-disable-next-line no-console
|
|
335
|
+
console.error(`Authorization code grant flow error (${error}): ${errorDesc}`);
|
|
336
|
+
}
|
|
337
|
+
if (code && state !== this.#dynState.state) {
|
|
338
|
+
// eslint-disable-next-line no-console
|
|
339
|
+
console.error(
|
|
340
|
+
`Authorization code transfer error: state mismatch: ${state} ... expecting: ${this.#dynState.state}`
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
if (error || (code && state === this.#dynState.state)) {
|
|
344
|
+
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
|
345
|
+
fnGetTokenAndFinish(code, error, errorDesc);
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
} else {
|
|
349
|
+
window.removeEventListener('message', fnAuthMessageReceiver, false);
|
|
350
|
+
delete window.authCodeCallback;
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
const doAuthorize = () => {
|
|
355
|
+
// If there is a userIdentifier and password specified or an external SSO auth service,
|
|
356
|
+
// we can try to use this silently in an iFrame first
|
|
357
|
+
bWinIframe =
|
|
358
|
+
!this.isNode &&
|
|
359
|
+
!this.#dynState.silentAuthFailed &&
|
|
360
|
+
iframeTimeout > 0 &&
|
|
361
|
+
((!!this.#config.userIdentifier && !!this.#config.password) ||
|
|
362
|
+
this.#config.iframeLoginUI ||
|
|
363
|
+
this.#config.authService !== 'pega');
|
|
364
|
+
// Enable message receiver
|
|
365
|
+
if (!this.isNode) {
|
|
366
|
+
fnEnableMessageReceiver(true);
|
|
367
|
+
}
|
|
368
|
+
if (bWinIframe) {
|
|
369
|
+
const nFrameZLevel = 99999;
|
|
370
|
+
elIframe = document.createElement('iframe');
|
|
371
|
+
elIframe.id = `pe${this.#config.clientId}`;
|
|
372
|
+
const loginBoxWidth = 500;
|
|
373
|
+
const loginBoxHeight = 700;
|
|
374
|
+
const oStyle = elIframe.style;
|
|
375
|
+
oStyle.position = 'absolute';
|
|
376
|
+
oStyle.display = 'none';
|
|
377
|
+
oStyle.zIndex = nFrameZLevel;
|
|
378
|
+
oStyle.top = `${Math.round(Math.max(window.innerHeight - loginBoxHeight, 0) / 2)}px`;
|
|
379
|
+
oStyle.left = `${Math.round(Math.max(window.innerWidth - loginBoxWidth, 0) / 2)}px`;
|
|
380
|
+
oStyle.width = '500px';
|
|
381
|
+
oStyle.height = '700px';
|
|
382
|
+
// Add Iframe to top of document DOM to have it load
|
|
383
|
+
document.body.insertBefore(elIframe, document.body.firstChild);
|
|
384
|
+
// document.getElementsByTagName('body')[0].appendChild(elIframe);
|
|
385
|
+
elIframe.addEventListener('load', myWinOnLoad, true);
|
|
386
|
+
// Disallow iframe content attempts to navigate main window
|
|
387
|
+
elIframe.setAttribute('sandbox', 'allow-scripts allow-forms allow-same-origin');
|
|
388
|
+
// Adding prompt=none as this is standard OIDC way to communicate no UI is expected (With Infinity '23 or better, this is passed on to
|
|
389
|
+
// configured OIDC authentication services). cookies=none disables the temporary Pega-Rules cookie otherwise created on auth code
|
|
390
|
+
// grant flow. For now these two args are either both set or not set, but might have a cookies="partitioned" one day.
|
|
391
|
+
elIframe.setAttribute('src', bDisablePromptNone ? theUrl : `${theUrl}&prompt=none`);
|
|
392
|
+
|
|
393
|
+
const svgCloseBtn = `<?xml version="1.0" encoding="UTF-8"?>
|
|
394
|
+
<svg width="34px" height="34px" viewBox="0 0 34 34" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
|
395
|
+
<title>Dismiss - Black</title>
|
|
396
|
+
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
|
397
|
+
<g transform="translate(1.000000, 1.000000)">
|
|
398
|
+
<circle fill="#252C32" cx="16" cy="16" r="16"></circle>
|
|
399
|
+
<g transform="translate(9.109375, 9.214844)" fill="#FFFFFF" fill-rule="nonzero">
|
|
400
|
+
<path d="M12.7265625,0 L0,12.6210938 L1.0546875,13.5703125 L13.78125,1.0546875 L12.7265625,0 Z M13.7460938,12.5507812 L1.01953125,0 L0,1.01953125 L12.7617188,13.6054688 L13.7460938,12.5507812 Z"></path>
|
|
401
|
+
</g>
|
|
402
|
+
</g>
|
|
403
|
+
</g>
|
|
404
|
+
</svg>`;
|
|
405
|
+
const bCloseWithinFrame = false;
|
|
406
|
+
elCloseBtn = document.createElement('img');
|
|
407
|
+
elCloseBtn.onclick = fnCloseAndReject;
|
|
408
|
+
elCloseBtn.src = `data:image/svg+xml;base64,${btoa(svgCloseBtn)}`;
|
|
409
|
+
const oBtnStyle = elCloseBtn.style;
|
|
410
|
+
oBtnStyle.cursor = 'pointer';
|
|
411
|
+
// If svg doesn't set width and height might want to set oBtStyle width and height to something like '2em'
|
|
412
|
+
oBtnStyle.position = 'absolute';
|
|
413
|
+
oBtnStyle.display = 'none';
|
|
414
|
+
oBtnStyle.zIndex = nFrameZLevel + 1;
|
|
415
|
+
const nTopOffset = bCloseWithinFrame ? 5 : -10;
|
|
416
|
+
const nRightOffset = bCloseWithinFrame ? -34 : -20;
|
|
417
|
+
const nTop = Math.round(Math.max(window.innerHeight - loginBoxHeight, 0) / 2) + nTopOffset;
|
|
418
|
+
oBtnStyle.top = `${nTop}px`;
|
|
419
|
+
const nLeft = Math.round(Math.max(window.innerWidth - loginBoxWidth, 0) / 2) + loginBoxWidth + nRightOffset;
|
|
420
|
+
oBtnStyle.left = `${nLeft}px`;
|
|
421
|
+
document.body.insertBefore(elCloseBtn, document.body.firstChild);
|
|
422
|
+
// If the password was wrong, then the login screen will be in the iframe
|
|
423
|
+
// ..and with Pega without realization of US-372314 it may replace the top (main portal) window
|
|
424
|
+
// For now set a timer and if the timer expires, remove the iFrame and use same url within
|
|
425
|
+
// visible window
|
|
426
|
+
tmrAuthComplete = setTimeout(() => {
|
|
427
|
+
clearTimeout(tmrAuthComplete);
|
|
428
|
+
/*
|
|
429
|
+
// remove password from config
|
|
430
|
+
if (this.#config.password) {
|
|
431
|
+
delete this.#config.password;
|
|
432
|
+
this.#updateConfig();
|
|
433
|
+
}
|
|
434
|
+
*/
|
|
435
|
+
// Display the iframe where the redirects did not succeed (or invoke a popup window)
|
|
436
|
+
if (this.#config.iframeLoginUI) {
|
|
437
|
+
elIframe.style.display = 'block';
|
|
438
|
+
elCloseBtn.style.display = 'block';
|
|
439
|
+
} else {
|
|
140
440
|
fnCloseIframe();
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
oStyle.left=`${Math.round(Math.max(window.innerWidth-loginBoxWidth,0)/2)}px`;
|
|
159
|
-
oStyle.width='500px';
|
|
160
|
-
oStyle.height='700px';
|
|
161
|
-
// Add Iframe to top of document DOM to have it load
|
|
162
|
-
document.body.insertBefore(elIframe,document.body.firstChild);
|
|
163
|
-
// Add Iframe to DOM to have it load
|
|
164
|
-
document.getElementsByTagName('body')[0].appendChild(elIframe);
|
|
165
|
-
elIframe.addEventListener("load", myWinOnLoad, true);
|
|
166
|
-
// Disallow iframe content attempts to navigate main window
|
|
167
|
-
elIframe.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin");
|
|
168
|
-
elIframe.setAttribute('src', url);
|
|
169
|
-
|
|
170
|
-
const svgCloseBtn =
|
|
171
|
-
`<?xml version="1.0" encoding="UTF-8"?>
|
|
172
|
-
<svg width="34px" height="34px" viewBox="0 0 34 34" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
|
173
|
-
<title>Dismiss - Black</title>
|
|
174
|
-
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
|
175
|
-
<g transform="translate(1.000000, 1.000000)">
|
|
176
|
-
<circle fill="#252C32" cx="16" cy="16" r="16"></circle>
|
|
177
|
-
<g transform="translate(9.109375, 9.214844)" fill="#FFFFFF" fill-rule="nonzero">
|
|
178
|
-
<path d="M12.7265625,0 L0,12.6210938 L1.0546875,13.5703125 L13.78125,1.0546875 L12.7265625,0 Z M13.7460938,12.5507812 L1.01953125,0 L0,1.01953125 L12.7617188,13.6054688 L13.7460938,12.5507812 Z"></path>
|
|
179
|
-
</g>
|
|
180
|
-
</g>
|
|
181
|
-
</g>
|
|
182
|
-
</svg>`;
|
|
183
|
-
const bCloseWithinFrame = false;
|
|
184
|
-
elCloseBtn = document.createElement('img');
|
|
185
|
-
elCloseBtn.onclick = fnCloseAndReject;
|
|
186
|
-
// eslint-disable-next-line prefer-template
|
|
187
|
-
elCloseBtn.src = 'data:image/svg+xml;base64,' + window.btoa(svgCloseBtn);
|
|
188
|
-
const oBtnStyle = elCloseBtn.style;
|
|
189
|
-
oBtnStyle.cursor = 'pointer';
|
|
190
|
-
// If svg doesn't set width and height might want to set oBtStyle width and height to something like '2em'
|
|
191
|
-
oBtnStyle.position = 'absolute';
|
|
192
|
-
oBtnStyle.display = 'none';
|
|
193
|
-
oBtnStyle.zIndex = nFrameZLevel+1;
|
|
194
|
-
const nTopOffset = bCloseWithinFrame ? 5 : -10;
|
|
195
|
-
const nRightOffset = bCloseWithinFrame ? -34 : -20;
|
|
196
|
-
oBtnStyle.top = `${Math.round(Math.max(window.innerHeight-loginBoxHeight,0)/2)+nTopOffset}px`;
|
|
197
|
-
oBtnStyle.left = `${Math.round(Math.max(window.innerWidth-loginBoxWidth,0)/2)+loginBoxWidth+nRightOffset}px`;
|
|
198
|
-
document.body.insertBefore(elCloseBtn,document.body.firstChild);
|
|
199
|
-
// If the password was wrong, then the login screen will be in the iframe
|
|
200
|
-
// ..and with Pega without realization of US-372314 it may replace the top (main portal) window
|
|
201
|
-
// For now set a timer and if the timer expires, remove the iFrame and use same url within
|
|
202
|
-
// visible window
|
|
203
|
-
tmrAuthComplete = setTimeout( () => {
|
|
204
|
-
clearTimeout(tmrAuthComplete);
|
|
205
|
-
// remove password from config
|
|
206
|
-
if( this.config.password ) {
|
|
207
|
-
delete this.config.password;
|
|
208
|
-
this.#updateConfig();
|
|
441
|
+
fnOpenPopup();
|
|
442
|
+
}
|
|
443
|
+
}, iframeTimeout);
|
|
444
|
+
} else {
|
|
445
|
+
if (this.isNode) {
|
|
446
|
+
// Determine port to listen to by extracting it from redirect uri
|
|
447
|
+
const { redirectUri, cert, key } = this.#config;
|
|
448
|
+
const isHttp = redirectUri.startsWith('http:');
|
|
449
|
+
const nLocalhost = redirectUri.indexOf('localhost:');
|
|
450
|
+
const nSlash = redirectUri.indexOf('/', nLocalhost + 10);
|
|
451
|
+
const nPort = parseInt(redirectUri.substring(nLocalhost + 10, nSlash), 10);
|
|
452
|
+
if (nLocalhost !== -1) {
|
|
453
|
+
const options =
|
|
454
|
+
key && cert && !isHttp
|
|
455
|
+
? {
|
|
456
|
+
key: this.fs.readFileSync(key),
|
|
457
|
+
cert: this.fs.readFileSync(cert)
|
|
209
458
|
}
|
|
459
|
+
: {};
|
|
460
|
+
const server = (isHttp ? this.http : this.https).createServer(options, (req, res) => {
|
|
461
|
+
const { winTitle, winBodyHtml } = this.#config;
|
|
462
|
+
res.writeHead(200, { 'Content-Type': 'text/html' });
|
|
463
|
+
// Auto closing window for now. Can always leave it up and allow authConfig props to set title and bodyHtml
|
|
464
|
+
res.end(
|
|
465
|
+
`<html><head><title>${winTitle}</title><script>window.close();</script></head><body>${winBodyHtml}</body></html>`
|
|
466
|
+
);
|
|
467
|
+
const queryString = req.url.split('?')[1];
|
|
468
|
+
const urlParams = new URLSearchParams(queryString);
|
|
469
|
+
const code = urlParams.get('code');
|
|
470
|
+
const state = urlParams.get('state');
|
|
471
|
+
const error = urlParams.get('error');
|
|
472
|
+
const errorDesc = urlParams.get('error_description');
|
|
473
|
+
if (error || (code && state === this.#dynState.state)) {
|
|
474
|
+
// Stop receiving connections and close when all are handled.
|
|
475
|
+
server.close();
|
|
476
|
+
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
|
477
|
+
fnGetTokenAndFinish(code, error, errorDesc);
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
server.listen(nPort);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
fnOpenPopup();
|
|
484
|
+
}
|
|
485
|
+
};
|
|
210
486
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
487
|
+
/* Retrieve token(s) and close login window */
|
|
488
|
+
const fnGetTokenAndFinish = (code, error, errorDesc) => {
|
|
489
|
+
// Can clear state in session info at this point
|
|
490
|
+
delete this.#dynState.state;
|
|
491
|
+
this.#updateConfig();
|
|
492
|
+
|
|
493
|
+
if (!this.isNode) {
|
|
494
|
+
fnEnableMessageReceiver(false);
|
|
495
|
+
if (bWinIframe) {
|
|
496
|
+
clearTimeout(tmrAuthComplete);
|
|
497
|
+
fnCloseIframe();
|
|
498
|
+
} else {
|
|
499
|
+
clearInterval(checkWindowClosed);
|
|
500
|
+
try {
|
|
501
|
+
if (myWindow) {
|
|
502
|
+
myWindow.close();
|
|
503
|
+
myWindow = null;
|
|
504
|
+
}
|
|
505
|
+
} catch (e) {
|
|
506
|
+
// keep going and process code or error even though issue closing popup
|
|
507
|
+
// eslint-disable-next-line no-console
|
|
508
|
+
console.warn(`Error closing window: ${e}`);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
if (code) {
|
|
513
|
+
this.getToken(code)
|
|
514
|
+
.then((token) => {
|
|
515
|
+
resolve(token);
|
|
516
|
+
})
|
|
517
|
+
.catch((e) => {
|
|
518
|
+
reject(e);
|
|
519
|
+
});
|
|
520
|
+
} else if (error) {
|
|
521
|
+
// Handle some errors in a special manner and pass others back to client
|
|
522
|
+
if (error === 'login_required') {
|
|
523
|
+
// eslint-disable-next-line no-console
|
|
524
|
+
console.warn('silent authentication failed...starting full authentication');
|
|
525
|
+
const bSpecialDebugPath = false;
|
|
526
|
+
if (bSpecialDebugPath) {
|
|
527
|
+
fnSetSilentAuthFailed(false);
|
|
528
|
+
bDisablePromptNone = true;
|
|
219
529
|
} else {
|
|
220
|
-
|
|
530
|
+
fnSetSilentAuthFailed(true);
|
|
531
|
+
bDisablePromptNone = false;
|
|
221
532
|
}
|
|
533
|
+
this.#buildAuthorizeUrl(startState).then((url) => {
|
|
534
|
+
theUrl = url;
|
|
535
|
+
doAuthorize();
|
|
536
|
+
});
|
|
537
|
+
} else if (error === 'invalid_session_index') {
|
|
538
|
+
// eslint-disable-next-line no-console
|
|
539
|
+
console.warn('auth session no longer valid...starting new session');
|
|
540
|
+
// In these scenarios, not much user can do without just starting a new session, so do that
|
|
541
|
+
this.#updateSessionIndex(null);
|
|
542
|
+
fnSetSilentAuthFailed(false);
|
|
543
|
+
this.#buildAuthorizeUrl(startState).then((url) => {
|
|
544
|
+
theUrl = url;
|
|
545
|
+
doAuthorize();
|
|
546
|
+
});
|
|
547
|
+
} else {
|
|
548
|
+
// eslint-disable-next-line no-console
|
|
549
|
+
console.warn(`Authorize failed: ${error}. ${errorDesc}\nFailing authorize url: ${theUrl}`);
|
|
550
|
+
throw new Error(error, { cause: errorDesc });
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
};
|
|
222
554
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
this.getToken(code).then(token => {
|
|
228
|
-
if( bWinIframe ) {
|
|
229
|
-
clearTimeout(tmrAuthComplete);
|
|
230
|
-
fnCloseIframe();
|
|
231
|
-
} else {
|
|
232
|
-
clearInterval(checkWindowClosed);
|
|
233
|
-
try {
|
|
234
|
-
myWindow.close();
|
|
235
|
-
} catch (e) {
|
|
236
|
-
// eslint-disable-next-line no-console
|
|
237
|
-
console.warn(`attempt to close opened window failed`);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
resolve(token);
|
|
241
|
-
})
|
|
242
|
-
.catch(e => {
|
|
243
|
-
reject(e);
|
|
244
|
-
});
|
|
245
|
-
};
|
|
246
|
-
/* Handler to receive the auth code */
|
|
247
|
-
authMessageReceiver = (event) => {
|
|
248
|
-
// Check origin to make sure it is the redirect origin
|
|
249
|
-
if( event.origin !== redirectOrigin ) {
|
|
250
|
-
// eslint-disable-next-line no-console
|
|
251
|
-
console.info(`Received event from unexpected origin: ${event.origin} (was expecting: ${redirectOrigin})`);
|
|
252
|
-
}
|
|
253
|
-
if( !event.data || !event.data.type || event.data.type !== "PegaAuth" )
|
|
254
|
-
return;
|
|
255
|
-
// eslint-disable-next-line no-console
|
|
256
|
-
console.log("authjs(login): postMessage received with code");
|
|
257
|
-
const code = event.data.code.toString();
|
|
258
|
-
fnGetTokenAndFinish(code);
|
|
259
|
-
};
|
|
260
|
-
window.addEventListener("message", authMessageReceiver, false);
|
|
261
|
-
window.authCodeCallback = (code) => {
|
|
262
|
-
// eslint-disable-next-line no-console
|
|
263
|
-
console.log("authjs(login): authCodeCallback used with code");
|
|
264
|
-
fnGetTokenAndFinish(code);
|
|
265
|
-
};
|
|
266
|
-
});
|
|
555
|
+
this.#buildAuthorizeUrl(startState).then((url) => {
|
|
556
|
+
theUrl = url;
|
|
557
|
+
doAuthorize();
|
|
558
|
+
});
|
|
267
559
|
});
|
|
268
|
-
|
|
560
|
+
}
|
|
269
561
|
|
|
270
|
-
|
|
271
|
-
|
|
562
|
+
// Login redirect
|
|
563
|
+
loginRedirect() {
|
|
272
564
|
// eslint-disable-next-line no-restricted-globals
|
|
273
565
|
const state = btoa(location.origin);
|
|
274
566
|
this.#buildAuthorizeUrl(state).then((url) => {
|
|
275
|
-
|
|
276
|
-
|
|
567
|
+
// eslint-disable-next-line no-restricted-globals
|
|
568
|
+
location.href = url;
|
|
277
569
|
});
|
|
278
|
-
|
|
570
|
+
}
|
|
279
571
|
|
|
572
|
+
// check state
|
|
573
|
+
checkStateMatch(state) {
|
|
574
|
+
return state === this.#dynState.state;
|
|
575
|
+
}
|
|
280
576
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
577
|
+
// Clear session index within config
|
|
578
|
+
#updateSessionIndex(sessionIndex) {
|
|
579
|
+
if (sessionIndex) {
|
|
580
|
+
this.#dynState.sessionIndex = sessionIndex;
|
|
581
|
+
this.#dynState.sessionIndexAttempts = 0;
|
|
582
|
+
} else if (this.#dynState.sessionIndex) {
|
|
583
|
+
delete this.#dynState.sessionIndex;
|
|
584
|
+
}
|
|
585
|
+
this.#updateConfig();
|
|
586
|
+
}
|
|
285
587
|
|
|
286
|
-
|
|
588
|
+
// For PKCE token endpoint includes code_verifier
|
|
287
589
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
590
|
+
getToken(authCode) {
|
|
591
|
+
// Reload config to pick up the previously stored codeVerifier
|
|
592
|
+
this.#reloadConfig();
|
|
593
|
+
|
|
594
|
+
const {
|
|
595
|
+
serverType,
|
|
596
|
+
isolationId,
|
|
597
|
+
clientId,
|
|
598
|
+
clientSecret,
|
|
599
|
+
tokenUri,
|
|
600
|
+
grantType,
|
|
601
|
+
customTokenParams,
|
|
602
|
+
userIdentifier,
|
|
603
|
+
password,
|
|
604
|
+
noPKCE,
|
|
605
|
+
secureCookie
|
|
606
|
+
} = this.#config;
|
|
607
|
+
|
|
608
|
+
const { sessionIndex, acRedirectUri, codeVerifier } = this.#dynState;
|
|
609
|
+
|
|
610
|
+
const bAuthCode = !grantType || grantType === 'authCode';
|
|
611
|
+
if (bAuthCode && !authCode && !this.isNode) {
|
|
612
|
+
const queryString = window.location.search;
|
|
613
|
+
const urlParams = new URLSearchParams(queryString);
|
|
614
|
+
authCode = urlParams.get('code');
|
|
615
|
+
}
|
|
292
616
|
|
|
293
617
|
const formData = new URLSearchParams();
|
|
294
|
-
formData.append(
|
|
295
|
-
if(
|
|
296
|
-
|
|
618
|
+
formData.append('client_id', clientId);
|
|
619
|
+
if (clientSecret) {
|
|
620
|
+
formData.append('client_secret', clientSecret);
|
|
621
|
+
}
|
|
622
|
+
if (secureCookie) {
|
|
623
|
+
formData.append('send_token_as_cookie', 'true');
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const fullGTName = {
|
|
627
|
+
authCode: 'authorization_code',
|
|
628
|
+
clientCreds: 'client_credentials',
|
|
629
|
+
customBearer: 'custom-bearer',
|
|
630
|
+
passwordCreds: 'password'
|
|
631
|
+
}[grantType];
|
|
632
|
+
formData.append('grant_type', fullGTName || grantType || 'authorization_code');
|
|
633
|
+
if (serverType === 'launchpad' && grantType !== 'authCode' && isolationId) {
|
|
634
|
+
formData.append('isolation_ids', isolationId);
|
|
635
|
+
}
|
|
636
|
+
if (bAuthCode) {
|
|
637
|
+
formData.append('code', authCode);
|
|
638
|
+
formData.append('redirect_uri', acRedirectUri);
|
|
639
|
+
if (!noPKCE) {
|
|
640
|
+
formData.append('code_verifier', codeVerifier);
|
|
641
|
+
}
|
|
642
|
+
} else if (sessionIndex) {
|
|
643
|
+
formData.append('session_index', sessionIndex);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
if (grantType === 'customBearer' && customTokenParams) {
|
|
647
|
+
Object.keys(customTokenParams).forEach((param) => {
|
|
648
|
+
formData.append(param, customTokenParams[param]);
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
if (grantType !== 'authCode') {
|
|
652
|
+
formData.append('enable_psyncId', 'true');
|
|
653
|
+
}
|
|
654
|
+
if (grantType === 'passwordCreds') {
|
|
655
|
+
formData.append('username', userIdentifier);
|
|
656
|
+
formData.append('password', atob(password));
|
|
297
657
|
}
|
|
298
|
-
formData.append("grant_type", "authorization_code");
|
|
299
|
-
formData.append("code", code);
|
|
300
|
-
formData.append("redirect_uri", redirectUri);
|
|
301
|
-
formData.append("code_verifier", codeVerifier);
|
|
302
658
|
|
|
303
659
|
return fetch(tokenUri, {
|
|
304
|
-
|
|
660
|
+
agent: this.#getAgent(),
|
|
661
|
+
method: 'POST',
|
|
305
662
|
headers: new Headers({
|
|
306
|
-
|
|
663
|
+
'content-type': this.urlencoded
|
|
307
664
|
}),
|
|
308
|
-
|
|
309
|
-
body: formData.toString()
|
|
665
|
+
credentials: secureCookie ? 'include' : 'omit',
|
|
666
|
+
body: formData.toString()
|
|
310
667
|
})
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
// add property to keep track of current time when the token expires
|
|
315
|
-
token.eA = Date.now() + (token.expires_in * 1000);
|
|
316
|
-
if( this.config.codeVerifier ) {
|
|
317
|
-
delete this.config.codeVerifier;
|
|
318
|
-
}
|
|
319
|
-
// If there is a session_index then move this to the peConfig structure (as used on authorize)
|
|
320
|
-
if( token.session_index ) {
|
|
321
|
-
this.config.sessionIndex = token.session_index;
|
|
668
|
+
.then((response) => {
|
|
669
|
+
if (response.ok) {
|
|
670
|
+
return response.json();
|
|
322
671
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
672
|
+
throw Error(`${this.tokenError}.`, { cause: response.status });
|
|
673
|
+
})
|
|
674
|
+
.then((token) => {
|
|
675
|
+
if (token.errors || token.error) {
|
|
676
|
+
// eslint-disable-next-line no-console
|
|
677
|
+
console.error(`${this.tokenError}: ${JSON.stringify(token.errors || token.error)}`);
|
|
678
|
+
} else {
|
|
679
|
+
// .expires_in contains the # of seconds before access token expires
|
|
680
|
+
// add property to keep track of current time when the token expires
|
|
681
|
+
token.eA = Date.now() + token.expires_in * 1000;
|
|
682
|
+
// Clear authCode related config state: state, codeVerifier, acRedirectUri
|
|
683
|
+
if (this.#dynState.state) {
|
|
684
|
+
delete this.#dynState.state;
|
|
685
|
+
}
|
|
686
|
+
if (this.#dynState.codeVerifier) {
|
|
687
|
+
delete this.#dynState.codeVerifier;
|
|
688
|
+
}
|
|
689
|
+
if (this.#dynState.acRedirectUri) {
|
|
690
|
+
delete this.#dynState.acRedirectUri;
|
|
691
|
+
}
|
|
692
|
+
// If there is a session_index then move this to the peConfig structure (as used on authorize)
|
|
693
|
+
if (token.session_index) {
|
|
694
|
+
this.#updateSessionIndex(token.session_index);
|
|
695
|
+
// does an #updateConfig within #updateSessionIndex
|
|
696
|
+
} else {
|
|
697
|
+
this.#updateConfig();
|
|
698
|
+
}
|
|
326
699
|
}
|
|
327
|
-
this.#updateConfig();
|
|
328
700
|
return token;
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
701
|
+
})
|
|
702
|
+
.catch((e) => {
|
|
703
|
+
const msg = `${e}`;
|
|
704
|
+
// eslint-disable-next-line no-console
|
|
705
|
+
console.error(msg.indexOf(this.tokenError) !== -1 ? msg : `${this.tokenError}: ${msg}`);
|
|
706
|
+
throw e;
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
async refreshToken(refreshToken) {
|
|
711
|
+
const { clientId, clientSecret, tokenUri, secureCookie } = this.#config;
|
|
335
712
|
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
713
|
+
if (this.isNode && !this.crypto) {
|
|
714
|
+
// Deferring dynamic loading of node libraries til this first method to avoid doing this in constructor
|
|
715
|
+
await this.#importNodeLibs();
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
if (!secureCookie && !refreshToken) {
|
|
719
|
+
return null;
|
|
720
|
+
}
|
|
339
721
|
|
|
340
722
|
const formData = new URLSearchParams();
|
|
341
|
-
formData.append(
|
|
342
|
-
if(
|
|
343
|
-
|
|
723
|
+
formData.append('client_id', clientId);
|
|
724
|
+
if (clientSecret) {
|
|
725
|
+
formData.append('client_secret', clientSecret);
|
|
726
|
+
}
|
|
727
|
+
formData.append('grant_type', 'refresh_token');
|
|
728
|
+
if (secureCookie) {
|
|
729
|
+
formData.append('send_token_as_cookie', 'true');
|
|
730
|
+
}
|
|
731
|
+
if (refreshToken) {
|
|
732
|
+
formData.append('refresh_token', refreshToken);
|
|
344
733
|
}
|
|
345
|
-
formData.append("grant_type", "refresh_token");
|
|
346
|
-
formData.append("refresh_token", refresh_token);
|
|
347
734
|
|
|
348
735
|
return fetch(tokenUri, {
|
|
349
|
-
|
|
736
|
+
agent: this.#getAgent(),
|
|
737
|
+
method: 'POST',
|
|
350
738
|
headers: new Headers({
|
|
351
|
-
|
|
739
|
+
'content-type': this.urlencoded
|
|
352
740
|
}),
|
|
353
|
-
|
|
354
|
-
body: formData.toString()
|
|
741
|
+
credentials: secureCookie ? 'include' : 'omit',
|
|
742
|
+
body: formData.toString()
|
|
355
743
|
})
|
|
356
|
-
|
|
357
|
-
|
|
744
|
+
.then((response) => {
|
|
745
|
+
if (!response.ok && response.status === 401) {
|
|
358
746
|
return null;
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
if(
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
747
|
+
}
|
|
748
|
+
return response.json();
|
|
749
|
+
})
|
|
750
|
+
.then((token) => {
|
|
751
|
+
if (token) {
|
|
752
|
+
// .expires_in contains the # of seconds before access token expires
|
|
753
|
+
// add property to keep track of current time when the token expires
|
|
754
|
+
token.eA = Date.now() + token.expires_in * 1000;
|
|
367
755
|
}
|
|
368
756
|
return token;
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
757
|
+
})
|
|
758
|
+
.catch((e) => {
|
|
759
|
+
// eslint-disable-next-line no-console
|
|
760
|
+
console.warn(`Refresh token failed: ${e}`);
|
|
761
|
+
return null;
|
|
762
|
+
});
|
|
763
|
+
}
|
|
375
764
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
765
|
+
/**
|
|
766
|
+
* Revokes tokens (useful as part of a logout operation). For non-secureCookie, the accessToken and
|
|
767
|
+
* the optional refreshToken would be passed in and the routine will generate two separate revoke
|
|
768
|
+
* transactions. For secureCookie scenario, will issue just one for the accessToken, but this will
|
|
769
|
+
* also revoke the refresh token if present.
|
|
770
|
+
* @param {string} accessToken - the access token (or any string value for secureCookie scenario)
|
|
771
|
+
* @param {string} refreshToken - optional refresh token (or any string value for non secureCookie
|
|
772
|
+
* scenario, when a refreshToken exists)
|
|
773
|
+
* @returns
|
|
774
|
+
*/
|
|
775
|
+
async revokeTokens(accessToken, refreshToken = null) {
|
|
776
|
+
if (Object.keys(this.#config).length === 0) {
|
|
777
|
+
// Must have a config structure to proceed
|
|
778
|
+
return;
|
|
380
779
|
}
|
|
381
|
-
const {clientId, clientSecret, revokeUri} = this
|
|
780
|
+
const { clientId, clientSecret, revokeUri, secureCookie } = this.#config;
|
|
382
781
|
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
782
|
+
if (this.isNode && !this.crypto) {
|
|
783
|
+
// Deferring dynamic loading of node libraries til this first method to avoid doing this in constructor
|
|
784
|
+
await this.#importNodeLibs();
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
const headers = { 'content-type': this.urlencoded };
|
|
788
|
+
if (clientSecret) {
|
|
789
|
+
const basicCreds = btoa(`${clientId}:${clientSecret}`);
|
|
790
|
+
headers.authorization = `Basic ${basicCreds}`;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// A revoke of a refresh_token will also revoke any associated access_tokens, so only one
|
|
794
|
+
// transaction is necessary.
|
|
795
|
+
const prop = refreshToken ? 'refresh_token' : 'access_token';
|
|
796
|
+
const formData = new URLSearchParams();
|
|
797
|
+
if (!clientSecret) {
|
|
798
|
+
formData.append('client_id', clientId);
|
|
799
|
+
}
|
|
800
|
+
if (secureCookie) {
|
|
801
|
+
formData.append('send_token_as_cookie', 'true');
|
|
387
802
|
}
|
|
388
|
-
const
|
|
389
|
-
if(
|
|
390
|
-
|
|
803
|
+
const token = prop === 'access_token' ? accessToken : refreshToken;
|
|
804
|
+
if (!secureCookie && token) {
|
|
805
|
+
formData.append('token', token);
|
|
391
806
|
}
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
807
|
+
formData.append('token_type_hint', prop);
|
|
808
|
+
return fetch(revokeUri, {
|
|
809
|
+
agent: this.#getAgent(),
|
|
810
|
+
method: 'POST',
|
|
811
|
+
headers: new Headers(headers),
|
|
812
|
+
credentials: secureCookie ? 'include' : 'omit',
|
|
813
|
+
body: formData.toString()
|
|
814
|
+
})
|
|
815
|
+
.then((response) => {
|
|
816
|
+
if (!response.ok) {
|
|
817
|
+
// eslint-disable-next-line no-console
|
|
818
|
+
console.error(`Error revoking ${prop}:${response.status}`);
|
|
396
819
|
}
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
// Also clobber any sessionIndex
|
|
416
|
-
if( this.config.sessionIndex ) {
|
|
417
|
-
delete this.config.sessionIndex;
|
|
418
|
-
this.#updateConfig();
|
|
820
|
+
})
|
|
821
|
+
.catch((e) => {
|
|
822
|
+
// eslint-disable-next-line no-console
|
|
823
|
+
console.error(`Error revoking ${prop}; ${e}`);
|
|
824
|
+
})
|
|
825
|
+
.finally(() => {
|
|
826
|
+
this.#dynState.silentAuthFailed = false;
|
|
827
|
+
// Also clobber any sessionIndex
|
|
828
|
+
this.#updateSessionIndex(null);
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// For userinfo endpoint to return meaningful data, endpoint must include appAlias (if specified) and authorize must
|
|
833
|
+
// specify profile and optionally email scope to get such info returned
|
|
834
|
+
async getUserinfo(accessToken) {
|
|
835
|
+
if (!this.#config || !this.#config.userinfoUri) {
|
|
836
|
+
// Must have a config structure and userInfo to proceed
|
|
837
|
+
return {};
|
|
419
838
|
}
|
|
420
|
-
|
|
839
|
+
const headers = {
|
|
840
|
+
authorization: `bearer ${accessToken}`,
|
|
841
|
+
'content-type': 'application/json;charset=UTF-8'
|
|
842
|
+
};
|
|
843
|
+
return fetch(this.#config.userinfoUri, {
|
|
844
|
+
agent: this.#getAgent(),
|
|
845
|
+
method: 'GET',
|
|
846
|
+
headers: new Headers(headers)
|
|
847
|
+
})
|
|
848
|
+
.then((response) => {
|
|
849
|
+
if (response.ok) {
|
|
850
|
+
return response.json();
|
|
851
|
+
}
|
|
852
|
+
// eslint-disable-next-line no-console
|
|
853
|
+
console.log(`Error invoking userinfo: ${response.status}`);
|
|
854
|
+
})
|
|
855
|
+
.then((data) => {
|
|
856
|
+
return data;
|
|
857
|
+
})
|
|
858
|
+
.catch((e) => {
|
|
859
|
+
// eslint-disable-next-line no-console
|
|
860
|
+
console.log(e);
|
|
861
|
+
});
|
|
862
|
+
}
|
|
421
863
|
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
864
|
+
#sha256Hash(str) {
|
|
865
|
+
// Found that the Node implementation of subtle.digest is yielding incorrect results
|
|
866
|
+
// so using a different set of apis to get expected results.
|
|
867
|
+
if (this.isNode) {
|
|
868
|
+
return new Promise((resolve) => {
|
|
869
|
+
resolve(this.crypto.createHash('sha256').update(str).digest());
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
return this.subtle.digest('SHA-256', new TextEncoder().encode(str));
|
|
428
873
|
}
|
|
429
|
-
const hdrs = {'authorization':`bearer ${access_token}`,'content-type':'application/json;charset=UTF-8'};
|
|
430
|
-
return fetch(this.config.userinfoUri, {
|
|
431
|
-
method: "GET",
|
|
432
|
-
headers: new Headers(hdrs)})
|
|
433
|
-
.then( response => {
|
|
434
|
-
if( response.ok) {
|
|
435
|
-
return response.json();
|
|
436
|
-
} else {
|
|
437
|
-
// eslint-disable-next-line no-console
|
|
438
|
-
console.log( `Error invoking userinfo: ${response.status}` );
|
|
439
|
-
}
|
|
440
|
-
})
|
|
441
|
-
.then( data => {
|
|
442
|
-
return data;
|
|
443
|
-
})
|
|
444
|
-
.catch(e => {
|
|
445
|
-
// eslint-disable-next-line no-console
|
|
446
|
-
console.log(e);
|
|
447
|
-
});
|
|
448
|
-
}
|
|
449
874
|
|
|
450
|
-
|
|
875
|
+
// Base64 encode
|
|
876
|
+
/* eslint-disable-next-line class-methods-use-this */
|
|
877
|
+
#encode64(buff) {
|
|
878
|
+
return btoa(new Uint8Array(buff).reduce((s, b) => s + String.fromCharCode(b), ''));
|
|
879
|
+
}
|
|
451
880
|
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
881
|
+
/*
|
|
882
|
+
* Base64 url safe encoding of an array
|
|
883
|
+
*/
|
|
884
|
+
#base64UrlSafeEncode(buf) {
|
|
885
|
+
return this.#encode64(buf).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
|
|
886
|
+
}
|
|
456
887
|
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
888
|
+
/*
|
|
889
|
+
* Get Random string starting with buffer of specified size
|
|
890
|
+
*/
|
|
891
|
+
#getRandomString(nSize) {
|
|
892
|
+
const buf = new Uint8Array(nSize);
|
|
893
|
+
this.crypto.getRandomValues(buf);
|
|
894
|
+
return this.#base64UrlSafeEncode(buf);
|
|
895
|
+
}
|
|
462
896
|
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
897
|
+
/*
|
|
898
|
+
* Calc code verifier if necessary
|
|
899
|
+
*/
|
|
900
|
+
async #getCodeChallenge(codeVerifier) {
|
|
901
|
+
return this.#sha256Hash(codeVerifier)
|
|
902
|
+
.then((hashed) => {
|
|
903
|
+
return this.#base64UrlSafeEncode(hashed);
|
|
904
|
+
})
|
|
905
|
+
.catch((error) => {
|
|
906
|
+
// eslint-disable-next-line no-console
|
|
907
|
+
console.error(`Error calculation code challenge for PKCE: ${error}`);
|
|
908
|
+
})
|
|
909
|
+
.finally(() => {
|
|
910
|
+
return null;
|
|
911
|
+
});
|
|
912
|
+
}
|
|
470
913
|
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
).finally(
|
|
485
|
-
() => { return null }
|
|
486
|
-
)
|
|
914
|
+
/*
|
|
915
|
+
* Return agent value for POST commands
|
|
916
|
+
*/
|
|
917
|
+
#getAgent() {
|
|
918
|
+
if (this.isNode && this.#config.ignoreInvalidCerts) {
|
|
919
|
+
const options = { rejectUnauthorized: false };
|
|
920
|
+
if (this.#config.legacyTLS) {
|
|
921
|
+
options.secureOptions = this.crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT;
|
|
922
|
+
}
|
|
923
|
+
return new this.https.Agent(options);
|
|
924
|
+
}
|
|
925
|
+
return undefined;
|
|
926
|
+
}
|
|
487
927
|
}
|
|
488
|
-
/* eslint-enable camelcase */
|
|
489
|
-
|
|
490
|
-
}
|
|
491
928
|
|
|
492
|
-
export default PegaAuth;
|
|
929
|
+
export default PegaAuth;
|