@versini/auth-provider 7.5.3 → 8.0.0

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/dist/auth.js ADDED
@@ -0,0 +1,1104 @@
1
+ var Pe = Object.defineProperty;
2
+ var Ce = (e, t, n) => t in e ? Pe(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var K = (e, t, n) => Ce(e, typeof t != "symbol" ? t + "" : t, n);
4
+ import { jsx as H } from "react/jsx-runtime";
5
+ import { at as ie, st as ve, O as T, ot as M, nt as C, Ye as D, ct as Ue } from "./index-Dk6T3xdb.js";
6
+ import De, { useSyncExternalStore as Le, useCallback as S, useEffect as ce, createContext as $e, useContext as Ke, useReducer as Ye, useRef as Ge } from "react";
7
+ import { AuthHookContext as Ve } from "./AuthHookContext-C9a2AwWZ.js";
8
+ /*!
9
+ @versini/auth-provider v8.0.0
10
+ © 2025 gizmette.com
11
+ */
12
+ try {
13
+ window.__VERSINI_AUTH_CLIENT__ || (window.__VERSINI_AUTH_CLIENT__ = {
14
+ version: "8.0.0",
15
+ buildTime: "04/13/2025 02:38 PM EDT",
16
+ homepage: "https://github.com/aversini/auth-client",
17
+ license: "MIT"
18
+ });
19
+ } catch {
20
+ }
21
+ function R(e) {
22
+ const t = new Uint8Array(e);
23
+ let n = "";
24
+ for (const s of t)
25
+ n += String.fromCharCode(s);
26
+ return btoa(n).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
27
+ }
28
+ function F(e) {
29
+ const t = e.replace(/-/g, "+").replace(/_/g, "/"), n = (4 - t.length % 4) % 4, a = t.padEnd(t.length + n, "="), s = atob(a), o = new ArrayBuffer(s.length), c = new Uint8Array(o);
30
+ for (let r = 0; r < s.length; r++)
31
+ c[r] = s.charCodeAt(r);
32
+ return o;
33
+ }
34
+ function X() {
35
+ return He.stubThis(globalThis?.PublicKeyCredential !== void 0 && typeof globalThis.PublicKeyCredential == "function");
36
+ }
37
+ const He = {
38
+ stubThis: (e) => e
39
+ };
40
+ function ue(e) {
41
+ const { id: t } = e;
42
+ return {
43
+ ...e,
44
+ id: F(t),
45
+ /**
46
+ * `descriptor.transports` is an array of our `AuthenticatorTransportFuture` that includes newer
47
+ * transports that TypeScript's DOM lib is ignorant of. Convince TS that our list of transports
48
+ * are fine to pass to WebAuthn since browsers will recognize the new value.
49
+ */
50
+ transports: e.transports
51
+ };
52
+ }
53
+ function le(e) {
54
+ return (
55
+ // Consider localhost valid as well since it's okay wrt Secure Contexts
56
+ e === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)
57
+ );
58
+ }
59
+ class p extends Error {
60
+ constructor({ message: t, code: n, cause: a, name: s }) {
61
+ super(t, { cause: a }), Object.defineProperty(this, "code", {
62
+ enumerable: !0,
63
+ configurable: !0,
64
+ writable: !0,
65
+ value: void 0
66
+ }), this.name = s ?? a.name, this.code = n;
67
+ }
68
+ }
69
+ function xe({ error: e, options: t }) {
70
+ const { publicKey: n } = t;
71
+ if (!n)
72
+ throw Error("options was missing required publicKey property");
73
+ if (e.name === "AbortError") {
74
+ if (t.signal instanceof AbortSignal)
75
+ return new p({
76
+ message: "Registration ceremony was sent an abort signal",
77
+ code: "ERROR_CEREMONY_ABORTED",
78
+ cause: e
79
+ });
80
+ } else if (e.name === "ConstraintError") {
81
+ if (n.authenticatorSelection?.requireResidentKey === !0)
82
+ return new p({
83
+ message: "Discoverable credentials were required but no available authenticator supported it",
84
+ code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",
85
+ cause: e
86
+ });
87
+ if (
88
+ // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024
89
+ t.mediation === "conditional" && n.authenticatorSelection?.userVerification === "required"
90
+ )
91
+ return new p({
92
+ message: "User verification was required during automatic registration but it could not be performed",
93
+ code: "ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",
94
+ cause: e
95
+ });
96
+ if (n.authenticatorSelection?.userVerification === "required")
97
+ return new p({
98
+ message: "User verification was required but no available authenticator supported it",
99
+ code: "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",
100
+ cause: e
101
+ });
102
+ } else {
103
+ if (e.name === "InvalidStateError")
104
+ return new p({
105
+ message: "The authenticator was previously registered",
106
+ code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",
107
+ cause: e
108
+ });
109
+ if (e.name === "NotAllowedError")
110
+ return new p({
111
+ message: e.message,
112
+ code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
113
+ cause: e
114
+ });
115
+ if (e.name === "NotSupportedError")
116
+ return n.pubKeyCredParams.filter((s) => s.type === "public-key").length === 0 ? new p({
117
+ message: 'No entry in pubKeyCredParams was of type "public-key"',
118
+ code: "ERROR_MALFORMED_PUBKEYCREDPARAMS",
119
+ cause: e
120
+ }) : new p({
121
+ message: "No available authenticator supported any of the specified pubKeyCredParams algorithms",
122
+ code: "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",
123
+ cause: e
124
+ });
125
+ if (e.name === "SecurityError") {
126
+ const a = globalThis.location.hostname;
127
+ if (le(a)) {
128
+ if (n.rp.id !== a)
129
+ return new p({
130
+ message: `The RP ID "${n.rp.id}" is invalid for this domain`,
131
+ code: "ERROR_INVALID_RP_ID",
132
+ cause: e
133
+ });
134
+ } else return new p({
135
+ message: `${globalThis.location.hostname} is an invalid domain`,
136
+ code: "ERROR_INVALID_DOMAIN",
137
+ cause: e
138
+ });
139
+ } else if (e.name === "TypeError") {
140
+ if (n.user.id.byteLength < 1 || n.user.id.byteLength > 64)
141
+ return new p({
142
+ message: "User ID was not between 1 and 64 characters",
143
+ code: "ERROR_INVALID_USER_ID_LENGTH",
144
+ cause: e
145
+ });
146
+ } else if (e.name === "UnknownError")
147
+ return new p({
148
+ message: "The authenticator was unable to process the specified options, or could not create a new credential",
149
+ code: "ERROR_AUTHENTICATOR_GENERAL_ERROR",
150
+ cause: e
151
+ });
152
+ }
153
+ return e;
154
+ }
155
+ class Fe {
156
+ constructor() {
157
+ Object.defineProperty(this, "controller", {
158
+ enumerable: !0,
159
+ configurable: !0,
160
+ writable: !0,
161
+ value: void 0
162
+ });
163
+ }
164
+ createNewAbortSignal() {
165
+ if (this.controller) {
166
+ const n = new Error("Cancelling existing WebAuthn API call for new one");
167
+ n.name = "AbortError", this.controller.abort(n);
168
+ }
169
+ const t = new AbortController();
170
+ return this.controller = t, t.signal;
171
+ }
172
+ cancelCeremony() {
173
+ if (this.controller) {
174
+ const t = new Error("Manually cancelling existing WebAuthn API call");
175
+ t.name = "AbortError", this.controller.abort(t), this.controller = void 0;
176
+ }
177
+ }
178
+ }
179
+ const de = new Fe(), Me = ["cross-platform", "platform"];
180
+ function he(e) {
181
+ if (e && !(Me.indexOf(e) < 0))
182
+ return e;
183
+ }
184
+ async function Je(e) {
185
+ !e.optionsJSON && e.challenge && (console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."), e = { optionsJSON: e });
186
+ const { optionsJSON: t, useAutoRegister: n = !1 } = e;
187
+ if (!X())
188
+ throw new Error("WebAuthn is not supported in this browser");
189
+ const a = {
190
+ ...t,
191
+ challenge: F(t.challenge),
192
+ user: {
193
+ ...t.user,
194
+ id: F(t.user.id)
195
+ },
196
+ excludeCredentials: t.excludeCredentials?.map(ue)
197
+ }, s = {};
198
+ n && (s.mediation = "conditional"), s.publicKey = a, s.signal = de.createNewAbortSignal();
199
+ let o;
200
+ try {
201
+ o = await navigator.credentials.create(s);
202
+ } catch (E) {
203
+ throw xe({ error: E, options: s });
204
+ }
205
+ if (!o)
206
+ throw new Error("Registration was not completed");
207
+ const { id: c, rawId: r, response: i, type: w } = o;
208
+ let d;
209
+ typeof i.getTransports == "function" && (d = i.getTransports());
210
+ let m;
211
+ if (typeof i.getPublicKeyAlgorithm == "function")
212
+ try {
213
+ m = i.getPublicKeyAlgorithm();
214
+ } catch (E) {
215
+ j("getPublicKeyAlgorithm()", E);
216
+ }
217
+ let y;
218
+ if (typeof i.getPublicKey == "function")
219
+ try {
220
+ const E = i.getPublicKey();
221
+ E !== null && (y = R(E));
222
+ } catch (E) {
223
+ j("getPublicKey()", E);
224
+ }
225
+ let f;
226
+ if (typeof i.getAuthenticatorData == "function")
227
+ try {
228
+ f = R(i.getAuthenticatorData());
229
+ } catch (E) {
230
+ j("getAuthenticatorData()", E);
231
+ }
232
+ return {
233
+ id: c,
234
+ rawId: R(r),
235
+ response: {
236
+ attestationObject: R(i.attestationObject),
237
+ clientDataJSON: R(i.clientDataJSON),
238
+ transports: d,
239
+ publicKeyAlgorithm: m,
240
+ publicKey: y,
241
+ authenticatorData: f
242
+ },
243
+ type: w,
244
+ clientExtensionResults: o.getClientExtensionResults(),
245
+ authenticatorAttachment: he(o.authenticatorAttachment)
246
+ };
247
+ }
248
+ function j(e, t) {
249
+ console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.
250
+ `, t);
251
+ }
252
+ function We() {
253
+ if (!X())
254
+ return B.stubThis(new Promise((t) => t(!1)));
255
+ const e = globalThis.PublicKeyCredential;
256
+ return e?.isConditionalMediationAvailable === void 0 ? B.stubThis(new Promise((t) => t(!1))) : B.stubThis(e.isConditionalMediationAvailable());
257
+ }
258
+ const B = {
259
+ stubThis: (e) => e
260
+ };
261
+ function je({ error: e, options: t }) {
262
+ const { publicKey: n } = t;
263
+ if (!n)
264
+ throw Error("options was missing required publicKey property");
265
+ if (e.name === "AbortError") {
266
+ if (t.signal instanceof AbortSignal)
267
+ return new p({
268
+ message: "Authentication ceremony was sent an abort signal",
269
+ code: "ERROR_CEREMONY_ABORTED",
270
+ cause: e
271
+ });
272
+ } else {
273
+ if (e.name === "NotAllowedError")
274
+ return new p({
275
+ message: e.message,
276
+ code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
277
+ cause: e
278
+ });
279
+ if (e.name === "SecurityError") {
280
+ const a = globalThis.location.hostname;
281
+ if (le(a)) {
282
+ if (n.rpId !== a)
283
+ return new p({
284
+ message: `The RP ID "${n.rpId}" is invalid for this domain`,
285
+ code: "ERROR_INVALID_RP_ID",
286
+ cause: e
287
+ });
288
+ } else return new p({
289
+ message: `${globalThis.location.hostname} is an invalid domain`,
290
+ code: "ERROR_INVALID_DOMAIN",
291
+ cause: e
292
+ });
293
+ } else if (e.name === "UnknownError")
294
+ return new p({
295
+ message: "The authenticator was unable to process the specified options, or could not create a new assertion signature",
296
+ code: "ERROR_AUTHENTICATOR_GENERAL_ERROR",
297
+ cause: e
298
+ });
299
+ }
300
+ return e;
301
+ }
302
+ async function Be(e) {
303
+ !e.optionsJSON && e.challenge && (console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."), e = { optionsJSON: e });
304
+ const { optionsJSON: t, useBrowserAutofill: n = !1, verifyBrowserAutofillInput: a = !0 } = e;
305
+ if (!X())
306
+ throw new Error("WebAuthn is not supported in this browser");
307
+ let s;
308
+ t.allowCredentials?.length !== 0 && (s = t.allowCredentials?.map(ue));
309
+ const o = {
310
+ ...t,
311
+ challenge: F(t.challenge),
312
+ allowCredentials: s
313
+ }, c = {};
314
+ if (n) {
315
+ if (!await We())
316
+ throw Error("Browser does not support WebAuthn autofill");
317
+ if (document.querySelectorAll("input[autocomplete$='webauthn']").length < 1 && a)
318
+ throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');
319
+ c.mediation = "conditional", o.allowCredentials = [];
320
+ }
321
+ c.publicKey = o, c.signal = de.createNewAbortSignal();
322
+ let r;
323
+ try {
324
+ r = await navigator.credentials.get(c);
325
+ } catch (f) {
326
+ throw je({ error: f, options: c });
327
+ }
328
+ if (!r)
329
+ throw new Error("Authentication was not completed");
330
+ const { id: i, rawId: w, response: d, type: m } = r;
331
+ let y;
332
+ return d.userHandle && (y = R(d.userHandle)), {
333
+ id: i,
334
+ rawId: R(w),
335
+ response: {
336
+ authenticatorData: R(d.authenticatorData),
337
+ clientDataJSON: R(d.clientDataJSON),
338
+ signature: R(d.signature),
339
+ userHandle: y
340
+ },
341
+ type: m,
342
+ clientExtensionResults: r.getClientExtensionResults(),
343
+ authenticatorAttachment: he(r.authenticatorAttachment)
344
+ };
345
+ }
346
+ function ge(e, t) {
347
+ window.dispatchEvent(new StorageEvent("storage", { key: e, newValue: t }));
348
+ }
349
+ const se = (e, t) => {
350
+ const n = JSON.stringify(
351
+ typeof t == "function" ? t() : t
352
+ );
353
+ window.localStorage.setItem(e, n), ge(e, n);
354
+ }, qe = (e) => {
355
+ window.localStorage.removeItem(e), ge(e, null);
356
+ }, re = (e) => window.localStorage.getItem(e), ze = (e) => (window.addEventListener("storage", e), () => window.removeEventListener("storage", e));
357
+ function Y({
358
+ key: e,
359
+ initialValue: t
360
+ }) {
361
+ const n = Le(ze, () => re(e)), a = S(
362
+ (c) => {
363
+ try {
364
+ const r = typeof c == "function" ? c(JSON.parse(n)) : c;
365
+ r == null ? qe(e) : se(e, r);
366
+ } catch (r) {
367
+ console.warn(r);
368
+ }
369
+ },
370
+ [e, n]
371
+ ), s = S(() => {
372
+ a(t);
373
+ }, [t, a]), o = S(() => {
374
+ a(null);
375
+ }, [a]);
376
+ return ce(() => {
377
+ try {
378
+ re(e) === null && typeof t < "u" && se(e, t);
379
+ } catch (c) {
380
+ console.warn(c);
381
+ }
382
+ }, [e, t]), [n ? JSON.parse(n) : null, a, s, o];
383
+ }
384
+ const g = [];
385
+ for (let e = 0; e < 256; ++e)
386
+ g.push((e + 256).toString(16).slice(1));
387
+ function Qe(e, t = 0) {
388
+ return (g[e[t + 0]] + g[e[t + 1]] + g[e[t + 2]] + g[e[t + 3]] + "-" + g[e[t + 4]] + g[e[t + 5]] + "-" + g[e[t + 6]] + g[e[t + 7]] + "-" + g[e[t + 8]] + g[e[t + 9]] + "-" + g[e[t + 10]] + g[e[t + 11]] + g[e[t + 12]] + g[e[t + 13]] + g[e[t + 14]] + g[e[t + 15]]).toLowerCase();
389
+ }
390
+ let q;
391
+ const Xe = new Uint8Array(16);
392
+ function Ze() {
393
+ if (!q) {
394
+ if (typeof crypto > "u" || !crypto.getRandomValues)
395
+ throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
396
+ q = crypto.getRandomValues.bind(crypto);
397
+ }
398
+ return q(Xe);
399
+ }
400
+ const et = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), oe = { randomUUID: et };
401
+ function z(e, t, n) {
402
+ if (oe.randomUUID && !e)
403
+ return oe.randomUUID();
404
+ e = e || {};
405
+ const a = e.random ?? e.rng?.() ?? Ze();
406
+ if (a.length < 16)
407
+ throw new Error("Random bytes length must be >= 16");
408
+ return a[6] = a[6] & 15 | 64, a[8] = a[8] & 63 | 128, Qe(a);
409
+ }
410
+ const b = "Your session has expired. For your security, please log in again to continue.", tt = "Your session has been successfully terminated.", Q = "Login failed. Please try again.", nt = "Error getting access token, please re-authenticate.", at = "You forgot to wrap your component in <AuthProvider>.", G = "@@auth@@", U = "LOADING", x = "LOGIN", pe = "LOGOUT", L = "success", A = "failure", fe = "include", Te = "POST", ye = "application/json", V = {
411
+ GET_REGISTRATION_OPTIONS: `mutation GetPasskeyRegistrationOptions(
412
+ $clientId: String!,
413
+ $username: String!,
414
+ $id: String!) {
415
+ getPasskeyRegistrationOptions(clientId: $clientId, username: $username, id: $id) {
416
+ challenge
417
+ rp {
418
+ id
419
+ name
420
+ }
421
+ user {
422
+ id
423
+ name
424
+ displayName
425
+ }
426
+ pubKeyCredParams {
427
+ type
428
+ alg
429
+ }
430
+ timeout
431
+ attestation
432
+ }
433
+ }`,
434
+ VERIFY_REGISTRATION: `mutation VerifyPasskeyRegistration(
435
+ $clientId: String!,
436
+ $username: String!,
437
+ $id: String!,
438
+ $registration: RegistrationOptionsInput!) {
439
+ verifyPasskeyRegistration(
440
+ clientId: $clientId,
441
+ username: $username,
442
+ id: $id,
443
+ registration: $registration) {
444
+ status
445
+ message
446
+ }
447
+ }`,
448
+ GET_AUTHENTICATION_OPTIONS: `mutation GetPasskeyAuthenticationOptions(
449
+ $id: String!,
450
+ $clientId: String!,
451
+ ) {
452
+ getPasskeyAuthenticationOptions(
453
+ id: $id,
454
+ clientId: $clientId) {
455
+ rpId,
456
+ challenge,
457
+ allowCredentials {
458
+ id,
459
+ type,
460
+ transports
461
+ }
462
+ timeout,
463
+ userVerification,
464
+ }
465
+ }`,
466
+ VERIFY_AUTHENTICATION: `mutation VerifyPasskeyAuthentication(
467
+ $clientId: String!,
468
+ $id: String!,
469
+ $authentication: AuthenticationOptionsInput!,
470
+ $nonce: String!,
471
+ $domain: String,
472
+ $sessionExpiration: String,
473
+ $ua: String) {
474
+ verifyPasskeyAuthentication(
475
+ clientId: $clientId,
476
+ id: $id,
477
+ authentication: $authentication,
478
+ nonce: $nonce,
479
+ domain: $domain,
480
+ sessionExpiration: $sessionExpiration,
481
+ ua: $ua) {
482
+ status,
483
+ idToken,
484
+ accessToken,
485
+ refreshToken,
486
+ userId,
487
+ username,
488
+ email
489
+ }
490
+ }`
491
+ }, N = {
492
+ GET_REGISTRATION_OPTIONS: {
493
+ schema: V.GET_REGISTRATION_OPTIONS,
494
+ method: "getPasskeyRegistrationOptions"
495
+ },
496
+ VERIFY_REGISTRATION: {
497
+ schema: V.VERIFY_REGISTRATION,
498
+ method: "verifyPasskeyRegistration"
499
+ },
500
+ GET_AUTHENTICATION_OPTIONS: {
501
+ schema: V.GET_AUTHENTICATION_OPTIONS,
502
+ method: "getPasskeyAuthenticationOptions"
503
+ },
504
+ VERIFY_AUTHENTICATION: {
505
+ schema: V.VERIFY_AUTHENTICATION,
506
+ method: "verifyPasskeyAuthentication"
507
+ }
508
+ }, k = async ({
509
+ accessToken: e,
510
+ type: t,
511
+ clientId: n,
512
+ params: a = {},
513
+ endpoint: s
514
+ }) => {
515
+ try {
516
+ const o = `Bearer ${e}`, c = await fetch(`${s}/graphql`, {
517
+ credentials: fe,
518
+ method: Te,
519
+ headers: {
520
+ authorization: o,
521
+ "Content-Type": ye,
522
+ [ie.CLIENT_ID]: `${n}`
523
+ },
524
+ body: JSON.stringify({
525
+ query: t.schema,
526
+ variables: a
527
+ })
528
+ });
529
+ if (c.status !== 200)
530
+ return { status: A, data: [] };
531
+ const { data: r } = await c.json();
532
+ return {
533
+ status: L,
534
+ data: r[t.method]
535
+ };
536
+ } catch (o) {
537
+ return console.error(o), { status: A, data: [] };
538
+ }
539
+ }, J = async ({
540
+ type: e,
541
+ clientId: t,
542
+ params: n = {},
543
+ endpoint: a
544
+ }) => {
545
+ try {
546
+ const s = await fetch(`${a}/${e}`, {
547
+ credentials: fe,
548
+ method: Te,
549
+ headers: {
550
+ "Content-Type": ye,
551
+ [ie.CLIENT_ID]: `${t}`
552
+ },
553
+ body: JSON.stringify(n)
554
+ });
555
+ if (s.status !== 200)
556
+ return { status: A, data: [] };
557
+ const { data: o } = await s.json();
558
+ return {
559
+ status: L,
560
+ data: o || []
561
+ };
562
+ } catch (s) {
563
+ return console.error(s), { status: A, data: [] };
564
+ }
565
+ }, st = process.env.NODE_ENV === "production", rt = !st, Ee = {
566
+ isLoading: !0,
567
+ isAuthenticated: !1,
568
+ user: void 0,
569
+ logoutReason: "",
570
+ debug: !1,
571
+ authenticationType: ""
572
+ }, ot = (e) => {
573
+ try {
574
+ const t = ve(e);
575
+ return t ? t[T.USER_ID_KEY] : "";
576
+ } catch {
577
+ return "";
578
+ }
579
+ }, it = async ({
580
+ userId: e,
581
+ clientId: t,
582
+ domain: n,
583
+ idToken: a = "",
584
+ endpoint: s
585
+ }) => {
586
+ try {
587
+ return {
588
+ status: (await J({
589
+ endpoint: s,
590
+ type: M.LOGOUT,
591
+ clientId: t,
592
+ params: {
593
+ userId: e,
594
+ domain: n,
595
+ idToken: a
596
+ }
597
+ }))?.status || A
598
+ };
599
+ } catch {
600
+ return {
601
+ status: A
602
+ };
603
+ }
604
+ }, ct = async ({
605
+ username: e,
606
+ password: t,
607
+ clientId: n,
608
+ nonce: a,
609
+ type: s,
610
+ sessionExpiration: o,
611
+ code: c,
612
+ code_verifier: r,
613
+ domain: i,
614
+ ua: w,
615
+ endpoint: d
616
+ }) => {
617
+ try {
618
+ const m = await J({
619
+ endpoint: d,
620
+ type: M.LOGIN,
621
+ clientId: n,
622
+ params: {
623
+ type: s || C.ID_AND_ACCESS_TOKEN,
624
+ username: e,
625
+ password: t,
626
+ sessionExpiration: o,
627
+ nonce: a,
628
+ code: c,
629
+ code_verifier: r,
630
+ domain: i,
631
+ ua: w
632
+ }
633
+ }), y = await D(m?.data?.idToken);
634
+ return y && y.payload[T.USER_ID_KEY] !== "" && y.payload[T.NONCE_KEY] === a ? {
635
+ idToken: m.data.idToken,
636
+ accessToken: m.data.accessToken,
637
+ refreshToken: m.data.refreshToken,
638
+ userId: y.payload[T.USER_ID_KEY],
639
+ email: y.payload[T.EMAIL_KEY],
640
+ status: !0
641
+ } : {
642
+ status: !1
643
+ };
644
+ } catch {
645
+ return {
646
+ status: !1
647
+ };
648
+ }
649
+ }, ut = async ({
650
+ nonce: e,
651
+ clientId: t,
652
+ code_challenge: n,
653
+ endpoint: a
654
+ }) => {
655
+ try {
656
+ const s = await J({
657
+ endpoint: a,
658
+ type: M.CODE,
659
+ clientId: t,
660
+ params: {
661
+ type: C.CODE,
662
+ nonce: e,
663
+ code_challenge: n
664
+ }
665
+ });
666
+ return s?.data?.code ? {
667
+ status: L,
668
+ data: s.data.code
669
+ } : {
670
+ status: A,
671
+ data: ""
672
+ };
673
+ } catch {
674
+ return {
675
+ status: A,
676
+ data: ""
677
+ };
678
+ }
679
+ }, lt = async ({
680
+ clientId: e,
681
+ userId: t,
682
+ nonce: n,
683
+ refreshToken: a,
684
+ accessToken: s,
685
+ domain: o,
686
+ endpoint: c
687
+ }) => {
688
+ try {
689
+ const r = await J({
690
+ endpoint: c,
691
+ type: M.REFRESH,
692
+ clientId: e,
693
+ params: {
694
+ type: C.REFRESH_TOKEN,
695
+ userId: t,
696
+ nonce: n,
697
+ refreshToken: a,
698
+ accessToken: s,
699
+ domain: o
700
+ }
701
+ }), i = await D(r?.data?.accessToken);
702
+ return i && i.payload[T.USER_ID_KEY] !== "" && i.payload[T.NONCE_KEY] === n ? {
703
+ accessToken: r.data.accessToken,
704
+ refreshToken: r.data.refreshToken,
705
+ userId: i.payload[T.USER_ID_KEY],
706
+ status: !0
707
+ } : {
708
+ status: !1
709
+ };
710
+ } catch {
711
+ return {
712
+ status: !1
713
+ };
714
+ }
715
+ };
716
+ class dt {
717
+ constructor(t = null, n = null) {
718
+ K(this, "refreshTokenPromise", null);
719
+ K(this, "accessToken");
720
+ K(this, "refreshToken");
721
+ this.accessToken = t || "", this.refreshToken = n || "";
722
+ }
723
+ async refreshtoken({
724
+ clientId: t,
725
+ userId: n,
726
+ nonce: a,
727
+ domain: s,
728
+ endpoint: o
729
+ }) {
730
+ this.refreshTokenPromise || (this.refreshTokenPromise = this._refreshToken({
731
+ endpoint: o,
732
+ clientId: t,
733
+ userId: n,
734
+ nonce: a,
735
+ domain: s
736
+ }));
737
+ try {
738
+ return await this.refreshTokenPromise;
739
+ } finally {
740
+ this.refreshTokenPromise = null;
741
+ }
742
+ }
743
+ async _refreshToken({
744
+ endpoint: t,
745
+ clientId: n,
746
+ userId: a,
747
+ nonce: s,
748
+ domain: o
749
+ }) {
750
+ const c = await D(this.refreshToken);
751
+ if (c && c.payload[T.USER_ID_KEY] !== "") {
752
+ const r = await lt({
753
+ endpoint: t,
754
+ clientId: n,
755
+ userId: a,
756
+ nonce: s,
757
+ refreshToken: this.refreshToken,
758
+ accessToken: this.accessToken,
759
+ domain: o
760
+ });
761
+ return r.status ? (this.accessToken = r.accessToken, this.refreshToken = r.refreshToken, {
762
+ status: L,
763
+ newAccessToken: r.accessToken,
764
+ newRefreshToken: r.refreshToken
765
+ }) : {
766
+ status: A
767
+ };
768
+ } else
769
+ return {
770
+ status: A
771
+ };
772
+ }
773
+ }
774
+ const P = () => {
775
+ throw new Error(at);
776
+ }, me = $e({
777
+ isAuthenticated: !1,
778
+ isLoading: !1,
779
+ login: P,
780
+ logout: P,
781
+ getAccessToken: P,
782
+ getIdToken: P,
783
+ registeringForPasskey: P,
784
+ loginWithPasskey: P,
785
+ logoutReason: "",
786
+ authenticationType: ""
787
+ }), ht = () => ({
788
+ ...Ke(me)
789
+ }), gt = (e) => S(
790
+ (...t) => {
791
+ e && console.info(`==> [Auth ${Date.now()}]: `, ...t);
792
+ },
793
+ [e]
794
+ ), pt = De.createContext({
795
+ state: Ee,
796
+ dispatch: () => {
797
+ }
798
+ }), ft = (e, t) => t?.type === U ? {
799
+ ...e,
800
+ isLoading: t.payload.isLoading
801
+ } : t?.type === x ? {
802
+ ...e,
803
+ isLoading: !1,
804
+ isAuthenticated: !0,
805
+ user: t.payload.user,
806
+ authenticationType: t.payload.authenticationType,
807
+ logoutReason: ""
808
+ } : t?.type === pe ? {
809
+ ...e,
810
+ isLoading: !1,
811
+ isAuthenticated: !1,
812
+ user: void 0,
813
+ authenticationType: "",
814
+ logoutReason: t.payload.logoutReason
815
+ } : e, Tt = ({ children: e }) => {
816
+ const t = ht();
817
+ return /* @__PURE__ */ H(Ve.Provider, { value: t, children: e });
818
+ }, wt = ({
819
+ children: e,
820
+ sessionExpiration: t,
821
+ clientId: n,
822
+ domain: a = "",
823
+ debug: s = !1,
824
+ endpoint: o = rt ? "https://auth.gizmette.local.com:3003" : "https://mylogin.gizmette.com/auth"
825
+ }) => {
826
+ const [c, r] = Ye(ft, {
827
+ ...Ee,
828
+ debug: s
829
+ }), i = gt(s), w = Ge(!1), [d, m, , y] = Y({
830
+ key: `${G}::${n}::@@user@@`
831
+ }), [f, E, , Z] = Y({
832
+ key: `${G}::${n}::@@access@@`
833
+ }), [Re, W, , ee] = Y(
834
+ {
835
+ key: `${G}::${n}::@@refresh@@`
836
+ }
837
+ ), [Ae, te, , ne] = Y({
838
+ key: `${G}::${n}::@@nonce@@`
839
+ }), we = new dt(f, Re), $ = S(() => {
840
+ i("removeLocalStorage: removing local storage"), y(), Z(), ee(), ne();
841
+ }, [
842
+ Z,
843
+ y,
844
+ ne,
845
+ ee,
846
+ i
847
+ ]), v = S(
848
+ (u) => {
849
+ i(
850
+ "removeStateAndLocalStorage: removing state and local storage with reason: ",
851
+ u
852
+ ), r({
853
+ type: pe,
854
+ payload: {
855
+ logoutReason: u || b
856
+ }
857
+ }), $(), r({ type: U, payload: { isLoading: !1 } });
858
+ },
859
+ [$, i]
860
+ ), I = S(
861
+ async (u) => {
862
+ i("invalidateAndLogout: invalidating and logging out");
863
+ const { user: h } = c, l = h?.userId || ot(d);
864
+ l || i(
865
+ "invalidateAndLogout: user cannot be identified, logging out without userId"
866
+ ), await it({
867
+ userId: l,
868
+ clientId: n,
869
+ domain: a,
870
+ idToken: d,
871
+ endpoint: o
872
+ }), v(u || b);
873
+ },
874
+ [
875
+ d,
876
+ c,
877
+ n,
878
+ a,
879
+ v,
880
+ i,
881
+ o
882
+ ]
883
+ );
884
+ ce(() => {
885
+ if (!w.current)
886
+ return c.isLoading && d !== null ? (async () => {
887
+ try {
888
+ const u = await D(d);
889
+ u && u.payload[T.USER_ID_KEY] !== "" ? (i("useEffect: setting the authentication state"), r({
890
+ type: x,
891
+ payload: {
892
+ authenticationType: u.payload[T.AUTH_TYPE_KEY],
893
+ user: {
894
+ userId: u.payload[T.USER_ID_KEY],
895
+ username: u.payload[T.USERNAME_KEY],
896
+ email: u.payload[T.EMAIL_KEY]
897
+ }
898
+ }
899
+ })) : (i("useEffect: invalid JWT, invalidating and logging out"), await I(b));
900
+ } catch {
901
+ i(
902
+ "useEffect: exception validating JWT, invalidating and logging out"
903
+ ), await I(b);
904
+ }
905
+ })() : (i("useEffect: setting the loading state to false"), r({ type: U, payload: { isLoading: !1 } })), () => {
906
+ w.current = !0;
907
+ };
908
+ }, [c.isLoading, d, I, i]);
909
+ const Ie = async (u, h) => {
910
+ r({ type: U, payload: { isLoading: !0 } }), $();
911
+ const l = z();
912
+ te(l), i("login: Logging in with password");
913
+ const { code_verifier: _, code_challenge: ke } = await Ue(), ae = await ut({
914
+ endpoint: o,
915
+ nonce: l,
916
+ clientId: n,
917
+ code_challenge: ke
918
+ });
919
+ if (ae.status) {
920
+ const O = await ct({
921
+ endpoint: o,
922
+ username: u,
923
+ password: h,
924
+ clientId: n,
925
+ sessionExpiration: t,
926
+ nonce: l,
927
+ type: C.CODE,
928
+ code: ae.data,
929
+ code_verifier: _,
930
+ domain: a,
931
+ ua: navigator.userAgent
932
+ });
933
+ return O.status ? (m(O.idToken), E(O.accessToken), W(O.refreshToken), r({
934
+ type: x,
935
+ payload: {
936
+ authenticationType: C.CODE,
937
+ user: {
938
+ userId: O.userId,
939
+ username: u,
940
+ email: O.email
941
+ }
942
+ }
943
+ }), !0) : (v(Q), !1);
944
+ }
945
+ return !1;
946
+ }, _e = async (u) => {
947
+ u?.preventDefault(), await I(tt);
948
+ }, Se = async () => {
949
+ const { isAuthenticated: u, user: h } = c;
950
+ try {
951
+ if (u && h && h.userId) {
952
+ if (f) {
953
+ i("getAccessToken");
954
+ const _ = await D(f);
955
+ if (_ && _.payload[T.USER_ID_KEY] !== "")
956
+ return f;
957
+ }
958
+ i("getAccessToken: invalid access token, trying to refresh it");
959
+ const l = await we.refreshtoken({
960
+ endpoint: o,
961
+ clientId: n,
962
+ userId: h.userId,
963
+ nonce: Ae,
964
+ domain: a
965
+ });
966
+ return l.status && l.status === "success" && l.newAccessToken ? (E(l.newAccessToken), W(l.newRefreshToken), l.newAccessToken) : (i(
967
+ "getAccessToken: invalid refresh token, need to re-authenticate"
968
+ ), await I(b), "");
969
+ }
970
+ return i(
971
+ "getAccessToken: user is not authenticated, cannot get access token"
972
+ ), await I(b), "";
973
+ } catch {
974
+ return i(
975
+ "getAccessToken: exception occurred, invalidating and logging out"
976
+ ), await I(nt), "";
977
+ }
978
+ }, Oe = () => c.isAuthenticated && d ? d : "", be = async () => {
979
+ const { user: u } = c;
980
+ let h = await k({
981
+ endpoint: o,
982
+ accessToken: f,
983
+ clientId: n,
984
+ type: N.GET_REGISTRATION_OPTIONS,
985
+ params: {
986
+ clientId: n,
987
+ id: u?.userId,
988
+ username: u?.username
989
+ }
990
+ });
991
+ if (h.status)
992
+ try {
993
+ const l = await Je({
994
+ optionsJSON: h.data
995
+ });
996
+ return h = await k({
997
+ endpoint: o,
998
+ accessToken: f,
999
+ clientId: n,
1000
+ type: N.VERIFY_REGISTRATION,
1001
+ params: {
1002
+ clientId: n,
1003
+ id: u?.userId,
1004
+ username: u?.username,
1005
+ registration: l
1006
+ }
1007
+ }), !!(h.status && h.data.length > 0);
1008
+ } catch {
1009
+ return await k({
1010
+ endpoint: o,
1011
+ accessToken: f,
1012
+ clientId: n,
1013
+ type: N.VERIFY_REGISTRATION,
1014
+ params: {
1015
+ clientId: n,
1016
+ id: u?.userId,
1017
+ username: u?.username,
1018
+ registration: {}
1019
+ }
1020
+ }), !1;
1021
+ }
1022
+ return !1;
1023
+ }, Ne = async () => {
1024
+ r({ type: U, payload: { isLoading: !0 } }), $();
1025
+ const u = z();
1026
+ te(u), i("loginWithPasskey");
1027
+ const h = z();
1028
+ let l = await k({
1029
+ endpoint: o,
1030
+ accessToken: f,
1031
+ clientId: n,
1032
+ type: N.GET_AUTHENTICATION_OPTIONS,
1033
+ params: {
1034
+ id: h,
1035
+ clientId: n
1036
+ }
1037
+ });
1038
+ if (l.status)
1039
+ try {
1040
+ const _ = await Be({
1041
+ optionsJSON: l.data
1042
+ });
1043
+ return l = await k({
1044
+ endpoint: o,
1045
+ accessToken: f,
1046
+ clientId: n,
1047
+ type: N.VERIFY_AUTHENTICATION,
1048
+ params: {
1049
+ clientId: n,
1050
+ id: h,
1051
+ authentication: _,
1052
+ nonce: u,
1053
+ domain: a,
1054
+ sessionExpiration: t,
1055
+ ua: navigator.userAgent
1056
+ }
1057
+ }), l.data.status === L ? (m(l.data.idToken), E(l.data.accessToken), W(l.data.refreshToken), r({
1058
+ type: x,
1059
+ payload: {
1060
+ authenticationType: C.PASSKEY,
1061
+ user: {
1062
+ userId: l.data.userId,
1063
+ username: l.data.username,
1064
+ email: l.data.email
1065
+ }
1066
+ }
1067
+ }), !0) : (v(Q), !1);
1068
+ } catch {
1069
+ return await k({
1070
+ endpoint: o,
1071
+ accessToken: f,
1072
+ clientId: n,
1073
+ type: N.VERIFY_AUTHENTICATION,
1074
+ params: {
1075
+ clientId: n,
1076
+ id: h,
1077
+ authentication: {},
1078
+ nonce: u,
1079
+ domain: a,
1080
+ sessionExpiration: t
1081
+ }
1082
+ }), v(Q), !1;
1083
+ }
1084
+ return !1;
1085
+ };
1086
+ return /* @__PURE__ */ H(pt.Provider, { value: { state: c, dispatch: r }, children: /* @__PURE__ */ H(
1087
+ me.Provider,
1088
+ {
1089
+ value: {
1090
+ ...c,
1091
+ login: Ie,
1092
+ logout: _e,
1093
+ getAccessToken: Se,
1094
+ getIdToken: Oe,
1095
+ registeringForPasskey: be,
1096
+ loginWithPasskey: Ne
1097
+ },
1098
+ children: /* @__PURE__ */ H(Tt, { children: e })
1099
+ }
1100
+ ) });
1101
+ };
1102
+ export {
1103
+ wt as AuthProvider
1104
+ };