@versini/auth-provider 7.5.3 → 8.0.1

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/index.js CHANGED
@@ -1,2073 +1,18 @@
1
- var yt = Object.defineProperty;
2
- var pt = (e, t, r) => t in e ? yt(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
3
- var X = (e, t, r) => pt(e, typeof t != "symbol" ? t + "" : t, r);
4
- import { jsx as _e } from "react/jsx-runtime";
5
- import ft, { useSyncExternalStore as Et, useCallback as D, useEffect as Ue, createContext as gt, useReducer as mt, useRef as wt, useContext as St } from "react";
1
+ import { nt as t, ft as r } from "./index-BUUrGwOT.js";
6
2
  /*!
7
- @versini/auth-provider v7.5.3
3
+ @versini/auth-provider v8.0.1
8
4
  © 2025 gizmette.com
9
5
  */
10
6
  try {
11
7
  window.__VERSINI_AUTH_CLIENT__ || (window.__VERSINI_AUTH_CLIENT__ = {
12
- version: "7.5.3",
13
- buildTime: "04/02/2025 05:48 PM EDT",
8
+ version: "8.0.1",
9
+ buildTime: "04/13/2025 07:33 PM EDT",
14
10
  homepage: "https://github.com/aversini/auth-client",
15
11
  license: "MIT"
16
12
  });
17
13
  } catch {
18
14
  }
19
- function I(e) {
20
- const t = new Uint8Array(e);
21
- let r = "";
22
- for (const n of t)
23
- r += String.fromCharCode(n);
24
- return btoa(r).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
25
- }
26
- function se(e) {
27
- const t = e.replace(/-/g, "+").replace(/_/g, "/"), r = (4 - t.length % 4) % 4, a = t.padEnd(t.length + r, "="), n = atob(a), s = new ArrayBuffer(n.length), o = new Uint8Array(s);
28
- for (let i = 0; i < n.length; i++)
29
- o[i] = n.charCodeAt(i);
30
- return s;
31
- }
32
- function me() {
33
- return At.stubThis(globalThis?.PublicKeyCredential !== void 0 && typeof globalThis.PublicKeyCredential == "function");
34
- }
35
- const At = {
36
- stubThis: (e) => e
37
- };
38
- function He(e) {
39
- const { id: t } = e;
40
- return {
41
- ...e,
42
- id: se(t),
43
- /**
44
- * `descriptor.transports` is an array of our `AuthenticatorTransportFuture` that includes newer
45
- * transports that TypeScript's DOM lib is ignorant of. Convince TS that our list of transports
46
- * are fine to pass to WebAuthn since browsers will recognize the new value.
47
- */
48
- transports: e.transports
49
- };
50
- }
51
- function Le(e) {
52
- return (
53
- // Consider localhost valid as well since it's okay wrt Secure Contexts
54
- e === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)
55
- );
56
- }
57
- class b extends Error {
58
- constructor({ message: t, code: r, cause: a, name: n }) {
59
- super(t, { cause: a }), Object.defineProperty(this, "code", {
60
- enumerable: !0,
61
- configurable: !0,
62
- writable: !0,
63
- value: void 0
64
- }), this.name = n ?? a.name, this.code = r;
65
- }
66
- }
67
- function Tt({ error: e, options: t }) {
68
- const { publicKey: r } = t;
69
- if (!r)
70
- throw Error("options was missing required publicKey property");
71
- if (e.name === "AbortError") {
72
- if (t.signal instanceof AbortSignal)
73
- return new b({
74
- message: "Registration ceremony was sent an abort signal",
75
- code: "ERROR_CEREMONY_ABORTED",
76
- cause: e
77
- });
78
- } else if (e.name === "ConstraintError") {
79
- if (r.authenticatorSelection?.requireResidentKey === !0)
80
- return new b({
81
- message: "Discoverable credentials were required but no available authenticator supported it",
82
- code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",
83
- cause: e
84
- });
85
- if (
86
- // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024
87
- t.mediation === "conditional" && r.authenticatorSelection?.userVerification === "required"
88
- )
89
- return new b({
90
- message: "User verification was required during automatic registration but it could not be performed",
91
- code: "ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",
92
- cause: e
93
- });
94
- if (r.authenticatorSelection?.userVerification === "required")
95
- return new b({
96
- message: "User verification was required but no available authenticator supported it",
97
- code: "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",
98
- cause: e
99
- });
100
- } else {
101
- if (e.name === "InvalidStateError")
102
- return new b({
103
- message: "The authenticator was previously registered",
104
- code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",
105
- cause: e
106
- });
107
- if (e.name === "NotAllowedError")
108
- return new b({
109
- message: e.message,
110
- code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
111
- cause: e
112
- });
113
- if (e.name === "NotSupportedError")
114
- return r.pubKeyCredParams.filter((n) => n.type === "public-key").length === 0 ? new b({
115
- message: 'No entry in pubKeyCredParams was of type "public-key"',
116
- code: "ERROR_MALFORMED_PUBKEYCREDPARAMS",
117
- cause: e
118
- }) : new b({
119
- message: "No available authenticator supported any of the specified pubKeyCredParams algorithms",
120
- code: "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",
121
- cause: e
122
- });
123
- if (e.name === "SecurityError") {
124
- const a = globalThis.location.hostname;
125
- if (Le(a)) {
126
- if (r.rp.id !== a)
127
- return new b({
128
- message: `The RP ID "${r.rp.id}" is invalid for this domain`,
129
- code: "ERROR_INVALID_RP_ID",
130
- cause: e
131
- });
132
- } else return new b({
133
- message: `${globalThis.location.hostname} is an invalid domain`,
134
- code: "ERROR_INVALID_DOMAIN",
135
- cause: e
136
- });
137
- } else if (e.name === "TypeError") {
138
- if (r.user.id.byteLength < 1 || r.user.id.byteLength > 64)
139
- return new b({
140
- message: "User ID was not between 1 and 64 characters",
141
- code: "ERROR_INVALID_USER_ID_LENGTH",
142
- cause: e
143
- });
144
- } else if (e.name === "UnknownError")
145
- return new b({
146
- message: "The authenticator was unable to process the specified options, or could not create a new credential",
147
- code: "ERROR_AUTHENTICATOR_GENERAL_ERROR",
148
- cause: e
149
- });
150
- }
151
- return e;
152
- }
153
- class bt {
154
- constructor() {
155
- Object.defineProperty(this, "controller", {
156
- enumerable: !0,
157
- configurable: !0,
158
- writable: !0,
159
- value: void 0
160
- });
161
- }
162
- createNewAbortSignal() {
163
- if (this.controller) {
164
- const r = new Error("Cancelling existing WebAuthn API call for new one");
165
- r.name = "AbortError", this.controller.abort(r);
166
- }
167
- const t = new AbortController();
168
- return this.controller = t, t.signal;
169
- }
170
- cancelCeremony() {
171
- if (this.controller) {
172
- const t = new Error("Manually cancelling existing WebAuthn API call");
173
- t.name = "AbortError", this.controller.abort(t), this.controller = void 0;
174
- }
175
- }
176
- }
177
- const $e = new bt(), Rt = ["cross-platform", "platform"];
178
- function We(e) {
179
- if (e && !(Rt.indexOf(e) < 0))
180
- return e;
181
- }
182
- async function _t(e) {
183
- !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 });
184
- const { optionsJSON: t, useAutoRegister: r = !1 } = e;
185
- if (!me())
186
- throw new Error("WebAuthn is not supported in this browser");
187
- const a = {
188
- ...t,
189
- challenge: se(t.challenge),
190
- user: {
191
- ...t.user,
192
- id: se(t.user.id)
193
- },
194
- excludeCredentials: t.excludeCredentials?.map(He)
195
- }, n = {};
196
- r && (n.mediation = "conditional"), n.publicKey = a, n.signal = $e.createNewAbortSignal();
197
- let s;
198
- try {
199
- s = await navigator.credentials.create(n);
200
- } catch (h) {
201
- throw Tt({ error: h, options: n });
202
- }
203
- if (!s)
204
- throw new Error("Registration was not completed");
205
- const { id: o, rawId: i, response: c, type: m } = s;
206
- let d;
207
- typeof c.getTransports == "function" && (d = c.getTransports());
208
- let p;
209
- if (typeof c.getPublicKeyAlgorithm == "function")
210
- try {
211
- p = c.getPublicKeyAlgorithm();
212
- } catch (h) {
213
- ue("getPublicKeyAlgorithm()", h);
214
- }
215
- let E;
216
- if (typeof c.getPublicKey == "function")
217
- try {
218
- const h = c.getPublicKey();
219
- h !== null && (E = I(h));
220
- } catch (h) {
221
- ue("getPublicKey()", h);
222
- }
223
- let y;
224
- if (typeof c.getAuthenticatorData == "function")
225
- try {
226
- y = I(c.getAuthenticatorData());
227
- } catch (h) {
228
- ue("getAuthenticatorData()", h);
229
- }
230
- return {
231
- id: o,
232
- rawId: I(i),
233
- response: {
234
- attestationObject: I(c.attestationObject),
235
- clientDataJSON: I(c.clientDataJSON),
236
- transports: d,
237
- publicKeyAlgorithm: p,
238
- publicKey: E,
239
- authenticatorData: y
240
- },
241
- type: m,
242
- clientExtensionResults: s.getClientExtensionResults(),
243
- authenticatorAttachment: We(s.authenticatorAttachment)
244
- };
245
- }
246
- function ue(e, t) {
247
- console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.
248
- `, t);
249
- }
250
- function It() {
251
- if (!me())
252
- return le.stubThis(new Promise((t) => t(!1)));
253
- const e = globalThis.PublicKeyCredential;
254
- return e?.isConditionalMediationAvailable === void 0 ? le.stubThis(new Promise((t) => t(!1))) : le.stubThis(e.isConditionalMediationAvailable());
255
- }
256
- const le = {
257
- stubThis: (e) => e
258
- };
259
- function Ot({ error: e, options: t }) {
260
- const { publicKey: r } = t;
261
- if (!r)
262
- throw Error("options was missing required publicKey property");
263
- if (e.name === "AbortError") {
264
- if (t.signal instanceof AbortSignal)
265
- return new b({
266
- message: "Authentication ceremony was sent an abort signal",
267
- code: "ERROR_CEREMONY_ABORTED",
268
- cause: e
269
- });
270
- } else {
271
- if (e.name === "NotAllowedError")
272
- return new b({
273
- message: e.message,
274
- code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",
275
- cause: e
276
- });
277
- if (e.name === "SecurityError") {
278
- const a = globalThis.location.hostname;
279
- if (Le(a)) {
280
- if (r.rpId !== a)
281
- return new b({
282
- message: `The RP ID "${r.rpId}" is invalid for this domain`,
283
- code: "ERROR_INVALID_RP_ID",
284
- cause: e
285
- });
286
- } else return new b({
287
- message: `${globalThis.location.hostname} is an invalid domain`,
288
- code: "ERROR_INVALID_DOMAIN",
289
- cause: e
290
- });
291
- } else if (e.name === "UnknownError")
292
- return new b({
293
- message: "The authenticator was unable to process the specified options, or could not create a new assertion signature",
294
- code: "ERROR_AUTHENTICATOR_GENERAL_ERROR",
295
- cause: e
296
- });
297
- }
298
- return e;
299
- }
300
- async function vt(e) {
301
- !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 });
302
- const { optionsJSON: t, useBrowserAutofill: r = !1, verifyBrowserAutofillInput: a = !0 } = e;
303
- if (!me())
304
- throw new Error("WebAuthn is not supported in this browser");
305
- let n;
306
- t.allowCredentials?.length !== 0 && (n = t.allowCredentials?.map(He));
307
- const s = {
308
- ...t,
309
- challenge: se(t.challenge),
310
- allowCredentials: n
311
- }, o = {};
312
- if (r) {
313
- if (!await It())
314
- throw Error("Browser does not support WebAuthn autofill");
315
- if (document.querySelectorAll("input[autocomplete$='webauthn']").length < 1 && a)
316
- throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');
317
- o.mediation = "conditional", s.allowCredentials = [];
318
- }
319
- o.publicKey = s, o.signal = $e.createNewAbortSignal();
320
- let i;
321
- try {
322
- i = await navigator.credentials.get(o);
323
- } catch (y) {
324
- throw Ot({ error: y, options: o });
325
- }
326
- if (!i)
327
- throw new Error("Authentication was not completed");
328
- const { id: c, rawId: m, response: d, type: p } = i;
329
- let E;
330
- return d.userHandle && (E = I(d.userHandle)), {
331
- id: c,
332
- rawId: I(m),
333
- response: {
334
- authenticatorData: I(d.authenticatorData),
335
- clientDataJSON: I(d.clientDataJSON),
336
- signature: I(d.signature),
337
- userHandle: E
338
- },
339
- type: p,
340
- clientExtensionResults: i.getClientExtensionResults(),
341
- authenticatorAttachment: We(i.authenticatorAttachment)
342
- };
343
- }
344
- var kt = Object.defineProperty, Ct = (e, t, r) => t in e ? kt(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r, f = (e, t, r) => Ct(e, typeof t != "symbol" ? t + "" : t, r);
345
- /*!
346
- @versini/auth-common v4.2.1
347
- © 2025 gizmette.com
348
- */
349
- try {
350
- window.__VERSINI_AUTH_COMMON__ || (window.__VERSINI_AUTH_COMMON__ = {
351
- version: "4.2.1",
352
- buildTime: "04/02/2025 05:48 PM EDT",
353
- homepage: "https://github.com/aversini/auth-client",
354
- license: "MIT"
355
- });
356
- } catch {
357
- }
358
- const x = {
359
- ID_TOKEN: "id_token",
360
- ACCESS_TOKEN: "token",
361
- ID_AND_ACCESS_TOKEN: "id_token token",
362
- CODE: "code",
363
- REFRESH_TOKEN: "refresh_token",
364
- PASSKEY: "passkey"
365
- }, Je = {
366
- CLIENT_ID: "X-Auth-ClientId"
367
- }, g = {
368
- ALG: "RS256",
369
- USER_ID_KEY: "sub",
370
- USERNAME_KEY: "username",
371
- EMAIL_KEY: "email",
372
- TOKEN_ID_KEY: "__raw",
373
- NONCE_KEY: "_nonce",
374
- AUTH_TYPE_KEY: "auth_type",
375
- EXPIRES_AT_KEY: "exp",
376
- CREATED_AT_KEY: "iat",
377
- SCOPES_KEY: "scopes",
378
- CLIENT_ID_KEY: "aud",
379
- ISSUER: "gizmette.com"
380
- }, Pt = `-----BEGIN PUBLIC KEY-----
381
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsF6i3Jd9fY/3COqCw/m7
382
- w5PKyTYLGAI2I6SIIdpe6i6DOCbEkmDz7LdVsBqwNtVi8gvWYIj+8ol6rU3qu1v5
383
- i1Jd45GSK4kzkVdgCmQZbM5ak0KI99q5wsrAIzUd+LRJ2HRvWtr5IYdsIiXaQjle
384
- aMwPFOIcJH+rKfFgNcHLcaS5syp7zU1ANwZ+trgR+DifBr8TLVkBynmNeTyhDm2+
385
- l0haqjMk0UoNPPE8iYBWUHQJJE1Dqstj65d6Eh5g64Pao25y4cmYJbKjiblIGEkE
386
- sjqybA9mARAqh9k/eiIopecWSiffNQTwVQVd2I9ZH3BalhEXHlqFgrjz51kFqg81
387
- awIDAQAB
388
- -----END PUBLIC KEY-----`, oe = {
389
- CODE: "code",
390
- LOGOUT: "logout",
391
- LOGIN: "login",
392
- REFRESH: "refresh"
393
- }, Z = new TextEncoder(), G = new TextDecoder();
394
- function Nt(...e) {
395
- const t = e.reduce((n, { length: s }) => n + s, 0), r = new Uint8Array(t);
396
- let a = 0;
397
- for (const n of e)
398
- r.set(n, a), a += n.length;
399
- return r;
400
- }
401
- function Kt(e) {
402
- if (Uint8Array.fromBase64)
403
- return Uint8Array.fromBase64(e);
404
- const t = atob(e), r = new Uint8Array(t.length);
405
- for (let a = 0; a < t.length; a++)
406
- r[a] = t.charCodeAt(a);
407
- return r;
408
- }
409
- function F(e) {
410
- if (Uint8Array.fromBase64)
411
- return Uint8Array.fromBase64(typeof e == "string" ? e : G.decode(e), {
412
- alphabet: "base64url"
413
- });
414
- let t = e;
415
- t instanceof Uint8Array && (t = G.decode(t)), t = t.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
416
- try {
417
- return Kt(t);
418
- } catch {
419
- throw new TypeError("The input to be decoded is not correctly encoded.");
420
- }
421
- }
422
- class P extends Error {
423
- constructor(t, r) {
424
- var a;
425
- super(t, r), f(this, "code", "ERR_JOSE_GENERIC"), this.name = this.constructor.name, (a = Error.captureStackTrace) == null || a.call(Error, this, this.constructor);
426
- }
427
- }
428
- f(P, "code", "ERR_JOSE_GENERIC");
429
- class R extends P {
430
- constructor(t, r, a = "unspecified", n = "unspecified") {
431
- super(t, { cause: { claim: a, reason: n, payload: r } }), f(this, "code", "ERR_JWT_CLAIM_VALIDATION_FAILED"), f(this, "claim"), f(this, "reason"), f(this, "payload"), this.claim = a, this.reason = n, this.payload = r;
432
- }
433
- }
434
- f(R, "code", "ERR_JWT_CLAIM_VALIDATION_FAILED");
435
- class Ee extends P {
436
- constructor(t, r, a = "unspecified", n = "unspecified") {
437
- super(t, { cause: { claim: a, reason: n, payload: r } }), f(this, "code", "ERR_JWT_EXPIRED"), f(this, "claim"), f(this, "reason"), f(this, "payload"), this.claim = a, this.reason = n, this.payload = r;
438
- }
439
- }
440
- f(Ee, "code", "ERR_JWT_EXPIRED");
441
- class Ye extends P {
442
- constructor() {
443
- super(...arguments), f(this, "code", "ERR_JOSE_ALG_NOT_ALLOWED");
444
- }
445
- }
446
- f(Ye, "code", "ERR_JOSE_ALG_NOT_ALLOWED");
447
- let k = class extends P {
448
- constructor() {
449
- super(...arguments), f(this, "code", "ERR_JOSE_NOT_SUPPORTED");
450
- }
451
- };
452
- f(k, "code", "ERR_JOSE_NOT_SUPPORTED");
453
- class w extends P {
454
- constructor() {
455
- super(...arguments), f(this, "code", "ERR_JWS_INVALID");
456
- }
457
- }
458
- f(w, "code", "ERR_JWS_INVALID");
459
- class _ extends P {
460
- constructor() {
461
- super(...arguments), f(this, "code", "ERR_JWT_INVALID");
462
- }
463
- }
464
- f(_, "code", "ERR_JWT_INVALID");
465
- class xe extends P {
466
- constructor(t = "signature verification failed", r) {
467
- super(t, r), f(this, "code", "ERR_JWS_SIGNATURE_VERIFICATION_FAILED");
468
- }
469
- }
470
- f(xe, "code", "ERR_JWS_SIGNATURE_VERIFICATION_FAILED");
471
- function v(e, t = "algorithm.name") {
472
- return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);
473
- }
474
- function V(e, t) {
475
- return e.name === t;
476
- }
477
- function de(e) {
478
- return parseInt(e.name.slice(4), 10);
479
- }
480
- function Dt(e) {
481
- switch (e) {
482
- case "ES256":
483
- return "P-256";
484
- case "ES384":
485
- return "P-384";
486
- case "ES512":
487
- return "P-521";
488
- default:
489
- throw new Error("unreachable");
490
- }
491
- }
492
- function Ut(e, t) {
493
- if (!e.usages.includes(t))
494
- throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`);
495
- }
496
- function Ht(e, t, r) {
497
- switch (t) {
498
- case "HS256":
499
- case "HS384":
500
- case "HS512": {
501
- if (!V(e.algorithm, "HMAC"))
502
- throw v("HMAC");
503
- const a = parseInt(t.slice(2), 10);
504
- if (de(e.algorithm.hash) !== a)
505
- throw v(`SHA-${a}`, "algorithm.hash");
506
- break;
507
- }
508
- case "RS256":
509
- case "RS384":
510
- case "RS512": {
511
- if (!V(e.algorithm, "RSASSA-PKCS1-v1_5"))
512
- throw v("RSASSA-PKCS1-v1_5");
513
- const a = parseInt(t.slice(2), 10);
514
- if (de(e.algorithm.hash) !== a)
515
- throw v(`SHA-${a}`, "algorithm.hash");
516
- break;
517
- }
518
- case "PS256":
519
- case "PS384":
520
- case "PS512": {
521
- if (!V(e.algorithm, "RSA-PSS"))
522
- throw v("RSA-PSS");
523
- const a = parseInt(t.slice(2), 10);
524
- if (de(e.algorithm.hash) !== a)
525
- throw v(`SHA-${a}`, "algorithm.hash");
526
- break;
527
- }
528
- case "Ed25519":
529
- case "EdDSA": {
530
- if (!V(e.algorithm, "Ed25519"))
531
- throw v("Ed25519");
532
- break;
533
- }
534
- case "ES256":
535
- case "ES384":
536
- case "ES512": {
537
- if (!V(e.algorithm, "ECDSA"))
538
- throw v("ECDSA");
539
- const a = Dt(t);
540
- if (e.algorithm.namedCurve !== a)
541
- throw v(a, "algorithm.namedCurve");
542
- break;
543
- }
544
- default:
545
- throw new TypeError("CryptoKey does not support this operation");
546
- }
547
- Ut(e, r);
548
- }
549
- function Ge(e, t, ...r) {
550
- var a;
551
- if (r = r.filter(Boolean), r.length > 2) {
552
- const n = r.pop();
553
- e += `one of type ${r.join(", ")}, or ${n}.`;
554
- } else r.length === 2 ? e += `one of type ${r[0]} or ${r[1]}.` : e += `of type ${r[0]}.`;
555
- return t == null ? e += ` Received ${t}` : typeof t == "function" && t.name ? e += ` Received function ${t.name}` : typeof t == "object" && t != null && (a = t.constructor) != null && a.name && (e += ` Received an instance of ${t.constructor.name}`), e;
556
- }
557
- const Lt = (e, ...t) => Ge("Key must be ", e, ...t);
558
- function Me(e, t, ...r) {
559
- return Ge(`Key for the ${e} algorithm must be `, t, ...r);
560
- }
561
- function je(e) {
562
- return e?.[Symbol.toStringTag] === "CryptoKey";
563
- }
564
- function Ve(e) {
565
- return e?.[Symbol.toStringTag] === "KeyObject";
566
- }
567
- const Be = (e) => je(e) || Ve(e), $t = (...e) => {
568
- const t = e.filter(Boolean);
569
- if (t.length === 0 || t.length === 1)
570
- return !0;
571
- let r;
572
- for (const a of t) {
573
- const n = Object.keys(a);
574
- if (!r || r.size === 0) {
575
- r = new Set(n);
576
- continue;
577
- }
578
- for (const s of n) {
579
- if (r.has(s))
580
- return !1;
581
- r.add(s);
582
- }
583
- }
584
- return !0;
585
- };
586
- function Wt(e) {
587
- return typeof e == "object" && e !== null;
588
- }
589
- const q = (e) => {
590
- if (!Wt(e) || Object.prototype.toString.call(e) !== "[object Object]")
591
- return !1;
592
- if (Object.getPrototypeOf(e) === null)
593
- return !0;
594
- let t = e;
595
- for (; Object.getPrototypeOf(t) !== null; )
596
- t = Object.getPrototypeOf(t);
597
- return Object.getPrototypeOf(e) === t;
598
- }, Jt = (e, t) => {
599
- if (e.startsWith("RS") || e.startsWith("PS")) {
600
- const { modulusLength: r } = t.algorithm;
601
- if (typeof r != "number" || r < 2048)
602
- throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`);
603
- }
604
- }, ae = (e, t, r = 0) => {
605
- r === 0 && (t.unshift(t.length), t.unshift(6));
606
- const a = e.indexOf(t[0], r);
607
- if (a === -1)
608
- return !1;
609
- const n = e.subarray(a, a + t.length);
610
- return n.length !== t.length ? !1 : n.every((s, o) => s === t[o]) || ae(e, t, a + 1);
611
- }, Yt = (e) => {
612
- switch (!0) {
613
- case ae(e, [42, 134, 72, 206, 61, 3, 1, 7]):
614
- return "P-256";
615
- case ae(e, [43, 129, 4, 0, 34]):
616
- return "P-384";
617
- case ae(e, [43, 129, 4, 0, 35]):
618
- return "P-521";
619
- default:
620
- return;
621
- }
622
- }, xt = async (e, t, r, a, n) => {
623
- let s, o;
624
- const i = new Uint8Array(atob(r.replace(e, "")).split("").map((c) => c.charCodeAt(0)));
625
- switch (a) {
626
- case "PS256":
627
- case "PS384":
628
- case "PS512":
629
- s = { name: "RSA-PSS", hash: `SHA-${a.slice(-3)}` }, o = ["verify"];
630
- break;
631
- case "RS256":
632
- case "RS384":
633
- case "RS512":
634
- s = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${a.slice(-3)}` }, o = ["verify"];
635
- break;
636
- case "RSA-OAEP":
637
- case "RSA-OAEP-256":
638
- case "RSA-OAEP-384":
639
- case "RSA-OAEP-512":
640
- s = {
641
- name: "RSA-OAEP",
642
- hash: `SHA-${parseInt(a.slice(-3), 10) || 1}`
643
- }, o = ["encrypt", "wrapKey"];
644
- break;
645
- case "ES256":
646
- s = { name: "ECDSA", namedCurve: "P-256" }, o = ["verify"];
647
- break;
648
- case "ES384":
649
- s = { name: "ECDSA", namedCurve: "P-384" }, o = ["verify"];
650
- break;
651
- case "ES512":
652
- s = { name: "ECDSA", namedCurve: "P-521" }, o = ["verify"];
653
- break;
654
- case "ECDH-ES":
655
- case "ECDH-ES+A128KW":
656
- case "ECDH-ES+A192KW":
657
- case "ECDH-ES+A256KW": {
658
- const c = Yt(i);
659
- s = c != null && c.startsWith("P-") ? { name: "ECDH", namedCurve: c } : { name: "X25519" }, o = [];
660
- break;
661
- }
662
- case "Ed25519":
663
- case "EdDSA":
664
- s = { name: "Ed25519" }, o = ["verify"];
665
- break;
666
- default:
667
- throw new k('Invalid or unsupported "alg" (Algorithm) value');
668
- }
669
- return crypto.subtle.importKey(t, i, s, !0, o);
670
- }, Gt = (e, t, r) => xt(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", e, t);
671
- function Mt(e) {
672
- let t, r;
673
- switch (e.kty) {
674
- case "RSA": {
675
- switch (e.alg) {
676
- case "PS256":
677
- case "PS384":
678
- case "PS512":
679
- t = { name: "RSA-PSS", hash: `SHA-${e.alg.slice(-3)}` }, r = e.d ? ["sign"] : ["verify"];
680
- break;
681
- case "RS256":
682
- case "RS384":
683
- case "RS512":
684
- t = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${e.alg.slice(-3)}` }, r = e.d ? ["sign"] : ["verify"];
685
- break;
686
- case "RSA-OAEP":
687
- case "RSA-OAEP-256":
688
- case "RSA-OAEP-384":
689
- case "RSA-OAEP-512":
690
- t = {
691
- name: "RSA-OAEP",
692
- hash: `SHA-${parseInt(e.alg.slice(-3), 10) || 1}`
693
- }, r = e.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
694
- break;
695
- default:
696
- throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
697
- }
698
- break;
699
- }
700
- case "EC": {
701
- switch (e.alg) {
702
- case "ES256":
703
- t = { name: "ECDSA", namedCurve: "P-256" }, r = e.d ? ["sign"] : ["verify"];
704
- break;
705
- case "ES384":
706
- t = { name: "ECDSA", namedCurve: "P-384" }, r = e.d ? ["sign"] : ["verify"];
707
- break;
708
- case "ES512":
709
- t = { name: "ECDSA", namedCurve: "P-521" }, r = e.d ? ["sign"] : ["verify"];
710
- break;
711
- case "ECDH-ES":
712
- case "ECDH-ES+A128KW":
713
- case "ECDH-ES+A192KW":
714
- case "ECDH-ES+A256KW":
715
- t = { name: "ECDH", namedCurve: e.crv }, r = e.d ? ["deriveBits"] : [];
716
- break;
717
- default:
718
- throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
719
- }
720
- break;
721
- }
722
- case "OKP": {
723
- switch (e.alg) {
724
- case "Ed25519":
725
- case "EdDSA":
726
- t = { name: "Ed25519" }, r = e.d ? ["sign"] : ["verify"];
727
- break;
728
- case "ECDH-ES":
729
- case "ECDH-ES+A128KW":
730
- case "ECDH-ES+A192KW":
731
- case "ECDH-ES+A256KW":
732
- t = { name: e.crv }, r = e.d ? ["deriveBits"] : [];
733
- break;
734
- default:
735
- throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
736
- }
737
- break;
738
- }
739
- default:
740
- throw new k('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
741
- }
742
- return { algorithm: t, keyUsages: r };
743
- }
744
- const jt = async (e) => {
745
- if (!e.alg)
746
- throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
747
- const { algorithm: t, keyUsages: r } = Mt(e), a = { ...e };
748
- return delete a.alg, delete a.use, crypto.subtle.importKey("jwk", a, t, e.ext ?? !e.d, e.key_ops ?? r);
749
- };
750
- async function Vt(e, t, r) {
751
- if (e.indexOf("-----BEGIN PUBLIC KEY-----") !== 0)
752
- throw new TypeError('"spki" must be SPKI formatted string');
753
- return Gt(e, t);
754
- }
755
- const Bt = (e, t, r, a, n) => {
756
- if (n.crit !== void 0 && a?.crit === void 0)
757
- throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');
758
- if (!a || a.crit === void 0)
759
- return /* @__PURE__ */ new Set();
760
- if (!Array.isArray(a.crit) || a.crit.length === 0 || a.crit.some((o) => typeof o != "string" || o.length === 0))
761
- throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
762
- let s;
763
- r !== void 0 ? s = new Map([...Object.entries(r), ...t.entries()]) : s = t;
764
- for (const o of a.crit) {
765
- if (!s.has(o))
766
- throw new k(`Extension Header Parameter "${o}" is not recognized`);
767
- if (n[o] === void 0)
768
- throw new e(`Extension Header Parameter "${o}" is missing`);
769
- if (s.get(o) && a[o] === void 0)
770
- throw new e(`Extension Header Parameter "${o}" MUST be integrity protected`);
771
- }
772
- return new Set(a.crit);
773
- }, Ft = (e, t) => {
774
- if (t !== void 0 && (!Array.isArray(t) || t.some((r) => typeof r != "string")))
775
- throw new TypeError(`"${e}" option must be an array of strings`);
776
- if (t)
777
- return new Set(t);
778
- };
779
- function we(e) {
780
- return q(e) && typeof e.kty == "string";
781
- }
782
- function qt(e) {
783
- return e.kty !== "oct" && typeof e.d == "string";
784
- }
785
- function zt(e) {
786
- return e.kty !== "oct" && typeof e.d > "u";
787
- }
788
- function Qt(e) {
789
- return e.kty === "oct" && typeof e.k == "string";
790
- }
791
- let C;
792
- const Ie = async (e, t, r, a = !1) => {
793
- C || (C = /* @__PURE__ */ new WeakMap());
794
- let n = C.get(e);
795
- if (n != null && n[r])
796
- return n[r];
797
- const s = await jt({ ...t, alg: r });
798
- return a && Object.freeze(e), n ? n[r] = s : C.set(e, { [r]: s }), s;
799
- }, Xt = (e, t) => {
800
- var r;
801
- C || (C = /* @__PURE__ */ new WeakMap());
802
- let a = C.get(e);
803
- if (a != null && a[t])
804
- return a[t];
805
- const n = e.type === "public", s = !!n;
806
- let o;
807
- if (e.asymmetricKeyType === "x25519") {
808
- switch (t) {
809
- case "ECDH-ES":
810
- case "ECDH-ES+A128KW":
811
- case "ECDH-ES+A192KW":
812
- case "ECDH-ES+A256KW":
813
- break;
814
- default:
815
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
816
- }
817
- o = e.toCryptoKey(e.asymmetricKeyType, s, n ? [] : ["deriveBits"]);
818
- }
819
- if (e.asymmetricKeyType === "ed25519") {
820
- if (t !== "EdDSA" && t !== "Ed25519")
821
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
822
- o = e.toCryptoKey(e.asymmetricKeyType, s, [
823
- n ? "verify" : "sign"
824
- ]);
825
- }
826
- if (e.asymmetricKeyType === "rsa") {
827
- let i;
828
- switch (t) {
829
- case "RSA-OAEP":
830
- i = "SHA-1";
831
- break;
832
- case "RS256":
833
- case "PS256":
834
- case "RSA-OAEP-256":
835
- i = "SHA-256";
836
- break;
837
- case "RS384":
838
- case "PS384":
839
- case "RSA-OAEP-384":
840
- i = "SHA-384";
841
- break;
842
- case "RS512":
843
- case "PS512":
844
- case "RSA-OAEP-512":
845
- i = "SHA-512";
846
- break;
847
- default:
848
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
849
- }
850
- if (t.startsWith("RSA-OAEP"))
851
- return e.toCryptoKey({
852
- name: "RSA-OAEP",
853
- hash: i
854
- }, s, n ? ["encrypt"] : ["decrypt"]);
855
- o = e.toCryptoKey({
856
- name: t.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
857
- hash: i
858
- }, s, [n ? "verify" : "sign"]);
859
- }
860
- if (e.asymmetricKeyType === "ec") {
861
- const i = (/* @__PURE__ */ new Map([
862
- ["prime256v1", "P-256"],
863
- ["secp384r1", "P-384"],
864
- ["secp521r1", "P-521"]
865
- ])).get((r = e.asymmetricKeyDetails) == null ? void 0 : r.namedCurve);
866
- if (!i)
867
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
868
- t === "ES256" && i === "P-256" && (o = e.toCryptoKey({
869
- name: "ECDSA",
870
- namedCurve: i
871
- }, s, [n ? "verify" : "sign"])), t === "ES384" && i === "P-384" && (o = e.toCryptoKey({
872
- name: "ECDSA",
873
- namedCurve: i
874
- }, s, [n ? "verify" : "sign"])), t === "ES512" && i === "P-521" && (o = e.toCryptoKey({
875
- name: "ECDSA",
876
- namedCurve: i
877
- }, s, [n ? "verify" : "sign"])), t.startsWith("ECDH-ES") && (o = e.toCryptoKey({
878
- name: "ECDH",
879
- namedCurve: i
880
- }, s, n ? [] : ["deriveBits"]));
881
- }
882
- if (!o)
883
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
884
- return a ? a[t] = o : C.set(e, { [t]: o }), o;
885
- }, Zt = async (e, t) => {
886
- if (e instanceof Uint8Array || je(e))
887
- return e;
888
- if (Ve(e)) {
889
- if (e.type === "secret")
890
- return e.export();
891
- if ("toCryptoKey" in e && typeof e.toCryptoKey == "function")
892
- try {
893
- return Xt(e, t);
894
- } catch (a) {
895
- if (a instanceof TypeError)
896
- throw a;
897
- }
898
- let r = e.export({ format: "jwk" });
899
- return Ie(e, r, t);
900
- }
901
- if (we(e))
902
- return e.k ? F(e.k) : Ie(e, e, t, !0);
903
- throw new Error("unreachable");
904
- }, Y = (e) => e?.[Symbol.toStringTag], ge = (e, t, r) => {
905
- var a, n;
906
- if (t.use !== void 0) {
907
- let s;
908
- switch (r) {
909
- case "sign":
910
- case "verify":
911
- s = "sig";
912
- break;
913
- case "encrypt":
914
- case "decrypt":
915
- s = "enc";
916
- break;
917
- }
918
- if (t.use !== s)
919
- throw new TypeError(`Invalid key for this operation, its "use" must be "${s}" when present`);
920
- }
921
- if (t.alg !== void 0 && t.alg !== e)
922
- throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);
923
- if (Array.isArray(t.key_ops)) {
924
- let s;
925
- switch (!0) {
926
- case r === "verify":
927
- case e === "dir":
928
- case e.includes("CBC-HS"):
929
- s = r;
930
- break;
931
- case e.startsWith("PBES2"):
932
- s = "deriveBits";
933
- break;
934
- case /^A\d{3}(?:GCM)?(?:KW)?$/.test(e):
935
- !e.includes("GCM") && e.endsWith("KW") ? s = "unwrapKey" : s = r;
936
- break;
937
- case r === "encrypt":
938
- s = "wrapKey";
939
- break;
940
- case r === "decrypt":
941
- s = e.startsWith("RSA") ? "unwrapKey" : "deriveBits";
942
- break;
943
- }
944
- if (s && ((n = (a = t.key_ops) == null ? void 0 : a.includes) == null ? void 0 : n.call(a, s)) === !1)
945
- throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${s}" when present`);
946
- }
947
- return !0;
948
- }, er = (e, t, r) => {
949
- if (!(t instanceof Uint8Array)) {
950
- if (we(t)) {
951
- if (Qt(t) && ge(e, t, r))
952
- return;
953
- throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present');
954
- }
955
- if (!Be(t))
956
- throw new TypeError(Me(e, t, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
957
- if (t.type !== "secret")
958
- throw new TypeError(`${Y(t)} instances for symmetric algorithms must be of type "secret"`);
959
- }
960
- }, tr = (e, t, r) => {
961
- if (we(t))
962
- switch (r) {
963
- case "decrypt":
964
- case "sign":
965
- if (qt(t) && ge(e, t, r))
966
- return;
967
- throw new TypeError("JSON Web Key for this operation be a private JWK");
968
- case "encrypt":
969
- case "verify":
970
- if (zt(t) && ge(e, t, r))
971
- return;
972
- throw new TypeError("JSON Web Key for this operation be a public JWK");
973
- }
974
- if (!Be(t))
975
- throw new TypeError(Me(e, t, "CryptoKey", "KeyObject", "JSON Web Key"));
976
- if (t.type === "secret")
977
- throw new TypeError(`${Y(t)} instances for asymmetric algorithms must not be of type "secret"`);
978
- if (t.type === "public")
979
- switch (r) {
980
- case "sign":
981
- throw new TypeError(`${Y(t)} instances for asymmetric algorithm signing must be of type "private"`);
982
- case "decrypt":
983
- throw new TypeError(`${Y(t)} instances for asymmetric algorithm decryption must be of type "private"`);
984
- }
985
- if (t.type === "private")
986
- switch (r) {
987
- case "verify":
988
- throw new TypeError(`${Y(t)} instances for asymmetric algorithm verifying must be of type "public"`);
989
- case "encrypt":
990
- throw new TypeError(`${Y(t)} instances for asymmetric algorithm encryption must be of type "public"`);
991
- }
992
- }, rr = (e, t, r) => {
993
- e.startsWith("HS") || e === "dir" || e.startsWith("PBES2") || /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(e) || /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(e) ? er(e, t, r) : tr(e, t, r);
994
- }, ar = (e, t) => {
995
- const r = `SHA-${e.slice(-3)}`;
996
- switch (e) {
997
- case "HS256":
998
- case "HS384":
999
- case "HS512":
1000
- return { hash: r, name: "HMAC" };
1001
- case "PS256":
1002
- case "PS384":
1003
- case "PS512":
1004
- return { hash: r, name: "RSA-PSS", saltLength: parseInt(e.slice(-3), 10) >> 3 };
1005
- case "RS256":
1006
- case "RS384":
1007
- case "RS512":
1008
- return { hash: r, name: "RSASSA-PKCS1-v1_5" };
1009
- case "ES256":
1010
- case "ES384":
1011
- case "ES512":
1012
- return { hash: r, name: "ECDSA", namedCurve: t.namedCurve };
1013
- case "Ed25519":
1014
- case "EdDSA":
1015
- return { name: "Ed25519" };
1016
- default:
1017
- throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`);
1018
- }
1019
- }, nr = async (e, t, r) => {
1020
- if (t instanceof Uint8Array) {
1021
- if (!e.startsWith("HS"))
1022
- throw new TypeError(Lt(t, "CryptoKey", "KeyObject", "JSON Web Key"));
1023
- return crypto.subtle.importKey("raw", t, { hash: `SHA-${e.slice(-3)}`, name: "HMAC" }, !1, [r]);
1024
- }
1025
- return Ht(t, e, r), t;
1026
- }, sr = async (e, t, r, a) => {
1027
- const n = await nr(e, t, "verify");
1028
- Jt(e, n);
1029
- const s = ar(e, n.algorithm);
1030
- try {
1031
- return await crypto.subtle.verify(s, n, r, a);
1032
- } catch {
1033
- return !1;
1034
- }
1035
- };
1036
- async function or(e, t, r) {
1037
- if (!q(e))
1038
- throw new w("Flattened JWS must be an object");
1039
- if (e.protected === void 0 && e.header === void 0)
1040
- throw new w('Flattened JWS must have either of the "protected" or "header" members');
1041
- if (e.protected !== void 0 && typeof e.protected != "string")
1042
- throw new w("JWS Protected Header incorrect type");
1043
- if (e.payload === void 0)
1044
- throw new w("JWS Payload missing");
1045
- if (typeof e.signature != "string")
1046
- throw new w("JWS Signature missing or incorrect type");
1047
- if (e.header !== void 0 && !q(e.header))
1048
- throw new w("JWS Unprotected Header incorrect type");
1049
- let a = {};
1050
- if (e.protected)
1051
- try {
1052
- const U = F(e.protected);
1053
- a = JSON.parse(G.decode(U));
1054
- } catch {
1055
- throw new w("JWS Protected Header is invalid");
1056
- }
1057
- if (!$t(a, e.header))
1058
- throw new w("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1059
- const n = {
1060
- ...a,
1061
- ...e.header
1062
- }, s = Bt(w, /* @__PURE__ */ new Map([["b64", !0]]), r?.crit, a, n);
1063
- let o = !0;
1064
- if (s.has("b64") && (o = a.b64, typeof o != "boolean"))
1065
- throw new w('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
1066
- const { alg: i } = n;
1067
- if (typeof i != "string" || !i)
1068
- throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');
1069
- const c = r && Ft("algorithms", r.algorithms);
1070
- if (c && !c.has(i))
1071
- throw new Ye('"alg" (Algorithm) Header Parameter value not allowed');
1072
- if (o) {
1073
- if (typeof e.payload != "string")
1074
- throw new w("JWS Payload must be a string");
1075
- } else if (typeof e.payload != "string" && !(e.payload instanceof Uint8Array))
1076
- throw new w("JWS Payload must be a string or an Uint8Array instance");
1077
- let m = !1;
1078
- typeof t == "function" && (t = await t(a, e), m = !0), rr(i, t, "verify");
1079
- const d = Nt(Z.encode(e.protected ?? ""), Z.encode("."), typeof e.payload == "string" ? Z.encode(e.payload) : e.payload);
1080
- let p;
1081
- try {
1082
- p = F(e.signature);
1083
- } catch {
1084
- throw new w("Failed to base64url decode the signature");
1085
- }
1086
- const E = await Zt(t, i);
1087
- if (!await sr(i, E, p, d))
1088
- throw new xe();
1089
- let y;
1090
- if (o)
1091
- try {
1092
- y = F(e.payload);
1093
- } catch {
1094
- throw new w("Failed to base64url decode the payload");
1095
- }
1096
- else typeof e.payload == "string" ? y = Z.encode(e.payload) : y = e.payload;
1097
- const h = { payload: y };
1098
- return e.protected !== void 0 && (h.protectedHeader = a), e.header !== void 0 && (h.unprotectedHeader = e.header), m ? { ...h, key: E } : h;
1099
- }
1100
- async function ir(e, t, r) {
1101
- if (e instanceof Uint8Array && (e = G.decode(e)), typeof e != "string")
1102
- throw new w("Compact JWS must be a string or Uint8Array");
1103
- const { 0: a, 1: n, 2: s, length: o } = e.split(".");
1104
- if (o !== 3)
1105
- throw new w("Invalid Compact JWS");
1106
- const i = await or({ payload: n, protected: a, signature: s }, t, r), c = { payload: i.payload, protectedHeader: i.protectedHeader };
1107
- return typeof t == "function" ? { ...c, key: i.key } : c;
1108
- }
1109
- const cr = (e) => Math.floor(e.getTime() / 1e3), Fe = 60, qe = Fe * 60, Se = qe * 24, ur = Se * 7, lr = Se * 365.25, dr = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, Oe = (e) => {
1110
- const t = dr.exec(e);
1111
- if (!t || t[4] && t[1])
1112
- throw new TypeError("Invalid time period format");
1113
- const r = parseFloat(t[2]), a = t[3].toLowerCase();
1114
- let n;
1115
- switch (a) {
1116
- case "sec":
1117
- case "secs":
1118
- case "second":
1119
- case "seconds":
1120
- case "s":
1121
- n = Math.round(r);
1122
- break;
1123
- case "minute":
1124
- case "minutes":
1125
- case "min":
1126
- case "mins":
1127
- case "m":
1128
- n = Math.round(r * Fe);
1129
- break;
1130
- case "hour":
1131
- case "hours":
1132
- case "hr":
1133
- case "hrs":
1134
- case "h":
1135
- n = Math.round(r * qe);
1136
- break;
1137
- case "day":
1138
- case "days":
1139
- case "d":
1140
- n = Math.round(r * Se);
1141
- break;
1142
- case "week":
1143
- case "weeks":
1144
- case "w":
1145
- n = Math.round(r * ur);
1146
- break;
1147
- default:
1148
- n = Math.round(r * lr);
1149
- break;
1150
- }
1151
- return t[1] === "-" || t[4] === "ago" ? -n : n;
1152
- }, ve = (e) => e.toLowerCase().replace(/^application\//, ""), hr = (e, t) => typeof e == "string" ? t.includes(e) : Array.isArray(e) ? t.some(Set.prototype.has.bind(new Set(e))) : !1;
1153
- function yr(e, t, r = {}) {
1154
- let a;
1155
- try {
1156
- a = JSON.parse(G.decode(t));
1157
- } catch {
1158
- }
1159
- if (!q(a))
1160
- throw new _("JWT Claims Set must be a top-level JSON object");
1161
- const { typ: n } = r;
1162
- if (n && (typeof e.typ != "string" || ve(e.typ) !== ve(n)))
1163
- throw new R('unexpected "typ" JWT header value', a, "typ", "check_failed");
1164
- const { requiredClaims: s = [], issuer: o, subject: i, audience: c, maxTokenAge: m } = r, d = [...s];
1165
- m !== void 0 && d.push("iat"), c !== void 0 && d.push("aud"), i !== void 0 && d.push("sub"), o !== void 0 && d.push("iss");
1166
- for (const h of new Set(d.reverse()))
1167
- if (!(h in a))
1168
- throw new R(`missing required "${h}" claim`, a, h, "missing");
1169
- if (o && !(Array.isArray(o) ? o : [o]).includes(a.iss))
1170
- throw new R('unexpected "iss" claim value', a, "iss", "check_failed");
1171
- if (i && a.sub !== i)
1172
- throw new R('unexpected "sub" claim value', a, "sub", "check_failed");
1173
- if (c && !hr(a.aud, typeof c == "string" ? [c] : c))
1174
- throw new R('unexpected "aud" claim value', a, "aud", "check_failed");
1175
- let p;
1176
- switch (typeof r.clockTolerance) {
1177
- case "string":
1178
- p = Oe(r.clockTolerance);
1179
- break;
1180
- case "number":
1181
- p = r.clockTolerance;
1182
- break;
1183
- case "undefined":
1184
- p = 0;
1185
- break;
1186
- default:
1187
- throw new TypeError("Invalid clockTolerance option type");
1188
- }
1189
- const { currentDate: E } = r, y = cr(E || /* @__PURE__ */ new Date());
1190
- if ((a.iat !== void 0 || m) && typeof a.iat != "number")
1191
- throw new R('"iat" claim must be a number', a, "iat", "invalid");
1192
- if (a.nbf !== void 0) {
1193
- if (typeof a.nbf != "number")
1194
- throw new R('"nbf" claim must be a number', a, "nbf", "invalid");
1195
- if (a.nbf > y + p)
1196
- throw new R('"nbf" claim timestamp check failed', a, "nbf", "check_failed");
1197
- }
1198
- if (a.exp !== void 0) {
1199
- if (typeof a.exp != "number")
1200
- throw new R('"exp" claim must be a number', a, "exp", "invalid");
1201
- if (a.exp <= y - p)
1202
- throw new Ee('"exp" claim timestamp check failed', a, "exp", "check_failed");
1203
- }
1204
- if (m) {
1205
- const h = y - a.iat, U = typeof m == "number" ? m : Oe(m);
1206
- if (h - p > U)
1207
- throw new Ee('"iat" claim timestamp check failed (too far in the past)', a, "iat", "check_failed");
1208
- if (h < 0 - p)
1209
- throw new R('"iat" claim timestamp check failed (it should be in the past)', a, "iat", "check_failed");
1210
- }
1211
- return a;
1212
- }
1213
- async function pr(e, t, r) {
1214
- var a;
1215
- const n = await ir(e, t, r);
1216
- if ((a = n.protectedHeader.crit) != null && a.includes("b64") && n.protectedHeader.b64 === !1)
1217
- throw new _("JWTs MUST NOT use unencoded payload");
1218
- const s = { payload: yr(n.protectedHeader, n.payload, r), protectedHeader: n.protectedHeader };
1219
- return typeof t == "function" ? { ...s, key: n.key } : s;
1220
- }
1221
- function fr(e) {
1222
- if (typeof e != "string")
1223
- throw new _("JWTs must use Compact JWS serialization, JWT must be a string");
1224
- const { 1: t, length: r } = e.split(".");
1225
- if (r === 5)
1226
- throw new _("Only JWTs using Compact JWS serialization can be decoded");
1227
- if (r !== 3)
1228
- throw new _("Invalid JWT");
1229
- if (!t)
1230
- throw new _("JWTs must contain a payload");
1231
- let a;
1232
- try {
1233
- a = F(t);
1234
- } catch {
1235
- throw new _("Failed to base64url decode the payload");
1236
- }
1237
- let n;
1238
- try {
1239
- n = JSON.parse(G.decode(a));
1240
- } catch {
1241
- throw new _("Failed to parse the decoded payload as JSON");
1242
- }
1243
- if (!q(n))
1244
- throw new _("Invalid JWT Claims Set");
1245
- return n;
1246
- }
1247
- const M = async (e) => {
1248
- try {
1249
- const t = g.ALG, r = await Vt(Pt, t);
1250
- return await pr(e, r, {
1251
- issuer: g.ISSUER
1252
- });
1253
- } catch {
1254
- return;
1255
- }
1256
- }, Er = (e) => {
1257
- try {
1258
- return fr(e);
1259
- } catch {
1260
- return;
1261
- }
1262
- }, A = [];
1263
- for (let e = 0; e < 256; ++e)
1264
- A.push((e + 256).toString(16).slice(1));
1265
- function gr(e, t = 0) {
1266
- return (A[e[t + 0]] + A[e[t + 1]] + A[e[t + 2]] + A[e[t + 3]] + "-" + A[e[t + 4]] + A[e[t + 5]] + "-" + A[e[t + 6]] + A[e[t + 7]] + "-" + A[e[t + 8]] + A[e[t + 9]] + "-" + A[e[t + 10]] + A[e[t + 11]] + A[e[t + 12]] + A[e[t + 13]] + A[e[t + 14]] + A[e[t + 15]]).toLowerCase();
1267
- }
1268
- let he;
1269
- const mr = new Uint8Array(16);
1270
- function wr() {
1271
- if (!he) {
1272
- if (typeof crypto > "u" || !crypto.getRandomValues)
1273
- throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
1274
- he = crypto.getRandomValues.bind(crypto);
1275
- }
1276
- return he(mr);
1277
- }
1278
- const Sr = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), ke = { randomUUID: Sr };
1279
- function Ce(e, t, r) {
1280
- var a;
1281
- if (ke.randomUUID && !e)
1282
- return ke.randomUUID();
1283
- e = e || {};
1284
- const n = e.random ?? ((a = e.rng) == null ? void 0 : a.call(e)) ?? wr();
1285
- if (n.length < 16)
1286
- throw new Error("Random bytes length must be >= 16");
1287
- return n[6] = n[6] & 15 | 64, n[8] = n[8] & 63 | 128, gr(n);
1288
- }
1289
- const Pe = globalThis.crypto, Ar = (e) => `${Ce()}${Ce()}`.slice(0, e), Tr = (e) => btoa(
1290
- [...new Uint8Array(e)].map((t) => String.fromCharCode(t)).join("")
1291
- );
1292
- async function br(e) {
1293
- if (!Pe.subtle)
1294
- throw new Error(
1295
- "crypto.subtle is available only in secure contexts (HTTPS)."
1296
- );
1297
- const t = new TextEncoder().encode(e), r = await Pe.subtle.digest("SHA-256", t);
1298
- return Tr(r).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1299
- }
1300
- async function Rr(e) {
1301
- const r = Ar(43), a = await br(r);
1302
- return {
1303
- code_verifier: r,
1304
- code_challenge: a
1305
- };
1306
- }
1307
- const qr = async (e, t) => {
1308
- var r;
1309
- const a = await M(e);
1310
- if (!a || !Array.isArray((r = a.payload) == null ? void 0 : r[g.SCOPES_KEY]))
1311
- return !1;
1312
- const n = a.payload[g.SCOPES_KEY];
1313
- return Array.isArray(t) ? t.every((s) => n.includes(s)) : Object.keys(t).some(
1314
- (s) => t[s].every((o) => n.includes(o))
1315
- );
1316
- };
1317
- function ze(e, t) {
1318
- window.dispatchEvent(new StorageEvent("storage", { key: e, newValue: t }));
1319
- }
1320
- const Ne = (e, t) => {
1321
- const r = JSON.stringify(
1322
- typeof t == "function" ? t() : t
1323
- );
1324
- window.localStorage.setItem(e, r), ze(e, r);
1325
- }, _r = (e) => {
1326
- window.localStorage.removeItem(e), ze(e, null);
1327
- }, Ke = (e) => window.localStorage.getItem(e), Ir = (e) => (window.addEventListener("storage", e), () => window.removeEventListener("storage", e));
1328
- function ee({
1329
- key: e,
1330
- initialValue: t
1331
- }) {
1332
- const r = Et(Ir, () => Ke(e)), a = D(
1333
- (o) => {
1334
- try {
1335
- const i = typeof o == "function" ? o(JSON.parse(r)) : o;
1336
- i == null ? _r(e) : Ne(e, i);
1337
- } catch (i) {
1338
- console.warn(i);
1339
- }
1340
- },
1341
- [e, r]
1342
- ), n = D(() => {
1343
- a(t);
1344
- }, [t, a]), s = D(() => {
1345
- a(null);
1346
- }, [a]);
1347
- return Ue(() => {
1348
- try {
1349
- Ke(e) === null && typeof t < "u" && Ne(e, t);
1350
- } catch (o) {
1351
- console.warn(o);
1352
- }
1353
- }, [e, t]), [r ? JSON.parse(r) : null, a, n, s];
1354
- }
1355
- const T = [];
1356
- for (let e = 0; e < 256; ++e)
1357
- T.push((e + 256).toString(16).slice(1));
1358
- function Or(e, t = 0) {
1359
- return (T[e[t + 0]] + T[e[t + 1]] + T[e[t + 2]] + T[e[t + 3]] + "-" + T[e[t + 4]] + T[e[t + 5]] + "-" + T[e[t + 6]] + T[e[t + 7]] + "-" + T[e[t + 8]] + T[e[t + 9]] + "-" + T[e[t + 10]] + T[e[t + 11]] + T[e[t + 12]] + T[e[t + 13]] + T[e[t + 14]] + T[e[t + 15]]).toLowerCase();
1360
- }
1361
- let ye;
1362
- const vr = new Uint8Array(16);
1363
- function kr() {
1364
- if (!ye) {
1365
- if (typeof crypto > "u" || !crypto.getRandomValues)
1366
- throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
1367
- ye = crypto.getRandomValues.bind(crypto);
1368
- }
1369
- return ye(vr);
1370
- }
1371
- const Cr = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), De = { randomUUID: Cr };
1372
- function pe(e, t, r) {
1373
- if (De.randomUUID && !e)
1374
- return De.randomUUID();
1375
- e = e || {};
1376
- const a = e.random ?? e.rng?.() ?? kr();
1377
- if (a.length < 16)
1378
- throw new Error("Random bytes length must be >= 16");
1379
- return a[6] = a[6] & 15 | 64, a[8] = a[8] & 63 | 128, Or(a);
1380
- }
1381
- const L = "Your session has expired. For your security, please log in again to continue.", Pr = "Your session has been successfully terminated.", fe = "Login failed. Please try again.", Nr = "Error getting access token, please re-authenticate.", Kr = "You forgot to wrap your component in <AuthProvider>.", te = "@@auth@@", B = "LOADING", ne = "LOGIN", Qe = "LOGOUT", z = "success", O = "failure", Xe = "include", Ze = "POST", et = "application/json", re = {
1382
- GET_REGISTRATION_OPTIONS: `mutation GetPasskeyRegistrationOptions(
1383
- $clientId: String!,
1384
- $username: String!,
1385
- $id: String!) {
1386
- getPasskeyRegistrationOptions(clientId: $clientId, username: $username, id: $id) {
1387
- challenge
1388
- rp {
1389
- id
1390
- name
1391
- }
1392
- user {
1393
- id
1394
- name
1395
- displayName
1396
- }
1397
- pubKeyCredParams {
1398
- type
1399
- alg
1400
- }
1401
- timeout
1402
- attestation
1403
- }
1404
- }`,
1405
- VERIFY_REGISTRATION: `mutation VerifyPasskeyRegistration(
1406
- $clientId: String!,
1407
- $username: String!,
1408
- $id: String!,
1409
- $registration: RegistrationOptionsInput!) {
1410
- verifyPasskeyRegistration(
1411
- clientId: $clientId,
1412
- username: $username,
1413
- id: $id,
1414
- registration: $registration) {
1415
- status
1416
- message
1417
- }
1418
- }`,
1419
- GET_AUTHENTICATION_OPTIONS: `mutation GetPasskeyAuthenticationOptions(
1420
- $id: String!,
1421
- $clientId: String!,
1422
- ) {
1423
- getPasskeyAuthenticationOptions(
1424
- id: $id,
1425
- clientId: $clientId) {
1426
- rpId,
1427
- challenge,
1428
- allowCredentials {
1429
- id,
1430
- type,
1431
- transports
1432
- }
1433
- timeout,
1434
- userVerification,
1435
- }
1436
- }`,
1437
- VERIFY_AUTHENTICATION: `mutation VerifyPasskeyAuthentication(
1438
- $clientId: String!,
1439
- $id: String!,
1440
- $authentication: AuthenticationOptionsInput!,
1441
- $nonce: String!,
1442
- $domain: String,
1443
- $sessionExpiration: String,
1444
- $ua: String) {
1445
- verifyPasskeyAuthentication(
1446
- clientId: $clientId,
1447
- id: $id,
1448
- authentication: $authentication,
1449
- nonce: $nonce,
1450
- domain: $domain,
1451
- sessionExpiration: $sessionExpiration,
1452
- ua: $ua) {
1453
- status,
1454
- idToken,
1455
- accessToken,
1456
- refreshToken,
1457
- userId,
1458
- username,
1459
- email
1460
- }
1461
- }`
1462
- }, $ = {
1463
- GET_REGISTRATION_OPTIONS: {
1464
- schema: re.GET_REGISTRATION_OPTIONS,
1465
- method: "getPasskeyRegistrationOptions"
1466
- },
1467
- VERIFY_REGISTRATION: {
1468
- schema: re.VERIFY_REGISTRATION,
1469
- method: "verifyPasskeyRegistration"
1470
- },
1471
- GET_AUTHENTICATION_OPTIONS: {
1472
- schema: re.GET_AUTHENTICATION_OPTIONS,
1473
- method: "getPasskeyAuthenticationOptions"
1474
- },
1475
- VERIFY_AUTHENTICATION: {
1476
- schema: re.VERIFY_AUTHENTICATION,
1477
- method: "verifyPasskeyAuthentication"
1478
- }
1479
- }, W = async ({
1480
- accessToken: e,
1481
- type: t,
1482
- clientId: r,
1483
- params: a = {},
1484
- endpoint: n
1485
- }) => {
1486
- try {
1487
- const s = `Bearer ${e}`, o = await fetch(`${n}/graphql`, {
1488
- credentials: Xe,
1489
- method: Ze,
1490
- headers: {
1491
- authorization: s,
1492
- "Content-Type": et,
1493
- [Je.CLIENT_ID]: `${r}`
1494
- },
1495
- body: JSON.stringify({
1496
- query: t.schema,
1497
- variables: a
1498
- })
1499
- });
1500
- if (o.status !== 200)
1501
- return { status: O, data: [] };
1502
- const { data: i } = await o.json();
1503
- return {
1504
- status: z,
1505
- data: i[t.method]
1506
- };
1507
- } catch (s) {
1508
- return console.error(s), { status: O, data: [] };
1509
- }
1510
- }, ie = async ({
1511
- type: e,
1512
- clientId: t,
1513
- params: r = {},
1514
- endpoint: a
1515
- }) => {
1516
- try {
1517
- const n = await fetch(`${a}/${e}`, {
1518
- credentials: Xe,
1519
- method: Ze,
1520
- headers: {
1521
- "Content-Type": et,
1522
- [Je.CLIENT_ID]: `${t}`
1523
- },
1524
- body: JSON.stringify(r)
1525
- });
1526
- if (n.status !== 200)
1527
- return { status: O, data: [] };
1528
- const { data: s } = await n.json();
1529
- return {
1530
- status: z,
1531
- data: s || []
1532
- };
1533
- } catch (n) {
1534
- return console.error(n), { status: O, data: [] };
1535
- }
1536
- }, Dr = process.env.NODE_ENV === "production", Ur = !Dr, tt = {
1537
- isLoading: !0,
1538
- isAuthenticated: !1,
1539
- user: void 0,
1540
- logoutReason: "",
1541
- debug: !1,
1542
- authenticationType: ""
1543
- }, Hr = (e) => {
1544
- try {
1545
- const t = Er(e);
1546
- return t ? t[g.USER_ID_KEY] : "";
1547
- } catch {
1548
- return "";
1549
- }
1550
- }, Lr = async ({
1551
- userId: e,
1552
- clientId: t,
1553
- domain: r,
1554
- idToken: a = "",
1555
- endpoint: n
1556
- }) => {
1557
- try {
1558
- return {
1559
- status: (await ie({
1560
- endpoint: n,
1561
- type: oe.LOGOUT,
1562
- clientId: t,
1563
- params: {
1564
- userId: e,
1565
- domain: r,
1566
- idToken: a
1567
- }
1568
- }))?.status || O
1569
- };
1570
- } catch {
1571
- return {
1572
- status: O
1573
- };
1574
- }
1575
- }, $r = async ({
1576
- username: e,
1577
- password: t,
1578
- clientId: r,
1579
- nonce: a,
1580
- type: n,
1581
- sessionExpiration: s,
1582
- code: o,
1583
- code_verifier: i,
1584
- domain: c,
1585
- ua: m,
1586
- endpoint: d
1587
- }) => {
1588
- try {
1589
- const p = await ie({
1590
- endpoint: d,
1591
- type: oe.LOGIN,
1592
- clientId: r,
1593
- params: {
1594
- type: n || x.ID_AND_ACCESS_TOKEN,
1595
- username: e,
1596
- password: t,
1597
- sessionExpiration: s,
1598
- nonce: a,
1599
- code: o,
1600
- code_verifier: i,
1601
- domain: c,
1602
- ua: m
1603
- }
1604
- }), E = await M(p?.data?.idToken);
1605
- return E && E.payload[g.USER_ID_KEY] !== "" && E.payload[g.NONCE_KEY] === a ? {
1606
- idToken: p.data.idToken,
1607
- accessToken: p.data.accessToken,
1608
- refreshToken: p.data.refreshToken,
1609
- userId: E.payload[g.USER_ID_KEY],
1610
- email: E.payload[g.EMAIL_KEY],
1611
- status: !0
1612
- } : {
1613
- status: !1
1614
- };
1615
- } catch {
1616
- return {
1617
- status: !1
1618
- };
1619
- }
1620
- }, Wr = async ({
1621
- nonce: e,
1622
- clientId: t,
1623
- code_challenge: r,
1624
- endpoint: a
1625
- }) => {
1626
- try {
1627
- const n = await ie({
1628
- endpoint: a,
1629
- type: oe.CODE,
1630
- clientId: t,
1631
- params: {
1632
- type: x.CODE,
1633
- nonce: e,
1634
- code_challenge: r
1635
- }
1636
- });
1637
- return n?.data?.code ? {
1638
- status: z,
1639
- data: n.data.code
1640
- } : {
1641
- status: O,
1642
- data: ""
1643
- };
1644
- } catch {
1645
- return {
1646
- status: O,
1647
- data: ""
1648
- };
1649
- }
1650
- }, Jr = async ({
1651
- clientId: e,
1652
- userId: t,
1653
- nonce: r,
1654
- refreshToken: a,
1655
- accessToken: n,
1656
- domain: s,
1657
- endpoint: o
1658
- }) => {
1659
- try {
1660
- const i = await ie({
1661
- endpoint: o,
1662
- type: oe.REFRESH,
1663
- clientId: e,
1664
- params: {
1665
- type: x.REFRESH_TOKEN,
1666
- userId: t,
1667
- nonce: r,
1668
- refreshToken: a,
1669
- accessToken: n,
1670
- domain: s
1671
- }
1672
- }), c = await M(i?.data?.accessToken);
1673
- return c && c.payload[g.USER_ID_KEY] !== "" && c.payload[g.NONCE_KEY] === r ? {
1674
- accessToken: i.data.accessToken,
1675
- refreshToken: i.data.refreshToken,
1676
- userId: c.payload[g.USER_ID_KEY],
1677
- status: !0
1678
- } : {
1679
- status: !1
1680
- };
1681
- } catch {
1682
- return {
1683
- status: !1
1684
- };
1685
- }
1686
- };
1687
- class Yr {
1688
- constructor(t = null, r = null) {
1689
- X(this, "refreshTokenPromise", null);
1690
- X(this, "accessToken");
1691
- X(this, "refreshToken");
1692
- this.accessToken = t || "", this.refreshToken = r || "";
1693
- }
1694
- async refreshtoken({
1695
- clientId: t,
1696
- userId: r,
1697
- nonce: a,
1698
- domain: n,
1699
- endpoint: s
1700
- }) {
1701
- this.refreshTokenPromise || (this.refreshTokenPromise = this._refreshToken({
1702
- endpoint: s,
1703
- clientId: t,
1704
- userId: r,
1705
- nonce: a,
1706
- domain: n
1707
- }));
1708
- try {
1709
- return await this.refreshTokenPromise;
1710
- } finally {
1711
- this.refreshTokenPromise = null;
1712
- }
1713
- }
1714
- async _refreshToken({
1715
- endpoint: t,
1716
- clientId: r,
1717
- userId: a,
1718
- nonce: n,
1719
- domain: s
1720
- }) {
1721
- const o = await M(this.refreshToken);
1722
- if (o && o.payload[g.USER_ID_KEY] !== "") {
1723
- const i = await Jr({
1724
- endpoint: t,
1725
- clientId: r,
1726
- userId: a,
1727
- nonce: n,
1728
- refreshToken: this.refreshToken,
1729
- accessToken: this.accessToken,
1730
- domain: s
1731
- });
1732
- return i.status ? (this.accessToken = i.accessToken, this.refreshToken = i.refreshToken, {
1733
- status: z,
1734
- newAccessToken: i.accessToken,
1735
- newRefreshToken: i.refreshToken
1736
- }) : {
1737
- status: O
1738
- };
1739
- } else
1740
- return {
1741
- status: O
1742
- };
1743
- }
1744
- }
1745
- const xr = (e) => D(
1746
- (...t) => {
1747
- e && console.info(`==> [Auth ${Date.now()}]: `, ...t);
1748
- },
1749
- [e]
1750
- ), J = () => {
1751
- throw new Error(Kr);
1752
- }, rt = gt({
1753
- isAuthenticated: !1,
1754
- isLoading: !1,
1755
- login: J,
1756
- logout: J,
1757
- getAccessToken: J,
1758
- getIdToken: J,
1759
- registeringForPasskey: J,
1760
- loginWithPasskey: J,
1761
- logoutReason: "",
1762
- authenticationType: ""
1763
- }), Gr = ft.createContext({
1764
- state: tt,
1765
- dispatch: () => {
1766
- }
1767
- }), Mr = (e, t) => t?.type === B ? {
1768
- ...e,
1769
- isLoading: t.payload.isLoading
1770
- } : t?.type === ne ? {
1771
- ...e,
1772
- isLoading: !1,
1773
- isAuthenticated: !0,
1774
- user: t.payload.user,
1775
- authenticationType: t.payload.authenticationType,
1776
- logoutReason: ""
1777
- } : t?.type === Qe ? {
1778
- ...e,
1779
- isLoading: !1,
1780
- isAuthenticated: !1,
1781
- user: void 0,
1782
- authenticationType: "",
1783
- logoutReason: t.payload.logoutReason
1784
- } : e, zr = ({
1785
- children: e,
1786
- sessionExpiration: t,
1787
- clientId: r,
1788
- domain: a = "",
1789
- debug: n = !1,
1790
- endpoint: s = Ur ? "https://auth.gizmette.local.com:3003" : "https://mylogin.gizmette.com/auth"
1791
- }) => {
1792
- const [o, i] = mt(Mr, {
1793
- ...tt,
1794
- debug: n
1795
- }), c = xr(n), m = wt(!1), [d, p, , E] = ee({
1796
- key: `${te}::${r}::@@user@@`
1797
- }), [y, h, , U] = ee({
1798
- key: `${te}::${r}::@@access@@`
1799
- }), [at, ce, , Ae] = ee(
1800
- {
1801
- key: `${te}::${r}::@@refresh@@`
1802
- }
1803
- ), [nt, Te, , be] = ee({
1804
- key: `${te}::${r}::@@nonce@@`
1805
- }), st = new Yr(y, at), Q = D(() => {
1806
- c("removeLocalStorage: removing local storage"), E(), U(), Ae(), be();
1807
- }, [
1808
- U,
1809
- E,
1810
- be,
1811
- Ae,
1812
- c
1813
- ]), j = D(
1814
- (u) => {
1815
- c(
1816
- "removeStateAndLocalStorage: removing state and local storage with reason: ",
1817
- u
1818
- ), i({
1819
- type: Qe,
1820
- payload: {
1821
- logoutReason: u || L
1822
- }
1823
- }), Q(), i({ type: B, payload: { isLoading: !1 } });
1824
- },
1825
- [Q, c]
1826
- ), N = D(
1827
- async (u) => {
1828
- c("invalidateAndLogout: invalidating and logging out");
1829
- const { user: S } = o, l = S?.userId || Hr(d);
1830
- l || c(
1831
- "invalidateAndLogout: user cannot be identified, logging out without userId"
1832
- ), await Lr({
1833
- userId: l,
1834
- clientId: r,
1835
- domain: a,
1836
- idToken: d,
1837
- endpoint: s
1838
- }), j(u || L);
1839
- },
1840
- [
1841
- d,
1842
- o,
1843
- r,
1844
- a,
1845
- j,
1846
- c,
1847
- s
1848
- ]
1849
- );
1850
- Ue(() => {
1851
- if (!m.current)
1852
- return o.isLoading && d !== null ? (async () => {
1853
- try {
1854
- const u = await M(d);
1855
- u && u.payload[g.USER_ID_KEY] !== "" ? (c("useEffect: setting the authentication state"), i({
1856
- type: ne,
1857
- payload: {
1858
- authenticationType: u.payload[g.AUTH_TYPE_KEY],
1859
- user: {
1860
- userId: u.payload[g.USER_ID_KEY],
1861
- username: u.payload[g.USERNAME_KEY],
1862
- email: u.payload[g.EMAIL_KEY]
1863
- }
1864
- }
1865
- })) : (c("useEffect: invalid JWT, invalidating and logging out"), await N(L));
1866
- } catch {
1867
- c(
1868
- "useEffect: exception validating JWT, invalidating and logging out"
1869
- ), await N(L);
1870
- }
1871
- })() : (c("useEffect: setting the loading state to false"), i({ type: B, payload: { isLoading: !1 } })), () => {
1872
- m.current = !0;
1873
- };
1874
- }, [o.isLoading, d, N, c]);
1875
- const ot = async (u, S) => {
1876
- i({ type: B, payload: { isLoading: !0 } }), Q();
1877
- const l = pe();
1878
- Te(l), c("login: Logging in with password");
1879
- const { code_verifier: K, code_challenge: ht } = await Rr(), Re = await Wr({
1880
- endpoint: s,
1881
- nonce: l,
1882
- clientId: r,
1883
- code_challenge: ht
1884
- });
1885
- if (Re.status) {
1886
- const H = await $r({
1887
- endpoint: s,
1888
- username: u,
1889
- password: S,
1890
- clientId: r,
1891
- sessionExpiration: t,
1892
- nonce: l,
1893
- type: x.CODE,
1894
- code: Re.data,
1895
- code_verifier: K,
1896
- domain: a,
1897
- ua: navigator.userAgent
1898
- });
1899
- return H.status ? (p(H.idToken), h(H.accessToken), ce(H.refreshToken), i({
1900
- type: ne,
1901
- payload: {
1902
- authenticationType: x.CODE,
1903
- user: {
1904
- userId: H.userId,
1905
- username: u,
1906
- email: H.email
1907
- }
1908
- }
1909
- }), !0) : (j(fe), !1);
1910
- }
1911
- return !1;
1912
- }, it = async (u) => {
1913
- u?.preventDefault(), await N(Pr);
1914
- }, ct = async () => {
1915
- const { isAuthenticated: u, user: S } = o;
1916
- try {
1917
- if (u && S && S.userId) {
1918
- if (y) {
1919
- c("getAccessToken");
1920
- const K = await M(y);
1921
- if (K && K.payload[g.USER_ID_KEY] !== "")
1922
- return y;
1923
- }
1924
- c("getAccessToken: invalid access token, trying to refresh it");
1925
- const l = await st.refreshtoken({
1926
- endpoint: s,
1927
- clientId: r,
1928
- userId: S.userId,
1929
- nonce: nt,
1930
- domain: a
1931
- });
1932
- return l.status && l.status === "success" && l.newAccessToken ? (h(l.newAccessToken), ce(l.newRefreshToken), l.newAccessToken) : (c(
1933
- "getAccessToken: invalid refresh token, need to re-authenticate"
1934
- ), await N(L), "");
1935
- }
1936
- return c(
1937
- "getAccessToken: user is not authenticated, cannot get access token"
1938
- ), await N(L), "";
1939
- } catch {
1940
- return c(
1941
- "getAccessToken: exception occurred, invalidating and logging out"
1942
- ), await N(Nr), "";
1943
- }
1944
- }, ut = () => o.isAuthenticated && d ? d : "", lt = async () => {
1945
- const { user: u } = o;
1946
- let S = await W({
1947
- endpoint: s,
1948
- accessToken: y,
1949
- clientId: r,
1950
- type: $.GET_REGISTRATION_OPTIONS,
1951
- params: {
1952
- clientId: r,
1953
- id: u?.userId,
1954
- username: u?.username
1955
- }
1956
- });
1957
- if (S.status)
1958
- try {
1959
- const l = await _t({
1960
- optionsJSON: S.data
1961
- });
1962
- return S = await W({
1963
- endpoint: s,
1964
- accessToken: y,
1965
- clientId: r,
1966
- type: $.VERIFY_REGISTRATION,
1967
- params: {
1968
- clientId: r,
1969
- id: u?.userId,
1970
- username: u?.username,
1971
- registration: l
1972
- }
1973
- }), !!(S.status && S.data.length > 0);
1974
- } catch {
1975
- return await W({
1976
- endpoint: s,
1977
- accessToken: y,
1978
- clientId: r,
1979
- type: $.VERIFY_REGISTRATION,
1980
- params: {
1981
- clientId: r,
1982
- id: u?.userId,
1983
- username: u?.username,
1984
- registration: {}
1985
- }
1986
- }), !1;
1987
- }
1988
- return !1;
1989
- }, dt = async () => {
1990
- i({ type: B, payload: { isLoading: !0 } }), Q();
1991
- const u = pe();
1992
- Te(u), c("loginWithPasskey");
1993
- const S = pe();
1994
- let l = await W({
1995
- endpoint: s,
1996
- accessToken: y,
1997
- clientId: r,
1998
- type: $.GET_AUTHENTICATION_OPTIONS,
1999
- params: {
2000
- id: S,
2001
- clientId: r
2002
- }
2003
- });
2004
- if (l.status)
2005
- try {
2006
- const K = await vt({
2007
- optionsJSON: l.data
2008
- });
2009
- return l = await W({
2010
- endpoint: s,
2011
- accessToken: y,
2012
- clientId: r,
2013
- type: $.VERIFY_AUTHENTICATION,
2014
- params: {
2015
- clientId: r,
2016
- id: S,
2017
- authentication: K,
2018
- nonce: u,
2019
- domain: a,
2020
- sessionExpiration: t,
2021
- ua: navigator.userAgent
2022
- }
2023
- }), l.data.status === z ? (p(l.data.idToken), h(l.data.accessToken), ce(l.data.refreshToken), i({
2024
- type: ne,
2025
- payload: {
2026
- authenticationType: x.PASSKEY,
2027
- user: {
2028
- userId: l.data.userId,
2029
- username: l.data.username,
2030
- email: l.data.email
2031
- }
2032
- }
2033
- }), !0) : (j(fe), !1);
2034
- } catch {
2035
- return await W({
2036
- endpoint: s,
2037
- accessToken: y,
2038
- clientId: r,
2039
- type: $.VERIFY_AUTHENTICATION,
2040
- params: {
2041
- clientId: r,
2042
- id: S,
2043
- authentication: {},
2044
- nonce: u,
2045
- domain: a,
2046
- sessionExpiration: t
2047
- }
2048
- }), j(fe), !1;
2049
- }
2050
- return !1;
2051
- };
2052
- return /* @__PURE__ */ _e(Gr.Provider, { value: { state: o, dispatch: i }, children: /* @__PURE__ */ _e(
2053
- rt.Provider,
2054
- {
2055
- value: {
2056
- ...o,
2057
- login: ot,
2058
- logout: it,
2059
- getAccessToken: ct,
2060
- getIdToken: ut,
2061
- registeringForPasskey: lt,
2062
- loginWithPasskey: dt
2063
- },
2064
- children: e
2065
- }
2066
- ) });
2067
- }, Qr = (e = rt) => St(e);
2068
15
  export {
2069
- x as AUTH_TYPES,
2070
- zr as AuthProvider,
2071
- qr as isGranted,
2072
- Qr as useAuth
16
+ t as AUTH_TYPES,
17
+ r as isGranted
2073
18
  };