@versini/auth-common 2.6.0 → 2.7.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.d.ts CHANGED
@@ -4,6 +4,7 @@ declare const AUTH_TYPES: {
4
4
  ID_TOKEN: string;
5
5
  ACCESS_TOKEN: string;
6
6
  ID_AND_ACCESS_TOKEN: string;
7
+ CODE: string;
7
8
  };
8
9
  declare const HEADERS: {
9
10
  CLIENT_ID: string;
@@ -20,6 +21,38 @@ declare const TOKEN_EXPIRATION: {
20
21
  ACCESS: string;
21
22
  ID: string;
22
23
  };
23
- declare const verifyAndExtractToken: (token: string, audience: string) => Promise<jose.JWTVerifyResult<jose.JWTPayload> | undefined>;
24
+ declare const API_TYPE: {
25
+ AUTHENTICATE: string;
26
+ CODE: string;
27
+ LOGOUT: string;
28
+ };
29
+
30
+ declare const verifyAndExtractToken: (token: string) => Promise<jose.JWTVerifyResult<jose.JWTPayload> | undefined>;
31
+
32
+ /**
33
+ * Generate a PKCE code challenge from a code verifier.
34
+ *
35
+ * @param code_verifier
36
+ * @returns The base64 url encoded code challenge.
37
+ */
38
+ declare function generateCodeChallenge(code_verifier: string): Promise<string>;
39
+ /**
40
+ * Generate a PKCE challenge pair.
41
+ *
42
+ * @param length Length of the verifier (between 43-128). Defaults to 43.
43
+ * @returns PKCE challenge pair.
44
+ */
45
+ declare function pkceChallengePair(length?: number): Promise<{
46
+ code_verifier: string;
47
+ code_challenge: string;
48
+ }>;
49
+ /**
50
+ * Verify that a code_verifier produces the expected code challenge.
51
+ *
52
+ * @param code_verifier
53
+ * @param expectedChallenge The code challenge to verify.
54
+ * @returns True if challenges are equal. False otherwise.
55
+ */
56
+ declare function verifyChallenge(code_verifier: string, expectedChallenge: string): Promise<boolean>;
24
57
 
25
- export { AUTH_TYPES, HEADERS, JWT, JWT_PUBLIC_KEY, TOKEN_EXPIRATION, verifyAndExtractToken };
58
+ export { API_TYPE, AUTH_TYPES, HEADERS, JWT, JWT_PUBLIC_KEY, TOKEN_EXPIRATION, generateCodeChallenge, pkceChallengePair, verifyAndExtractToken, verifyChallenge };
package/dist/index.js CHANGED
@@ -1,39 +1,67 @@
1
1
  /*!
2
- @versini/auth-common v2.6.0
2
+ @versini/auth-common v2.7.1
3
3
  © 2024 gizmette.com
4
4
  */
5
5
  try {
6
6
  window.__VERSINI_AUTH_COMMON__ || (window.__VERSINI_AUTH_COMMON__ = {
7
- version: "2.6.0",
8
- buildTime: "06/26/2024 08:40 AM EDT",
7
+ version: "2.7.1",
8
+ buildTime: "06/27/2024 02:22 PM EDT",
9
9
  homepage: "https://github.com/aversini/auth-client",
10
10
  license: "MIT"
11
11
  });
12
12
  } catch {
13
13
  }
14
- const P = crypto, D = (e) => e instanceof CryptoKey, A = new TextEncoder(), g = new TextDecoder();
15
- function V(...e) {
14
+ const Ke = {
15
+ ID_TOKEN: "id_token",
16
+ ACCESS_TOKEN: "token",
17
+ ID_AND_ACCESS_TOKEN: "id_token token",
18
+ CODE: "code"
19
+ }, De = {
20
+ CLIENT_ID: "X-Auth-ClientId"
21
+ }, K = {
22
+ ALG: "RS256",
23
+ USER_ID_KEY: "_id",
24
+ TOKEN_ID_KEY: "__raw",
25
+ NONCE_KEY: "_nonce",
26
+ ISSUER: "gizmette.com"
27
+ }, X = `-----BEGIN PUBLIC KEY-----
28
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsF6i3Jd9fY/3COqCw/m7
29
+ w5PKyTYLGAI2I6SIIdpe6i6DOCbEkmDz7LdVsBqwNtVi8gvWYIj+8ol6rU3qu1v5
30
+ i1Jd45GSK4kzkVdgCmQZbM5ak0KI99q5wsrAIzUd+LRJ2HRvWtr5IYdsIiXaQjle
31
+ aMwPFOIcJH+rKfFgNcHLcaS5syp7zU1ANwZ+trgR+DifBr8TLVkBynmNeTyhDm2+
32
+ l0haqjMk0UoNPPE8iYBWUHQJJE1Dqstj65d6Eh5g64Pao25y4cmYJbKjiblIGEkE
33
+ sjqybA9mARAqh9k/eiIopecWSiffNQTwVQVd2I9ZH3BalhEXHlqFgrjz51kFqg81
34
+ awIDAQAB
35
+ -----END PUBLIC KEY-----`, Ne = {
36
+ ACCESS: "5m",
37
+ ID: "90d"
38
+ }, He = {
39
+ AUTHENTICATE: "authenticate",
40
+ CODE: "code",
41
+ LOGOUT: "logout"
42
+ }, O = crypto, V = (e) => e instanceof CryptoKey, g = new TextEncoder(), C = new TextDecoder();
43
+ function j(...e) {
16
44
  const t = e.reduce((o, { length: i }) => o + i, 0), n = new Uint8Array(t);
17
45
  let r = 0;
18
46
  for (const o of e)
19
47
  n.set(o, r), r += o.length;
20
48
  return n;
21
49
  }
22
- const F = (e) => {
50
+ const Z = (e) => {
23
51
  const t = atob(e), n = new Uint8Array(t.length);
24
52
  for (let r = 0; r < t.length; r++)
25
53
  n[r] = t.charCodeAt(r);
26
54
  return n;
27
- }, C = (e) => {
55
+ }, R = (e) => {
28
56
  let t = e;
29
- t instanceof Uint8Array && (t = g.decode(t)), t = t.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
57
+ t instanceof Uint8Array && (t = C.decode(t)), t = t.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
30
58
  try {
31
- return F(t);
59
+ return Z(t);
32
60
  } catch {
33
61
  throw new TypeError("The input to be decoded is not correctly encoded.");
34
62
  }
35
63
  };
36
- class w extends Error {
64
+ class b extends Error {
37
65
  static get code() {
38
66
  return "ERR_JOSE_GENERIC";
39
67
  }
@@ -42,7 +70,7 @@ class w extends Error {
42
70
  super(t), this.code = "ERR_JOSE_GENERIC", this.name = this.constructor.name, (n = Error.captureStackTrace) == null || n.call(Error, this, this.constructor);
43
71
  }
44
72
  }
45
- class h extends w {
73
+ class h extends b {
46
74
  static get code() {
47
75
  return "ERR_JWT_CLAIM_VALIDATION_FAILED";
48
76
  }
@@ -50,7 +78,7 @@ class h extends w {
50
78
  super(t), this.code = "ERR_JWT_CLAIM_VALIDATION_FAILED", this.claim = r, this.reason = o, this.payload = n;
51
79
  }
52
80
  }
53
- class O extends w {
81
+ class D extends b {
54
82
  static get code() {
55
83
  return "ERR_JWT_EXPIRED";
56
84
  }
@@ -58,7 +86,7 @@ class O extends w {
58
86
  super(t), this.code = "ERR_JWT_EXPIRED", this.claim = r, this.reason = o, this.payload = n;
59
87
  }
60
88
  }
61
- class G extends w {
89
+ class ee extends b {
62
90
  constructor() {
63
91
  super(...arguments), this.code = "ERR_JOSE_ALG_NOT_ALLOWED";
64
92
  }
@@ -66,7 +94,7 @@ class G extends w {
66
94
  return "ERR_JOSE_ALG_NOT_ALLOWED";
67
95
  }
68
96
  }
69
- class _ extends w {
97
+ class _ extends b {
70
98
  constructor() {
71
99
  super(...arguments), this.code = "ERR_JOSE_NOT_SUPPORTED";
72
100
  }
@@ -74,7 +102,7 @@ class _ extends w {
74
102
  return "ERR_JOSE_NOT_SUPPORTED";
75
103
  }
76
104
  }
77
- class d extends w {
105
+ class u extends b {
78
106
  constructor() {
79
107
  super(...arguments), this.code = "ERR_JWS_INVALID";
80
108
  }
@@ -82,7 +110,7 @@ class d extends w {
82
110
  return "ERR_JWS_INVALID";
83
111
  }
84
112
  }
85
- class k extends w {
113
+ class B extends b {
86
114
  constructor() {
87
115
  super(...arguments), this.code = "ERR_JWT_INVALID";
88
116
  }
@@ -90,7 +118,7 @@ class k extends w {
90
118
  return "ERR_JWT_INVALID";
91
119
  }
92
120
  }
93
- class Y extends w {
121
+ class te extends b {
94
122
  constructor() {
95
123
  super(...arguments), this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED", this.message = "signature verification failed";
96
124
  }
@@ -98,16 +126,16 @@ class Y extends w {
98
126
  return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
99
127
  }
100
128
  }
101
- function p(e, t = "algorithm.name") {
129
+ function m(e, t = "algorithm.name") {
102
130
  return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);
103
131
  }
104
- function b(e, t) {
132
+ function A(e, t) {
105
133
  return e.name === t;
106
134
  }
107
- function T(e) {
135
+ function v(e) {
108
136
  return parseInt(e.name.slice(4), 10);
109
137
  }
110
- function q(e) {
138
+ function re(e) {
111
139
  switch (e) {
112
140
  case "ES256":
113
141
  return "P-256";
@@ -119,7 +147,7 @@ function q(e) {
119
147
  throw new Error("unreachable");
120
148
  }
121
149
  }
122
- function z(e, t) {
150
+ function ne(e, t) {
123
151
  if (t.length && !t.some((n) => e.usages.includes(n))) {
124
152
  let n = "CryptoKey does not support this operation, its usages must include ";
125
153
  if (t.length > 2) {
@@ -130,59 +158,59 @@ function z(e, t) {
130
158
  throw new TypeError(n);
131
159
  }
132
160
  }
133
- function Q(e, t, ...n) {
161
+ function oe(e, t, ...n) {
134
162
  switch (t) {
135
163
  case "HS256":
136
164
  case "HS384":
137
165
  case "HS512": {
138
- if (!b(e.algorithm, "HMAC"))
139
- throw p("HMAC");
166
+ if (!A(e.algorithm, "HMAC"))
167
+ throw m("HMAC");
140
168
  const r = parseInt(t.slice(2), 10);
141
- if (T(e.algorithm.hash) !== r)
142
- throw p(`SHA-${r}`, "algorithm.hash");
169
+ if (v(e.algorithm.hash) !== r)
170
+ throw m(`SHA-${r}`, "algorithm.hash");
143
171
  break;
144
172
  }
145
173
  case "RS256":
146
174
  case "RS384":
147
175
  case "RS512": {
148
- if (!b(e.algorithm, "RSASSA-PKCS1-v1_5"))
149
- throw p("RSASSA-PKCS1-v1_5");
176
+ if (!A(e.algorithm, "RSASSA-PKCS1-v1_5"))
177
+ throw m("RSASSA-PKCS1-v1_5");
150
178
  const r = parseInt(t.slice(2), 10);
151
- if (T(e.algorithm.hash) !== r)
152
- throw p(`SHA-${r}`, "algorithm.hash");
179
+ if (v(e.algorithm.hash) !== r)
180
+ throw m(`SHA-${r}`, "algorithm.hash");
153
181
  break;
154
182
  }
155
183
  case "PS256":
156
184
  case "PS384":
157
185
  case "PS512": {
158
- if (!b(e.algorithm, "RSA-PSS"))
159
- throw p("RSA-PSS");
186
+ if (!A(e.algorithm, "RSA-PSS"))
187
+ throw m("RSA-PSS");
160
188
  const r = parseInt(t.slice(2), 10);
161
- if (T(e.algorithm.hash) !== r)
162
- throw p(`SHA-${r}`, "algorithm.hash");
189
+ if (v(e.algorithm.hash) !== r)
190
+ throw m(`SHA-${r}`, "algorithm.hash");
163
191
  break;
164
192
  }
165
193
  case "EdDSA": {
166
194
  if (e.algorithm.name !== "Ed25519" && e.algorithm.name !== "Ed448")
167
- throw p("Ed25519 or Ed448");
195
+ throw m("Ed25519 or Ed448");
168
196
  break;
169
197
  }
170
198
  case "ES256":
171
199
  case "ES384":
172
200
  case "ES512": {
173
- if (!b(e.algorithm, "ECDSA"))
174
- throw p("ECDSA");
175
- const r = q(t);
201
+ if (!A(e.algorithm, "ECDSA"))
202
+ throw m("ECDSA");
203
+ const r = re(t);
176
204
  if (e.algorithm.namedCurve !== r)
177
- throw p(r, "algorithm.namedCurve");
205
+ throw m(r, "algorithm.namedCurve");
178
206
  break;
179
207
  }
180
208
  default:
181
209
  throw new TypeError("CryptoKey does not support this operation");
182
210
  }
183
- z(e, n);
211
+ ne(e, n);
184
212
  }
185
- function L(e, t, ...n) {
213
+ function F(e, t, ...n) {
186
214
  var r;
187
215
  if (n.length > 2) {
188
216
  const o = n.pop();
@@ -191,11 +219,11 @@ function L(e, t, ...n) {
191
219
  n.length === 2 ? e += `one of type ${n[0]} or ${n[1]}.` : e += `of type ${n[0]}.`;
192
220
  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;
193
221
  }
194
- const J = (e, ...t) => L("Key must be ", e, ...t);
195
- function U(e, t, ...n) {
196
- return L(`Key for the ${e} algorithm must be `, t, ...n);
222
+ const N = (e, ...t) => F("Key must be ", e, ...t);
223
+ function G(e, t, ...n) {
224
+ return F(`Key for the ${e} algorithm must be `, t, ...n);
197
225
  }
198
- const $ = (e) => D(e), S = ["CryptoKey"], X = (...e) => {
226
+ const Y = (e) => V(e), w = ["CryptoKey"], ae = (...e) => {
199
227
  const t = e.filter(Boolean);
200
228
  if (t.length === 0 || t.length === 1)
201
229
  return !0;
@@ -214,11 +242,11 @@ const $ = (e) => D(e), S = ["CryptoKey"], X = (...e) => {
214
242
  }
215
243
  return !0;
216
244
  };
217
- function j(e) {
245
+ function ie(e) {
218
246
  return typeof e == "object" && e !== null;
219
247
  }
220
- function R(e) {
221
- if (!j(e) || Object.prototype.toString.call(e) !== "[object Object]")
248
+ function x(e) {
249
+ if (!ie(e) || Object.prototype.toString.call(e) !== "[object Object]")
222
250
  return !1;
223
251
  if (Object.getPrototypeOf(e) === null)
224
252
  return !0;
@@ -227,39 +255,39 @@ function R(e) {
227
255
  t = Object.getPrototypeOf(t);
228
256
  return Object.getPrototypeOf(e) === t;
229
257
  }
230
- const Z = (e, t) => {
258
+ const ce = (e, t) => {
231
259
  if (e.startsWith("RS") || e.startsWith("PS")) {
232
260
  const { modulusLength: n } = t.algorithm;
233
261
  if (typeof n != "number" || n < 2048)
234
262
  throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`);
235
263
  }
236
- }, y = (e, t, n = 0) => {
264
+ }, S = (e, t, n = 0) => {
237
265
  n === 0 && (t.unshift(t.length), t.unshift(6));
238
266
  const r = e.indexOf(t[0], n);
239
267
  if (r === -1)
240
268
  return !1;
241
269
  const o = e.subarray(r, r + t.length);
242
- return o.length !== t.length ? !1 : o.every((i, a) => i === t[a]) || y(e, t, r + 1);
243
- }, K = (e) => {
270
+ return o.length !== t.length ? !1 : o.every((i, a) => i === t[a]) || S(e, t, r + 1);
271
+ }, H = (e) => {
244
272
  switch (!0) {
245
- case y(e, [42, 134, 72, 206, 61, 3, 1, 7]):
273
+ case S(e, [42, 134, 72, 206, 61, 3, 1, 7]):
246
274
  return "P-256";
247
- case y(e, [43, 129, 4, 0, 34]):
275
+ case S(e, [43, 129, 4, 0, 34]):
248
276
  return "P-384";
249
- case y(e, [43, 129, 4, 0, 35]):
277
+ case S(e, [43, 129, 4, 0, 35]):
250
278
  return "P-521";
251
- case y(e, [43, 101, 110]):
279
+ case S(e, [43, 101, 110]):
252
280
  return "X25519";
253
- case y(e, [43, 101, 111]):
281
+ case S(e, [43, 101, 111]):
254
282
  return "X448";
255
- case y(e, [43, 101, 112]):
283
+ case S(e, [43, 101, 112]):
256
284
  return "Ed25519";
257
- case y(e, [43, 101, 113]):
285
+ case S(e, [43, 101, 113]):
258
286
  return "Ed448";
259
287
  default:
260
288
  throw new _("Invalid or unsupported EC Key Curve or OKP Key Sub Type");
261
289
  }
262
- }, ee = async (e, t, n, r, o) => {
290
+ }, se = async (e, t, n, r, o) => {
263
291
  let i, a;
264
292
  const c = new Uint8Array(atob(n.replace(e, "")).split("").map((s) => s.charCodeAt(0)));
265
293
  switch (r) {
@@ -295,43 +323,43 @@ const Z = (e, t) => {
295
323
  case "ECDH-ES+A128KW":
296
324
  case "ECDH-ES+A192KW":
297
325
  case "ECDH-ES+A256KW": {
298
- const s = K(c);
326
+ const s = H(c);
299
327
  i = s.startsWith("P-") ? { name: "ECDH", namedCurve: s } : { name: s }, a = [];
300
328
  break;
301
329
  }
302
330
  case "EdDSA":
303
- i = { name: K(c) }, a = ["verify"];
331
+ i = { name: H(c) }, a = ["verify"];
304
332
  break;
305
333
  default:
306
334
  throw new _('Invalid or unsupported "alg" (Algorithm) value');
307
335
  }
308
- return P.subtle.importKey(t, c, i, !1, a);
309
- }, te = (e, t, n) => ee(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", e, t);
310
- async function re(e, t, n) {
336
+ return O.subtle.importKey(t, c, i, !1, a);
337
+ }, de = (e, t, n) => se(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", e, t);
338
+ async function ue(e, t, n) {
311
339
  if (e.indexOf("-----BEGIN PUBLIC KEY-----") !== 0)
312
340
  throw new TypeError('"spki" must be SPKI formatted string');
313
- return te(e, t);
341
+ return de(e, t);
314
342
  }
315
- const ne = (e, t) => {
343
+ const le = (e, t) => {
316
344
  if (!(t instanceof Uint8Array)) {
317
- if (!$(t))
318
- throw new TypeError(U(e, t, ...S, "Uint8Array"));
345
+ if (!Y(t))
346
+ throw new TypeError(G(e, t, ...w, "Uint8Array"));
319
347
  if (t.type !== "secret")
320
- throw new TypeError(`${S.join(" or ")} instances for symmetric algorithms must be of type "secret"`);
348
+ throw new TypeError(`${w.join(" or ")} instances for symmetric algorithms must be of type "secret"`);
321
349
  }
322
- }, oe = (e, t, n) => {
323
- if (!$(t))
324
- throw new TypeError(U(e, t, ...S));
350
+ }, fe = (e, t, n) => {
351
+ if (!Y(t))
352
+ throw new TypeError(G(e, t, ...w));
325
353
  if (t.type === "secret")
326
- throw new TypeError(`${S.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);
354
+ throw new TypeError(`${w.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);
327
355
  if (t.algorithm && n === "verify" && t.type === "private")
328
- throw new TypeError(`${S.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);
356
+ throw new TypeError(`${w.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);
329
357
  if (t.algorithm && n === "encrypt" && t.type === "private")
330
- throw new TypeError(`${S.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`);
331
- }, ae = (e, t, n) => {
332
- e.startsWith("HS") || e === "dir" || e.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(e) ? ne(e, t) : oe(e, t, n);
358
+ throw new TypeError(`${w.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`);
359
+ }, he = (e, t, n) => {
360
+ e.startsWith("HS") || e === "dir" || e.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(e) ? le(e, t) : fe(e, t, n);
333
361
  };
334
- function ie(e, t, n, r, o) {
362
+ function pe(e, t, n, r, o) {
335
363
  if (o.crit !== void 0 && (r == null ? void 0 : r.crit) === void 0)
336
364
  throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');
337
365
  if (!r || r.crit === void 0)
@@ -350,13 +378,13 @@ function ie(e, t, n, r, o) {
350
378
  }
351
379
  return new Set(r.crit);
352
380
  }
353
- const ce = (e, t) => {
381
+ const me = (e, t) => {
354
382
  if (t !== void 0 && (!Array.isArray(t) || t.some((n) => typeof n != "string")))
355
383
  throw new TypeError(`"${e}" option must be an array of strings`);
356
384
  if (t)
357
385
  return new Set(t);
358
386
  };
359
- function se(e, t) {
387
+ function ye(e, t) {
360
388
  const n = `SHA-${e.slice(-3)}`;
361
389
  switch (e) {
362
390
  case "HS256":
@@ -381,101 +409,101 @@ function se(e, t) {
381
409
  throw new _(`alg ${e} is not supported either by JOSE or your javascript runtime`);
382
410
  }
383
411
  }
384
- function de(e, t, n) {
385
- if (D(t))
386
- return Q(t, e, n), t;
412
+ function Se(e, t, n) {
413
+ if (V(t))
414
+ return oe(t, e, n), t;
387
415
  if (t instanceof Uint8Array) {
388
416
  if (!e.startsWith("HS"))
389
- throw new TypeError(J(t, ...S));
390
- return P.subtle.importKey("raw", t, { hash: `SHA-${e.slice(-3)}`, name: "HMAC" }, !1, [n]);
417
+ throw new TypeError(N(t, ...w));
418
+ return O.subtle.importKey("raw", t, { hash: `SHA-${e.slice(-3)}`, name: "HMAC" }, !1, [n]);
391
419
  }
392
- throw new TypeError(J(t, ...S, "Uint8Array"));
420
+ throw new TypeError(N(t, ...w, "Uint8Array"));
393
421
  }
394
- const ue = async (e, t, n, r) => {
395
- const o = await de(e, t, "verify");
396
- Z(e, o);
397
- const i = se(e, o.algorithm);
422
+ const we = async (e, t, n, r) => {
423
+ const o = await Se(e, t, "verify");
424
+ ce(e, o);
425
+ const i = ye(e, o.algorithm);
398
426
  try {
399
- return await P.subtle.verify(i, o, n, r);
427
+ return await O.subtle.verify(i, o, n, r);
400
428
  } catch {
401
429
  return !1;
402
430
  }
403
431
  };
404
- async function fe(e, t, n) {
405
- if (!R(e))
406
- throw new d("Flattened JWS must be an object");
432
+ async function Ee(e, t, n) {
433
+ if (!x(e))
434
+ throw new u("Flattened JWS must be an object");
407
435
  if (e.protected === void 0 && e.header === void 0)
408
- throw new d('Flattened JWS must have either of the "protected" or "header" members');
436
+ throw new u('Flattened JWS must have either of the "protected" or "header" members');
409
437
  if (e.protected !== void 0 && typeof e.protected != "string")
410
- throw new d("JWS Protected Header incorrect type");
438
+ throw new u("JWS Protected Header incorrect type");
411
439
  if (e.payload === void 0)
412
- throw new d("JWS Payload missing");
440
+ throw new u("JWS Payload missing");
413
441
  if (typeof e.signature != "string")
414
- throw new d("JWS Signature missing or incorrect type");
415
- if (e.header !== void 0 && !R(e.header))
416
- throw new d("JWS Unprotected Header incorrect type");
442
+ throw new u("JWS Signature missing or incorrect type");
443
+ if (e.header !== void 0 && !x(e.header))
444
+ throw new u("JWS Unprotected Header incorrect type");
417
445
  let r = {};
418
446
  if (e.protected)
419
447
  try {
420
- const I = C(e.protected);
421
- r = JSON.parse(g.decode(I));
448
+ const T = R(e.protected);
449
+ r = JSON.parse(C.decode(T));
422
450
  } catch {
423
- throw new d("JWS Protected Header is invalid");
451
+ throw new u("JWS Protected Header is invalid");
424
452
  }
425
- if (!X(r, e.header))
426
- throw new d("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
453
+ if (!ae(r, e.header))
454
+ throw new u("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
427
455
  const o = {
428
456
  ...r,
429
457
  ...e.header
430
- }, i = ie(d, /* @__PURE__ */ new Map([["b64", !0]]), n == null ? void 0 : n.crit, r, o);
458
+ }, i = pe(u, /* @__PURE__ */ new Map([["b64", !0]]), n == null ? void 0 : n.crit, r, o);
431
459
  let a = !0;
432
460
  if (i.has("b64") && (a = r.b64, typeof a != "boolean"))
433
- throw new d('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
461
+ throw new u('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
434
462
  const { alg: c } = o;
435
463
  if (typeof c != "string" || !c)
436
- throw new d('JWS "alg" (Algorithm) Header Parameter missing or invalid');
437
- const s = n && ce("algorithms", n.algorithms);
464
+ throw new u('JWS "alg" (Algorithm) Header Parameter missing or invalid');
465
+ const s = n && me("algorithms", n.algorithms);
438
466
  if (s && !s.has(c))
439
- throw new G('"alg" (Algorithm) Header Parameter value not allowed');
467
+ throw new ee('"alg" (Algorithm) Header Parameter value not allowed');
440
468
  if (a) {
441
469
  if (typeof e.payload != "string")
442
- throw new d("JWS Payload must be a string");
470
+ throw new u("JWS Payload must be a string");
443
471
  } else if (typeof e.payload != "string" && !(e.payload instanceof Uint8Array))
444
- throw new d("JWS Payload must be a string or an Uint8Array instance");
445
- let l = !1;
446
- typeof t == "function" && (t = await t(r, e), l = !0), ae(c, t, "verify");
447
- const E = V(A.encode(e.protected ?? ""), A.encode("."), typeof e.payload == "string" ? A.encode(e.payload) : e.payload);
472
+ throw new u("JWS Payload must be a string or an Uint8Array instance");
473
+ let p = !1;
474
+ typeof t == "function" && (t = await t(r, e), p = !0), he(c, t, "verify");
475
+ const E = j(g.encode(e.protected ?? ""), g.encode("."), typeof e.payload == "string" ? g.encode(e.payload) : e.payload);
448
476
  let f;
449
477
  try {
450
- f = C(e.signature);
478
+ f = R(e.signature);
451
479
  } catch {
452
- throw new d("Failed to base64url decode the signature");
480
+ throw new u("Failed to base64url decode the signature");
453
481
  }
454
- if (!await ue(c, t, f, E))
455
- throw new Y();
456
- let m;
482
+ if (!await we(c, t, f, E))
483
+ throw new te();
484
+ let y;
457
485
  if (a)
458
486
  try {
459
- m = C(e.payload);
487
+ y = R(e.payload);
460
488
  } catch {
461
- throw new d("Failed to base64url decode the payload");
489
+ throw new u("Failed to base64url decode the payload");
462
490
  }
463
491
  else
464
- typeof e.payload == "string" ? m = A.encode(e.payload) : m = e.payload;
465
- const u = { payload: m };
466
- return e.protected !== void 0 && (u.protectedHeader = r), e.header !== void 0 && (u.unprotectedHeader = e.header), l ? { ...u, key: t } : u;
492
+ typeof e.payload == "string" ? y = g.encode(e.payload) : y = e.payload;
493
+ const l = { payload: y };
494
+ return e.protected !== void 0 && (l.protectedHeader = r), e.header !== void 0 && (l.unprotectedHeader = e.header), p ? { ...l, key: t } : l;
467
495
  }
468
- async function he(e, t, n) {
469
- if (e instanceof Uint8Array && (e = g.decode(e)), typeof e != "string")
470
- throw new d("Compact JWS must be a string or Uint8Array");
496
+ async function be(e, t, n) {
497
+ if (e instanceof Uint8Array && (e = C.decode(e)), typeof e != "string")
498
+ throw new u("Compact JWS must be a string or Uint8Array");
471
499
  const { 0: r, 1: o, 2: i, length: a } = e.split(".");
472
500
  if (a !== 3)
473
- throw new d("Invalid Compact JWS");
474
- const c = await fe({ payload: o, protected: r, signature: i }, t, n), s = { payload: c.payload, protectedHeader: c.protectedHeader };
501
+ throw new u("Invalid Compact JWS");
502
+ const c = await Ee({ payload: o, protected: r, signature: i }, t, n), s = { payload: c.payload, protectedHeader: c.protectedHeader };
475
503
  return typeof t == "function" ? { ...s, key: c.key } : s;
476
504
  }
477
- const le = (e) => Math.floor(e.getTime() / 1e3), M = 60, B = M * 60, v = B * 24, pe = v * 7, me = v * 365.25, ye = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, N = (e) => {
478
- const t = ye.exec(e);
505
+ const ge = (e) => Math.floor(e.getTime() / 1e3), q = 60, z = q * 60, J = z * 24, Ae = J * 7, Ie = J * 365.25, Ce = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, W = (e) => {
506
+ const t = Ce.exec(e);
479
507
  if (!t || t[4] && t[1])
480
508
  throw new TypeError("Invalid time period format");
481
509
  const n = parseFloat(t[2]), r = t[3].toLowerCase();
@@ -493,56 +521,56 @@ const le = (e) => Math.floor(e.getTime() / 1e3), M = 60, B = M * 60, v = B * 24,
493
521
  case "min":
494
522
  case "mins":
495
523
  case "m":
496
- o = Math.round(n * M);
524
+ o = Math.round(n * q);
497
525
  break;
498
526
  case "hour":
499
527
  case "hours":
500
528
  case "hr":
501
529
  case "hrs":
502
530
  case "h":
503
- o = Math.round(n * B);
531
+ o = Math.round(n * z);
504
532
  break;
505
533
  case "day":
506
534
  case "days":
507
535
  case "d":
508
- o = Math.round(n * v);
536
+ o = Math.round(n * J);
509
537
  break;
510
538
  case "week":
511
539
  case "weeks":
512
540
  case "w":
513
- o = Math.round(n * pe);
541
+ o = Math.round(n * Ae);
514
542
  break;
515
543
  default:
516
- o = Math.round(n * me);
544
+ o = Math.round(n * Ie);
517
545
  break;
518
546
  }
519
547
  return t[1] === "-" || t[4] === "ago" ? -o : o;
520
- }, W = (e) => e.toLowerCase().replace(/^application\//, ""), Se = (e, t) => typeof e == "string" ? t.includes(e) : Array.isArray(e) ? t.some(Set.prototype.has.bind(new Set(e))) : !1, Ee = (e, t, n = {}) => {
548
+ }, $ = (e) => e.toLowerCase().replace(/^application\//, ""), _e = (e, t) => typeof e == "string" ? t.includes(e) : Array.isArray(e) ? t.some(Set.prototype.has.bind(new Set(e))) : !1, Te = (e, t, n = {}) => {
521
549
  let r;
522
550
  try {
523
- r = JSON.parse(g.decode(t));
551
+ r = JSON.parse(C.decode(t));
524
552
  } catch {
525
553
  }
526
- if (!R(r))
527
- throw new k("JWT Claims Set must be a top-level JSON object");
554
+ if (!x(r))
555
+ throw new B("JWT Claims Set must be a top-level JSON object");
528
556
  const { typ: o } = n;
529
- if (o && (typeof e.typ != "string" || W(e.typ) !== W(o)))
557
+ if (o && (typeof e.typ != "string" || $(e.typ) !== $(o)))
530
558
  throw new h('unexpected "typ" JWT header value', r, "typ", "check_failed");
531
- const { requiredClaims: i = [], issuer: a, subject: c, audience: s, maxTokenAge: l } = n, E = [...i];
532
- l !== void 0 && E.push("iat"), s !== void 0 && E.push("aud"), c !== void 0 && E.push("sub"), a !== void 0 && E.push("iss");
533
- for (const u of new Set(E.reverse()))
534
- if (!(u in r))
535
- throw new h(`missing required "${u}" claim`, r, u, "missing");
559
+ const { requiredClaims: i = [], issuer: a, subject: c, audience: s, maxTokenAge: p } = n, E = [...i];
560
+ p !== void 0 && E.push("iat"), s !== void 0 && E.push("aud"), c !== void 0 && E.push("sub"), a !== void 0 && E.push("iss");
561
+ for (const l of new Set(E.reverse()))
562
+ if (!(l in r))
563
+ throw new h(`missing required "${l}" claim`, r, l, "missing");
536
564
  if (a && !(Array.isArray(a) ? a : [a]).includes(r.iss))
537
565
  throw new h('unexpected "iss" claim value', r, "iss", "check_failed");
538
566
  if (c && r.sub !== c)
539
567
  throw new h('unexpected "sub" claim value', r, "sub", "check_failed");
540
- if (s && !Se(r.aud, typeof s == "string" ? [s] : s))
568
+ if (s && !_e(r.aud, typeof s == "string" ? [s] : s))
541
569
  throw new h('unexpected "aud" claim value', r, "aud", "check_failed");
542
570
  let f;
543
571
  switch (typeof n.clockTolerance) {
544
572
  case "string":
545
- f = N(n.clockTolerance);
573
+ f = W(n.clockTolerance);
546
574
  break;
547
575
  case "number":
548
576
  f = n.clockTolerance;
@@ -553,77 +581,104 @@ const le = (e) => Math.floor(e.getTime() / 1e3), M = 60, B = M * 60, v = B * 24,
553
581
  default:
554
582
  throw new TypeError("Invalid clockTolerance option type");
555
583
  }
556
- const { currentDate: x } = n, m = le(x || /* @__PURE__ */ new Date());
557
- if ((r.iat !== void 0 || l) && typeof r.iat != "number")
584
+ const { currentDate: U } = n, y = ge(U || /* @__PURE__ */ new Date());
585
+ if ((r.iat !== void 0 || p) && typeof r.iat != "number")
558
586
  throw new h('"iat" claim must be a number', r, "iat", "invalid");
559
587
  if (r.nbf !== void 0) {
560
588
  if (typeof r.nbf != "number")
561
589
  throw new h('"nbf" claim must be a number', r, "nbf", "invalid");
562
- if (r.nbf > m + f)
590
+ if (r.nbf > y + f)
563
591
  throw new h('"nbf" claim timestamp check failed', r, "nbf", "check_failed");
564
592
  }
565
593
  if (r.exp !== void 0) {
566
594
  if (typeof r.exp != "number")
567
595
  throw new h('"exp" claim must be a number', r, "exp", "invalid");
568
- if (r.exp <= m - f)
569
- throw new O('"exp" claim timestamp check failed', r, "exp", "check_failed");
570
- }
571
- if (l) {
572
- const u = m - r.iat, I = typeof l == "number" ? l : N(l);
573
- if (u - f > I)
574
- throw new O('"iat" claim timestamp check failed (too far in the past)', r, "iat", "check_failed");
575
- if (u < 0 - f)
596
+ if (r.exp <= y - f)
597
+ throw new D('"exp" claim timestamp check failed', r, "exp", "check_failed");
598
+ }
599
+ if (p) {
600
+ const l = y - r.iat, T = typeof p == "number" ? p : W(p);
601
+ if (l - f > T)
602
+ throw new D('"iat" claim timestamp check failed (too far in the past)', r, "iat", "check_failed");
603
+ if (l < 0 - f)
576
604
  throw new h('"iat" claim timestamp check failed (it should be in the past)', r, "iat", "check_failed");
577
605
  }
578
606
  return r;
579
607
  };
580
- async function we(e, t, n) {
608
+ async function Re(e, t, n) {
581
609
  var a;
582
- const r = await he(e, t, n);
610
+ const r = await be(e, t, n);
583
611
  if ((a = r.protectedHeader.crit) != null && a.includes("b64") && r.protectedHeader.b64 === !1)
584
- throw new k("JWTs MUST NOT use unencoded payload");
585
- const i = { payload: Ee(r.protectedHeader, r.payload, n), protectedHeader: r.protectedHeader };
612
+ throw new B("JWTs MUST NOT use unencoded payload");
613
+ const i = { payload: Te(r.protectedHeader, r.payload, n), protectedHeader: r.protectedHeader };
586
614
  return typeof t == "function" ? { ...i, key: r.key } : i;
587
615
  }
588
- const be = {
589
- ID_TOKEN: "id_token",
590
- ACCESS_TOKEN: "token",
591
- ID_AND_ACCESS_TOKEN: "id_token token"
592
- }, ge = {
593
- CLIENT_ID: "X-Auth-ClientId"
594
- }, H = {
595
- ALG: "RS256",
596
- USER_ID_KEY: "_id",
597
- TOKEN_ID_KEY: "__raw",
598
- NONCE_KEY: "_nonce",
599
- ISSUER: "gizmette.com"
600
- }, Ae = `-----BEGIN PUBLIC KEY-----
601
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsF6i3Jd9fY/3COqCw/m7
602
- w5PKyTYLGAI2I6SIIdpe6i6DOCbEkmDz7LdVsBqwNtVi8gvWYIj+8ol6rU3qu1v5
603
- i1Jd45GSK4kzkVdgCmQZbM5ak0KI99q5wsrAIzUd+LRJ2HRvWtr5IYdsIiXaQjle
604
- aMwPFOIcJH+rKfFgNcHLcaS5syp7zU1ANwZ+trgR+DifBr8TLVkBynmNeTyhDm2+
605
- l0haqjMk0UoNPPE8iYBWUHQJJE1Dqstj65d6Eh5g64Pao25y4cmYJbKjiblIGEkE
606
- sjqybA9mARAqh9k/eiIopecWSiffNQTwVQVd2I9ZH3BalhEXHlqFgrjz51kFqg81
607
- awIDAQAB
608
- -----END PUBLIC KEY-----`, _e = {
609
- ACCESS: "5m",
610
- ID: "90d"
611
- }, Ie = async (e, t) => {
616
+ const We = async (e) => {
612
617
  try {
613
- const n = H.ALG, o = await re(Ae, n);
614
- return await we(e, o, {
615
- issuer: H.ISSUER,
616
- audience: t
618
+ const t = K.ALG, r = await ue(X, t);
619
+ return await Re(e, r, {
620
+ issuer: K.ISSUER
617
621
  });
618
622
  } catch {
619
623
  return;
620
624
  }
621
625
  };
626
+ var d = [];
627
+ for (var P = 0; P < 256; ++P)
628
+ d.push((P + 256).toString(16).slice(1));
629
+ function ve(e, t = 0) {
630
+ 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();
631
+ }
632
+ var I, Pe = new Uint8Array(16);
633
+ function xe() {
634
+ if (!I && (I = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !I))
635
+ throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
636
+ return I(Pe);
637
+ }
638
+ var Oe = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
639
+ const L = {
640
+ randomUUID: Oe
641
+ };
642
+ function k(e, t, n) {
643
+ if (L.randomUUID && !t && !e)
644
+ return L.randomUUID();
645
+ e = e || {};
646
+ var r = e.random || (e.rng || xe)();
647
+ return r[6] = r[6] & 15 | 64, r[8] = r[8] & 63 | 128, ve(r);
648
+ }
649
+ const M = globalThis.crypto, Je = (e) => `${k()}${k()}`.slice(0, e), Ue = (e) => btoa(
650
+ [...new Uint8Array(e)].map((t) => String.fromCharCode(t)).join("")
651
+ );
652
+ async function Q(e) {
653
+ if (!M.subtle)
654
+ throw new Error(
655
+ "crypto.subtle is available only in secure contexts (HTTPS)."
656
+ );
657
+ const t = new TextEncoder().encode(e), n = await M.subtle.digest("SHA-256", t);
658
+ return Ue(n).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
659
+ }
660
+ async function $e(e) {
661
+ const t = e || 43;
662
+ if (t < 43 || t > 128)
663
+ throw `Expected a length between 43 and 128. Received ${e}.`;
664
+ const n = Je(t), r = await Q(n);
665
+ return {
666
+ code_verifier: n,
667
+ code_challenge: r
668
+ };
669
+ }
670
+ async function Le(e, t) {
671
+ return await Q(e) === t;
672
+ }
622
673
  export {
623
- be as AUTH_TYPES,
624
- ge as HEADERS,
625
- H as JWT,
626
- Ae as JWT_PUBLIC_KEY,
627
- _e as TOKEN_EXPIRATION,
628
- Ie as verifyAndExtractToken
674
+ He as API_TYPE,
675
+ Ke as AUTH_TYPES,
676
+ De as HEADERS,
677
+ K as JWT,
678
+ X as JWT_PUBLIC_KEY,
679
+ Ne as TOKEN_EXPIRATION,
680
+ Q as generateCodeChallenge,
681
+ $e as pkceChallengePair,
682
+ We as verifyAndExtractToken,
683
+ Le as verifyChallenge
629
684
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@versini/auth-common",
3
- "version": "2.6.0",
3
+ "version": "2.7.1",
4
4
  "license": "MIT",
5
5
  "author": "Arno Versini",
6
6
  "publishConfig": {
@@ -27,10 +27,13 @@
27
27
  "dev:types": "tsup --watch src",
28
28
  "dev": "npm-run-all clean --parallel dev:js dev:types",
29
29
  "lint": "biome lint src",
30
- "start": "static-server dist --port 5173"
30
+ "start": "static-server dist --port 5173",
31
+ "test:watch": "vitest",
32
+ "test": "vitest run"
31
33
  },
32
34
  "dependencies": {
33
- "jose": "5.4.1"
35
+ "jose": "5.4.1",
36
+ "uuid": "10.0.0"
34
37
  },
35
- "gitHead": "c88e96be92c0d2dcf576d1c71a4971025178ac79"
38
+ "gitHead": "1e41e4a8ebc16b39fa416e6eb1aa214475ba2865"
36
39
  }