forked from ForgeRock/appAuthHelper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathappAuthHelperBundle.js
1801 lines (1728 loc) · 72.6 KB
/
appAuthHelperBundle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AppAuthHelper = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
(function () {
"use strict";
var AppAuth = require("@openid/appauth");
/**
* Module used to easily setup AppAuthJS in a way that allows it to transparently obtain and renew access tokens
* @module AppAuthHelper
*/
module.exports = {
/** @function init
* @param {Object} config - configation needed for working with the OP
* @param {string} config.clientId - The id of this RP client within the OP
* @param {boolean} config.oidc [true] - indicate whether or not you want OIDC included
* @param {string} config.authorizationEndpoint - Full URL to the OP authorization endpoint
* @param {string} config.tokenEndpoint - Full URL to the OP token endpoint
* @param {string} config.revocationEndpoint - Full URL to the OP revocation endpoint
* @param {string} config.endSessionEndpoint - Full URL to the OP end session endpoint
* @param {object} config.resourceServers - Map of resource server urls to the scopes which they require. Map values are space-delimited list of scopes requested by this RP for use with this RS
* @param {function} config.interactionRequiredHandler - optional function to be called anytime interaction is required. When not provided, default behavior is to redirect the current window to the authorizationEndpoint
* @param {function} config.tokensAvailableHandler - function to be called every time tokens are available - both initially and upon renewal
* @param {number} config.renewCooldownPeriod [1] - Minimum time (in seconds) between requests to the authorizationEndpoint for token renewal attempts
* @param {string} config.redirectUri [appAuthHelperRedirect.html] - The redirect uri registered in the OP
* @param {string} config.serviceWorkerUri [appAuthServiceWorker.js] - The path to the service worker script
*/
init: function (config) {
var calculatedUriLink,
iframe = document.createElement("iframe");
this.renewCooldownPeriod = config.renewCooldownPeriod || 1;
this.appAuthConfig = {};
this.tokensAvailableHandler = config.tokensAvailableHandler;
this.interactionRequiredHandler = config.interactionRequiredHandler;
this.appAuthConfig.oidc = typeof config.oidc !== "undefined" ? !!config.oidc : true;
this.pendingResourceServerRenewals = [];
if (!config.redirectUri) {
calculatedUriLink = document.createElement("a");
calculatedUriLink.href = "appAuthHelperRedirect.html";
this.appAuthConfig.redirectUri = calculatedUriLink.href;
} else {
this.appAuthConfig.redirectUri = config.redirectUri;
}
if (!config.serviceWorkerUri) {
calculatedUriLink = document.createElement("a");
calculatedUriLink.href = "appAuthServiceWorker.js";
this.appAuthConfig.serviceWorkerUri = calculatedUriLink.href;
} else {
this.appAuthConfig.serviceWorkerUri = config.serviceWorkerUri;
}
this.appAuthConfig.resourceServers = config.resourceServers || {};
this.appAuthConfig.clientId = config.clientId;
this.appAuthConfig.scopes = (this.appAuthConfig.oidc ? ["openid"] : [])
.concat(
Object.keys(this.appAuthConfig.resourceServers).reduce((scopes, rs) =>
scopes.concat(this.appAuthConfig.resourceServers[rs])
, [])
).join(" ");
this.appAuthConfig.endpoints = {
"authorization_endpoint": config.authorizationEndpoint,
"token_endpoint": config.tokenEndpoint,
"revocation_endpoint": config.revocationEndpoint,
"end_session_endpoint": config.endSessionEndpoint
};
window.addEventListener("message", (function (e) {
if (e.origin !== document.location.origin) {
return;
}
switch (e.data) {
case "appAuth-tokensAvailable":
var originalWindowHash = sessionStorage.getItem("originalWindowHash");
if (originalWindowHash !== null) {
window.location.hash = originalWindowHash;
sessionStorage.removeItem("originalWindowHash");
}
// this should only be set as part of token renewal
if (sessionStorage.getItem("currentResourceServer")) {
var currentResourceServer = sessionStorage.getItem("currentResourceServer");
sessionStorage.removeItem("currentResourceServer");
this.renewTokenTimestamp = false;
if (this.pendingResourceServerRenewals.length) {
this.pendingResourceServerRenewals.shift()();
}
navigator.serviceWorker.controller.postMessage({
"message": "tokensRenewed",
"resourceServer": currentResourceServer
});
} else {
this.registerServiceWorker()
.then(() => this.fetchTokensFromIndexedDB())
.then((tokens) =>
this.tokensAvailableHandler(this.appAuthConfig.oidc ? getIdTokenClaims(tokens.idToken) : {})
);
}
break;
case "appAuth-interactionRequired":
if (this.interactionRequiredHandler) {
this.interactionRequiredHandler();
} else {
// Default behavior for when interaction is required is to redirect to the OP for login.
// When interaction is required, the current hash state may be lost during redirection.
// Save it in sessionStorage so that it can be returned to upon successfully authenticating
sessionStorage.setItem("originalWindowHash", window.location.hash);
// Use the default redirect request handler, because it will use the current window
// as the redirect target (rather than the hidden iframe).
this.client.authorizationHandler = (new AppAuth.RedirectRequestHandler());
authnRequest(this.client, this.appAuthConfig);
}
break;
}
}).bind(this), false);
/*
* Attach a hidden iframe onto the main document body that is used to handle
* interaction with the token endpoint. This will allow us to perform
* background access token renewal, in addition to handling the main PKCE-based
* authorization code flow performed in the foreground.
*
* sessionStorage is used to pass the configuration down to the iframe
*/
sessionStorage.setItem("appAuthConfig", JSON.stringify(this.appAuthConfig));
iframe.setAttribute("src", this.appAuthConfig.redirectUri + window.location.hash);
iframe.setAttribute("id", "AppAuthHelper");
iframe.setAttribute("style", "display:none");
document.getElementsByTagName("body")[0].appendChild(iframe);
var tokenHandler;
if (typeof Promise === "undefined" || typeof fetch === "undefined") {
// Fall back to default, jQuery-based implementation for legacy browsers (IE).
// Be sure jQuery is available globally if you need to support these.
tokenHandler = new AppAuth.BaseTokenRequestHandler();
} else {
tokenHandler = new AppAuth.BaseTokenRequestHandler({
// fetch-based alternative to built-in jquery implementation
// TODO: replace with new AppAuth option
xhr: function (settings) {
return new Promise(function (resolve, reject) {
fetch(settings.url, {
method: settings.method,
body: settings.data,
mode: "cors",
cache: "no-cache",
headers: settings.headers
}).then(function (response) {
if (response.ok) {
response.json().then(resolve);
} else {
reject(response.statusText);
}
}, reject);
});
}
});
}
this.client = {
configuration: new AppAuth.AuthorizationServiceConfiguration(this.appAuthConfig.endpoints),
notifier: new AppAuth.AuthorizationNotifier(),
authorizationHandler: new AppAuth.RedirectRequestHandler(
// handle redirection within the hidden iframe
void 0, void 0, iframe.contentWindow.location
),
tokenHandler: tokenHandler
};
},
/**
* Pass in a reference to an iframe element that you would like to use to handle the AS redirection,
* rather than relying on a full-page redirection.
*/
iframeRedirect: function (iframe) {
// Use a provided iframe element to handle the authentication request.
this.client.authorizationHandler = (new AppAuth.RedirectRequestHandler(
// handle redirection within the hidden iframe
void 0, void 0, iframe.contentWindow.location
));
authnRequest(this.client, this.appAuthConfig);
},
/**
* Begins process which will either get the tokens that are in session storage or will attempt to
* get them from the OP. In either case, the tokensAvailableHandler will be called. No guarentee that the
* tokens are still valid, however - you must be prepared to handle the case when they are not.
*/
getTokens: function () {
this.fetchTokensFromIndexedDB().then((tokens) => {
if (!tokens) {
// attempt silent authorization
authnRequest(this.client, this.appAuthConfig, { "prompt": "none" });
} else {
this.registerServiceWorker()
.then(() => this.tokensAvailableHandler(this.appAuthConfig.oidc ? getIdTokenClaims(tokens.idToken) : {}));
}
});
},
/**
* logout() will revoke the access token, use the id_token to end the session on the OP, clear them from the
* local session, and finally notify the SPA that they are gone.
*/
logout: function () {
return this.fetchTokensFromIndexedDB().then((tokens) => {
if (!tokens) {
return;
}
var revokeRequests = [];
if (tokens.accessToken) {
revokeRequests.push(new AppAuth.RevokeTokenRequest({
client_id: this.appAuthConfig.clientId,
token: tokens.accessToken
}));
}
return Promise.all(revokeRequests.concat(
Object.keys(this.appAuthConfig.resourceServers)
.filter((rs) => !!tokens[rs])
.map((rs) =>
new AppAuth.RevokeTokenRequest({
client_id: this.appAuthConfig.clientId,
token: tokens[rs]
})
)
)
.map((revokeRequest) =>
this.client.tokenHandler.performRevokeTokenRequest(
this.client.configuration,
revokeRequest
)
)
)
.then(() => {
if (this.appAuthConfig.oidc && tokens.idToken && this.client.configuration.endSessionEndpoint) {
return fetch(this.client.configuration.endSessionEndpoint + "?id_token_hint=" + tokens.idToken);
} else {
return;
}
})
.then(() => new Promise((resolve, reject) => {
var dbReq = indexedDB.open("appAuth",1);
dbReq.onsuccess = () => {
var objectStoreRequest = dbReq.result.transaction([this.appAuthConfig.clientId], "readwrite")
.objectStore(this.appAuthConfig.clientId).clear();
dbReq.result.close();
objectStoreRequest.onsuccess = resolve;
};
dbReq.onerror = reject;
}));
});
},
whenRenewTokenFrameAvailable: function (resourceServer) {
return new Promise((resolve) => {
var currentResourceServer = sessionStorage.getItem("currentResourceServer");
if (currentResourceServer === null || resourceServer === currentResourceServer) {
resolve();
} else {
this.pendingResourceServerRenewals.push(resolve);
}
});
},
renewTokens: function (resourceServer) {
this.whenRenewTokenFrameAvailable(resourceServer).then(() => {
var timestamp = (new Date()).getTime();
sessionStorage.setItem("currentResourceServer", resourceServer);
if (!this.renewTokenTimestamp || (this.renewTokenTimestamp + (this.renewCooldownPeriod*1000)) < timestamp) {
this.renewTokenTimestamp = timestamp;
// update reference to iframe, to ensure it is still valid
this.client.authorizationHandler = new AppAuth.RedirectRequestHandler(
// handle redirection within the hidden iframe
void 0, void 0, document.getElementById("AppAuthHelper").contentWindow.location
);
var rsConfig = Object.create(this.appAuthConfig);
rsConfig.scopes = this.appAuthConfig.resourceServers[resourceServer];
authnRequest(this.client, rsConfig, { "prompt": "none" });
}
});
},
fetchTokensFromIndexedDB: function () {
return new Promise((resolve, reject) => {
var dbReq = indexedDB.open("appAuth",1);
dbReq.onupgradeneeded = () => {
dbReq.result.createObjectStore(this.appAuthConfig.clientId);
};
dbReq.onsuccess = () => {
var objectStoreRequest = dbReq.result.transaction([this.appAuthConfig.clientId], "readonly")
.objectStore(this.appAuthConfig.clientId).get("tokens");
objectStoreRequest.onsuccess = () => {
var tokens = objectStoreRequest.result;
dbReq.result.close();
resolve(tokens);
};
objectStoreRequest.onerror = reject;
};
dbReq.onerror = reject;
});
},
receiveMessageFromServiceWorker: function (event) {
return new Promise((resolve) => {
if (event.data.message === "renewTokens") {
this.renewTokens(event.data.resourceServer);
}
resolve();
});
},
registerServiceWorker: function () {
return new Promise((resolve, reject) => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register(this.appAuthConfig.serviceWorkerUri)
.then((reg) => {
var sendConfigMessage = () => {
this.serviceWorkerMessageChannel = new MessageChannel();
this.serviceWorkerMessageChannel.port1.onmessage = (event) =>
this.receiveMessageFromServiceWorker(event).then(() => resolve());
reg.active.postMessage({
"message": "configuration",
"config": this.appAuthConfig
}, [this.serviceWorkerMessageChannel.port2]);
};
if (reg.active) {
sendConfigMessage();
} else {
navigator.serviceWorker.addEventListener("controllerchange", () => {
sendConfigMessage();
});
}
})
.catch(reject);
}
});
}
};
/**
* Helper function that reduces the amount of duplicated code, as there are several different
* places in the code that require initiating an authorization request.
*/
function authnRequest(client, config, extras) {
var request = new AppAuth.AuthorizationRequest({
client_id: config.clientId,
redirect_uri: config.redirectUri,
scope: config.scopes,
response_type: AppAuth.AuthorizationRequest.RESPONSE_TYPE_CODE,
extras: extras || {}
});
client.authorizationHandler.performAuthorizationRequest(
client.configuration,
request
);
}
/**
* Simple jwt parsing code purely used for extracting claims.
*/
function getIdTokenClaims(id_token) {
return JSON.parse(
atob(id_token.split(".")[1].replace("-", "+").replace("_", "/"))
);
}
}());
},{"@openid/appauth":9}],2:[function(require,module,exports){
"use strict";
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var crypto_utils_1 = require("./crypto_utils");
var logger_1 = require("./logger");
/**
* Generates a cryptographically random new state. Useful for CSRF protection.
*/
var SIZE = 10; // 10 bytes
var newState = function (crypto) {
return crypto.generateRandom(SIZE);
};
/**
* Represents the AuthorizationRequest.
* For more information look at
* https://tools.ietf.org/html/rfc6749#section-4.1.1
*/
var AuthorizationRequest = /** @class */ (function () {
/**
* Constructs a new AuthorizationRequest.
* Use a `undefined` value for the `state` parameter, to generate a random
* state for CSRF protection.
*/
function AuthorizationRequest(request, crypto, usePkce) {
if (crypto === void 0) { crypto = new crypto_utils_1.DefaultCrypto(); }
if (usePkce === void 0) { usePkce = true; }
this.crypto = crypto;
this.usePkce = usePkce;
this.clientId = request.client_id;
this.redirectUri = request.redirect_uri;
this.scope = request.scope;
this.responseType = request.response_type || AuthorizationRequest.RESPONSE_TYPE_CODE;
this.state = request.state || newState(crypto);
this.extras = request.extras;
// read internal properties if available
this.internal = request.internal;
}
AuthorizationRequest.prototype.setupCodeVerifier = function () {
var _this = this;
if (!this.usePkce) {
return Promise.resolve();
}
else {
var codeVerifier_1 = this.crypto.generateRandom(128);
var challenge = this.crypto.deriveChallenge(codeVerifier_1).catch(function (error) {
logger_1.log('Unable to generate PKCE challenge. Not using PKCE', error);
return undefined;
});
return challenge.then(function (result) {
if (result) {
// keep track of the code used.
_this.internal = _this.internal || {};
_this.internal['code_verifier'] = codeVerifier_1;
_this.extras = _this.extras || {};
_this.extras['code_challenge'] = result;
// We always use S256. Plain is not good enough.
_this.extras['code_challenge_method'] = 'S256';
}
});
}
};
/**
* Serializes the AuthorizationRequest to a JavaScript Object.
*/
AuthorizationRequest.prototype.toJson = function () {
var _this = this;
// Always make sure that the code verifier is setup when toJson() is called.
return this.setupCodeVerifier().then(function () {
return {
response_type: _this.responseType,
client_id: _this.clientId,
redirect_uri: _this.redirectUri,
scope: _this.scope,
state: _this.state,
extras: _this.extras,
internal: _this.internal
};
});
};
AuthorizationRequest.RESPONSE_TYPE_TOKEN = 'token';
AuthorizationRequest.RESPONSE_TYPE_CODE = 'code';
return AuthorizationRequest;
}());
exports.AuthorizationRequest = AuthorizationRequest;
},{"./crypto_utils":6,"./logger":10}],3:[function(require,module,exports){
"use strict";
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var logger_1 = require("./logger");
/**
* Authorization Service notifier.
* This manages the communication of the AuthorizationResponse to the 3p client.
*/
var AuthorizationNotifier = /** @class */ (function () {
function AuthorizationNotifier() {
this.listener = null;
}
AuthorizationNotifier.prototype.setAuthorizationListener = function (listener) {
this.listener = listener;
};
/**
* The authorization complete callback.
*/
AuthorizationNotifier.prototype.onAuthorizationComplete = function (request, response, error) {
if (this.listener) {
// complete authorization request
this.listener(request, response, error);
}
};
return AuthorizationNotifier;
}());
exports.AuthorizationNotifier = AuthorizationNotifier;
// TODO(rahulrav@): add more built in parameters.
/* built in parameters. */
exports.BUILT_IN_PARAMETERS = ['redirect_uri', 'client_id', 'response_type', 'state', 'scope'];
/**
* Defines the interface which is capable of handling an authorization request
* using various methods (iframe / popup / different process etc.).
*/
var AuthorizationRequestHandler = /** @class */ (function () {
function AuthorizationRequestHandler(utils, crypto) {
this.utils = utils;
this.crypto = crypto;
// notifier send the response back to the client.
this.notifier = null;
}
/**
* A utility method to be able to build the authorization request URL.
*/
AuthorizationRequestHandler.prototype.buildRequestUrl = function (configuration, request) {
// build the query string
// coerce to any type for convenience
var requestMap = {
'redirect_uri': request.redirectUri,
'client_id': request.clientId,
'response_type': request.responseType,
'state': request.state,
'scope': request.scope
};
// copy over extras
if (request.extras) {
for (var extra in request.extras) {
if (request.extras.hasOwnProperty(extra)) {
// check before inserting to requestMap
if (exports.BUILT_IN_PARAMETERS.indexOf(extra) < 0) {
requestMap[extra] = request.extras[extra];
}
}
}
}
var query = this.utils.stringify(requestMap);
var baseUrl = configuration.authorizationEndpoint;
var url = baseUrl + "?" + query;
return url;
};
/**
* Completes the authorization request if necessary & when possible.
*/
AuthorizationRequestHandler.prototype.completeAuthorizationRequestIfPossible = function () {
var _this = this;
// call complete authorization if possible to see there might
// be a response that needs to be delivered.
logger_1.log("Checking to see if there is an authorization response to be delivered.");
if (!this.notifier) {
logger_1.log("Notifier is not present on AuthorizationRequest handler.\n No delivery of result will be possible");
}
return this.completeAuthorizationRequest().then(function (result) {
if (!result) {
logger_1.log("No result is available yet.");
}
if (result && _this.notifier) {
_this.notifier.onAuthorizationComplete(result.request, result.response, result.error);
}
});
};
/**
* Sets the default Authorization Service notifier.
*/
AuthorizationRequestHandler.prototype.setAuthorizationNotifier = function (notifier) {
this.notifier = notifier;
return this;
};
;
return AuthorizationRequestHandler;
}());
exports.AuthorizationRequestHandler = AuthorizationRequestHandler;
},{"./logger":10}],4:[function(require,module,exports){
"use strict";
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Represents the Authorization Response type.
* For more information look at
* https://tools.ietf.org/html/rfc6749#section-4.1.2
*/
var AuthorizationResponse = /** @class */ (function () {
function AuthorizationResponse(response) {
this.code = response.code;
this.state = response.state;
}
AuthorizationResponse.prototype.toJson = function () {
return { code: this.code, state: this.state };
};
return AuthorizationResponse;
}());
exports.AuthorizationResponse = AuthorizationResponse;
/**
* Represents the Authorization error response.
* For more information look at:
* https://tools.ietf.org/html/rfc6749#section-4.1.2.1
*/
var AuthorizationError = /** @class */ (function () {
function AuthorizationError(error) {
this.error = error.error;
this.errorDescription = error.error_description;
this.errorUri = error.error_uri;
this.state = error.state;
}
AuthorizationError.prototype.toJson = function () {
return {
error: this.error,
error_description: this.errorDescription,
error_uri: this.errorUri,
state: this.state
};
};
return AuthorizationError;
}());
exports.AuthorizationError = AuthorizationError;
},{}],5:[function(require,module,exports){
"use strict";
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var xhr_1 = require("./xhr");
/**
* The standard base path for well-known resources on domains.
* See https://tools.ietf.org/html/rfc5785 for more information.
*/
var WELL_KNOWN_PATH = '.well-known';
/**
* The standard resource under the well known path at which an OpenID Connect
* discovery document can be found under an issuer's base URI.
*/
var OPENID_CONFIGURATION = 'openid-configuration';
/**
* Configuration details required to interact with an authorization service.
*
* More information at https://openid.net/specs/openid-connect-discovery-1_0-17.html
*/
var AuthorizationServiceConfiguration = /** @class */ (function () {
function AuthorizationServiceConfiguration(request) {
this.authorizationEndpoint = request.authorization_endpoint;
this.tokenEndpoint = request.token_endpoint;
this.revocationEndpoint = request.revocation_endpoint;
this.userInfoEndpoint = request.userinfo_endpoint;
this.endSessionEndpoint = request.end_session_endpoint;
}
AuthorizationServiceConfiguration.prototype.toJson = function () {
return {
authorization_endpoint: this.authorizationEndpoint,
token_endpoint: this.tokenEndpoint,
revocation_endpoint: this.revocationEndpoint,
end_session_endpoint: this.endSessionEndpoint,
userinfo_endpoint: this.userInfoEndpoint
};
};
AuthorizationServiceConfiguration.fetchFromIssuer = function (openIdIssuerUrl, requestor) {
var fullUrl = openIdIssuerUrl + "/" + WELL_KNOWN_PATH + "/" + OPENID_CONFIGURATION;
var requestorToUse = requestor || new xhr_1.JQueryRequestor();
return requestorToUse
.xhr({ url: fullUrl, dataType: 'json' })
.then(function (json) { return new AuthorizationServiceConfiguration(json); });
};
return AuthorizationServiceConfiguration;
}());
exports.AuthorizationServiceConfiguration = AuthorizationServiceConfiguration;
},{"./xhr":18}],6:[function(require,module,exports){
"use strict";
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var base64 = require("base64-js");
var errors_1 = require("./errors");
var HAS_CRYPTO = typeof window !== 'undefined' && !!window.crypto;
var HAS_SUBTLE_CRYPTO = HAS_CRYPTO && !!window.crypto.subtle;
var CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
function bufferToString(buffer) {
var state = [];
for (var i = 0; i < buffer.byteLength; i += 1) {
var index = buffer[i] % CHARSET.length;
state.push(CHARSET[index]);
}
return state.join('');
}
exports.bufferToString = bufferToString;
function urlSafe(buffer) {
var encoded = base64.fromByteArray(new Uint8Array(buffer));
return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
exports.urlSafe = urlSafe;
// adapted from source: http://stackoverflow.com/a/11058858
// this is used in place of TextEncode as the api is not yet
// well supported: https://caniuse.com/#search=TextEncoder
function textEncodeLite(str) {
var buf = new ArrayBuffer(str.length);
var bufView = new Uint8Array(buf);
for (var i = 0; i < str.length; i++) {
bufView[i] = str.charCodeAt(i);
}
return bufView;
}
exports.textEncodeLite = textEncodeLite;
/**
* The default implementation of the `Crypto` interface.
* This uses the capabilities of the browser.
*/
var DefaultCrypto = /** @class */ (function () {
function DefaultCrypto() {
}
DefaultCrypto.prototype.generateRandom = function (size) {
var buffer = new Uint8Array(size);
if (HAS_CRYPTO) {
window.crypto.getRandomValues(buffer);
}
else {
// fall back to Math.random() if nothing else is available
for (var i = 0; i < size; i += 1) {
buffer[i] = Math.random();
}
}
return bufferToString(buffer);
};
DefaultCrypto.prototype.deriveChallenge = function (code) {
if (code.length < 43 || code.length > 128) {
return Promise.reject(new errors_1.AppAuthError('Invalid code length.'));
}
if (!HAS_SUBTLE_CRYPTO) {
return Promise.reject(new errors_1.AppAuthError('window.crypto.subtle is unavailable.'));
}
return new Promise(function (resolve, reject) {
crypto.subtle.digest('SHA-256', textEncodeLite(code)).then(function (buffer) {
return resolve(urlSafe(new Uint8Array(buffer)));
}, function (error) { return reject(error); });
});
};
return DefaultCrypto;
}());
exports.DefaultCrypto = DefaultCrypto;
},{"./errors":7,"base64-js":19}],7:[function(require,module,exports){
"use strict";
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Represents the AppAuthError type.
*/
var AppAuthError = /** @class */ (function () {
function AppAuthError(message, extras) {
this.message = message;
this.extras = extras;
}
return AppAuthError;
}());
exports.AppAuthError = AppAuthError;
},{}],8:[function(require,module,exports){
"use strict";
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/* Global flags that control the behavior of App Auth JS. */
/* Logging turned on ? */
exports.IS_LOG = true;
/* Profiling turned on ? */
exports.IS_PROFILE = false;
},{}],9:[function(require,module,exports){
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./authorization_request"));
__export(require("./authorization_request_handler"));
__export(require("./authorization_response"));
__export(require("./authorization_service_configuration"));
__export(require("./crypto_utils"));
__export(require("./errors"));
__export(require("./flags"));
__export(require("./logger"));
__export(require("./query_string_utils"));
__export(require("./redirect_based_handler"));
__export(require("./revoke_token_request"));
__export(require("./storage"));
__export(require("./token_request"));
__export(require("./token_request_handler"));
__export(require("./token_response"));
__export(require("./xhr"));
},{"./authorization_request":2,"./authorization_request_handler":3,"./authorization_response":4,"./authorization_service_configuration":5,"./crypto_utils":6,"./errors":7,"./flags":8,"./logger":10,"./query_string_utils":11,"./redirect_based_handler":12,"./revoke_token_request":13,"./storage":14,"./token_request":15,"./token_request_handler":16,"./token_response":17,"./xhr":18}],10:[function(require,module,exports){
"use strict";
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var flags_1 = require("./flags");
function log(message) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (flags_1.IS_LOG) {
var length_1 = args ? args.length : 0;
if (length_1 > 0) {
console.log.apply(console, [message].concat(args));
}
else {
console.log(message);
}
}
}
exports.log = log;
;
// check to see if native support for profiling is available.
var NATIVE_PROFILE_SUPPORT = typeof window !== 'undefined' && !!window.performance && !!console.profile;
/**
* A decorator that can profile a function.
*/
function profile(target, propertyKey, descriptor) {
if (flags_1.IS_PROFILE) {
return performProfile(target, propertyKey, descriptor);
}
else {
// return as-is
return descriptor;
}
}
exports.profile = profile;
function performProfile(target, propertyKey, descriptor) {
var originalCallable = descriptor.value;
// name must exist
var name = originalCallable.name;
if (!name) {
name = 'anonymous function';
}
if (NATIVE_PROFILE_SUPPORT) {
descriptor.value = function (args) {
console.profile(name);
var startTime = window.performance.now();
var result = originalCallable.call.apply(originalCallable, [this || window].concat(args));
var duration = window.performance.now() - startTime;
console.log(name + " took " + duration + " ms");
console.profileEnd();
return result;
};
}
else {
descriptor.value = function (args) {
log("Profile start " + name);
var start = Date.now();
var result = originalCallable.call.apply(originalCallable, [this || window].concat(args));
var duration = Date.now() - start;
log("Profile end " + name + " took " + duration + " ms.");
return result;
};
}
return descriptor;
}
},{"./flags":8}],11:[function(require,module,exports){
"use strict";
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var BasicQueryStringUtils = /** @class */ (function () {
function BasicQueryStringUtils() {
}
BasicQueryStringUtils.prototype.parse = function (input, useHash) {
if (useHash) {
return this.parseQueryString(input.hash);
}
else {
return this.parseQueryString(input.search);
}
};
BasicQueryStringUtils.prototype.parseQueryString = function (query) {
var result = {};
// if anything starts with ?, # or & remove it
query = query.trim().replace(/^(\?|#|&)/, '');
var params = query.split('&');
for (var i = 0; i < params.length; i += 1) {
var param = params[i]; // looks something like a=b
var parts = param.split('=');
if (parts.length >= 2) {
var key = decodeURIComponent(parts.shift());
var value = parts.length > 0 ? parts.join('=') : null;
if (value) {
result[key] = decodeURIComponent(value);
}
}
}
return result;
};
BasicQueryStringUtils.prototype.stringify = function (input) {
var encoded = [];
for (var key in input) {
if (input.hasOwnProperty(key) && input[key]) {
encoded.push(encodeURIComponent(key) + "=" + encodeURIComponent(input[key]));
}
}
return encoded.join('&');
};
return BasicQueryStringUtils;
}());
exports.BasicQueryStringUtils = BasicQueryStringUtils;