@versini/auth-provider 2.0.1 → 2.1.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/index.d.ts CHANGED
@@ -8,17 +8,21 @@ type AuthProviderProps = {
8
8
  accessType?: string;
9
9
  };
10
10
 
11
- type AuthContextProps = {
12
- login: (username: string, password: string) => Promise<boolean>;
13
- logout: () => void;
11
+ type AuthState = {
14
12
  isAuthenticated: boolean;
13
+ idToken?: string;
15
14
  accessToken?: string;
16
15
  refreshToken?: string;
17
- idToken?: string;
18
16
  logoutReason?: string;
17
+ userId?: string;
19
18
  };
20
19
 
21
- declare const AuthProvider: ({ children, sessionExpiration, clientId, accessType, }: AuthProviderProps) => react_jsx_runtime.JSX.Element;
20
+ type AuthContextProps = {
21
+ login: (username: string, password: string) => Promise<boolean>;
22
+ logout: () => void;
23
+ } & AuthState;
24
+
25
+ declare const AuthProvider: ({ children, sessionExpiration, clientId, }: AuthProviderProps) => react_jsx_runtime.JSX.Element;
22
26
 
23
27
  declare const useAuth: (context?: react.Context<AuthContextProps>) => AuthContextProps;
24
28
 
package/dist/index.js CHANGED
@@ -1,257 +1,820 @@
1
- import { jsx as P } from "react/jsx-runtime";
2
- import { useCallback as p, useState as U, useEffect as w, useRef as _, useLayoutEffect as z, createContext as M, useContext as F } from "react";
1
+ import { jsx as ne } from "react/jsx-runtime";
2
+ import * as A from "react";
3
+ import { useRef as oe, useEffect as G, createContext as ae, useState as se, useContext as ie } from "react";
3
4
  /*!
4
- @versini/auth-provider v2.0.1
5
+ @versini/auth-provider v2.1.0
5
6
  © 2024 gizmette.com
6
7
  */
7
8
  try {
8
9
  window.__VERSINI_AUTH_CLIENT__ || (window.__VERSINI_AUTH_CLIENT__ = {
9
- version: "2.0.1",
10
- buildTime: "06/18/2024 11:21 AM EDT",
10
+ version: "2.1.0",
11
+ buildTime: "06/24/2024 02:46 PM EDT",
11
12
  homepage: "https://github.com/aversini/auth-client",
12
13
  license: "MIT"
13
14
  });
14
15
  } catch {
15
16
  }
16
17
  /*!
17
- @versini/auth-common v2.0.0
18
+ @versini/auth-common v2.1.0
18
19
  © 2024 gizmette.com
19
20
  */
20
21
  try {
21
22
  window.__VERSINI_AUTH_COMMON__ || (window.__VERSINI_AUTH_COMMON__ = {
22
- version: "2.0.0",
23
- buildTime: "06/18/2024 11:21 AM EDT",
23
+ version: "2.1.0",
24
+ buildTime: "06/24/2024 02:46 PM EDT",
24
25
  homepage: "https://github.com/aversini/auth-client",
25
26
  license: "MIT"
26
27
  });
27
28
  } catch {
28
29
  }
29
- const H = {
30
+ const ce = {
30
31
  ID_TOKEN: "id_token"
31
- }, j = {
32
+ }, ue = {
32
33
  CLIENT_ID: "X-Auth-ClientId"
34
+ }, b = {
35
+ ALG: "RS256",
36
+ USER_ID_KEY: "_id",
37
+ ISSUER: "gizmette.com"
33
38
  };
34
- var D = typeof window < "u" ? z : w;
35
- function A(e, t, n, r) {
36
- const c = _(t);
37
- D(() => {
38
- c.current = t;
39
- }, [t]), w(() => {
40
- const l = window;
41
- if (!(l && l.addEventListener))
42
- return;
43
- const u = (h) => {
44
- c.current(h);
45
- };
46
- return l.addEventListener(e, u, r), () => {
47
- l.removeEventListener(e, u, r);
48
- };
49
- }, [e, n, r]);
39
+ function Y(e, t) {
40
+ window.dispatchEvent(new StorageEvent("storage", { key: e, newValue: t }));
50
41
  }
51
- function N(e) {
52
- const t = _(() => {
53
- throw new Error("Cannot call an event handler while rendering.");
54
- });
55
- return D(() => {
56
- t.current = e;
57
- }, [e]), p((...n) => {
58
- var r;
59
- return (r = t.current) == null ? void 0 : r.call(t, ...n);
60
- }, [t]);
61
- }
62
- var I = typeof window > "u";
63
- function E(e, t, n = {}) {
64
- const { initializeWithValue: r = !0 } = n, c = p(
65
- (o) => n.serializer ? n.serializer(o) : JSON.stringify(o),
66
- [n]
67
- ), l = p(
68
- (o) => {
69
- if (n.deserializer)
70
- return n.deserializer(o);
71
- if (o === "undefined")
72
- return;
73
- const a = t instanceof Function ? t() : t;
74
- let T;
42
+ const D = (e, t) => {
43
+ const n = JSON.stringify(
44
+ typeof t == "function" ? t() : t
45
+ );
46
+ window.localStorage.setItem(e, n), Y(e, n);
47
+ }, de = (e) => {
48
+ window.localStorage.removeItem(e), Y(e, null);
49
+ }, K = (e) => window.localStorage.getItem(e), le = (e) => (window.addEventListener("storage", e), () => window.removeEventListener("storage", e));
50
+ function fe({
51
+ key: e,
52
+ initialValue: t
53
+ }) {
54
+ const n = () => K(e), r = A.useSyncExternalStore(
55
+ le,
56
+ n
57
+ ), o = A.useCallback(
58
+ (i) => {
75
59
  try {
76
- T = JSON.parse(o);
77
- } catch (v) {
78
- return console.error("Error parsing JSON:", v), a;
60
+ const c = typeof i == "function" ? i(JSON.parse(r)) : i;
61
+ c == null ? de(e) : D(e, c);
62
+ } catch (c) {
63
+ console.warn(c);
79
64
  }
80
- return T;
81
65
  },
82
- [n, t]
83
- ), u = p(() => {
84
- const o = t instanceof Function ? t() : t;
85
- if (I)
86
- return o;
87
- try {
88
- const a = window.localStorage.getItem(e);
89
- return a ? l(a) : o;
90
- } catch (a) {
91
- return console.warn(`Error reading localStorage key “${e}”:`, a), o;
92
- }
93
- }, [t, e, l]), [h, g] = U(() => r ? u() : t instanceof Function ? t() : t), k = N((o) => {
94
- I && console.warn(
95
- `Tried setting localStorage key “${e}” even though environment is not a client`
96
- );
66
+ [e, r]
67
+ ), s = A.useCallback(() => {
68
+ o(t);
69
+ }, [t, o]), a = A.useCallback(() => {
70
+ o(null);
71
+ }, [o]);
72
+ return A.useEffect(() => {
97
73
  try {
98
- const a = o instanceof Function ? o(u()) : o;
99
- window.localStorage.setItem(e, c(a)), g(a), window.dispatchEvent(new StorageEvent("local-storage", { key: e }));
100
- } catch (a) {
101
- console.warn(`Error setting localStorage key “${e}”:`, a);
74
+ K(e) === null && typeof t < "u" && D(e, t);
75
+ } catch (i) {
76
+ console.warn(i);
102
77
  }
103
- }), i = N(() => {
104
- I && console.warn(
105
- `Tried removing localStorage key “${e}” even though environment is not a client`
106
- );
107
- const o = t instanceof Function ? t() : t;
108
- window.localStorage.removeItem(e), g(o), window.dispatchEvent(new StorageEvent("local-storage", { key: e }));
109
- });
110
- w(() => {
111
- g(u());
112
- }, [e]);
113
- const y = p(
114
- (o) => {
115
- o.key && o.key !== e || g(u());
116
- },
117
- [e, u]
118
- );
119
- return A("storage", y), A("local-storage", y), [h, k, i];
78
+ }, [e, t]), [r ? JSON.parse(r) : null, o, s, a];
120
79
  }
121
- const J = "Oops! It looks like your session has expired. For your security, please log in again to continue.", X = "You forgot to wrap your component in <AuthProvider>.", R = {
80
+ const he = "Oops! It looks like your session has expired. For your security, please log in again to continue.", pe = "Your session has been successfully terminated.", me = "You forgot to wrap your component in <AuthProvider>.", L = {
122
81
  dev: "https://auth.gizmette.local.com:3003",
123
82
  prod: "https://mylogin.gizmette.com"
83
+ }, ye = "@@auth@@", Se = `-----BEGIN PUBLIC KEY-----
84
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsF6i3Jd9fY/3COqCw/m7
85
+ w5PKyTYLGAI2I6SIIdpe6i6DOCbEkmDz7LdVsBqwNtVi8gvWYIj+8ol6rU3qu1v5
86
+ i1Jd45GSK4kzkVdgCmQZbM5ak0KI99q5wsrAIzUd+LRJ2HRvWtr5IYdsIiXaQjle
87
+ aMwPFOIcJH+rKfFgNcHLcaS5syp7zU1ANwZ+trgR+DifBr8TLVkBynmNeTyhDm2+
88
+ l0haqjMk0UoNPPE8iYBWUHQJJE1Dqstj65d6Eh5g64Pao25y4cmYJbKjiblIGEkE
89
+ sjqybA9mARAqh9k/eiIopecWSiffNQTwVQVd2I9ZH3BalhEXHlqFgrjz51kFqg81
90
+ awIDAQAB
91
+ -----END PUBLIC KEY-----`, J = crypto, q = (e) => e instanceof CryptoKey, _ = new TextEncoder(), R = new TextDecoder();
92
+ function we(...e) {
93
+ const t = e.reduce((o, { length: s }) => o + s, 0), n = new Uint8Array(t);
94
+ let r = 0;
95
+ for (const o of e)
96
+ n.set(o, r), r += o.length;
97
+ return n;
98
+ }
99
+ const Ee = (e) => {
100
+ const t = atob(e), n = new Uint8Array(t.length);
101
+ for (let r = 0; r < t.length; r++)
102
+ n[r] = t.charCodeAt(r);
103
+ return n;
104
+ }, x = (e) => {
105
+ let t = e;
106
+ t instanceof Uint8Array && (t = R.decode(t)), t = t.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
107
+ try {
108
+ return Ee(t);
109
+ } catch {
110
+ throw new TypeError("The input to be decoded is not correctly encoded.");
111
+ }
112
+ };
113
+ class g extends Error {
114
+ static get code() {
115
+ return "ERR_JOSE_GENERIC";
116
+ }
117
+ constructor(t) {
118
+ var n;
119
+ super(t), this.code = "ERR_JOSE_GENERIC", this.name = this.constructor.name, (n = Error.captureStackTrace) == null || n.call(Error, this, this.constructor);
120
+ }
121
+ }
122
+ class m extends g {
123
+ static get code() {
124
+ return "ERR_JWT_CLAIM_VALIDATION_FAILED";
125
+ }
126
+ constructor(t, n, r = "unspecified", o = "unspecified") {
127
+ super(t), this.code = "ERR_JWT_CLAIM_VALIDATION_FAILED", this.claim = r, this.reason = o, this.payload = n;
128
+ }
129
+ }
130
+ class W extends g {
131
+ static get code() {
132
+ return "ERR_JWT_EXPIRED";
133
+ }
134
+ constructor(t, n, r = "unspecified", o = "unspecified") {
135
+ super(t), this.code = "ERR_JWT_EXPIRED", this.claim = r, this.reason = o, this.payload = n;
136
+ }
137
+ }
138
+ class ge extends g {
139
+ constructor() {
140
+ super(...arguments), this.code = "ERR_JOSE_ALG_NOT_ALLOWED";
141
+ }
142
+ static get code() {
143
+ return "ERR_JOSE_ALG_NOT_ALLOWED";
144
+ }
145
+ }
146
+ class C extends g {
147
+ constructor() {
148
+ super(...arguments), this.code = "ERR_JOSE_NOT_SUPPORTED";
149
+ }
150
+ static get code() {
151
+ return "ERR_JOSE_NOT_SUPPORTED";
152
+ }
153
+ }
154
+ class l extends g {
155
+ constructor() {
156
+ super(...arguments), this.code = "ERR_JWS_INVALID";
157
+ }
158
+ static get code() {
159
+ return "ERR_JWS_INVALID";
160
+ }
161
+ }
162
+ class z extends g {
163
+ constructor() {
164
+ super(...arguments), this.code = "ERR_JWT_INVALID";
165
+ }
166
+ static get code() {
167
+ return "ERR_JWT_INVALID";
168
+ }
169
+ }
170
+ class be extends g {
171
+ constructor() {
172
+ super(...arguments), this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED", this.message = "signature verification failed";
173
+ }
174
+ static get code() {
175
+ return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
176
+ }
177
+ }
178
+ function S(e, t = "algorithm.name") {
179
+ return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);
180
+ }
181
+ function T(e, t) {
182
+ return e.name === t;
183
+ }
184
+ function O(e) {
185
+ return parseInt(e.name.slice(4), 10);
186
+ }
187
+ function Ae(e) {
188
+ switch (e) {
189
+ case "ES256":
190
+ return "P-256";
191
+ case "ES384":
192
+ return "P-384";
193
+ case "ES512":
194
+ return "P-521";
195
+ default:
196
+ throw new Error("unreachable");
197
+ }
198
+ }
199
+ function Ie(e, t) {
200
+ if (t.length && !t.some((n) => e.usages.includes(n))) {
201
+ let n = "CryptoKey does not support this operation, its usages must include ";
202
+ if (t.length > 2) {
203
+ const r = t.pop();
204
+ n += `one of ${t.join(", ")}, or ${r}.`;
205
+ } else
206
+ t.length === 2 ? n += `one of ${t[0]} or ${t[1]}.` : n += `${t[0]}.`;
207
+ throw new TypeError(n);
208
+ }
209
+ }
210
+ function _e(e, t, ...n) {
211
+ switch (t) {
212
+ case "HS256":
213
+ case "HS384":
214
+ case "HS512": {
215
+ if (!T(e.algorithm, "HMAC"))
216
+ throw S("HMAC");
217
+ const r = parseInt(t.slice(2), 10);
218
+ if (O(e.algorithm.hash) !== r)
219
+ throw S(`SHA-${r}`, "algorithm.hash");
220
+ break;
221
+ }
222
+ case "RS256":
223
+ case "RS384":
224
+ case "RS512": {
225
+ if (!T(e.algorithm, "RSASSA-PKCS1-v1_5"))
226
+ throw S("RSASSA-PKCS1-v1_5");
227
+ const r = parseInt(t.slice(2), 10);
228
+ if (O(e.algorithm.hash) !== r)
229
+ throw S(`SHA-${r}`, "algorithm.hash");
230
+ break;
231
+ }
232
+ case "PS256":
233
+ case "PS384":
234
+ case "PS512": {
235
+ if (!T(e.algorithm, "RSA-PSS"))
236
+ throw S("RSA-PSS");
237
+ const r = parseInt(t.slice(2), 10);
238
+ if (O(e.algorithm.hash) !== r)
239
+ throw S(`SHA-${r}`, "algorithm.hash");
240
+ break;
241
+ }
242
+ case "EdDSA": {
243
+ if (e.algorithm.name !== "Ed25519" && e.algorithm.name !== "Ed448")
244
+ throw S("Ed25519 or Ed448");
245
+ break;
246
+ }
247
+ case "ES256":
248
+ case "ES384":
249
+ case "ES512": {
250
+ if (!T(e.algorithm, "ECDSA"))
251
+ throw S("ECDSA");
252
+ const r = Ae(t);
253
+ if (e.algorithm.namedCurve !== r)
254
+ throw S(r, "algorithm.namedCurve");
255
+ break;
256
+ }
257
+ default:
258
+ throw new TypeError("CryptoKey does not support this operation");
259
+ }
260
+ Ie(e, n);
261
+ }
262
+ function X(e, t, ...n) {
263
+ var r;
264
+ if (n.length > 2) {
265
+ const o = n.pop();
266
+ e += `one of type ${n.join(", ")}, or ${o}.`;
267
+ } else
268
+ n.length === 2 ? e += `one of type ${n[0]} or ${n[1]}.` : e += `of type ${n[0]}.`;
269
+ return t == null ? e += ` Received ${t}` : typeof t == "function" && t.name ? e += ` Received function ${t.name}` : typeof t == "object" && t != null && (r = t.constructor) != null && r.name && (e += ` Received an instance of ${t.constructor.name}`), e;
270
+ }
271
+ const H = (e, ...t) => X("Key must be ", e, ...t);
272
+ function j(e, t, ...n) {
273
+ return X(`Key for the ${e} algorithm must be `, t, ...n);
274
+ }
275
+ const Q = (e) => q(e), E = ["CryptoKey"], Te = (...e) => {
276
+ const t = e.filter(Boolean);
277
+ if (t.length === 0 || t.length === 1)
278
+ return !0;
279
+ let n;
280
+ for (const r of t) {
281
+ const o = Object.keys(r);
282
+ if (!n || n.size === 0) {
283
+ n = new Set(o);
284
+ continue;
285
+ }
286
+ for (const s of o) {
287
+ if (n.has(s))
288
+ return !1;
289
+ n.add(s);
290
+ }
291
+ }
292
+ return !0;
124
293
  };
125
- var s = [];
126
- for (var f = 0; f < 256; ++f)
127
- s.push((f + 256).toString(16).slice(1));
128
- function K(e, t = 0) {
129
- return (s[e[t + 0]] + s[e[t + 1]] + s[e[t + 2]] + s[e[t + 3]] + "-" + s[e[t + 4]] + s[e[t + 5]] + "-" + s[e[t + 6]] + s[e[t + 7]] + "-" + s[e[t + 8]] + s[e[t + 9]] + "-" + s[e[t + 10]] + s[e[t + 11]] + s[e[t + 12]] + s[e[t + 13]] + s[e[t + 14]] + s[e[t + 15]]).toLowerCase();
130
- }
131
- var m, W = new Uint8Array(16);
132
- function Y() {
133
- if (!m && (m = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !m))
294
+ function ve(e) {
295
+ return typeof e == "object" && e !== null;
296
+ }
297
+ function U(e) {
298
+ if (!ve(e) || Object.prototype.toString.call(e) !== "[object Object]")
299
+ return !1;
300
+ if (Object.getPrototypeOf(e) === null)
301
+ return !0;
302
+ let t = e;
303
+ for (; Object.getPrototypeOf(t) !== null; )
304
+ t = Object.getPrototypeOf(t);
305
+ return Object.getPrototypeOf(e) === t;
306
+ }
307
+ const Re = (e, t) => {
308
+ if (e.startsWith("RS") || e.startsWith("PS")) {
309
+ const { modulusLength: n } = t.algorithm;
310
+ if (typeof n != "number" || n < 2048)
311
+ throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`);
312
+ }
313
+ }, w = (e, t, n = 0) => {
314
+ n === 0 && (t.unshift(t.length), t.unshift(6));
315
+ const r = e.indexOf(t[0], n);
316
+ if (r === -1)
317
+ return !1;
318
+ const o = e.subarray(r, r + t.length);
319
+ return o.length !== t.length ? !1 : o.every((s, a) => s === t[a]) || w(e, t, r + 1);
320
+ }, $ = (e) => {
321
+ switch (!0) {
322
+ case w(e, [42, 134, 72, 206, 61, 3, 1, 7]):
323
+ return "P-256";
324
+ case w(e, [43, 129, 4, 0, 34]):
325
+ return "P-384";
326
+ case w(e, [43, 129, 4, 0, 35]):
327
+ return "P-521";
328
+ case w(e, [43, 101, 110]):
329
+ return "X25519";
330
+ case w(e, [43, 101, 111]):
331
+ return "X448";
332
+ case w(e, [43, 101, 112]):
333
+ return "Ed25519";
334
+ case w(e, [43, 101, 113]):
335
+ return "Ed448";
336
+ default:
337
+ throw new C("Invalid or unsupported EC Key Curve or OKP Key Sub Type");
338
+ }
339
+ }, Ce = async (e, t, n, r, o) => {
340
+ let s, a;
341
+ const i = new Uint8Array(atob(n.replace(e, "")).split("").map((c) => c.charCodeAt(0)));
342
+ switch (r) {
343
+ case "PS256":
344
+ case "PS384":
345
+ case "PS512":
346
+ s = { name: "RSA-PSS", hash: `SHA-${r.slice(-3)}` }, a = ["verify"];
347
+ break;
348
+ case "RS256":
349
+ case "RS384":
350
+ case "RS512":
351
+ s = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${r.slice(-3)}` }, a = ["verify"];
352
+ break;
353
+ case "RSA-OAEP":
354
+ case "RSA-OAEP-256":
355
+ case "RSA-OAEP-384":
356
+ case "RSA-OAEP-512":
357
+ s = {
358
+ name: "RSA-OAEP",
359
+ hash: `SHA-${parseInt(r.slice(-3), 10) || 1}`
360
+ }, a = ["encrypt", "wrapKey"];
361
+ break;
362
+ case "ES256":
363
+ s = { name: "ECDSA", namedCurve: "P-256" }, a = ["verify"];
364
+ break;
365
+ case "ES384":
366
+ s = { name: "ECDSA", namedCurve: "P-384" }, a = ["verify"];
367
+ break;
368
+ case "ES512":
369
+ s = { name: "ECDSA", namedCurve: "P-521" }, a = ["verify"];
370
+ break;
371
+ case "ECDH-ES":
372
+ case "ECDH-ES+A128KW":
373
+ case "ECDH-ES+A192KW":
374
+ case "ECDH-ES+A256KW": {
375
+ const c = $(i);
376
+ s = c.startsWith("P-") ? { name: "ECDH", namedCurve: c } : { name: c }, a = [];
377
+ break;
378
+ }
379
+ case "EdDSA":
380
+ s = { name: $(i) }, a = ["verify"];
381
+ break;
382
+ default:
383
+ throw new C('Invalid or unsupported "alg" (Algorithm) value');
384
+ }
385
+ return J.subtle.importKey(t, i, s, !1, a);
386
+ }, Pe = (e, t, n) => Ce(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", e, t);
387
+ async function xe(e, t, n) {
388
+ if (e.indexOf("-----BEGIN PUBLIC KEY-----") !== 0)
389
+ throw new TypeError('"spki" must be SPKI formatted string');
390
+ return Pe(e, t);
391
+ }
392
+ const Oe = (e, t) => {
393
+ if (!(t instanceof Uint8Array)) {
394
+ if (!Q(t))
395
+ throw new TypeError(j(e, t, ...E, "Uint8Array"));
396
+ if (t.type !== "secret")
397
+ throw new TypeError(`${E.join(" or ")} instances for symmetric algorithms must be of type "secret"`);
398
+ }
399
+ }, Ne = (e, t, n) => {
400
+ if (!Q(t))
401
+ throw new TypeError(j(e, t, ...E));
402
+ if (t.type === "secret")
403
+ throw new TypeError(`${E.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);
404
+ if (t.algorithm && n === "verify" && t.type === "private")
405
+ throw new TypeError(`${E.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);
406
+ if (t.algorithm && n === "encrypt" && t.type === "private")
407
+ throw new TypeError(`${E.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`);
408
+ }, Ue = (e, t, n) => {
409
+ e.startsWith("HS") || e === "dir" || e.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(e) ? Oe(e, t) : Ne(e, t, n);
410
+ };
411
+ function Je(e, t, n, r, o) {
412
+ if (o.crit !== void 0 && (r == null ? void 0 : r.crit) === void 0)
413
+ throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');
414
+ if (!r || r.crit === void 0)
415
+ return /* @__PURE__ */ new Set();
416
+ if (!Array.isArray(r.crit) || r.crit.length === 0 || r.crit.some((a) => typeof a != "string" || a.length === 0))
417
+ throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
418
+ let s;
419
+ n !== void 0 ? s = new Map([...Object.entries(n), ...t.entries()]) : s = t;
420
+ for (const a of r.crit) {
421
+ if (!s.has(a))
422
+ throw new C(`Extension Header Parameter "${a}" is not recognized`);
423
+ if (o[a] === void 0)
424
+ throw new e(`Extension Header Parameter "${a}" is missing`);
425
+ if (s.get(a) && r[a] === void 0)
426
+ throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`);
427
+ }
428
+ return new Set(r.crit);
429
+ }
430
+ const ke = (e, t) => {
431
+ if (t !== void 0 && (!Array.isArray(t) || t.some((n) => typeof n != "string")))
432
+ throw new TypeError(`"${e}" option must be an array of strings`);
433
+ if (t)
434
+ return new Set(t);
435
+ };
436
+ function De(e, t) {
437
+ const n = `SHA-${e.slice(-3)}`;
438
+ switch (e) {
439
+ case "HS256":
440
+ case "HS384":
441
+ case "HS512":
442
+ return { hash: n, name: "HMAC" };
443
+ case "PS256":
444
+ case "PS384":
445
+ case "PS512":
446
+ return { hash: n, name: "RSA-PSS", saltLength: e.slice(-3) >> 3 };
447
+ case "RS256":
448
+ case "RS384":
449
+ case "RS512":
450
+ return { hash: n, name: "RSASSA-PKCS1-v1_5" };
451
+ case "ES256":
452
+ case "ES384":
453
+ case "ES512":
454
+ return { hash: n, name: "ECDSA", namedCurve: t.namedCurve };
455
+ case "EdDSA":
456
+ return { name: t.name };
457
+ default:
458
+ throw new C(`alg ${e} is not supported either by JOSE or your javascript runtime`);
459
+ }
460
+ }
461
+ function Ke(e, t, n) {
462
+ if (q(t))
463
+ return _e(t, e, n), t;
464
+ if (t instanceof Uint8Array) {
465
+ if (!e.startsWith("HS"))
466
+ throw new TypeError(H(t, ...E));
467
+ return J.subtle.importKey("raw", t, { hash: `SHA-${e.slice(-3)}`, name: "HMAC" }, !1, [n]);
468
+ }
469
+ throw new TypeError(H(t, ...E, "Uint8Array"));
470
+ }
471
+ const Le = async (e, t, n, r) => {
472
+ const o = await Ke(e, t, "verify");
473
+ Re(e, o);
474
+ const s = De(e, o.algorithm);
475
+ try {
476
+ return await J.subtle.verify(s, o, n, r);
477
+ } catch {
478
+ return !1;
479
+ }
480
+ };
481
+ async function We(e, t, n) {
482
+ if (!U(e))
483
+ throw new l("Flattened JWS must be an object");
484
+ if (e.protected === void 0 && e.header === void 0)
485
+ throw new l('Flattened JWS must have either of the "protected" or "header" members');
486
+ if (e.protected !== void 0 && typeof e.protected != "string")
487
+ throw new l("JWS Protected Header incorrect type");
488
+ if (e.payload === void 0)
489
+ throw new l("JWS Payload missing");
490
+ if (typeof e.signature != "string")
491
+ throw new l("JWS Signature missing or incorrect type");
492
+ if (e.header !== void 0 && !U(e.header))
493
+ throw new l("JWS Unprotected Header incorrect type");
494
+ let r = {};
495
+ if (e.protected)
496
+ try {
497
+ const P = x(e.protected);
498
+ r = JSON.parse(R.decode(P));
499
+ } catch {
500
+ throw new l("JWS Protected Header is invalid");
501
+ }
502
+ if (!Te(r, e.header))
503
+ throw new l("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
504
+ const o = {
505
+ ...r,
506
+ ...e.header
507
+ }, s = Je(l, /* @__PURE__ */ new Map([["b64", !0]]), n == null ? void 0 : n.crit, r, o);
508
+ let a = !0;
509
+ if (s.has("b64") && (a = r.b64, typeof a != "boolean"))
510
+ throw new l('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
511
+ const { alg: i } = o;
512
+ if (typeof i != "string" || !i)
513
+ throw new l('JWS "alg" (Algorithm) Header Parameter missing or invalid');
514
+ const c = n && ke("algorithms", n.algorithms);
515
+ if (c && !c.has(i))
516
+ throw new ge('"alg" (Algorithm) Header Parameter value not allowed');
517
+ if (a) {
518
+ if (typeof e.payload != "string")
519
+ throw new l("JWS Payload must be a string");
520
+ } else if (typeof e.payload != "string" && !(e.payload instanceof Uint8Array))
521
+ throw new l("JWS Payload must be a string or an Uint8Array instance");
522
+ let h = !1;
523
+ typeof t == "function" && (t = await t(r, e), h = !0), Ue(i, t, "verify");
524
+ const y = we(_.encode(e.protected ?? ""), _.encode("."), typeof e.payload == "string" ? _.encode(e.payload) : e.payload);
525
+ let u;
526
+ try {
527
+ u = x(e.signature);
528
+ } catch {
529
+ throw new l("Failed to base64url decode the signature");
530
+ }
531
+ if (!await Le(i, t, u, y))
532
+ throw new be();
533
+ let f;
534
+ if (a)
535
+ try {
536
+ f = x(e.payload);
537
+ } catch {
538
+ throw new l("Failed to base64url decode the payload");
539
+ }
540
+ else
541
+ typeof e.payload == "string" ? f = _.encode(e.payload) : f = e.payload;
542
+ const p = { payload: f };
543
+ return e.protected !== void 0 && (p.protectedHeader = r), e.header !== void 0 && (p.unprotectedHeader = e.header), h ? { ...p, key: t } : p;
544
+ }
545
+ async function He(e, t, n) {
546
+ if (e instanceof Uint8Array && (e = R.decode(e)), typeof e != "string")
547
+ throw new l("Compact JWS must be a string or Uint8Array");
548
+ const { 0: r, 1: o, 2: s, length: a } = e.split(".");
549
+ if (a !== 3)
550
+ throw new l("Invalid Compact JWS");
551
+ const i = await We({ payload: o, protected: r, signature: s }, t, n), c = { payload: i.payload, protectedHeader: i.protectedHeader };
552
+ return typeof t == "function" ? { ...c, key: i.key } : c;
553
+ }
554
+ const $e = (e) => Math.floor(e.getTime() / 1e3), Z = 60, ee = Z * 60, k = ee * 24, Me = k * 7, Ve = k * 365.25, Be = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, M = (e) => {
555
+ const t = Be.exec(e);
556
+ if (!t || t[4] && t[1])
557
+ throw new TypeError("Invalid time period format");
558
+ const n = parseFloat(t[2]), r = t[3].toLowerCase();
559
+ let o;
560
+ switch (r) {
561
+ case "sec":
562
+ case "secs":
563
+ case "second":
564
+ case "seconds":
565
+ case "s":
566
+ o = Math.round(n);
567
+ break;
568
+ case "minute":
569
+ case "minutes":
570
+ case "min":
571
+ case "mins":
572
+ case "m":
573
+ o = Math.round(n * Z);
574
+ break;
575
+ case "hour":
576
+ case "hours":
577
+ case "hr":
578
+ case "hrs":
579
+ case "h":
580
+ o = Math.round(n * ee);
581
+ break;
582
+ case "day":
583
+ case "days":
584
+ case "d":
585
+ o = Math.round(n * k);
586
+ break;
587
+ case "week":
588
+ case "weeks":
589
+ case "w":
590
+ o = Math.round(n * Me);
591
+ break;
592
+ default:
593
+ o = Math.round(n * Ve);
594
+ break;
595
+ }
596
+ return t[1] === "-" || t[4] === "ago" ? -o : o;
597
+ }, V = (e) => e.toLowerCase().replace(/^application\//, ""), Fe = (e, t) => typeof e == "string" ? t.includes(e) : Array.isArray(e) ? t.some(Set.prototype.has.bind(new Set(e))) : !1, Ge = (e, t, n = {}) => {
598
+ let r;
599
+ try {
600
+ r = JSON.parse(R.decode(t));
601
+ } catch {
602
+ }
603
+ if (!U(r))
604
+ throw new z("JWT Claims Set must be a top-level JSON object");
605
+ const { typ: o } = n;
606
+ if (o && (typeof e.typ != "string" || V(e.typ) !== V(o)))
607
+ throw new m('unexpected "typ" JWT header value', r, "typ", "check_failed");
608
+ const { requiredClaims: s = [], issuer: a, subject: i, audience: c, maxTokenAge: h } = n, y = [...s];
609
+ h !== void 0 && y.push("iat"), c !== void 0 && y.push("aud"), i !== void 0 && y.push("sub"), a !== void 0 && y.push("iss");
610
+ for (const p of new Set(y.reverse()))
611
+ if (!(p in r))
612
+ throw new m(`missing required "${p}" claim`, r, p, "missing");
613
+ if (a && !(Array.isArray(a) ? a : [a]).includes(r.iss))
614
+ throw new m('unexpected "iss" claim value', r, "iss", "check_failed");
615
+ if (i && r.sub !== i)
616
+ throw new m('unexpected "sub" claim value', r, "sub", "check_failed");
617
+ if (c && !Fe(r.aud, typeof c == "string" ? [c] : c))
618
+ throw new m('unexpected "aud" claim value', r, "aud", "check_failed");
619
+ let u;
620
+ switch (typeof n.clockTolerance) {
621
+ case "string":
622
+ u = M(n.clockTolerance);
623
+ break;
624
+ case "number":
625
+ u = n.clockTolerance;
626
+ break;
627
+ case "undefined":
628
+ u = 0;
629
+ break;
630
+ default:
631
+ throw new TypeError("Invalid clockTolerance option type");
632
+ }
633
+ const { currentDate: I } = n, f = $e(I || /* @__PURE__ */ new Date());
634
+ if ((r.iat !== void 0 || h) && typeof r.iat != "number")
635
+ throw new m('"iat" claim must be a number', r, "iat", "invalid");
636
+ if (r.nbf !== void 0) {
637
+ if (typeof r.nbf != "number")
638
+ throw new m('"nbf" claim must be a number', r, "nbf", "invalid");
639
+ if (r.nbf > f + u)
640
+ throw new m('"nbf" claim timestamp check failed', r, "nbf", "check_failed");
641
+ }
642
+ if (r.exp !== void 0) {
643
+ if (typeof r.exp != "number")
644
+ throw new m('"exp" claim must be a number', r, "exp", "invalid");
645
+ if (r.exp <= f - u)
646
+ throw new W('"exp" claim timestamp check failed', r, "exp", "check_failed");
647
+ }
648
+ if (h) {
649
+ const p = f - r.iat, P = typeof h == "number" ? h : M(h);
650
+ if (p - u > P)
651
+ throw new W('"iat" claim timestamp check failed (too far in the past)', r, "iat", "check_failed");
652
+ if (p < 0 - u)
653
+ throw new m('"iat" claim timestamp check failed (it should be in the past)', r, "iat", "check_failed");
654
+ }
655
+ return r;
656
+ };
657
+ async function Ye(e, t, n) {
658
+ var a;
659
+ const r = await He(e, t, n);
660
+ if ((a = r.protectedHeader.crit) != null && a.includes("b64") && r.protectedHeader.b64 === !1)
661
+ throw new z("JWTs MUST NOT use unencoded payload");
662
+ const s = { payload: Ge(r.protectedHeader, r.payload, n), protectedHeader: r.protectedHeader };
663
+ return typeof t == "function" ? { ...s, key: r.key } : s;
664
+ }
665
+ var d = [];
666
+ for (var N = 0; N < 256; ++N)
667
+ d.push((N + 256).toString(16).slice(1));
668
+ function qe(e, t = 0) {
669
+ return (d[e[t + 0]] + d[e[t + 1]] + d[e[t + 2]] + d[e[t + 3]] + "-" + d[e[t + 4]] + d[e[t + 5]] + "-" + d[e[t + 6]] + d[e[t + 7]] + "-" + d[e[t + 8]] + d[e[t + 9]] + "-" + d[e[t + 10]] + d[e[t + 11]] + d[e[t + 12]] + d[e[t + 13]] + d[e[t + 14]] + d[e[t + 15]]).toLowerCase();
670
+ }
671
+ var v, ze = new Uint8Array(16);
672
+ function Xe() {
673
+ if (!v && (v = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !v))
134
674
  throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
135
- return m(W);
675
+ return v(ze);
136
676
  }
137
- var q = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
138
- const C = {
139
- randomUUID: q
677
+ var je = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
678
+ const B = {
679
+ randomUUID: je
140
680
  };
141
- function B(e, t, n) {
142
- if (C.randomUUID && !t && !e)
143
- return C.randomUUID();
681
+ function Qe(e, t, n) {
682
+ if (B.randomUUID && !t && !e)
683
+ return B.randomUUID();
144
684
  e = e || {};
145
- var r = e.random || (e.rng || Y)();
146
- return r[6] = r[6] & 15 | 64, r[8] = r[8] & 63 | 128, K(r);
685
+ var r = e.random || (e.rng || Xe)();
686
+ return r[6] = r[6] & 15 | 64, r[8] = r[8] & 63 | 128, qe(r);
147
687
  }
148
- const G = process.env.NODE_ENV === "production", Q = !G, Z = async ({ params: e = {} }) => {
688
+ const Ze = process.env.NODE_ENV === "production", et = !Ze, tt = async ({ params: e = {} }) => {
149
689
  try {
150
- const t = B(), n = await fetch(
151
- Q ? `${R.dev}/authenticate` : `${R.prod}/authenticate`,
690
+ const t = Qe(), n = await fetch(
691
+ et ? `${L.dev}/authenticate` : `${L.prod}/authenticate`,
152
692
  {
153
693
  credentials: "include",
154
694
  method: "POST",
155
695
  headers: {
156
696
  "Content-Type": "application/json",
157
- [j.CLIENT_ID]: `${e.clientId}`
697
+ [ue.CLIENT_ID]: `${e.clientId}`
158
698
  },
159
699
  body: JSON.stringify({ ...e, nonce: t })
160
700
  }
161
701
  );
162
702
  if (n.status !== 200)
163
703
  return { status: n.status, data: [] };
164
- const { data: r, errors: c } = await n.json();
704
+ const { data: r, errors: o } = await n.json();
165
705
  return r.nonce !== t ? { status: 500, data: [] } : {
166
706
  status: n.status,
167
707
  data: r,
168
- errors: c
708
+ errors: o
169
709
  };
170
710
  } catch (t) {
171
711
  return console.error(t), { status: 500, data: [] };
172
712
  }
713
+ }, te = async (e) => {
714
+ try {
715
+ const t = b.ALG, r = await xe(Se, t);
716
+ return await Ye(e, r, {
717
+ issuer: b.ISSUER
718
+ });
719
+ } catch {
720
+ return;
721
+ }
722
+ }, rt = async ({
723
+ username: e,
724
+ password: t,
725
+ clientId: n,
726
+ sessionExpiration: r
727
+ }) => {
728
+ try {
729
+ const o = await tt({
730
+ params: {
731
+ type: ce.ID_TOKEN,
732
+ username: e,
733
+ password: t,
734
+ sessionExpiration: r,
735
+ clientId: n
736
+ }
737
+ }), s = await te(o.data.idToken);
738
+ return s && s.payload[b.USER_ID_KEY] !== "" ? {
739
+ idToken: o.data.idToken,
740
+ userId: s.payload[b.USER_ID_KEY],
741
+ status: !0
742
+ } : {
743
+ status: !1
744
+ };
745
+ } catch {
746
+ return {
747
+ status: !1
748
+ };
749
+ }
173
750
  };
174
- function ee(e) {
175
- const t = _();
176
- return w(() => {
751
+ function nt(e) {
752
+ const t = oe();
753
+ return G(() => {
177
754
  t.current = e;
178
755
  }), t.current;
179
756
  }
180
- const O = () => {
181
- throw new Error(X);
182
- }, x = M({
757
+ const F = () => {
758
+ throw new Error(me);
759
+ }, re = ae({
183
760
  isAuthenticated: !1,
184
- login: O,
185
- logout: O,
761
+ login: F,
762
+ logout: F,
186
763
  accessToken: void 0,
187
764
  refreshToken: void 0,
188
765
  idToken: void 0,
189
766
  logoutReason: ""
190
- }), oe = ({
767
+ }), st = ({
191
768
  children: e,
192
769
  sessionExpiration: t,
193
- clientId: n,
194
- accessType: r
770
+ clientId: n
195
771
  }) => {
196
- const [c, l, u] = E(
197
- `@@auth@@::${n}::@@access@@`,
198
- ""
199
- ), [h, g, k] = E(
200
- `@@auth@@::${n}::@@refresh@@`,
201
- ""
202
- ), [i, y, o] = E(
203
- `@@auth@@::${n}::@@user@@`,
204
- ""
205
- ), [a, T] = U({
206
- isAuthenticated: !!i,
207
- accessToken: c,
208
- refreshToken: h,
209
- idToken: i,
772
+ const [r, o, , s] = fe({
773
+ key: `${ye}::${n}::@@user@@`
774
+ }), [a, i] = se({
775
+ isAuthenticated: !!r,
210
776
  logoutReason: "",
211
777
  userId: ""
212
- }), v = ee(i) || "";
213
- w(() => {
214
- v !== i && i !== "" ? T({
215
- isAuthenticated: !0,
216
- accessToken: c,
217
- refreshToken: h,
218
- idToken: i,
219
- logoutReason: "",
220
- userId: a.userId
221
- }) : v !== i && i === "" && T({
222
- isAuthenticated: !1,
223
- accessToken: "",
224
- refreshToken: "",
225
- idToken: "",
226
- logoutReason: J,
227
- userId: ""
228
- });
229
- }, [c, h, i, v, a.userId]);
230
- const $ = async (L, V) => {
231
- var S;
232
- const d = await Z({
233
- params: {
234
- type: r || H.ID_TOKEN,
235
- username: L,
236
- password: V,
237
- sessionExpiration: t,
238
- clientId: n
778
+ }), c = nt(r) || "";
779
+ G(() => {
780
+ c !== r && r !== null && (async () => {
781
+ try {
782
+ const u = await te(r);
783
+ u && u.payload[b.USER_ID_KEY] !== "" && i({
784
+ isAuthenticated: !0,
785
+ logoutReason: "",
786
+ userId: u.payload[b.USER_ID_KEY]
787
+ });
788
+ } catch {
789
+ i({
790
+ isAuthenticated: !1,
791
+ logoutReason: he,
792
+ userId: ""
793
+ });
239
794
  }
795
+ })();
796
+ }, [r, c]);
797
+ const h = async (u, I) => {
798
+ const f = await rt({
799
+ username: u,
800
+ password: I,
801
+ clientId: n,
802
+ sessionExpiration: t
240
803
  });
241
- return (S = d.data) != null && S.idToken ? (y(d.data.idToken), d.data.accessToken && l(d.data.accessToken), d.data.refreshToken && g(d.data.refreshToken), T({
804
+ return f.status ? (o(f.idToken), i({
242
805
  isAuthenticated: !0,
243
- idToken: d.data.idToken,
244
- accessToken: d.data.accessToken,
245
- refreshToken: d.data.refreshToken,
246
- userId: d.data.userId,
247
- logoutReason: ""
806
+ userId: f.userId
248
807
  }), !0) : !1;
249
- }, b = () => {
250
- u(), k(), o();
808
+ }, y = () => {
809
+ i({
810
+ isAuthenticated: !1,
811
+ logoutReason: pe,
812
+ userId: ""
813
+ }), s();
251
814
  };
252
- return /* @__PURE__ */ P(x.Provider, { value: { ...a, login: $, logout: b }, children: e });
253
- }, re = (e = x) => F(e);
815
+ return /* @__PURE__ */ ne(re.Provider, { value: { ...a, login: h, logout: y }, children: e });
816
+ }, it = (e = re) => ie(e);
254
817
  export {
255
- oe as AuthProvider,
256
- re as useAuth
818
+ st as AuthProvider,
819
+ it as useAuth
257
820
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@versini/auth-provider",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
4
  "license": "MIT",
5
5
  "author": "Arno Versini",
6
6
  "publishConfig": {
@@ -44,9 +44,10 @@
44
44
  "react-dom": "18.3.1"
45
45
  },
46
46
  "dependencies": {
47
- "@versini/auth-common": "2.0.0",
48
- "@versini/ui-hooks": "3.0.0",
47
+ "@versini/auth-common": "2.1.0",
48
+ "@versini/ui-hooks": "4.0.0",
49
+ "jose": "5.4.1",
49
50
  "uuid": "10.0.0"
50
51
  },
51
- "gitHead": "396698b2ecd3da3881a4b226a99eff3003501a27"
52
+ "gitHead": "a94b2706534018d76db4f96687260291b2b3b31e"
52
53
  }