@versini/auth-common 3.2.0 → 3.3.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
@@ -94,6 +94,43 @@ type GetToken = {
94
94
  };
95
95
  declare const getToken: ({ headers, body, clientId }: GetToken) => string;
96
96
 
97
- declare const isGranted: (token: string, scopes: string[]) => Promise<boolean>;
97
+ type ScopesGrants = {
98
+ [key: string]: string[];
99
+ } | string[];
100
+ /**
101
+ * Checks if the given token grants the required scopes.
102
+ *
103
+ * This function verifies the provided token and extracts its payload.
104
+ * It then checks if the token contains the required scopes. The scopes can be provided
105
+ * either as an array of strings or as a map of string arrays. When the scopes are provided
106
+ * as a map, the function checks if the token contains at least one of the scopes in each
107
+ * of the map's values (OR operation).
108
+ *
109
+ *
110
+ * @async
111
+ * @function isGranted
112
+ * @param {string} token - The token to be verified and checked for scopes.
113
+ * @param {ScopesGrants} scopes - The required scopes. This can be an array of strings
114
+ * representing the scopes or a map where the keys are strings
115
+ * and the values are arrays of strings representing the scopes.
116
+ * @returns {Promise<boolean>} - A promise that resolves to a boolean indicating whether the
117
+ * token grants the required scopes.
118
+ *
119
+ * @example
120
+ * Example with an array of scopes (AND operation)
121
+ * const scopesArray = ["read", "write"];
122
+ * const res = isGranted(token, scopesArray);
123
+ * console.log(res); // true only if the token has both "read" and "write" scopes
124
+ *
125
+ * @example
126
+ * Example with a map of scopes (OR operation)
127
+ * const scopesMap = {
128
+ * "admin": ["read", "write"],
129
+ * "user": ["read"]
130
+ * };
131
+ * const res = isGranted(token, scopesMap);
132
+ * console.log(res); // true if the token has either "read" and "write" scopes or "read" scope
133
+ */
134
+ declare const isGranted: (token: string, scopes: ScopesGrants) => Promise<boolean>;
98
135
 
99
- export { API_TYPE, AUTH_TYPES, BODY, type BodyLike, HEADERS, type HeadersLike, JWT, JWT_PUBLIC_KEY, TOKEN_EXPIRATION, decodeToken, generateCodeChallenge, getToken, isGranted, pkceChallengePair, verifyAndExtractToken, verifyChallenge };
136
+ export { API_TYPE, AUTH_TYPES, BODY, type BodyLike, HEADERS, type HeadersLike, JWT, JWT_PUBLIC_KEY, type ScopesGrants, TOKEN_EXPIRATION, decodeToken, generateCodeChallenge, getToken, isGranted, pkceChallengePair, verifyAndExtractToken, verifyChallenge };
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /*!
2
- @versini/auth-common v3.2.0
2
+ @versini/auth-common v3.3.0
3
3
  © 2024 gizmette.com
4
4
  */
5
5
  try {
6
6
  window.__VERSINI_AUTH_COMMON__ || (window.__VERSINI_AUTH_COMMON__ = {
7
- version: "3.2.0",
8
- buildTime: "07/21/2024 03:41 PM EDT",
7
+ version: "3.3.0",
8
+ buildTime: "07/21/2024 07:33 PM EDT",
9
9
  homepage: "https://github.com/aversini/auth-client",
10
10
  license: "MIT"
11
11
  });
@@ -51,7 +51,7 @@ awIDAQAB
51
51
  LOGOUT: "logout"
52
52
  }, O = crypto, G = (e) => e instanceof CryptoKey, T = new TextEncoder(), C = new TextDecoder();
53
53
  function oe(...e) {
54
- const t = e.reduce((a, { length: i }) => a + i, 0), r = new Uint8Array(t);
54
+ const t = e.reduce((a, { length: o }) => a + o, 0), r = new Uint8Array(t);
55
55
  let n = 0;
56
56
  for (const a of e)
57
57
  r.set(a, n), n += a.length;
@@ -139,7 +139,7 @@ class se extends A {
139
139
  function m(e, t = "algorithm.name") {
140
140
  return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);
141
141
  }
142
- function _(e, t) {
142
+ function v(e, t) {
143
143
  return e.name === t;
144
144
  }
145
145
  function W(e) {
@@ -172,7 +172,7 @@ function le(e, t, ...r) {
172
172
  case "HS256":
173
173
  case "HS384":
174
174
  case "HS512": {
175
- if (!_(e.algorithm, "HMAC"))
175
+ if (!v(e.algorithm, "HMAC"))
176
176
  throw m("HMAC");
177
177
  const n = parseInt(t.slice(2), 10);
178
178
  if (W(e.algorithm.hash) !== n)
@@ -182,7 +182,7 @@ function le(e, t, ...r) {
182
182
  case "RS256":
183
183
  case "RS384":
184
184
  case "RS512": {
185
- if (!_(e.algorithm, "RSASSA-PKCS1-v1_5"))
185
+ if (!v(e.algorithm, "RSASSA-PKCS1-v1_5"))
186
186
  throw m("RSASSA-PKCS1-v1_5");
187
187
  const n = parseInt(t.slice(2), 10);
188
188
  if (W(e.algorithm.hash) !== n)
@@ -192,7 +192,7 @@ function le(e, t, ...r) {
192
192
  case "PS256":
193
193
  case "PS384":
194
194
  case "PS512": {
195
- if (!_(e.algorithm, "RSA-PSS"))
195
+ if (!v(e.algorithm, "RSA-PSS"))
196
196
  throw m("RSA-PSS");
197
197
  const n = parseInt(t.slice(2), 10);
198
198
  if (W(e.algorithm.hash) !== n)
@@ -207,7 +207,7 @@ function le(e, t, ...r) {
207
207
  case "ES256":
208
208
  case "ES384":
209
209
  case "ES512": {
210
- if (!_(e.algorithm, "ECDSA"))
210
+ if (!v(e.algorithm, "ECDSA"))
211
211
  throw m("ECDSA");
212
212
  const n = de(t);
213
213
  if (e.algorithm.namedCurve !== n)
@@ -242,10 +242,10 @@ const X = (e) => G(e) ? !0 : (e == null ? void 0 : e[Symbol.toStringTag]) === "K
242
242
  r = new Set(a);
243
243
  continue;
244
244
  }
245
- for (const i of a) {
246
- if (r.has(i))
245
+ for (const o of a) {
246
+ if (r.has(o))
247
247
  return !1;
248
- r.add(i);
248
+ r.add(o);
249
249
  }
250
250
  }
251
251
  return !0;
@@ -357,8 +357,8 @@ const Z = (e) => (e == null ? void 0 : e[Symbol.toStringTag]) === "KeyObject", j
357
357
  let a = e.get(t);
358
358
  if (a != null && a[n])
359
359
  return a[n];
360
- const i = await Se({ ...r, alg: n });
361
- return a ? a[n] = i : e.set(t, { [n]: i }), i;
360
+ const o = await Se({ ...r, alg: n });
361
+ return a ? a[n] = o : e.set(t, { [n]: o }), o;
362
362
  }, ye = (e, t) => {
363
363
  if (Z(e)) {
364
364
  let r = e.export({ format: "jwk" });
@@ -377,7 +377,7 @@ const Z = (e) => (e == null ? void 0 : e[Symbol.toStringTag]) === "KeyObject", j
377
377
  if (n === -1)
378
378
  return !1;
379
379
  const a = e.subarray(n, n + t.length);
380
- return a.length !== t.length ? !1 : a.every((i, o) => i === t[o]) || E(e, t, n + 1);
380
+ return a.length !== t.length ? !1 : a.every((o, i) => o === t[i]) || E(e, t, n + 1);
381
381
  }, k = (e) => {
382
382
  switch (!0) {
383
383
  case E(e, [42, 134, 72, 206, 61, 3, 1, 7]):
@@ -398,52 +398,52 @@ const Z = (e) => (e == null ? void 0 : e[Symbol.toStringTag]) === "KeyObject", j
398
398
  throw new w("Invalid or unsupported EC Key Curve or OKP Key Sub Type");
399
399
  }
400
400
  }, ge = async (e, t, r, n, a) => {
401
- let i, o;
401
+ let o, i;
402
402
  const c = new Uint8Array(atob(r.replace(e, "")).split("").map((s) => s.charCodeAt(0)));
403
403
  switch (n) {
404
404
  case "PS256":
405
405
  case "PS384":
406
406
  case "PS512":
407
- i = { name: "RSA-PSS", hash: `SHA-${n.slice(-3)}` }, o = ["verify"];
407
+ o = { name: "RSA-PSS", hash: `SHA-${n.slice(-3)}` }, i = ["verify"];
408
408
  break;
409
409
  case "RS256":
410
410
  case "RS384":
411
411
  case "RS512":
412
- i = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${n.slice(-3)}` }, o = ["verify"];
412
+ o = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${n.slice(-3)}` }, i = ["verify"];
413
413
  break;
414
414
  case "RSA-OAEP":
415
415
  case "RSA-OAEP-256":
416
416
  case "RSA-OAEP-384":
417
417
  case "RSA-OAEP-512":
418
- i = {
418
+ o = {
419
419
  name: "RSA-OAEP",
420
420
  hash: `SHA-${parseInt(n.slice(-3), 10) || 1}`
421
- }, o = ["encrypt", "wrapKey"];
421
+ }, i = ["encrypt", "wrapKey"];
422
422
  break;
423
423
  case "ES256":
424
- i = { name: "ECDSA", namedCurve: "P-256" }, o = ["verify"];
424
+ o = { name: "ECDSA", namedCurve: "P-256" }, i = ["verify"];
425
425
  break;
426
426
  case "ES384":
427
- i = { name: "ECDSA", namedCurve: "P-384" }, o = ["verify"];
427
+ o = { name: "ECDSA", namedCurve: "P-384" }, i = ["verify"];
428
428
  break;
429
429
  case "ES512":
430
- i = { name: "ECDSA", namedCurve: "P-521" }, o = ["verify"];
430
+ o = { name: "ECDSA", namedCurve: "P-521" }, i = ["verify"];
431
431
  break;
432
432
  case "ECDH-ES":
433
433
  case "ECDH-ES+A128KW":
434
434
  case "ECDH-ES+A192KW":
435
435
  case "ECDH-ES+A256KW": {
436
436
  const s = k(c);
437
- i = s.startsWith("P-") ? { name: "ECDH", namedCurve: s } : { name: s }, o = [];
437
+ o = s.startsWith("P-") ? { name: "ECDH", namedCurve: s } : { name: s }, i = [];
438
438
  break;
439
439
  }
440
440
  case "EdDSA":
441
- i = { name: k(c) }, o = ["verify"];
441
+ o = { name: k(c) }, i = ["verify"];
442
442
  break;
443
443
  default:
444
444
  throw new w('Invalid or unsupported "alg" (Algorithm) value');
445
445
  }
446
- return O.subtle.importKey(t, c, i, !1, o);
446
+ return O.subtle.importKey(t, c, o, !1, i);
447
447
  }, Ae = (e, t, r) => ge(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", e, t);
448
448
  async function be(e, t, r) {
449
449
  if (e.indexOf("-----BEGIN PUBLIC KEY-----") !== 0)
@@ -466,25 +466,25 @@ const P = (e) => e == null ? void 0 : e[Symbol.toStringTag], Ce = (e, t) => {
466
466
  throw new TypeError(`${P(t)} instances for asymmetric algorithm verifying must be of type "public"`);
467
467
  if (t.algorithm && r === "encrypt" && t.type === "private")
468
468
  throw new TypeError(`${P(t)} instances for asymmetric algorithm encryption must be of type "public"`);
469
- }, _e = (e, t, r) => {
469
+ }, ve = (e, t, r) => {
470
470
  e.startsWith("HS") || e === "dir" || e.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(e) ? Ce(e, t) : Te(e, t, r);
471
471
  };
472
- function ve(e, t, r, n, a) {
472
+ function _e(e, t, r, n, a) {
473
473
  if (a.crit !== void 0 && (n == null ? void 0 : n.crit) === void 0)
474
474
  throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');
475
475
  if (!n || n.crit === void 0)
476
476
  return /* @__PURE__ */ new Set();
477
- if (!Array.isArray(n.crit) || n.crit.length === 0 || n.crit.some((o) => typeof o != "string" || o.length === 0))
477
+ if (!Array.isArray(n.crit) || n.crit.length === 0 || n.crit.some((i) => typeof i != "string" || i.length === 0))
478
478
  throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
479
- let i;
480
- r !== void 0 ? i = new Map([...Object.entries(r), ...t.entries()]) : i = t;
481
- for (const o of n.crit) {
482
- if (!i.has(o))
483
- throw new w(`Extension Header Parameter "${o}" is not recognized`);
484
- if (a[o] === void 0)
485
- throw new e(`Extension Header Parameter "${o}" is missing`);
486
- if (i.get(o) && n[o] === void 0)
487
- throw new e(`Extension Header Parameter "${o}" MUST be integrity protected`);
479
+ let o;
480
+ r !== void 0 ? o = new Map([...Object.entries(r), ...t.entries()]) : o = t;
481
+ for (const i of n.crit) {
482
+ if (!o.has(i))
483
+ throw new w(`Extension Header Parameter "${i}" is not recognized`);
484
+ if (a[i] === void 0)
485
+ throw new e(`Extension Header Parameter "${i}" is missing`);
486
+ if (o.get(i) && n[i] === void 0)
487
+ throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`);
488
488
  }
489
489
  return new Set(n.crit);
490
490
  }
@@ -532,9 +532,9 @@ async function Re(e, t, r) {
532
532
  const Ke = async (e, t, r, n) => {
533
533
  const a = await Re(e, t, "verify");
534
534
  pe(e, a);
535
- const i = Ie(e, a.algorithm);
535
+ const o = Ie(e, a.algorithm);
536
536
  try {
537
- return await O.subtle.verify(i, a, r, n);
537
+ return await O.subtle.verify(o, a, r, n);
538
538
  } catch {
539
539
  return !1;
540
540
  }
@@ -565,9 +565,9 @@ async function Oe(e, t, r) {
565
565
  const a = {
566
566
  ...n,
567
567
  ...e.header
568
- }, i = ve(u, /* @__PURE__ */ new Map([["b64", !0]]), r == null ? void 0 : r.crit, n, a);
569
- let o = !0;
570
- if (i.has("b64") && (o = n.b64, typeof o != "boolean"))
568
+ }, o = _e(u, /* @__PURE__ */ new Map([["b64", !0]]), r == null ? void 0 : r.crit, n, a);
569
+ let i = !0;
570
+ if (o.has("b64") && (i = n.b64, typeof i != "boolean"))
571
571
  throw new u('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
572
572
  const { alg: c } = a;
573
573
  if (typeof c != "string" || !c)
@@ -575,13 +575,13 @@ async function Oe(e, t, r) {
575
575
  const s = r && Pe("algorithms", r.algorithms);
576
576
  if (s && !s.has(c))
577
577
  throw new ce('"alg" (Algorithm) Header Parameter value not allowed');
578
- if (o) {
578
+ if (i) {
579
579
  if (typeof e.payload != "string")
580
580
  throw new u("JWS Payload must be a string");
581
581
  } else if (typeof e.payload != "string" && !(e.payload instanceof Uint8Array))
582
582
  throw new u("JWS Payload must be a string or an Uint8Array instance");
583
583
  let p = !1;
584
- typeof t == "function" && (t = await t(n, e), p = !0), _e(c, t, "verify");
584
+ typeof t == "function" && (t = await t(n, e), p = !0), ve(c, t, "verify");
585
585
  const g = oe(T.encode(e.protected ?? ""), T.encode("."), typeof e.payload == "string" ? T.encode(e.payload) : e.payload);
586
586
  let f;
587
587
  try {
@@ -592,7 +592,7 @@ async function Oe(e, t, r) {
592
592
  if (!await Ke(c, t, f, g))
593
593
  throw new se();
594
594
  let y;
595
- if (o)
595
+ if (i)
596
596
  try {
597
597
  y = b(e.payload);
598
598
  } catch {
@@ -605,10 +605,10 @@ async function Oe(e, t, r) {
605
605
  async function xe(e, t, r) {
606
606
  if (e instanceof Uint8Array && (e = C.decode(e)), typeof e != "string")
607
607
  throw new u("Compact JWS must be a string or Uint8Array");
608
- const { 0: n, 1: a, 2: i, length: o } = e.split(".");
609
- if (o !== 3)
608
+ const { 0: n, 1: a, 2: o, length: i } = e.split(".");
609
+ if (i !== 3)
610
610
  throw new u("Invalid Compact JWS");
611
- const c = await Oe({ payload: a, protected: n, signature: i }, t, r), s = { payload: c.payload, protectedHeader: c.protectedHeader };
611
+ const c = await Oe({ payload: a, protected: n, signature: o }, t, r), s = { payload: c.payload, protectedHeader: c.protectedHeader };
612
612
  return typeof t == "function" ? { ...s, key: c.key } : s;
613
613
  }
614
614
  const We = (e) => Math.floor(e.getTime() / 1e3), ee = 60, te = ee * 60, N = te * 24, Je = N * 7, De = N * 365.25, He = /^(\+|\-)? ?(\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) => {
@@ -665,12 +665,12 @@ const We = (e) => Math.floor(e.getTime() / 1e3), ee = 60, te = ee * 60, N = te *
665
665
  const { typ: a } = r;
666
666
  if (a && (typeof e.typ != "string" || B(e.typ) !== B(a)))
667
667
  throw new h('unexpected "typ" JWT header value', n, "typ", "check_failed");
668
- const { requiredClaims: i = [], issuer: o, subject: c, audience: s, maxTokenAge: p } = r, g = [...i];
669
- p !== void 0 && g.push("iat"), s !== void 0 && g.push("aud"), c !== void 0 && g.push("sub"), o !== void 0 && g.push("iss");
668
+ const { requiredClaims: o = [], issuer: i, subject: c, audience: s, maxTokenAge: p } = r, g = [...o];
669
+ p !== void 0 && g.push("iat"), s !== void 0 && g.push("aud"), c !== void 0 && g.push("sub"), i !== void 0 && g.push("iss");
670
670
  for (const l of new Set(g.reverse()))
671
671
  if (!(l in n))
672
672
  throw new h(`missing required "${l}" claim`, n, l, "missing");
673
- if (o && !(Array.isArray(o) ? o : [o]).includes(n.iss))
673
+ if (i && !(Array.isArray(i) ? i : [i]).includes(n.iss))
674
674
  throw new h('unexpected "iss" claim value', n, "iss", "check_failed");
675
675
  if (c && n.sub !== c)
676
676
  throw new h('unexpected "sub" claim value', n, "sub", "check_failed");
@@ -715,12 +715,12 @@ const We = (e) => Math.floor(e.getTime() / 1e3), ee = 60, te = ee * 60, N = te *
715
715
  return n;
716
716
  };
717
717
  async function $e(e, t, r) {
718
- var o;
718
+ var i;
719
719
  const n = await xe(e, t, r);
720
- if ((o = n.protectedHeader.crit) != null && o.includes("b64") && n.protectedHeader.b64 === !1)
720
+ if ((i = n.protectedHeader.crit) != null && i.includes("b64") && n.protectedHeader.b64 === !1)
721
721
  throw new S("JWTs MUST NOT use unencoded payload");
722
- const i = { payload: Ue(n.protectedHeader, n.payload, r), protectedHeader: n.protectedHeader };
723
- return typeof t == "function" ? { ...i, key: n.key } : i;
722
+ const o = { payload: Ue(n.protectedHeader, n.payload, r), protectedHeader: n.protectedHeader };
723
+ return typeof t == "function" ? { ...o, key: n.key } : o;
724
724
  }
725
725
  const Le = b;
726
726
  function ke(e) {
@@ -771,11 +771,11 @@ for (var H = 0; H < 256; ++H)
771
771
  function Be(e, t = 0) {
772
772
  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();
773
773
  }
774
- var v, Fe = new Uint8Array(16);
774
+ var _, Fe = new Uint8Array(16);
775
775
  function Ve() {
776
- if (!v && (v = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !v))
776
+ if (!_ && (_ = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !_))
777
777
  throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
778
- return v(Fe);
778
+ return _(Fe);
779
779
  }
780
780
  var Ye = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
781
781
  const F = {
@@ -833,13 +833,14 @@ const ze = /^Bearer (.+)$/i, Xe = (e) => {
833
833
  const n = Xe(e), a = Qe(e, r);
834
834
  return Ze(t) || a || n || "";
835
835
  }, ct = async (e, t) => {
836
- var n, a;
836
+ var a;
837
837
  const r = await Me(e);
838
- if ((a = r && ((n = r == null ? void 0 : r.payload) == null ? void 0 : n[I.SCOPES_KEY])) != null && a.length) {
839
- const i = r.payload[I.SCOPES_KEY];
840
- return t.every((o) => i.includes(o));
841
- }
842
- return !1;
838
+ if (!r || !Array.isArray((a = r.payload) == null ? void 0 : a[I.SCOPES_KEY]))
839
+ return !1;
840
+ const n = r.payload[I.SCOPES_KEY];
841
+ return Array.isArray(t) ? t.every((o) => n.includes(o)) : Object.keys(t).some(
842
+ (o) => t[o].every((i) => n.includes(i))
843
+ );
843
844
  };
844
845
  export {
845
846
  rt as API_TYPE,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@versini/auth-common",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "license": "MIT",
5
5
  "author": "Arno Versini",
6
6
  "publishConfig": {
@@ -36,5 +36,5 @@
36
36
  "jose": "5.6.3",
37
37
  "uuid": "10.0.0"
38
38
  },
39
- "gitHead": "57d681a2201591a0623cbbef9dc2edc65f2e3cdc"
39
+ "gitHead": "8df31ef170a75c2983d7ac821fe0371641139815"
40
40
  }