@ghentcdh/authentication-vue 0.0.2-4 → 0.0.2-6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs ADDED
@@ -0,0 +1,964 @@
1
+ import { defineStore as G } from "pinia";
2
+ import { shallowRef as oe, ref as F, watch as ae } from "vue";
3
+ function q(k) {
4
+ if (!(this instanceof q))
5
+ throw new Error("The 'Keycloak' constructor must be invoked with 'new'.");
6
+ if (typeof k != "string" && !O(k))
7
+ throw new Error("The 'Keycloak' constructor must be provided with a configuration object, or a URL to a JSON configuration file.");
8
+ if (O(k)) {
9
+ const r = "oidcProvider" in k ? ["clientId"] : ["url", "realm", "clientId"];
10
+ for (const t of r)
11
+ if (!k[t])
12
+ throw new Error(`The configuration object is missing the required '${t}' property.`);
13
+ }
14
+ var e = this, p, m = [], l, h = {
15
+ enable: !0,
16
+ callbackList: [],
17
+ interval: 5
18
+ };
19
+ e.didInitialize = !1;
20
+ var b = !0, w = Y(console.info), A = Y(console.warn);
21
+ globalThis.isSecureContext || A(
22
+ `[KEYCLOAK] Keycloak JS must be used in a 'secure context' to function properly as it relies on browser APIs that are otherwise not available.
23
+ Continuing to run your application insecurely will lead to unexpected behavior and breakage.
24
+
25
+ For more information see: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts`
26
+ ), e.init = function(r = {}) {
27
+ if (e.didInitialize)
28
+ throw new Error("A 'Keycloak' instance can only be initialized once.");
29
+ e.didInitialize = !0, e.authenticated = !1, l = ne();
30
+ var t = ["default", "cordova", "cordova-native"];
31
+ if (t.indexOf(r.adapter) > -1 ? p = M(r.adapter) : typeof r.adapter == "object" ? p = r.adapter : window.Cordova || window.cordova ? p = M("cordova") : p = M(), typeof r.useNonce < "u" && (b = r.useNonce), typeof r.checkLoginIframe < "u" && (h.enable = r.checkLoginIframe), r.checkLoginIframeInterval && (h.interval = r.checkLoginIframeInterval), r.onLoad === "login-required" && (e.loginRequired = !0), r.responseMode)
32
+ if (r.responseMode === "query" || r.responseMode === "fragment")
33
+ e.responseMode = r.responseMode;
34
+ else
35
+ throw "Invalid value for responseMode";
36
+ if (r.flow) {
37
+ switch (r.flow) {
38
+ case "standard":
39
+ e.responseType = "code";
40
+ break;
41
+ case "implicit":
42
+ e.responseType = "id_token token";
43
+ break;
44
+ case "hybrid":
45
+ e.responseType = "code id_token token";
46
+ break;
47
+ default:
48
+ throw "Invalid value for flow";
49
+ }
50
+ e.flow = r.flow;
51
+ }
52
+ if (r.timeSkew != null && (e.timeSkew = r.timeSkew), r.redirectUri && (e.redirectUri = r.redirectUri), r.silentCheckSsoRedirectUri && (e.silentCheckSsoRedirectUri = r.silentCheckSsoRedirectUri), typeof r.silentCheckSsoFallback == "boolean" ? e.silentCheckSsoFallback = r.silentCheckSsoFallback : e.silentCheckSsoFallback = !0, typeof r.pkceMethod < "u") {
53
+ if (r.pkceMethod !== "S256" && r.pkceMethod !== !1)
54
+ throw new TypeError(`Invalid value for pkceMethod', expected 'S256' or false but got ${r.pkceMethod}.`);
55
+ e.pkceMethod = r.pkceMethod;
56
+ } else
57
+ e.pkceMethod = "S256";
58
+ typeof r.enableLogging == "boolean" ? e.enableLogging = r.enableLogging : e.enableLogging = !1, r.logoutMethod === "POST" ? e.logoutMethod = "POST" : e.logoutMethod = "GET", typeof r.scope == "string" && (e.scope = r.scope), typeof r.acrValues == "string" && (e.acrValues = r.acrValues), typeof r.messageReceiveTimeout == "number" && r.messageReceiveTimeout > 0 ? e.messageReceiveTimeout = r.messageReceiveTimeout : e.messageReceiveTimeout = 1e4, e.responseMode || (e.responseMode = "fragment"), e.responseType || (e.responseType = "code", e.flow = "standard");
59
+ var i = v(), s = v();
60
+ s.promise.then(function() {
61
+ e.onReady && e.onReady(e.authenticated), i.setSuccess(e.authenticated);
62
+ }).catch(function(o) {
63
+ i.setError(o);
64
+ });
65
+ var a = Z();
66
+ function c() {
67
+ var o = function(d) {
68
+ d || (f.prompt = "none"), r.locale && (f.locale = r.locale), e.login(f).then(function() {
69
+ s.setSuccess();
70
+ }).catch(function(g) {
71
+ s.setError(g);
72
+ });
73
+ }, u = async function() {
74
+ var d = document.createElement("iframe"), g = await e.createLoginUrl({ prompt: "none", redirectUri: e.silentCheckSsoRedirectUri });
75
+ d.setAttribute("src", g), d.setAttribute("sandbox", "allow-storage-access-by-user-activation allow-scripts allow-same-origin"), d.setAttribute("title", "keycloak-silent-check-sso"), d.style.display = "none", document.body.appendChild(d);
76
+ var y = function(T) {
77
+ if (!(T.origin !== window.location.origin || d.contentWindow !== T.source)) {
78
+ var S = E(T.data);
79
+ U(S, s), document.body.removeChild(d), window.removeEventListener("message", y);
80
+ }
81
+ };
82
+ window.addEventListener("message", y);
83
+ }, f = {};
84
+ switch (r.onLoad) {
85
+ case "check-sso":
86
+ h.enable ? x().then(function() {
87
+ L().then(function(d) {
88
+ d ? s.setSuccess() : e.silentCheckSsoRedirectUri ? u() : o(!1);
89
+ }).catch(function(d) {
90
+ s.setError(d);
91
+ });
92
+ }) : e.silentCheckSsoRedirectUri ? u() : o(!1);
93
+ break;
94
+ case "login-required":
95
+ o(!0);
96
+ break;
97
+ default:
98
+ throw "Invalid value for onLoad";
99
+ }
100
+ }
101
+ function n() {
102
+ var o = E(window.location.href);
103
+ if (o && window.history.replaceState(window.history.state, null, o.newUrl), o && o.valid)
104
+ return x().then(function() {
105
+ U(o, s);
106
+ }).catch(function(u) {
107
+ s.setError(u);
108
+ });
109
+ r.token && r.refreshToken ? (C(r.token, r.refreshToken, r.idToken), h.enable ? x().then(function() {
110
+ L().then(function(u) {
111
+ u ? (e.onAuthSuccess && e.onAuthSuccess(), s.setSuccess(), P()) : s.setSuccess();
112
+ }).catch(function(u) {
113
+ s.setError(u);
114
+ });
115
+ }) : e.updateToken(-1).then(function() {
116
+ e.onAuthSuccess && e.onAuthSuccess(), s.setSuccess();
117
+ }).catch(function(u) {
118
+ e.onAuthError && e.onAuthError(), r.onLoad ? c() : s.setError(u);
119
+ })) : r.onLoad ? c() : s.setSuccess();
120
+ }
121
+ return a.then(function() {
122
+ te().then(n).catch(function(o) {
123
+ i.setError(o);
124
+ });
125
+ }), a.catch(function(o) {
126
+ i.setError(o);
127
+ }), i.promise;
128
+ }, e.login = function(r) {
129
+ return p.login(r);
130
+ };
131
+ function R(r) {
132
+ if (typeof crypto > "u" || typeof crypto.getRandomValues > "u")
133
+ throw new Error("Web Crypto API is not available.");
134
+ return crypto.getRandomValues(new Uint8Array(r));
135
+ }
136
+ function B(r) {
137
+ return X(r, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
138
+ }
139
+ function X(r, t) {
140
+ for (var i = R(r), s = new Array(r), a = 0; a < r; a++)
141
+ s[a] = t.charCodeAt(i[a] % t.length);
142
+ return String.fromCharCode.apply(null, s);
143
+ }
144
+ async function W(r, t) {
145
+ if (r !== "S256")
146
+ throw new TypeError(`Invalid value for 'pkceMethod', expected 'S256' but got '${r}'.`);
147
+ const i = new Uint8Array(await ie(t));
148
+ return se(i).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=/g, "");
149
+ }
150
+ function $(r) {
151
+ var t = {
152
+ id_token: {
153
+ acr: r
154
+ }
155
+ };
156
+ return JSON.stringify(t);
157
+ }
158
+ e.createLoginUrl = async function(r) {
159
+ var t = V(), i = V(), s = p.redirectUri(r), a = {
160
+ state: t,
161
+ nonce: i,
162
+ redirectUri: encodeURIComponent(s),
163
+ loginOptions: r
164
+ };
165
+ r && r.prompt && (a.prompt = r.prompt);
166
+ var c;
167
+ r && r.action == "register" ? c = e.endpoints.register() : c = e.endpoints.authorize();
168
+ var n = r && r.scope || e.scope;
169
+ n ? n.indexOf("openid") === -1 && (n = "openid " + n) : n = "openid";
170
+ var o = c + "?client_id=" + encodeURIComponent(e.clientId) + "&redirect_uri=" + encodeURIComponent(s) + "&state=" + encodeURIComponent(t) + "&response_mode=" + encodeURIComponent(e.responseMode) + "&response_type=" + encodeURIComponent(e.responseType) + "&scope=" + encodeURIComponent(n);
171
+ if (b && (o = o + "&nonce=" + encodeURIComponent(i)), r && r.prompt && (o += "&prompt=" + encodeURIComponent(r.prompt)), r && typeof r.maxAge == "number" && (o += "&max_age=" + encodeURIComponent(r.maxAge)), r && r.loginHint && (o += "&login_hint=" + encodeURIComponent(r.loginHint)), r && r.idpHint && (o += "&kc_idp_hint=" + encodeURIComponent(r.idpHint)), r && r.action && r.action != "register" && (o += "&kc_action=" + encodeURIComponent(r.action)), r && r.locale && (o += "&ui_locales=" + encodeURIComponent(r.locale)), r && r.acr) {
172
+ var u = $(r.acr);
173
+ o += "&claims=" + encodeURIComponent(u);
174
+ }
175
+ if ((r && r.acrValues || e.acrValues) && (o += "&acr_values=" + encodeURIComponent(r.acrValues || e.acrValues)), e.pkceMethod)
176
+ try {
177
+ const f = B(96), d = await W(e.pkceMethod, f);
178
+ a.pkceCodeVerifier = f, o += "&code_challenge=" + d, o += "&code_challenge_method=" + e.pkceMethod;
179
+ } catch (f) {
180
+ throw new Error("Failed to generate PKCE challenge.", { cause: f });
181
+ }
182
+ return l.add(a), o;
183
+ }, e.logout = function(r) {
184
+ return p.logout(r);
185
+ }, e.createLogoutUrl = function(r) {
186
+ if (((r == null ? void 0 : r.logoutMethod) ?? e.logoutMethod) === "POST")
187
+ return e.endpoints.logout();
188
+ var i = e.endpoints.logout() + "?client_id=" + encodeURIComponent(e.clientId) + "&post_logout_redirect_uri=" + encodeURIComponent(p.redirectUri(r, !1));
189
+ return e.idToken && (i += "&id_token_hint=" + encodeURIComponent(e.idToken)), i;
190
+ }, e.register = function(r) {
191
+ return p.register(r);
192
+ }, e.createRegisterUrl = async function(r) {
193
+ return r || (r = {}), r.action = "register", await e.createLoginUrl(r);
194
+ }, e.createAccountUrl = function(r) {
195
+ var t = _(), i = void 0;
196
+ return typeof t < "u" && (i = t + "/account?referrer=" + encodeURIComponent(e.clientId) + "&referrer_uri=" + encodeURIComponent(p.redirectUri(r))), i;
197
+ }, e.accountManagement = function() {
198
+ return p.accountManagement();
199
+ }, e.hasRealmRole = function(r) {
200
+ var t = e.realmAccess;
201
+ return !!t && t.roles.indexOf(r) >= 0;
202
+ }, e.hasResourceRole = function(r, t) {
203
+ if (!e.resourceAccess)
204
+ return !1;
205
+ var i = e.resourceAccess[t || e.clientId];
206
+ return !!i && i.roles.indexOf(r) >= 0;
207
+ }, e.loadUserProfile = function() {
208
+ var r = _() + "/account", t = new XMLHttpRequest();
209
+ t.open("GET", r, !0), t.setRequestHeader("Accept", "application/json"), t.setRequestHeader("Authorization", "bearer " + e.token);
210
+ var i = v();
211
+ return t.onreadystatechange = function() {
212
+ t.readyState == 4 && (t.status == 200 ? (e.profile = JSON.parse(t.responseText), i.setSuccess(e.profile)) : i.setError());
213
+ }, t.send(), i.promise;
214
+ }, e.loadUserInfo = function() {
215
+ var r = e.endpoints.userinfo(), t = new XMLHttpRequest();
216
+ t.open("GET", r, !0), t.setRequestHeader("Accept", "application/json"), t.setRequestHeader("Authorization", "bearer " + e.token);
217
+ var i = v();
218
+ return t.onreadystatechange = function() {
219
+ t.readyState == 4 && (t.status == 200 ? (e.userInfo = JSON.parse(t.responseText), i.setSuccess(e.userInfo)) : i.setError());
220
+ }, t.send(), i.promise;
221
+ }, e.isTokenExpired = function(r) {
222
+ if (!e.tokenParsed || !e.refreshToken && e.flow != "implicit")
223
+ throw "Not authenticated";
224
+ if (e.timeSkew == null)
225
+ return w("[KEYCLOAK] Unable to determine if token is expired as timeskew is not set"), !0;
226
+ var t = e.tokenParsed.exp - Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3) + e.timeSkew;
227
+ if (r) {
228
+ if (isNaN(r))
229
+ throw "Invalid minValidity";
230
+ t -= r;
231
+ }
232
+ return t < 0;
233
+ }, e.updateToken = function(r) {
234
+ var t = v();
235
+ if (!e.refreshToken)
236
+ return t.setError(), t.promise;
237
+ r = r || 5;
238
+ var i = function() {
239
+ var a = !1;
240
+ if (r == -1 ? (a = !0, w("[KEYCLOAK] Refreshing token: forced refresh")) : (!e.tokenParsed || e.isTokenExpired(r)) && (a = !0, w("[KEYCLOAK] Refreshing token: token expired")), !a)
241
+ t.setSuccess(!1);
242
+ else {
243
+ var c = "grant_type=refresh_token&refresh_token=" + e.refreshToken, n = e.endpoints.token();
244
+ if (m.push(t), m.length == 1) {
245
+ var o = new XMLHttpRequest();
246
+ o.open("POST", n, !0), o.setRequestHeader("Content-type", "application/x-www-form-urlencoded"), o.withCredentials = !0, c += "&client_id=" + encodeURIComponent(e.clientId);
247
+ var u = (/* @__PURE__ */ new Date()).getTime();
248
+ o.onreadystatechange = function() {
249
+ if (o.readyState == 4)
250
+ if (o.status == 200) {
251
+ w("[KEYCLOAK] Token refreshed"), u = (u + (/* @__PURE__ */ new Date()).getTime()) / 2;
252
+ var f = JSON.parse(o.responseText);
253
+ C(f.access_token, f.refresh_token, f.id_token, u), e.onAuthRefreshSuccess && e.onAuthRefreshSuccess();
254
+ for (var d = m.pop(); d != null; d = m.pop())
255
+ d.setSuccess(!0);
256
+ } else {
257
+ A("[KEYCLOAK] Failed to refresh token"), o.status == 400 && e.clearToken(), e.onAuthRefreshError && e.onAuthRefreshError();
258
+ for (var d = m.pop(); d != null; d = m.pop())
259
+ d.setError("Failed to refresh token: An unexpected HTTP error occurred while attempting to refresh the token.");
260
+ }
261
+ }, o.send(c);
262
+ }
263
+ }
264
+ };
265
+ if (h.enable) {
266
+ var s = L();
267
+ s.then(function() {
268
+ i();
269
+ }).catch(function(a) {
270
+ t.setError(a);
271
+ });
272
+ } else
273
+ i();
274
+ return t.promise;
275
+ }, e.clearToken = function() {
276
+ e.token && (C(null, null, null), e.onAuthLogout && e.onAuthLogout(), e.loginRequired && e.login());
277
+ };
278
+ function _() {
279
+ if (typeof e.authServerUrl < "u")
280
+ return e.authServerUrl.charAt(e.authServerUrl.length - 1) == "/" ? e.authServerUrl + "realms/" + encodeURIComponent(e.realm) : e.authServerUrl + "/realms/" + encodeURIComponent(e.realm);
281
+ }
282
+ function Q() {
283
+ return window.location.origin ? window.location.origin : window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
284
+ }
285
+ function U(r, t) {
286
+ var i = r.code, s = r.error, a = r.prompt, c = (/* @__PURE__ */ new Date()).getTime();
287
+ if (r.kc_action_status && e.onActionUpdate && e.onActionUpdate(r.kc_action_status, r.kc_action), s) {
288
+ if (a != "none")
289
+ if (r.error_description && r.error_description === "authentication_expired")
290
+ e.login(r.loginOptions);
291
+ else {
292
+ var n = { error: s, error_description: r.error_description };
293
+ e.onAuthError && e.onAuthError(n), t && t.setError(n);
294
+ }
295
+ else
296
+ t && t.setSuccess();
297
+ return;
298
+ } else e.flow != "standard" && (r.access_token || r.id_token) && d(r.access_token, null, r.id_token, !0);
299
+ if (e.flow != "implicit" && i) {
300
+ var o = "code=" + i + "&grant_type=authorization_code", u = e.endpoints.token(), f = new XMLHttpRequest();
301
+ f.open("POST", u, !0), f.setRequestHeader("Content-type", "application/x-www-form-urlencoded"), o += "&client_id=" + encodeURIComponent(e.clientId), o += "&redirect_uri=" + r.redirectUri, r.pkceCodeVerifier && (o += "&code_verifier=" + r.pkceCodeVerifier), f.withCredentials = !0, f.onreadystatechange = function() {
302
+ if (f.readyState == 4)
303
+ if (f.status == 200) {
304
+ var g = JSON.parse(f.responseText);
305
+ d(g.access_token, g.refresh_token, g.id_token, e.flow === "standard"), P();
306
+ } else
307
+ e.onAuthError && e.onAuthError(), t && t.setError();
308
+ }, f.send(o);
309
+ }
310
+ function d(g, y, T, S) {
311
+ c = (c + (/* @__PURE__ */ new Date()).getTime()) / 2, C(g, y, T, c), b && e.idTokenParsed && e.idTokenParsed.nonce != r.storedNonce ? (w("[KEYCLOAK] Invalid nonce, clearing token"), e.clearToken(), t && t.setError()) : S && (e.onAuthSuccess && e.onAuthSuccess(), t && t.setSuccess());
312
+ }
313
+ }
314
+ function Z() {
315
+ var r = v(), t;
316
+ typeof k == "string" && (t = k);
317
+ function i(n) {
318
+ n ? e.endpoints = {
319
+ authorize: function() {
320
+ return n.authorization_endpoint;
321
+ },
322
+ token: function() {
323
+ return n.token_endpoint;
324
+ },
325
+ logout: function() {
326
+ if (!n.end_session_endpoint)
327
+ throw "Not supported by the OIDC server";
328
+ return n.end_session_endpoint;
329
+ },
330
+ checkSessionIframe: function() {
331
+ if (!n.check_session_iframe)
332
+ throw "Not supported by the OIDC server";
333
+ return n.check_session_iframe;
334
+ },
335
+ register: function() {
336
+ throw 'Redirection to "Register user" page not supported in standard OIDC mode';
337
+ },
338
+ userinfo: function() {
339
+ if (!n.userinfo_endpoint)
340
+ throw "Not supported by the OIDC server";
341
+ return n.userinfo_endpoint;
342
+ }
343
+ } : e.endpoints = {
344
+ authorize: function() {
345
+ return _() + "/protocol/openid-connect/auth";
346
+ },
347
+ token: function() {
348
+ return _() + "/protocol/openid-connect/token";
349
+ },
350
+ logout: function() {
351
+ return _() + "/protocol/openid-connect/logout";
352
+ },
353
+ checkSessionIframe: function() {
354
+ return _() + "/protocol/openid-connect/login-status-iframe.html";
355
+ },
356
+ thirdPartyCookiesIframe: function() {
357
+ return _() + "/protocol/openid-connect/3p-cookies/step1.html";
358
+ },
359
+ register: function() {
360
+ return _() + "/protocol/openid-connect/registrations";
361
+ },
362
+ userinfo: function() {
363
+ return _() + "/protocol/openid-connect/userinfo";
364
+ }
365
+ };
366
+ }
367
+ if (t) {
368
+ var s = new XMLHttpRequest();
369
+ s.open("GET", t, !0), s.setRequestHeader("Accept", "application/json"), s.onreadystatechange = function() {
370
+ if (s.readyState == 4)
371
+ if (s.status == 200 || J(s)) {
372
+ var n = JSON.parse(s.responseText);
373
+ e.authServerUrl = n["auth-server-url"], e.realm = n.realm, e.clientId = n.resource, i(null), r.setSuccess();
374
+ } else
375
+ r.setError();
376
+ }, s.send();
377
+ } else {
378
+ e.clientId = k.clientId;
379
+ var a = k.oidcProvider;
380
+ if (!a)
381
+ e.authServerUrl = k.url, e.realm = k.realm, i(null), r.setSuccess();
382
+ else if (typeof a == "string") {
383
+ var c;
384
+ a.charAt(a.length - 1) == "/" ? c = a + ".well-known/openid-configuration" : c = a + "/.well-known/openid-configuration";
385
+ var s = new XMLHttpRequest();
386
+ s.open("GET", c, !0), s.setRequestHeader("Accept", "application/json"), s.onreadystatechange = function() {
387
+ if (s.readyState == 4)
388
+ if (s.status == 200 || J(s)) {
389
+ var o = JSON.parse(s.responseText);
390
+ i(o), r.setSuccess();
391
+ } else
392
+ r.setError();
393
+ }, s.send();
394
+ } else
395
+ i(a), r.setSuccess();
396
+ }
397
+ return r.promise;
398
+ }
399
+ function J(r) {
400
+ return r.status == 0 && r.responseText && r.responseURL.startsWith("file:");
401
+ }
402
+ function C(r, t, i, s) {
403
+ if (e.tokenTimeoutHandle && (clearTimeout(e.tokenTimeoutHandle), e.tokenTimeoutHandle = null), t ? (e.refreshToken = t, e.refreshTokenParsed = D(t)) : (delete e.refreshToken, delete e.refreshTokenParsed), i ? (e.idToken = i, e.idTokenParsed = D(i)) : (delete e.idToken, delete e.idTokenParsed), r) {
404
+ if (e.token = r, e.tokenParsed = D(r), e.sessionId = e.tokenParsed.sid, e.authenticated = !0, e.subject = e.tokenParsed.sub, e.realmAccess = e.tokenParsed.realm_access, e.resourceAccess = e.tokenParsed.resource_access, s && (e.timeSkew = Math.floor(s / 1e3) - e.tokenParsed.iat), e.timeSkew != null && (w("[KEYCLOAK] Estimated time difference between browser and server is " + e.timeSkew + " seconds"), e.onTokenExpired)) {
405
+ var a = (e.tokenParsed.exp - (/* @__PURE__ */ new Date()).getTime() / 1e3 + e.timeSkew) * 1e3;
406
+ w("[KEYCLOAK] Token expires in " + Math.round(a / 1e3) + " s"), a <= 0 ? e.onTokenExpired() : e.tokenTimeoutHandle = setTimeout(e.onTokenExpired, a);
407
+ }
408
+ } else
409
+ delete e.token, delete e.tokenParsed, delete e.subject, delete e.realmAccess, delete e.resourceAccess, e.authenticated = !1;
410
+ }
411
+ function V() {
412
+ if (typeof crypto > "u" || typeof crypto.randomUUID > "u")
413
+ throw new Error("Web Crypto API is not available.");
414
+ return crypto.randomUUID();
415
+ }
416
+ function E(r) {
417
+ var t = ee(r);
418
+ if (t) {
419
+ var i = l.get(t.state);
420
+ return i && (t.valid = !0, t.redirectUri = i.redirectUri, t.storedNonce = i.nonce, t.prompt = i.prompt, t.pkceCodeVerifier = i.pkceCodeVerifier, t.loginOptions = i.loginOptions), t;
421
+ }
422
+ }
423
+ function ee(r) {
424
+ var t;
425
+ switch (e.flow) {
426
+ case "standard":
427
+ t = ["code", "state", "session_state", "kc_action_status", "kc_action", "iss"];
428
+ break;
429
+ case "implicit":
430
+ t = ["access_token", "token_type", "id_token", "state", "session_state", "expires_in", "kc_action_status", "kc_action", "iss"];
431
+ break;
432
+ case "hybrid":
433
+ t = ["access_token", "token_type", "id_token", "code", "state", "session_state", "expires_in", "kc_action_status", "kc_action", "iss"];
434
+ break;
435
+ }
436
+ t.push("error"), t.push("error_description"), t.push("error_uri");
437
+ var i = r.indexOf("?"), s = r.indexOf("#"), a, c;
438
+ if (e.responseMode === "query" && i !== -1 ? (a = r.substring(0, i), c = z(r.substring(i + 1, s !== -1 ? s : r.length), t), c.paramsString !== "" && (a += "?" + c.paramsString), s !== -1 && (a += r.substring(s))) : e.responseMode === "fragment" && s !== -1 && (a = r.substring(0, s), c = z(r.substring(s + 1), t), c.paramsString !== "" && (a += "#" + c.paramsString)), c && c.oauthParams) {
439
+ if (e.flow === "standard" || e.flow === "hybrid") {
440
+ if ((c.oauthParams.code || c.oauthParams.error) && c.oauthParams.state)
441
+ return c.oauthParams.newUrl = a, c.oauthParams;
442
+ } else if (e.flow === "implicit" && (c.oauthParams.access_token || c.oauthParams.error) && c.oauthParams.state)
443
+ return c.oauthParams.newUrl = a, c.oauthParams;
444
+ }
445
+ }
446
+ function z(r, t) {
447
+ for (var i = r.split("&"), s = {
448
+ paramsString: "",
449
+ oauthParams: {}
450
+ }, a = 0; a < i.length; a++) {
451
+ var c = i[a].indexOf("="), n = i[a].slice(0, c);
452
+ t.indexOf(n) !== -1 ? s.oauthParams[n] = i[a].slice(c + 1) : (s.paramsString !== "" && (s.paramsString += "&"), s.paramsString += i[a]);
453
+ }
454
+ return s;
455
+ }
456
+ function v() {
457
+ var r = {
458
+ setSuccess: function(t) {
459
+ r.resolve(t);
460
+ },
461
+ setError: function(t) {
462
+ r.reject(t);
463
+ }
464
+ };
465
+ return r.promise = new Promise(function(t, i) {
466
+ r.resolve = t, r.reject = i;
467
+ }), r;
468
+ }
469
+ function re(r, t, i) {
470
+ var s = null, a = new Promise(function(c, n) {
471
+ s = setTimeout(function() {
472
+ n({ error: i });
473
+ }, t);
474
+ });
475
+ return Promise.race([r, a]).finally(function() {
476
+ clearTimeout(s);
477
+ });
478
+ }
479
+ function x() {
480
+ var r = v();
481
+ if (!h.enable || h.iframe)
482
+ return r.setSuccess(), r.promise;
483
+ var t = document.createElement("iframe");
484
+ h.iframe = t, t.onload = function() {
485
+ var a = e.endpoints.authorize();
486
+ a.charAt(0) === "/" ? h.iframeOrigin = Q() : h.iframeOrigin = a.substring(0, a.indexOf("/", 8)), r.setSuccess();
487
+ };
488
+ var i = e.endpoints.checkSessionIframe();
489
+ t.setAttribute("src", i), t.setAttribute("sandbox", "allow-storage-access-by-user-activation allow-scripts allow-same-origin"), t.setAttribute("title", "keycloak-session-iframe"), t.style.display = "none", document.body.appendChild(t);
490
+ var s = function(a) {
491
+ if (!(a.origin !== h.iframeOrigin || h.iframe.contentWindow !== a.source) && (a.data == "unchanged" || a.data == "changed" || a.data == "error")) {
492
+ a.data != "unchanged" && e.clearToken();
493
+ for (var c = h.callbackList.splice(0, h.callbackList.length), n = c.length - 1; n >= 0; --n) {
494
+ var o = c[n];
495
+ a.data == "error" ? o.setError() : o.setSuccess(a.data == "unchanged");
496
+ }
497
+ }
498
+ };
499
+ return window.addEventListener("message", s, !1), r.promise;
500
+ }
501
+ function P() {
502
+ h.enable && e.token && setTimeout(function() {
503
+ L().then(function(r) {
504
+ r && P();
505
+ });
506
+ }, h.interval * 1e3);
507
+ }
508
+ function L() {
509
+ var r = v();
510
+ if (h.iframe && h.iframeOrigin) {
511
+ var t = e.clientId + " " + (e.sessionId ? e.sessionId : "");
512
+ h.callbackList.push(r);
513
+ var i = h.iframeOrigin;
514
+ h.callbackList.length == 1 && h.iframe.contentWindow.postMessage(t, i);
515
+ } else
516
+ r.setSuccess();
517
+ return r.promise;
518
+ }
519
+ function te() {
520
+ var r = v();
521
+ if ((h.enable || e.silentCheckSsoRedirectUri) && typeof e.endpoints.thirdPartyCookiesIframe == "function") {
522
+ var t = document.createElement("iframe");
523
+ t.setAttribute("src", e.endpoints.thirdPartyCookiesIframe()), t.setAttribute("sandbox", "allow-storage-access-by-user-activation allow-scripts allow-same-origin"), t.setAttribute("title", "keycloak-3p-check-iframe"), t.style.display = "none", document.body.appendChild(t);
524
+ var i = function(s) {
525
+ t.contentWindow === s.source && (s.data !== "supported" && s.data !== "unsupported" || (s.data === "unsupported" && (A(
526
+ `[KEYCLOAK] Your browser is blocking access to 3rd-party cookies, this means:
527
+
528
+ - It is not possible to retrieve tokens without redirecting to the Keycloak server (a.k.a. no support for silent authentication).
529
+ - It is not possible to automatically detect changes to the session status (such as the user logging out in another tab).
530
+
531
+ For more information see: https://www.keycloak.org/securing-apps/javascript-adapter#_modern_browsers`
532
+ ), h.enable = !1, e.silentCheckSsoFallback && (e.silentCheckSsoRedirectUri = !1)), document.body.removeChild(t), window.removeEventListener("message", i), r.setSuccess()));
533
+ };
534
+ window.addEventListener("message", i, !1);
535
+ } else
536
+ r.setSuccess();
537
+ return re(r.promise, e.messageReceiveTimeout, "Timeout when waiting for 3rd party check iframe message.");
538
+ }
539
+ function M(r) {
540
+ if (!r || r == "default")
541
+ return {
542
+ login: async function(n) {
543
+ return window.location.assign(await e.createLoginUrl(n)), v().promise;
544
+ },
545
+ logout: async function(n) {
546
+ if (((n == null ? void 0 : n.logoutMethod) ?? e.logoutMethod) === "GET") {
547
+ window.location.replace(e.createLogoutUrl(n));
548
+ return;
549
+ }
550
+ const u = document.createElement("form");
551
+ u.setAttribute("method", "POST"), u.setAttribute("action", e.createLogoutUrl(n)), u.style.display = "none";
552
+ const f = {
553
+ id_token_hint: e.idToken,
554
+ client_id: e.clientId,
555
+ post_logout_redirect_uri: p.redirectUri(n, !1)
556
+ };
557
+ for (const [d, g] of Object.entries(f)) {
558
+ const y = document.createElement("input");
559
+ y.setAttribute("type", "hidden"), y.setAttribute("name", d), y.setAttribute("value", g), u.appendChild(y);
560
+ }
561
+ document.body.appendChild(u), u.submit();
562
+ },
563
+ register: async function(n) {
564
+ return window.location.assign(await e.createRegisterUrl(n)), v().promise;
565
+ },
566
+ accountManagement: function() {
567
+ var n = e.createAccountUrl();
568
+ if (typeof n < "u")
569
+ window.location.href = n;
570
+ else
571
+ throw "Not supported by the OIDC server";
572
+ return v().promise;
573
+ },
574
+ redirectUri: function(n, o) {
575
+ return n && n.redirectUri ? n.redirectUri : e.redirectUri ? e.redirectUri : location.href;
576
+ }
577
+ };
578
+ if (r == "cordova") {
579
+ h.enable = !1;
580
+ var t = function(n, o, u) {
581
+ return window.cordova && window.cordova.InAppBrowser ? window.cordova.InAppBrowser.open(n, o, u) : window.open(n, o, u);
582
+ }, i = function(n) {
583
+ return n && n.cordovaOptions ? Object.keys(n.cordovaOptions).reduce(function(o, u) {
584
+ return o[u] = n.cordovaOptions[u], o;
585
+ }, {}) : {};
586
+ }, s = function(n) {
587
+ return Object.keys(n).reduce(function(o, u) {
588
+ return o.push(u + "=" + n[u]), o;
589
+ }, []).join(",");
590
+ }, a = function(n) {
591
+ var o = i(n);
592
+ return o.location = "no", n && n.prompt == "none" && (o.hidden = "yes"), s(o);
593
+ }, c = function() {
594
+ return e.redirectUri || "http://localhost";
595
+ };
596
+ return {
597
+ login: async function(n) {
598
+ var o = v(), u = a(n), f = await e.createLoginUrl(n), d = t(f, "_blank", u), g = !1, y = !1, T = function() {
599
+ y = !0, d.close();
600
+ };
601
+ return d.addEventListener("loadstart", function(S) {
602
+ if (S.url.indexOf(c()) == 0) {
603
+ var K = E(S.url);
604
+ U(K, o), T(), g = !0;
605
+ }
606
+ }), d.addEventListener("loaderror", function(S) {
607
+ if (!g)
608
+ if (S.url.indexOf(c()) == 0) {
609
+ var K = E(S.url);
610
+ U(K, o), T(), g = !0;
611
+ } else
612
+ o.setError(), T();
613
+ }), d.addEventListener("exit", function(S) {
614
+ y || o.setError({
615
+ reason: "closed_by_user"
616
+ });
617
+ }), o.promise;
618
+ },
619
+ logout: function(n) {
620
+ var o = v(), u = e.createLogoutUrl(n), f = t(u, "_blank", "location=no,hidden=yes,clearcache=yes"), d;
621
+ return f.addEventListener("loadstart", function(g) {
622
+ g.url.indexOf(c()) == 0 && f.close();
623
+ }), f.addEventListener("loaderror", function(g) {
624
+ g.url.indexOf(c()) == 0 || (d = !0), f.close();
625
+ }), f.addEventListener("exit", function(g) {
626
+ d ? o.setError() : (e.clearToken(), o.setSuccess());
627
+ }), o.promise;
628
+ },
629
+ register: async function(n) {
630
+ var o = v(), u = await e.createRegisterUrl(), f = a(n), d = t(u, "_blank", f);
631
+ return d.addEventListener("loadstart", function(g) {
632
+ if (g.url.indexOf(c()) == 0) {
633
+ d.close();
634
+ var y = E(g.url);
635
+ U(y, o);
636
+ }
637
+ }), o.promise;
638
+ },
639
+ accountManagement: function() {
640
+ var n = e.createAccountUrl();
641
+ if (typeof n < "u") {
642
+ var o = t(n, "_blank", "location=no");
643
+ o.addEventListener("loadstart", function(u) {
644
+ u.url.indexOf(c()) == 0 && o.close();
645
+ });
646
+ } else
647
+ throw "Not supported by the OIDC server";
648
+ },
649
+ redirectUri: function(n) {
650
+ return c();
651
+ }
652
+ };
653
+ }
654
+ if (r == "cordova-native")
655
+ return h.enable = !1, {
656
+ login: async function(n) {
657
+ var o = v(), u = await e.createLoginUrl(n);
658
+ return universalLinks.subscribe("keycloak", function(f) {
659
+ universalLinks.unsubscribe("keycloak"), window.cordova.plugins.browsertab.close();
660
+ var d = E(f.url);
661
+ U(d, o);
662
+ }), window.cordova.plugins.browsertab.openUrl(u), o.promise;
663
+ },
664
+ logout: function(n) {
665
+ var o = v(), u = e.createLogoutUrl(n);
666
+ return universalLinks.subscribe("keycloak", function(f) {
667
+ universalLinks.unsubscribe("keycloak"), window.cordova.plugins.browsertab.close(), e.clearToken(), o.setSuccess();
668
+ }), window.cordova.plugins.browsertab.openUrl(u), o.promise;
669
+ },
670
+ register: async function(n) {
671
+ var o = v(), u = await e.createRegisterUrl(n);
672
+ return universalLinks.subscribe("keycloak", function(f) {
673
+ universalLinks.unsubscribe("keycloak"), window.cordova.plugins.browsertab.close();
674
+ var d = E(f.url);
675
+ U(d, o);
676
+ }), window.cordova.plugins.browsertab.openUrl(u), o.promise;
677
+ },
678
+ accountManagement: function() {
679
+ var n = e.createAccountUrl();
680
+ if (typeof n < "u")
681
+ window.cordova.plugins.browsertab.openUrl(n);
682
+ else
683
+ throw "Not supported by the OIDC server";
684
+ },
685
+ redirectUri: function(n) {
686
+ return n && n.redirectUri ? n.redirectUri : e.redirectUri ? e.redirectUri : "http://localhost";
687
+ }
688
+ };
689
+ throw "invalid adapter type: " + r;
690
+ }
691
+ const I = "kc-callback-";
692
+ var H = function() {
693
+ if (!(this instanceof H))
694
+ return new H();
695
+ localStorage.setItem("kc-test", "test"), localStorage.removeItem("kc-test");
696
+ var r = this;
697
+ function t() {
698
+ const c = Date.now();
699
+ for (const [n, o] of s()) {
700
+ const u = a(o);
701
+ (u === null || u < c) && localStorage.removeItem(n);
702
+ }
703
+ }
704
+ function i() {
705
+ for (const [c] of s())
706
+ localStorage.removeItem(c);
707
+ }
708
+ function s() {
709
+ return Object.entries(localStorage).filter(([c]) => c.startsWith(I));
710
+ }
711
+ function a(c) {
712
+ let n;
713
+ try {
714
+ n = JSON.parse(c);
715
+ } catch {
716
+ return null;
717
+ }
718
+ return O(n) && "expires" in n && typeof n.expires == "number" ? n.expires : null;
719
+ }
720
+ r.get = function(c) {
721
+ if (c) {
722
+ var n = I + c, o = localStorage.getItem(n);
723
+ return o && (localStorage.removeItem(n), o = JSON.parse(o)), t(), o;
724
+ }
725
+ }, r.add = function(c) {
726
+ t();
727
+ const n = I + c.state, o = JSON.stringify({
728
+ ...c,
729
+ // Set the expiry time to 1 hour from now.
730
+ expires: Date.now() + 60 * 60 * 1e3
731
+ });
732
+ try {
733
+ localStorage.setItem(n, o);
734
+ } catch {
735
+ i(), localStorage.setItem(n, o);
736
+ }
737
+ };
738
+ }, N = function() {
739
+ if (!(this instanceof N))
740
+ return new N();
741
+ var r = this;
742
+ r.get = function(a) {
743
+ if (a) {
744
+ var c = i(I + a);
745
+ if (s(I + a, "", t(-100)), c)
746
+ return JSON.parse(c);
747
+ }
748
+ }, r.add = function(a) {
749
+ s(I + a.state, JSON.stringify(a), t(60));
750
+ }, r.removeItem = function(a) {
751
+ s(a, "", t(-100));
752
+ };
753
+ var t = function(a) {
754
+ var c = /* @__PURE__ */ new Date();
755
+ return c.setTime(c.getTime() + a * 60 * 1e3), c;
756
+ }, i = function(a) {
757
+ for (var c = a + "=", n = document.cookie.split(";"), o = 0; o < n.length; o++) {
758
+ for (var u = n[o]; u.charAt(0) == " "; )
759
+ u = u.substring(1);
760
+ if (u.indexOf(c) == 0)
761
+ return u.substring(c.length, u.length);
762
+ }
763
+ return "";
764
+ }, s = function(a, c, n) {
765
+ var o = a + "=" + c + "; expires=" + n.toUTCString() + "; ";
766
+ document.cookie = o;
767
+ };
768
+ };
769
+ function ne() {
770
+ try {
771
+ return new H();
772
+ } catch {
773
+ }
774
+ return new N();
775
+ }
776
+ function Y(r) {
777
+ return function() {
778
+ e.enableLogging && r.apply(console, Array.prototype.slice.call(arguments));
779
+ };
780
+ }
781
+ }
782
+ function se(k) {
783
+ const e = String.fromCodePoint(...k);
784
+ return btoa(e);
785
+ }
786
+ async function ie(k) {
787
+ const p = new TextEncoder().encode(k);
788
+ if (typeof crypto > "u" || typeof crypto.subtle > "u")
789
+ throw new Error("Web Crypto API is not available.");
790
+ return await crypto.subtle.digest("SHA-256", p);
791
+ }
792
+ function D(k) {
793
+ const [e, p] = k.split(".");
794
+ if (typeof p != "string")
795
+ throw new Error("Unable to decode token, payload not found.");
796
+ let m;
797
+ try {
798
+ m = ce(p);
799
+ } catch (l) {
800
+ throw new Error("Unable to decode token, payload is not a valid Base64URL value.", { cause: l });
801
+ }
802
+ try {
803
+ return JSON.parse(m);
804
+ } catch (l) {
805
+ throw new Error("Unable to decode token, payload is not a valid JSON value.", { cause: l });
806
+ }
807
+ }
808
+ function ce(k) {
809
+ let e = k.replaceAll("-", "+").replaceAll("_", "/");
810
+ switch (e.length % 4) {
811
+ case 0:
812
+ break;
813
+ case 2:
814
+ e += "==";
815
+ break;
816
+ case 3:
817
+ e += "=";
818
+ break;
819
+ default:
820
+ throw new Error("Input is not of the correct length.");
821
+ }
822
+ try {
823
+ return ue(e);
824
+ } catch {
825
+ return atob(e);
826
+ }
827
+ }
828
+ function ue(k) {
829
+ return decodeURIComponent(atob(k).replace(/(.)/g, (e, p) => {
830
+ let m = p.charCodeAt(0).toString(16).toUpperCase();
831
+ return m.length < 2 && (m = "0" + m), "%" + m;
832
+ }));
833
+ }
834
+ function O(k) {
835
+ return typeof k == "object" && k !== null;
836
+ }
837
+ const le = {};
838
+ class j extends q {
839
+ constructor() {
840
+ const { VITE_KEYCLOAK_REALM: e, VITE_KEYCLOAK_HOST: p, VITE_KEYCLOAK_CLIENT_ID: m } = le;
841
+ super({
842
+ url: p,
843
+ realm: e,
844
+ clientId: m
845
+ });
846
+ }
847
+ async initialize() {
848
+ try {
849
+ await this.init(
850
+ {
851
+ onLoad: "login-required"
852
+ }
853
+ ) && console.log("User is authenticated"), console.log("User is not authenticated");
854
+ } catch (e) {
855
+ console.error("Failed to initialize adapter:", e);
856
+ }
857
+ }
858
+ static async init() {
859
+ const e = new j();
860
+ return await e.initialize(), e;
861
+ }
862
+ get userInfo() {
863
+ return this.idTokenParsed;
864
+ }
865
+ updateToken() {
866
+ return this.updateToken(30);
867
+ }
868
+ get isAuthenticated() {
869
+ return this.authenticated ?? !1;
870
+ }
871
+ }
872
+ const de = "GHENT_CDH_AUTH_STORE", fe = G(de, () => {
873
+ const k = oe(!1), e = F(), p = F(!1);
874
+ return j.init().then((l) => (k.value = l.isAuthenticated, e.value = l, p.value = !0, l)), {
875
+ token: () => {
876
+ var l;
877
+ return (l = e.value) == null ? void 0 : l.token;
878
+ },
879
+ user: () => {
880
+ var l;
881
+ return (l = e.value) == null ? void 0 : l.userInfo;
882
+ },
883
+ isAuthenticated: () => {
884
+ var l;
885
+ return (l = e.value) == null ? void 0 : l.isAuthenticated;
886
+ },
887
+ logout: () => {
888
+ console.warn("logout");
889
+ },
890
+ updateToken: async () => {
891
+ var l;
892
+ return p.value || await new Promise((h) => {
893
+ const b = ae(p, (w) => {
894
+ w && (b(), h());
895
+ });
896
+ }), (l = e.value) == null ? void 0 : l.updateToken();
897
+ }
898
+ };
899
+ }), pe = "GHENT_CDH_HTTP_REQUEST", ke = G(pe, () => {
900
+ const k = fe(), e = async (p, m, l = { contentType: "application/json" }) => {
901
+ const h = {
902
+ accept: "application/json",
903
+ ...m.headers ?? {}
904
+ };
905
+ l.contentType && (h["Content-Type"] = l.contentType), l != null && l.skipAuth || (await k.updateToken(), h.Authorization = `Bearer ${k.token()}`);
906
+ const b = new URL(p, window.location.href);
907
+ if (l != null && l.queryParams)
908
+ for (const [A, R] of Object.entries(l.queryParams))
909
+ b.searchParams.set(A, R);
910
+ const w = await fetch(b.toString(), {
911
+ ...m,
912
+ headers: h
913
+ });
914
+ return w.ok ? w.json() : (l != null && l.skipAuth, Promise.reject({
915
+ content: w.body,
916
+ status: w.status
917
+ }));
918
+ };
919
+ return {
920
+ get: (p, m) => e(p, { method: "GET" }, m),
921
+ postFile: (p, m, l = {}, h) => {
922
+ const b = new FormData();
923
+ for (const w in l)
924
+ b.append(w, l[w]);
925
+ return b.append("file", m), e(
926
+ p,
927
+ {
928
+ method: "POST",
929
+ body: b
930
+ },
931
+ { ...h, contentType: void 0 }
932
+ );
933
+ },
934
+ post: (p, m, l) => e(
935
+ p,
936
+ {
937
+ method: "POST",
938
+ body: JSON.stringify(m)
939
+ },
940
+ l
941
+ ),
942
+ patch: (p, m, l) => e(
943
+ p,
944
+ {
945
+ method: "PATCH",
946
+ body: JSON.stringify(m)
947
+ },
948
+ l
949
+ ),
950
+ delete: (p, m, l) => e(
951
+ p,
952
+ {
953
+ method: "DELETE",
954
+ body: JSON.stringify(m)
955
+ },
956
+ l
957
+ )
958
+ };
959
+ });
960
+ export {
961
+ j as KeycloakAdapter,
962
+ fe as useAuthenticationStore,
963
+ ke as useHttpStore
964
+ };