@axa-fr/react-oidc 6.5.7 → 6.5.8

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.
Files changed (92) hide show
  1. package/dist/FetchToken.js +39 -104
  2. package/dist/FetchToken.js.map +1 -1
  3. package/dist/OidcProvider.js +76 -110
  4. package/dist/OidcProvider.js.map +1 -1
  5. package/dist/OidcSecure.js +11 -60
  6. package/dist/OidcSecure.js.map +1 -1
  7. package/dist/ReactOidc.js +56 -74
  8. package/dist/ReactOidc.js.map +1 -1
  9. package/dist/User.js +13 -32
  10. package/dist/User.js.map +1 -1
  11. package/dist/core/default-component/AuthenticateError.component.js +4 -29
  12. package/dist/core/default-component/AuthenticateError.component.js.map +1 -1
  13. package/dist/core/default-component/Authenticating.component.js +4 -29
  14. package/dist/core/default-component/Authenticating.component.js.map +1 -1
  15. package/dist/core/default-component/Callback.component.js +29 -99
  16. package/dist/core/default-component/Callback.component.js.map +1 -1
  17. package/dist/core/default-component/Loading.component.js +3 -28
  18. package/dist/core/default-component/Loading.component.js.map +1 -1
  19. package/dist/core/default-component/ServiceWorkerNotSupported.component.js +4 -29
  20. package/dist/core/default-component/ServiceWorkerNotSupported.component.js.map +1 -1
  21. package/dist/core/default-component/SessionLost.component.js +6 -13
  22. package/dist/core/default-component/SessionLost.component.js.map +1 -1
  23. package/dist/core/default-component/SilentCallback.component.js +13 -73
  24. package/dist/core/default-component/SilentCallback.component.js.map +1 -1
  25. package/dist/core/default-component/SilentLogin.component.js +13 -43
  26. package/dist/core/default-component/SilentLogin.component.js.map +1 -1
  27. package/dist/core/default-component/index.js +6 -19
  28. package/dist/core/default-component/index.js.map +1 -1
  29. package/dist/core/routes/OidcRoutes.js +20 -49
  30. package/dist/core/routes/OidcRoutes.js.map +1 -1
  31. package/dist/core/routes/index.js +1 -8
  32. package/dist/core/routes/index.js.map +1 -1
  33. package/dist/core/routes/withRouter.js +13 -20
  34. package/dist/core/routes/withRouter.js.map +1 -1
  35. package/dist/index.js +5 -18
  36. package/dist/index.js.map +1 -1
  37. package/dist/vanilla/checkSessionIFrame.js +21 -30
  38. package/dist/vanilla/checkSessionIFrame.js.map +1 -1
  39. package/dist/vanilla/index.js +1 -5
  40. package/dist/vanilla/index.js.map +1 -1
  41. package/dist/vanilla/initSession.js +41 -78
  42. package/dist/vanilla/initSession.js.map +1 -1
  43. package/dist/vanilla/initWorker.js +99 -168
  44. package/dist/vanilla/initWorker.js.map +1 -1
  45. package/dist/vanilla/memoryStorageBackend.js +11 -17
  46. package/dist/vanilla/memoryStorageBackend.js.map +1 -1
  47. package/dist/vanilla/noHashQueryStringUtils.js +15 -46
  48. package/dist/vanilla/noHashQueryStringUtils.js.map +1 -1
  49. package/dist/vanilla/oidc.js +945 -1394
  50. package/dist/vanilla/oidc.js.map +1 -1
  51. package/dist/vanilla/parseTokens.js +33 -53
  52. package/dist/vanilla/parseTokens.js.map +1 -1
  53. package/dist/vanilla/route-utils.js +17 -23
  54. package/dist/vanilla/route-utils.js.map +1 -1
  55. package/dist/vanilla/timer.js +21 -23
  56. package/dist/vanilla/timer.js.map +1 -1
  57. package/package.json +2 -3
  58. package/src/oidc/FetchToken.tsx +0 -61
  59. package/src/oidc/OidcProvider.tsx +0 -206
  60. package/src/oidc/OidcSecure.tsx +0 -37
  61. package/src/oidc/ReactOidc.tsx +0 -139
  62. package/src/oidc/User.ts +0 -38
  63. package/src/oidc/core/default-component/AuthenticateError.component.tsx +0 -13
  64. package/src/oidc/core/default-component/Authenticating.component.tsx +0 -13
  65. package/src/oidc/core/default-component/Callback.component.tsx +0 -46
  66. package/src/oidc/core/default-component/Loading.component.tsx +0 -10
  67. package/src/oidc/core/default-component/ServiceWorkerNotSupported.component.tsx +0 -13
  68. package/src/oidc/core/default-component/SessionLost.component.tsx +0 -14
  69. package/src/oidc/core/default-component/SilentCallback.component.tsx +0 -22
  70. package/src/oidc/core/default-component/SilentLogin.component.tsx +0 -35
  71. package/src/oidc/core/default-component/index.ts +0 -6
  72. package/src/oidc/core/routes/OidcRoutes.spec.tsx +0 -15
  73. package/src/oidc/core/routes/OidcRoutes.tsx +0 -69
  74. package/src/oidc/core/routes/__snapshots__/OidcRoutes.spec.tsx.snap +0 -7
  75. package/src/oidc/core/routes/index.ts +0 -2
  76. package/src/oidc/core/routes/withRouter.spec.tsx +0 -48
  77. package/src/oidc/core/routes/withRouter.tsx +0 -64
  78. package/src/oidc/index.ts +0 -5
  79. package/src/oidc/vanilla/OidcServiceWorker.js +0 -435
  80. package/src/oidc/vanilla/OidcTrustedDomains.js +0 -16
  81. package/src/oidc/vanilla/checkSessionIFrame.ts +0 -82
  82. package/src/oidc/vanilla/index.ts +0 -1
  83. package/src/oidc/vanilla/initSession.ts +0 -67
  84. package/src/oidc/vanilla/initWorker.ts +0 -165
  85. package/src/oidc/vanilla/memoryStorageBackend.ts +0 -33
  86. package/src/oidc/vanilla/noHashQueryStringUtils.ts +0 -33
  87. package/src/oidc/vanilla/oidc.ts +0 -1230
  88. package/src/oidc/vanilla/parseTokens.ts +0 -150
  89. package/src/oidc/vanilla/route-utils.spec.ts +0 -15
  90. package/src/oidc/vanilla/route-utils.ts +0 -76
  91. package/src/oidc/vanilla/timer.ts +0 -165
  92. package/tsconfig.json +0 -38
@@ -1,30 +1,3 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __assign = (this && this.__assign) || function () {
18
- __assign = Object.assign || function(t) {
19
- for (var s, i = 1, n = arguments.length; i < n; i++) {
20
- s = arguments[i];
21
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
- t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
1
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
2
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
3
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -34,278 +7,168 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
34
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
35
8
  });
36
9
  };
37
- var __generator = (this && this.__generator) || function (thisArg, body) {
38
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
39
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
40
- function verb(n) { return function (v) { return step([n, v]); }; }
41
- function step(op) {
42
- if (f) throw new TypeError("Generator is already executing.");
43
- while (_) try {
44
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
45
- if (y = 0, t) op = [op[0] & 2, t.value];
46
- switch (op[0]) {
47
- case 0: case 1: t = op; break;
48
- case 4: _.label++; return { value: op[1], done: false };
49
- case 5: _.label++; y = op[1]; op = [0]; continue;
50
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
51
- default:
52
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
53
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
54
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
55
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
56
- if (t[2]) _.ops.pop();
57
- _.trys.pop(); continue;
58
- }
59
- op = body.call(thisArg, _);
60
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
61
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
- }
63
- };
64
- var __importDefault = (this && this.__importDefault) || function (mod) {
65
- return (mod && mod.__esModule) ? mod : { "default": mod };
66
- };
67
- Object.defineProperty(exports, "__esModule", { value: true });
68
- exports.Oidc = exports.OidcAuthorizationServiceConfiguration = void 0;
69
- var appauth_1 = require("@openid/appauth");
70
- var noHashQueryStringUtils_1 = require("./noHashQueryStringUtils");
71
- var initWorker_1 = require("./initWorker");
72
- var memoryStorageBackend_1 = require("./memoryStorageBackend");
73
- var initSession_1 = require("./initSession");
74
- var timer_1 = __importDefault(require("./timer"));
75
- var checkSessionIFrame_1 = require("./checkSessionIFrame");
76
- var route_utils_1 = require("./route-utils");
77
- var parseTokens_1 = require("./parseTokens");
78
- var performTokenRequestAsync = function (url, details, extras, oldTokens) { return __awaiter(void 0, void 0, void 0, function () {
79
- var _i, _a, _b, key, value, formBody, property, encodedKey, encodedValue, formBodyString, response, tokens;
80
- return __generator(this, function (_c) {
81
- switch (_c.label) {
82
- case 0:
83
- for (_i = 0, _a = Object.entries(extras); _i < _a.length; _i++) {
84
- _b = _a[_i], key = _b[0], value = _b[1];
85
- if (details[key] === undefined) {
86
- details[key] = value;
87
- }
88
- }
89
- formBody = [];
90
- for (property in details) {
91
- encodedKey = encodeURIComponent(property);
92
- encodedValue = encodeURIComponent(details[property]);
93
- formBody.push("".concat(encodedKey, "=").concat(encodedValue));
94
- }
95
- formBodyString = formBody.join("&");
96
- return [4 /*yield*/, internalFetch(url, {
97
- method: 'POST',
98
- headers: {
99
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
100
- },
101
- body: formBodyString,
102
- })];
103
- case 1:
104
- response = _c.sent();
105
- if (response.status !== 200) {
106
- return [2 /*return*/, { success: false, status: response.status }];
107
- }
108
- return [4 /*yield*/, response.json()];
109
- case 2:
110
- tokens = _c.sent();
111
- return [2 /*return*/, {
112
- success: true,
113
- data: (0, parseTokens_1.parseOriginalTokens)(tokens, oldTokens)
114
- }];
10
+ import { AuthorizationNotifier, AuthorizationRequest, AuthorizationServiceConfiguration, BaseTokenRequestHandler, DefaultCrypto, FetchRequestor, GRANT_TYPE_AUTHORIZATION_CODE, GRANT_TYPE_REFRESH_TOKEN, RedirectRequestHandler, TokenRequest } from '@openid/appauth';
11
+ import { HashQueryStringUtils, NoHashQueryStringUtils } from './noHashQueryStringUtils';
12
+ import { initWorkerAsync, sleepAsync } from './initWorker';
13
+ import { MemoryStorageBackend } from "./memoryStorageBackend";
14
+ import { initSession } from "./initSession";
15
+ import timer from './timer';
16
+ import { CheckSessionIFrame } from "./checkSessionIFrame";
17
+ import { getParseQueryStringFromLocation } from "./route-utils";
18
+ import { computeTimeLeft, isTokensOidcValid, isTokensValid, parseOriginalTokens, setTokens } from "./parseTokens";
19
+ const performTokenRequestAsync = (url, details, extras, oldTokens) => __awaiter(void 0, void 0, void 0, function* () {
20
+ for (let [key, value] of Object.entries(extras)) {
21
+ if (details[key] === undefined) {
22
+ details[key] = value;
115
23
  }
24
+ }
25
+ let formBody = [];
26
+ for (const property in details) {
27
+ const encodedKey = encodeURIComponent(property);
28
+ const encodedValue = encodeURIComponent(details[property]);
29
+ formBody.push(`${encodedKey}=${encodedValue}`);
30
+ }
31
+ const formBodyString = formBody.join("&");
32
+ const response = yield internalFetch(url, {
33
+ method: 'POST',
34
+ headers: {
35
+ 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
36
+ },
37
+ body: formBodyString,
116
38
  });
117
- }); };
118
- var internalFetch = function (url, headers, numberRetry) {
119
- if (numberRetry === void 0) { numberRetry = 0; }
120
- return __awaiter(void 0, void 0, void 0, function () {
121
- var response, controller_1, e_1;
122
- return __generator(this, function (_a) {
123
- switch (_a.label) {
124
- case 0:
125
- _a.trys.push([0, 2, , 8]);
126
- controller_1 = new AbortController();
127
- setTimeout(function () { return controller_1.abort(); }, 10000);
128
- return [4 /*yield*/, fetch(url, __assign(__assign({}, headers), { signal: controller_1.signal }))];
129
- case 1:
130
- response = _a.sent();
131
- return [3 /*break*/, 8];
132
- case 2:
133
- e_1 = _a.sent();
134
- if (!(e_1.message === 'AbortError'
135
- || e_1.message === 'Network request failed')) return [3 /*break*/, 6];
136
- if (!(numberRetry <= 1)) return [3 /*break*/, 4];
137
- return [4 /*yield*/, internalFetch(url, headers, numberRetry + 1)];
138
- case 3: return [2 /*return*/, _a.sent()];
139
- case 4: throw e_1;
140
- case 5: return [3 /*break*/, 7];
141
- case 6:
142
- console.error(e_1.message);
143
- throw e_1; // rethrow other unexpected errors
144
- case 7: return [3 /*break*/, 8];
145
- case 8: return [2 /*return*/, response];
39
+ if (response.status !== 200) {
40
+ return { success: false, status: response.status };
41
+ }
42
+ const tokens = yield response.json();
43
+ return {
44
+ success: true,
45
+ data: parseOriginalTokens(tokens, oldTokens)
46
+ };
47
+ });
48
+ const internalFetch = (url, headers, numberRetry = 0) => __awaiter(void 0, void 0, void 0, function* () {
49
+ let response;
50
+ try {
51
+ let controller = new AbortController();
52
+ setTimeout(() => controller.abort(), 10000);
53
+ response = yield fetch(url, Object.assign(Object.assign({}, headers), { signal: controller.signal }));
54
+ }
55
+ catch (e) {
56
+ if (e.message === 'AbortError'
57
+ || e.message === 'Network request failed') {
58
+ if (numberRetry <= 1) {
59
+ return yield internalFetch(url, headers, numberRetry + 1);
146
60
  }
147
- });
148
- });
149
- };
150
- var OidcAuthorizationServiceConfiguration = /** @class */ (function (_super) {
151
- __extends(OidcAuthorizationServiceConfiguration, _super);
152
- function OidcAuthorizationServiceConfiguration(request) {
153
- var _this = _super.call(this, request) || this;
154
- _this.authorizationEndpoint = request.authorization_endpoint;
155
- _this.tokenEndpoint = request.token_endpoint;
156
- _this.revocationEndpoint = request.revocation_endpoint;
157
- _this.userInfoEndpoint = request.userinfo_endpoint;
158
- _this.check_session_iframe = request.check_session_iframe;
159
- _this.issuer = request.issuer;
160
- return _this;
61
+ else {
62
+ throw e;
63
+ }
64
+ }
65
+ else {
66
+ console.error(e.message);
67
+ throw e; // rethrow other unexpected errors
68
+ }
161
69
  }
162
- return OidcAuthorizationServiceConfiguration;
163
- }(appauth_1.AuthorizationServiceConfiguration));
164
- exports.OidcAuthorizationServiceConfiguration = OidcAuthorizationServiceConfiguration;
165
- var oidcDatabase = {};
166
- var oidcFactory = function (configuration, name) {
167
- if (name === void 0) { name = "default"; }
70
+ return response;
71
+ });
72
+ export class OidcAuthorizationServiceConfiguration extends AuthorizationServiceConfiguration {
73
+ constructor(request) {
74
+ super(request);
75
+ this.authorizationEndpoint = request.authorization_endpoint;
76
+ this.tokenEndpoint = request.token_endpoint;
77
+ this.revocationEndpoint = request.revocation_endpoint;
78
+ this.userInfoEndpoint = request.userinfo_endpoint;
79
+ this.check_session_iframe = request.check_session_iframe;
80
+ this.issuer = request.issuer;
81
+ }
82
+ }
83
+ const oidcDatabase = {};
84
+ const oidcFactory = (configuration, name = "default") => {
168
85
  if (oidcDatabase[name]) {
169
86
  return oidcDatabase[name];
170
87
  }
171
88
  oidcDatabase[name] = new Oidc(configuration, name);
172
89
  return oidcDatabase[name];
173
90
  };
174
- var loginCallbackWithAutoTokensRenewAsync = function (oidc) { return __awaiter(void 0, void 0, void 0, function () {
175
- var _a, parsedTokens, state, callbackPath;
176
- return __generator(this, function (_b) {
177
- switch (_b.label) {
178
- case 0: return [4 /*yield*/, oidc.loginCallbackAsync()];
179
- case 1:
180
- _a = _b.sent(), parsedTokens = _a.parsedTokens, state = _a.state, callbackPath = _a.callbackPath;
181
- oidc.timeoutId = autoRenewTokens(oidc, parsedTokens.refreshToken, parsedTokens.expiresAt);
182
- return [2 /*return*/, { state: state, callbackPath: callbackPath }];
91
+ const loginCallbackWithAutoTokensRenewAsync = (oidc) => __awaiter(void 0, void 0, void 0, function* () {
92
+ const { parsedTokens, state, callbackPath } = yield oidc.loginCallbackAsync();
93
+ oidc.timeoutId = autoRenewTokens(oidc, parsedTokens.refreshToken, parsedTokens.expiresAt);
94
+ return { state, callbackPath };
95
+ });
96
+ function renewTokensAndStartTimerAsync(oidc, refreshToken, forceRefresh = false, extras = null) {
97
+ return __awaiter(this, void 0, void 0, function* () {
98
+ const { tokens, status } = yield oidc.synchroniseTokensAsync(refreshToken, 0, forceRefresh, extras);
99
+ oidc.tokens = tokens;
100
+ const serviceWorker = yield initWorkerAsync(oidc.configuration.service_worker_relative_url, oidc.configurationName);
101
+ if (!serviceWorker) {
102
+ const session = initSession(oidc.configurationName, oidc.configuration.redirect_uri, oidc.configuration.storage);
103
+ yield session.setTokens(oidc.tokens);
104
+ }
105
+ if (!oidc.tokens) {
106
+ yield oidc.destroyAsync(status);
107
+ return;
108
+ }
109
+ if (oidc.timeoutId) {
110
+ oidc.timeoutId = autoRenewTokens(oidc, tokens.refreshToken, oidc.tokens.expiresAt, extras);
183
111
  }
184
- });
185
- }); };
186
- function renewTokensAndStartTimerAsync(oidc, refreshToken, forceRefresh, extras) {
187
- if (forceRefresh === void 0) { forceRefresh = false; }
188
- if (extras === void 0) { extras = null; }
189
- return __awaiter(this, void 0, void 0, function () {
190
- var _a, tokens, status, serviceWorker, session;
191
- return __generator(this, function (_b) {
192
- switch (_b.label) {
193
- case 0: return [4 /*yield*/, oidc.synchroniseTokensAsync(refreshToken, 0, forceRefresh, extras)];
194
- case 1:
195
- _a = _b.sent(), tokens = _a.tokens, status = _a.status;
196
- oidc.tokens = tokens;
197
- return [4 /*yield*/, (0, initWorker_1.initWorkerAsync)(oidc.configuration.service_worker_relative_url, oidc.configurationName)];
198
- case 2:
199
- serviceWorker = _b.sent();
200
- if (!!serviceWorker) return [3 /*break*/, 4];
201
- session = (0, initSession_1.initSession)(oidc.configurationName, oidc.configuration.redirect_uri, oidc.configuration.storage);
202
- return [4 /*yield*/, session.setTokens(oidc.tokens)];
203
- case 3:
204
- _b.sent();
205
- _b.label = 4;
206
- case 4:
207
- if (!!oidc.tokens) return [3 /*break*/, 6];
208
- return [4 /*yield*/, oidc.destroyAsync(status)];
209
- case 5:
210
- _b.sent();
211
- return [2 /*return*/];
212
- case 6:
213
- if (oidc.timeoutId) {
214
- oidc.timeoutId = autoRenewTokens(oidc, tokens.refreshToken, oidc.tokens.expiresAt, extras);
215
- }
216
- return [2 /*return*/];
217
- }
218
- });
219
112
  });
220
113
  }
221
- var autoRenewTokens = function (oidc, refreshToken, expiresAt, extras) {
222
- if (extras === void 0) { extras = null; }
223
- var refreshTimeBeforeTokensExpirationInSecond = oidc.configuration.refresh_time_before_tokens_expiration_in_second;
224
- return timer_1.default.setTimeout(function () { return __awaiter(void 0, void 0, void 0, function () {
225
- var timeLeft, timeInfo;
226
- return __generator(this, function (_a) {
227
- switch (_a.label) {
228
- case 0:
229
- timeLeft = (0, parseTokens_1.computeTimeLeft)(refreshTimeBeforeTokensExpirationInSecond, expiresAt);
230
- timeInfo = { timeLeft: timeLeft };
231
- oidc.publishEvent(Oidc.eventNames.token_timer, timeInfo);
232
- return [4 /*yield*/, renewTokensAndStartTimerAsync(oidc, refreshToken, false, extras)];
233
- case 1:
234
- _a.sent();
235
- return [2 /*return*/];
236
- }
237
- });
238
- }); }, 1000);
114
+ const autoRenewTokens = (oidc, refreshToken, expiresAt, extras = null) => {
115
+ const refreshTimeBeforeTokensExpirationInSecond = oidc.configuration.refresh_time_before_tokens_expiration_in_second;
116
+ return timer.setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
117
+ const timeLeft = computeTimeLeft(refreshTimeBeforeTokensExpirationInSecond, expiresAt);
118
+ const timeInfo = { timeLeft };
119
+ oidc.publishEvent(Oidc.eventNames.token_timer, timeInfo);
120
+ yield renewTokensAndStartTimerAsync(oidc, refreshToken, false, extras);
121
+ }), 1000);
239
122
  };
240
- var getLoginSessionKey = function (configurationName, redirectUri) {
241
- return "oidc_login.".concat(configurationName, ":").concat(redirectUri);
123
+ const getLoginSessionKey = (configurationName, redirectUri) => {
124
+ return `oidc_login.${configurationName}:${redirectUri}`;
242
125
  };
243
- var setLoginParams = function (configurationName, redirectUri, data) {
244
- var sessionKey = getLoginSessionKey(configurationName, redirectUri);
126
+ const setLoginParams = (configurationName, redirectUri, data) => {
127
+ const sessionKey = getLoginSessionKey(configurationName, redirectUri);
245
128
  getLoginParamsCache = data;
246
129
  sessionStorage[sessionKey] = JSON.stringify(data);
247
130
  };
248
- var getLoginParamsCache = null;
249
- var getLoginParams = function (configurationName, redirectUri) {
250
- var dataString = sessionStorage[getLoginSessionKey(configurationName, redirectUri)];
131
+ let getLoginParamsCache = null;
132
+ const getLoginParams = (configurationName, redirectUri) => {
133
+ const dataString = sessionStorage[getLoginSessionKey(configurationName, redirectUri)];
251
134
  if (!getLoginParamsCache) {
252
135
  getLoginParamsCache = JSON.parse(dataString);
253
136
  }
254
137
  return getLoginParamsCache;
255
138
  };
256
- var userInfoAsync = function (oidc) { return __awaiter(void 0, void 0, void 0, function () {
257
- var accessToken, oidcServerConfiguration, url, fetchUserInfo, userInfo;
258
- return __generator(this, function (_a) {
259
- switch (_a.label) {
260
- case 0:
261
- if (oidc.userInfo != null) {
262
- return [2 /*return*/, oidc.userInfo];
263
- }
264
- if (!oidc.tokens) {
265
- return [2 /*return*/, null];
266
- }
267
- accessToken = oidc.tokens.accessToken;
268
- if (!accessToken) {
269
- return [2 /*return*/, null];
270
- }
271
- _a.label = 1;
272
- case 1:
273
- if (!(oidc.tokens && !(0, parseTokens_1.isTokensValid)(oidc.tokens))) return [3 /*break*/, 3];
274
- return [4 /*yield*/, (0, initWorker_1.sleepAsync)(200)];
275
- case 2:
276
- _a.sent();
277
- return [3 /*break*/, 1];
278
- case 3: return [4 /*yield*/, oidc.initAsync(oidc.configuration.authority, oidc.configuration.authority_configuration)];
279
- case 4:
280
- oidcServerConfiguration = _a.sent();
281
- url = oidcServerConfiguration.userInfoEndpoint;
282
- fetchUserInfo = function (accessToken) { return __awaiter(void 0, void 0, void 0, function () {
283
- var res;
284
- return __generator(this, function (_a) {
285
- switch (_a.label) {
286
- case 0: return [4 /*yield*/, fetch(url, {
287
- headers: {
288
- authorization: "Bearer ".concat(accessToken),
289
- }
290
- })];
291
- case 1:
292
- res = _a.sent();
293
- if (res.status != 200) {
294
- return [2 /*return*/, null];
295
- }
296
- return [2 /*return*/, res.json()];
297
- }
298
- });
299
- }); };
300
- return [4 /*yield*/, fetchUserInfo(accessToken)];
301
- case 5:
302
- userInfo = _a.sent();
303
- oidc.userInfo = userInfo;
304
- return [2 /*return*/, userInfo];
139
+ const userInfoAsync = (oidc) => __awaiter(void 0, void 0, void 0, function* () {
140
+ if (oidc.userInfo != null) {
141
+ return oidc.userInfo;
142
+ }
143
+ if (!oidc.tokens) {
144
+ return null;
145
+ }
146
+ const accessToken = oidc.tokens.accessToken;
147
+ if (!accessToken) {
148
+ return null;
149
+ }
150
+ // We wait the synchronisation before making a request
151
+ while (oidc.tokens && !isTokensValid(oidc.tokens)) {
152
+ yield sleepAsync(200);
153
+ }
154
+ const oidcServerConfiguration = yield oidc.initAsync(oidc.configuration.authority, oidc.configuration.authority_configuration);
155
+ const url = oidcServerConfiguration.userInfoEndpoint;
156
+ const fetchUserInfo = (accessToken) => __awaiter(void 0, void 0, void 0, function* () {
157
+ const res = yield fetch(url, {
158
+ headers: {
159
+ authorization: `Bearer ${accessToken}`,
160
+ }
161
+ });
162
+ if (res.status != 200) {
163
+ return null;
305
164
  }
165
+ return res.json();
306
166
  });
307
- }); };
308
- var eventNames = {
167
+ const userInfo = yield fetchUserInfo(accessToken);
168
+ oidc.userInfo = userInfo;
169
+ return userInfo;
170
+ });
171
+ const eventNames = {
309
172
  service_worker_not_supported_by_browser: "service_worker_not_supported_by_browser",
310
173
  token_aquired: "token_aquired",
311
174
  logout_from_another_tab: "logout_from_another_tab",
@@ -333,71 +196,55 @@ var eventNames = {
333
196
  syncTokensAsync_end: "syncTokensAsync_end",
334
197
  syncTokensAsync_error: "syncTokensAsync_error"
335
198
  };
336
- var getRandomInt = function (max) {
199
+ const getRandomInt = (max) => {
337
200
  return Math.floor(Math.random() * max);
338
201
  };
339
- var oneHourSecond = 60 * 60;
340
- var fetchFromIssuerCache = {};
341
- var fetchFromIssuer = function (openIdIssuerUrl, timeCacheSecond, storage) {
342
- if (timeCacheSecond === void 0) { timeCacheSecond = oneHourSecond; }
343
- if (storage === void 0) { storage = window.sessionStorage; }
344
- return __awaiter(void 0, void 0, void 0, function () {
345
- var fullUrl, localStorageKey, cacheJson, oneHourMinisecond, response, result, timestamp;
346
- return __generator(this, function (_a) {
347
- switch (_a.label) {
348
- case 0:
349
- fullUrl = "".concat(openIdIssuerUrl, "/.well-known/openid-configuration");
350
- localStorageKey = "oidc.server:".concat(openIdIssuerUrl);
351
- if (!fetchFromIssuerCache[localStorageKey]) {
352
- if (storage) {
353
- cacheJson = storage.getItem(localStorageKey);
354
- if (cacheJson) {
355
- fetchFromIssuerCache[localStorageKey] = JSON.parse(cacheJson);
356
- }
357
- }
358
- }
359
- oneHourMinisecond = 1000 * timeCacheSecond;
360
- // @ts-ignore
361
- if (fetchFromIssuerCache[localStorageKey] && (fetchFromIssuerCache[localStorageKey].timestamp + oneHourMinisecond) > Date.now()) {
362
- return [2 /*return*/, new OidcAuthorizationServiceConfiguration(fetchFromIssuerCache[localStorageKey].result)];
363
- }
364
- return [4 /*yield*/, fetch(fullUrl)];
365
- case 1:
366
- response = _a.sent();
367
- if (response.status != 200) {
368
- return [2 /*return*/, null];
369
- }
370
- return [4 /*yield*/, response.json()];
371
- case 2:
372
- result = _a.sent();
373
- timestamp = Date.now();
374
- fetchFromIssuerCache[localStorageKey] = { result: result, timestamp: timestamp };
375
- if (storage) {
376
- storage.setItem(localStorageKey, JSON.stringify({ result: result, timestamp: timestamp }));
377
- }
378
- return [2 /*return*/, new OidcAuthorizationServiceConfiguration(result)];
202
+ const oneHourSecond = 60 * 60;
203
+ let fetchFromIssuerCache = {};
204
+ const fetchFromIssuer = (openIdIssuerUrl, timeCacheSecond = oneHourSecond, storage = window.sessionStorage) => __awaiter(void 0, void 0, void 0, function* () {
205
+ const fullUrl = `${openIdIssuerUrl}/.well-known/openid-configuration`;
206
+ const localStorageKey = `oidc.server:${openIdIssuerUrl}`;
207
+ if (!fetchFromIssuerCache[localStorageKey]) {
208
+ if (storage) {
209
+ const cacheJson = storage.getItem(localStorageKey);
210
+ if (cacheJson) {
211
+ fetchFromIssuerCache[localStorageKey] = JSON.parse(cacheJson);
379
212
  }
380
- });
381
- });
382
- };
383
- var buildQueries = function (extras) {
384
- var queries = '';
213
+ }
214
+ }
215
+ const oneHourMinisecond = 1000 * timeCacheSecond;
216
+ // @ts-ignore
217
+ if (fetchFromIssuerCache[localStorageKey] && (fetchFromIssuerCache[localStorageKey].timestamp + oneHourMinisecond) > Date.now()) {
218
+ return new OidcAuthorizationServiceConfiguration(fetchFromIssuerCache[localStorageKey].result);
219
+ }
220
+ const response = yield fetch(fullUrl);
221
+ if (response.status != 200) {
222
+ return null;
223
+ }
224
+ const result = yield response.json();
225
+ const timestamp = Date.now();
226
+ fetchFromIssuerCache[localStorageKey] = { result, timestamp };
227
+ if (storage) {
228
+ storage.setItem(localStorageKey, JSON.stringify({ result, timestamp }));
229
+ }
230
+ return new OidcAuthorizationServiceConfiguration(result);
231
+ });
232
+ const buildQueries = (extras) => {
233
+ let queries = '';
385
234
  if (extras != null) {
386
- for (var _i = 0, _a = Object.entries(extras); _i < _a.length; _i++) {
387
- var _b = _a[_i], key = _b[0], value = _b[1];
235
+ for (let [key, value] of Object.entries(extras)) {
388
236
  if (queries === "") {
389
- queries = "?".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(value));
237
+ queries = `?${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
390
238
  }
391
239
  else {
392
- queries += "&".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(value));
240
+ queries += `&${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
393
241
  }
394
242
  }
395
243
  }
396
244
  return queries;
397
245
  };
398
- var Oidc = /** @class */ (function () {
399
- function Oidc(configuration, configurationName) {
400
- if (configurationName === void 0) { configurationName = "default"; }
246
+ export class Oidc {
247
+ constructor(configuration, configurationName = "default") {
401
248
  var _a, _b, _c;
402
249
  this.initPromise = null;
403
250
  this.tryKeepExistingSessionPromise = null;
@@ -405,11 +252,11 @@ var Oidc = /** @class */ (function () {
405
252
  this.loginCallbackPromise = null;
406
253
  this.loginCallbackWithAutoTokensRenewPromise = null;
407
254
  this.userInfoPromise = null;
408
- var silent_login_uri = configuration.silent_login_uri;
255
+ let silent_login_uri = configuration.silent_login_uri;
409
256
  if (configuration.silent_redirect_uri && !configuration.silent_login_uri) {
410
- silent_login_uri = "".concat(configuration.silent_redirect_uri.replace("-callback", "").replace("callback", ""), "-login");
257
+ silent_login_uri = `${configuration.silent_redirect_uri.replace("-callback", "").replace("callback", "")}-login`;
411
258
  }
412
- this.configuration = __assign(__assign({}, configuration), { silent_login_uri: silent_login_uri, monitor_session: (_a = configuration.monitor_session) !== null && _a !== void 0 ? _a : false, refresh_time_before_tokens_expiration_in_second: (_b = configuration.refresh_time_before_tokens_expiration_in_second) !== null && _b !== void 0 ? _b : 60, silent_login_timeout: (_c = configuration.silent_login_timeout) !== null && _c !== void 0 ? _c : 12000 });
259
+ this.configuration = Object.assign(Object.assign({}, configuration), { silent_login_uri, monitor_session: (_a = configuration.monitor_session) !== null && _a !== void 0 ? _a : false, refresh_time_before_tokens_expiration_in_second: (_b = configuration.refresh_time_before_tokens_expiration_in_second) !== null && _b !== void 0 ? _b : 60, silent_login_timeout: (_c = configuration.silent_login_timeout) !== null && _c !== void 0 ? _c : 12000 });
413
260
  this.configurationName = configurationName;
414
261
  this.tokens = null;
415
262
  this.userInfo = null;
@@ -428,1149 +275,853 @@ var Oidc = /** @class */ (function () {
428
275
  this.renewTokensAsync.bind(this);
429
276
  this.initAsync(this.configuration.authority, this.configuration.authority_configuration);
430
277
  }
431
- Oidc.prototype.subscriveEvents = function (func) {
432
- var id = getRandomInt(9999999999999).toString();
433
- this.events.push({ id: id, func: func });
278
+ subscriveEvents(func) {
279
+ const id = getRandomInt(9999999999999).toString();
280
+ this.events.push({ id, func });
434
281
  return id;
435
- };
436
- Oidc.prototype.removeEventSubscription = function (id) {
437
- var newEvents = this.events.filter(function (e) { return e.id !== id; });
282
+ }
283
+ removeEventSubscription(id) {
284
+ const newEvents = this.events.filter(e => e.id !== id);
438
285
  this.events = newEvents;
439
- };
440
- Oidc.prototype.publishEvent = function (eventName, data) {
441
- this.events.forEach(function (event) {
286
+ }
287
+ publishEvent(eventName, data) {
288
+ this.events.forEach(event => {
442
289
  event.func(eventName, data);
443
290
  });
444
- };
445
- Oidc.getOrCreate = function (configuration, name) {
446
- if (name === void 0) { name = "default"; }
291
+ }
292
+ static getOrCreate(configuration, name = "default") {
447
293
  return oidcFactory(configuration, name);
448
- };
449
- Oidc.get = function (name) {
450
- if (name === void 0) { name = "default"; }
451
- var insideBrowser = (typeof process === 'undefined');
294
+ }
295
+ static get(name = "default") {
296
+ const insideBrowser = (typeof process === 'undefined');
452
297
  if (!oidcDatabase.hasOwnProperty(name) && insideBrowser) {
453
- throw Error("Oidc library does seem initialized.\nPlease checkout that you are using OIDC hook inside a <OidcProvider configurationName=\"".concat(name, "\"></OidcProvider> compoment."));
298
+ throw Error(`Oidc library does seem initialized.
299
+ Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${name}"></OidcProvider> compoment.`);
454
300
  }
455
301
  return oidcDatabase[name];
456
- };
457
- Oidc.prototype._silentLoginCallbackFromIFrame = function () {
302
+ }
303
+ _silentLoginCallbackFromIFrame() {
458
304
  if (this.configuration.silent_redirect_uri && this.configuration.silent_login_uri) {
459
- var queryParams = (0, route_utils_1.getParseQueryStringFromLocation)(window.location.href);
460
- window.top.postMessage("".concat(this.configurationName, "_oidc_tokens:").concat(JSON.stringify({ tokens: this.tokens, sessionState: queryParams.session_state })), window.location.origin);
305
+ const queryParams = getParseQueryStringFromLocation(window.location.href);
306
+ window.top.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({ tokens: this.tokens, sessionState: queryParams.session_state })}`, window.location.origin);
461
307
  }
462
- };
463
- Oidc.prototype._silentLoginErrorCallbackFromIFrame = function () {
308
+ }
309
+ _silentLoginErrorCallbackFromIFrame() {
464
310
  if (this.configuration.silent_redirect_uri && this.configuration.silent_login_uri) {
465
- var queryParams = (0, route_utils_1.getParseQueryStringFromLocation)(window.location.href);
466
- window.top.postMessage("".concat(this.configurationName, "_oidc_error:").concat(JSON.stringify({ error: queryParams.error })), window.location.origin);
311
+ const queryParams = getParseQueryStringFromLocation(window.location.href);
312
+ window.top.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({ error: queryParams.error })}`, window.location.origin);
467
313
  }
468
- };
469
- Oidc.prototype.silentLoginCallBackAsync = function () {
470
- return __awaiter(this, void 0, void 0, function () {
471
- var error_1;
472
- return __generator(this, function (_a) {
473
- switch (_a.label) {
474
- case 0:
475
- _a.trys.push([0, 2, , 3]);
476
- return [4 /*yield*/, this.loginCallbackAsync(true)];
477
- case 1:
478
- _a.sent();
479
- this._silentLoginCallbackFromIFrame();
480
- return [3 /*break*/, 3];
481
- case 2:
482
- error_1 = _a.sent();
483
- console.error(error_1);
484
- this._silentLoginErrorCallbackFromIFrame();
485
- return [3 /*break*/, 3];
486
- case 3: return [2 /*return*/];
487
- }
488
- });
314
+ }
315
+ silentLoginCallBackAsync() {
316
+ return __awaiter(this, void 0, void 0, function* () {
317
+ try {
318
+ yield this.loginCallbackAsync(true);
319
+ this._silentLoginCallbackFromIFrame();
320
+ }
321
+ catch (error) {
322
+ console.error(error);
323
+ this._silentLoginErrorCallbackFromIFrame();
324
+ }
489
325
  });
490
- };
491
- Oidc.prototype.silentLoginAsync = function (extras, state, scope) {
492
- if (extras === void 0) { extras = null; }
493
- if (state === void 0) { state = null; }
494
- if (scope === void 0) { scope = null; }
495
- return __awaiter(this, void 0, void 0, function () {
496
- var configuration_1, queries, _i, _a, _b, key, value, link, idx, iFrameOrigin_1, iframe_1, self_1;
497
- return __generator(this, function (_c) {
498
- if (!this.configuration.silent_redirect_uri || !this.configuration.silent_login_uri) {
499
- return [2 /*return*/, Promise.resolve(null)];
326
+ }
327
+ silentLoginAsync(extras = null, state = null, scope = null) {
328
+ return __awaiter(this, void 0, void 0, function* () {
329
+ if (!this.configuration.silent_redirect_uri || !this.configuration.silent_login_uri) {
330
+ return Promise.resolve(null);
331
+ }
332
+ try {
333
+ this.publishEvent(eventNames.silentLoginAsync_begin, {});
334
+ const configuration = this.configuration;
335
+ let queries = "";
336
+ if (state) {
337
+ if (extras == null) {
338
+ extras = {};
339
+ }
340
+ extras.state = state;
500
341
  }
501
- try {
502
- this.publishEvent(eventNames.silentLoginAsync_begin, {});
503
- configuration_1 = this.configuration;
504
- queries = "";
505
- if (state) {
506
- if (extras == null) {
507
- extras = {};
508
- }
509
- extras.state = state;
342
+ if (scope) {
343
+ if (extras == null) {
344
+ extras = {};
510
345
  }
511
- if (scope) {
512
- if (extras == null) {
513
- extras = {};
346
+ extras.scope = scope;
347
+ }
348
+ if (extras != null) {
349
+ for (let [key, value] of Object.entries(extras)) {
350
+ if (queries === "") {
351
+ queries = `?${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
514
352
  }
515
- extras.scope = scope;
516
- }
517
- if (extras != null) {
518
- for (_i = 0, _a = Object.entries(extras); _i < _a.length; _i++) {
519
- _b = _a[_i], key = _b[0], value = _b[1];
520
- if (queries === "") {
521
- queries = "?".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(value));
522
- }
523
- else {
524
- queries += "&".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(value));
525
- }
353
+ else {
354
+ queries += `&${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
526
355
  }
527
356
  }
528
- link = configuration_1.silent_login_uri + queries;
529
- idx = link.indexOf("/", link.indexOf("//") + 2);
530
- iFrameOrigin_1 = link.substr(0, idx);
531
- iframe_1 = document.createElement('iframe');
532
- iframe_1.width = "0px";
533
- iframe_1.height = "0px";
534
- iframe_1.id = "".concat(this.configurationName, "_oidc_iframe");
535
- iframe_1.setAttribute("src", link);
536
- document.body.appendChild(iframe_1);
537
- self_1 = this;
538
- return [2 /*return*/, new Promise(function (resolve, reject) {
539
- try {
540
- var isResolved_1 = false;
541
- window.onmessage = function (e) {
542
- if (e.origin === iFrameOrigin_1 &&
543
- e.source === iframe_1.contentWindow) {
544
- var key = "".concat(self_1.configurationName, "_oidc_tokens:");
545
- var key_error = "".concat(self_1.configurationName, "_oidc_error:");
546
- var data = e.data;
547
- if (data && typeof (data) === "string") {
548
- if (!isResolved_1) {
549
- if (data.startsWith(key)) {
550
- var result = JSON.parse(e.data.replace(key, ''));
551
- self_1.publishEvent(eventNames.silentLoginAsync_end, {});
552
- iframe_1.remove();
553
- isResolved_1 = true;
554
- resolve(result);
555
- }
556
- else if (data.startsWith(key_error)) {
557
- var result = JSON.parse(e.data.replace(key_error, ''));
558
- self_1.publishEvent(eventNames.silentLoginAsync_error, result);
559
- iframe_1.remove();
560
- isResolved_1 = true;
561
- reject(new Error("oidc_" + result.error));
562
- }
563
- }
357
+ }
358
+ const link = configuration.silent_login_uri + queries;
359
+ const idx = link.indexOf("/", link.indexOf("//") + 2);
360
+ const iFrameOrigin = link.substr(0, idx);
361
+ const iframe = document.createElement('iframe');
362
+ iframe.width = "0px";
363
+ iframe.height = "0px";
364
+ iframe.id = `${this.configurationName}_oidc_iframe`;
365
+ iframe.setAttribute("src", link);
366
+ document.body.appendChild(iframe);
367
+ const self = this;
368
+ return new Promise((resolve, reject) => {
369
+ try {
370
+ let isResolved = false;
371
+ window.onmessage = function (e) {
372
+ if (e.origin === iFrameOrigin &&
373
+ e.source === iframe.contentWindow) {
374
+ const key = `${self.configurationName}_oidc_tokens:`;
375
+ const key_error = `${self.configurationName}_oidc_error:`;
376
+ const data = e.data;
377
+ if (data && typeof (data) === "string") {
378
+ if (!isResolved) {
379
+ if (data.startsWith(key)) {
380
+ const result = JSON.parse(e.data.replace(key, ''));
381
+ self.publishEvent(eventNames.silentLoginAsync_end, {});
382
+ iframe.remove();
383
+ isResolved = true;
384
+ resolve(result);
385
+ }
386
+ else if (data.startsWith(key_error)) {
387
+ const result = JSON.parse(e.data.replace(key_error, ''));
388
+ self.publishEvent(eventNames.silentLoginAsync_error, result);
389
+ iframe.remove();
390
+ isResolved = true;
391
+ reject(new Error("oidc_" + result.error));
564
392
  }
565
393
  }
566
- };
567
- var silentSigninTimeout = configuration_1.silent_login_timeout;
568
- setTimeout(function () {
569
- if (!isResolved_1) {
570
- self_1.publishEvent(eventNames.silentLoginAsync_error, { reason: "timeout" });
571
- iframe_1.remove();
572
- isResolved_1 = true;
573
- reject(new Error("timeout"));
574
- }
575
- }, silentSigninTimeout);
394
+ }
576
395
  }
577
- catch (e) {
578
- iframe_1.remove();
579
- self_1.publishEvent(eventNames.silentLoginAsync_error, e);
580
- reject(e);
396
+ };
397
+ const silentSigninTimeout = configuration.silent_login_timeout;
398
+ setTimeout(() => {
399
+ if (!isResolved) {
400
+ self.publishEvent(eventNames.silentLoginAsync_error, { reason: "timeout" });
401
+ iframe.remove();
402
+ isResolved = true;
403
+ reject(new Error("timeout"));
581
404
  }
582
- })];
583
- }
584
- catch (e) {
585
- this.publishEvent(eventNames.silentLoginAsync_error, e);
586
- throw e;
405
+ }, silentSigninTimeout);
406
+ }
407
+ catch (e) {
408
+ iframe.remove();
409
+ self.publishEvent(eventNames.silentLoginAsync_error, e);
410
+ reject(e);
411
+ }
412
+ });
413
+ }
414
+ catch (e) {
415
+ this.publishEvent(eventNames.silentLoginAsync_error, e);
416
+ throw e;
417
+ }
418
+ });
419
+ }
420
+ initAsync(authority, authorityConfiguration) {
421
+ return __awaiter(this, void 0, void 0, function* () {
422
+ if (this.initPromise !== null) {
423
+ return this.initPromise;
424
+ }
425
+ const localFuncAsync = () => __awaiter(this, void 0, void 0, function* () {
426
+ var _a;
427
+ if (authorityConfiguration != null) {
428
+ return new OidcAuthorizationServiceConfiguration({
429
+ authorization_endpoint: authorityConfiguration.authorization_endpoint,
430
+ end_session_endpoint: authorityConfiguration.end_session_endpoint,
431
+ revocation_endpoint: authorityConfiguration.revocation_endpoint,
432
+ token_endpoint: authorityConfiguration.token_endpoint,
433
+ userinfo_endpoint: authorityConfiguration.userinfo_endpoint,
434
+ check_session_iframe: authorityConfiguration.check_session_iframe,
435
+ issuer: authorityConfiguration.issuer,
436
+ });
587
437
  }
588
- return [2 /*return*/];
438
+ const serviceWorker = yield initWorkerAsync(this.configuration.service_worker_relative_url, this.configurationName);
439
+ const storage = serviceWorker ? window.localStorage : null;
440
+ return yield fetchFromIssuer(authority, (_a = this.configuration.authority_time_cache_wellknowurl_in_second) !== null && _a !== void 0 ? _a : 60 * 60, storage);
441
+ });
442
+ this.initPromise = localFuncAsync();
443
+ return this.initPromise.then((result) => {
444
+ this.initPromise = null;
445
+ return result;
589
446
  });
590
447
  });
591
- };
592
- Oidc.prototype.initAsync = function (authority, authorityConfiguration) {
593
- return __awaiter(this, void 0, void 0, function () {
594
- var localFuncAsync;
595
- var _this = this;
596
- return __generator(this, function (_a) {
597
- if (this.initPromise !== null) {
598
- return [2 /*return*/, this.initPromise];
448
+ }
449
+ tryKeepExistingSessionAsync() {
450
+ return __awaiter(this, void 0, void 0, function* () {
451
+ if (this.tryKeepExistingSessionPromise !== null) {
452
+ return this.tryKeepExistingSessionPromise;
453
+ }
454
+ const funcAsync = () => __awaiter(this, void 0, void 0, function* () {
455
+ var _a;
456
+ let serviceWorker;
457
+ if (this.tokens != null) {
458
+ return false;
599
459
  }
600
- localFuncAsync = function () { return __awaiter(_this, void 0, void 0, function () {
601
- var serviceWorker, storage;
602
- var _a;
603
- return __generator(this, function (_b) {
604
- switch (_b.label) {
605
- case 0:
606
- if (authorityConfiguration != null) {
607
- return [2 /*return*/, new OidcAuthorizationServiceConfiguration({
608
- authorization_endpoint: authorityConfiguration.authorization_endpoint,
609
- end_session_endpoint: authorityConfiguration.end_session_endpoint,
610
- revocation_endpoint: authorityConfiguration.revocation_endpoint,
611
- token_endpoint: authorityConfiguration.token_endpoint,
612
- userinfo_endpoint: authorityConfiguration.userinfo_endpoint,
613
- check_session_iframe: authorityConfiguration.check_session_iframe,
614
- issuer: authorityConfiguration.issuer,
615
- })];
616
- }
617
- return [4 /*yield*/, (0, initWorker_1.initWorkerAsync)(this.configuration.service_worker_relative_url, this.configurationName)];
618
- case 1:
619
- serviceWorker = _b.sent();
620
- storage = serviceWorker ? window.localStorage : null;
621
- return [4 /*yield*/, fetchFromIssuer(authority, (_a = this.configuration.authority_time_cache_wellknowurl_in_second) !== null && _a !== void 0 ? _a : 60 * 60, storage)];
622
- case 2: return [2 /*return*/, _b.sent()];
460
+ this.publishEvent(eventNames.tryKeepExistingSessionAsync_begin, {});
461
+ try {
462
+ const configuration = this.configuration;
463
+ const oidcServerConfiguration = yield this.initAsync(configuration.authority, configuration.authority_configuration);
464
+ serviceWorker = yield initWorkerAsync(configuration.service_worker_relative_url, this.configurationName);
465
+ if (serviceWorker) {
466
+ const { tokens } = yield serviceWorker.initAsync(oidcServerConfiguration, "tryKeepExistingSessionAsync");
467
+ if (tokens) {
468
+ serviceWorker.startKeepAliveServiceWorker();
469
+ // @ts-ignore
470
+ this.tokens = tokens;
471
+ // @ts-ignore
472
+ this.timeoutId = autoRenewTokens(this, this.tokens.refreshToken, this.tokens.expiresAt);
473
+ const sessionState = yield serviceWorker.getSessionStateAsync();
474
+ // @ts-ignore
475
+ yield this.startCheckSessionAsync(oidcServerConfiguration.check_session_iframe, configuration.client_id, sessionState);
476
+ this.publishEvent(eventNames.tryKeepExistingSessionAsync_end, {
477
+ success: true,
478
+ message: "tokens inside ServiceWorker are valid"
479
+ });
480
+ return true;
481
+ }
482
+ this.publishEvent(eventNames.tryKeepExistingSessionAsync_end, {
483
+ success: false,
484
+ message: "no exiting session found"
485
+ });
486
+ }
487
+ else {
488
+ if (configuration.service_worker_relative_url) {
489
+ this.publishEvent(eventNames.service_worker_not_supported_by_browser, {
490
+ message: "service worker is not supported by this browser"
491
+ });
623
492
  }
493
+ const session = initSession(this.configurationName, configuration.redirect_uri, (_a = configuration.storage) !== null && _a !== void 0 ? _a : sessionStorage);
494
+ const { tokens } = yield session.initAsync();
495
+ if (tokens) {
496
+ // @ts-ignore
497
+ this.tokens = setTokens(tokens);
498
+ // @ts-ignore
499
+ this.timeoutId = autoRenewTokens(this, tokens.refreshToken, this.tokens.expiresAt);
500
+ const sessionState = session.getSessionState();
501
+ // @ts-ignore
502
+ yield this.startCheckSessionAsync(oidcServerConfiguration.check_session_iframe, configuration.client_id, sessionState);
503
+ this.publishEvent(eventNames.tryKeepExistingSessionAsync_end, {
504
+ success: true,
505
+ message: `tokens inside storage are valid`
506
+ });
507
+ return true;
508
+ }
509
+ }
510
+ this.publishEvent(eventNames.tryKeepExistingSessionAsync_end, {
511
+ success: false,
512
+ message: serviceWorker ? "service worker sessions not retrieved" : "session storage sessions not retrieved"
624
513
  });
625
- }); };
626
- this.initPromise = localFuncAsync();
627
- return [2 /*return*/, this.initPromise.then(function (result) {
628
- _this.initPromise = null;
629
- return result;
630
- })];
514
+ return false;
515
+ }
516
+ catch (exception) {
517
+ console.error(exception);
518
+ if (serviceWorker) {
519
+ yield serviceWorker.clearAsync();
520
+ }
521
+ this.publishEvent(eventNames.tryKeepExistingSessionAsync_error, "tokens inside ServiceWorker are invalid");
522
+ return false;
523
+ }
524
+ });
525
+ this.tryKeepExistingSessionPromise = funcAsync();
526
+ return this.tryKeepExistingSessionPromise.then((result) => {
527
+ this.tryKeepExistingSessionPromise = null;
528
+ return result;
631
529
  });
632
530
  });
633
- };
634
- Oidc.prototype.tryKeepExistingSessionAsync = function () {
635
- return __awaiter(this, void 0, void 0, function () {
636
- var funcAsync;
637
- var _this = this;
638
- return __generator(this, function (_a) {
639
- if (this.tryKeepExistingSessionPromise !== null) {
640
- return [2 /*return*/, this.tryKeepExistingSessionPromise];
531
+ }
532
+ loginAsync(callbackPath = undefined, extras = null, isSilentSignin = false, scope = undefined, silentLoginOnly = false) {
533
+ return __awaiter(this, void 0, void 0, function* () {
534
+ if (this.loginPromise !== null) {
535
+ return this.loginPromise;
536
+ }
537
+ const loginLocalAsync = () => __awaiter(this, void 0, void 0, function* () {
538
+ var _a, _b;
539
+ const location = window.location;
540
+ const url = callbackPath || location.pathname + (location.search || '') + (location.hash || '');
541
+ const configuration = this.configuration;
542
+ let state = undefined;
543
+ if (extras && "state" in extras) {
544
+ state = extras["state"];
545
+ delete extras["state"];
641
546
  }
642
- funcAsync = function () { return __awaiter(_this, void 0, void 0, function () {
643
- var serviceWorker, configuration, oidcServerConfiguration, tokens, sessionState, session, tokens, sessionState, exception_1;
644
- var _a;
645
- return __generator(this, function (_b) {
646
- switch (_b.label) {
647
- case 0:
648
- if (this.tokens != null) {
649
- return [2 /*return*/, false];
650
- }
651
- this.publishEvent(eventNames.tryKeepExistingSessionAsync_begin, {});
652
- _b.label = 1;
653
- case 1:
654
- _b.trys.push([1, 12, , 15]);
655
- configuration = this.configuration;
656
- return [4 /*yield*/, this.initAsync(configuration.authority, configuration.authority_configuration)];
657
- case 2:
658
- oidcServerConfiguration = _b.sent();
659
- return [4 /*yield*/, (0, initWorker_1.initWorkerAsync)(configuration.service_worker_relative_url, this.configurationName)];
660
- case 3:
661
- serviceWorker = _b.sent();
662
- if (!serviceWorker) return [3 /*break*/, 8];
663
- return [4 /*yield*/, serviceWorker.initAsync(oidcServerConfiguration, "tryKeepExistingSessionAsync")];
664
- case 4:
665
- tokens = (_b.sent()).tokens;
666
- if (!tokens) return [3 /*break*/, 7];
667
- serviceWorker.startKeepAliveServiceWorker();
668
- // @ts-ignore
669
- this.tokens = tokens;
670
- // @ts-ignore
671
- this.timeoutId = autoRenewTokens(this, this.tokens.refreshToken, this.tokens.expiresAt);
672
- return [4 /*yield*/, serviceWorker.getSessionStateAsync()];
673
- case 5:
674
- sessionState = _b.sent();
675
- // @ts-ignore
676
- return [4 /*yield*/, this.startCheckSessionAsync(oidcServerConfiguration.check_session_iframe, configuration.client_id, sessionState)];
677
- case 6:
678
- // @ts-ignore
679
- _b.sent();
680
- this.publishEvent(eventNames.tryKeepExistingSessionAsync_end, {
681
- success: true,
682
- message: "tokens inside ServiceWorker are valid"
683
- });
684
- return [2 /*return*/, true];
685
- case 7:
686
- this.publishEvent(eventNames.tryKeepExistingSessionAsync_end, {
687
- success: false,
688
- message: "no exiting session found"
689
- });
690
- return [3 /*break*/, 11];
691
- case 8:
692
- if (configuration.service_worker_relative_url) {
693
- this.publishEvent(eventNames.service_worker_not_supported_by_browser, {
694
- message: "service worker is not supported by this browser"
695
- });
696
- }
697
- session = (0, initSession_1.initSession)(this.configurationName, configuration.redirect_uri, (_a = configuration.storage) !== null && _a !== void 0 ? _a : sessionStorage);
698
- return [4 /*yield*/, session.initAsync()];
699
- case 9:
700
- tokens = (_b.sent()).tokens;
701
- if (!tokens) return [3 /*break*/, 11];
702
- // @ts-ignore
703
- this.tokens = (0, parseTokens_1.setTokens)(tokens);
704
- // @ts-ignore
705
- this.timeoutId = autoRenewTokens(this, tokens.refreshToken, this.tokens.expiresAt);
706
- sessionState = session.getSessionState();
707
- // @ts-ignore
708
- return [4 /*yield*/, this.startCheckSessionAsync(oidcServerConfiguration.check_session_iframe, configuration.client_id, sessionState)];
709
- case 10:
710
- // @ts-ignore
711
- _b.sent();
712
- this.publishEvent(eventNames.tryKeepExistingSessionAsync_end, {
713
- success: true,
714
- message: "tokens inside storage are valid"
715
- });
716
- return [2 /*return*/, true];
717
- case 11:
718
- this.publishEvent(eventNames.tryKeepExistingSessionAsync_end, {
719
- success: false,
720
- message: serviceWorker ? "service worker sessions not retrieved" : "session storage sessions not retrieved"
721
- });
722
- return [2 /*return*/, false];
723
- case 12:
724
- exception_1 = _b.sent();
725
- console.error(exception_1);
726
- if (!serviceWorker) return [3 /*break*/, 14];
727
- return [4 /*yield*/, serviceWorker.clearAsync()];
728
- case 13:
729
- _b.sent();
730
- _b.label = 14;
731
- case 14:
732
- this.publishEvent(eventNames.tryKeepExistingSessionAsync_error, "tokens inside ServiceWorker are invalid");
733
- return [2 /*return*/, false];
734
- case 15: return [2 /*return*/];
547
+ if (silentLoginOnly) {
548
+ try {
549
+ const extraFinal = (_a = extras !== null && extras !== void 0 ? extras : configuration.extras) !== null && _a !== void 0 ? _a : {};
550
+ const silentResult = yield this.silentLoginAsync(Object.assign(Object.assign({}, extraFinal), { prompt: "none" }), state, scope);
551
+ if (silentResult) {
552
+ this.tokens = silentResult.tokens;
553
+ this.publishEvent(eventNames.token_aquired, {});
554
+ // @ts-ignore
555
+ this.timeoutId = autoRenewTokens(this, this.tokens.refreshToken, this.tokens.expiresAt, extras);
556
+ return {};
735
557
  }
736
- });
737
- }); };
738
- this.tryKeepExistingSessionPromise = funcAsync();
739
- return [2 /*return*/, this.tryKeepExistingSessionPromise.then(function (result) {
740
- _this.tryKeepExistingSessionPromise = null;
741
- return result;
742
- })];
743
- });
744
- });
745
- };
746
- Oidc.prototype.loginAsync = function (callbackPath, extras, isSilentSignin, scope, silentLoginOnly) {
747
- if (callbackPath === void 0) { callbackPath = undefined; }
748
- if (extras === void 0) { extras = null; }
749
- if (isSilentSignin === void 0) { isSilentSignin = false; }
750
- if (scope === void 0) { scope = undefined; }
751
- if (silentLoginOnly === void 0) { silentLoginOnly = false; }
752
- return __awaiter(this, void 0, void 0, function () {
753
- var loginLocalAsync;
754
- var _this = this;
755
- return __generator(this, function (_a) {
756
- if (this.loginPromise !== null) {
757
- return [2 /*return*/, this.loginPromise];
558
+ }
559
+ catch (e) {
560
+ return e;
561
+ }
758
562
  }
759
- loginLocalAsync = function () { return __awaiter(_this, void 0, void 0, function () {
760
- var location, url, configuration, state, extraFinal, silentResult, e_2, redirectUri, randomString, extraFinal, nonce, serviceWorker, oidcServerConfiguration, storage, session, queryStringUtil, authorizationHandler, authRequest, exception_2;
761
- var _a, _b;
762
- return __generator(this, function (_c) {
763
- switch (_c.label) {
764
- case 0:
765
- location = window.location;
766
- url = callbackPath || location.pathname + (location.search || '') + (location.hash || '');
767
- configuration = this.configuration;
768
- state = undefined;
769
- if (extras && "state" in extras) {
770
- state = extras["state"];
771
- delete extras["state"];
772
- }
773
- if (!silentLoginOnly) return [3 /*break*/, 4];
774
- _c.label = 1;
775
- case 1:
776
- _c.trys.push([1, 3, , 4]);
777
- extraFinal = (_a = extras !== null && extras !== void 0 ? extras : configuration.extras) !== null && _a !== void 0 ? _a : {};
778
- return [4 /*yield*/, this.silentLoginAsync(__assign(__assign({}, extraFinal), { prompt: "none" }), state, scope)];
779
- case 2:
780
- silentResult = _c.sent();
781
- if (silentResult) {
782
- this.tokens = silentResult.tokens;
783
- this.publishEvent(eventNames.token_aquired, {});
784
- // @ts-ignore
785
- this.timeoutId = autoRenewTokens(this, this.tokens.refreshToken, this.tokens.expiresAt, extras);
786
- return [2 /*return*/, {}];
787
- }
788
- return [3 /*break*/, 4];
789
- case 3:
790
- e_2 = _c.sent();
791
- return [2 /*return*/, e_2];
792
- case 4:
793
- this.publishEvent(eventNames.loginAsync_begin, {});
794
- _c.label = 5;
795
- case 5:
796
- _c.trys.push([5, 14, , 15]);
797
- redirectUri = isSilentSignin ? configuration.silent_redirect_uri : configuration.redirect_uri;
798
- if (!scope) {
799
- scope = configuration.scope;
800
- }
801
- randomString = function (length) {
802
- var text = "";
803
- var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
804
- for (var i = 0; i < length; i++) {
805
- text += possible.charAt(Math.floor(Math.random() * possible.length));
806
- }
807
- return text;
808
- };
809
- setLoginParams(this.configurationName, redirectUri, { callbackPath: url, extras: extras, state: state });
810
- extraFinal = (_b = extras !== null && extras !== void 0 ? extras : configuration.extras) !== null && _b !== void 0 ? _b : {};
811
- if (!extraFinal.nonce) {
812
- extraFinal["nonce"] = randomString(12);
813
- }
814
- nonce = { "nonce": extraFinal.nonce };
815
- return [4 /*yield*/, (0, initWorker_1.initWorkerAsync)(configuration.service_worker_relative_url, this.configurationName)];
816
- case 6:
817
- serviceWorker = _c.sent();
818
- return [4 /*yield*/, this.initAsync(configuration.authority, configuration.authority_configuration)];
819
- case 7:
820
- oidcServerConfiguration = _c.sent();
821
- storage = void 0;
822
- if (!serviceWorker) return [3 /*break*/, 11];
823
- serviceWorker.startKeepAliveServiceWorker();
824
- return [4 /*yield*/, serviceWorker.initAsync(oidcServerConfiguration, "loginAsync")];
825
- case 8:
826
- _c.sent();
827
- return [4 /*yield*/, serviceWorker.setNonceAsync(nonce)];
828
- case 9:
829
- _c.sent();
830
- storage = new memoryStorageBackend_1.MemoryStorageBackend(serviceWorker.saveItemsAsync, {});
831
- return [4 /*yield*/, storage.setItem("dummy", {})];
832
- case 10:
833
- _c.sent();
834
- return [3 /*break*/, 13];
835
- case 11:
836
- session = (0, initSession_1.initSession)(this.configurationName, redirectUri);
837
- return [4 /*yield*/, session.setNonceAsync(nonce)];
838
- case 12:
839
- _c.sent();
840
- storage = new memoryStorageBackend_1.MemoryStorageBackend(session.saveItemsAsync, {});
841
- _c.label = 13;
842
- case 13:
843
- queryStringUtil = redirectUri.includes("#") ? new noHashQueryStringUtils_1.HashQueryStringUtils() : new noHashQueryStringUtils_1.NoHashQueryStringUtils();
844
- authorizationHandler = new appauth_1.RedirectRequestHandler(storage, queryStringUtil, window.location, new appauth_1.DefaultCrypto());
845
- authRequest = new appauth_1.AuthorizationRequest({
846
- client_id: configuration.client_id,
847
- redirect_uri: redirectUri,
848
- scope: scope,
849
- response_type: appauth_1.AuthorizationRequest.RESPONSE_TYPE_CODE,
850
- state: state,
851
- extras: extraFinal
852
- });
853
- authorizationHandler.performAuthorizationRequest(oidcServerConfiguration, authRequest);
854
- return [3 /*break*/, 15];
855
- case 14:
856
- exception_2 = _c.sent();
857
- this.publishEvent(eventNames.loginAsync_error, exception_2);
858
- throw exception_2;
859
- case 15: return [2 /*return*/];
563
+ this.publishEvent(eventNames.loginAsync_begin, {});
564
+ try {
565
+ const redirectUri = isSilentSignin ? configuration.silent_redirect_uri : configuration.redirect_uri;
566
+ if (!scope) {
567
+ scope = configuration.scope;
568
+ }
569
+ const randomString = function (length) {
570
+ let text = "";
571
+ const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
572
+ for (let i = 0; i < length; i++) {
573
+ text += possible.charAt(Math.floor(Math.random() * possible.length));
860
574
  }
575
+ return text;
576
+ };
577
+ setLoginParams(this.configurationName, redirectUri, { callbackPath: url, extras, state });
578
+ const extraFinal = (_b = extras !== null && extras !== void 0 ? extras : configuration.extras) !== null && _b !== void 0 ? _b : {};
579
+ if (!extraFinal.nonce) {
580
+ extraFinal["nonce"] = randomString(12);
581
+ }
582
+ const nonce = { "nonce": extraFinal.nonce };
583
+ let serviceWorker = yield initWorkerAsync(configuration.service_worker_relative_url, this.configurationName);
584
+ const oidcServerConfiguration = yield this.initAsync(configuration.authority, configuration.authority_configuration);
585
+ let storage;
586
+ if (serviceWorker) {
587
+ serviceWorker.startKeepAliveServiceWorker();
588
+ yield serviceWorker.initAsync(oidcServerConfiguration, "loginAsync");
589
+ yield serviceWorker.setNonceAsync(nonce);
590
+ storage = new MemoryStorageBackend(serviceWorker.saveItemsAsync, {});
591
+ yield storage.setItem("dummy", {});
592
+ }
593
+ else {
594
+ const session = initSession(this.configurationName, redirectUri);
595
+ yield session.setNonceAsync(nonce);
596
+ storage = new MemoryStorageBackend(session.saveItemsAsync, {});
597
+ }
598
+ // @ts-ignore
599
+ const queryStringUtil = redirectUri.includes("#") ? new HashQueryStringUtils() : new NoHashQueryStringUtils();
600
+ const authorizationHandler = new RedirectRequestHandler(storage, queryStringUtil, window.location, new DefaultCrypto());
601
+ const authRequest = new AuthorizationRequest({
602
+ client_id: configuration.client_id,
603
+ redirect_uri: redirectUri,
604
+ scope,
605
+ response_type: AuthorizationRequest.RESPONSE_TYPE_CODE,
606
+ state,
607
+ extras: extraFinal
861
608
  });
862
- }); };
863
- this.loginPromise = loginLocalAsync();
864
- return [2 /*return*/, this.loginPromise.then(function (result) {
865
- _this.loginPromise = null;
866
- return result;
867
- })];
609
+ authorizationHandler.performAuthorizationRequest(oidcServerConfiguration, authRequest);
610
+ }
611
+ catch (exception) {
612
+ this.publishEvent(eventNames.loginAsync_error, exception);
613
+ throw exception;
614
+ }
615
+ });
616
+ this.loginPromise = loginLocalAsync();
617
+ return this.loginPromise.then(result => {
618
+ this.loginPromise = null;
619
+ return result;
868
620
  });
869
621
  });
870
- };
871
- Oidc.prototype.startCheckSessionAsync = function (checkSessionIFrameUri, clientId, sessionState, isSilentSignin) {
872
- if (isSilentSignin === void 0) { isSilentSignin = false; }
873
- return __awaiter(this, void 0, void 0, function () {
874
- var _this = this;
875
- return __generator(this, function (_a) {
876
- return [2 /*return*/, new Promise(function (resolve, reject) {
877
- if (_this.configuration.silent_login_uri && _this.configuration.silent_redirect_uri && _this.configuration.monitor_session && checkSessionIFrameUri && sessionState && !isSilentSignin) {
878
- var checkSessionCallback = function () {
879
- _this.checkSessionIFrame.stop();
880
- if (_this.tokens === null) {
881
- return;
622
+ }
623
+ startCheckSessionAsync(checkSessionIFrameUri, clientId, sessionState, isSilentSignin = false) {
624
+ return __awaiter(this, void 0, void 0, function* () {
625
+ return new Promise((resolve, reject) => {
626
+ if (this.configuration.silent_login_uri && this.configuration.silent_redirect_uri && this.configuration.monitor_session && checkSessionIFrameUri && sessionState && !isSilentSignin) {
627
+ const checkSessionCallback = () => {
628
+ this.checkSessionIFrame.stop();
629
+ if (this.tokens === null) {
630
+ return;
631
+ }
632
+ // @ts-ignore
633
+ const idToken = this.tokens.idToken;
634
+ // @ts-ignore
635
+ const idTokenPayload = this.tokens.idTokenPayload;
636
+ this.silentLoginAsync({
637
+ prompt: "none",
638
+ id_token_hint: idToken,
639
+ scope: "openid"
640
+ }).then((silentSigninResponse) => {
641
+ const iFrameIdTokenPayload = silentSigninResponse.tokens.idTokenPayload;
642
+ if (idTokenPayload.sub === iFrameIdTokenPayload.sub) {
643
+ const sessionState = silentSigninResponse.sessionState;
644
+ this.checkSessionIFrame.start(silentSigninResponse.sessionState);
645
+ if (idTokenPayload.sid === iFrameIdTokenPayload.sid) {
646
+ console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:", sessionState);
882
647
  }
648
+ else {
649
+ console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:", sessionState);
650
+ }
651
+ }
652
+ else {
653
+ console.debug("SessionMonitor._callback: Different subject signed into OP:", iFrameIdTokenPayload.sub);
654
+ }
655
+ }).catch((e) => __awaiter(this, void 0, void 0, function* () {
656
+ for (const [key, oidc] of Object.entries(oidcDatabase)) {
657
+ //if(oidc !== this) {
883
658
  // @ts-ignore
884
- var idToken = _this.tokens.idToken;
885
- // @ts-ignore
886
- var idTokenPayload = _this.tokens.idTokenPayload;
887
- _this.silentLoginAsync({
888
- prompt: "none",
889
- id_token_hint: idToken,
890
- scope: "openid"
891
- }).then(function (silentSigninResponse) {
892
- var iFrameIdTokenPayload = silentSigninResponse.tokens.idTokenPayload;
893
- if (idTokenPayload.sub === iFrameIdTokenPayload.sub) {
894
- var sessionState_1 = silentSigninResponse.sessionState;
895
- _this.checkSessionIFrame.start(silentSigninResponse.sessionState);
896
- if (idTokenPayload.sid === iFrameIdTokenPayload.sid) {
897
- console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:", sessionState_1);
898
- }
899
- else {
900
- console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:", sessionState_1);
901
- }
902
- }
903
- else {
904
- console.debug("SessionMonitor._callback: Different subject signed into OP:", iFrameIdTokenPayload.sub);
905
- }
906
- }).catch(function (e) { return __awaiter(_this, void 0, void 0, function () {
907
- var _i, _a, _b, key, oidc;
908
- return __generator(this, function (_c) {
909
- switch (_c.label) {
910
- case 0:
911
- _i = 0, _a = Object.entries(oidcDatabase);
912
- _c.label = 1;
913
- case 1:
914
- if (!(_i < _a.length)) return [3 /*break*/, 4];
915
- _b = _a[_i], key = _b[0], oidc = _b[1];
916
- //if(oidc !== this) {
917
- // @ts-ignore
918
- return [4 /*yield*/, oidc.logoutOtherTabAsync(this.configuration.client_id, idTokenPayload.sub)];
919
- case 2:
920
- //if(oidc !== this) {
921
- // @ts-ignore
922
- _c.sent();
923
- _c.label = 3;
924
- case 3:
925
- _i++;
926
- return [3 /*break*/, 1];
927
- case 4: return [2 /*return*/];
928
- }
929
- });
930
- }); });
931
- };
932
- _this.checkSessionIFrame = new checkSessionIFrame_1.CheckSessionIFrame(checkSessionCallback, clientId, checkSessionIFrameUri);
933
- _this.checkSessionIFrame.load().then(function () {
934
- _this.checkSessionIFrame.start(sessionState);
935
- resolve();
936
- }).catch(function (e) {
937
- reject(e);
938
- });
939
- }
940
- else {
941
- resolve();
942
- }
943
- })];
659
+ yield oidc.logoutOtherTabAsync(this.configuration.client_id, idTokenPayload.sub);
660
+ //}
661
+ }
662
+ //await this.destroyAsync();
663
+ //this.publishEvent(eventNames.logout_from_another_tab, {message : "SessionMonitor"});
664
+ }));
665
+ };
666
+ this.checkSessionIFrame = new CheckSessionIFrame(checkSessionCallback, clientId, checkSessionIFrameUri);
667
+ this.checkSessionIFrame.load().then(() => {
668
+ this.checkSessionIFrame.start(sessionState);
669
+ resolve();
670
+ }).catch((e) => {
671
+ reject(e);
672
+ });
673
+ }
674
+ else {
675
+ resolve();
676
+ }
944
677
  });
945
678
  });
946
- };
947
- Oidc.prototype.loginCallbackAsync = function (isSilenSignin) {
948
- if (isSilenSignin === void 0) { isSilenSignin = false; }
949
- return __awaiter(this, void 0, void 0, function () {
950
- var loginCallbackLocalAsync;
951
- var _this = this;
952
- return __generator(this, function (_a) {
953
- if (this.loginCallbackPromise !== null) {
954
- return [2 /*return*/, this.loginCallbackPromise];
679
+ }
680
+ loginCallbackAsync(isSilenSignin = false) {
681
+ return __awaiter(this, void 0, void 0, function* () {
682
+ if (this.loginCallbackPromise !== null) {
683
+ return this.loginCallbackPromise;
684
+ }
685
+ const loginCallbackLocalAsync = () => __awaiter(this, void 0, void 0, function* () {
686
+ const response = yield this._loginCallbackAsync(isSilenSignin);
687
+ // @ts-ignore
688
+ const tokens = response.tokens;
689
+ const parsedTokens = setTokens(tokens);
690
+ this.tokens = parsedTokens;
691
+ const oidc = this;
692
+ const serviceWorker = yield initWorkerAsync(oidc.configuration.service_worker_relative_url, oidc.configurationName);
693
+ if (!serviceWorker) {
694
+ const session = initSession(this.configurationName, oidc.configuration.redirect_uri, oidc.configuration.storage);
695
+ yield session.setTokens(parsedTokens);
955
696
  }
956
- loginCallbackLocalAsync = function () { return __awaiter(_this, void 0, void 0, function () {
957
- var response, tokens, parsedTokens, oidc, serviceWorker, session;
958
- return __generator(this, function (_a) {
959
- switch (_a.label) {
960
- case 0: return [4 /*yield*/, this._loginCallbackAsync(isSilenSignin)];
961
- case 1:
962
- response = _a.sent();
963
- tokens = response.tokens;
964
- parsedTokens = (0, parseTokens_1.setTokens)(tokens);
965
- this.tokens = parsedTokens;
966
- oidc = this;
967
- return [4 /*yield*/, (0, initWorker_1.initWorkerAsync)(oidc.configuration.service_worker_relative_url, oidc.configurationName)];
968
- case 2:
969
- serviceWorker = _a.sent();
970
- if (!!serviceWorker) return [3 /*break*/, 4];
971
- session = (0, initSession_1.initSession)(this.configurationName, oidc.configuration.redirect_uri, oidc.configuration.storage);
972
- return [4 /*yield*/, session.setTokens(parsedTokens)];
973
- case 3:
974
- _a.sent();
975
- _a.label = 4;
976
- case 4:
977
- this.publishEvent(Oidc.eventNames.token_aquired, parsedTokens);
978
- // @ts-ignore
979
- return [2 /*return*/, { parsedTokens: parsedTokens, state: response.state, callbackPath: response.callbackPath }];
980
- }
981
- });
982
- }); };
983
- this.loginCallbackPromise = loginCallbackLocalAsync();
984
- return [2 /*return*/, this.loginCallbackPromise.then(function (result) {
985
- _this.loginCallbackPromise = null;
986
- return result;
987
- })];
697
+ this.publishEvent(Oidc.eventNames.token_aquired, parsedTokens);
698
+ // @ts-ignore
699
+ return { parsedTokens, state: response.state, callbackPath: response.callbackPath };
700
+ });
701
+ this.loginCallbackPromise = loginCallbackLocalAsync();
702
+ return this.loginCallbackPromise.then(result => {
703
+ this.loginCallbackPromise = null;
704
+ return result;
988
705
  });
989
706
  });
990
- };
991
- Oidc.prototype._loginCallbackAsync = function (isSilentSignin) {
992
- if (isSilentSignin === void 0) { isSilentSignin = false; }
993
- return __awaiter(this, void 0, void 0, function () {
994
- var configuration_2, clientId_1, redirectUri_1, authority, tokenRequestTimeout_1, oidcServerConfiguration_1, queryParams, sessionState_2, serviceWorker_1, storage_1, nonceData_1, items, dummy, session, items, exception_3;
995
- var _this = this;
996
- return __generator(this, function (_a) {
997
- switch (_a.label) {
998
- case 0:
999
- _a.trys.push([0, 13, , 14]);
1000
- this.publishEvent(eventNames.loginCallbackAsync_begin, {});
1001
- configuration_2 = this.configuration;
1002
- clientId_1 = configuration_2.client_id;
1003
- redirectUri_1 = isSilentSignin ? configuration_2.silent_redirect_uri : configuration_2.redirect_uri;
1004
- authority = configuration_2.authority;
1005
- tokenRequestTimeout_1 = configuration_2.token_request_timeout;
1006
- return [4 /*yield*/, this.initAsync(authority, configuration_2.authority_configuration)];
1007
- case 1:
1008
- oidcServerConfiguration_1 = _a.sent();
1009
- queryParams = (0, route_utils_1.getParseQueryStringFromLocation)(window.location.href);
1010
- sessionState_2 = queryParams.session_state;
1011
- return [4 /*yield*/, (0, initWorker_1.initWorkerAsync)(configuration_2.service_worker_relative_url, this.configurationName)];
1012
- case 2:
1013
- serviceWorker_1 = _a.sent();
1014
- storage_1 = null;
1015
- nonceData_1 = null;
1016
- if (!serviceWorker_1) return [3 /*break*/, 9];
1017
- serviceWorker_1.startKeepAliveServiceWorker();
1018
- return [4 /*yield*/, serviceWorker_1.initAsync(oidcServerConfiguration_1, "loginCallbackAsync")];
1019
- case 3:
1020
- _a.sent();
1021
- return [4 /*yield*/, serviceWorker_1.loadItemsAsync()];
1022
- case 4:
1023
- items = _a.sent();
1024
- storage_1 = new memoryStorageBackend_1.MemoryStorageBackend(serviceWorker_1.saveItemsAsync, items);
1025
- return [4 /*yield*/, storage_1.getItem("dummy")];
1026
- case 5:
1027
- dummy = _a.sent();
1028
- if (!dummy) {
1029
- throw new Error("Service Worker storage disapear");
707
+ }
708
+ _loginCallbackAsync(isSilentSignin = false) {
709
+ return __awaiter(this, void 0, void 0, function* () {
710
+ try {
711
+ this.publishEvent(eventNames.loginCallbackAsync_begin, {});
712
+ const configuration = this.configuration;
713
+ const clientId = configuration.client_id;
714
+ const redirectUri = isSilentSignin ? configuration.silent_redirect_uri : configuration.redirect_uri;
715
+ const authority = configuration.authority;
716
+ const tokenRequestTimeout = configuration.token_request_timeout;
717
+ const oidcServerConfiguration = yield this.initAsync(authority, configuration.authority_configuration);
718
+ const queryParams = getParseQueryStringFromLocation(window.location.href);
719
+ const sessionState = queryParams.session_state;
720
+ const serviceWorker = yield initWorkerAsync(configuration.service_worker_relative_url, this.configurationName);
721
+ let storage = null;
722
+ let nonceData = null;
723
+ if (serviceWorker) {
724
+ serviceWorker.startKeepAliveServiceWorker();
725
+ yield serviceWorker.initAsync(oidcServerConfiguration, "loginCallbackAsync");
726
+ const items = yield serviceWorker.loadItemsAsync();
727
+ storage = new MemoryStorageBackend(serviceWorker.saveItemsAsync, items);
728
+ const dummy = yield storage.getItem("dummy");
729
+ if (!dummy) {
730
+ throw new Error("Service Worker storage disapear");
731
+ }
732
+ yield storage.removeItem("dummy");
733
+ yield serviceWorker.setSessionStateAsync(sessionState);
734
+ nonceData = yield serviceWorker.getNonceAsync();
735
+ }
736
+ else {
737
+ const session = initSession(this.configurationName, redirectUri);
738
+ session.setSessionState(sessionState);
739
+ const items = yield session.loadItemsAsync();
740
+ storage = new MemoryStorageBackend(session.saveItemsAsync, items);
741
+ nonceData = yield session.getNonceAsync();
742
+ }
743
+ return new Promise((resolve, reject) => {
744
+ // @ts-ignore
745
+ let queryStringUtil = new NoHashQueryStringUtils();
746
+ if (redirectUri.includes("#")) {
747
+ const splithash = window.location.href.split("#");
748
+ if (splithash.length === 2 && splithash[1].includes("?")) {
749
+ queryStringUtil = new HashQueryStringUtils();
1030
750
  }
1031
- return [4 /*yield*/, storage_1.removeItem("dummy")];
1032
- case 6:
1033
- _a.sent();
1034
- return [4 /*yield*/, serviceWorker_1.setSessionStateAsync(sessionState_2)];
1035
- case 7:
1036
- _a.sent();
1037
- return [4 /*yield*/, serviceWorker_1.getNonceAsync()];
1038
- case 8:
1039
- nonceData_1 = _a.sent();
1040
- return [3 /*break*/, 12];
1041
- case 9:
1042
- session = (0, initSession_1.initSession)(this.configurationName, redirectUri_1);
1043
- session.setSessionState(sessionState_2);
1044
- return [4 /*yield*/, session.loadItemsAsync()];
1045
- case 10:
1046
- items = _a.sent();
1047
- storage_1 = new memoryStorageBackend_1.MemoryStorageBackend(session.saveItemsAsync, items);
1048
- return [4 /*yield*/, session.getNonceAsync()];
1049
- case 11:
1050
- nonceData_1 = _a.sent();
1051
- _a.label = 12;
1052
- case 12: return [2 /*return*/, new Promise(function (resolve, reject) {
1053
- // @ts-ignore
1054
- var queryStringUtil = new noHashQueryStringUtils_1.NoHashQueryStringUtils();
1055
- if (redirectUri_1.includes("#")) {
1056
- var splithash = window.location.href.split("#");
1057
- if (splithash.length === 2 && splithash[1].includes("?")) {
1058
- queryStringUtil = new noHashQueryStringUtils_1.HashQueryStringUtils();
751
+ }
752
+ // @ts-ignore
753
+ const authorizationHandler = new RedirectRequestHandler(storage, queryStringUtil, window.location, new DefaultCrypto());
754
+ const notifier = new AuthorizationNotifier();
755
+ authorizationHandler.setAuthorizationNotifier(notifier);
756
+ notifier.setAuthorizationListener((request, response, error) => {
757
+ if (error) {
758
+ reject(error);
759
+ return;
760
+ }
761
+ if (!response) {
762
+ reject("no response");
763
+ return;
764
+ }
765
+ let extras = null;
766
+ if (request && request.internal) {
767
+ extras = {};
768
+ extras.code_verifier = request.internal.code_verifier;
769
+ if (configuration.token_request_extras) {
770
+ for (let [key, value] of Object.entries(configuration.token_request_extras)) {
771
+ extras[key] = value;
1059
772
  }
1060
773
  }
1061
- // @ts-ignore
1062
- var authorizationHandler = new appauth_1.RedirectRequestHandler(storage_1, queryStringUtil, window.location, new appauth_1.DefaultCrypto());
1063
- var notifier = new appauth_1.AuthorizationNotifier();
1064
- authorizationHandler.setAuthorizationNotifier(notifier);
1065
- notifier.setAuthorizationListener(function (request, response, error) {
1066
- if (error) {
1067
- reject(error);
1068
- return;
1069
- }
1070
- if (!response) {
1071
- reject("no response");
1072
- return;
1073
- }
1074
- var extras = null;
1075
- if (request && request.internal) {
1076
- extras = {};
1077
- extras.code_verifier = request.internal.code_verifier;
1078
- if (configuration_2.token_request_extras) {
1079
- for (var _i = 0, _a = Object.entries(configuration_2.token_request_extras); _i < _a.length; _i++) {
1080
- var _b = _a[_i], key = _b[0], value = _b[1];
1081
- extras[key] = value;
774
+ }
775
+ const tokenRequest = new TokenRequest({
776
+ client_id: clientId,
777
+ redirect_uri: redirectUri,
778
+ grant_type: GRANT_TYPE_AUTHORIZATION_CODE,
779
+ code: response.code,
780
+ refresh_token: undefined,
781
+ extras,
782
+ });
783
+ let timeoutId = setTimeout(() => {
784
+ reject("performTokenRequest timeout");
785
+ timeoutId = null;
786
+ }, tokenRequestTimeout !== null && tokenRequestTimeout !== void 0 ? tokenRequestTimeout : 12000);
787
+ try {
788
+ const tokenHandler = new BaseTokenRequestHandler(new FetchRequestor());
789
+ tokenHandler.performTokenRequest(oidcServerConfiguration, tokenRequest).then((tokenResponse) => __awaiter(this, void 0, void 0, function* () {
790
+ if (timeoutId) {
791
+ clearTimeout(timeoutId);
792
+ this.timeoutId = null;
793
+ const loginParams = getLoginParams(this.configurationName, redirectUri);
794
+ if (serviceWorker) {
795
+ const { tokens } = yield serviceWorker.initAsync(oidcServerConfiguration, "syncTokensAsync");
796
+ tokenResponse = tokens;
797
+ }
798
+ if (!isTokensOidcValid(tokenResponse, nonceData.nonce, oidcServerConfiguration)) {
799
+ const exception = new Error("Tokens are not OpenID valid");
800
+ if (timeoutId) {
801
+ clearTimeout(timeoutId);
802
+ this.timeoutId = null;
803
+ this.publishEvent(eventNames.loginCallbackAsync_error, exception);
804
+ console.error(exception);
805
+ reject(exception);
1082
806
  }
1083
807
  }
1084
- }
1085
- var tokenRequest = new appauth_1.TokenRequest({
1086
- client_id: clientId_1,
1087
- redirect_uri: redirectUri_1,
1088
- grant_type: appauth_1.GRANT_TYPE_AUTHORIZATION_CODE,
1089
- code: response.code,
1090
- refresh_token: undefined,
1091
- extras: extras,
1092
- });
1093
- var timeoutId = setTimeout(function () {
1094
- reject("performTokenRequest timeout");
1095
- timeoutId = null;
1096
- }, tokenRequestTimeout_1 !== null && tokenRequestTimeout_1 !== void 0 ? tokenRequestTimeout_1 : 12000);
1097
- try {
1098
- var tokenHandler = new appauth_1.BaseTokenRequestHandler(new appauth_1.FetchRequestor());
1099
- tokenHandler.performTokenRequest(oidcServerConfiguration_1, tokenRequest).then(function (tokenResponse) { return __awaiter(_this, void 0, void 0, function () {
1100
- var loginParams_1, tokens, exception;
1101
- var _this = this;
1102
- return __generator(this, function (_a) {
1103
- switch (_a.label) {
1104
- case 0:
1105
- if (!timeoutId) return [3 /*break*/, 3];
1106
- clearTimeout(timeoutId);
1107
- this.timeoutId = null;
1108
- loginParams_1 = getLoginParams(this.configurationName, redirectUri_1);
1109
- if (!serviceWorker_1) return [3 /*break*/, 2];
1110
- return [4 /*yield*/, serviceWorker_1.initAsync(oidcServerConfiguration_1, "syncTokensAsync")];
1111
- case 1:
1112
- tokens = (_a.sent()).tokens;
1113
- tokenResponse = tokens;
1114
- _a.label = 2;
1115
- case 2:
1116
- if (!(0, parseTokens_1.isTokensOidcValid)(tokenResponse, nonceData_1.nonce, oidcServerConfiguration_1)) {
1117
- exception = new Error("Tokens are not OpenID valid");
1118
- if (timeoutId) {
1119
- clearTimeout(timeoutId);
1120
- this.timeoutId = null;
1121
- this.publishEvent(eventNames.loginCallbackAsync_error, exception);
1122
- console.error(exception);
1123
- reject(exception);
1124
- }
1125
- }
1126
- // @ts-ignore
1127
- this.startCheckSessionAsync(oidcServerConfiguration_1.check_session_iframe, clientId_1, sessionState_2, isSilentSignin).then(function () {
1128
- _this.publishEvent(eventNames.loginCallbackAsync_end, {});
1129
- resolve({
1130
- tokens: tokenResponse,
1131
- state: request.state,
1132
- callbackPath: loginParams_1.callbackPath,
1133
- });
1134
- });
1135
- _a.label = 3;
1136
- case 3: return [2 /*return*/];
1137
- }
808
+ // @ts-ignore
809
+ this.startCheckSessionAsync(oidcServerConfiguration.check_session_iframe, clientId, sessionState, isSilentSignin).then(() => {
810
+ this.publishEvent(eventNames.loginCallbackAsync_end, {});
811
+ resolve({
812
+ tokens: tokenResponse,
813
+ state: request.state,
814
+ callbackPath: loginParams.callbackPath,
1138
815
  });
1139
- }); });
1140
- }
1141
- catch (exception) {
1142
- if (timeoutId) {
1143
- clearTimeout(timeoutId);
1144
- _this.timeoutId = null;
1145
- _this.publishEvent(eventNames.loginCallbackAsync_error, exception);
1146
- console.error(exception);
1147
- reject(exception);
1148
- }
1149
- }
1150
- });
1151
- authorizationHandler.completeAuthorizationRequestIfPossible();
1152
- })];
1153
- case 13:
1154
- exception_3 = _a.sent();
1155
- console.error(exception_3);
1156
- this.publishEvent(eventNames.loginCallbackAsync_error, exception_3);
1157
- throw exception_3;
1158
- case 14: return [2 /*return*/];
1159
- }
1160
- });
1161
- });
1162
- };
1163
- Oidc.prototype.synchroniseTokensAsync = function (refreshToken, index, forceRefresh, extras) {
1164
- if (index === void 0) { index = 0; }
1165
- if (forceRefresh === void 0) { forceRefresh = false; }
1166
- if (extras === void 0) { extras = null; }
1167
- return __awaiter(this, void 0, void 0, function () {
1168
- var numberTryOnline, configuration, localsilentLoginAsync, _a, status_1, tokens, nonce, _b, clientId, redirectUri, authority, tokenExtras, finalExtras, details, oidcServerConfiguration, tokenResponse, exception_4;
1169
- var _this = this;
1170
- return __generator(this, function (_c) {
1171
- switch (_c.label) {
1172
- case 0:
1173
- if (!document.hidden) return [3 /*break*/, 3];
1174
- return [4 /*yield*/, (0, initWorker_1.sleepAsync)(1000)];
1175
- case 1:
1176
- _c.sent();
1177
- this.publishEvent(eventNames.refreshTokensAsync, { message: "wait because document is hidden" });
1178
- return [4 /*yield*/, this.synchroniseTokensAsync(refreshToken, index, forceRefresh)];
1179
- case 2: return [2 /*return*/, _c.sent()];
1180
- case 3:
1181
- numberTryOnline = 6;
1182
- _c.label = 4;
1183
- case 4:
1184
- if (!(!navigator.onLine && numberTryOnline > 0)) return [3 /*break*/, 6];
1185
- return [4 /*yield*/, (0, initWorker_1.sleepAsync)(1000)];
1186
- case 5:
1187
- _c.sent();
1188
- numberTryOnline--;
1189
- this.publishEvent(eventNames.refreshTokensAsync, { message: "wait because navigator is offline try ".concat(numberTryOnline) });
1190
- return [3 /*break*/, 4];
1191
- case 6:
1192
- if (!extras) {
1193
- extras = {};
1194
- }
1195
- configuration = this.configuration;
1196
- localsilentLoginAsync = function () { return __awaiter(_this, void 0, void 0, function () {
1197
- var loginParams, silent_token_response, exceptionSilent_1;
1198
- return __generator(this, function (_a) {
1199
- switch (_a.label) {
1200
- case 0:
1201
- _a.trys.push([0, 2, , 4]);
1202
- loginParams = getLoginParams(this.configurationName, configuration.redirect_uri);
1203
- return [4 /*yield*/, this.silentLoginAsync(__assign(__assign(__assign({}, loginParams.extras), extras), { prompt: "none" }), loginParams.state)];
1204
- case 1:
1205
- silent_token_response = _a.sent();
1206
- if (silent_token_response) {
1207
- this.publishEvent(Oidc.eventNames.token_renewed, {});
1208
- return [2 /*return*/, { tokens: silent_token_response.tokens, status: "LOGGED" }];
1209
- }
1210
- return [3 /*break*/, 4];
1211
- case 2:
1212
- exceptionSilent_1 = _a.sent();
1213
- console.error(exceptionSilent_1);
1214
- this.publishEvent(eventNames.refreshTokensAsync_silent_error, { message: "exceptionSilent", exception: exceptionSilent_1.message });
1215
- if (exceptionSilent_1 && exceptionSilent_1.message && exceptionSilent_1.message.startsWith("oidc")) {
1216
- this.publishEvent(eventNames.refreshTokensAsync_error, { message: "refresh token silent" });
1217
- return [2 /*return*/, { tokens: null, status: "SESSION_LOST" }];
1218
- }
1219
- return [4 /*yield*/, (0, initWorker_1.sleepAsync)(1000)];
1220
- case 3:
1221
- _a.sent();
1222
- throw exceptionSilent_1;
1223
- case 4:
1224
- this.publishEvent(eventNames.refreshTokensAsync_error, { message: "refresh token silent return" });
1225
- return [2 /*return*/, { tokens: null, status: "SESSION_LOST" }];
816
+ });
1226
817
  }
1227
- });
1228
- }); };
1229
- if (!(index <= 4)) return [3 /*break*/, 25];
1230
- _c.label = 7;
1231
- case 7:
1232
- _c.trys.push([7, 24, , 25]);
1233
- return [4 /*yield*/, this.syncTokensInfoAsync(configuration, this.configurationName, this.tokens, forceRefresh)];
1234
- case 8:
1235
- _a = _c.sent(), status_1 = _a.status, tokens = _a.tokens, nonce = _a.nonce;
1236
- _b = status_1;
1237
- switch (_b) {
1238
- case "SESSION_LOST": return [3 /*break*/, 9];
1239
- case "NOT_CONNECTED": return [3 /*break*/, 10];
1240
- case "TOKENS_VALID": return [3 /*break*/, 11];
1241
- case "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID": return [3 /*break*/, 12];
1242
- case "LOGOUT_FROM_ANOTHER_TAB": return [3 /*break*/, 13];
1243
- case "REQUIRE_SYNC_TOKENS": return [3 /*break*/, 14];
818
+ }));
1244
819
  }
1245
- return [3 /*break*/, 16];
1246
- case 9:
1247
- this.publishEvent(eventNames.refreshTokensAsync_error, { message: "refresh token session lost" });
1248
- return [2 /*return*/, { tokens: null, status: "SESSION_LOST" }];
1249
- case 10: return [2 /*return*/, { tokens: null, status: null }];
1250
- case 11: return [2 /*return*/, { tokens: tokens, status: "LOGGED_IN" }];
1251
- case 12:
1252
- this.publishEvent(Oidc.eventNames.token_renewed, {});
1253
- return [2 /*return*/, { tokens: tokens, status: "LOGGED_IN" }];
1254
- case 13:
1255
- this.publishEvent(eventNames.logout_from_another_tab, { "status": "session syncTokensAsync" });
1256
- return [2 /*return*/, { tokens: null, status: "LOGGED_OUT" }];
1257
- case 14:
1258
- this.publishEvent(eventNames.refreshTokensAsync_begin, { refreshToken: refreshToken, status: status_1, tryNumber: index });
1259
- return [4 /*yield*/, localsilentLoginAsync()];
1260
- case 15: return [2 /*return*/, _c.sent()];
1261
- case 16:
1262
- if (!!refreshToken) return [3 /*break*/, 18];
1263
- this.publishEvent(eventNames.refreshTokensAsync_begin, { refreshToken: refreshToken, tryNumber: index });
1264
- return [4 /*yield*/, localsilentLoginAsync()];
1265
- case 17: return [2 /*return*/, _c.sent()];
1266
- case 18:
1267
- this.publishEvent(eventNames.refreshTokensAsync_begin, { refreshToken: refreshToken, status: status_1, tryNumber: index });
1268
- clientId = configuration.client_id;
1269
- redirectUri = configuration.redirect_uri;
1270
- authority = configuration.authority;
1271
- tokenExtras = configuration.token_request_extras ? configuration.token_request_extras : {};
1272
- finalExtras = __assign(__assign({}, tokenExtras), extras);
1273
- details = {
1274
- client_id: clientId,
1275
- redirect_uri: redirectUri,
1276
- grant_type: appauth_1.GRANT_TYPE_REFRESH_TOKEN,
1277
- refresh_token: tokens.refreshToken,
1278
- };
1279
- return [4 /*yield*/, this.initAsync(authority, configuration.authority_configuration)];
1280
- case 19:
1281
- oidcServerConfiguration = _c.sent();
1282
- return [4 /*yield*/, performTokenRequestAsync(oidcServerConfiguration.tokenEndpoint, details, finalExtras, tokens)];
1283
- case 20:
1284
- tokenResponse = _c.sent();
1285
- if (!tokenResponse.success) return [3 /*break*/, 21];
1286
- if (!(0, parseTokens_1.isTokensOidcValid)(tokenResponse.data, nonce.nonce, oidcServerConfiguration)) {
1287
- this.publishEvent(eventNames.refreshTokensAsync_error, { message: "refresh token return not valid tokens" });
1288
- return [2 /*return*/, { tokens: null, status: "SESSION_LOST" }];
820
+ catch (exception) {
821
+ if (timeoutId) {
822
+ clearTimeout(timeoutId);
823
+ this.timeoutId = null;
824
+ this.publishEvent(eventNames.loginCallbackAsync_error, exception);
825
+ console.error(exception);
826
+ reject(exception);
827
+ }
1289
828
  }
1290
- this.publishEvent(eventNames.refreshTokensAsync_end, { success: tokenResponse.success });
829
+ });
830
+ authorizationHandler.completeAuthorizationRequestIfPossible();
831
+ });
832
+ }
833
+ catch (exception) {
834
+ console.error(exception);
835
+ this.publishEvent(eventNames.loginCallbackAsync_error, exception);
836
+ throw exception;
837
+ }
838
+ });
839
+ }
840
+ synchroniseTokensAsync(refreshToken, index = 0, forceRefresh = false, extras = null) {
841
+ return __awaiter(this, void 0, void 0, function* () {
842
+ if (document.hidden) {
843
+ yield sleepAsync(1000);
844
+ this.publishEvent(eventNames.refreshTokensAsync, { message: "wait because document is hidden" });
845
+ return yield this.synchroniseTokensAsync(refreshToken, index, forceRefresh);
846
+ }
847
+ let numberTryOnline = 6;
848
+ while (!navigator.onLine && numberTryOnline > 0) {
849
+ yield sleepAsync(1000);
850
+ numberTryOnline--;
851
+ this.publishEvent(eventNames.refreshTokensAsync, { message: `wait because navigator is offline try ${numberTryOnline}` });
852
+ }
853
+ if (!extras) {
854
+ extras = {};
855
+ }
856
+ const configuration = this.configuration;
857
+ const localsilentLoginAsync = () => __awaiter(this, void 0, void 0, function* () {
858
+ try {
859
+ const loginParams = getLoginParams(this.configurationName, configuration.redirect_uri);
860
+ const silent_token_response = yield this.silentLoginAsync(Object.assign(Object.assign(Object.assign({}, loginParams.extras), extras), { prompt: "none" }), loginParams.state);
861
+ if (silent_token_response) {
1291
862
  this.publishEvent(Oidc.eventNames.token_renewed, {});
1292
- return [2 /*return*/, { tokens: tokenResponse.data, status: "LOGGED_IN" }];
1293
- case 21:
1294
- this.publishEvent(eventNames.refreshTokensAsync_silent_error, {
1295
- message: "bad request",
1296
- tokenResponse: tokenResponse
1297
- });
1298
- return [4 /*yield*/, this.synchroniseTokensAsync(null, index + 1, forceRefresh)];
1299
- case 22: return [2 /*return*/, _c.sent()];
1300
- case 23: return [3 /*break*/, 25];
1301
- case 24:
1302
- exception_4 = _c.sent();
1303
- console.error(exception_4);
1304
- this.publishEvent(eventNames.refreshTokensAsync_silent_error, { message: "exception", exception: exception_4.message });
1305
- return [2 /*return*/, this.synchroniseTokensAsync(refreshToken, index + 1, forceRefresh)];
1306
- case 25:
1307
- this.publishEvent(eventNames.refreshTokensAsync_error, { message: "refresh token" });
1308
- return [2 /*return*/, { tokens: null, status: "SESSION_LOST" }];
863
+ return { tokens: silent_token_response.tokens, status: "LOGGED" };
864
+ }
865
+ }
866
+ catch (exceptionSilent) {
867
+ console.error(exceptionSilent);
868
+ this.publishEvent(eventNames.refreshTokensAsync_silent_error, { message: "exceptionSilent", exception: exceptionSilent.message });
869
+ if (exceptionSilent && exceptionSilent.message && exceptionSilent.message.startsWith("oidc")) {
870
+ this.publishEvent(eventNames.refreshTokensAsync_error, { message: `refresh token silent` });
871
+ return { tokens: null, status: "SESSION_LOST" };
872
+ }
873
+ yield sleepAsync(1000);
874
+ throw exceptionSilent;
1309
875
  }
876
+ this.publishEvent(eventNames.refreshTokensAsync_error, { message: `refresh token silent return` });
877
+ return { tokens: null, status: "SESSION_LOST" };
1310
878
  });
879
+ if (index <= 4) {
880
+ try {
881
+ const { status, tokens, nonce } = yield this.syncTokensInfoAsync(configuration, this.configurationName, this.tokens, forceRefresh);
882
+ switch (status) {
883
+ case "SESSION_LOST":
884
+ this.publishEvent(eventNames.refreshTokensAsync_error, { message: `refresh token session lost` });
885
+ return { tokens: null, status: "SESSION_LOST" };
886
+ case "NOT_CONNECTED":
887
+ return { tokens: null, status: null };
888
+ case "TOKENS_VALID":
889
+ return { tokens, status: "LOGGED_IN" };
890
+ case "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":
891
+ this.publishEvent(Oidc.eventNames.token_renewed, {});
892
+ return { tokens, status: "LOGGED_IN" };
893
+ case "LOGOUT_FROM_ANOTHER_TAB":
894
+ this.publishEvent(eventNames.logout_from_another_tab, { "status": "session syncTokensAsync" });
895
+ return { tokens: null, status: "LOGGED_OUT" };
896
+ case "REQUIRE_SYNC_TOKENS":
897
+ this.publishEvent(eventNames.refreshTokensAsync_begin, { refreshToken: refreshToken, status, tryNumber: index });
898
+ return yield localsilentLoginAsync();
899
+ default:
900
+ if (!refreshToken) {
901
+ this.publishEvent(eventNames.refreshTokensAsync_begin, { refreshToken: refreshToken, tryNumber: index });
902
+ return yield localsilentLoginAsync();
903
+ }
904
+ this.publishEvent(eventNames.refreshTokensAsync_begin, { refreshToken: refreshToken, status, tryNumber: index });
905
+ const clientId = configuration.client_id;
906
+ const redirectUri = configuration.redirect_uri;
907
+ const authority = configuration.authority;
908
+ const tokenExtras = configuration.token_request_extras ? configuration.token_request_extras : {};
909
+ let finalExtras = Object.assign(Object.assign({}, tokenExtras), extras);
910
+ const details = {
911
+ client_id: clientId,
912
+ redirect_uri: redirectUri,
913
+ grant_type: GRANT_TYPE_REFRESH_TOKEN,
914
+ refresh_token: tokens.refreshToken,
915
+ };
916
+ const oidcServerConfiguration = yield this.initAsync(authority, configuration.authority_configuration);
917
+ const tokenResponse = yield performTokenRequestAsync(oidcServerConfiguration.tokenEndpoint, details, finalExtras, tokens);
918
+ if (tokenResponse.success) {
919
+ if (!isTokensOidcValid(tokenResponse.data, nonce.nonce, oidcServerConfiguration)) {
920
+ this.publishEvent(eventNames.refreshTokensAsync_error, { message: `refresh token return not valid tokens` });
921
+ return { tokens: null, status: "SESSION_LOST" };
922
+ }
923
+ this.publishEvent(eventNames.refreshTokensAsync_end, { success: tokenResponse.success });
924
+ this.publishEvent(Oidc.eventNames.token_renewed, {});
925
+ return { tokens: tokenResponse.data, status: "LOGGED_IN" };
926
+ }
927
+ else {
928
+ this.publishEvent(eventNames.refreshTokensAsync_silent_error, {
929
+ message: "bad request",
930
+ tokenResponse: tokenResponse
931
+ });
932
+ return yield this.synchroniseTokensAsync(null, index + 1, forceRefresh);
933
+ }
934
+ }
935
+ }
936
+ catch (exception) {
937
+ console.error(exception);
938
+ this.publishEvent(eventNames.refreshTokensAsync_silent_error, { message: "exception", exception: exception.message });
939
+ return this.synchroniseTokensAsync(refreshToken, index + 1, forceRefresh);
940
+ }
941
+ }
942
+ this.publishEvent(eventNames.refreshTokensAsync_error, { message: `refresh token` });
943
+ return { tokens: null, status: "SESSION_LOST" };
1311
944
  });
1312
- };
1313
- Oidc.prototype.syncTokensInfoAsync = function (configuration, configurationName, currentTokens, forceRefresh) {
945
+ }
946
+ syncTokensInfoAsync(configuration, configurationName, currentTokens, forceRefresh = false) {
1314
947
  var _a;
1315
- if (forceRefresh === void 0) { forceRefresh = false; }
1316
- return __awaiter(this, void 0, void 0, function () {
1317
- var nullNonce, nonce, oidcServerConfiguration, serviceWorker, _b, status_2, tokens, timeLeft_1, status_3, nonce_1, session, _c, tokens, status_4, timeLeft_2, status_5, nonce_2, timeLeft, status;
1318
- return __generator(this, function (_d) {
1319
- switch (_d.label) {
1320
- case 0:
1321
- nullNonce = { nonce: null };
1322
- if (!currentTokens) {
1323
- return [2 /*return*/, { tokens: null, status: "NOT_CONNECTED", nonce: nullNonce }];
1324
- }
1325
- nonce = nullNonce;
1326
- return [4 /*yield*/, this.initAsync(configuration.authority, configuration.authority_configuration)];
1327
- case 1:
1328
- oidcServerConfiguration = _d.sent();
1329
- return [4 /*yield*/, (0, initWorker_1.initWorkerAsync)(configuration.service_worker_relative_url, configurationName)];
1330
- case 2:
1331
- serviceWorker = _d.sent();
1332
- if (!serviceWorker) return [3 /*break*/, 10];
1333
- return [4 /*yield*/, serviceWorker.initAsync(oidcServerConfiguration, "syncTokensAsync")];
1334
- case 3:
1335
- _b = _d.sent(), status_2 = _b.status, tokens = _b.tokens;
1336
- if (!(status_2 == "LOGGED_OUT")) return [3 /*break*/, 4];
1337
- return [2 /*return*/, { tokens: null, status: "LOGOUT_FROM_ANOTHER_TAB", nonce: nullNonce }];
1338
- case 4:
1339
- if (!(status_2 == "SESSIONS_LOST")) return [3 /*break*/, 5];
1340
- return [2 /*return*/, { tokens: null, status: "SESSIONS_LOST", nonce: nullNonce }];
1341
- case 5:
1342
- if (!(!status_2 || !tokens)) return [3 /*break*/, 6];
1343
- return [2 /*return*/, { tokens: null, status: "REQUIRE_SYNC_TOKENS", nonce: nullNonce }];
1344
- case 6:
1345
- if (!(tokens.issuedAt !== currentTokens.issuedAt)) return [3 /*break*/, 8];
1346
- timeLeft_1 = (0, parseTokens_1.computeTimeLeft)(configuration.refresh_time_before_tokens_expiration_in_second, tokens.expiresAt);
1347
- status_3 = (timeLeft_1 > 0) ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID";
1348
- return [4 /*yield*/, serviceWorker.getNonceAsync()];
1349
- case 7:
1350
- nonce_1 = _d.sent();
1351
- return [2 /*return*/, { tokens: tokens, status: status_3, nonce: nonce_1 }];
1352
- case 8: return [4 /*yield*/, serviceWorker.getNonceAsync()];
1353
- case 9:
1354
- nonce = _d.sent();
1355
- return [3 /*break*/, 17];
1356
- case 10:
1357
- session = (0, initSession_1.initSession)(configurationName, configuration.redirect_uri, (_a = configuration.storage) !== null && _a !== void 0 ? _a : sessionStorage);
1358
- return [4 /*yield*/, session.initAsync()];
1359
- case 11:
1360
- _c = _d.sent(), tokens = _c.tokens, status_4 = _c.status;
1361
- if (!!tokens) return [3 /*break*/, 12];
1362
- return [2 /*return*/, { tokens: null, status: "LOGOUT_FROM_ANOTHER_TAB", nonce: nullNonce }];
1363
- case 12:
1364
- if (!(status_4 == "SESSIONS_LOST")) return [3 /*break*/, 13];
1365
- return [2 /*return*/, { tokens: null, status: "SESSIONS_LOST", nonce: nullNonce }];
1366
- case 13:
1367
- if (!(tokens.issuedAt !== currentTokens.issuedAt)) return [3 /*break*/, 15];
1368
- timeLeft_2 = (0, parseTokens_1.computeTimeLeft)(configuration.refresh_time_before_tokens_expiration_in_second, tokens.expiresAt);
1369
- status_5 = (timeLeft_2 > 0) ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID";
1370
- return [4 /*yield*/, session.getNonceAsync()];
1371
- case 14:
1372
- nonce_2 = _d.sent();
1373
- return [2 /*return*/, { tokens: tokens, status: status_5, nonce: nonce_2 }];
1374
- case 15: return [4 /*yield*/, session.getNonceAsync()];
1375
- case 16:
1376
- nonce = _d.sent();
1377
- _d.label = 17;
1378
- case 17:
1379
- timeLeft = (0, parseTokens_1.computeTimeLeft)(configuration.refresh_time_before_tokens_expiration_in_second, currentTokens.expiresAt);
1380
- status = (timeLeft > 0) ? "TOKENS_VALID" : "TOKENS_INVALID";
1381
- if (forceRefresh) {
1382
- return [2 /*return*/, { tokens: currentTokens, status: "FORCE_REFRESH", nonce: nonce }];
1383
- }
1384
- return [2 /*return*/, { tokens: currentTokens, status: status, nonce: nonce }];
948
+ return __awaiter(this, void 0, void 0, function* () {
949
+ // Service Worker can be killed by the browser (when it wants,for example after 10 seconds of inactivity, so we retreieve the session if it happen)
950
+ //const configuration = this.configuration;
951
+ const nullNonce = { nonce: null };
952
+ if (!currentTokens) {
953
+ return { tokens: null, status: "NOT_CONNECTED", nonce: nullNonce };
954
+ }
955
+ let nonce = nullNonce;
956
+ const oidcServerConfiguration = yield this.initAsync(configuration.authority, configuration.authority_configuration);
957
+ const serviceWorker = yield initWorkerAsync(configuration.service_worker_relative_url, configurationName);
958
+ if (serviceWorker) {
959
+ const { status, tokens } = yield serviceWorker.initAsync(oidcServerConfiguration, "syncTokensAsync");
960
+ if (status == "LOGGED_OUT") {
961
+ return { tokens: null, status: "LOGOUT_FROM_ANOTHER_TAB", nonce: nullNonce };
1385
962
  }
1386
- });
963
+ else if (status == "SESSIONS_LOST") {
964
+ return { tokens: null, status: "SESSIONS_LOST", nonce: nullNonce };
965
+ }
966
+ else if (!status || !tokens) {
967
+ return { tokens: null, status: "REQUIRE_SYNC_TOKENS", nonce: nullNonce };
968
+ }
969
+ else if (tokens.issuedAt !== currentTokens.issuedAt) {
970
+ const timeLeft = computeTimeLeft(configuration.refresh_time_before_tokens_expiration_in_second, tokens.expiresAt);
971
+ const status = (timeLeft > 0) ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID";
972
+ const nonce = yield serviceWorker.getNonceAsync();
973
+ return { tokens: tokens, status, nonce };
974
+ }
975
+ nonce = yield serviceWorker.getNonceAsync();
976
+ }
977
+ else {
978
+ const session = initSession(configurationName, configuration.redirect_uri, (_a = configuration.storage) !== null && _a !== void 0 ? _a : sessionStorage);
979
+ const { tokens, status } = yield session.initAsync();
980
+ if (!tokens) {
981
+ return { tokens: null, status: "LOGOUT_FROM_ANOTHER_TAB", nonce: nullNonce };
982
+ }
983
+ else if (status == "SESSIONS_LOST") {
984
+ return { tokens: null, status: "SESSIONS_LOST", nonce: nullNonce };
985
+ }
986
+ else if (tokens.issuedAt !== currentTokens.issuedAt) {
987
+ const timeLeft = computeTimeLeft(configuration.refresh_time_before_tokens_expiration_in_second, tokens.expiresAt);
988
+ const status = (timeLeft > 0) ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID";
989
+ const nonce = yield session.getNonceAsync();
990
+ return { tokens: tokens, status, nonce };
991
+ }
992
+ nonce = yield session.getNonceAsync();
993
+ }
994
+ const timeLeft = computeTimeLeft(configuration.refresh_time_before_tokens_expiration_in_second, currentTokens.expiresAt);
995
+ const status = (timeLeft > 0) ? "TOKENS_VALID" : "TOKENS_INVALID";
996
+ if (forceRefresh) {
997
+ return { tokens: currentTokens, status: "FORCE_REFRESH", nonce };
998
+ }
999
+ return { tokens: currentTokens, status, nonce };
1387
1000
  });
1388
- };
1389
- Oidc.prototype.loginCallbackWithAutoTokensRenewAsync = function () {
1390
- var _this = this;
1001
+ }
1002
+ loginCallbackWithAutoTokensRenewAsync() {
1391
1003
  if (this.loginCallbackWithAutoTokensRenewPromise !== null) {
1392
1004
  return this.loginCallbackWithAutoTokensRenewPromise;
1393
1005
  }
1394
1006
  this.loginCallbackWithAutoTokensRenewPromise = loginCallbackWithAutoTokensRenewAsync(this);
1395
- return this.loginCallbackWithAutoTokensRenewPromise.then(function (result) {
1396
- _this.loginCallbackWithAutoTokensRenewPromise = null;
1007
+ return this.loginCallbackWithAutoTokensRenewPromise.then(result => {
1008
+ this.loginCallbackWithAutoTokensRenewPromise = null;
1397
1009
  return result;
1398
1010
  });
1399
- };
1400
- Oidc.prototype.userInfoAsync = function () {
1401
- var _this = this;
1011
+ }
1012
+ userInfoAsync() {
1402
1013
  if (this.userInfoPromise !== null) {
1403
1014
  return this.userInfoPromise;
1404
1015
  }
1405
1016
  this.userInfoPromise = userInfoAsync(this);
1406
- return this.userInfoPromise.then(function (result) {
1407
- _this.userInfoPromise = null;
1017
+ return this.userInfoPromise.then(result => {
1018
+ this.userInfoPromise = null;
1408
1019
  return result;
1409
1020
  });
1410
- };
1411
- Oidc.prototype.renewTokensAsync = function (extras) {
1412
- if (extras === void 0) { extras = null; }
1413
- return __awaiter(this, void 0, void 0, function () {
1414
- return __generator(this, function (_a) {
1415
- switch (_a.label) {
1416
- case 0:
1417
- if (!this.timeoutId) {
1418
- return [2 /*return*/];
1419
- }
1420
- timer_1.default.clearTimeout(this.timeoutId);
1421
- // @ts-ignore
1422
- return [4 /*yield*/, renewTokensAndStartTimerAsync(this, this.tokens.refreshToken, true, extras)];
1423
- case 1:
1424
- // @ts-ignore
1425
- _a.sent();
1426
- return [2 /*return*/];
1427
- }
1428
- });
1021
+ }
1022
+ renewTokensAsync(extras = null) {
1023
+ return __awaiter(this, void 0, void 0, function* () {
1024
+ if (!this.timeoutId) {
1025
+ return;
1026
+ }
1027
+ timer.clearTimeout(this.timeoutId);
1028
+ // @ts-ignore
1029
+ yield renewTokensAndStartTimerAsync(this, this.tokens.refreshToken, true, extras);
1429
1030
  });
1430
- };
1431
- Oidc.prototype.destroyAsync = function (status) {
1432
- return __awaiter(this, void 0, void 0, function () {
1433
- var oidc, serviceWorker, session;
1434
- return __generator(this, function (_a) {
1435
- switch (_a.label) {
1436
- case 0:
1437
- timer_1.default.clearTimeout(this.timeoutId);
1438
- this.timeoutId = null;
1439
- if (this.checkSessionIFrame) {
1440
- this.checkSessionIFrame.stop();
1441
- }
1442
- oidc = this;
1443
- return [4 /*yield*/, (0, initWorker_1.initWorkerAsync)(oidc.configuration.service_worker_relative_url, oidc.configurationName)];
1444
- case 1:
1445
- serviceWorker = _a.sent();
1446
- if (!!serviceWorker) return [3 /*break*/, 3];
1447
- session = (0, initSession_1.initSession)(this.configurationName, oidc.configuration.redirect_uri, oidc.configuration.storage);
1448
- return [4 /*yield*/, session.clearAsync(status)];
1449
- case 2:
1450
- _a.sent();
1451
- return [3 /*break*/, 5];
1452
- case 3: return [4 /*yield*/, serviceWorker.clearAsync(status)];
1453
- case 4:
1454
- _a.sent();
1455
- _a.label = 5;
1456
- case 5:
1457
- this.tokens = null;
1458
- this.userInfo = null;
1459
- return [2 /*return*/];
1460
- }
1461
- });
1031
+ }
1032
+ destroyAsync(status) {
1033
+ return __awaiter(this, void 0, void 0, function* () {
1034
+ timer.clearTimeout(this.timeoutId);
1035
+ this.timeoutId = null;
1036
+ if (this.checkSessionIFrame) {
1037
+ this.checkSessionIFrame.stop();
1038
+ }
1039
+ const oidc = this;
1040
+ const serviceWorker = yield initWorkerAsync(oidc.configuration.service_worker_relative_url, oidc.configurationName);
1041
+ if (!serviceWorker) {
1042
+ const session = initSession(this.configurationName, oidc.configuration.redirect_uri, oidc.configuration.storage);
1043
+ yield session.clearAsync(status);
1044
+ }
1045
+ else {
1046
+ yield serviceWorker.clearAsync(status);
1047
+ }
1048
+ this.tokens = null;
1049
+ this.userInfo = null;
1050
+ // this.events = [];
1462
1051
  });
1463
- };
1464
- Oidc.prototype.logoutSameTabAsync = function (clientId, sub) {
1465
- return __awaiter(this, void 0, void 0, function () {
1466
- return __generator(this, function (_a) {
1467
- switch (_a.label) {
1468
- case 0:
1469
- if (!(this.configuration.monitor_session && this.configuration.client_id === clientId && sub && this.tokens && this.tokens.idTokenPayload && this.tokens.idTokenPayload.sub === sub)) return [3 /*break*/, 2];
1470
- this.publishEvent(eventNames.logout_from_same_tab, { "message": sub });
1471
- return [4 /*yield*/, this.destroyAsync("LOGGED_OUT")];
1472
- case 1:
1473
- _a.sent();
1474
- _a.label = 2;
1475
- case 2: return [2 /*return*/];
1476
- }
1477
- });
1052
+ }
1053
+ logoutSameTabAsync(clientId, sub) {
1054
+ return __awaiter(this, void 0, void 0, function* () {
1055
+ // @ts-ignore
1056
+ if (this.configuration.monitor_session && this.configuration.client_id === clientId && sub && this.tokens && this.tokens.idTokenPayload && this.tokens.idTokenPayload.sub === sub) {
1057
+ this.publishEvent(eventNames.logout_from_same_tab, { "message": sub });
1058
+ yield this.destroyAsync("LOGGED_OUT");
1059
+ }
1478
1060
  });
1479
- };
1480
- Oidc.prototype.logoutOtherTabAsync = function (clientId, sub) {
1481
- return __awaiter(this, void 0, void 0, function () {
1482
- return __generator(this, function (_a) {
1483
- switch (_a.label) {
1484
- case 0:
1485
- if (!(this.configuration.monitor_session && this.configuration.client_id === clientId && sub && this.tokens && this.tokens.idTokenPayload && this.tokens.idTokenPayload.sub === sub)) return [3 /*break*/, 2];
1486
- return [4 /*yield*/, this.destroyAsync("LOGGED_OUT")];
1487
- case 1:
1488
- _a.sent();
1489
- this.publishEvent(eventNames.logout_from_another_tab, { message: "SessionMonitor", "sub": sub });
1490
- _a.label = 2;
1491
- case 2: return [2 /*return*/];
1492
- }
1493
- });
1061
+ }
1062
+ logoutOtherTabAsync(clientId, sub) {
1063
+ return __awaiter(this, void 0, void 0, function* () {
1064
+ // @ts-ignore
1065
+ if (this.configuration.monitor_session && this.configuration.client_id === clientId && sub && this.tokens && this.tokens.idTokenPayload && this.tokens.idTokenPayload.sub === sub) {
1066
+ yield this.destroyAsync("LOGGED_OUT");
1067
+ this.publishEvent(eventNames.logout_from_another_tab, { message: "SessionMonitor", "sub": sub });
1068
+ }
1494
1069
  });
1495
- };
1496
- Oidc.prototype.logoutAsync = function (callbackPathOrUrl, extras) {
1497
- if (callbackPathOrUrl === void 0) { callbackPathOrUrl = undefined; }
1498
- if (extras === void 0) { extras = null; }
1499
- return __awaiter(this, void 0, void 0, function () {
1500
- var configuration, oidcServerConfiguration, path, isUri, url, idToken, sub, _i, _a, _b, key, oidc, queryString, _c, _d, _e, key, value;
1501
- return __generator(this, function (_f) {
1502
- switch (_f.label) {
1503
- case 0:
1504
- configuration = this.configuration;
1505
- return [4 /*yield*/, this.initAsync(configuration.authority, configuration.authority_configuration)];
1506
- case 1:
1507
- oidcServerConfiguration = _f.sent();
1508
- if (callbackPathOrUrl && (typeof callbackPathOrUrl !== 'string')) {
1509
- callbackPathOrUrl = undefined;
1510
- console.warn('callbackPathOrUrl path is not a string');
1511
- }
1512
- path = (callbackPathOrUrl === null || callbackPathOrUrl === undefined) ? location.pathname + (location.search || '') + (location.hash || '') : callbackPathOrUrl;
1513
- isUri = false;
1514
- if (callbackPathOrUrl) {
1515
- isUri = callbackPathOrUrl.includes("https://") || callbackPathOrUrl.includes("http://");
1516
- }
1517
- url = isUri ? callbackPathOrUrl : window.location.origin + path;
1518
- idToken = this.tokens ? this.tokens.idToken : "";
1519
- sub = this.tokens && this.tokens.idTokenPayload ? this.tokens.idTokenPayload.sub : null;
1520
- return [4 /*yield*/, this.destroyAsync("LOGGED_OUT")];
1521
- case 2:
1522
- _f.sent();
1523
- _i = 0, _a = Object.entries(oidcDatabase);
1524
- _f.label = 3;
1525
- case 3:
1526
- if (!(_i < _a.length)) return [3 /*break*/, 6];
1527
- _b = _a[_i], key = _b[0], oidc = _b[1];
1528
- if (!(oidc !== this)) return [3 /*break*/, 5];
1529
- // @ts-ignore
1530
- return [4 /*yield*/, oidc.logoutSameTabAsync(this.configuration.client_id, sub)];
1531
- case 4:
1532
- // @ts-ignore
1533
- _f.sent();
1534
- _f.label = 5;
1535
- case 5:
1536
- _i++;
1537
- return [3 /*break*/, 3];
1538
- case 6:
1539
- if (oidcServerConfiguration.endSessionEndpoint) {
1540
- if (!extras) {
1541
- extras = {
1542
- id_token_hint: idToken
1543
- };
1544
- if (callbackPathOrUrl !== null) {
1545
- extras["post_logout_redirect_uri"] = url;
1546
- }
1547
- }
1548
- queryString = "";
1549
- if (extras) {
1550
- for (_c = 0, _d = Object.entries(extras); _c < _d.length; _c++) {
1551
- _e = _d[_c], key = _e[0], value = _e[1];
1552
- if (queryString === "") {
1553
- queryString += "?";
1554
- }
1555
- else {
1556
- queryString += "&";
1557
- }
1558
- queryString += "".concat(key, "=").concat(encodeURIComponent(value));
1559
- }
1560
- }
1561
- window.location.href = "".concat(oidcServerConfiguration.endSessionEndpoint).concat(queryString);
1070
+ }
1071
+ logoutAsync(callbackPathOrUrl = undefined, extras = null) {
1072
+ return __awaiter(this, void 0, void 0, function* () {
1073
+ const configuration = this.configuration;
1074
+ const oidcServerConfiguration = yield this.initAsync(configuration.authority, configuration.authority_configuration);
1075
+ if (callbackPathOrUrl && (typeof callbackPathOrUrl !== 'string')) {
1076
+ callbackPathOrUrl = undefined;
1077
+ console.warn('callbackPathOrUrl path is not a string');
1078
+ }
1079
+ const path = (callbackPathOrUrl === null || callbackPathOrUrl === undefined) ? location.pathname + (location.search || '') + (location.hash || '') : callbackPathOrUrl;
1080
+ let isUri = false;
1081
+ if (callbackPathOrUrl) {
1082
+ isUri = callbackPathOrUrl.includes("https://") || callbackPathOrUrl.includes("http://");
1083
+ }
1084
+ const url = isUri ? callbackPathOrUrl : window.location.origin + path;
1085
+ // @ts-ignore
1086
+ const idToken = this.tokens ? this.tokens.idToken : "";
1087
+ // @ts-ignore
1088
+ const sub = this.tokens && this.tokens.idTokenPayload ? this.tokens.idTokenPayload.sub : null;
1089
+ yield this.destroyAsync("LOGGED_OUT");
1090
+ for (const [key, oidc] of Object.entries(oidcDatabase)) {
1091
+ if (oidc !== this) {
1092
+ // @ts-ignore
1093
+ yield oidc.logoutSameTabAsync(this.configuration.client_id, sub);
1094
+ }
1095
+ }
1096
+ if (oidcServerConfiguration.endSessionEndpoint) {
1097
+ if (!extras) {
1098
+ extras = {
1099
+ id_token_hint: idToken
1100
+ };
1101
+ if (callbackPathOrUrl !== null) {
1102
+ extras["post_logout_redirect_uri"] = url;
1103
+ }
1104
+ }
1105
+ let queryString = "";
1106
+ if (extras) {
1107
+ for (let [key, value] of Object.entries(extras)) {
1108
+ if (queryString === "") {
1109
+ queryString += "?";
1562
1110
  }
1563
1111
  else {
1564
- window.location.reload();
1112
+ queryString += "&";
1565
1113
  }
1566
- return [2 /*return*/];
1114
+ queryString += `${key}=${encodeURIComponent(value)}`;
1115
+ }
1567
1116
  }
1568
- });
1117
+ window.location.href = `${oidcServerConfiguration.endSessionEndpoint}${queryString}`;
1118
+ }
1119
+ else {
1120
+ window.location.reload();
1121
+ }
1569
1122
  });
1570
- };
1571
- Oidc.eventNames = eventNames;
1572
- return Oidc;
1573
- }());
1574
- exports.Oidc = Oidc;
1575
- exports.default = Oidc;
1123
+ }
1124
+ }
1125
+ Oidc.eventNames = eventNames;
1126
+ export default Oidc;
1576
1127
  //# sourceMappingURL=oidc.js.map