@genation/sdk 0.2.9 → 0.2.11

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.
@@ -1,150 +1,150 @@
1
- class m extends Error {
1
+ class N extends Error {
2
2
  code;
3
3
  cause;
4
- constructor(e, t, s) {
5
- super(e), this.name = "GenationError", this.code = t, this.cause = s;
4
+ constructor(t, r, n) {
5
+ super(t), this.name = "GenationError", this.code = r, this.cause = n;
6
6
  }
7
7
  }
8
- class l extends m {
9
- constructor(e, t, s) {
10
- super(e, t, s), this.name = "AuthError";
8
+ class g extends N {
9
+ constructor(t, r, n) {
10
+ super(t, r, n), this.name = "AuthError";
11
11
  }
12
- static invalidGrant(e = "Invalid authorization code or refresh token") {
13
- return new l(e, "invalid_grant");
12
+ static invalidGrant(t = "Invalid authorization code or refresh token") {
13
+ return new g(t, "invalid_grant");
14
14
  }
15
- static accessDenied(e = "User denied access") {
16
- return new l(e, "access_denied");
15
+ static accessDenied(t = "User denied access") {
16
+ return new g(t, "access_denied");
17
17
  }
18
- static expiredToken(e = "Token has expired") {
19
- return new l(e, "expired_token");
18
+ static expiredToken(t = "Token has expired") {
19
+ return new g(t, "expired_token");
20
20
  }
21
- static invalidState(e = "State mismatch, possible CSRF attack") {
22
- return new l(e, "invalid_state");
21
+ static invalidState(t = "State mismatch, possible CSRF attack") {
22
+ return new g(t, "invalid_state");
23
23
  }
24
- static pkceVerificationFailed(e = "PKCE verification failed") {
25
- return new l(e, "pkce_verification_failed");
24
+ static pkceVerificationFailed(t = "PKCE verification failed") {
25
+ return new g(t, "pkce_verification_failed");
26
26
  }
27
27
  }
28
- class h extends m {
28
+ class S extends N {
29
29
  status;
30
- constructor(e, t, s) {
31
- super(e, "network_error", s), this.name = "NetworkError", this.status = t;
30
+ constructor(t, r, n) {
31
+ super(t, "network_error", n), this.name = "NetworkError", this.status = r;
32
32
  }
33
- static fromResponse(e) {
34
- return new h(
35
- `HTTP ${e.status}: ${e.statusText}`,
36
- e.status
33
+ static fromResponse(t) {
34
+ return new S(
35
+ `HTTP ${t.status}: ${t.statusText}`,
36
+ t.status
37
37
  );
38
38
  }
39
39
  }
40
- class u extends m {
41
- constructor(e) {
42
- super(e, "config_error"), this.name = "ConfigError";
40
+ class v extends N {
41
+ constructor(t) {
42
+ super(t, "config_error"), this.name = "ConfigError";
43
43
  }
44
- static missingField(e) {
45
- return new u(`Missing required config field: ${e}`);
44
+ static missingField(t) {
45
+ return new v(`Missing required config field: ${t}`);
46
46
  }
47
47
  }
48
- class p {
48
+ class D {
49
49
  baseUrl;
50
50
  timeout;
51
- constructor(e) {
52
- this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.timeout = e.timeout ?? 3e4;
51
+ constructor(t) {
52
+ this.baseUrl = t.baseUrl.replace(/\/$/, ""), this.timeout = t.timeout ?? 3e4;
53
53
  }
54
54
  /**
55
55
  * Make an HTTP request
56
56
  */
57
- async request(e, t = {}) {
58
- const { method: s = "GET", headers: n = {}, body: i, params: c } = t;
59
- let a = `${this.baseUrl}${e}`;
60
- if (c) {
61
- const o = new URLSearchParams(c);
62
- a += `?${o.toString()}`;
63
- }
64
- const y = new AbortController(), S = setTimeout(() => y.abort(), this.timeout);
57
+ async request(t, r = {}) {
58
+ const { method: n = "GET", headers: s = {}, body: a, params: i } = r;
59
+ let c = `${this.baseUrl}${t}`;
60
+ if (i) {
61
+ const o = new URLSearchParams(i);
62
+ c += `?${o.toString()}`;
63
+ }
64
+ const h = new AbortController(), u = setTimeout(() => h.abort(), this.timeout);
65
65
  try {
66
- const o = await fetch(a, {
67
- method: s,
66
+ const o = await fetch(c, {
67
+ method: n,
68
68
  headers: {
69
69
  "Content-Type": "application/json",
70
- ...n
70
+ ...s
71
71
  },
72
- body: i ? JSON.stringify(i) : void 0,
73
- signal: y.signal
72
+ body: a ? JSON.stringify(a) : void 0,
73
+ signal: h.signal
74
74
  });
75
- if (clearTimeout(S), !o.ok)
76
- throw h.fromResponse(o);
75
+ if (clearTimeout(u), !o.ok)
76
+ throw S.fromResponse(o);
77
77
  return await o.json();
78
78
  } catch (o) {
79
- throw clearTimeout(S), o instanceof h ? o : o instanceof Error && o.name === "AbortError" ? new h("Request timeout", void 0, o) : new h("Network request failed", void 0, o);
79
+ throw clearTimeout(u), o instanceof S ? o : o instanceof Error && o.name === "AbortError" ? new S("Request timeout", void 0, o) : new S("Network request failed", void 0, o);
80
80
  }
81
81
  }
82
82
  /**
83
83
  * POST request with form data (for OAuth token exchange)
84
84
  */
85
- async postForm(e, t, s = {}) {
86
- const n = `${this.baseUrl}${e}`, i = new AbortController(), c = setTimeout(() => i.abort(), this.timeout);
85
+ async postForm(t, r, n = {}) {
86
+ const s = `${this.baseUrl}${t}`, a = new AbortController(), i = setTimeout(() => a.abort(), this.timeout);
87
87
  try {
88
- const a = await fetch(n, {
88
+ const c = await fetch(s, {
89
89
  method: "POST",
90
90
  headers: {
91
91
  "Content-Type": "application/x-www-form-urlencoded",
92
- ...s
92
+ ...n
93
93
  },
94
- body: new URLSearchParams(t).toString(),
95
- signal: i.signal
94
+ body: new URLSearchParams(r).toString(),
95
+ signal: a.signal
96
96
  });
97
- if (clearTimeout(c), !a.ok)
98
- throw h.fromResponse(a);
99
- return await a.json();
100
- } catch (a) {
101
- throw clearTimeout(c), a instanceof h ? a : new h("Network request failed", void 0, a);
97
+ if (clearTimeout(i), !c.ok)
98
+ throw S.fromResponse(c);
99
+ return await c.json();
100
+ } catch (c) {
101
+ throw clearTimeout(i), c instanceof S ? c : new S("Network request failed", void 0, c);
102
102
  }
103
103
  }
104
104
  }
105
- function k(r) {
106
- return btoa(String.fromCharCode(...r)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
105
+ function $(e) {
106
+ return btoa(String.fromCharCode(...e)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
107
107
  }
108
- function _() {
109
- const r = new Uint8Array(32);
110
- return crypto.getRandomValues(r), k(r);
108
+ function fe() {
109
+ const e = new Uint8Array(32);
110
+ return crypto.getRandomValues(e), $(e);
111
111
  }
112
- async function b(r) {
113
- const t = new TextEncoder().encode(r), s = await crypto.subtle.digest("SHA-256", t);
114
- return k(new Uint8Array(s));
112
+ async function de(e) {
113
+ const r = new TextEncoder().encode(e), n = await crypto.subtle.digest("SHA-256", r);
114
+ return $(new Uint8Array(n));
115
115
  }
116
- async function v() {
117
- const r = _(), e = await b(r);
116
+ async function le() {
117
+ const e = fe(), t = await de(e);
118
118
  return {
119
- codeVerifier: r,
120
- codeChallenge: e,
119
+ codeVerifier: e,
120
+ codeChallenge: t,
121
121
  codeChallengeMethod: "S256"
122
122
  };
123
123
  }
124
- function C() {
125
- const r = new Uint8Array(16);
126
- return crypto.getRandomValues(r), k(r);
124
+ function pe() {
125
+ const e = new Uint8Array(16);
126
+ return crypto.getRandomValues(e), $(e);
127
127
  }
128
- const d = "tokens", g = "pkce", f = "state";
129
- class I {
128
+ const W = "tokens", k = "pkce", I = "state";
129
+ class ye {
130
130
  storage;
131
- constructor(e) {
132
- this.storage = e;
131
+ constructor(t) {
132
+ this.storage = t;
133
133
  }
134
134
  /**
135
135
  * Store token set
136
136
  */
137
- async setTokens(e) {
138
- await this.storage.set(d, JSON.stringify(e));
137
+ async setTokens(t) {
138
+ await this.storage.set(W, JSON.stringify(t));
139
139
  }
140
140
  /**
141
141
  * Get stored tokens
142
142
  */
143
143
  async getTokens() {
144
- const e = await this.storage.get(d);
145
- if (!e) return null;
144
+ const t = await this.storage.get(W);
145
+ if (!t) return null;
146
146
  try {
147
- return JSON.parse(e);
147
+ return JSON.parse(t);
148
148
  } catch {
149
149
  return null;
150
150
  }
@@ -153,42 +153,42 @@ class I {
153
153
  * Clear stored tokens
154
154
  */
155
155
  async clearTokens() {
156
- await this.storage.remove(d);
156
+ await this.storage.remove(W);
157
157
  }
158
158
  /**
159
159
  * Check if access token is expired
160
160
  */
161
161
  async isTokenExpired() {
162
- const e = await this.getTokens();
163
- if (!e) return !0;
164
- const t = e.issuedAt + e.expiresIn * 1e3;
165
- return Date.now() > t - 6e4;
162
+ const t = await this.getTokens();
163
+ if (!t) return !0;
164
+ const r = t.issuedAt + t.expiresIn * 1e3;
165
+ return Date.now() > r - 6e4;
166
166
  }
167
167
  /**
168
168
  * Store PKCE verifier for later validation
169
169
  */
170
- async setPKCE(e) {
171
- await this.storage.set(g, e);
170
+ async setPKCE(t) {
171
+ await this.storage.set(k, t);
172
172
  }
173
173
  /**
174
174
  * Get and clear stored PKCE verifier
175
175
  */
176
176
  async consumePKCE() {
177
- const e = await this.storage.get(g);
178
- return e && await this.storage.remove(g), e;
177
+ const t = await this.storage.get(k);
178
+ return t && await this.storage.remove(k), t;
179
179
  }
180
180
  /**
181
181
  * Store state for CSRF validation
182
182
  */
183
- async setState(e) {
184
- await this.storage.set(f, e);
183
+ async setState(t) {
184
+ await this.storage.set(I, t);
185
185
  }
186
186
  /**
187
187
  * Get and clear stored state
188
188
  */
189
189
  async consumeState() {
190
- const e = await this.storage.get(f);
191
- return e && await this.storage.remove(f), e;
190
+ const t = await this.storage.get(I);
191
+ return t && await this.storage.remove(I), t;
192
192
  }
193
193
  /**
194
194
  * Clear all auth-related data
@@ -197,87 +197,87 @@ class I {
197
197
  await this.storage.clear();
198
198
  }
199
199
  }
200
- const U = "https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";
201
- class x {
200
+ const ee = "https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";
201
+ class me {
202
202
  config;
203
203
  http;
204
204
  tokenManager;
205
- constructor(e, t) {
205
+ constructor(t, r) {
206
206
  this.config = {
207
- clientId: e.clientId,
208
- clientSecret: e.clientSecret,
209
- redirectUri: e.redirectUri,
210
- scopes: e.scopes,
211
- authUrl: e.authUrl ?? U
212
- }, this.http = new p({ baseUrl: this.config.authUrl }), this.tokenManager = t;
207
+ clientId: t.clientId,
208
+ clientSecret: t.clientSecret,
209
+ redirectUri: t.redirectUri,
210
+ scopes: t.scopes,
211
+ authUrl: t.authUrl ?? ee
212
+ }, this.http = new D({ baseUrl: this.config.authUrl }), this.tokenManager = r;
213
213
  }
214
214
  /**
215
215
  * Generate authorization URL for OAuth flow
216
216
  * Stores PKCE verifier and state for later validation
217
217
  */
218
218
  async getAuthorizationUrl() {
219
- const e = await v(), t = C();
220
- await this.tokenManager.setPKCE(e.codeVerifier), await this.tokenManager.setState(t);
221
- const s = new URLSearchParams({
219
+ const t = await le(), r = pe();
220
+ await this.tokenManager.setPKCE(t.codeVerifier), await this.tokenManager.setState(r);
221
+ const n = new URLSearchParams({
222
222
  response_type: "code",
223
223
  client_id: this.config.clientId,
224
224
  redirect_uri: this.config.redirectUri,
225
- state: t,
226
- code_challenge: e.codeChallenge,
227
- code_challenge_method: e.codeChallengeMethod
225
+ state: r,
226
+ code_challenge: t.codeChallenge,
227
+ code_challenge_method: t.codeChallengeMethod
228
228
  });
229
- return this.config.scopes && this.config.scopes.length > 0 && s.append("scope", this.config.scopes.join(" ")), `${this.config.authUrl}/oauth/authorize?${s.toString()}`;
229
+ return this.config.scopes && this.config.scopes.length > 0 && n.append("scope", this.config.scopes.join(" ")), `${this.config.authUrl}/oauth/authorize?${n.toString()}`;
230
230
  }
231
231
  /**
232
232
  * Exchange authorization code for tokens
233
233
  */
234
- async exchangeCode(e, t) {
235
- const s = await this.tokenManager.consumeState();
236
- if (!s || s !== t)
237
- throw l.invalidState();
238
- const n = await this.tokenManager.consumePKCE();
239
- if (!n)
240
- throw l.pkceVerificationFailed("Missing code verifier");
241
- const i = await this.http.postForm(
234
+ async exchangeCode(t, r) {
235
+ const n = await this.tokenManager.consumeState();
236
+ if (!n || n !== r)
237
+ throw g.invalidState();
238
+ const s = await this.tokenManager.consumePKCE();
239
+ if (!s)
240
+ throw g.pkceVerificationFailed("Missing code verifier");
241
+ const a = await this.http.postForm(
242
242
  "/oauth/token",
243
243
  {
244
244
  grant_type: "authorization_code",
245
- code: e,
245
+ code: t,
246
246
  redirect_uri: this.config.redirectUri,
247
247
  client_id: this.config.clientId,
248
248
  client_secret: this.config.clientSecret,
249
- code_verifier: n
249
+ code_verifier: s
250
250
  }
251
- ), c = this.mapTokenResponse(i);
252
- return await this.tokenManager.setTokens(c), c;
251
+ ), i = this.mapTokenResponse(a);
252
+ return await this.tokenManager.setTokens(i), i;
253
253
  }
254
254
  /**
255
255
  * Refresh access token using refresh token
256
256
  */
257
257
  async refreshToken() {
258
- const e = await this.tokenManager.getTokens();
259
- if (!e?.refreshToken)
260
- throw l.invalidGrant("No refresh token available");
261
- const t = await this.http.postForm(
258
+ const t = await this.tokenManager.getTokens();
259
+ if (!t?.refreshToken)
260
+ throw g.invalidGrant("No refresh token available");
261
+ const r = await this.http.postForm(
262
262
  "/oauth/token",
263
263
  {
264
264
  grant_type: "refresh_token",
265
- refresh_token: e.refreshToken,
265
+ refresh_token: t.refreshToken,
266
266
  client_id: this.config.clientId,
267
267
  client_secret: this.config.clientSecret
268
268
  }
269
- ), s = this.mapTokenResponse(t);
270
- return await this.tokenManager.setTokens(s), s;
269
+ ), n = this.mapTokenResponse(r);
270
+ return await this.tokenManager.setTokens(n), n;
271
271
  }
272
272
  /**
273
273
  * Revoke current tokens
274
274
  */
275
275
  async revokeToken() {
276
- const e = await this.tokenManager.getTokens();
277
- if (e)
276
+ const t = await this.tokenManager.getTokens();
277
+ if (t)
278
278
  try {
279
279
  await this.http.postForm("/oauth/revoke", {
280
- token: e.accessToken,
280
+ token: t.accessToken,
281
281
  client_id: this.config.clientId,
282
282
  client_secret: this.config.clientSecret
283
283
  });
@@ -288,132 +288,1171 @@ class x {
288
288
  /**
289
289
  * Map OAuth token response to TokenSet
290
290
  */
291
- mapTokenResponse(e) {
291
+ mapTokenResponse(t) {
292
292
  return {
293
- accessToken: e.access_token,
294
- refreshToken: e.refresh_token,
295
- tokenType: e.token_type,
296
- expiresIn: e.expires_in,
293
+ accessToken: t.access_token,
294
+ refreshToken: t.refresh_token,
295
+ tokenType: t.token_type,
296
+ expiresIn: t.expires_in,
297
297
  issuedAt: Date.now(),
298
- scope: e.scope
298
+ scope: t.scope
299
299
  };
300
300
  }
301
301
  }
302
- class E {
302
+ const G = new TextEncoder(), _ = new TextDecoder();
303
+ function we(...e) {
304
+ const t = e.reduce((s, { length: a }) => s + a, 0), r = new Uint8Array(t);
305
+ let n = 0;
306
+ for (const s of e)
307
+ r.set(s, n), n += s.length;
308
+ return r;
309
+ }
310
+ function J(e) {
311
+ const t = new Uint8Array(e.length);
312
+ for (let r = 0; r < e.length; r++) {
313
+ const n = e.charCodeAt(r);
314
+ if (n > 127)
315
+ throw new TypeError("non-ASCII string encountered in encode()");
316
+ t[r] = n;
317
+ }
318
+ return t;
319
+ }
320
+ function Se(e) {
321
+ if (Uint8Array.fromBase64)
322
+ return Uint8Array.fromBase64(e);
323
+ const t = atob(e), r = new Uint8Array(t.length);
324
+ for (let n = 0; n < t.length; n++)
325
+ r[n] = t.charCodeAt(n);
326
+ return r;
327
+ }
328
+ function C(e) {
329
+ if (Uint8Array.fromBase64)
330
+ return Uint8Array.fromBase64(typeof e == "string" ? e : _.decode(e), {
331
+ alphabet: "base64url"
332
+ });
333
+ let t = e;
334
+ t instanceof Uint8Array && (t = _.decode(t)), t = t.replace(/-/g, "+").replace(/_/g, "/");
335
+ try {
336
+ return Se(t);
337
+ } catch {
338
+ throw new TypeError("The input to be decoded is not correctly encoded.");
339
+ }
340
+ }
341
+ class l extends Error {
342
+ static code = "ERR_JOSE_GENERIC";
343
+ code = "ERR_JOSE_GENERIC";
344
+ constructor(t, r) {
345
+ super(t, r), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
346
+ }
347
+ }
348
+ class y extends l {
349
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
350
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
351
+ claim;
352
+ reason;
353
+ payload;
354
+ constructor(t, r, n = "unspecified", s = "unspecified") {
355
+ super(t, { cause: { claim: n, reason: s, payload: r } }), this.claim = n, this.reason = s, this.payload = r;
356
+ }
357
+ }
358
+ class z extends l {
359
+ static code = "ERR_JWT_EXPIRED";
360
+ code = "ERR_JWT_EXPIRED";
361
+ claim;
362
+ reason;
363
+ payload;
364
+ constructor(t, r, n = "unspecified", s = "unspecified") {
365
+ super(t, { cause: { claim: n, reason: s, payload: r } }), this.claim = n, this.reason = s, this.payload = r;
366
+ }
367
+ }
368
+ class w extends l {
369
+ static code = "ERR_JOSE_NOT_SUPPORTED";
370
+ code = "ERR_JOSE_NOT_SUPPORTED";
371
+ }
372
+ class f extends l {
373
+ static code = "ERR_JWS_INVALID";
374
+ code = "ERR_JWS_INVALID";
375
+ }
376
+ class te extends l {
377
+ static code = "ERR_JWT_INVALID";
378
+ code = "ERR_JWT_INVALID";
379
+ }
380
+ class re extends l {
381
+ static code = "ERR_JWKS_INVALID";
382
+ code = "ERR_JWKS_INVALID";
383
+ }
384
+ class ne extends l {
385
+ static code = "ERR_JWKS_NO_MATCHING_KEY";
386
+ code = "ERR_JWKS_NO_MATCHING_KEY";
387
+ constructor(t = "no applicable key found in the JSON Web Key Set", r) {
388
+ super(t, r);
389
+ }
390
+ }
391
+ class ge extends l {
392
+ [Symbol.asyncIterator];
393
+ static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
394
+ code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
395
+ constructor(t = "multiple matching keys found in the JSON Web Key Set", r) {
396
+ super(t, r);
397
+ }
398
+ }
399
+ class be extends l {
400
+ static code = "ERR_JWKS_TIMEOUT";
401
+ code = "ERR_JWKS_TIMEOUT";
402
+ constructor(t = "request timed out", r) {
403
+ super(t, r);
404
+ }
405
+ }
406
+ class Ee extends l {
407
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
408
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
409
+ constructor(t = "signature verification failed", r) {
410
+ super(t, r);
411
+ }
412
+ }
413
+ const m = (e, t = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`), A = (e, t) => e.name === t;
414
+ function x(e) {
415
+ return parseInt(e.name.slice(4), 10);
416
+ }
417
+ function Ae(e) {
418
+ switch (e) {
419
+ case "ES256":
420
+ return "P-256";
421
+ case "ES384":
422
+ return "P-384";
423
+ case "ES512":
424
+ return "P-521";
425
+ default:
426
+ throw new Error("unreachable");
427
+ }
428
+ }
429
+ function Ke(e, t) {
430
+ if (!e.usages.includes(t))
431
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`);
432
+ }
433
+ function Te(e, t, r) {
434
+ switch (t) {
435
+ case "HS256":
436
+ case "HS384":
437
+ case "HS512": {
438
+ if (!A(e.algorithm, "HMAC"))
439
+ throw m("HMAC");
440
+ const n = parseInt(t.slice(2), 10);
441
+ if (x(e.algorithm.hash) !== n)
442
+ throw m(`SHA-${n}`, "algorithm.hash");
443
+ break;
444
+ }
445
+ case "RS256":
446
+ case "RS384":
447
+ case "RS512": {
448
+ if (!A(e.algorithm, "RSASSA-PKCS1-v1_5"))
449
+ throw m("RSASSA-PKCS1-v1_5");
450
+ const n = parseInt(t.slice(2), 10);
451
+ if (x(e.algorithm.hash) !== n)
452
+ throw m(`SHA-${n}`, "algorithm.hash");
453
+ break;
454
+ }
455
+ case "PS256":
456
+ case "PS384":
457
+ case "PS512": {
458
+ if (!A(e.algorithm, "RSA-PSS"))
459
+ throw m("RSA-PSS");
460
+ const n = parseInt(t.slice(2), 10);
461
+ if (x(e.algorithm.hash) !== n)
462
+ throw m(`SHA-${n}`, "algorithm.hash");
463
+ break;
464
+ }
465
+ case "Ed25519":
466
+ case "EdDSA": {
467
+ if (!A(e.algorithm, "Ed25519"))
468
+ throw m("Ed25519");
469
+ break;
470
+ }
471
+ case "ML-DSA-44":
472
+ case "ML-DSA-65":
473
+ case "ML-DSA-87": {
474
+ if (!A(e.algorithm, t))
475
+ throw m(t);
476
+ break;
477
+ }
478
+ case "ES256":
479
+ case "ES384":
480
+ case "ES512": {
481
+ if (!A(e.algorithm, "ECDSA"))
482
+ throw m("ECDSA");
483
+ const n = Ae(t);
484
+ if (e.algorithm.namedCurve !== n)
485
+ throw m(n, "algorithm.namedCurve");
486
+ break;
487
+ }
488
+ default:
489
+ throw new TypeError("CryptoKey does not support this operation");
490
+ }
491
+ Ke(e, r);
492
+ }
493
+ function se(e, t, ...r) {
494
+ if (r = r.filter(Boolean), r.length > 2) {
495
+ const n = r.pop();
496
+ e += `one of type ${r.join(", ")}, or ${n}.`;
497
+ } else r.length === 2 ? e += `one of type ${r[0]} or ${r[1]}.` : e += `of type ${r[0]}.`;
498
+ return t == null ? e += ` Received ${t}` : typeof t == "function" && t.name ? e += ` Received function ${t.name}` : typeof t == "object" && t != null && t.constructor?.name && (e += ` Received an instance of ${t.constructor.name}`), e;
499
+ }
500
+ const ve = (e, ...t) => se("Key must be ", e, ...t), ae = (e, t, ...r) => se(`Key for the ${e} algorithm must be `, t, ...r), ie = (e) => {
501
+ if (e?.[Symbol.toStringTag] === "CryptoKey")
502
+ return !0;
503
+ try {
504
+ return e instanceof CryptoKey;
505
+ } catch {
506
+ return !1;
507
+ }
508
+ }, oe = (e) => e?.[Symbol.toStringTag] === "KeyObject", ce = (e) => ie(e) || oe(e);
509
+ function Ce(...e) {
510
+ const t = e.filter(Boolean);
511
+ if (t.length === 0 || t.length === 1)
512
+ return !0;
513
+ let r;
514
+ for (const n of t) {
515
+ const s = Object.keys(n);
516
+ if (!r || r.size === 0) {
517
+ r = new Set(s);
518
+ continue;
519
+ }
520
+ for (const a of s) {
521
+ if (r.has(a))
522
+ return !1;
523
+ r.add(a);
524
+ }
525
+ }
526
+ return !0;
527
+ }
528
+ const _e = (e) => typeof e == "object" && e !== null;
529
+ function E(e) {
530
+ if (!_e(e) || Object.prototype.toString.call(e) !== "[object Object]")
531
+ return !1;
532
+ if (Object.getPrototypeOf(e) === null)
533
+ return !0;
534
+ let t = e;
535
+ for (; Object.getPrototypeOf(t) !== null; )
536
+ t = Object.getPrototypeOf(t);
537
+ return Object.getPrototypeOf(e) === t;
538
+ }
539
+ function Re(e, t) {
540
+ if (e.startsWith("RS") || e.startsWith("PS")) {
541
+ const { modulusLength: r } = t.algorithm;
542
+ if (typeof r != "number" || r < 2048)
543
+ throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`);
544
+ }
545
+ }
546
+ function Pe(e) {
547
+ let t, r;
548
+ switch (e.kty) {
549
+ case "AKP": {
550
+ switch (e.alg) {
551
+ case "ML-DSA-44":
552
+ case "ML-DSA-65":
553
+ case "ML-DSA-87":
554
+ t = { name: e.alg }, r = e.priv ? ["sign"] : ["verify"];
555
+ break;
556
+ default:
557
+ throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
558
+ }
559
+ break;
560
+ }
561
+ case "RSA": {
562
+ switch (e.alg) {
563
+ case "PS256":
564
+ case "PS384":
565
+ case "PS512":
566
+ t = { name: "RSA-PSS", hash: `SHA-${e.alg.slice(-3)}` }, r = e.d ? ["sign"] : ["verify"];
567
+ break;
568
+ case "RS256":
569
+ case "RS384":
570
+ case "RS512":
571
+ t = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${e.alg.slice(-3)}` }, r = e.d ? ["sign"] : ["verify"];
572
+ break;
573
+ case "RSA-OAEP":
574
+ case "RSA-OAEP-256":
575
+ case "RSA-OAEP-384":
576
+ case "RSA-OAEP-512":
577
+ t = {
578
+ name: "RSA-OAEP",
579
+ hash: `SHA-${parseInt(e.alg.slice(-3), 10) || 1}`
580
+ }, r = e.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
581
+ break;
582
+ default:
583
+ throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
584
+ }
585
+ break;
586
+ }
587
+ case "EC": {
588
+ switch (e.alg) {
589
+ case "ES256":
590
+ t = { name: "ECDSA", namedCurve: "P-256" }, r = e.d ? ["sign"] : ["verify"];
591
+ break;
592
+ case "ES384":
593
+ t = { name: "ECDSA", namedCurve: "P-384" }, r = e.d ? ["sign"] : ["verify"];
594
+ break;
595
+ case "ES512":
596
+ t = { name: "ECDSA", namedCurve: "P-521" }, r = e.d ? ["sign"] : ["verify"];
597
+ break;
598
+ case "ECDH-ES":
599
+ case "ECDH-ES+A128KW":
600
+ case "ECDH-ES+A192KW":
601
+ case "ECDH-ES+A256KW":
602
+ t = { name: "ECDH", namedCurve: e.crv }, r = e.d ? ["deriveBits"] : [];
603
+ break;
604
+ default:
605
+ throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
606
+ }
607
+ break;
608
+ }
609
+ case "OKP": {
610
+ switch (e.alg) {
611
+ case "Ed25519":
612
+ case "EdDSA":
613
+ t = { name: "Ed25519" }, r = e.d ? ["sign"] : ["verify"];
614
+ break;
615
+ case "ECDH-ES":
616
+ case "ECDH-ES+A128KW":
617
+ case "ECDH-ES+A192KW":
618
+ case "ECDH-ES+A256KW":
619
+ t = { name: e.crv }, r = e.d ? ["deriveBits"] : [];
620
+ break;
621
+ default:
622
+ throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
623
+ }
624
+ break;
625
+ }
626
+ default:
627
+ throw new w('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
628
+ }
629
+ return { algorithm: t, keyUsages: r };
630
+ }
631
+ async function R(e) {
632
+ if (!e.alg)
633
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
634
+ const { algorithm: t, keyUsages: r } = Pe(e), n = { ...e };
635
+ return n.kty !== "AKP" && delete n.alg, delete n.use, crypto.subtle.importKey("jwk", n, t, e.ext ?? !(e.d || e.priv), e.key_ops ?? r);
636
+ }
637
+ async function We(e, t, r) {
638
+ if (!E(e))
639
+ throw new TypeError("JWK must be an object");
640
+ let n;
641
+ switch (t ??= e.alg, n ??= e.ext, e.kty) {
642
+ case "oct":
643
+ if (typeof e.k != "string" || !e.k)
644
+ throw new TypeError('missing "k" (Key Value) Parameter value');
645
+ return C(e.k);
646
+ case "RSA":
647
+ if ("oth" in e && e.oth !== void 0)
648
+ throw new w('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
649
+ return R({ ...e, alg: t, ext: n });
650
+ case "AKP": {
651
+ if (typeof e.alg != "string" || !e.alg)
652
+ throw new TypeError('missing "alg" (Algorithm) Parameter value');
653
+ if (t !== void 0 && t !== e.alg)
654
+ throw new TypeError("JWK alg and alg option value mismatch");
655
+ return R({ ...e, ext: n });
656
+ }
657
+ case "EC":
658
+ case "OKP":
659
+ return R({ ...e, alg: t, ext: n });
660
+ default:
661
+ throw new w('Unsupported "kty" (Key Type) Parameter value');
662
+ }
663
+ }
664
+ function ke(e, t, r, n, s) {
665
+ if (s.crit !== void 0 && n?.crit === void 0)
666
+ throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');
667
+ if (!n || n.crit === void 0)
668
+ return /* @__PURE__ */ new Set();
669
+ if (!Array.isArray(n.crit) || n.crit.length === 0 || n.crit.some((i) => typeof i != "string" || i.length === 0))
670
+ throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
671
+ let a;
672
+ a = t;
673
+ for (const i of n.crit) {
674
+ if (!a.has(i))
675
+ throw new w(`Extension Header Parameter "${i}" is not recognized`);
676
+ if (s[i] === void 0)
677
+ throw new e(`Extension Header Parameter "${i}" is missing`);
678
+ if (a.get(i) && n[i] === void 0)
679
+ throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`);
680
+ }
681
+ return new Set(n.crit);
682
+ }
683
+ const L = (e) => E(e) && typeof e.kty == "string", Ie = (e) => e.kty !== "oct" && (e.kty === "AKP" && typeof e.priv == "string" || typeof e.d == "string"), Je = (e) => e.kty !== "oct" && e.d === void 0 && e.priv === void 0, xe = (e) => e.kty === "oct" && typeof e.k == "string";
684
+ let T;
685
+ const B = async (e, t, r, n = !1) => {
686
+ T ||= /* @__PURE__ */ new WeakMap();
687
+ let s = T.get(e);
688
+ if (s?.[r])
689
+ return s[r];
690
+ const a = await R({ ...t, alg: r });
691
+ return n && Object.freeze(e), s ? s[r] = a : T.set(e, { [r]: a }), a;
692
+ }, Ue = (e, t) => {
693
+ T ||= /* @__PURE__ */ new WeakMap();
694
+ let r = T.get(e);
695
+ if (r?.[t])
696
+ return r[t];
697
+ const n = e.type === "public", s = !!n;
698
+ let a;
699
+ if (e.asymmetricKeyType === "x25519") {
700
+ switch (t) {
701
+ case "ECDH-ES":
702
+ case "ECDH-ES+A128KW":
703
+ case "ECDH-ES+A192KW":
704
+ case "ECDH-ES+A256KW":
705
+ break;
706
+ default:
707
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
708
+ }
709
+ a = e.toCryptoKey(e.asymmetricKeyType, s, n ? [] : ["deriveBits"]);
710
+ }
711
+ if (e.asymmetricKeyType === "ed25519") {
712
+ if (t !== "EdDSA" && t !== "Ed25519")
713
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
714
+ a = e.toCryptoKey(e.asymmetricKeyType, s, [
715
+ n ? "verify" : "sign"
716
+ ]);
717
+ }
718
+ switch (e.asymmetricKeyType) {
719
+ case "ml-dsa-44":
720
+ case "ml-dsa-65":
721
+ case "ml-dsa-87": {
722
+ if (t !== e.asymmetricKeyType.toUpperCase())
723
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
724
+ a = e.toCryptoKey(e.asymmetricKeyType, s, [
725
+ n ? "verify" : "sign"
726
+ ]);
727
+ }
728
+ }
729
+ if (e.asymmetricKeyType === "rsa") {
730
+ let i;
731
+ switch (t) {
732
+ case "RSA-OAEP":
733
+ i = "SHA-1";
734
+ break;
735
+ case "RS256":
736
+ case "PS256":
737
+ case "RSA-OAEP-256":
738
+ i = "SHA-256";
739
+ break;
740
+ case "RS384":
741
+ case "PS384":
742
+ case "RSA-OAEP-384":
743
+ i = "SHA-384";
744
+ break;
745
+ case "RS512":
746
+ case "PS512":
747
+ case "RSA-OAEP-512":
748
+ i = "SHA-512";
749
+ break;
750
+ default:
751
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
752
+ }
753
+ if (t.startsWith("RSA-OAEP"))
754
+ return e.toCryptoKey({
755
+ name: "RSA-OAEP",
756
+ hash: i
757
+ }, s, n ? ["encrypt"] : ["decrypt"]);
758
+ a = e.toCryptoKey({
759
+ name: t.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
760
+ hash: i
761
+ }, s, [n ? "verify" : "sign"]);
762
+ }
763
+ if (e.asymmetricKeyType === "ec") {
764
+ const c = (/* @__PURE__ */ new Map([
765
+ ["prime256v1", "P-256"],
766
+ ["secp384r1", "P-384"],
767
+ ["secp521r1", "P-521"]
768
+ ])).get(e.asymmetricKeyDetails?.namedCurve);
769
+ if (!c)
770
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
771
+ t === "ES256" && c === "P-256" && (a = e.toCryptoKey({
772
+ name: "ECDSA",
773
+ namedCurve: c
774
+ }, s, [n ? "verify" : "sign"])), t === "ES384" && c === "P-384" && (a = e.toCryptoKey({
775
+ name: "ECDSA",
776
+ namedCurve: c
777
+ }, s, [n ? "verify" : "sign"])), t === "ES512" && c === "P-521" && (a = e.toCryptoKey({
778
+ name: "ECDSA",
779
+ namedCurve: c
780
+ }, s, [n ? "verify" : "sign"])), t.startsWith("ECDH-ES") && (a = e.toCryptoKey({
781
+ name: "ECDH",
782
+ namedCurve: c
783
+ }, s, n ? [] : ["deriveBits"]));
784
+ }
785
+ if (!a)
786
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
787
+ return r ? r[t] = a : T.set(e, { [t]: a }), a;
788
+ };
789
+ async function De(e, t) {
790
+ if (e instanceof Uint8Array || ie(e))
791
+ return e;
792
+ if (oe(e)) {
793
+ if (e.type === "secret")
794
+ return e.export();
795
+ if ("toCryptoKey" in e && typeof e.toCryptoKey == "function")
796
+ try {
797
+ return Ue(e, t);
798
+ } catch (n) {
799
+ if (n instanceof TypeError)
800
+ throw n;
801
+ }
802
+ let r = e.export({ format: "jwk" });
803
+ return B(e, r, t);
804
+ }
805
+ if (L(e))
806
+ return e.k ? C(e.k) : B(e, e, t, !0);
807
+ throw new Error("unreachable");
808
+ }
809
+ const K = (e) => e?.[Symbol.toStringTag], M = (e, t, r) => {
810
+ if (t.use !== void 0) {
811
+ let n;
812
+ switch (r) {
813
+ case "sign":
814
+ case "verify":
815
+ n = "sig";
816
+ break;
817
+ case "encrypt":
818
+ case "decrypt":
819
+ n = "enc";
820
+ break;
821
+ }
822
+ if (t.use !== n)
823
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`);
824
+ }
825
+ if (t.alg !== void 0 && t.alg !== e)
826
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);
827
+ if (Array.isArray(t.key_ops)) {
828
+ let n;
829
+ switch (!0) {
830
+ case r === "verify":
831
+ case e === "dir":
832
+ case e.includes("CBC-HS"):
833
+ n = r;
834
+ break;
835
+ case e.startsWith("PBES2"):
836
+ n = "deriveBits";
837
+ break;
838
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(e):
839
+ !e.includes("GCM") && e.endsWith("KW") ? n = "unwrapKey" : n = r;
840
+ break;
841
+ case r === "encrypt":
842
+ n = "wrapKey";
843
+ break;
844
+ case r === "decrypt":
845
+ n = e.startsWith("RSA") ? "unwrapKey" : "deriveBits";
846
+ break;
847
+ }
848
+ if (n && t.key_ops?.includes?.(n) === !1)
849
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`);
850
+ }
851
+ return !0;
852
+ }, Me = (e, t, r) => {
853
+ if (!(t instanceof Uint8Array)) {
854
+ if (L(t)) {
855
+ if (xe(t) && M(e, t, r))
856
+ return;
857
+ 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');
858
+ }
859
+ if (!ce(t))
860
+ throw new TypeError(ae(e, t, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
861
+ if (t.type !== "secret")
862
+ throw new TypeError(`${K(t)} instances for symmetric algorithms must be of type "secret"`);
863
+ }
864
+ }, Oe = (e, t, r) => {
865
+ if (L(t))
866
+ switch (r) {
867
+ case "decrypt":
868
+ case "sign":
869
+ if (Ie(t) && M(e, t, r))
870
+ return;
871
+ throw new TypeError("JSON Web Key for this operation must be a private JWK");
872
+ case "encrypt":
873
+ case "verify":
874
+ if (Je(t) && M(e, t, r))
875
+ return;
876
+ throw new TypeError("JSON Web Key for this operation must be a public JWK");
877
+ }
878
+ if (!ce(t))
879
+ throw new TypeError(ae(e, t, "CryptoKey", "KeyObject", "JSON Web Key"));
880
+ if (t.type === "secret")
881
+ throw new TypeError(`${K(t)} instances for asymmetric algorithms must not be of type "secret"`);
882
+ if (t.type === "public")
883
+ switch (r) {
884
+ case "sign":
885
+ throw new TypeError(`${K(t)} instances for asymmetric algorithm signing must be of type "private"`);
886
+ case "decrypt":
887
+ throw new TypeError(`${K(t)} instances for asymmetric algorithm decryption must be of type "private"`);
888
+ }
889
+ if (t.type === "private")
890
+ switch (r) {
891
+ case "verify":
892
+ throw new TypeError(`${K(t)} instances for asymmetric algorithm verifying must be of type "public"`);
893
+ case "encrypt":
894
+ throw new TypeError(`${K(t)} instances for asymmetric algorithm encryption must be of type "public"`);
895
+ }
896
+ };
897
+ function He(e, t, r) {
898
+ switch (e.substring(0, 2)) {
899
+ case "A1":
900
+ case "A2":
901
+ case "di":
902
+ case "HS":
903
+ case "PB":
904
+ Me(e, t, r);
905
+ break;
906
+ default:
907
+ Oe(e, t, r);
908
+ }
909
+ }
910
+ function Ne(e, t) {
911
+ const r = `SHA-${e.slice(-3)}`;
912
+ switch (e) {
913
+ case "HS256":
914
+ case "HS384":
915
+ case "HS512":
916
+ return { hash: r, name: "HMAC" };
917
+ case "PS256":
918
+ case "PS384":
919
+ case "PS512":
920
+ return { hash: r, name: "RSA-PSS", saltLength: parseInt(e.slice(-3), 10) >> 3 };
921
+ case "RS256":
922
+ case "RS384":
923
+ case "RS512":
924
+ return { hash: r, name: "RSASSA-PKCS1-v1_5" };
925
+ case "ES256":
926
+ case "ES384":
927
+ case "ES512":
928
+ return { hash: r, name: "ECDSA", namedCurve: t.namedCurve };
929
+ case "Ed25519":
930
+ case "EdDSA":
931
+ return { name: "Ed25519" };
932
+ case "ML-DSA-44":
933
+ case "ML-DSA-65":
934
+ case "ML-DSA-87":
935
+ return { name: e };
936
+ default:
937
+ throw new w(`alg ${e} is not supported either by JOSE or your javascript runtime`);
938
+ }
939
+ }
940
+ async function $e(e, t, r) {
941
+ if (t instanceof Uint8Array) {
942
+ if (!e.startsWith("HS"))
943
+ throw new TypeError(ve(t, "CryptoKey", "KeyObject", "JSON Web Key"));
944
+ return crypto.subtle.importKey("raw", t, { hash: `SHA-${e.slice(-3)}`, name: "HMAC" }, !1, [r]);
945
+ }
946
+ return Te(t, e, r), t;
947
+ }
948
+ async function Le(e, t, r, n) {
949
+ const s = await $e(e, t, "verify");
950
+ Re(e, s);
951
+ const a = Ne(e, s.algorithm);
952
+ try {
953
+ return await crypto.subtle.verify(a, s, r, n);
954
+ } catch {
955
+ return !1;
956
+ }
957
+ }
958
+ async function Fe(e, t, r) {
959
+ if (!E(e))
960
+ throw new f("Flattened JWS must be an object");
961
+ if (e.protected === void 0 && e.header === void 0)
962
+ throw new f('Flattened JWS must have either of the "protected" or "header" members');
963
+ if (e.protected !== void 0 && typeof e.protected != "string")
964
+ throw new f("JWS Protected Header incorrect type");
965
+ if (e.payload === void 0)
966
+ throw new f("JWS Payload missing");
967
+ if (typeof e.signature != "string")
968
+ throw new f("JWS Signature missing or incorrect type");
969
+ if (e.header !== void 0 && !E(e.header))
970
+ throw new f("JWS Unprotected Header incorrect type");
971
+ let n = {};
972
+ if (e.protected)
973
+ try {
974
+ const P = C(e.protected);
975
+ n = JSON.parse(_.decode(P));
976
+ } catch {
977
+ throw new f("JWS Protected Header is invalid");
978
+ }
979
+ if (!Ce(n, e.header))
980
+ throw new f("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
981
+ const s = {
982
+ ...n,
983
+ ...e.header
984
+ }, a = ke(f, /* @__PURE__ */ new Map([["b64", !0]]), r?.crit, n, s);
985
+ let i = !0;
986
+ if (a.has("b64") && (i = n.b64, typeof i != "boolean"))
987
+ throw new f('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
988
+ const { alg: c } = s;
989
+ if (typeof c != "string" || !c)
990
+ throw new f('JWS "alg" (Algorithm) Header Parameter missing or invalid');
991
+ if (i) {
992
+ if (typeof e.payload != "string")
993
+ throw new f("JWS Payload must be a string");
994
+ } else if (typeof e.payload != "string" && !(e.payload instanceof Uint8Array))
995
+ throw new f("JWS Payload must be a string or an Uint8Array instance");
996
+ let h = !1;
997
+ typeof t == "function" && (t = await t(n, e), h = !0), He(c, t, "verify");
998
+ const u = we(e.protected !== void 0 ? J(e.protected) : new Uint8Array(), J("."), typeof e.payload == "string" ? i ? J(e.payload) : G.encode(e.payload) : e.payload);
999
+ let o;
1000
+ try {
1001
+ o = C(e.signature);
1002
+ } catch {
1003
+ throw new f("Failed to base64url decode the signature");
1004
+ }
1005
+ const d = await De(t, c);
1006
+ if (!await Le(c, d, o, u))
1007
+ throw new Ee();
1008
+ let b;
1009
+ if (i)
1010
+ try {
1011
+ b = C(e.payload);
1012
+ } catch {
1013
+ throw new f("Failed to base64url decode the payload");
1014
+ }
1015
+ else typeof e.payload == "string" ? b = G.encode(e.payload) : b = e.payload;
1016
+ const p = { payload: b };
1017
+ return e.protected !== void 0 && (p.protectedHeader = n), e.header !== void 0 && (p.unprotectedHeader = e.header), h ? { ...p, key: d } : p;
1018
+ }
1019
+ async function Ve(e, t, r) {
1020
+ if (e instanceof Uint8Array && (e = _.decode(e)), typeof e != "string")
1021
+ throw new f("Compact JWS must be a string or Uint8Array");
1022
+ const { 0: n, 1: s, 2: a, length: i } = e.split(".");
1023
+ if (i !== 3)
1024
+ throw new f("Invalid Compact JWS");
1025
+ const c = await Fe({ payload: s, protected: n, signature: a }, t, r), h = { payload: c.payload, protectedHeader: c.protectedHeader };
1026
+ return typeof t == "function" ? { ...h, key: c.key } : h;
1027
+ }
1028
+ const Ge = (e) => Math.floor(e.getTime() / 1e3), ue = 60, he = ue * 60, F = he * 24, ze = F * 7, Be = F * 365.25, qe = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
1029
+ function q(e) {
1030
+ const t = qe.exec(e);
1031
+ if (!t || t[4] && t[1])
1032
+ throw new TypeError("Invalid time period format");
1033
+ const r = parseFloat(t[2]), n = t[3].toLowerCase();
1034
+ let s;
1035
+ switch (n) {
1036
+ case "sec":
1037
+ case "secs":
1038
+ case "second":
1039
+ case "seconds":
1040
+ case "s":
1041
+ s = Math.round(r);
1042
+ break;
1043
+ case "minute":
1044
+ case "minutes":
1045
+ case "min":
1046
+ case "mins":
1047
+ case "m":
1048
+ s = Math.round(r * ue);
1049
+ break;
1050
+ case "hour":
1051
+ case "hours":
1052
+ case "hr":
1053
+ case "hrs":
1054
+ case "h":
1055
+ s = Math.round(r * he);
1056
+ break;
1057
+ case "day":
1058
+ case "days":
1059
+ case "d":
1060
+ s = Math.round(r * F);
1061
+ break;
1062
+ case "week":
1063
+ case "weeks":
1064
+ case "w":
1065
+ s = Math.round(r * ze);
1066
+ break;
1067
+ default:
1068
+ s = Math.round(r * Be);
1069
+ break;
1070
+ }
1071
+ return t[1] === "-" || t[4] === "ago" ? -s : s;
1072
+ }
1073
+ const Y = (e) => e.includes("/") ? e.toLowerCase() : `application/${e.toLowerCase()}`, Ye = (e, t) => typeof e == "string" ? t.includes(e) : Array.isArray(e) ? t.some(Set.prototype.has.bind(new Set(e))) : !1;
1074
+ function Xe(e, t, r = {}) {
1075
+ let n;
1076
+ try {
1077
+ n = JSON.parse(_.decode(t));
1078
+ } catch {
1079
+ }
1080
+ if (!E(n))
1081
+ throw new te("JWT Claims Set must be a top-level JSON object");
1082
+ const { typ: s } = r;
1083
+ if (s && (typeof e.typ != "string" || Y(e.typ) !== Y(s)))
1084
+ throw new y('unexpected "typ" JWT header value', n, "typ", "check_failed");
1085
+ const { requiredClaims: a = [], issuer: i, subject: c, audience: h, maxTokenAge: u } = r, o = [...a];
1086
+ u !== void 0 && o.push("iat"), h !== void 0 && o.push("aud"), c !== void 0 && o.push("sub"), i !== void 0 && o.push("iss");
1087
+ for (const p of new Set(o.reverse()))
1088
+ if (!(p in n))
1089
+ throw new y(`missing required "${p}" claim`, n, p, "missing");
1090
+ if (i && !(Array.isArray(i) ? i : [i]).includes(n.iss))
1091
+ throw new y('unexpected "iss" claim value', n, "iss", "check_failed");
1092
+ if (c && n.sub !== c)
1093
+ throw new y('unexpected "sub" claim value', n, "sub", "check_failed");
1094
+ if (h && !Ye(n.aud, typeof h == "string" ? [h] : h))
1095
+ throw new y('unexpected "aud" claim value', n, "aud", "check_failed");
1096
+ let d;
1097
+ switch (typeof r.clockTolerance) {
1098
+ case "string":
1099
+ d = q(r.clockTolerance);
1100
+ break;
1101
+ case "number":
1102
+ d = r.clockTolerance;
1103
+ break;
1104
+ case "undefined":
1105
+ d = 0;
1106
+ break;
1107
+ default:
1108
+ throw new TypeError("Invalid clockTolerance option type");
1109
+ }
1110
+ const { currentDate: V } = r, b = Ge(V || /* @__PURE__ */ new Date());
1111
+ if ((n.iat !== void 0 || u) && typeof n.iat != "number")
1112
+ throw new y('"iat" claim must be a number', n, "iat", "invalid");
1113
+ if (n.nbf !== void 0) {
1114
+ if (typeof n.nbf != "number")
1115
+ throw new y('"nbf" claim must be a number', n, "nbf", "invalid");
1116
+ if (n.nbf > b + d)
1117
+ throw new y('"nbf" claim timestamp check failed', n, "nbf", "check_failed");
1118
+ }
1119
+ if (n.exp !== void 0) {
1120
+ if (typeof n.exp != "number")
1121
+ throw new y('"exp" claim must be a number', n, "exp", "invalid");
1122
+ if (n.exp <= b - d)
1123
+ throw new z('"exp" claim timestamp check failed', n, "exp", "check_failed");
1124
+ }
1125
+ if (u) {
1126
+ const p = b - n.iat, P = typeof u == "number" ? u : q(u);
1127
+ if (p - d > P)
1128
+ throw new z('"iat" claim timestamp check failed (too far in the past)', n, "iat", "check_failed");
1129
+ if (p < 0 - d)
1130
+ throw new y('"iat" claim timestamp check failed (it should be in the past)', n, "iat", "check_failed");
1131
+ }
1132
+ return n;
1133
+ }
1134
+ async function Qe(e, t, r) {
1135
+ const n = await Ve(e, t, r);
1136
+ if (n.protectedHeader.crit?.includes("b64") && n.protectedHeader.b64 === !1)
1137
+ throw new te("JWTs MUST NOT use unencoded payload");
1138
+ const a = { payload: Xe(n.protectedHeader, n.payload, r), protectedHeader: n.protectedHeader };
1139
+ return typeof t == "function" ? { ...a, key: n.key } : a;
1140
+ }
1141
+ function Ze(e) {
1142
+ switch (typeof e == "string" && e.slice(0, 2)) {
1143
+ case "RS":
1144
+ case "PS":
1145
+ return "RSA";
1146
+ case "ES":
1147
+ return "EC";
1148
+ case "Ed":
1149
+ return "OKP";
1150
+ case "ML":
1151
+ return "AKP";
1152
+ default:
1153
+ throw new w('Unsupported "alg" value for a JSON Web Key Set');
1154
+ }
1155
+ }
1156
+ function je(e) {
1157
+ return e && typeof e == "object" && Array.isArray(e.keys) && e.keys.every(et);
1158
+ }
1159
+ function et(e) {
1160
+ return E(e);
1161
+ }
1162
+ class tt {
1163
+ #r;
1164
+ #i = /* @__PURE__ */ new WeakMap();
1165
+ constructor(t) {
1166
+ if (!je(t))
1167
+ throw new re("JSON Web Key Set malformed");
1168
+ this.#r = structuredClone(t);
1169
+ }
1170
+ jwks() {
1171
+ return this.#r;
1172
+ }
1173
+ async getKey(t, r) {
1174
+ const { alg: n, kid: s } = { ...t, ...r?.header }, a = Ze(n), i = this.#r.keys.filter((u) => {
1175
+ let o = a === u.kty;
1176
+ if (o && typeof s == "string" && (o = s === u.kid), o && (typeof u.alg == "string" || a === "AKP") && (o = n === u.alg), o && typeof u.use == "string" && (o = u.use === "sig"), o && Array.isArray(u.key_ops) && (o = u.key_ops.includes("verify")), o)
1177
+ switch (n) {
1178
+ case "ES256":
1179
+ o = u.crv === "P-256";
1180
+ break;
1181
+ case "ES384":
1182
+ o = u.crv === "P-384";
1183
+ break;
1184
+ case "ES512":
1185
+ o = u.crv === "P-521";
1186
+ break;
1187
+ case "Ed25519":
1188
+ case "EdDSA":
1189
+ o = u.crv === "Ed25519";
1190
+ break;
1191
+ }
1192
+ return o;
1193
+ }), { 0: c, length: h } = i;
1194
+ if (h === 0)
1195
+ throw new ne();
1196
+ if (h !== 1) {
1197
+ const u = new ge(), o = this.#i;
1198
+ throw u[Symbol.asyncIterator] = async function* () {
1199
+ for (const d of i)
1200
+ try {
1201
+ yield await X(o, d, n);
1202
+ } catch {
1203
+ }
1204
+ }, u;
1205
+ }
1206
+ return X(this.#i, c, n);
1207
+ }
1208
+ }
1209
+ async function X(e, t, r) {
1210
+ const n = e.get(t) || e.set(t, {}).get(t);
1211
+ if (n[r] === void 0) {
1212
+ const s = await We({ ...t, ext: !0 }, r);
1213
+ if (s instanceof Uint8Array || s.type !== "public")
1214
+ throw new re("JSON Web Key Set members must be public keys");
1215
+ n[r] = s;
1216
+ }
1217
+ return n[r];
1218
+ }
1219
+ function Q(e) {
1220
+ const t = new tt(e), r = async (n, s) => t.getKey(n, s);
1221
+ return Object.defineProperties(r, {
1222
+ jwks: {
1223
+ value: () => structuredClone(t.jwks()),
1224
+ enumerable: !1,
1225
+ configurable: !1,
1226
+ writable: !1
1227
+ }
1228
+ }), r;
1229
+ }
1230
+ function rt() {
1231
+ return typeof WebSocketPair < "u" || typeof navigator < "u" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime < "u" && EdgeRuntime === "vercel";
1232
+ }
1233
+ let O;
1234
+ (typeof navigator > "u" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) && (O = "jose/v6.1.3");
1235
+ const nt = /* @__PURE__ */ Symbol();
1236
+ async function st(e, t, r, n = fetch) {
1237
+ const s = await n(e, {
1238
+ method: "GET",
1239
+ signal: r,
1240
+ redirect: "manual",
1241
+ headers: t
1242
+ }).catch((a) => {
1243
+ throw a.name === "TimeoutError" ? new be() : a;
1244
+ });
1245
+ if (s.status !== 200)
1246
+ throw new l("Expected 200 OK from the JSON Web Key Set HTTP response");
1247
+ try {
1248
+ return await s.json();
1249
+ } catch {
1250
+ throw new l("Failed to parse the JSON Web Key Set HTTP response as JSON");
1251
+ }
1252
+ }
1253
+ const U = /* @__PURE__ */ Symbol();
1254
+ function at(e, t) {
1255
+ return !(typeof e != "object" || e === null || !("uat" in e) || typeof e.uat != "number" || Date.now() - e.uat >= t || !("jwks" in e) || !E(e.jwks) || !Array.isArray(e.jwks.keys) || !Array.prototype.every.call(e.jwks.keys, E));
1256
+ }
1257
+ class it {
1258
+ #r;
1259
+ #i;
1260
+ #c;
1261
+ #o;
1262
+ #n;
1263
+ #e;
1264
+ #t;
1265
+ #u;
1266
+ #s;
1267
+ #a;
1268
+ constructor(t, r) {
1269
+ if (!(t instanceof URL))
1270
+ throw new TypeError("url must be an instance of URL");
1271
+ this.#r = new URL(t.href), this.#i = typeof r?.timeoutDuration == "number" ? r?.timeoutDuration : 5e3, this.#c = typeof r?.cooldownDuration == "number" ? r?.cooldownDuration : 3e4, this.#o = typeof r?.cacheMaxAge == "number" ? r?.cacheMaxAge : 6e5, this.#t = new Headers(r?.headers), O && !this.#t.has("User-Agent") && this.#t.set("User-Agent", O), this.#t.has("accept") || (this.#t.set("accept", "application/json"), this.#t.append("accept", "application/jwk-set+json")), this.#u = r?.[nt], r?.[U] !== void 0 && (this.#a = r?.[U], at(r?.[U], this.#o) && (this.#n = this.#a.uat, this.#s = Q(this.#a.jwks)));
1272
+ }
1273
+ pendingFetch() {
1274
+ return !!this.#e;
1275
+ }
1276
+ coolingDown() {
1277
+ return typeof this.#n == "number" ? Date.now() < this.#n + this.#c : !1;
1278
+ }
1279
+ fresh() {
1280
+ return typeof this.#n == "number" ? Date.now() < this.#n + this.#o : !1;
1281
+ }
1282
+ jwks() {
1283
+ return this.#s?.jwks();
1284
+ }
1285
+ async getKey(t, r) {
1286
+ (!this.#s || !this.fresh()) && await this.reload();
1287
+ try {
1288
+ return await this.#s(t, r);
1289
+ } catch (n) {
1290
+ if (n instanceof ne && this.coolingDown() === !1)
1291
+ return await this.reload(), this.#s(t, r);
1292
+ throw n;
1293
+ }
1294
+ }
1295
+ async reload() {
1296
+ this.#e && rt() && (this.#e = void 0), this.#e ||= st(this.#r.href, this.#t, AbortSignal.timeout(this.#i), this.#u).then((t) => {
1297
+ this.#s = Q(t), this.#a && (this.#a.uat = Date.now(), this.#a.jwks = t), this.#n = Date.now(), this.#e = void 0;
1298
+ }).catch((t) => {
1299
+ throw this.#e = void 0, t;
1300
+ }), await this.#e;
1301
+ }
1302
+ }
1303
+ function ot(e, t) {
1304
+ const r = new it(e, t), n = async (s, a) => r.getKey(s, a);
1305
+ return Object.defineProperties(n, {
1306
+ coolingDown: {
1307
+ get: () => r.coolingDown(),
1308
+ enumerable: !0,
1309
+ configurable: !1
1310
+ },
1311
+ fresh: {
1312
+ get: () => r.fresh(),
1313
+ enumerable: !0,
1314
+ configurable: !1
1315
+ },
1316
+ reload: {
1317
+ value: () => r.reload(),
1318
+ enumerable: !0,
1319
+ configurable: !1,
1320
+ writable: !1
1321
+ },
1322
+ reloading: {
1323
+ get: () => r.pendingFetch(),
1324
+ enumerable: !0,
1325
+ configurable: !1
1326
+ },
1327
+ jwks: {
1328
+ value: () => r.jwks(),
1329
+ enumerable: !0,
1330
+ configurable: !1,
1331
+ writable: !1
1332
+ }
1333
+ }), n;
1334
+ }
1335
+ const Z = /* @__PURE__ */ new Map();
1336
+ async function ct(e, t = `${ee}/.well-known/jwks.json`) {
1337
+ let r = Z.get(t);
1338
+ return r || (r = ot(new URL(t)), Z.set(t, r)), Qe(e, r);
1339
+ }
1340
+ class ut {
303
1341
  store = /* @__PURE__ */ new Map();
304
- async get(e) {
305
- return this.store.get(e) ?? null;
1342
+ async get(t) {
1343
+ return this.store.get(t) ?? null;
306
1344
  }
307
- async set(e, t) {
308
- this.store.set(e, t);
1345
+ async set(t, r) {
1346
+ this.store.set(t, r);
309
1347
  }
310
- async remove(e) {
311
- this.store.delete(e);
1348
+ async remove(t) {
1349
+ this.store.delete(t);
312
1350
  }
313
1351
  async clear() {
314
1352
  this.store.clear();
315
1353
  }
316
1354
  }
317
- class T {
1355
+ class j {
318
1356
  prefix;
319
- constructor(e = "genation") {
320
- this.prefix = e;
1357
+ constructor(t = "genation") {
1358
+ this.prefix = t;
321
1359
  }
322
- getKey(e) {
323
- return `${this.prefix}:${e}`;
1360
+ getKey(t) {
1361
+ return `${this.prefix}:${t}`;
324
1362
  }
325
- async get(e) {
326
- return typeof window > "u" ? null : localStorage.getItem(this.getKey(e));
1363
+ async get(t) {
1364
+ return typeof window > "u" ? null : localStorage.getItem(this.getKey(t));
327
1365
  }
328
- async set(e, t) {
329
- typeof window > "u" || localStorage.setItem(this.getKey(e), t);
1366
+ async set(t, r) {
1367
+ typeof window > "u" || localStorage.setItem(this.getKey(t), r);
330
1368
  }
331
- async remove(e) {
332
- typeof window > "u" || localStorage.removeItem(this.getKey(e));
1369
+ async remove(t) {
1370
+ typeof window > "u" || localStorage.removeItem(this.getKey(t));
333
1371
  }
334
1372
  async clear() {
335
1373
  if (typeof window > "u") return;
336
1374
  Object.keys(localStorage).filter(
337
- (t) => t.startsWith(`${this.prefix}:`)
338
- ).forEach((t) => localStorage.removeItem(t));
1375
+ (r) => r.startsWith(`${this.prefix}:`)
1376
+ ).forEach((r) => localStorage.removeItem(r));
339
1377
  }
340
1378
  }
341
- class A {
1379
+ class ht {
342
1380
  prefix;
343
- constructor(e = "genation") {
344
- this.prefix = e;
1381
+ constructor(t = "genation") {
1382
+ this.prefix = t;
345
1383
  }
346
- getKey(e) {
347
- return `${this.prefix}:${e}`;
1384
+ getKey(t) {
1385
+ return `${this.prefix}:${t}`;
348
1386
  }
349
- async get(e) {
350
- return typeof window > "u" ? null : sessionStorage.getItem(this.getKey(e));
1387
+ async get(t) {
1388
+ return typeof window > "u" ? null : sessionStorage.getItem(this.getKey(t));
351
1389
  }
352
- async set(e, t) {
353
- typeof window > "u" || sessionStorage.setItem(this.getKey(e), t);
1390
+ async set(t, r) {
1391
+ typeof window > "u" || sessionStorage.setItem(this.getKey(t), r);
354
1392
  }
355
- async remove(e) {
356
- typeof window > "u" || sessionStorage.removeItem(this.getKey(e));
1393
+ async remove(t) {
1394
+ typeof window > "u" || sessionStorage.removeItem(this.getKey(t));
357
1395
  }
358
1396
  async clear() {
359
1397
  if (typeof window > "u") return;
360
1398
  Object.keys(sessionStorage).filter(
361
- (t) => t.startsWith(`${this.prefix}:`)
362
- ).forEach((t) => sessionStorage.removeItem(t));
1399
+ (r) => r.startsWith(`${this.prefix}:`)
1400
+ ).forEach((r) => sessionStorage.removeItem(r));
363
1401
  }
364
1402
  }
365
- function M(r = "localStorage") {
366
- switch (r) {
1403
+ function ft(e = "localStorage") {
1404
+ switch (e) {
367
1405
  case "memory":
368
- return new E();
1406
+ return new ut();
369
1407
  case "localStorage":
370
- return new T();
1408
+ return new j();
371
1409
  case "sessionStorage":
372
- return new A();
1410
+ return new ht();
373
1411
  default:
374
- return new T();
1412
+ return new j();
375
1413
  }
376
1414
  }
377
- function w(r) {
378
- return Array.isArray(r) ? r.map(w) : typeof r == "object" && r !== null ? Object.fromEntries(
379
- Object.entries(r).map(([e, t]) => [
380
- e.replace(/_([a-z])/g, (s, n) => n.toUpperCase()),
381
- w(t)
1415
+ function H(e) {
1416
+ return Array.isArray(e) ? e.map(H) : typeof e == "object" && e !== null ? Object.fromEntries(
1417
+ Object.entries(e).map(([t, r]) => [
1418
+ t.replace(/_([a-z])/g, (n, s) => s.toUpperCase()),
1419
+ H(r)
382
1420
  ])
383
- ) : r;
1421
+ ) : e;
384
1422
  }
385
- class K {
1423
+ class dt {
386
1424
  oauth;
387
1425
  tokenManager;
1426
+ jwksUrl;
388
1427
  http;
389
1428
  httpServer;
390
1429
  listeners = /* @__PURE__ */ new Set();
391
1430
  initialized = !1;
392
- constructor(e) {
393
- this.validateConfig(e);
394
- const t = typeof e.storage == "object" ? e.storage : M(e.storage);
395
- this.tokenManager = new I(t), this.oauth = new x(e, this.tokenManager), this.http = new p({
396
- baseUrl: e.authUrl ?? "https://mnnoheowoowbtpuoguul.supabase.co/auth/v1"
397
- }), this.httpServer = new p({
1431
+ constructor(t) {
1432
+ this.validateConfig(t);
1433
+ const r = typeof t.storage == "object" ? t.storage : ft(t.storage), n = t.authUrl ?? "https://mnnoheowoowbtpuoguul.supabase.co/auth/v1";
1434
+ this.tokenManager = new ye(r), this.oauth = new me(t, this.tokenManager), this.jwksUrl = `${n}/.well-known/jwks.json`, this.http = new D({
1435
+ baseUrl: n
1436
+ }), this.httpServer = new D({
398
1437
  baseUrl: "https://ff-api.genation.ai/api/v2/client"
399
1438
  });
400
1439
  }
401
- validateConfig(e) {
402
- if (!e.clientId) throw u.missingField("clientId");
403
- if (!e.clientSecret)
404
- throw u.missingField("clientSecret");
405
- if (!e.redirectUri) throw u.missingField("redirectUri");
1440
+ validateConfig(t) {
1441
+ if (!t.clientId) throw v.missingField("clientId");
1442
+ if (!t.clientSecret)
1443
+ throw v.missingField("clientSecret");
1444
+ if (!t.redirectUri) throw v.missingField("redirectUri");
406
1445
  }
407
1446
  /**
408
1447
  * Emit auth state change event to all listeners
409
1448
  */
410
- async emitAuthStateChange(e) {
411
- const t = await this.getSession();
412
- this.listeners.forEach((s) => {
1449
+ async emitAuthStateChange(t) {
1450
+ const r = await this.getSession();
1451
+ this.listeners.forEach((n) => {
413
1452
  try {
414
- s(e, t);
415
- } catch (n) {
416
- console.error("Error in auth state change callback:", n);
1453
+ n(t, r);
1454
+ } catch (s) {
1455
+ console.error("Error in auth state change callback:", s);
417
1456
  }
418
1457
  });
419
1458
  }
@@ -452,15 +1491,15 @@ class K {
452
1491
  * subscription.unsubscribe();
453
1492
  * ```
454
1493
  */
455
- onAuthStateChange(e) {
456
- return this.listeners.add(e), this.initialized ? setTimeout(() => {
1494
+ onAuthStateChange(t) {
1495
+ return this.listeners.add(t), this.initialized ? setTimeout(() => {
457
1496
  this.emitAuthStateChange("INITIAL_SESSION");
458
1497
  }, 0) : (this.initialized = !0, setTimeout(() => {
459
1498
  this.emitAuthStateChange("INITIAL_SESSION");
460
1499
  }, 0)), {
461
1500
  subscription: {
462
1501
  unsubscribe: () => {
463
- this.listeners.delete(e);
1502
+ this.listeners.delete(t);
464
1503
  }
465
1504
  }
466
1505
  };
@@ -506,31 +1545,30 @@ class K {
506
1545
  * }
507
1546
  * ```
508
1547
  */
509
- async handleCallback(e) {
510
- const t = new URL(e), s = t.searchParams.get("code"), n = t.searchParams.get("state");
511
- if (!s || !n)
1548
+ async handleCallback(t) {
1549
+ const r = new URL(t), n = r.searchParams.get("code"), s = r.searchParams.get("state");
1550
+ if (!n || !s)
512
1551
  throw new Error("Missing code or state");
513
- const i = await this.oauth.exchangeCode(s, n);
514
- return await this.emitAuthStateChange("SIGNED_IN"), i;
515
- }
516
- // /**
517
- // * Sign out and revoke tokens
518
- // *
519
- // * Clears local session and revokes tokens on server.
520
- // * Triggers `SIGNED_OUT` event for all listeners.
521
- // *
522
- // * @example
523
- // * ```typescript
524
- // * async function handleLogout() {
525
- // * await client.signOut();
526
- // * // onAuthStateChange will fire with SIGNED_OUT event
527
- // * }
528
- // * ```
529
- // */
530
- // async signOut(): Promise<void> {
531
- // await this.oauth.revokeToken();
532
- // await this.emitAuthStateChange("SIGNED_OUT");
533
- // }
1552
+ const a = await this.oauth.exchangeCode(n, s);
1553
+ return await this.emitAuthStateChange("SIGNED_IN"), a;
1554
+ }
1555
+ /**
1556
+ * Sign out and revoke tokens
1557
+ *
1558
+ * Clears local session.
1559
+ * Triggers `SIGNED_OUT` event for all listeners.
1560
+ *
1561
+ * @example
1562
+ * ```typescript
1563
+ * async function handleLogout() {
1564
+ * await client.signOut();
1565
+ * // onAuthStateChange will fire with SIGNED_OUT event
1566
+ * }
1567
+ * ```
1568
+ */
1569
+ async signOut() {
1570
+ await this.tokenManager.clearTokens(), await this.emitAuthStateChange("SIGNED_OUT");
1571
+ }
534
1572
  /**
535
1573
  * Get current session
536
1574
  *
@@ -559,17 +1597,30 @@ class K {
559
1597
  } catch {
560
1598
  return null;
561
1599
  }
562
- const t = await this.tokenManager.getTokens();
563
- if (!t) return null;
564
- const s = await this.fetchUser(t.accessToken);
1600
+ const r = await this.tokenManager.getTokens();
1601
+ if (!r) return null;
1602
+ const n = await this.fetchUser(r.accessToken);
565
1603
  return {
566
- accessToken: t.accessToken,
567
- refreshToken: t.refreshToken,
568
- expiresIn: t.expiresIn,
569
- expiresAt: t.issuedAt + t.expiresIn * 1e3,
570
- user: s
1604
+ accessToken: r.accessToken,
1605
+ refreshToken: r.refreshToken,
1606
+ expiresIn: r.expiresIn,
1607
+ expiresAt: r.issuedAt + r.expiresIn * 1e3,
1608
+ user: n
571
1609
  };
572
1610
  }
1611
+ /**
1612
+ * Verify a JWT token
1613
+ *
1614
+ * Validates the token signature using the public JWKS.
1615
+ *
1616
+ * @param token - JWT token to verify
1617
+ * @returns Decoded token payload if valid
1618
+ * @throws Error if token is invalid
1619
+ */
1620
+ async verifyToken(t) {
1621
+ const { payload: r } = await ct(t, this.jwksUrl);
1622
+ return r;
1623
+ }
573
1624
  /**
574
1625
  * Get licenses
575
1626
  * @param accessToken - The access token to use for the request
@@ -577,51 +1628,52 @@ class K {
577
1628
  * @param options.expiresAfter - Query licenses that are expired after the given date, default set to today to get all valid licenses (unexpired licenses)
578
1629
  * @returns The licenses
579
1630
  */
580
- async getLicenses(e = {}) {
581
- const t = await this.getSession();
582
- if (!t)
1631
+ async getLicenses(t = {}) {
1632
+ const r = await this.getSession();
1633
+ if (!r)
583
1634
  return null;
584
- const s = t.accessToken, { expiresAfter: n = /* @__PURE__ */ new Date() } = e, i = await this.httpServer.request("/licenses", {
585
- headers: { Authorization: `Bearer ${s}` },
586
- params: { expiresAfter: n.toISOString() }
1635
+ const n = r.accessToken, { expiresAfter: s = /* @__PURE__ */ new Date() } = t, a = await this.httpServer.request("/licenses", {
1636
+ headers: { Authorization: `Bearer ${n}` },
1637
+ params: { expiresAfter: s.toISOString() }
587
1638
  });
588
- return i.ok ? w(i.data) : (console.error("GenationClient: Error fetching licenses:", i.error), null);
1639
+ return a.ok ? H(a.data) : (console.error("GenationClient: Error fetching licenses:", a.error), null);
589
1640
  }
590
1641
  /**
591
1642
  * Fetch user info from auth server
592
1643
  */
593
- async fetchUser(e) {
1644
+ async fetchUser(t) {
594
1645
  try {
595
- const t = await this.http.request("/oauth/userinfo", {
596
- headers: { Authorization: `Bearer ${e}` }
1646
+ const r = await this.http.request("/oauth/userinfo", {
1647
+ headers: { Authorization: `Bearer ${t}` }
597
1648
  });
598
1649
  return {
599
- sub: t.sub,
600
- name: t.name,
601
- picture: t.picture,
602
- email: t.email,
603
- email_verified: t.email_verified,
604
- phone_number: t.phone_number,
605
- phone_number_verified: t.phone_number_verified
1650
+ sub: r.sub,
1651
+ name: r.name,
1652
+ picture: r.picture,
1653
+ email: r.email,
1654
+ email_verified: r.email_verified,
1655
+ phone_number: r.phone_number,
1656
+ phone_number_verified: r.phone_number_verified
606
1657
  };
607
- } catch (t) {
608
- return console.error("GenationClient: Error fetching user:", t), null;
1658
+ } catch (r) {
1659
+ return console.error("GenationClient: Error fetching user:", r), null;
609
1660
  }
610
1661
  }
611
1662
  }
612
- function $(r) {
613
- return new K(r);
1663
+ function lt(e) {
1664
+ return new dt(e);
614
1665
  }
615
1666
  export {
616
- l as AuthError,
617
- u as ConfigError,
618
- K as GenationClient,
619
- m as GenationError,
620
- T as LocalStorage,
621
- E as MemoryStorage,
622
- h as NetworkError,
623
- A as SessionStorage,
624
- $ as createClient,
625
- M as createStorage
1667
+ g as AuthError,
1668
+ v as ConfigError,
1669
+ dt as GenationClient,
1670
+ N as GenationError,
1671
+ j as LocalStorage,
1672
+ ut as MemoryStorage,
1673
+ S as NetworkError,
1674
+ ht as SessionStorage,
1675
+ lt as createClient,
1676
+ ft as createStorage,
1677
+ ct as verifyToken
626
1678
  };
627
1679
  //# sourceMappingURL=genation.es.js.map