@crossauth/frontend 0.0.5 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,47 +1,39 @@
1
- var __defProp = Object.defineProperty;
2
- var __typeError = (msg) => {
3
- throw TypeError(msg);
1
+ var Ie = Object.defineProperty;
2
+ var ce = (r) => {
3
+ throw TypeError(r);
4
4
  };
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
8
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
9
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
- var _accessToken, _refreshToken, _idTokenPayload, _accessTokenPayload, _refreshTokenPayload, _client_id, _client_secret;
12
- var fe = Object.defineProperty;
13
- var G = (e) => {
14
- throw TypeError(e);
15
- };
16
- var pe = (e, t, r) => t in e ? fe(e, t, { enumerable: true, configurable: true, writable: true, value: r }) : e[t] = r;
17
- var a = (e, t, r) => pe(e, typeof t != "symbol" ? t + "" : t, r), Y = (e, t, r) => t.has(e) || G("Cannot " + r);
18
- var u = (e, t, r) => (Y(e, t, "read from private field"), r ? r.call(e) : t.get(e)), O = (e, t, r) => t.has(e) ? G("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, r), _ = (e, t, r, n) => (Y(e, t, "write to private field"), t.set(e, r), r);
19
- class k {
5
+ var Ue = (r, e, t) => e in r ? Ie(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
6
+ var f = (r, e, t) => Ue(r, typeof e != "symbol" ? e + "" : e, t), de = (r, e, t) => e.has(r) || ce("Cannot " + t);
7
+ var w = (r, e, t) => (de(r, e, "read from private field"), t ? t.call(r) : e.get(r)), N = (r, e, t) => e.has(r) ? ce("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t), b = (r, e, t, o) => (de(r, e, "write to private field"), o ? o.call(r, t) : e.set(r, t), t);
8
+ var Oe = Object.defineProperty, ge = (r) => {
9
+ throw TypeError(r);
10
+ }, Ne = (r, e, t) => e in r ? Oe(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t, l = (r, e, t) => Ne(r, typeof e != "symbol" ? e + "" : e, t), pe = (r, e, t) => e.has(r) || ge("Cannot " + t), p = (r, e, t) => (pe(r, e, "read from private field"), t ? t.call(r) : e.get(r)), $ = (r, e, t) => e.has(r) ? ge("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t), A = (r, e, t, o) => (pe(r, e, "write to private field"), e.set(r, t), t);
11
+ class H {
20
12
  }
21
- a(k, "active", "active"), /** Deactivated account. User cannot log in */
22
- a(k, "disabled", "disabled"), /** Two factor authentication has been actived for this user
13
+ l(H, "active", "active"), /** Deactivated account. User cannot log in */
14
+ l(H, "disabled", "disabled"), /** Two factor authentication has been actived for this user
23
15
  * but has not yet been configured. Once a user logs in,
24
16
  * they will be directed to a page to configure 2FA and will
25
17
  * not be able to do anything else (that requires login) until
26
18
  * they have done so.
27
19
  */
28
- a(k, "awaitingTwoFactorSetup", "awaitingtwofactorsetup"), /** Email verification has been turned on but user has not
20
+ l(H, "awaitingTwoFactorSetup", "awaitingtwofactorsetup"), /** Email verification has been turned on but user has not
29
21
  * verified his or her email address. Cannot log on until it has
30
22
  * been verified.
31
23
  */
32
- a(k, "awaitingEmailVerification", "awaitingemailverification"), /**
24
+ l(H, "awaitingEmailVerification", "awaitingemailverification"), /**
33
25
  * If the state is set to this, the user may not access any
34
26
  * login-required functions unless he or she has changed their password.
35
27
  *
36
28
  * Upon login, the user is redirected to the change password page.
37
29
  */
38
- a(k, "passwordChangeNeeded", "passwordchangeneeded"), /**
30
+ l(H, "passwordChangeNeeded", "passwordchangeneeded"), /**
39
31
  * If the state is set to this, the user may not access any
40
32
  * login-required functions unless he or she has reset their password.
41
33
  *
42
34
  * Upon login, the user is redirected to the reset password page.
43
35
  */
44
- a(k, "passwordResetNeeded", "passwordresetneeded"), /**
36
+ l(H, "passwordResetNeeded", "passwordresetneeded"), /**
45
37
  * If the state is set to this, the user may not access any
46
38
  * login-required functions unless he or she has reset their second
47
39
  * factor configuration.
@@ -52,27 +44,27 @@ a(k, "passwordResetNeeded", "passwordresetneeded"), /**
52
44
  * this value and the user will then be prompted to configure 2FA
53
45
  * upon login.
54
46
  */
55
- a(k, "factor2ResetNeeded", "factor2resetneeded"), /**
47
+ l(H, "factor2ResetNeeded", "factor2resetneeded"), /**
56
48
  * If the state is set to this, the user may not access any
57
49
  * login-required functions unless he or she has reset their password
58
50
  * and then resets factor2.
59
51
  *
60
52
  * Upon login, the user is redirected to the reset password page.
61
53
  */
62
- a(k, "passwordAndFactor2ResetNeeded", "passwordandfactor2resetneeded");
63
- class C {
54
+ l(H, "passwordAndFactor2ResetNeeded", "passwordandfactor2resetneeded");
55
+ class P {
64
56
  }
65
- a(C, "session", "s:"), /** Password Reset Token */
66
- a(C, "passwordResetToken", "p:"), /** Email verification token */
67
- a(C, "emailVerificationToken", "e:"), /** API key */
68
- a(C, "apiKey", "api:"), /** OAuth authorization code */
69
- a(C, "authorizationCode", "authz:"), /** OAuth access token */
70
- a(C, "accessToken", "access:"), /** OAuth refresh token */
71
- a(C, "refreshToken", "refresh:"), /** OAuth MFA key (used by the password MFA flow) */
72
- a(C, "mfaToken", "omfa:"), /** Device code device code */
73
- a(C, "deviceCode", "dc:"), /** Device code flow user code */
74
- a(C, "userCode", "uc:");
75
- var y = /* @__PURE__ */ ((e) => (e[e.UserNotExist = 0] = "UserNotExist", e[e.PasswordInvalid = 1] = "PasswordInvalid", e[e.EmailNotExist = 2] = "EmailNotExist", e[e.UsernameOrPasswordInvalid = 3] = "UsernameOrPasswordInvalid", e[e.InvalidClientId = 4] = "InvalidClientId", e[e.ClientExists = 5] = "ClientExists", e[e.InvalidClientSecret = 6] = "InvalidClientSecret", e[e.InvalidClientIdOrSecret = 7] = "InvalidClientIdOrSecret", e[e.InvalidRedirectUri = 8] = "InvalidRedirectUri", e[e.InvalidOAuthFlow = 9] = "InvalidOAuthFlow", e[e.UserNotActive = 10] = "UserNotActive", e[e.EmailNotVerified = 11] = "EmailNotVerified", e[e.TwoFactorIncomplete = 12] = "TwoFactorIncomplete", e[e.Unauthorized = 13] = "Unauthorized", e[e.UnauthorizedClient = 14] = "UnauthorizedClient", e[e.InvalidScope = 15] = "InvalidScope", e[e.InsufficientScope = 16] = "InsufficientScope", e[e.InsufficientPriviledges = 17] = "InsufficientPriviledges", e[e.Forbidden = 18] = "Forbidden", e[e.InvalidKey = 19] = "InvalidKey", e[e.InvalidCsrf = 20] = "InvalidCsrf", e[e.InvalidSession = 21] = "InvalidSession", e[e.Expired = 22] = "Expired", e[e.Connection = 23] = "Connection", e[e.InvalidHash = 24] = "InvalidHash", e[e.UnsupportedAlgorithm = 25] = "UnsupportedAlgorithm", e[e.KeyExists = 26] = "KeyExists", e[e.PasswordChangeNeeded = 27] = "PasswordChangeNeeded", e[e.PasswordResetNeeded = 28] = "PasswordResetNeeded", e[e.Factor2ResetNeeded = 29] = "Factor2ResetNeeded", e[e.Configuration = 30] = "Configuration", e[e.InvalidEmail = 31] = "InvalidEmail", e[e.InvalidPhoneNumber = 32] = "InvalidPhoneNumber", e[e.InvalidUsername = 33] = "InvalidUsername", e[e.PasswordMatch = 34] = "PasswordMatch", e[e.InvalidToken = 35] = "InvalidToken", e[e.MfaRequired = 36] = "MfaRequired", e[e.PasswordFormat = 37] = "PasswordFormat", e[e.DataFormat = 38] = "DataFormat", e[e.FetchError = 39] = "FetchError", e[e.UserExists = 40] = "UserExists", e[e.FormEntry = 41] = "FormEntry", e[e.BadRequest = 42] = "BadRequest", e[e.AuthorizationPending = 43] = "AuthorizationPending", e[e.SlowDown = 44] = "SlowDown", e[e.ExpiredToken = 45] = "ExpiredToken", e[e.ConstraintViolation = 46] = "ConstraintViolation", e[e.NotImplemented = 47] = "NotImplemented", e[e.UnknownError = 48] = "UnknownError", e))(y || {});
57
+ l(P, "session", "s:"), /** Password Reset Token */
58
+ l(P, "passwordResetToken", "p:"), /** Email verification token */
59
+ l(P, "emailVerificationToken", "e:"), /** API key */
60
+ l(P, "apiKey", "api:"), /** OAuth authorization code */
61
+ l(P, "authorizationCode", "authz:"), /** OAuth access token */
62
+ l(P, "accessToken", "access:"), /** OAuth refresh token */
63
+ l(P, "refreshToken", "refresh:"), /** OAuth MFA key (used by the password MFA flow) */
64
+ l(P, "mfaToken", "omfa:"), /** Device code device code */
65
+ l(P, "deviceCode", "dc:"), /** Device code flow user code */
66
+ l(P, "userCode", "uc:");
67
+ var m = /* @__PURE__ */ ((r) => (r[r.UserNotExist = 0] = "UserNotExist", r[r.PasswordInvalid = 1] = "PasswordInvalid", r[r.EmailNotExist = 2] = "EmailNotExist", r[r.UsernameOrPasswordInvalid = 3] = "UsernameOrPasswordInvalid", r[r.InvalidClientId = 4] = "InvalidClientId", r[r.ClientExists = 5] = "ClientExists", r[r.InvalidClientSecret = 6] = "InvalidClientSecret", r[r.InvalidClientIdOrSecret = 7] = "InvalidClientIdOrSecret", r[r.InvalidRedirectUri = 8] = "InvalidRedirectUri", r[r.InvalidOAuthFlow = 9] = "InvalidOAuthFlow", r[r.UserNotActive = 10] = "UserNotActive", r[r.EmailNotVerified = 11] = "EmailNotVerified", r[r.TwoFactorIncomplete = 12] = "TwoFactorIncomplete", r[r.Unauthorized = 13] = "Unauthorized", r[r.UnauthorizedClient = 14] = "UnauthorizedClient", r[r.InvalidScope = 15] = "InvalidScope", r[r.InsufficientScope = 16] = "InsufficientScope", r[r.InsufficientPriviledges = 17] = "InsufficientPriviledges", r[r.Forbidden = 18] = "Forbidden", r[r.InvalidKey = 19] = "InvalidKey", r[r.InvalidCsrf = 20] = "InvalidCsrf", r[r.InvalidSession = 21] = "InvalidSession", r[r.Expired = 22] = "Expired", r[r.Connection = 23] = "Connection", r[r.InvalidHash = 24] = "InvalidHash", r[r.UnsupportedAlgorithm = 25] = "UnsupportedAlgorithm", r[r.KeyExists = 26] = "KeyExists", r[r.PasswordChangeNeeded = 27] = "PasswordChangeNeeded", r[r.PasswordResetNeeded = 28] = "PasswordResetNeeded", r[r.Factor2ResetNeeded = 29] = "Factor2ResetNeeded", r[r.Configuration = 30] = "Configuration", r[r.InvalidEmail = 31] = "InvalidEmail", r[r.InvalidPhoneNumber = 32] = "InvalidPhoneNumber", r[r.InvalidUsername = 33] = "InvalidUsername", r[r.PasswordMatch = 34] = "PasswordMatch", r[r.InvalidToken = 35] = "InvalidToken", r[r.MfaRequired = 36] = "MfaRequired", r[r.PasswordFormat = 37] = "PasswordFormat", r[r.DataFormat = 38] = "DataFormat", r[r.FetchError = 39] = "FetchError", r[r.UserExists = 40] = "UserExists", r[r.FormEntry = 41] = "FormEntry", r[r.BadRequest = 42] = "BadRequest", r[r.AuthorizationPending = 43] = "AuthorizationPending", r[r.SlowDown = 44] = "SlowDown", r[r.ExpiredToken = 45] = "ExpiredToken", r[r.ConstraintViolation = 46] = "ConstraintViolation", r[r.NotImplemented = 47] = "NotImplemented", r[r.UnknownError = 48] = "UnknownError", r))(m || {});
76
68
  class g extends Error {
77
69
  /**
78
70
  * Creates a new error to throw,
@@ -80,16 +72,9 @@ class g extends Error {
80
72
  * @param code describes the type of error
81
73
  * @param message if provided, this error will display. Otherwise a default one for the error code will be used.
82
74
  */
83
- constructor(r, n = void 0) {
84
- let i, s = 500;
85
- r == 0 ? (i = "User does not exist", s = 401) : r == 1 ? (i = "Password doesn't match", s = 401) : r == 3 ? (i = "Username or password incorrect", s = 401) : r == 4 ? (i = "Client id is invalid", s = 401) : r == 5 ? (i = "Client ID or name already exists", s = 500) : r == 6 ? (i = "Client secret is invalid", s = 401) : r == 7 ? (i = "Client id or secret is invalid", s = 401) : r == 8 ? (i = "Redirect Uri is not registered", s = 401) : r == 9 ? (i = "Invalid OAuth flow type", s = 500) : r == 2 ? (i = "No user exists with that email address", s = 401) : r == 10 ? (i = "Account is not active", s = 403) : r == 33 ? (i = "Username is not in an allowed format", s = 400) : r == 31 ? (i = "Email is not in an allowed format", s = 400) : r == 32 ? (i = "Phone number is not in an allowed format", s = 400) : r == 11 ? (i = "Email address has not been verified", s = 403) : r == 12 ? (i = "Two-factor setup is not complete", s = 403) : r == 13 ? (i = "Not authorized", s = 401) : r == 14 ? (i = "Client not authorized", s = 401) : r == 15 ? (i = "Invalid scope", s = 403) : r == 16 ? (i = "Insufficient scope", s = 403) : r == 23 ? i = "Connection failure" : r == 22 ? (i = "Token has expired", s = 401) : r == 24 ? i = "Hash is not in a valid format" : r == 19 ? (i = "Key is invalid", s = 401) : r == 18 ? (i = "You do not have permission to access this resource", s = 403) : r == 17 ? (i = "You do not have the right privileges to access this resource", s = 401) : r == 20 ? (i = "CSRF token is invalid", s = 401) : r == 21 ? (i = "Session cookie is invalid", s = 401) : r == 25 ? i = "Algorithm not supported" : r == 26 ? i = "Attempt to create a key that already exists" : r == 27 ? (i = "User must change password", s = 403) : r == 28 ? (i = "User must reset password", s = 403) : r == 29 ? (i = "User must reset 2FA", s = 403) : r == 30 ? i = "There was an error in the configuration" : r == 34 ? (i = "Passwords do not match", s = 401) : r == 35 ? (i = "Token is not valid", s = 401) : r == 36 ? (i = "MFA is required", s = 401) : r == 37 ? (i = "Password format was incorrect", s = 401) : r == 40 ? (i = "User already exists", s = 400) : r == 42 ? (i = "The request is invalid", s = 400) : r == 38 ? (i = "Session data has unexpected format", s = 500) : r == 39 ? (i = "Couldn't execute a fetch", s = 500) : r == 43 ? (i = "Waiting for authorization", s = 200) : r == 44 ? (i = "Slow polling down by 5 seconds", s = 200) : r == 45 ? (i = "Token has expired", s = 401) : r == 46 ? (i = "Database update/insert caused a constraint violation", s = 500) : r == 47 ? (i = "This method has not been implemented", s = 500) : (i = "Unknown error", s = 500), n != null && !Array.isArray(n) ? i = n : Array.isArray(n) && (i = n.join(". "));
86
- super(i);
87
- a(this, "isCrossauthError", true);
88
- a(this, "httpStatus");
89
- a(this, "code");
90
- a(this, "codeName");
91
- a(this, "messages");
92
- this.code = r, this.codeName = y[r], this.httpStatus = s, this.name = "CrossauthError", Array.isArray(n) ? this.messages = n : this.messages = [i], Object.setPrototypeOf(this, g.prototype);
75
+ constructor(e, t = void 0) {
76
+ let o, s = 500;
77
+ e == 0 ? (o = "User does not exist", s = 401) : e == 1 ? (o = "Password doesn't match", s = 401) : e == 3 ? (o = "Username or password incorrect", s = 401) : e == 4 ? (o = "Client id is invalid", s = 401) : e == 5 ? (o = "Client ID or name already exists", s = 500) : e == 6 ? (o = "Client secret is invalid", s = 401) : e == 7 ? (o = "Client id or secret is invalid", s = 401) : e == 8 ? (o = "Redirect Uri is not registered", s = 401) : e == 9 ? (o = "Invalid OAuth flow type", s = 500) : e == 2 ? (o = "No user exists with that email address", s = 401) : e == 10 ? (o = "Account is not active", s = 403) : e == 33 ? (o = "Username is not in an allowed format", s = 400) : e == 31 ? (o = "Email is not in an allowed format", s = 400) : e == 32 ? (o = "Phone number is not in an allowed format", s = 400) : e == 11 ? (o = "Email address has not been verified", s = 403) : e == 12 ? (o = "Two-factor setup is not complete", s = 403) : e == 13 ? (o = "Not authorized", s = 401) : e == 14 ? (o = "Client not authorized", s = 401) : e == 15 ? (o = "Invalid scope", s = 403) : e == 16 ? (o = "Insufficient scope", s = 403) : e == 23 ? o = "Connection failure" : e == 22 ? (o = "Token has expired", s = 401) : e == 24 ? o = "Hash is not in a valid format" : e == 19 ? (o = "Key is invalid", s = 401) : e == 18 ? (o = "You do not have permission to access this resource", s = 403) : e == 17 ? (o = "You do not have the right privileges to access this resource", s = 401) : e == 20 ? (o = "CSRF token is invalid", s = 401) : e == 21 ? (o = "Session cookie is invalid", s = 401) : e == 25 ? o = "Algorithm not supported" : e == 26 ? o = "Attempt to create a key that already exists" : e == 27 ? (o = "User must change password", s = 403) : e == 28 ? (o = "User must reset password", s = 403) : e == 29 ? (o = "User must reset 2FA", s = 403) : e == 30 ? o = "There was an error in the configuration" : e == 34 ? (o = "Passwords do not match", s = 401) : e == 35 ? (o = "Token is not valid", s = 401) : e == 36 ? (o = "MFA is required", s = 401) : e == 37 ? (o = "Password format was incorrect", s = 401) : e == 40 ? (o = "User already exists", s = 400) : e == 42 ? (o = "The request is invalid", s = 400) : e == 38 ? (o = "Session data has unexpected format", s = 500) : e == 39 ? (o = "Couldn't execute a fetch", s = 500) : e == 43 ? (o = "Waiting for authorization", s = 200) : e == 44 ? (o = "Slow polling down by 5 seconds", s = 200) : e == 45 ? (o = "Token has expired", s = 401) : e == 46 ? (o = "Database update/insert caused a constraint violation", s = 500) : e == 47 ? (o = "This method has not been implemented", s = 500) : (o = "Unknown error", s = 500), t != null && !Array.isArray(t) ? o = t : Array.isArray(t) && (o = t.join(". ")), super(o), l(this, "isCrossauthError", !0), l(this, "httpStatus"), l(this, "code"), l(this, "codeName"), l(this, "messages"), this.code = e, this.codeName = m[e], this.httpStatus = s, this.name = "CrossauthError", Array.isArray(t) ? this.messages = t : this.messages = [o], Object.setPrototypeOf(this, g.prototype);
93
78
  }
94
79
  /**
95
80
  * OAuth defines certain error types. To convert the error in an OAuth
@@ -99,52 +84,52 @@ class g extends Error {
99
84
  * @param error_description as returned by an OAuth call (put in the `message`)
100
85
  * @returns a `CrossauthError` instance.
101
86
  */
102
- static fromOAuthError(r, n) {
103
- let i;
104
- switch (r) {
87
+ static fromOAuthError(e, t) {
88
+ let o;
89
+ switch (e) {
105
90
  case "invalid_request":
106
- i = 42;
91
+ o = 42;
107
92
  break;
108
93
  case "unauthorized_client":
109
- i = 14;
94
+ o = 14;
110
95
  break;
111
96
  case "access_denied":
112
- i = 13;
97
+ o = 13;
113
98
  break;
114
99
  case "unsupported_response_type":
115
- i = 42;
100
+ o = 42;
116
101
  break;
117
102
  case "invalid_scope":
118
- i = 15;
103
+ o = 15;
119
104
  break;
120
105
  case "server_error":
121
- i = 48;
106
+ o = 48;
122
107
  break;
123
108
  case "temporarily_unavailable":
124
- i = 23;
109
+ o = 23;
125
110
  break;
126
111
  case "invalid_token":
127
- i = 35;
112
+ o = 35;
128
113
  break;
129
114
  case "expired_token":
130
- i = 45;
115
+ o = 45;
131
116
  break;
132
117
  case "insufficient_scope":
133
- i = 35;
118
+ o = 35;
134
119
  break;
135
120
  case "mfa_required":
136
- i = 36;
121
+ o = 36;
137
122
  break;
138
123
  case "authorization_pending":
139
- i = 43;
124
+ o = 43;
140
125
  break;
141
126
  case "slow_down":
142
- i = 44;
127
+ o = 44;
143
128
  break;
144
129
  default:
145
- i = 48;
130
+ o = 48;
146
131
  }
147
- return new g(i, n);
132
+ return new g(o, t);
148
133
  }
149
134
  get oauthErrorCode() {
150
135
  switch (this.code) {
@@ -185,38 +170,37 @@ class g extends Error {
185
170
  * @param e the error to convert.
186
171
  * @returns a `CrossauthError` instance.
187
172
  */
188
- static asCrossauthError(r, n) {
189
- if (r instanceof Error)
190
- return "isCrossauthError" in r ? r : new g(48, r.message);
191
- if ("errorCode" in r) {
173
+ static asCrossauthError(e, t) {
174
+ if (e instanceof Error)
175
+ return "isCrossauthError" in e ? e : new g(48, e.message);
176
+ if ("errorCode" in e) {
192
177
  let s = 48;
193
178
  try {
194
- s = Number(r.errorCode) ?? 48;
179
+ s = Number(e.errorCode) ?? 48;
195
180
  } catch {
196
181
  }
197
- let o = n ?? y[s];
198
- return "errorMessage" in r ? o = r.errorMessage : "message" in r && (o = r.message), new g(s, o);
182
+ let n = t ?? m[s];
183
+ return "errorMessage" in e ? n = e.errorMessage : "message" in e && (n = e.message), new g(s, n);
199
184
  }
200
- let i = n ?? y[
185
+ let o = t ?? m[
201
186
  48
202
187
  /* UnknownError */
203
188
  ];
204
- return "message" in r && (i = r.message), new g(48, i);
189
+ return "message" in e && (o = e.message), new g(48, o);
205
190
  }
206
191
  }
207
- const m = class m2 {
192
+ const W = class E {
208
193
  /**
209
194
  * Create a logger with the given level
210
195
  * @param level the level to report to
211
196
  */
212
- constructor(t) {
213
- a(this, "level");
214
- if (t) this.level = t;
197
+ constructor(e) {
198
+ if (l(this, "level"), e) this.level = e;
215
199
  else if (typeof process < "u" && "CROSSAUTH_LOG_LEVEL" in process.env) {
216
- const r = (process.env.CROSSAUTH_LOG_LEVEL ?? "ERROR").toUpperCase();
217
- m2.levelName.includes(r) ? this.level = m2.levelName.indexOf(r) : this.level = m2.Error;
200
+ const t = (process.env.CROSSAUTH_LOG_LEVEL ?? "ERROR").toUpperCase();
201
+ E.levelName.includes(t) ? this.level = E.levelName.indexOf(t) : this.level = E.Error;
218
202
  } else
219
- this.level = m2.Error;
203
+ this.level = E.Error;
220
204
  }
221
205
  /**
222
206
  * Return the singleton instance of the logger.
@@ -225,39 +209,39 @@ const m = class m2 {
225
209
  static get logger() {
226
210
  return globalThis.crossauthLogger;
227
211
  }
228
- setLevel(t) {
229
- this.level = t;
212
+ setLevel(e) {
213
+ this.level = e;
230
214
  }
231
- log(t, r) {
232
- t <= this.level && (typeof r == "string" ? console.log("Crossauth " + m2.levelName[t] + " " + (/* @__PURE__ */ new Date()).toISOString(), r) : console.log(JSON.stringify({ level: m2.levelName[t], time: (/* @__PURE__ */ new Date()).toISOString(), ...r })));
215
+ log(e, t) {
216
+ e <= this.level && (typeof t == "string" ? console.log("Crossauth " + E.levelName[e] + " " + (/* @__PURE__ */ new Date()).toISOString(), t) : console.log(JSON.stringify({ level: E.levelName[e], time: (/* @__PURE__ */ new Date()).toISOString(), ...t })));
233
217
  }
234
218
  /**
235
219
  * Report an error
236
220
  * @param output object to output
237
221
  */
238
- error(t) {
239
- this.log(m2.Error, t);
222
+ error(e) {
223
+ this.log(E.Error, e);
240
224
  }
241
225
  /**
242
226
  * Report an warning
243
227
  * @param output object to output
244
228
  */
245
- warn(t) {
246
- this.log(m2.Warn, t);
229
+ warn(e) {
230
+ this.log(E.Warn, e);
247
231
  }
248
232
  /**
249
233
  * Report information
250
234
  * @param output object to output
251
235
  */
252
- info(t) {
253
- this.log(m2.Info, t);
236
+ info(e) {
237
+ this.log(E.Info, e);
254
238
  }
255
239
  /**
256
240
  * Print a debugging message
257
241
  * @param output object to output
258
242
  */
259
- debug(t) {
260
- this.log(m2.Debug, t);
243
+ debug(e) {
244
+ this.log(E.Debug, e);
261
245
  }
262
246
  /**
263
247
  * Override the default logger.
@@ -269,40 +253,40 @@ const m = class m2 {
269
253
  * @param logger a new logger instance of any supported class
270
254
  * @param acceptsJson set this to false if the logger can only take strings.
271
255
  */
272
- static setLogger(t, r) {
273
- globalThis.crossauthLogger = t, globalThis.crossauthLoggerAcceptsJson = r;
256
+ static setLogger(e, t) {
257
+ globalThis.crossauthLogger = e, globalThis.crossauthLoggerAcceptsJson = t;
274
258
  }
275
259
  };
276
- a(m, "None", 0), /** Only log errors */
277
- a(m, "Error", 1), /** Log errors and warning */
278
- a(m, "Warn", 2), /** Log errors, warnings and info messages */
279
- a(m, "Info", 3), /** Log everything */
280
- a(m, "Debug", 4), a(m, "levelName", ["NONE", "ERROR", "WARN", "INFO", "DEBUG"]);
281
- let d = m;
282
- function h(e) {
283
- let t;
284
- typeof e == "object" && "err" in e && typeof e.err == "object" && (t = e.err.stack);
260
+ l(W, "None", 0), /** Only log errors */
261
+ l(W, "Error", 1), /** Log errors and warning */
262
+ l(W, "Warn", 2), /** Log errors, warnings and info messages */
263
+ l(W, "Info", 3), /** Log everything */
264
+ l(W, "Debug", 4), l(W, "levelName", ["NONE", "ERROR", "WARN", "INFO", "DEBUG"]);
265
+ let c = W;
266
+ function d(r) {
267
+ let e;
268
+ typeof r == "object" && "err" in r && typeof r.err == "object" && (e = r.err.stack);
285
269
  try {
286
- typeof e == "object" && "err" in e && typeof e.err == "object" && e.err && "message" in e.err && !("msg" in e) && (e.msg = e.err.message);
270
+ typeof r == "object" && "err" in r && typeof r.err == "object" && r.err && "message" in r.err && !("msg" in r) && (r.msg = r.err.message);
287
271
  } catch {
288
272
  }
289
273
  try {
290
- typeof e == "object" && "err" in e && typeof e.err == "object" && (e.err = { ...e.err, stack: t });
274
+ typeof r == "object" && "err" in r && typeof r.err == "object" && (r.err = { ...r.err, stack: e });
291
275
  } catch {
292
276
  }
293
277
  try {
294
- typeof e == "object" && "err" in e && !("msg" in e) && (e.msg = e.msg = "An unknown error occurred");
278
+ typeof r == "object" && "err" in r && !("msg" in r) && (r.msg = r.msg = "An unknown error occurred");
295
279
  } catch {
296
280
  }
297
281
  try {
298
- typeof e == "object" && "cerr" in e && "isCrossauthError" in e.cerr && e.cerr && (e.errorCode = e.cerr.code, e.errorCodeName = e.cerr.codeName, e.httpStatus = e.cerr.httpStatus, "msg" in e || (e.msg = e.cerr.message), delete e.cerr);
282
+ typeof r == "object" && "cerr" in r && "isCrossauthError" in r.cerr && r.cerr && (r.errorCode = r.cerr.code, r.errorCodeName = r.cerr.codeName, r.httpStatus = r.cerr.httpStatus, "msg" in r || (r.msg = r.cerr.message), delete r.cerr);
299
283
  } catch {
300
284
  }
301
- return typeof e == "string" || globalThis.crossauthLoggerAcceptsJson ? e : JSON.stringify(e);
285
+ return typeof r == "string" || globalThis.crossauthLoggerAcceptsJson ? r : JSON.stringify(r);
302
286
  }
303
- globalThis.crossauthLogger = new d(d.None);
304
- globalThis.crossauthLoggerAcceptsJson = true;
305
- const te = {
287
+ globalThis.crossauthLogger = new c(c.None);
288
+ globalThis.crossauthLoggerAcceptsJson = !0;
289
+ const ye = {
306
290
  issuer: "",
307
291
  authorization_endpoint: "",
308
292
  token_endpoint: "",
@@ -313,42 +297,42 @@ const te = {
313
297
  grant_types_supported: ["authorization_code", "implicit"],
314
298
  id_token_signing_alg_values_supported: [],
315
299
  claim_types_supported: ["normal"],
316
- claims_parameter_supported: false,
317
- request_parameter_supported: false,
318
- request_uri_parameter_supported: true,
319
- require_request_uri_registration: false
320
- }, F = crypto, re = (e) => e instanceof CryptoKey, H = new TextEncoder(), z = new TextDecoder();
321
- function ge(...e) {
322
- const t = e.reduce((i, { length: s }) => i + s, 0), r = new Uint8Array(t);
323
- let n = 0;
324
- for (const i of e)
325
- r.set(i, n), n += i.length;
326
- return r;
300
+ claims_parameter_supported: !1,
301
+ request_parameter_supported: !1,
302
+ request_uri_parameter_supported: !0,
303
+ require_request_uri_registration: !1
304
+ }, te = crypto, we = (r) => r instanceof CryptoKey, X = new TextEncoder(), G = new TextDecoder();
305
+ function He(...r) {
306
+ const e = r.reduce((s, { length: n }) => s + n, 0), t = new Uint8Array(e);
307
+ let o = 0;
308
+ for (const s of r)
309
+ t.set(s, o), o += s.length;
310
+ return t;
327
311
  }
328
- const ye = (e) => {
329
- const t = atob(e), r = new Uint8Array(t.length);
330
- for (let n = 0; n < t.length; n++)
331
- r[n] = t.charCodeAt(n);
332
- return r;
333
- }, K = (e) => {
334
- let t = e;
335
- t instanceof Uint8Array && (t = z.decode(t)), t = t.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
312
+ const xe = (r) => {
313
+ const e = atob(r), t = new Uint8Array(e.length);
314
+ for (let o = 0; o < e.length; o++)
315
+ t[o] = e.charCodeAt(o);
316
+ return t;
317
+ }, M = (r) => {
318
+ let e = r;
319
+ e instanceof Uint8Array && (e = G.decode(e)), e = e.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
336
320
  try {
337
- return ye(t);
321
+ return xe(e);
338
322
  } catch {
339
323
  throw new TypeError("The input to be decoded is not correctly encoded.");
340
324
  }
341
325
  };
342
- class $ extends Error {
326
+ class oe extends Error {
343
327
  static get code() {
344
328
  return "ERR_JOSE_GENERIC";
345
329
  }
346
- constructor(t) {
347
- var r;
348
- super(t), this.code = "ERR_JOSE_GENERIC", this.name = this.constructor.name, (r = Error.captureStackTrace) == null || r.call(Error, this, this.constructor);
330
+ constructor(e) {
331
+ var t;
332
+ super(e), this.code = "ERR_JOSE_GENERIC", this.name = this.constructor.name, (t = Error.captureStackTrace) == null || t.call(Error, this, this.constructor);
349
333
  }
350
334
  }
351
- class b extends $ {
335
+ class I extends oe {
352
336
  constructor() {
353
337
  super(...arguments), this.code = "ERR_JOSE_NOT_SUPPORTED";
354
338
  }
@@ -356,7 +340,7 @@ class b extends $ {
356
340
  return "ERR_JOSE_NOT_SUPPORTED";
357
341
  }
358
342
  }
359
- class v extends $ {
343
+ class S extends oe {
360
344
  constructor() {
361
345
  super(...arguments), this.code = "ERR_JWS_INVALID";
362
346
  }
@@ -364,7 +348,7 @@ class v extends $ {
364
348
  return "ERR_JWS_INVALID";
365
349
  }
366
350
  }
367
- class E extends $ {
351
+ class D extends oe {
368
352
  constructor() {
369
353
  super(...arguments), this.code = "ERR_JWT_INVALID";
370
354
  }
@@ -372,7 +356,7 @@ class E extends $ {
372
356
  return "ERR_JWT_INVALID";
373
357
  }
374
358
  }
375
- class me extends $ {
359
+ class je extends oe {
376
360
  constructor() {
377
361
  super(...arguments), this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED", this.message = "signature verification failed";
378
362
  }
@@ -380,17 +364,17 @@ class me extends $ {
380
364
  return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
381
365
  }
382
366
  }
383
- function A(e, t = "algorithm.name") {
384
- return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);
367
+ function U(r, e = "algorithm.name") {
368
+ return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`);
385
369
  }
386
- function J(e, t) {
387
- return e.name === t;
370
+ function Q(r, e) {
371
+ return r.name === e;
388
372
  }
389
- function L(e) {
390
- return parseInt(e.name.slice(4), 10);
373
+ function se(r) {
374
+ return parseInt(r.name.slice(4), 10);
391
375
  }
392
- function we(e) {
393
- switch (e) {
376
+ function Ke(r) {
377
+ switch (r) {
394
378
  case "ES256":
395
379
  return "P-256";
396
380
  case "ES384":
@@ -401,523 +385,523 @@ function we(e) {
401
385
  throw new Error("unreachable");
402
386
  }
403
387
  }
404
- function ve(e, t) {
405
- if (t.length && !t.some((r) => e.usages.includes(r))) {
406
- let r = "CryptoKey does not support this operation, its usages must include ";
407
- if (t.length > 2) {
408
- const n = t.pop();
409
- r += `one of ${t.join(", ")}, or ${n}.`;
410
- } else t.length === 2 ? r += `one of ${t[0]} or ${t[1]}.` : r += `${t[0]}.`;
411
- throw new TypeError(r);
388
+ function ze(r, e) {
389
+ if (e.length && !e.some((t) => r.usages.includes(t))) {
390
+ let t = "CryptoKey does not support this operation, its usages must include ";
391
+ if (e.length > 2) {
392
+ const o = e.pop();
393
+ t += `one of ${e.join(", ")}, or ${o}.`;
394
+ } else e.length === 2 ? t += `one of ${e[0]} or ${e[1]}.` : t += `${e[0]}.`;
395
+ throw new TypeError(t);
412
396
  }
413
397
  }
414
- function Se(e, t, ...r) {
415
- switch (t) {
398
+ function De(r, e, ...t) {
399
+ switch (e) {
416
400
  case "HS256":
417
401
  case "HS384":
418
402
  case "HS512": {
419
- if (!J(e.algorithm, "HMAC"))
420
- throw A("HMAC");
421
- const n = parseInt(t.slice(2), 10);
422
- if (L(e.algorithm.hash) !== n)
423
- throw A(`SHA-${n}`, "algorithm.hash");
403
+ if (!Q(r.algorithm, "HMAC"))
404
+ throw U("HMAC");
405
+ const o = parseInt(e.slice(2), 10);
406
+ if (se(r.algorithm.hash) !== o)
407
+ throw U(`SHA-${o}`, "algorithm.hash");
424
408
  break;
425
409
  }
426
410
  case "RS256":
427
411
  case "RS384":
428
412
  case "RS512": {
429
- if (!J(e.algorithm, "RSASSA-PKCS1-v1_5"))
430
- throw A("RSASSA-PKCS1-v1_5");
431
- const n = parseInt(t.slice(2), 10);
432
- if (L(e.algorithm.hash) !== n)
433
- throw A(`SHA-${n}`, "algorithm.hash");
413
+ if (!Q(r.algorithm, "RSASSA-PKCS1-v1_5"))
414
+ throw U("RSASSA-PKCS1-v1_5");
415
+ const o = parseInt(e.slice(2), 10);
416
+ if (se(r.algorithm.hash) !== o)
417
+ throw U(`SHA-${o}`, "algorithm.hash");
434
418
  break;
435
419
  }
436
420
  case "PS256":
437
421
  case "PS384":
438
422
  case "PS512": {
439
- if (!J(e.algorithm, "RSA-PSS"))
440
- throw A("RSA-PSS");
441
- const n = parseInt(t.slice(2), 10);
442
- if (L(e.algorithm.hash) !== n)
443
- throw A(`SHA-${n}`, "algorithm.hash");
423
+ if (!Q(r.algorithm, "RSA-PSS"))
424
+ throw U("RSA-PSS");
425
+ const o = parseInt(e.slice(2), 10);
426
+ if (se(r.algorithm.hash) !== o)
427
+ throw U(`SHA-${o}`, "algorithm.hash");
444
428
  break;
445
429
  }
446
430
  case "EdDSA": {
447
- if (e.algorithm.name !== "Ed25519" && e.algorithm.name !== "Ed448")
448
- throw A("Ed25519 or Ed448");
431
+ if (r.algorithm.name !== "Ed25519" && r.algorithm.name !== "Ed448")
432
+ throw U("Ed25519 or Ed448");
449
433
  break;
450
434
  }
451
435
  case "ES256":
452
436
  case "ES384":
453
437
  case "ES512": {
454
- if (!J(e.algorithm, "ECDSA"))
455
- throw A("ECDSA");
456
- const n = we(t);
457
- if (e.algorithm.namedCurve !== n)
458
- throw A(n, "algorithm.namedCurve");
438
+ if (!Q(r.algorithm, "ECDSA"))
439
+ throw U("ECDSA");
440
+ const o = Ke(e);
441
+ if (r.algorithm.namedCurve !== o)
442
+ throw U(o, "algorithm.namedCurve");
459
443
  break;
460
444
  }
461
445
  default:
462
446
  throw new TypeError("CryptoKey does not support this operation");
463
447
  }
464
- ve(e, r);
448
+ ze(r, t);
465
449
  }
466
- function ie(e, t, ...r) {
467
- var n;
468
- if (r.length > 2) {
469
- const i = r.pop();
470
- e += `one of type ${r.join(", ")}, or ${i}.`;
471
- } else r.length === 2 ? e += `one of type ${r[0]} or ${r[1]}.` : e += `of type ${r[0]}.`;
472
- return t == null ? e += ` Received ${t}` : typeof t == "function" && t.name ? e += ` Received function ${t.name}` : typeof t == "object" && t != null && (n = t.constructor) != null && n.name && (e += ` Received an instance of ${t.constructor.name}`), e;
450
+ function me(r, e, ...t) {
451
+ var o;
452
+ if (t.length > 2) {
453
+ const s = t.pop();
454
+ r += `one of type ${t.join(", ")}, or ${s}.`;
455
+ } else t.length === 2 ? r += `one of type ${t[0]} or ${t[1]}.` : r += `of type ${t[0]}.`;
456
+ return e == null ? r += ` Received ${e}` : typeof e == "function" && e.name ? r += ` Received function ${e.name}` : typeof e == "object" && e != null && (o = e.constructor) != null && o.name && (r += ` Received an instance of ${e.constructor.name}`), r;
473
457
  }
474
- const X = (e, ...t) => ie("Key must be ", e, ...t);
475
- function ne(e, t, ...r) {
476
- return ie(`Key for the ${e} algorithm must be `, t, ...r);
458
+ const he = (r, ...e) => me("Key must be ", r, ...e);
459
+ function ve(r, e, ...t) {
460
+ return me(`Key for the ${r} algorithm must be `, e, ...t);
477
461
  }
478
- const se = (e) => re(e) ? true : (e == null ? void 0 : e[Symbol.toStringTag]) === "KeyObject", M = ["CryptoKey"], _e = (...e) => {
479
- const t = e.filter(Boolean);
480
- if (t.length === 0 || t.length === 1)
481
- return true;
482
- let r;
483
- for (const n of t) {
484
- const i = Object.keys(n);
485
- if (!r || r.size === 0) {
486
- r = new Set(i);
462
+ const Ce = (r) => we(r) ? !0 : (r == null ? void 0 : r[Symbol.toStringTag]) === "KeyObject", re = ["CryptoKey"], We = (...r) => {
463
+ const e = r.filter(Boolean);
464
+ if (e.length === 0 || e.length === 1)
465
+ return !0;
466
+ let t;
467
+ for (const o of e) {
468
+ const s = Object.keys(o);
469
+ if (!t || t.size === 0) {
470
+ t = new Set(s);
487
471
  continue;
488
472
  }
489
- for (const s of i) {
490
- if (r.has(s))
491
- return false;
492
- r.add(s);
473
+ for (const n of s) {
474
+ if (t.has(n))
475
+ return !1;
476
+ t.add(n);
493
477
  }
494
478
  }
495
- return true;
479
+ return !0;
496
480
  };
497
- function Ce(e) {
498
- return typeof e == "object" && e !== null;
481
+ function Fe(r) {
482
+ return typeof r == "object" && r !== null;
499
483
  }
500
- function x(e) {
501
- if (!Ce(e) || Object.prototype.toString.call(e) !== "[object Object]")
502
- return false;
503
- if (Object.getPrototypeOf(e) === null)
504
- return true;
505
- let t = e;
506
- for (; Object.getPrototypeOf(t) !== null; )
507
- t = Object.getPrototypeOf(t);
508
- return Object.getPrototypeOf(e) === t;
484
+ function V(r) {
485
+ if (!Fe(r) || Object.prototype.toString.call(r) !== "[object Object]")
486
+ return !1;
487
+ if (Object.getPrototypeOf(r) === null)
488
+ return !0;
489
+ let e = r;
490
+ for (; Object.getPrototypeOf(e) !== null; )
491
+ e = Object.getPrototypeOf(e);
492
+ return Object.getPrototypeOf(r) === e;
509
493
  }
510
- const be = (e, t) => {
511
- if (e.startsWith("RS") || e.startsWith("PS")) {
512
- const { modulusLength: r } = t.algorithm;
513
- if (typeof r != "number" || r < 2048)
514
- throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`);
494
+ const Je = (r, e) => {
495
+ if (r.startsWith("RS") || r.startsWith("PS")) {
496
+ const { modulusLength: t } = e.algorithm;
497
+ if (typeof t != "number" || t < 2048)
498
+ throw new TypeError(`${r} requires key modulusLength to be 2048 bits or larger`);
515
499
  }
516
500
  };
517
- function Ae(e) {
518
- let t, r;
519
- switch (e.kty) {
501
+ function Me(r) {
502
+ let e, t;
503
+ switch (r.kty) {
520
504
  case "RSA": {
521
- switch (e.alg) {
505
+ switch (r.alg) {
522
506
  case "PS256":
523
507
  case "PS384":
524
508
  case "PS512":
525
- t = { name: "RSA-PSS", hash: `SHA-${e.alg.slice(-3)}` }, r = e.d ? ["sign"] : ["verify"];
509
+ e = { name: "RSA-PSS", hash: `SHA-${r.alg.slice(-3)}` }, t = r.d ? ["sign"] : ["verify"];
526
510
  break;
527
511
  case "RS256":
528
512
  case "RS384":
529
513
  case "RS512":
530
- t = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${e.alg.slice(-3)}` }, r = e.d ? ["sign"] : ["verify"];
514
+ e = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${r.alg.slice(-3)}` }, t = r.d ? ["sign"] : ["verify"];
531
515
  break;
532
516
  case "RSA-OAEP":
533
517
  case "RSA-OAEP-256":
534
518
  case "RSA-OAEP-384":
535
519
  case "RSA-OAEP-512":
536
- t = {
520
+ e = {
537
521
  name: "RSA-OAEP",
538
- hash: `SHA-${parseInt(e.alg.slice(-3), 10) || 1}`
539
- }, r = e.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
522
+ hash: `SHA-${parseInt(r.alg.slice(-3), 10) || 1}`
523
+ }, t = r.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
540
524
  break;
541
525
  default:
542
- throw new b('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
526
+ throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
543
527
  }
544
528
  break;
545
529
  }
546
530
  case "EC": {
547
- switch (e.alg) {
531
+ switch (r.alg) {
548
532
  case "ES256":
549
- t = { name: "ECDSA", namedCurve: "P-256" }, r = e.d ? ["sign"] : ["verify"];
533
+ e = { name: "ECDSA", namedCurve: "P-256" }, t = r.d ? ["sign"] : ["verify"];
550
534
  break;
551
535
  case "ES384":
552
- t = { name: "ECDSA", namedCurve: "P-384" }, r = e.d ? ["sign"] : ["verify"];
536
+ e = { name: "ECDSA", namedCurve: "P-384" }, t = r.d ? ["sign"] : ["verify"];
553
537
  break;
554
538
  case "ES512":
555
- t = { name: "ECDSA", namedCurve: "P-521" }, r = e.d ? ["sign"] : ["verify"];
539
+ e = { name: "ECDSA", namedCurve: "P-521" }, t = r.d ? ["sign"] : ["verify"];
556
540
  break;
557
541
  case "ECDH-ES":
558
542
  case "ECDH-ES+A128KW":
559
543
  case "ECDH-ES+A192KW":
560
544
  case "ECDH-ES+A256KW":
561
- t = { name: "ECDH", namedCurve: e.crv }, r = e.d ? ["deriveBits"] : [];
545
+ e = { name: "ECDH", namedCurve: r.crv }, t = r.d ? ["deriveBits"] : [];
562
546
  break;
563
547
  default:
564
- throw new b('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
548
+ throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
565
549
  }
566
550
  break;
567
551
  }
568
552
  case "OKP": {
569
- switch (e.alg) {
553
+ switch (r.alg) {
570
554
  case "EdDSA":
571
- t = { name: e.crv }, r = e.d ? ["sign"] : ["verify"];
555
+ e = { name: r.crv }, t = r.d ? ["sign"] : ["verify"];
572
556
  break;
573
557
  case "ECDH-ES":
574
558
  case "ECDH-ES+A128KW":
575
559
  case "ECDH-ES+A192KW":
576
560
  case "ECDH-ES+A256KW":
577
- t = { name: e.crv }, r = e.d ? ["deriveBits"] : [];
561
+ e = { name: r.crv }, t = r.d ? ["deriveBits"] : [];
578
562
  break;
579
563
  default:
580
- throw new b('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
564
+ throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
581
565
  }
582
566
  break;
583
567
  }
584
568
  default:
585
- throw new b('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
569
+ throw new I('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
586
570
  }
587
- return { algorithm: t, keyUsages: r };
571
+ return { algorithm: e, keyUsages: t };
588
572
  }
589
- const oe = async (e) => {
590
- if (!e.alg)
573
+ const ke = async (r) => {
574
+ if (!r.alg)
591
575
  throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
592
- const { algorithm: t, keyUsages: r } = Ae(e), n = [
593
- t,
594
- e.ext ?? false,
595
- e.key_ops ?? r
596
- ], i = { ...e };
597
- return delete i.alg, delete i.use, F.subtle.importKey("jwk", i, ...n);
598
- }, ae = (e) => K(e);
599
- let V, j;
600
- const ce = (e) => (e == null ? void 0 : e[Symbol.toStringTag]) === "KeyObject", de = async (e, t, r, n) => {
601
- let i = e.get(t);
602
- if (i != null && i[n])
603
- return i[n];
604
- const s = await oe({ ...r, alg: n });
605
- return i ? i[n] = s : e.set(t, { [n]: s }), s;
606
- }, Pe = (e, t) => {
607
- if (ce(e)) {
608
- let r = e.export({ format: "jwk" });
609
- return delete r.d, delete r.dp, delete r.dq, delete r.p, delete r.q, delete r.qi, r.k ? ae(r.k) : (j || (j = /* @__PURE__ */ new WeakMap()), de(j, e, r, t));
610
- }
611
- return e;
612
- }, ke = (e, t) => {
613
- if (ce(e)) {
614
- let r = e.export({ format: "jwk" });
615
- return r.k ? ae(r.k) : (V || (V = /* @__PURE__ */ new WeakMap()), de(V, e, r, t));
616
- }
617
- return e;
618
- }, Ie = { normalizePublicKey: Pe, normalizePrivateKey: ke }, I = (e, t, r = 0) => {
619
- r === 0 && (t.unshift(t.length), t.unshift(6));
620
- const n = e.indexOf(t[0], r);
621
- if (n === -1)
622
- return false;
623
- const i = e.subarray(n, n + t.length);
624
- return i.length !== t.length ? false : i.every((s, o) => s === t[o]) || I(e, t, n + 1);
625
- }, Q = (e) => {
626
- switch (true) {
627
- case I(e, [42, 134, 72, 206, 61, 3, 1, 7]):
576
+ const { algorithm: e, keyUsages: t } = Me(r), o = [
577
+ e,
578
+ r.ext ?? !1,
579
+ r.key_ops ?? t
580
+ ], s = { ...r };
581
+ return delete s.alg, delete s.use, te.subtle.importKey("jwk", s, ...o);
582
+ }, Se = (r) => M(r);
583
+ let ie, ne;
584
+ const _e = (r) => (r == null ? void 0 : r[Symbol.toStringTag]) === "KeyObject", Te = async (r, e, t, o) => {
585
+ let s = r.get(e);
586
+ if (s != null && s[o])
587
+ return s[o];
588
+ const n = await ke({ ...t, alg: o });
589
+ return s ? s[o] = n : r.set(e, { [o]: n }), n;
590
+ }, Be = (r, e) => {
591
+ if (_e(r)) {
592
+ let t = r.export({ format: "jwk" });
593
+ return delete t.d, delete t.dp, delete t.dq, delete t.p, delete t.q, delete t.qi, t.k ? Se(t.k) : (ne || (ne = /* @__PURE__ */ new WeakMap()), Te(ne, r, t, e));
594
+ }
595
+ return r;
596
+ }, Le = (r, e) => {
597
+ if (_e(r)) {
598
+ let t = r.export({ format: "jwk" });
599
+ return t.k ? Se(t.k) : (ie || (ie = /* @__PURE__ */ new WeakMap()), Te(ie, r, t, e));
600
+ }
601
+ return r;
602
+ }, $e = { normalizePublicKey: Be, normalizePrivateKey: Le }, x = (r, e, t = 0) => {
603
+ t === 0 && (e.unshift(e.length), e.unshift(6));
604
+ const o = r.indexOf(e[0], t);
605
+ if (o === -1)
606
+ return !1;
607
+ const s = r.subarray(o, o + e.length);
608
+ return s.length !== e.length ? !1 : s.every((n, i) => n === e[i]) || x(r, e, o + 1);
609
+ }, le = (r) => {
610
+ switch (!0) {
611
+ case x(r, [42, 134, 72, 206, 61, 3, 1, 7]):
628
612
  return "P-256";
629
- case I(e, [43, 129, 4, 0, 34]):
613
+ case x(r, [43, 129, 4, 0, 34]):
630
614
  return "P-384";
631
- case I(e, [43, 129, 4, 0, 35]):
615
+ case x(r, [43, 129, 4, 0, 35]):
632
616
  return "P-521";
633
- case I(e, [43, 101, 110]):
617
+ case x(r, [43, 101, 110]):
634
618
  return "X25519";
635
- case I(e, [43, 101, 111]):
619
+ case x(r, [43, 101, 111]):
636
620
  return "X448";
637
- case I(e, [43, 101, 112]):
621
+ case x(r, [43, 101, 112]):
638
622
  return "Ed25519";
639
- case I(e, [43, 101, 113]):
623
+ case x(r, [43, 101, 113]):
640
624
  return "Ed448";
641
625
  default:
642
- throw new b("Invalid or unsupported EC Key Curve or OKP Key Sub Type");
626
+ throw new I("Invalid or unsupported EC Key Curve or OKP Key Sub Type");
643
627
  }
644
- }, le = async (e, t, r, n, i) => {
645
- let s, o;
646
- const l = new Uint8Array(atob(r.replace(e, "")).split("").map((p) => p.charCodeAt(0))), f = t === "spki";
647
- switch (n) {
628
+ }, be = async (r, e, t, o, s) => {
629
+ let n, i;
630
+ const a = new Uint8Array(atob(t.replace(r, "")).split("").map((u) => u.charCodeAt(0))), h = e === "spki";
631
+ switch (o) {
648
632
  case "PS256":
649
633
  case "PS384":
650
634
  case "PS512":
651
- s = { name: "RSA-PSS", hash: `SHA-${n.slice(-3)}` }, o = f ? ["verify"] : ["sign"];
635
+ n = { name: "RSA-PSS", hash: `SHA-${o.slice(-3)}` }, i = h ? ["verify"] : ["sign"];
652
636
  break;
653
637
  case "RS256":
654
638
  case "RS384":
655
639
  case "RS512":
656
- s = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${n.slice(-3)}` }, o = f ? ["verify"] : ["sign"];
640
+ n = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${o.slice(-3)}` }, i = h ? ["verify"] : ["sign"];
657
641
  break;
658
642
  case "RSA-OAEP":
659
643
  case "RSA-OAEP-256":
660
644
  case "RSA-OAEP-384":
661
645
  case "RSA-OAEP-512":
662
- s = {
646
+ n = {
663
647
  name: "RSA-OAEP",
664
- hash: `SHA-${parseInt(n.slice(-3), 10) || 1}`
665
- }, o = f ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
648
+ hash: `SHA-${parseInt(o.slice(-3), 10) || 1}`
649
+ }, i = h ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
666
650
  break;
667
651
  case "ES256":
668
- s = { name: "ECDSA", namedCurve: "P-256" }, o = f ? ["verify"] : ["sign"];
652
+ n = { name: "ECDSA", namedCurve: "P-256" }, i = h ? ["verify"] : ["sign"];
669
653
  break;
670
654
  case "ES384":
671
- s = { name: "ECDSA", namedCurve: "P-384" }, o = f ? ["verify"] : ["sign"];
655
+ n = { name: "ECDSA", namedCurve: "P-384" }, i = h ? ["verify"] : ["sign"];
672
656
  break;
673
657
  case "ES512":
674
- s = { name: "ECDSA", namedCurve: "P-521" }, o = f ? ["verify"] : ["sign"];
658
+ n = { name: "ECDSA", namedCurve: "P-521" }, i = h ? ["verify"] : ["sign"];
675
659
  break;
676
660
  case "ECDH-ES":
677
661
  case "ECDH-ES+A128KW":
678
662
  case "ECDH-ES+A192KW":
679
663
  case "ECDH-ES+A256KW": {
680
- const p = Q(l);
681
- s = p.startsWith("P-") ? { name: "ECDH", namedCurve: p } : { name: p }, o = f ? [] : ["deriveBits"];
664
+ const u = le(a);
665
+ n = u.startsWith("P-") ? { name: "ECDH", namedCurve: u } : { name: u }, i = h ? [] : ["deriveBits"];
682
666
  break;
683
667
  }
684
668
  case "EdDSA":
685
- s = { name: Q(l) }, o = f ? ["verify"] : ["sign"];
669
+ n = { name: le(a) }, i = h ? ["verify"] : ["sign"];
686
670
  break;
687
671
  default:
688
- throw new b('Invalid or unsupported "alg" (Algorithm) value');
672
+ throw new I('Invalid or unsupported "alg" (Algorithm) value');
689
673
  }
690
- return F.subtle.importKey(t, l, s, false, o);
691
- }, Te = (e, t, r) => le(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", e, t), Re = (e, t, r) => le(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", e, t);
692
- async function Ee(e, t, r) {
693
- if (typeof e != "string" || e.indexOf("-----BEGIN PUBLIC KEY-----") !== 0)
674
+ return te.subtle.importKey(e, a, n, !1, i);
675
+ }, qe = (r, e, t) => be(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", r, e), Ve = (r, e, t) => be(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", r, e);
676
+ async function Ge(r, e, t) {
677
+ if (typeof r != "string" || r.indexOf("-----BEGIN PUBLIC KEY-----") !== 0)
694
678
  throw new TypeError('"spki" must be SPKI formatted string');
695
- return Re(e, t);
679
+ return Ve(r, e);
696
680
  }
697
- async function Oe(e, t, r) {
698
- if (typeof e != "string" || e.indexOf("-----BEGIN PRIVATE KEY-----") !== 0)
681
+ async function Ye(r, e, t) {
682
+ if (typeof r != "string" || r.indexOf("-----BEGIN PRIVATE KEY-----") !== 0)
699
683
  throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
700
- return Te(e, t);
684
+ return qe(r, e);
701
685
  }
702
- async function Z(e, t) {
703
- if (!x(e))
686
+ async function ue(r, e) {
687
+ if (!V(r))
704
688
  throw new TypeError("JWK must be an object");
705
- switch (t || (t = e.alg), e.kty) {
689
+ switch (e || (e = r.alg), r.kty) {
706
690
  case "oct":
707
- if (typeof e.k != "string" || !e.k)
691
+ if (typeof r.k != "string" || !r.k)
708
692
  throw new TypeError('missing "k" (Key Value) Parameter value');
709
- return K(e.k);
693
+ return M(r.k);
710
694
  case "RSA":
711
- if (e.oth !== void 0)
712
- throw new b('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
695
+ if (r.oth !== void 0)
696
+ throw new I('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
713
697
  case "EC":
714
698
  case "OKP":
715
- return oe({ ...e, alg: t });
699
+ return ke({ ...r, alg: e });
716
700
  default:
717
- throw new b('Unsupported "kty" (Key Type) Parameter value');
701
+ throw new I('Unsupported "kty" (Key Type) Parameter value');
718
702
  }
719
703
  }
720
- const q = (e) => e == null ? void 0 : e[Symbol.toStringTag], Ke = (e, t) => {
721
- if (!(t instanceof Uint8Array)) {
722
- if (!se(t))
723
- throw new TypeError(ne(e, t, ...M, "Uint8Array"));
724
- if (t.type !== "secret")
725
- throw new TypeError(`${q(t)} instances for symmetric algorithms must be of type "secret"`);
726
- }
727
- }, Ne = (e, t, r) => {
728
- if (!se(t))
729
- throw new TypeError(ne(e, t, ...M));
730
- if (t.type === "secret")
731
- throw new TypeError(`${q(t)} instances for asymmetric algorithms must not be of type "secret"`);
732
- if (t.algorithm && r === "verify" && t.type === "private")
733
- throw new TypeError(`${q(t)} instances for asymmetric algorithm verifying must be of type "public"`);
734
- if (t.algorithm && r === "encrypt" && t.type === "private")
735
- throw new TypeError(`${q(t)} instances for asymmetric algorithm encryption must be of type "public"`);
736
- }, Ue = (e, t, r) => {
737
- e.startsWith("HS") || e === "dir" || e.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(e) ? Ke(e, t) : Ne(e, t, r);
704
+ const ee = (r) => r == null ? void 0 : r[Symbol.toStringTag], Xe = (r, e) => {
705
+ if (!(e instanceof Uint8Array)) {
706
+ if (!Ce(e))
707
+ throw new TypeError(ve(r, e, ...re, "Uint8Array"));
708
+ if (e.type !== "secret")
709
+ throw new TypeError(`${ee(e)} instances for symmetric algorithms must be of type "secret"`);
710
+ }
711
+ }, Qe = (r, e, t) => {
712
+ if (!Ce(e))
713
+ throw new TypeError(ve(r, e, ...re));
714
+ if (e.type === "secret")
715
+ throw new TypeError(`${ee(e)} instances for asymmetric algorithms must not be of type "secret"`);
716
+ if (e.algorithm && t === "verify" && e.type === "private")
717
+ throw new TypeError(`${ee(e)} instances for asymmetric algorithm verifying must be of type "public"`);
718
+ if (e.algorithm && t === "encrypt" && e.type === "private")
719
+ throw new TypeError(`${ee(e)} instances for asymmetric algorithm encryption must be of type "public"`);
720
+ }, Ze = (r, e, t) => {
721
+ r.startsWith("HS") || r === "dir" || r.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(r) ? Xe(r, e) : Qe(r, e, t);
738
722
  };
739
- function xe(e, t, r, n, i) {
740
- if (i.crit !== void 0 && (n == null ? void 0 : n.crit) === void 0)
741
- throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');
742
- if (!n || n.crit === void 0)
723
+ function er(r, e, t, o, s) {
724
+ if (s.crit !== void 0 && (o == null ? void 0 : o.crit) === void 0)
725
+ throw new r('"crit" (Critical) Header Parameter MUST be integrity protected');
726
+ if (!o || o.crit === void 0)
743
727
  return /* @__PURE__ */ new Set();
744
- if (!Array.isArray(n.crit) || n.crit.length === 0 || n.crit.some((o) => typeof o != "string" || o.length === 0))
745
- throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
746
- let s;
747
- s = t;
748
- for (const o of n.crit) {
749
- if (!s.has(o))
750
- throw new b(`Extension Header Parameter "${o}" is not recognized`);
751
- if (i[o] === void 0)
752
- throw new e(`Extension Header Parameter "${o}" is missing`);
753
- if (s.get(o) && n[o] === void 0)
754
- throw new e(`Extension Header Parameter "${o}" MUST be integrity protected`);
755
- }
756
- return new Set(n.crit);
728
+ if (!Array.isArray(o.crit) || o.crit.length === 0 || o.crit.some((i) => typeof i != "string" || i.length === 0))
729
+ throw new r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
730
+ let n;
731
+ n = e;
732
+ for (const i of o.crit) {
733
+ if (!n.has(i))
734
+ throw new I(`Extension Header Parameter "${i}" is not recognized`);
735
+ if (s[i] === void 0)
736
+ throw new r(`Extension Header Parameter "${i}" is missing`);
737
+ if (n.get(i) && o[i] === void 0)
738
+ throw new r(`Extension Header Parameter "${i}" MUST be integrity protected`);
739
+ }
740
+ return new Set(o.crit);
757
741
  }
758
- function ze(e, t) {
759
- const r = `SHA-${e.slice(-3)}`;
760
- switch (e) {
742
+ function rr(r, e) {
743
+ const t = `SHA-${r.slice(-3)}`;
744
+ switch (r) {
761
745
  case "HS256":
762
746
  case "HS384":
763
747
  case "HS512":
764
- return { hash: r, name: "HMAC" };
748
+ return { hash: t, name: "HMAC" };
765
749
  case "PS256":
766
750
  case "PS384":
767
751
  case "PS512":
768
- return { hash: r, name: "RSA-PSS", saltLength: e.slice(-3) >> 3 };
752
+ return { hash: t, name: "RSA-PSS", saltLength: r.slice(-3) >> 3 };
769
753
  case "RS256":
770
754
  case "RS384":
771
755
  case "RS512":
772
- return { hash: r, name: "RSASSA-PKCS1-v1_5" };
756
+ return { hash: t, name: "RSASSA-PKCS1-v1_5" };
773
757
  case "ES256":
774
758
  case "ES384":
775
759
  case "ES512":
776
- return { hash: r, name: "ECDSA", namedCurve: t.namedCurve };
760
+ return { hash: t, name: "ECDSA", namedCurve: e.namedCurve };
777
761
  case "EdDSA":
778
- return { name: t.name };
762
+ return { name: e.name };
779
763
  default:
780
- throw new b(`alg ${e} is not supported either by JOSE or your javascript runtime`);
764
+ throw new I(`alg ${r} is not supported either by JOSE or your javascript runtime`);
781
765
  }
782
766
  }
783
- async function We(e, t, r) {
784
- if (t = await Ie.normalizePublicKey(t, e), re(t))
785
- return Se(t, e, r), t;
786
- if (t instanceof Uint8Array) {
787
- if (!e.startsWith("HS"))
788
- throw new TypeError(X(t, ...M));
789
- return F.subtle.importKey("raw", t, { hash: `SHA-${e.slice(-3)}`, name: "HMAC" }, false, [r]);
790
- }
791
- throw new TypeError(X(t, ...M, "Uint8Array"));
767
+ async function tr(r, e, t) {
768
+ if (e = await $e.normalizePublicKey(e, r), we(e))
769
+ return De(e, r, t), e;
770
+ if (e instanceof Uint8Array) {
771
+ if (!r.startsWith("HS"))
772
+ throw new TypeError(he(e, ...re));
773
+ return te.subtle.importKey("raw", e, { hash: `SHA-${r.slice(-3)}`, name: "HMAC" }, !1, [t]);
774
+ }
775
+ throw new TypeError(he(e, ...re, "Uint8Array"));
792
776
  }
793
- const De = async (e, t, r, n) => {
794
- const i = await We(e, t, "verify");
795
- be(e, i);
796
- const s = ze(e, i.algorithm);
777
+ const or = async (r, e, t, o) => {
778
+ const s = await tr(r, e, "verify");
779
+ Je(r, s);
780
+ const n = rr(r, s.algorithm);
797
781
  try {
798
- return await F.subtle.verify(s, i, r, n);
782
+ return await te.subtle.verify(n, s, t, o);
799
783
  } catch {
800
- return false;
784
+ return !1;
801
785
  }
802
786
  };
803
- async function He(e, t, r) {
804
- if (!x(e))
805
- throw new v("Flattened JWS must be an object");
806
- if (e.protected === void 0 && e.header === void 0)
807
- throw new v('Flattened JWS must have either of the "protected" or "header" members');
808
- if (e.protected !== void 0 && typeof e.protected != "string")
809
- throw new v("JWS Protected Header incorrect type");
810
- if (e.payload === void 0)
811
- throw new v("JWS Payload missing");
812
- if (typeof e.signature != "string")
813
- throw new v("JWS Signature missing or incorrect type");
814
- if (e.header !== void 0 && !x(e.header))
815
- throw new v("JWS Unprotected Header incorrect type");
816
- let n = {};
817
- if (e.protected)
787
+ async function sr(r, e, t) {
788
+ if (!V(r))
789
+ throw new S("Flattened JWS must be an object");
790
+ if (r.protected === void 0 && r.header === void 0)
791
+ throw new S('Flattened JWS must have either of the "protected" or "header" members');
792
+ if (r.protected !== void 0 && typeof r.protected != "string")
793
+ throw new S("JWS Protected Header incorrect type");
794
+ if (r.payload === void 0)
795
+ throw new S("JWS Payload missing");
796
+ if (typeof r.signature != "string")
797
+ throw new S("JWS Signature missing or incorrect type");
798
+ if (r.header !== void 0 && !V(r.header))
799
+ throw new S("JWS Unprotected Header incorrect type");
800
+ let o = {};
801
+ if (r.protected)
818
802
  try {
819
- const ue = K(e.protected);
820
- n = JSON.parse(z.decode(ue));
803
+ const Re = M(r.protected);
804
+ o = JSON.parse(G.decode(Re));
821
805
  } catch {
822
- throw new v("JWS Protected Header is invalid");
823
- }
824
- if (!_e(n, e.header))
825
- throw new v("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
826
- const i = {
827
- ...n,
828
- ...e.header
829
- }, s = xe(v, /* @__PURE__ */ new Map([["b64", true]]), void 0, n, i);
830
- let o = true;
831
- if (s.has("b64") && (o = n.b64, typeof o != "boolean"))
832
- throw new v('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
833
- const { alg: l } = i;
834
- if (typeof l != "string" || !l)
835
- throw new v('JWS "alg" (Algorithm) Header Parameter missing or invalid');
836
- if (o) {
837
- if (typeof e.payload != "string")
838
- throw new v("JWS Payload must be a string");
839
- } else if (typeof e.payload != "string" && !(e.payload instanceof Uint8Array))
840
- throw new v("JWS Payload must be a string or an Uint8Array instance");
841
- let f = false;
842
- typeof t == "function" && (t = await t(n, e), f = true), Ue(l, t, "verify");
843
- const p = ge(H.encode(e.protected ?? ""), H.encode("."), typeof e.payload == "string" ? H.encode(e.payload) : e.payload);
844
- let P;
806
+ throw new S("JWS Protected Header is invalid");
807
+ }
808
+ if (!We(o, r.header))
809
+ throw new S("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
810
+ const s = {
811
+ ...o,
812
+ ...r.header
813
+ }, n = er(S, /* @__PURE__ */ new Map([["b64", !0]]), void 0, o, s);
814
+ let i = !0;
815
+ if (n.has("b64") && (i = o.b64, typeof i != "boolean"))
816
+ throw new S('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
817
+ const { alg: a } = s;
818
+ if (typeof a != "string" || !a)
819
+ throw new S('JWS "alg" (Algorithm) Header Parameter missing or invalid');
820
+ if (i) {
821
+ if (typeof r.payload != "string")
822
+ throw new S("JWS Payload must be a string");
823
+ } else if (typeof r.payload != "string" && !(r.payload instanceof Uint8Array))
824
+ throw new S("JWS Payload must be a string or an Uint8Array instance");
825
+ let h = !1;
826
+ typeof e == "function" && (e = await e(o, r), h = !0), Ze(a, e, "verify");
827
+ const u = He(X.encode(r.protected ?? ""), X.encode("."), typeof r.payload == "string" ? X.encode(r.payload) : r.payload);
828
+ let y;
845
829
  try {
846
- P = K(e.signature);
830
+ y = M(r.signature);
847
831
  } catch {
848
- throw new v("Failed to base64url decode the signature");
832
+ throw new S("Failed to base64url decode the signature");
849
833
  }
850
- if (!await De(l, t, P, p))
851
- throw new me();
852
- let W;
853
- if (o)
834
+ if (!await or(a, e, y, u))
835
+ throw new je();
836
+ let _;
837
+ if (i)
854
838
  try {
855
- W = K(e.payload);
839
+ _ = M(r.payload);
856
840
  } catch {
857
- throw new v("Failed to base64url decode the payload");
841
+ throw new S("Failed to base64url decode the payload");
858
842
  }
859
- else typeof e.payload == "string" ? W = H.encode(e.payload) : W = e.payload;
860
- const D = { payload: W };
861
- return e.protected !== void 0 && (D.protectedHeader = n), e.header !== void 0 && (D.unprotectedHeader = e.header), f ? { ...D, key: t } : D;
843
+ else typeof r.payload == "string" ? _ = X.encode(r.payload) : _ = r.payload;
844
+ const Y = { payload: _ };
845
+ return r.protected !== void 0 && (Y.protectedHeader = o), r.header !== void 0 && (Y.unprotectedHeader = r.header), h ? { ...Y, key: e } : Y;
862
846
  }
863
- async function Je(e, t, r) {
864
- if (e instanceof Uint8Array && (e = z.decode(e)), typeof e != "string")
865
- throw new v("Compact JWS must be a string or Uint8Array");
866
- const { 0: n, 1: i, 2: s, length: o } = e.split(".");
867
- if (o !== 3)
868
- throw new v("Invalid Compact JWS");
869
- const l = await He({ payload: i, protected: n, signature: s }, t), f = { payload: l.payload, protectedHeader: l.protectedHeader };
870
- return typeof t == "function" ? { ...f, key: l.key } : f;
847
+ async function ir(r, e, t) {
848
+ if (r instanceof Uint8Array && (r = G.decode(r)), typeof r != "string")
849
+ throw new S("Compact JWS must be a string or Uint8Array");
850
+ const { 0: o, 1: s, 2: n, length: i } = r.split(".");
851
+ if (i !== 3)
852
+ throw new S("Invalid Compact JWS");
853
+ const a = await sr({ payload: s, protected: o, signature: n }, e), h = { payload: a.payload, protectedHeader: a.protectedHeader };
854
+ return typeof e == "function" ? { ...h, key: a.key } : h;
871
855
  }
872
- const he = K;
873
- function qe(e) {
874
- let t;
875
- if (typeof e == "string") {
876
- const r = e.split(".");
877
- (r.length === 3 || r.length === 5) && ([t] = r);
878
- } else if (typeof e == "object" && e)
879
- if ("protected" in e)
880
- t = e.protected;
856
+ const Ee = M;
857
+ function nr(r) {
858
+ let e;
859
+ if (typeof r == "string") {
860
+ const t = r.split(".");
861
+ (t.length === 3 || t.length === 5) && ([e] = t);
862
+ } else if (typeof r == "object" && r)
863
+ if ("protected" in r)
864
+ e = r.protected;
881
865
  else
882
866
  throw new TypeError("Token does not contain a Protected Header");
883
867
  try {
884
- if (typeof t != "string" || !t)
868
+ if (typeof e != "string" || !e)
885
869
  throw new Error();
886
- const r = JSON.parse(z.decode(he(t)));
887
- if (!x(r))
870
+ const t = JSON.parse(G.decode(Ee(e)));
871
+ if (!V(t))
888
872
  throw new Error();
889
- return r;
873
+ return t;
890
874
  } catch {
891
875
  throw new TypeError("Invalid Token or Protected Header formatting");
892
876
  }
893
877
  }
894
- function Me(e) {
895
- if (typeof e != "string")
896
- throw new E("JWTs must use Compact JWS serialization, JWT must be a string");
897
- const { 1: t, length: r } = e.split(".");
898
- if (r === 5)
899
- throw new E("Only JWTs using Compact JWS serialization can be decoded");
900
- if (r !== 3)
901
- throw new E("Invalid JWT");
902
- if (!t)
903
- throw new E("JWTs must contain a payload");
904
- let n;
878
+ function ar(r) {
879
+ if (typeof r != "string")
880
+ throw new D("JWTs must use Compact JWS serialization, JWT must be a string");
881
+ const { 1: e, length: t } = r.split(".");
882
+ if (t === 5)
883
+ throw new D("Only JWTs using Compact JWS serialization can be decoded");
884
+ if (t !== 3)
885
+ throw new D("Invalid JWT");
886
+ if (!e)
887
+ throw new D("JWTs must contain a payload");
888
+ let o;
905
889
  try {
906
- n = he(t);
890
+ o = Ee(e);
907
891
  } catch {
908
- throw new E("Failed to base64url decode the payload");
892
+ throw new D("Failed to base64url decode the payload");
909
893
  }
910
- let i;
894
+ let s;
911
895
  try {
912
- i = JSON.parse(z.decode(n));
896
+ s = JSON.parse(G.decode(o));
913
897
  } catch {
914
- throw new E("Failed to parse the decoded payload as JSON");
898
+ throw new D("Failed to parse the decoded payload as JSON");
915
899
  }
916
- if (!x(i))
917
- throw new E("Invalid JWT Claims Set");
918
- return i;
900
+ if (!V(s))
901
+ throw new D("Invalid JWT Claims Set");
902
+ return s;
919
903
  }
920
- const c = class c2 {
904
+ const C = class v {
921
905
  /**
922
906
  * Returns a user-friendly name for the given flow strings.
923
907
  *
@@ -925,41 +909,41 @@ const c = class c2 {
925
909
  * @param flows the flows to return the names of
926
910
  * @returns an array of strings
927
911
  */
928
- static flowNames(t) {
929
- let r = {};
930
- return t.forEach((n) => {
931
- n in c2.flowName && (r[n] = c2.flowName[n]);
932
- }), r;
912
+ static flowNames(e) {
913
+ let t = {};
914
+ return e.forEach((o) => {
915
+ o in v.flowName && (t[o] = v.flowName[o]);
916
+ }), t;
933
917
  }
934
918
  /**
935
919
  * Returns true if the given string is a valid flow name.
936
920
  * @param flow the flow to check
937
921
  * @returns true or false.
938
922
  */
939
- static isValidFlow(t) {
940
- return c2.allFlows().includes(t);
923
+ static isValidFlow(e) {
924
+ return v.allFlows().includes(e);
941
925
  }
942
926
  /**
943
927
  * Returns true only if all given strings are valid flows
944
928
  * @param flows the flows to check
945
929
  * @returns true or false.
946
930
  */
947
- static areAllValidFlows(t) {
948
- let r = true;
949
- return t.forEach((n) => {
950
- c2.isValidFlow(n) || (r = false);
951
- }), r;
931
+ static areAllValidFlows(e) {
932
+ let t = !0;
933
+ return e.forEach((o) => {
934
+ v.isValidFlow(o) || (t = !1);
935
+ }), t;
952
936
  }
953
937
  static allFlows() {
954
938
  return [
955
- c2.AuthorizationCode,
956
- c2.AuthorizationCodeWithPKCE,
957
- c2.ClientCredentials,
958
- c2.RefreshToken,
959
- c2.DeviceCode,
960
- c2.Password,
961
- c2.PasswordMfa,
962
- c2.OidcAuthorizationCode
939
+ v.AuthorizationCode,
940
+ v.AuthorizationCodeWithPKCE,
941
+ v.ClientCredentials,
942
+ v.RefreshToken,
943
+ v.DeviceCode,
944
+ v.Password,
945
+ v.PasswordMfa,
946
+ v.OidcAuthorizationCode
963
947
  ];
964
948
  }
965
949
  /**
@@ -968,52 +952,52 @@ const c = class c2 {
968
952
  * @param oauthFlow the flow to get the grant type for.
969
953
  * @returns a {@link GrantType} value
970
954
  */
971
- static grantType(t) {
972
- switch (t) {
973
- case c2.AuthorizationCode:
974
- case c2.AuthorizationCodeWithPKCE:
975
- case c2.OidcAuthorizationCode:
955
+ static grantType(e) {
956
+ switch (e) {
957
+ case v.AuthorizationCode:
958
+ case v.AuthorizationCodeWithPKCE:
959
+ case v.OidcAuthorizationCode:
976
960
  return ["authorization_code"];
977
- case c2.ClientCredentials:
961
+ case v.ClientCredentials:
978
962
  return ["client_credentials"];
979
- case c2.RefreshToken:
963
+ case v.RefreshToken:
980
964
  return ["refresh_token"];
981
- case c2.Password:
965
+ case v.Password:
982
966
  return ["password"];
983
- case c2.PasswordMfa:
967
+ case v.PasswordMfa:
984
968
  return ["http://auth0.com/oauth/grant-type/mfa-otp", "http://auth0.com/oauth/grant-type/mfa-oob"];
985
- case c2.DeviceCode:
969
+ case v.DeviceCode:
986
970
  return ["urn:ietf:params:oauth:grant-type:device_code"];
987
971
  }
988
972
  }
989
973
  };
990
- a(c, "All", "all"), /** OAuth authorization code flow (without PKCE) */
991
- a(c, "AuthorizationCode", "authorizationCode"), /** OAuth authorization code flow with PKCE */
992
- a(c, "AuthorizationCodeWithPKCE", "authorizationCodeWithPKCE"), /** Auth client credentials flow */
993
- a(c, "ClientCredentials", "clientCredentials"), /** OAuth refresh token flow */
994
- a(c, "RefreshToken", "refreshToken"), /** OAuth device code flow */
995
- a(c, "DeviceCode", "deviceCode"), /** OAuth password flow */
996
- a(c, "Password", "password"), /** The Auth0 password MFA extension to the password flow */
997
- a(c, "PasswordMfa", "passwordMfa"), /** The OpenID Connect authorization code flow, with or without
974
+ l(C, "All", "all"), /** OAuth authorization code flow (without PKCE) */
975
+ l(C, "AuthorizationCode", "authorizationCode"), /** OAuth authorization code flow with PKCE */
976
+ l(C, "AuthorizationCodeWithPKCE", "authorizationCodeWithPKCE"), /** Auth client credentials flow */
977
+ l(C, "ClientCredentials", "clientCredentials"), /** OAuth refresh token flow */
978
+ l(C, "RefreshToken", "refreshToken"), /** OAuth device code flow */
979
+ l(C, "DeviceCode", "deviceCode"), /** OAuth password flow */
980
+ l(C, "Password", "password"), /** The Auth0 password MFA extension to the password flow */
981
+ l(C, "PasswordMfa", "passwordMfa"), /** The OpenID Connect authorization code flow, with or without
998
982
  * PKCE.
999
983
  */
1000
- a(c, "OidcAuthorizationCode", "oidcAuthorizationCode"), /** A user friendly name for the given flow ID
984
+ l(C, "OidcAuthorizationCode", "oidcAuthorizationCode"), /** A user friendly name for the given flow ID
1001
985
  *
1002
986
  * For example, if you pass "authorizationCode"
1003
987
  * (`OAuthFlows.AuthorizationCode`) you will get `"Authorization Code"`.
1004
988
  */
1005
- a(c, "flowName", {
1006
- [c.AuthorizationCode]: "Authorization Code",
1007
- [c.AuthorizationCodeWithPKCE]: "Authorization Code with PKCE",
1008
- [c.ClientCredentials]: "Client Credentials",
1009
- [c.RefreshToken]: "Refresh Token",
1010
- [c.DeviceCode]: "Device Code",
1011
- [c.Password]: "Password",
1012
- [c.PasswordMfa]: "Password MFA",
1013
- [c.OidcAuthorizationCode]: "OIDC Authorization Code"
989
+ l(C, "flowName", {
990
+ [C.AuthorizationCode]: "Authorization Code",
991
+ [C.AuthorizationCodeWithPKCE]: "Authorization Code with PKCE",
992
+ [C.ClientCredentials]: "Client Credentials",
993
+ [C.RefreshToken]: "Refresh Token",
994
+ [C.DeviceCode]: "Device Code",
995
+ [C.Password]: "Password",
996
+ [C.PasswordMfa]: "Password MFA",
997
+ [C.OidcAuthorizationCode]: "OIDC Authorization Code"
1014
998
  });
1015
- var w, S, N, T, R;
1016
- class Be {
999
+ var k, T, q, F, J;
1000
+ class cr {
1017
1001
  /**
1018
1002
  * Constructor.
1019
1003
  *
@@ -1042,50 +1026,34 @@ class Be {
1042
1026
  * are received
1043
1027
  */
1044
1028
  constructor({
1045
- authServerBaseUrl: t,
1046
- client_id: r,
1047
- client_secret: n,
1048
- redirect_uri: i,
1049
- codeChallengeMethod: s,
1050
- stateLength: o,
1051
- verifierLength: l,
1052
- tokenConsumer: f,
1053
- authServerCredentials: p,
1054
- authServerMode: P,
1055
- authServerHeaders: U
1029
+ authServerBaseUrl: e,
1030
+ client_id: t,
1031
+ client_secret: o,
1032
+ redirect_uri: s,
1033
+ codeChallengeMethod: n,
1034
+ stateLength: i,
1035
+ verifierLength: a,
1036
+ tokenConsumer: h,
1037
+ authServerCredentials: u,
1038
+ authServerMode: y,
1039
+ authServerHeaders: _
1056
1040
  }) {
1057
- a(this, "authServerBaseUrl", "");
1058
- O(this, w);
1059
- O(this, S);
1060
- O(this, N);
1061
- a(this, "codeChallengeMethod", "S256");
1062
- O(this, T);
1063
- a(this, "verifierLength", 32);
1064
- a(this, "redirect_uri");
1065
- O(this, R, "");
1066
- a(this, "stateLength", 32);
1067
- a(this, "authzCode", "");
1068
- a(this, "oidcConfig");
1069
- a(this, "tokenConsumer");
1070
- a(this, "authServerHeaders", {});
1071
- a(this, "authServerMode");
1072
- a(this, "authServerCredentials");
1073
- this.tokenConsumer = f, this.authServerBaseUrl = t, l && (this.verifierLength = l), o && (this.stateLength = o), r && _(this, w, r), n && _(this, S, n), i && (this.redirect_uri = i), s && (this.codeChallengeMethod = s), this.authServerBaseUrl = t, p && (this.authServerCredentials = p), P && (this.authServerMode = P), U && (this.authServerHeaders = U);
1074
- }
1075
- set client_id(t) {
1076
- _(this, w, t);
1077
- }
1078
- set client_secret(t) {
1079
- _(this, S, t);
1080
- }
1081
- set codeVerifier(t) {
1082
- _(this, T, t);
1083
- }
1084
- set codeChallenge(t) {
1085
- _(this, N, t);
1086
- }
1087
- set state(t) {
1088
- _(this, R, t);
1041
+ l(this, "authServerBaseUrl", ""), $(this, k), $(this, T), $(this, q), l(this, "codeChallengeMethod", "S256"), $(this, F), l(this, "verifierLength", 32), l(this, "redirect_uri"), $(this, J, ""), l(this, "stateLength", 32), l(this, "authzCode", ""), l(this, "oidcConfig"), l(this, "tokenConsumer"), l(this, "authServerHeaders", {}), l(this, "authServerMode"), l(this, "authServerCredentials"), this.tokenConsumer = h, this.authServerBaseUrl = e, a && (this.verifierLength = a), i && (this.stateLength = i), t && A(this, k, t), o && A(this, T, o), s && (this.redirect_uri = s), n && (this.codeChallengeMethod = n), this.authServerBaseUrl = e, u && (this.authServerCredentials = u), y && (this.authServerMode = y), _ && (this.authServerHeaders = _);
1042
+ }
1043
+ set client_id(e) {
1044
+ A(this, k, e);
1045
+ }
1046
+ set client_secret(e) {
1047
+ A(this, T, e);
1048
+ }
1049
+ set codeVerifier(e) {
1050
+ A(this, F, e);
1051
+ }
1052
+ set codeChallenge(e) {
1053
+ A(this, q, e);
1054
+ }
1055
+ set state(e) {
1056
+ A(this, J, e);
1089
1057
  }
1090
1058
  /**
1091
1059
  * Loads OpenID Connect configuration so that the client can determine
@@ -1098,35 +1066,35 @@ class Be {
1098
1066
  * @throws {@link @crossauth/common!CrossauthError} with the following {@link @crossauth/common!ErrorCode}s
1099
1067
  * - `Connection` if data from the URL could not be fetched or parsed.
1100
1068
  */
1101
- async loadConfig(t) {
1102
- if (t) {
1103
- d.logger.debug(h({ msg: "Reading OIDC config locally" })), this.oidcConfig = t;
1069
+ async loadConfig(e) {
1070
+ if (e) {
1071
+ c.logger.debug(d({ msg: "Reading OIDC config locally" })), this.oidcConfig = e;
1104
1072
  return;
1105
1073
  }
1106
- let r;
1074
+ let t;
1107
1075
  try {
1108
- const n = new URL(
1076
+ const o = new URL(
1109
1077
  this.authServerBaseUrl + "/.well-known/openid-configuration"
1110
1078
  );
1111
- d.logger.debug(h({ msg: `Fetching OIDC config from ${n}` }));
1112
- let i = { headers: this.authServerHeaders };
1113
- this.authServerMode && (i.mode = this.authServerMode), this.authServerCredentials && (i.credentials = this.authServerCredentials), r = await fetch(n, i);
1114
- } catch (n) {
1115
- d.logger.error(h({ err: n }));
1079
+ c.logger.debug(d({ msg: `Fetching OIDC config from ${o}` }));
1080
+ let s = { headers: this.authServerHeaders };
1081
+ this.authServerMode && (s.mode = this.authServerMode), this.authServerCredentials && (s.credentials = this.authServerCredentials), t = await fetch(o, s);
1082
+ } catch (o) {
1083
+ c.logger.error(d({ err: o }));
1116
1084
  }
1117
- if (!r || !r.ok)
1085
+ if (!t || !t.ok)
1118
1086
  throw new g(
1119
- y.Connection,
1087
+ m.Connection,
1120
1088
  "Couldn't get OIDC configuration from URL" + this.authServerBaseUrl + "/.well-known/openid-configuration"
1121
1089
  );
1122
- this.oidcConfig = { ...te };
1090
+ this.oidcConfig = { ...ye };
1123
1091
  try {
1124
- const n = await r.json();
1125
- for (const [i, s] of Object.entries(n))
1126
- this.oidcConfig[i] = s;
1092
+ const o = await t.json();
1093
+ for (const [s, n] of Object.entries(o))
1094
+ this.oidcConfig[s] = n;
1127
1095
  } catch {
1128
1096
  throw new g(
1129
- y.Connection,
1097
+ m.Connection,
1130
1098
  "Unrecognized response from OIDC configuration endpoint"
1131
1099
  );
1132
1100
  }
@@ -1153,19 +1121,19 @@ class Be {
1153
1121
  * - `error_description` friendly error message or undefined
1154
1122
  * if no error
1155
1123
  */
1156
- async startAuthorizationCodeFlow(t, r = false) {
1157
- var s, o, l;
1158
- if (d.logger.debug(h({ msg: "Starting authorization code flow" })), this.oidcConfig || await this.loadConfig(), !((s = this.oidcConfig) != null && s.response_types_supported.includes("code")) || !((o = this.oidcConfig) != null && o.response_modes_supported.includes("query")))
1124
+ async startAuthorizationCodeFlow(e, t = !1) {
1125
+ var o, s, n;
1126
+ if (c.logger.debug(d({ msg: "Starting authorization code flow" })), this.oidcConfig || await this.loadConfig(), !((o = this.oidcConfig) != null && o.response_types_supported.includes("code")) || !((s = this.oidcConfig) != null && s.response_modes_supported.includes("query")))
1159
1127
  return {
1160
1128
  error: "invalid_request",
1161
1129
  error_description: "Server does not support authorization code flow"
1162
1130
  };
1163
- if (!((l = this.oidcConfig) != null && l.authorization_endpoint))
1131
+ if (!((n = this.oidcConfig) != null && n.authorization_endpoint))
1164
1132
  return {
1165
1133
  error: "server_error",
1166
1134
  error_description: "Cannot get authorize endpoint"
1167
1135
  };
1168
- if (_(this, R, this.randomValue(this.stateLength)), !u(this, w)) return {
1136
+ if (A(this, J, this.randomValue(this.stateLength)), !p(this, k)) return {
1169
1137
  error: "invalid_request",
1170
1138
  error_description: "Cannot make authorization code flow without client id"
1171
1139
  };
@@ -1173,8 +1141,8 @@ class Be {
1173
1141
  error: "invalid_request",
1174
1142
  error_description: "Cannot make authorization code flow without Redirect Uri"
1175
1143
  };
1176
- let i = this.oidcConfig.authorization_endpoint + "?response_type=code&client_id=" + encodeURIComponent(u(this, w)) + "&state=" + encodeURIComponent(u(this, R)) + "&redirect_uri=" + encodeURIComponent(this.redirect_uri);
1177
- return t && (i += "&scope=" + encodeURIComponent(t)), r && (_(this, T, this.randomValue(this.verifierLength)), _(this, N, this.codeChallengeMethod == "plain" ? u(this, T) : await this.sha256(u(this, T))), i += "&code_challenge=" + u(this, N)), { url: i };
1144
+ let i = this.oidcConfig.authorization_endpoint + "?response_type=code&client_id=" + encodeURIComponent(p(this, k)) + "&state=" + encodeURIComponent(p(this, J)) + "&redirect_uri=" + encodeURIComponent(this.redirect_uri);
1145
+ return e && (i += "&scope=" + encodeURIComponent(e)), t && (A(this, F, this.randomValue(this.verifierLength)), A(this, q, this.codeChallengeMethod == "plain" ? p(this, F) : await this.sha256(p(this, F))), i += "&code_challenge=" + p(this, q)), { url: i };
1178
1146
  }
1179
1147
  /**
1180
1148
  * This implements the functionality behind the redirect URI
@@ -1196,35 +1164,35 @@ class Be {
1196
1164
  * @returns The {@link OAuthTokenResponse} from the `token` endpoint
1197
1165
  * request, or `error` and `error_description`.
1198
1166
  */
1199
- async redirectEndpoint(t, r, n, i) {
1200
- var p, P;
1201
- if (this.oidcConfig || await this.loadConfig(), n || !t)
1202
- return n || (n = "server_error"), i || (i = "Unknown error"), { error: n, error_description: i };
1203
- if (u(this, R) && r != u(this, R))
1167
+ async redirectEndpoint(e, t, o, s) {
1168
+ var n, i;
1169
+ if (this.oidcConfig || await this.loadConfig(), o || !e)
1170
+ return o || (o = "server_error"), s || (s = "Unknown error"), { error: o, error_description: s };
1171
+ if (p(this, J) && t != p(this, J))
1204
1172
  return { error: "access_denied", error_description: "State is not valid" };
1205
- if (this.authzCode = t, !((p = this.oidcConfig) != null && p.grant_types_supported.includes("authorization_code")))
1173
+ if (this.authzCode = e, !((n = this.oidcConfig) != null && n.grant_types_supported.includes("authorization_code")))
1206
1174
  return {
1207
1175
  error: "invalid_request",
1208
1176
  error_description: "Server does not support authorization code grant"
1209
1177
  };
1210
- if (!((P = this.oidcConfig) != null && P.token_endpoint))
1178
+ if (!((i = this.oidcConfig) != null && i.token_endpoint))
1211
1179
  return {
1212
1180
  error: "server_error",
1213
1181
  error_description: "Cannot get token endpoint"
1214
1182
  };
1215
- const s = this.oidcConfig.token_endpoint;
1216
- let o, l;
1217
- o = "authorization_code", l = u(this, S);
1218
- let f = {
1219
- grant_type: o,
1220
- client_id: u(this, w),
1183
+ const a = this.oidcConfig.token_endpoint;
1184
+ let h, u;
1185
+ h = "authorization_code", u = p(this, T);
1186
+ let y = {
1187
+ grant_type: h,
1188
+ client_id: p(this, k),
1221
1189
  code: this.authzCode
1222
1190
  };
1223
- l && (f.client_secret = l), f.code_verifier = u(this, T);
1191
+ u && (y.client_secret = u), y.code_verifier = p(this, F);
1224
1192
  try {
1225
- return this.post(s, f, this.authServerHeaders);
1226
- } catch (U) {
1227
- return d.logger.error(h({ err: U })), {
1193
+ return this.post(a, y, this.authServerHeaders);
1194
+ } catch (_) {
1195
+ return c.logger.error(d({ err: _ })), {
1228
1196
  error: "server_error",
1229
1197
  error_description: "Unable to get access token from server"
1230
1198
  };
@@ -1244,30 +1212,30 @@ class Be {
1244
1212
  * @returns The {@link OAuthTokenResponse} from the `token` endpoint
1245
1213
  * request, or `error` and `error_description`.
1246
1214
  */
1247
- async clientCredentialsFlow(t) {
1248
- var i, s;
1249
- if (d.logger.debug(h({ msg: "Starting client credentials flow" })), this.oidcConfig || await this.loadConfig(), !((i = this.oidcConfig) != null && i.grant_types_supported.includes("client_credentials")))
1215
+ async clientCredentialsFlow(e) {
1216
+ var t, o;
1217
+ if (c.logger.debug(d({ msg: "Starting client credentials flow" })), this.oidcConfig || await this.loadConfig(), !((t = this.oidcConfig) != null && t.grant_types_supported.includes("client_credentials")))
1250
1218
  return {
1251
1219
  error: "invalid_request",
1252
1220
  error_description: "Server does not support client credentials grant"
1253
1221
  };
1254
- if (!((s = this.oidcConfig) != null && s.token_endpoint))
1222
+ if (!((o = this.oidcConfig) != null && o.token_endpoint))
1255
1223
  return { error: "server_error", error_description: "Cannot get token endpoint" };
1256
- if (!u(this, w)) return {
1224
+ if (!p(this, k)) return {
1257
1225
  error: "invalid_request",
1258
1226
  error_description: "Cannot make client credentials flow without client id"
1259
1227
  };
1260
- const r = this.oidcConfig.token_endpoint;
1228
+ const s = this.oidcConfig.token_endpoint;
1261
1229
  let n = {
1262
1230
  grant_type: "client_credentials",
1263
- client_id: u(this, w),
1264
- client_secret: u(this, S)
1231
+ client_id: p(this, k),
1232
+ client_secret: p(this, T)
1265
1233
  };
1266
- t && (n.scope = t);
1234
+ e && (n.scope = e);
1267
1235
  try {
1268
- return await this.post(r, n, this.authServerHeaders);
1269
- } catch (o) {
1270
- return d.logger.error(h({ err: o })), {
1236
+ return await this.post(s, n, this.authServerHeaders);
1237
+ } catch (i) {
1238
+ return c.logger.error(d({ err: i })), {
1271
1239
  error: "server_error",
1272
1240
  error_description: "Error connecting to authorization server"
1273
1241
  };
@@ -1288,31 +1256,31 @@ class Be {
1288
1256
  * {@link https://auth0.com/docs/secure/multi-factor-authentication/multi-factor-authentication-factors}.
1289
1257
  *
1290
1258
  */
1291
- async passwordFlow(t, r, n) {
1292
- var o, l;
1293
- if (d.logger.debug(h({ msg: "Starting password flow" })), this.oidcConfig || await this.loadConfig(), !((o = this.oidcConfig) != null && o.grant_types_supported.includes("password")))
1259
+ async passwordFlow(e, t, o) {
1260
+ var s, n;
1261
+ if (c.logger.debug(d({ msg: "Starting password flow" })), this.oidcConfig || await this.loadConfig(), !((s = this.oidcConfig) != null && s.grant_types_supported.includes("password")))
1294
1262
  return {
1295
1263
  error: "invalid_request",
1296
1264
  error_description: "Server does not support password grant"
1297
1265
  };
1298
- if (!((l = this.oidcConfig) != null && l.token_endpoint))
1266
+ if (!((n = this.oidcConfig) != null && n.token_endpoint))
1299
1267
  return {
1300
1268
  error: "server_error",
1301
1269
  error_description: "Cannot get token endpoint"
1302
1270
  };
1303
1271
  const i = this.oidcConfig.token_endpoint;
1304
- let s = {
1272
+ let a = {
1305
1273
  grant_type: "password",
1306
- client_id: u(this, w),
1307
- client_secret: u(this, S),
1308
- username: t,
1309
- password: r
1274
+ client_id: p(this, k),
1275
+ client_secret: p(this, T),
1276
+ username: e,
1277
+ password: t
1310
1278
  };
1311
- n && (s.scope = n);
1279
+ o && (a.scope = o);
1312
1280
  try {
1313
- return await this.post(i, s, this.authServerHeaders);
1314
- } catch (f) {
1315
- return d.logger.error(h({ err: f })), {
1281
+ return await this.post(i, a, this.authServerHeaders);
1282
+ } catch (h) {
1283
+ return c.logger.error(d({ err: h })), {
1316
1284
  error: "server_error",
1317
1285
  error_description: "Error connecting to authorization server"
1318
1286
  };
@@ -1331,38 +1299,38 @@ class Be {
1331
1299
  * - an `error` and `error_description`, also as per Auth0's Password MFA
1332
1300
  * documentation
1333
1301
  */
1334
- async mfaAuthenticators(t) {
1335
- var s, o, l;
1336
- if (d.logger.debug(h({ msg: "Getting valid MFA authenticators" })), this.oidcConfig || await this.loadConfig(), !((s = this.oidcConfig) != null && s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")) && ((o = this.oidcConfig) != null && o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))
1302
+ async mfaAuthenticators(e) {
1303
+ var t, o, s;
1304
+ if (c.logger.debug(d({ msg: "Getting valid MFA authenticators" })), this.oidcConfig || await this.loadConfig(), !((t = this.oidcConfig) != null && t.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")) && (o = this.oidcConfig) != null && o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob"))
1337
1305
  return {
1338
1306
  error: "invalid_request",
1339
1307
  error_description: "Server does not support password_mfa grant"
1340
1308
  };
1341
- if (!((l = this.oidcConfig) != null && l.issuer))
1309
+ if (!((s = this.oidcConfig) != null && s.issuer))
1342
1310
  return { error: "server_error", error_description: "Cannot get issuer" };
1343
- const r = this.oidcConfig.issuer + (this.oidcConfig.issuer.endsWith("/") ? "" : "/") + "mfa/authenticators", n = await this.get(r, { authorization: "Bearer " + t, ...this.authServerHeaders });
1344
- if (!Array.isArray(n))
1311
+ const n = this.oidcConfig.issuer + (this.oidcConfig.issuer.endsWith("/") ? "" : "/") + "mfa/authenticators", i = await this.get(n, { authorization: "Bearer " + e, ...this.authServerHeaders });
1312
+ if (!Array.isArray(i))
1345
1313
  return {
1346
1314
  error: "server_error",
1347
1315
  error_description: "Expected array of authenticators in mfa/authenticators response"
1348
1316
  };
1349
- let i = [];
1350
- for (let f = 0; f < n.length; ++f) {
1351
- const p = n[f];
1352
- if (!p.id || !p.authenticator_type || !p.active)
1317
+ let a = [];
1318
+ for (let h = 0; h < i.length; ++h) {
1319
+ const u = i[h];
1320
+ if (!u.id || !u.authenticator_type || !u.active)
1353
1321
  return {
1354
1322
  error: "server_error",
1355
1323
  error_description: "Invalid mfa/authenticators response"
1356
1324
  };
1357
- i.push({
1358
- id: p.id,
1359
- authenticator_type: p.authenticator_type,
1360
- active: p.active,
1361
- name: p.name,
1362
- oob_channel: p.oob_channel
1325
+ a.push({
1326
+ id: u.id,
1327
+ authenticator_type: u.authenticator_type,
1328
+ active: u.active,
1329
+ name: u.name,
1330
+ oob_channel: u.oob_channel
1363
1331
  });
1364
1332
  }
1365
- return { authenticators: i };
1333
+ return { authenticators: a };
1366
1334
  }
1367
1335
  /**
1368
1336
  * This is part of the Auth0 Password MFA flow. Once the client has
@@ -1376,21 +1344,21 @@ class Be {
1376
1344
  * @param authenticatorId the authenticator ID, as returned in the response
1377
1345
  * from the `mfaAuthenticators` request.
1378
1346
  */
1379
- async mfaOtpRequest(t, r) {
1380
- var s, o;
1381
- if (d.logger.debug(h({ msg: "Making MFA OTB request" })), this.oidcConfig || await this.loadConfig(), !((s = this.oidcConfig) != null && s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))
1347
+ async mfaOtpRequest(e, t) {
1348
+ var o, s;
1349
+ if (c.logger.debug(d({ msg: "Making MFA OTB request" })), this.oidcConfig || await this.loadConfig(), !((o = this.oidcConfig) != null && o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))
1382
1350
  return {
1383
1351
  error: "invalid_request",
1384
1352
  error_description: "Server does not support password_mfa grant"
1385
1353
  };
1386
- if (!((o = this.oidcConfig) != null && o.issuer))
1354
+ if (!((s = this.oidcConfig) != null && s.issuer))
1387
1355
  return { error: "server_error", error_description: "Cannot get issuer" };
1388
1356
  const n = this.oidcConfig.issuer + (this.oidcConfig.issuer.endsWith("/") ? "" : "/") + "mfa/challenge", i = await this.post(n, {
1389
- client_id: u(this, w),
1390
- client_secret: u(this, S),
1357
+ client_id: p(this, k),
1358
+ client_secret: p(this, T),
1391
1359
  challenge_type: "otp",
1392
- mfa_token: t,
1393
- authenticator_id: r
1360
+ mfa_token: e,
1361
+ authenticator_id: t
1394
1362
  }, this.authServerHeaders);
1395
1363
  return i.challenge_type != "otp" ? {
1396
1364
  error: i.error ?? "server_error",
@@ -1414,33 +1382,33 @@ class Be {
1414
1382
  * - `error` as per Auth0 Password MFA documentation
1415
1383
  * - `error_description` friendly error message
1416
1384
  */
1417
- async mfaOtpComplete(t, r, n) {
1418
- var o, l;
1419
- if (d.logger.debug(h({ msg: "Completing MFA OTP request" })), this.oidcConfig || await this.loadConfig(), !((o = this.oidcConfig) != null && o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))
1385
+ async mfaOtpComplete(e, t, o) {
1386
+ var s, n;
1387
+ if (c.logger.debug(d({ msg: "Completing MFA OTP request" })), this.oidcConfig || await this.loadConfig(), !((s = this.oidcConfig) != null && s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))
1420
1388
  return {
1421
1389
  error: "invalid_request",
1422
1390
  error_description: "Server does not support password_mfa grant"
1423
1391
  };
1424
- if (!((l = this.oidcConfig) != null && l.issuer))
1392
+ if (!((n = this.oidcConfig) != null && n.issuer))
1425
1393
  return { error: "server_error", error_description: "Cannot get issuer" };
1426
- const i = this.oidcConfig.token_endpoint, s = await this.post(i, {
1394
+ const i = this.oidcConfig.token_endpoint, a = await this.post(i, {
1427
1395
  grant_type: "http://auth0.com/oauth/grant-type/mfa-otp",
1428
- client_id: u(this, w),
1429
- client_secret: u(this, S),
1396
+ client_id: p(this, k),
1397
+ client_secret: p(this, T),
1430
1398
  challenge_type: "otp",
1431
- mfa_token: t,
1432
- otp: r,
1433
- scope: n
1399
+ mfa_token: e,
1400
+ otp: t,
1401
+ scope: o
1434
1402
  }, this.authServerHeaders);
1435
1403
  return {
1436
- id_token: s.id_token,
1437
- access_token: s.access_token,
1438
- refresh_token: s.refresh_token,
1439
- expires_in: Number(s.expires_in),
1440
- scope: s.scope,
1441
- token_type: s.token_type,
1442
- error: s.error,
1443
- error_description: s.error_description
1404
+ id_token: a.id_token,
1405
+ access_token: a.access_token,
1406
+ refresh_token: a.refresh_token,
1407
+ expires_in: Number(a.expires_in),
1408
+ scope: a.scope,
1409
+ token_type: a.token_type,
1410
+ error: a.error,
1411
+ error_description: a.error_description
1444
1412
  };
1445
1413
  }
1446
1414
  /**
@@ -1461,21 +1429,21 @@ class Be {
1461
1429
  * - `error` as per Auth0 Password MFA documentation
1462
1430
  * - `error_description` friendly error message
1463
1431
  */
1464
- async mfaOobRequest(t, r) {
1465
- var s, o;
1466
- if (d.logger.debug(h({ msg: "Making MFA OOB request" })), this.oidcConfig || await this.loadConfig(), !((s = this.oidcConfig) != null && s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))
1432
+ async mfaOobRequest(e, t) {
1433
+ var o, s;
1434
+ if (c.logger.debug(d({ msg: "Making MFA OOB request" })), this.oidcConfig || await this.loadConfig(), !((o = this.oidcConfig) != null && o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))
1467
1435
  return {
1468
1436
  error: "invalid_request",
1469
1437
  error_description: "Server does not support password_mfa grant"
1470
1438
  };
1471
- if (!((o = this.oidcConfig) != null && o.issuer))
1439
+ if (!((s = this.oidcConfig) != null && s.issuer))
1472
1440
  return { error: "server_error", error_description: "Cannot get issuer" };
1473
1441
  const n = this.oidcConfig.issuer + (this.oidcConfig.issuer.endsWith("/") ? "" : "/") + "mfa/challenge", i = await this.post(n, {
1474
- client_id: u(this, w),
1475
- client_secret: u(this, S),
1442
+ client_id: p(this, k),
1443
+ client_secret: p(this, T),
1476
1444
  challenge_type: "oob",
1477
- mfa_token: t,
1478
- authenticator_id: r
1445
+ mfa_token: e,
1446
+ authenticator_id: t
1479
1447
  }, this.authServerHeaders);
1480
1448
  return i.challenge_type != "oob" || !i.oob_code || !i.binding_method ? { error: i.error ?? "server_error", error_description: i.error_description ?? "Invalid OOB challenge response" } : {
1481
1449
  challenge_type: i.challenge_type,
@@ -1496,42 +1464,42 @@ class Be {
1496
1464
  * @returns an {@link OAuthTokenResponse} object, which may contain
1497
1465
  * an error instead of the response fields.
1498
1466
  */
1499
- async mfaOobComplete(t, r, n, i) {
1500
- var l, f;
1501
- if (d.logger.debug(h({ msg: "Completing MFA OOB request" })), this.oidcConfig || await this.loadConfig(), !((l = this.oidcConfig) != null && l.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))
1467
+ async mfaOobComplete(e, t, o, s) {
1468
+ var n, i;
1469
+ if (c.logger.debug(d({ msg: "Completing MFA OOB request" })), this.oidcConfig || await this.loadConfig(), !((n = this.oidcConfig) != null && n.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))
1502
1470
  return {
1503
1471
  error: "invalid_request",
1504
1472
  error_description: "Server does not support password_mfa grant"
1505
1473
  };
1506
- if (!((f = this.oidcConfig) != null && f.issuer))
1474
+ if (!((i = this.oidcConfig) != null && i.issuer))
1507
1475
  return { error: "server_error", error_description: "Cannot get issuer" };
1508
- const s = this.oidcConfig.token_endpoint, o = await this.post(s, {
1476
+ const a = this.oidcConfig.token_endpoint, h = await this.post(a, {
1509
1477
  grant_type: "http://auth0.com/oauth/grant-type/mfa-oob",
1510
- client_id: u(this, w),
1511
- client_secret: u(this, S),
1478
+ client_id: p(this, k),
1479
+ client_secret: p(this, T),
1512
1480
  challenge_type: "otp",
1513
- mfa_token: t,
1514
- oob_code: r,
1515
- binding_code: n,
1516
- scope: i
1481
+ mfa_token: e,
1482
+ oob_code: t,
1483
+ binding_code: o,
1484
+ scope: s
1517
1485
  }, this.authServerHeaders);
1518
- return o.error ? {
1519
- error: o.error,
1520
- error_description: o.error_description
1486
+ return h.error ? {
1487
+ error: h.error,
1488
+ error_description: h.error_description
1521
1489
  } : {
1522
- id_token: o.id_token,
1523
- access_token: o.access_token,
1524
- refresh_token: o.refresh_token,
1525
- expires_in: "expires_in" in o ? Number(o.expires_in) : void 0,
1526
- scope: o.scope,
1527
- token_type: o.token_type
1490
+ id_token: h.id_token,
1491
+ access_token: h.access_token,
1492
+ refresh_token: h.refresh_token,
1493
+ expires_in: "expires_in" in h ? Number(h.expires_in) : void 0,
1494
+ scope: h.scope,
1495
+ token_type: h.token_type
1528
1496
  };
1529
1497
  }
1530
1498
  //////////////////////////////////////////////////////////////////////
1531
1499
  // Refresh Token Flow
1532
- async refreshTokenFlow(t) {
1533
- var s, o;
1534
- if (d.logger.debug(h({ msg: "Starting refresh token flow" })), this.oidcConfig || await this.loadConfig(), !((s = this.oidcConfig) != null && s.grant_types_supported.includes("refresh_token")))
1500
+ async refreshTokenFlow(e) {
1501
+ var t, o;
1502
+ if (c.logger.debug(d({ msg: "Starting refresh token flow" })), this.oidcConfig || await this.loadConfig(), !((t = this.oidcConfig) != null && t.grant_types_supported.includes("refresh_token")))
1535
1503
  return {
1536
1504
  error: "invalid_request",
1537
1505
  error_description: "Server does not support refresh_token grant"
@@ -1541,19 +1509,19 @@ class Be {
1541
1509
  error: "server_error",
1542
1510
  error_description: "Cannot get token endpoint"
1543
1511
  };
1544
- const r = this.oidcConfig.token_endpoint;
1512
+ const s = this.oidcConfig.token_endpoint;
1545
1513
  let n;
1546
- n = u(this, S);
1514
+ n = p(this, T);
1547
1515
  let i = {
1548
1516
  grant_type: "refresh_token",
1549
- refresh_token: t,
1550
- client_id: u(this, w)
1517
+ refresh_token: e,
1518
+ client_id: p(this, k)
1551
1519
  };
1552
1520
  n && (i.client_secret = n);
1553
1521
  try {
1554
- return await this.post(r, i, this.authServerHeaders);
1555
- } catch (l) {
1556
- return d.logger.error(h({ err: l })), {
1522
+ return await this.post(s, i, this.authServerHeaders);
1523
+ } catch (a) {
1524
+ return c.logger.error(d({ err: a })), {
1557
1525
  error: "server_error",
1558
1526
  error_description: "Error connecting to authorization server"
1559
1527
  };
@@ -1567,23 +1535,23 @@ class Be {
1567
1535
  * @param scope optional scope to request authorization for
1568
1536
  * @returns See {@link OAuthDeviceAuthorizationResponse}
1569
1537
  */
1570
- async startDeviceCodeFlow(t, r) {
1571
- var i;
1572
- if (d.logger.debug(h({ msg: "Starting device code flow" })), this.oidcConfig || await this.loadConfig(), !((i = this.oidcConfig) != null && i.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))
1538
+ async startDeviceCodeFlow(e, t) {
1539
+ var o;
1540
+ if (c.logger.debug(d({ msg: "Starting device code flow" })), this.oidcConfig || await this.loadConfig(), !((o = this.oidcConfig) != null && o.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))
1573
1541
  return {
1574
1542
  error: "invalid_request",
1575
1543
  error_description: "Server does not support device code grant"
1576
1544
  };
1577
- let n = {
1545
+ let s = {
1578
1546
  grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1579
- client_id: u(this, w),
1580
- client_secret: u(this, S)
1547
+ client_id: p(this, k),
1548
+ client_secret: p(this, T)
1581
1549
  };
1582
- r && (n.scope = r);
1550
+ t && (s.scope = t);
1583
1551
  try {
1584
- return await this.post(t, n, this.authServerHeaders);
1585
- } catch (s) {
1586
- return d.logger.error(h({ err: s })), {
1552
+ return await this.post(e, s, this.authServerHeaders);
1553
+ } catch (n) {
1554
+ return c.logger.error(d({ err: n })), {
1587
1555
  error: "server_error",
1588
1556
  error_description: "Error connecting to authorization server"
1589
1557
  };
@@ -1596,29 +1564,29 @@ class Be {
1596
1564
  * @param deviceCode the device code to poll
1597
1565
  * @returns See {@link OAuthDeviceResponse}
1598
1566
  */
1599
- async pollDeviceCodeFlow(t) {
1600
- var n, i, s;
1601
- if (d.logger.debug(h({ msg: "Starting device code flow" })), this.oidcConfig || await this.loadConfig(), !((n = this.oidcConfig) != null && n.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))
1567
+ async pollDeviceCodeFlow(e) {
1568
+ var t, o, s;
1569
+ if (c.logger.debug(d({ msg: "Starting device code flow" })), this.oidcConfig || await this.loadConfig(), !((t = this.oidcConfig) != null && t.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))
1602
1570
  return {
1603
1571
  error: "invalid_request",
1604
1572
  error_description: "Server does not support device code grant"
1605
1573
  };
1606
- if (!((i = this.oidcConfig) != null && i.token_endpoint))
1574
+ if (!((o = this.oidcConfig) != null && o.token_endpoint))
1607
1575
  return {
1608
1576
  error: "server_error",
1609
1577
  error_description: "Cannot get token endpoint"
1610
1578
  };
1611
- let r = {
1579
+ let n = {
1612
1580
  grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1613
- client_id: u(this, w),
1614
- client_secret: u(this, S),
1615
- device_code: t
1581
+ client_id: p(this, k),
1582
+ client_secret: p(this, T),
1583
+ device_code: e
1616
1584
  };
1617
1585
  try {
1618
- const o = await this.post((s = this.oidcConfig) == null ? void 0 : s.token_endpoint, r, this.authServerHeaders);
1619
- return o.error, o;
1620
- } catch (o) {
1621
- return d.logger.error(h({ err: o })), {
1586
+ const i = await this.post((s = this.oidcConfig) == null ? void 0 : s.token_endpoint, n, this.authServerHeaders);
1587
+ return i.error, i;
1588
+ } catch (i) {
1589
+ return c.logger.error(d({ err: i })), {
1622
1590
  error: "server_error",
1623
1591
  error_description: "Error connecting to authorization server"
1624
1592
  };
@@ -1632,22 +1600,22 @@ class Be {
1632
1600
  * @returns the parsed JSON response as an object.
1633
1601
  * @throws any exception raised by `fetch()`
1634
1602
  */
1635
- async post(t, r, n = {}) {
1636
- d.logger.debug(h({
1603
+ async post(e, t, o = {}) {
1604
+ c.logger.debug(d({
1637
1605
  msg: "Fetch POST",
1638
- url: t,
1639
- params: Object.keys(r)
1606
+ url: e,
1607
+ params: Object.keys(t)
1640
1608
  }));
1641
- let i = {};
1642
- return this.authServerCredentials && (i.credentials = this.authServerCredentials), this.authServerMode && (i.mode = this.authServerMode), await (await fetch(t, {
1609
+ let s = {};
1610
+ return this.authServerCredentials && (s.credentials = this.authServerCredentials), this.authServerMode && (s.mode = this.authServerMode), await (await fetch(e, {
1643
1611
  method: "POST",
1644
- ...i,
1612
+ ...s,
1645
1613
  headers: {
1646
1614
  Accept: "application/json",
1647
1615
  "Content-Type": "application/json",
1648
- ...n
1616
+ ...o
1649
1617
  },
1650
- body: JSON.stringify(r)
1618
+ body: JSON.stringify(t)
1651
1619
  })).json();
1652
1620
  }
1653
1621
  /**
@@ -1658,16 +1626,16 @@ class Be {
1658
1626
  * @returns the parsed JSON response as an object.
1659
1627
  * @throws any exception raised by `fetch()`
1660
1628
  */
1661
- async get(t, r = {}) {
1662
- d.logger.debug(h({ msg: "Fetch GET", url: t }));
1663
- let n = {};
1664
- return this.authServerCredentials && (n.credentials = this.authServerCredentials), this.authServerMode && (n.mode = this.authServerMode), await (await fetch(t, {
1629
+ async get(e, t = {}) {
1630
+ c.logger.debug(d({ msg: "Fetch GET", url: e }));
1631
+ let o = {};
1632
+ return this.authServerCredentials && (o.credentials = this.authServerCredentials), this.authServerMode && (o.mode = this.authServerMode), await (await fetch(e, {
1665
1633
  method: "GET",
1666
- ...n,
1634
+ ...o,
1667
1635
  headers: {
1668
1636
  Accept: "application/json",
1669
1637
  "Content-Type": "application/json",
1670
- ...r
1638
+ ...t
1671
1639
  }
1672
1640
  })).json();
1673
1641
  }
@@ -1680,9 +1648,9 @@ class Be {
1680
1648
  * be valid and the `type` claim in the payload must be set to `id`.
1681
1649
  * @returns the parsed payload or undefined if the token is invalid.
1682
1650
  */
1683
- async validateIdToken(t) {
1651
+ async validateIdToken(e) {
1684
1652
  try {
1685
- return await this.tokenConsumer.tokenAuthorized(t, "id");
1653
+ return await this.tokenConsumer.tokenAuthorized(e, "id");
1686
1654
  } catch {
1687
1655
  return;
1688
1656
  }
@@ -1694,20 +1662,20 @@ class Be {
1694
1662
  * @returns the parsed JSON of the payload, or undefinedf if it is not
1695
1663
  * valid.
1696
1664
  */
1697
- async idTokenAuthorized(t) {
1665
+ async idTokenAuthorized(e) {
1698
1666
  try {
1699
- return await this.tokenConsumer.tokenAuthorized(t, "id");
1700
- } catch (r) {
1701
- d.logger.warn(h({ err: r }));
1667
+ return await this.tokenConsumer.tokenAuthorized(e, "id");
1668
+ } catch (t) {
1669
+ c.logger.warn(d({ err: t }));
1702
1670
  return;
1703
1671
  }
1704
1672
  }
1705
- getTokenPayload(t) {
1706
- return Me(t);
1673
+ getTokenPayload(e) {
1674
+ return ar(e);
1707
1675
  }
1708
1676
  }
1709
- w = /* @__PURE__ */ new WeakMap(), S = /* @__PURE__ */ new WeakMap(), N = /* @__PURE__ */ new WeakMap(), T = /* @__PURE__ */ new WeakMap(), R = /* @__PURE__ */ new WeakMap();
1710
- class Le {
1677
+ k = /* @__PURE__ */ new WeakMap(), T = /* @__PURE__ */ new WeakMap(), q = /* @__PURE__ */ new WeakMap(), F = /* @__PURE__ */ new WeakMap(), J = /* @__PURE__ */ new WeakMap();
1678
+ class dr {
1711
1679
  /**
1712
1680
  * Constrctor
1713
1681
  *
@@ -1715,18 +1683,10 @@ class Le {
1715
1683
  * of the JWT. The token is rejected if it doesn't match.
1716
1684
  * @param options See {@link OAuthTokenConsumerBaseOptions}.
1717
1685
  */
1718
- constructor(t, r = {}) {
1719
- a(this, "audience");
1720
- a(this, "jwtKeyType");
1721
- a(this, "jwtSecretKey");
1722
- a(this, "jwtPublicKey");
1723
- a(this, "clockTolerance", 10);
1724
- a(this, "authServerBaseUrl", "");
1725
- a(this, "oidcConfig");
1726
- a(this, "keys", {});
1727
- if (this.audience = t, r.authServerBaseUrl && (this.authServerBaseUrl = r.authServerBaseUrl), r.jwtKeyType && (this.jwtKeyType = r.jwtKeyType), r.jwtSecretKey && (this.jwtSecretKey = r.jwtSecretKey), r.jwtPublicKey && (this.jwtPublicKey = r.jwtPublicKey), r.clockTolerance && (this.clockTolerance = r.clockTolerance), r.oidcConfig && (this.oidcConfig = r.oidcConfig), this.jwtPublicKey && !this.jwtKeyType)
1686
+ constructor(e, t = {}) {
1687
+ if (l(this, "audience"), l(this, "jwtKeyType"), l(this, "jwtSecretKey"), l(this, "jwtPublicKey"), l(this, "clockTolerance", 10), l(this, "authServerBaseUrl", ""), l(this, "oidcConfig"), l(this, "keys", {}), this.audience = e, t.authServerBaseUrl && (this.authServerBaseUrl = t.authServerBaseUrl), t.jwtKeyType && (this.jwtKeyType = t.jwtKeyType), t.jwtSecretKey && (this.jwtSecretKey = t.jwtSecretKey), t.jwtPublicKey && (this.jwtPublicKey = t.jwtPublicKey), t.clockTolerance && (this.clockTolerance = t.clockTolerance), t.oidcConfig && (this.oidcConfig = t.oidcConfig), this.jwtPublicKey && !this.jwtKeyType)
1728
1688
  throw new g(
1729
- y.Configuration,
1689
+ m.Configuration,
1730
1690
  "If specifying jwtPublic key, must also specify jwtKeyType"
1731
1691
  );
1732
1692
  }
@@ -1743,28 +1703,28 @@ class Le {
1743
1703
  if (this.jwtSecretKey) {
1744
1704
  if (!this.jwtKeyType)
1745
1705
  throw new g(
1746
- y.Configuration,
1706
+ m.Configuration,
1747
1707
  "Must specify jwtKeyType if setting jwtSecretKey"
1748
1708
  );
1749
- this.keys._default = await Oe(this.jwtSecretKey, this.jwtKeyType);
1709
+ this.keys._default = await Ye(this.jwtSecretKey, this.jwtKeyType);
1750
1710
  } else if (this.jwtPublicKey) {
1751
1711
  if (!this.jwtKeyType)
1752
1712
  throw new g(
1753
- y.Configuration,
1713
+ m.Configuration,
1754
1714
  "Must specify jwtKeyType if setting jwtPublicKey"
1755
1715
  );
1756
- const t = await Ee(this.jwtPublicKey, this.jwtKeyType);
1757
- this.keys._default = t;
1716
+ const e = await Ge(this.jwtPublicKey, this.jwtKeyType);
1717
+ this.keys._default = e;
1758
1718
  } else {
1759
1719
  if (this.oidcConfig || await this.loadConfig(), !this.oidcConfig)
1760
1720
  throw new g(
1761
- y.Connection,
1721
+ m.Connection,
1762
1722
  "Load OIDC config before Jwks"
1763
1723
  );
1764
1724
  await this.loadJwks();
1765
1725
  }
1766
- } catch (t) {
1767
- throw d.logger.debug(h({ err: t })), new g(y.Connection, "Couldn't load keys");
1726
+ } catch (e) {
1727
+ throw c.logger.debug(d({ err: e })), new g(m.Connection, "Couldn't load keys");
1768
1728
  }
1769
1729
  }
1770
1730
  /**
@@ -1776,28 +1736,28 @@ class Le {
1776
1736
  * @throws a {@link @crossauth/common!CrossauthError} object with {@link @crossauth/common!ErrorCode} of
1777
1737
  * - `Connection` if the fetch to the authorization server failed.
1778
1738
  */
1779
- async loadConfig(t) {
1780
- if (t) {
1781
- this.oidcConfig = t;
1739
+ async loadConfig(e) {
1740
+ if (e) {
1741
+ this.oidcConfig = e;
1782
1742
  return;
1783
1743
  }
1784
1744
  if (!this.authServerBaseUrl)
1785
- throw new g(y.Connection, "Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");
1786
- let r;
1745
+ throw new g(m.Connection, "Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");
1746
+ let t;
1787
1747
  try {
1788
- r = await fetch(new URL("/.well-known/openid-configuration", this.authServerBaseUrl));
1789
- } catch (n) {
1790
- d.logger.error(h({ err: n }));
1748
+ t = await fetch(new URL("/.well-known/openid-configuration", this.authServerBaseUrl));
1749
+ } catch (o) {
1750
+ c.logger.error(d({ err: o }));
1791
1751
  }
1792
- if (!r || !r.ok)
1793
- throw new g(y.Connection, "Couldn't get OIDC configuration");
1794
- this.oidcConfig = { ...te };
1752
+ if (!t || !t.ok)
1753
+ throw new g(m.Connection, "Couldn't get OIDC configuration");
1754
+ this.oidcConfig = { ...ye };
1795
1755
  try {
1796
- const n = await r.json();
1797
- for (const [i, s] of Object.entries(n))
1798
- this.oidcConfig[i] = s;
1756
+ const o = await t.json();
1757
+ for (const [s, n] of Object.entries(o))
1758
+ this.oidcConfig[s] = n;
1799
1759
  } catch {
1800
- throw new g(y.Connection, "Unrecognized response from OIDC configuration endpoint");
1760
+ throw new g(m.Connection, "Unrecognized response from OIDC configuration endpoint");
1801
1761
  }
1802
1762
  }
1803
1763
  /**
@@ -1809,40 +1769,40 @@ class Le {
1809
1769
  * - `Connection` if the fetch to the authorization server failed,
1810
1770
  * the OIDC configuration wasn't set or the keys could not be parsed.
1811
1771
  */
1812
- async loadJwks(t) {
1813
- if (t) {
1772
+ async loadJwks(e) {
1773
+ if (e) {
1814
1774
  this.keys = {};
1815
- for (let r = 0; r < t.keys.length; ++r) {
1816
- const n = t.keys[r];
1817
- this.keys[n.kid ?? "_default"] = await Z(t.keys[r]);
1775
+ for (let t = 0; t < e.keys.length; ++t) {
1776
+ const o = e.keys[t];
1777
+ this.keys[o.kid ?? "_default"] = await ue(e.keys[t]);
1818
1778
  }
1819
1779
  } else {
1820
1780
  if (!this.oidcConfig)
1821
- throw new g(y.Connection, "Load OIDC config before Jwks");
1822
- let r;
1781
+ throw new g(m.Connection, "Load OIDC config before Jwks");
1782
+ let t;
1823
1783
  try {
1824
- r = await fetch(new URL(this.oidcConfig.jwks_uri));
1825
- } catch (n) {
1826
- d.logger.error(h({ err: n }));
1784
+ t = await fetch(new URL(this.oidcConfig.jwks_uri));
1785
+ } catch (o) {
1786
+ c.logger.error(d({ err: o }));
1827
1787
  }
1828
- if (!r || !r.ok)
1829
- throw new g(y.Connection, "Couldn't get OIDC configuration");
1788
+ if (!t || !t.ok)
1789
+ throw new g(m.Connection, "Couldn't get OIDC configuration");
1830
1790
  this.keys = {};
1831
1791
  try {
1832
- const n = await r.json();
1833
- if (!("keys" in n) || !Array.isArray(n.keys))
1834
- throw new g(y.Connection, "Couldn't fetch keys");
1835
- for (let i = 0; i < n.keys.length; ++i)
1792
+ const o = await t.json();
1793
+ if (!("keys" in o) || !Array.isArray(o.keys))
1794
+ throw new g(m.Connection, "Couldn't fetch keys");
1795
+ for (let s = 0; s < o.keys.length; ++s)
1836
1796
  try {
1837
- let s = "_default";
1838
- "kid" in n.keys[i] && typeof n.keys[i] == "string" && (s = String(n.keys[i]));
1839
- const o = await Z(n.keys[i]);
1840
- this.keys[s] = o;
1841
- } catch (s) {
1842
- throw d.logger.error(h({ err: s })), new g(y.Connection, "Couldn't load keys");
1797
+ let n = "_default";
1798
+ "kid" in o.keys[s] && typeof o.keys[s] == "string" && (n = String(o.keys[s]));
1799
+ const i = await ue(o.keys[s]);
1800
+ this.keys[n] = i;
1801
+ } catch (n) {
1802
+ throw c.logger.error(d({ err: n })), new g(m.Connection, "Couldn't load keys");
1843
1803
  }
1844
- } catch (n) {
1845
- throw d.logger.error(h({ err: n })), new g(y.Connection, "Unrecognized response from OIDC jwks endpoint");
1804
+ } catch (o) {
1805
+ throw c.logger.error(d({ err: o })), new g(m.Connection, "Unrecognized response from OIDC jwks endpoint");
1846
1806
  }
1847
1807
  }
1848
1808
  }
@@ -1857,58 +1817,56 @@ class Le {
1857
1817
  * fails.
1858
1818
  * @returns the JWT payload if the token is valid, `undefined` otherwise.
1859
1819
  */
1860
- async tokenAuthorized(t, r) {
1820
+ async tokenAuthorized(e, t) {
1861
1821
  (!this.keys || Object.keys(this.keys).length == 0) && await this.loadKeys();
1862
- const n = await this.validateToken(t);
1863
- if (n) {
1864
- if (n.type != r && d.logger.error(h({ msg: r + " expected but got " + n.type })), n.iss != this.authServerBaseUrl) {
1865
- d.logger.error(h({ msg: `Invalid issuer ${n.iss} in access token`, hashedAccessToken: await this.hash(n.jti) }));
1822
+ const o = await this.validateToken(e);
1823
+ if (o) {
1824
+ if (o.type != t && c.logger.error(d({ msg: t + " expected but got " + o.type })), o.iss != this.authServerBaseUrl) {
1825
+ c.logger.error(d({ msg: `Invalid issuer ${o.iss} in access token`, hashedAccessToken: await this.hash(o.jti) }));
1866
1826
  return;
1867
1827
  }
1868
- if (n.aud && (Array.isArray(n.aud) && !n.aud.includes(this.audience) || !Array.isArray(n.aud) && n.aud != this.audience)) {
1869
- d.logger.error(h({ msg: `Invalid audience ${n.aud} in access token`, hashedAccessToken: await this.hash(n.jti) }));
1828
+ if (o.aud && (Array.isArray(o.aud) && !o.aud.includes(this.audience) || !Array.isArray(o.aud) && o.aud != this.audience)) {
1829
+ c.logger.error(d({ msg: `Invalid audience ${o.aud} in access token`, hashedAccessToken: await this.hash(o.jti) }));
1870
1830
  return;
1871
1831
  }
1872
- return n;
1832
+ return o;
1873
1833
  }
1874
1834
  }
1875
- async validateToken(t) {
1876
- (!this.keys || Object.keys(this.keys).length == 0) && d.logger.warn("No keys loaded so cannot validate tokens");
1877
- let r;
1835
+ async validateToken(e) {
1836
+ (!this.keys || Object.keys(this.keys).length == 0) && c.logger.warn("No keys loaded so cannot validate tokens");
1837
+ let t;
1878
1838
  try {
1879
- r = qe(t).kid;
1839
+ t = nr(e).kid;
1880
1840
  } catch {
1881
- d.logger.warn(h({ msg: "Invalid access token format" }));
1841
+ c.logger.warn(d({ msg: "Invalid access token format" }));
1882
1842
  return;
1883
1843
  }
1884
- let n;
1885
- "_default" in this.keys && (n = this.keys._default);
1886
- for (let i in this.keys)
1887
- if (r == i) {
1888
- n = this.keys[i];
1844
+ let o;
1845
+ "_default" in this.keys && (o = this.keys._default);
1846
+ for (let s in this.keys)
1847
+ if (t == s) {
1848
+ o = this.keys[s];
1889
1849
  break;
1890
1850
  }
1891
- if (!n) {
1892
- d.logger.warn(h({ msg: "No matching keys found for access token" }));
1851
+ if (!o) {
1852
+ c.logger.warn(d({ msg: "No matching keys found for access token" }));
1893
1853
  return;
1894
1854
  }
1895
1855
  try {
1896
- const { payload: i } = await Je(t, n), s = JSON.parse(new TextDecoder().decode(i));
1897
- if (s.exp * 1e3 < Date.now() + this.clockTolerance) {
1898
- d.logger.warn(h({ msg: "Access token has expired" }));
1856
+ const { payload: s } = await ir(e, o), n = JSON.parse(new TextDecoder().decode(s));
1857
+ if (n.exp * 1e3 < Date.now() + this.clockTolerance) {
1858
+ c.logger.warn(d({ msg: "Access token has expired" }));
1899
1859
  return;
1900
1860
  }
1901
- return s;
1861
+ return n;
1902
1862
  } catch {
1903
- d.logger.warn(h({ msg: "Access token did not validate" }));
1863
+ c.logger.warn(d({ msg: "Access token did not validate" }));
1904
1864
  return;
1905
1865
  }
1906
1866
  }
1907
1867
  }
1908
- const TOLERANCE_SECONDS = 30;
1909
- const AUTOREFRESH_RETRIES = 2;
1910
- const AUTOREFRESH_RETRY_INTERVAL_SECS = 30;
1911
- class OAuthAutoRefresher {
1868
+ const fe = 30, Z = 2, ae = 30;
1869
+ class Ae {
1912
1870
  /**
1913
1871
  * Constructor
1914
1872
  *
@@ -1921,141 +1879,88 @@ class OAuthAutoRefresher {
1921
1879
  * - `headers` - adds headers to fetfh calls
1922
1880
  * - `tokenProvider` - class for fetching tokens and adding them to requests
1923
1881
  */
1924
- constructor(options) {
1925
- __publicField(this, "autoRefreshUrl", "/autorefresh");
1926
- __publicField(this, "csrfHeader", "X-CROSSAUTH-CSRF");
1927
- __publicField(this, "headers", {});
1928
- __publicField(this, "autoRefreshActive", false);
1929
- __publicField(this, "mode", "cors");
1930
- __publicField(this, "credentials", "same-origin");
1931
- __publicField(this, "tokenProvider");
1932
- this.tokenProvider = options.tokenProvider;
1933
- this.autoRefreshUrl = options.autoRefreshUrl;
1934
- if (options.csrfHeader) this.csrfHeader = options.csrfHeader;
1935
- if (options.headers) this.headers = options.headers;
1936
- if (options.mode) this.mode = options.mode;
1937
- if (options.credentials) this.credentials = options.credentials;
1938
- }
1939
- async startAutoRefresh(tokensToFetch = ["access", "id"], errorFn) {
1940
- if (!this.autoRefreshActive) {
1941
- this.autoRefreshActive = true;
1942
- d.logger.debug(h({ msg: "Starting auto refresh" }));
1943
- await this.scheduleAutoRefresh(tokensToFetch, errorFn);
1944
- }
1882
+ constructor(e) {
1883
+ f(this, "autoRefreshUrl", "/autorefresh");
1884
+ f(this, "csrfHeader", "X-CROSSAUTH-CSRF");
1885
+ f(this, "headers", {});
1886
+ f(this, "autoRefreshActive", !1);
1887
+ f(this, "mode", "cors");
1888
+ f(this, "credentials", "same-origin");
1889
+ f(this, "tokenProvider");
1890
+ this.tokenProvider = e.tokenProvider, this.autoRefreshUrl = e.autoRefreshUrl, e.csrfHeader && (this.csrfHeader = e.csrfHeader), e.headers && (this.headers = e.headers), e.mode && (this.mode = e.mode), e.credentials && (this.credentials = e.credentials);
1891
+ }
1892
+ async startAutoRefresh(e = ["access", "id"], t) {
1893
+ this.autoRefreshActive || (this.autoRefreshActive = !0, c.logger.debug(d({ msg: "Starting auto refresh" })), await this.scheduleAutoRefresh(e, t));
1945
1894
  }
1946
1895
  stopAutoRefresh() {
1947
- this.autoRefreshActive = false;
1948
- d.logger.debug(h({ msg: "Stopping auto refresh" }));
1949
- }
1950
- async scheduleAutoRefresh(tokensToFetch, errorFn) {
1951
- const csrfTokenPromise = this.tokenProvider.getCsrfToken();
1952
- const csrfToken = csrfTokenPromise ? await csrfTokenPromise : void 0;
1953
- const expiries = await this.tokenProvider.getTokenExpiries([...tokensToFetch, "refresh"], csrfToken);
1954
- if (expiries.refresh == void 0) {
1955
- d.logger.debug(h({ msg: `No refresh token found` }));
1896
+ this.autoRefreshActive = !1, c.logger.debug(d({ msg: "Stopping auto refresh" }));
1897
+ }
1898
+ async scheduleAutoRefresh(e, t) {
1899
+ const o = this.tokenProvider.getCsrfToken(), s = o ? await o : void 0, n = await this.tokenProvider.getTokenExpiries([...e, "refresh"], s);
1900
+ if (n.refresh == null) {
1901
+ c.logger.debug(d({ msg: "No refresh token found" }));
1956
1902
  return;
1957
1903
  }
1958
- const now = Date.now();
1959
- let tokenExpiry = expiries.id;
1960
- if (!tokenExpiry || expiries.access && expiries.access < tokenExpiry) tokenExpiry = expiries.access;
1961
- if (!tokenExpiry) {
1962
- d.logger.debug(h({ msg: `No tokens expire` }));
1904
+ const i = Date.now();
1905
+ let a = n.id;
1906
+ if ((!a || n.access && n.access < a) && (a = n.access), !a) {
1907
+ c.logger.debug(d({ msg: "No tokens expire" }));
1963
1908
  return;
1964
1909
  }
1965
- const renewTime = tokenExpiry * 1e3 - now - TOLERANCE_SECONDS;
1966
- if (renewTime < 0) {
1967
- d.logger.debug(h({ msg: `Expiry time has passed` }));
1910
+ const h = a * 1e3 - i - fe;
1911
+ if (h < 0) {
1912
+ c.logger.debug(d({ msg: "Expiry time has passed" }));
1968
1913
  return;
1969
1914
  }
1970
- if (expiries.refresh && expiries.refresh - TOLERANCE_SECONDS < renewTime) {
1971
- d.logger.debug(h({ msg: `Refresh token has expired` }));
1915
+ if (n.refresh && n.refresh - fe < h) {
1916
+ c.logger.debug(d({ msg: "Refresh token has expired" }));
1972
1917
  return;
1973
1918
  }
1974
- let wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1975
- d.logger.debug(h({ msg: `Waiting ${renewTime} before refreshing tokens` }));
1976
- await wait(renewTime);
1977
- await this.autoRefresh(tokensToFetch, csrfToken, errorFn);
1919
+ let u = (y) => new Promise((_) => setTimeout(_, y));
1920
+ c.logger.debug(d({ msg: `Waiting ${h} before refreshing tokens` })), await u(h), await this.autoRefresh(e, s, t);
1978
1921
  }
1979
- async autoRefresh(tokensToFetch, csrfToken, errorFn) {
1922
+ async autoRefresh(e, t, o) {
1980
1923
  if (this.autoRefreshActive) {
1981
- let reply = void 0;
1982
- let success = false;
1983
- let tries = 0;
1984
- while (!success && tries <= AUTOREFRESH_RETRIES) {
1924
+ let s, n = !1, i = 0;
1925
+ for (; !n && i <= Z; )
1985
1926
  try {
1986
- let headers = { ...this.headers };
1987
- if (csrfToken) {
1988
- headers[this.csrfHeader] = csrfToken;
1989
- }
1990
- d.logger.debug(h({ msg: `Initiating auto refresh` }));
1991
- const resp = await this.tokenProvider.jsonFetchWithToken(
1927
+ let a = { ...this.headers };
1928
+ t && (a[this.csrfHeader] = t), c.logger.debug(d({ msg: "Initiating auto refresh" }));
1929
+ const h = await this.tokenProvider.jsonFetchWithToken(
1992
1930
  this.autoRefreshUrl,
1993
1931
  {
1994
1932
  method: "POST",
1995
1933
  headers: {
1996
- "Accept": "application/json",
1934
+ Accept: "application/json",
1997
1935
  "Content-Type": "application/json",
1998
- ...headers
1936
+ ...a
1999
1937
  },
2000
1938
  mode: this.mode,
2001
1939
  credentials: this.credentials,
2002
1940
  body: {
2003
- csrfToken
1941
+ csrfToken: t
2004
1942
  }
2005
1943
  },
2006
1944
  "refresh"
2007
1945
  );
2008
- if (!resp.ok) {
2009
- d.logger.error(h({ msg: "Failed auto refreshing tokens", status: resp.status }));
2010
- }
2011
- reply = await resp.json();
2012
- if (reply == null ? void 0 : reply.ok) {
2013
- await this.scheduleAutoRefresh(tokensToFetch, errorFn);
2014
- success = true;
1946
+ if (h.ok || c.logger.error(d({ msg: "Failed auto refreshing tokens", status: h.status })), s = await h.json(), s != null && s.ok) {
1947
+ await this.scheduleAutoRefresh(e, o), n = !0;
2015
1948
  try {
2016
- await this.tokenProvider.receiveTokens(reply);
2017
- } catch (e) {
2018
- const cerr = g.asCrossauthError(e);
2019
- if (errorFn) {
2020
- errorFn("Couldn't receive tokens", cerr);
2021
- } else {
2022
- d.logger.debug(h({ err: e }));
2023
- d.logger.error(h({ msg: "Error receiving tokens", cerr }));
2024
- }
1949
+ await this.tokenProvider.receiveTokens(s);
1950
+ } catch (u) {
1951
+ const y = g.asCrossauthError(u);
1952
+ o ? o("Couldn't receive tokens", y) : (c.logger.debug(d({ err: u })), c.logger.error(d({ msg: "Error receiving tokens", cerr: y })));
2025
1953
  }
2026
- } else {
2027
- if (tries < AUTOREFRESH_RETRIES) {
2028
- d.logger.error(h({ msg: `Failed auto refreshing tokens. Retrying in ${AUTOREFRESH_RETRY_INTERVAL_SECS} seconds` }));
2029
- let wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2030
- await wait(AUTOREFRESH_RETRY_INTERVAL_SECS * 1e3);
2031
- } else {
2032
- d.logger.error(h({ msg: `Failed auto refreshing tokens. Number of retries exceeded` }));
2033
- if (errorFn) {
2034
- errorFn("Failed auto refreshing tokens");
2035
- }
2036
- }
2037
- tries++;
2038
- }
2039
- } catch (e) {
2040
- const ce2 = g.asCrossauthError(e);
2041
- d.logger.debug(h({ err: ce2 }));
2042
- if (tries < AUTOREFRESH_RETRIES) {
2043
- d.logger.error(h({ msg: `Failed auto refreshing tokens. Retrying in ${AUTOREFRESH_RETRIES} seconds` }));
2044
- let wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2045
- await wait(AUTOREFRESH_RETRY_INTERVAL_SECS);
2046
- } else {
2047
- d.logger.error(h({ msg: `Failed auto refreshing tokens. Number of retries exceeded` }));
2048
- if (errorFn) {
2049
- errorFn(ce2.message, ce2);
2050
- }
2051
- }
2052
- tries++;
1954
+ } else
1955
+ i < Z ? (c.logger.error(d({ msg: `Failed auto refreshing tokens. Retrying in ${ae} seconds` })), await ((y) => new Promise((_) => setTimeout(_, y)))(ae * 1e3)) : (c.logger.error(d({ msg: "Failed auto refreshing tokens. Number of retries exceeded" })), o && o("Failed auto refreshing tokens")), i++;
1956
+ } catch (a) {
1957
+ const h = g.asCrossauthError(a);
1958
+ c.logger.debug(d({ err: h })), i < Z ? (c.logger.error(d({ msg: `Failed auto refreshing tokens. Retrying in ${Z} seconds` })), await ((y) => new Promise((_) => setTimeout(_, y)))(ae)) : (c.logger.error(d({ msg: "Failed auto refreshing tokens. Number of retries exceeded" })), o && o(h.message, h)), i++;
2053
1959
  }
2054
- }
2055
1960
  }
2056
1961
  }
2057
1962
  }
2058
- class OAuthDeviceCodePoller {
1963
+ class Pe {
2059
1964
  /**
2060
1965
  * Constructor
2061
1966
  *
@@ -2065,105 +1970,73 @@ class OAuthDeviceCodePoller {
2065
1970
  * - `credentials` - overrides the default `credentials` for fetch calls
2066
1971
  * - `headers` - adds headers to fetfh calls
2067
1972
  */
2068
- constructor(options) {
2069
- __publicField(this, "deviceCodePollUrl", "/devicecodepoll");
2070
- __publicField(this, "headers", {});
2071
- __publicField(this, "pollingActive", false);
2072
- __publicField(this, "mode", "cors");
2073
- __publicField(this, "credentials", "same-origin");
2074
- __publicField(this, "respectRedirect", true);
2075
- __publicField(this, "oauthClient");
2076
- this.oauthClient = options.oauthClient;
2077
- if (options.deviceCodePollUrl != void 0) this.deviceCodePollUrl = options.deviceCodePollUrl;
2078
- if (options.headers) this.headers = options.headers;
2079
- if (options.mode) this.mode = options.mode;
2080
- if (options.credentials) this.credentials = options.credentials;
2081
- }
2082
- async startPolling(deviceCode, pollResultFn, interval = 5) {
2083
- if (!this.pollingActive) {
2084
- this.pollingActive = true;
2085
- d.logger.debug(h({ msg: "Starting auto refresh" }));
2086
- await this.poll(deviceCode, interval, pollResultFn);
2087
- }
1973
+ constructor(e) {
1974
+ f(this, "deviceCodePollUrl", "/devicecodepoll");
1975
+ f(this, "headers", {});
1976
+ f(this, "pollingActive", !1);
1977
+ f(this, "mode", "cors");
1978
+ f(this, "credentials", "same-origin");
1979
+ f(this, "respectRedirect", !0);
1980
+ f(this, "oauthClient");
1981
+ this.oauthClient = e.oauthClient, e.deviceCodePollUrl != null && (this.deviceCodePollUrl = e.deviceCodePollUrl), e.headers && (this.headers = e.headers), e.mode && (this.mode = e.mode), e.credentials && (this.credentials = e.credentials);
1982
+ }
1983
+ async startPolling(e, t, o = 5) {
1984
+ this.pollingActive || (this.pollingActive = !0, c.logger.debug(d({ msg: "Starting auto refresh" })), await this.poll(e, o, t));
2088
1985
  }
2089
1986
  stopPolling() {
2090
- this.pollingActive = false;
2091
- d.logger.debug(h({ msg: "Stopping auto refresh" }));
2092
- }
2093
- async poll(deviceCode, interval, pollResultFn) {
2094
- var _a;
2095
- if (!deviceCode) {
2096
- d.logger.debug(h({ msg: "device code poll: no device code provided" }));
2097
- pollResultFn("error", "Error waiting for authorization");
2098
- } else {
1987
+ this.pollingActive = !1, c.logger.debug(d({ msg: "Stopping auto refresh" }));
1988
+ }
1989
+ async poll(e, t, o) {
1990
+ var s;
1991
+ if (!e)
1992
+ c.logger.debug(d({ msg: "device code poll: no device code provided" })), o("error", "Error waiting for authorization");
1993
+ else
2099
1994
  try {
2100
- d.logger.debug(h({ msg: "device code poll: poll" }));
2101
- if (!this.deviceCodePollUrl && this.oauthClient) {
2102
- if (!this.oauthClient.getOidcConfig()) await this.oauthClient.loadConfig();
2103
- if (!((_a = this.oauthClient.getOidcConfig()) == null ? void 0 : _a.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob"))) {
1995
+ if (c.logger.debug(d({ msg: "device code poll: poll" })), !this.deviceCodePollUrl && this.oauthClient) {
1996
+ if (this.oauthClient.getOidcConfig() || await this.oauthClient.loadConfig(), !((s = this.oauthClient.getOidcConfig()) != null && s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))
2104
1997
  return {
2105
1998
  error: "invalid_request",
2106
1999
  error_description: "Server does not support password_mfa grant"
2107
2000
  };
2108
- }
2109
- let config = this.oauthClient.getOidcConfig();
2110
- if (!(config == null ? void 0 : config.token_endpoint)) return {
2001
+ let i = this.oauthClient.getOidcConfig();
2002
+ if (!(i != null && i.token_endpoint)) return {
2111
2003
  error: "server_error",
2112
2004
  error_description: "Couldn't get OIDC configuration"
2113
2005
  };
2114
- this.deviceCodePollUrl = config.token_endpoint;
2006
+ this.deviceCodePollUrl = i.token_endpoint;
2115
2007
  }
2116
- if (!this.deviceCodePollUrl) {
2008
+ if (!this.deviceCodePollUrl)
2117
2009
  return {
2118
2010
  error: "server_error",
2119
2011
  error_description: "Must either provide deviceCodePollUrl or an oauthClient to fetch it from"
2120
2012
  };
2121
- }
2122
- const resp = await fetch(this.deviceCodePollUrl, {
2013
+ const n = await fetch(this.deviceCodePollUrl, {
2123
2014
  method: "POST",
2124
- body: JSON.stringify({ device_code: deviceCode }),
2015
+ body: JSON.stringify({ device_code: e }),
2125
2016
  headers: { "content-type": "application/json" }
2126
2017
  });
2127
- if (resp.redirected) {
2128
- this.pollingActive = false;
2129
- if (resp.redirected) {
2130
- pollResultFn("completeAndRedirect", void 0, resp.url);
2131
- }
2132
- } else if (!resp.ok) {
2133
- this.pollingActive = false;
2134
- pollResultFn("error", "Received an error from the authorization server");
2135
- } else {
2136
- const body = await resp.json();
2137
- d.logger.debug(h({ msg: "device code poll: received" + JSON.stringify(body) }));
2138
- if (body.error == "expired_token") {
2139
- this.pollingActive = false;
2140
- pollResultFn("expired_token", "Timeout waiting for authorization");
2141
- } else if (body.error == "authorization_pending" || body.error == "slow_down") {
2142
- if (body.error == "slow_down") interval += 5;
2143
- let waitseconds = body.interval ?? interval;
2144
- let wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2145
- d.logger.debug(h({ msg: "device code poll: waiting " + String(waitseconds) + " seconds" }));
2146
- await wait(waitseconds * 1e3);
2147
- if (this.pollingActive) this.poll(deviceCode, interval, pollResultFn);
2148
- } else if (body.error) {
2149
- this.pollingActive = false;
2150
- pollResultFn("error", body.error_description ?? body.error);
2151
- } else {
2152
- this.pollingActive = false;
2153
- pollResultFn("complete");
2154
- }
2018
+ if (n.redirected)
2019
+ this.pollingActive = !1, n.redirected && o("completeAndRedirect", void 0, n.url);
2020
+ else if (!n.ok)
2021
+ this.pollingActive = !1, o("error", "Received an error from the authorization server");
2022
+ else {
2023
+ const i = await n.json();
2024
+ if (c.logger.debug(d({ msg: "device code poll: received" + JSON.stringify(i) })), i.error == "expired_token")
2025
+ this.pollingActive = !1, o("expired_token", "Timeout waiting for authorization");
2026
+ else if (i.error == "authorization_pending" || i.error == "slow_down") {
2027
+ i.error == "slow_down" && (t += 5);
2028
+ let a = i.interval ?? t, h = (u) => new Promise((y) => setTimeout(y, u));
2029
+ c.logger.debug(d({ msg: "device code poll: waiting " + String(a) + " seconds" })), await h(a * 1e3), this.pollingActive && this.poll(e, t, o);
2030
+ } else i.error ? (this.pollingActive = !1, o("error", i.error_description ?? i.error)) : (this.pollingActive = !1, o("complete"));
2155
2031
  }
2156
- } catch (e) {
2157
- this.pollingActive = false;
2158
- const ce2 = g.asCrossauthError(e);
2159
- d.logger.debug(h({ err: ce2 }));
2160
- d.logger.error(h({ msg: "Polling failed", cerr: ce2 }));
2161
- pollResultFn("error", ce2.message);
2032
+ } catch (n) {
2033
+ this.pollingActive = !1;
2034
+ const i = g.asCrossauthError(n);
2035
+ c.logger.debug(d({ err: i })), c.logger.error(d({ msg: "Polling failed", cerr: i })), o("error", i.message);
2162
2036
  }
2163
- }
2164
2037
  }
2165
2038
  }
2166
- class OAuthBffClient {
2039
+ class ur {
2167
2040
  /**
2168
2041
  * Constructor
2169
2042
  *
@@ -2184,34 +2057,23 @@ class OAuthBffClient {
2184
2057
  * - `credentials` - overrides the default `credentials` for fetch calls
2185
2058
  * - `headers` - adds headers to fetfh calls
2186
2059
  */
2187
- constructor(options = {}) {
2188
- __publicField(this, "bffPrefix", "/bff");
2189
- __publicField(this, "csrfHeader", "X-CROSSAUTH-CSRF");
2190
- __publicField(this, "enableCsrfProtection", true);
2191
- __publicField(this, "headers", {});
2192
- __publicField(this, "mode", "cors");
2193
- __publicField(this, "credentials", "same-origin");
2194
- __publicField(this, "autoRefresher");
2195
- __publicField(this, "deviceCodePoller");
2196
- __publicField(this, "getCsrfTokenUrl", "/api/getcsrftoken");
2197
- __publicField(this, "autoRefreshUrl", "/api/refreshtokens");
2198
- __publicField(this, "tokensUrl", "/tokens");
2199
- if (options.bffPrefix) this.bffPrefix = options.bffPrefix;
2200
- if (options.csrfHeader) this.csrfHeader = options.csrfHeader;
2201
- if (options.enableCsrfProtection != void 0) this.enableCsrfProtection = options.enableCsrfProtection;
2202
- if (options.getCsrfTokenUrl) this.getCsrfTokenUrl = options.getCsrfTokenUrl;
2203
- if (options.tokensUrl) this.tokensUrl = options.tokensUrl;
2204
- if (options.autoRefreshUrl) this.autoRefreshUrl = options.autoRefreshUrl;
2205
- if (!this.bffPrefix.endsWith("/")) this.bffPrefix += "/";
2206
- if (options.headers) this.headers = options.headers;
2207
- if (options.mode) this.mode = options.mode;
2208
- if (options.credentials) this.credentials = options.credentials;
2209
- this.autoRefresher = new OAuthAutoRefresher({
2210
- ...options,
2060
+ constructor(e = {}) {
2061
+ f(this, "bffPrefix", "/bff");
2062
+ f(this, "csrfHeader", "X-CROSSAUTH-CSRF");
2063
+ f(this, "enableCsrfProtection", !0);
2064
+ f(this, "headers", {});
2065
+ f(this, "mode", "cors");
2066
+ f(this, "credentials", "same-origin");
2067
+ f(this, "autoRefresher");
2068
+ f(this, "deviceCodePoller");
2069
+ f(this, "getCsrfTokenUrl", "/api/getcsrftoken");
2070
+ f(this, "autoRefreshUrl", "/api/refreshtokens");
2071
+ f(this, "tokensUrl", "/tokens");
2072
+ e.bffPrefix && (this.bffPrefix = e.bffPrefix), e.csrfHeader && (this.csrfHeader = e.csrfHeader), e.enableCsrfProtection != null && (this.enableCsrfProtection = e.enableCsrfProtection), e.getCsrfTokenUrl && (this.getCsrfTokenUrl = e.getCsrfTokenUrl), e.tokensUrl && (this.tokensUrl = e.tokensUrl), e.autoRefreshUrl && (this.autoRefreshUrl = e.autoRefreshUrl), this.bffPrefix.endsWith("/") || (this.bffPrefix += "/"), e.headers && (this.headers = e.headers), e.mode && (this.mode = e.mode), e.credentials && (this.credentials = e.credentials), this.autoRefresher = new Ae({
2073
+ ...e,
2211
2074
  autoRefreshUrl: this.autoRefreshUrl,
2212
2075
  tokenProvider: this
2213
- });
2214
- this.deviceCodePoller = new OAuthDeviceCodePoller({ ...options, oauthClient: void 0 });
2076
+ }), this.deviceCodePoller = new Pe({ ...e, oauthClient: void 0 });
2215
2077
  }
2216
2078
  /**
2217
2079
  * Gets a CSRF token from the server
@@ -2219,19 +2081,18 @@ class OAuthBffClient {
2219
2081
  * the `X-CROSSAUTH-CSRF` header
2220
2082
  */
2221
2083
  async getCsrfToken() {
2222
- if (!this.enableCsrfProtection) return void 0;
2223
- try {
2224
- const resp = await fetch(this.getCsrfTokenUrl, {
2225
- headers: this.headers,
2226
- credentials: this.credentials,
2227
- mode: this.mode
2228
- });
2229
- const json = await resp.json();
2230
- if (!json.ok) throw g.asCrossauthError(json);
2231
- return json.csrfToken;
2232
- } catch (e) {
2233
- throw g.asCrossauthError(e);
2234
- }
2084
+ if (this.enableCsrfProtection)
2085
+ try {
2086
+ const t = await (await fetch(this.getCsrfTokenUrl, {
2087
+ headers: this.headers,
2088
+ credentials: this.credentials,
2089
+ mode: this.mode
2090
+ })).json();
2091
+ if (!t.ok) throw g.asCrossauthError(t);
2092
+ return t.csrfToken;
2093
+ } catch (e) {
2094
+ throw g.asCrossauthError(e);
2095
+ }
2235
2096
  }
2236
2097
  /**
2237
2098
  * Fetches the ID token from the client.
@@ -2243,9 +2104,9 @@ class OAuthBffClient {
2243
2104
  * making the request
2244
2105
  * @returns the ID token payload or an empty object if there isn't one
2245
2106
  */
2246
- async getIdToken(csrfToken) {
2247
- const tokens = await this.getTokens(csrfToken);
2248
- return (tokens == null ? void 0 : tokens.id_token) ?? null;
2107
+ async getIdToken(e) {
2108
+ const t = await this.getTokens(e);
2109
+ return (t == null ? void 0 : t.id_token) ?? null;
2249
2110
  }
2250
2111
  /**
2251
2112
  * Returns whether or not there is an ID token stored in the BFF server
@@ -2255,11 +2116,9 @@ class OAuthBffClient {
2255
2116
  * making the request
2256
2117
  * @returns true or false
2257
2118
  */
2258
- async haveIdToken(csrfToken) {
2259
- const tokens = await this.getTokens(csrfToken);
2260
- if (tokens == null) return false;
2261
- if (tokens.have_id_token != void 0) return tokens.have_id_token;
2262
- return "id_token" in tokens;
2119
+ async haveIdToken(e) {
2120
+ const t = await this.getTokens(e);
2121
+ return t == null ? !1 : t.have_id_token != null ? t.have_id_token : "id_token" in t;
2263
2122
  }
2264
2123
  /**
2265
2124
  * Fetches the access token from the client.
@@ -2273,9 +2132,9 @@ class OAuthBffClient {
2273
2132
  * the ones given with {@link OAuthBffClient.addHeader} )
2274
2133
  * @returns the access token payload or an empty object if there isn't one
2275
2134
  */
2276
- async getAccessToken(csrfToken) {
2277
- const tokens = await this.getTokens(csrfToken);
2278
- return (tokens == null ? void 0 : tokens.access_token) ?? null;
2135
+ async getAccessToken(e) {
2136
+ const t = await this.getTokens(e);
2137
+ return (t == null ? void 0 : t.access_token) ?? null;
2279
2138
  }
2280
2139
  /**
2281
2140
  * Returns whether or not there is an access token stored in the BFF server
@@ -2285,11 +2144,9 @@ class OAuthBffClient {
2285
2144
  * making the request
2286
2145
  * @returns true or false
2287
2146
  */
2288
- async haveAccessToken(csrfToken) {
2289
- const tokens = await this.getTokens(csrfToken);
2290
- if (tokens == null) return false;
2291
- if (tokens.have_access_token != void 0) return tokens.have_access_token;
2292
- return "access_token" in tokens;
2147
+ async haveAccessToken(e) {
2148
+ const t = await this.getTokens(e);
2149
+ return t == null ? !1 : t.have_access_token != null ? t.have_access_token : "access_token" in t;
2293
2150
  }
2294
2151
  /**
2295
2152
  * Fetches the refresh token from the client.
@@ -2301,9 +2158,9 @@ class OAuthBffClient {
2301
2158
  * making the request
2302
2159
  * @returns the refresh token payload or an empty object if there isn't one
2303
2160
  */
2304
- async getRefreshToken(csrfToken) {
2305
- const tokens = await this.getTokens(csrfToken);
2306
- return (tokens == null ? void 0 : tokens.refresh_token) ?? null;
2161
+ async getRefreshToken(e) {
2162
+ const t = await this.getTokens(e);
2163
+ return (t == null ? void 0 : t.refresh_token) ?? null;
2307
2164
  }
2308
2165
  /**
2309
2166
  * Returns whether or not there is a refresh token stored in the BFF server
@@ -2313,11 +2170,9 @@ class OAuthBffClient {
2313
2170
  * making the request
2314
2171
  * @returns true or false
2315
2172
  */
2316
- async haveRefreshToken(csrfToken) {
2317
- const tokens = await this.getTokens(csrfToken);
2318
- if (tokens == null) return false;
2319
- if (tokens.have_refresh_token != void 0) return tokens.have_refresh_token;
2320
- return "refresh_token" in tokens;
2173
+ async haveRefreshToken(e) {
2174
+ const t = await this.getTokens(e);
2175
+ return t == null ? !1 : t.have_refresh_token != null ? t.have_refresh_token : "refresh_token" in t;
2321
2176
  }
2322
2177
  /**
2323
2178
  * Calls an API endpoint via the BFF server
@@ -2327,28 +2182,23 @@ class OAuthBffClient {
2327
2182
  * @param csrfToken : the CSRF token
2328
2183
  * @returns the HTTP status code and the body or null
2329
2184
  */
2330
- async api(method, endpoint, body, csrfToken) {
2331
- let headers = { ...this.headers };
2332
- if (!csrfToken && !["GET", "HEAD", "OPTIONS"].includes(method)) {
2333
- csrfToken = await this.getCsrfToken();
2334
- if (csrfToken) headers[this.csrfHeader] = csrfToken;
2335
- }
2336
- if (endpoint.startsWith("/")) endpoint = endpoint.substring(1);
2337
- let params = {};
2338
- if (body) params.body = JSON.stringify(body);
2339
- const resp = await fetch(
2340
- this.bffPrefix + endpoint,
2185
+ async api(e, t, o, s) {
2186
+ let n = { ...this.headers };
2187
+ !s && !["GET", "HEAD", "OPTIONS"].includes(e) && (s = await this.getCsrfToken(), s && (n[this.csrfHeader] = s)), t.startsWith("/") && (t = t.substring(1));
2188
+ let i = {};
2189
+ o && (i.body = JSON.stringify(o));
2190
+ const a = await fetch(
2191
+ this.bffPrefix + t,
2341
2192
  {
2342
- headers,
2343
- method,
2193
+ headers: n,
2194
+ method: e,
2344
2195
  mode: this.mode,
2345
2196
  credentials: this.credentials,
2346
- ...params
2197
+ ...i
2347
2198
  }
2348
2199
  );
2349
- let responseBody = null;
2350
- if (resp.body) responseBody = await resp.json();
2351
- return { status: resp.status, body: responseBody };
2200
+ let h = null;
2201
+ return a.body && (h = await a.json()), { status: a.status, body: h };
2352
2202
  }
2353
2203
  /**
2354
2204
  * Return all tokens that the client has been enabled to return.
@@ -2362,25 +2212,20 @@ class OAuthBffClient {
2362
2212
  * - `have_access_token`
2363
2213
  * - `have_refresh_token`
2364
2214
  */
2365
- async getTokens(csrfToken) {
2366
- if (!csrfToken) csrfToken = await this.getCsrfToken();
2367
- let headers = { ...this.headers };
2368
- if (csrfToken)
2369
- headers[this.csrfHeader] = csrfToken;
2215
+ async getTokens(e) {
2216
+ e || (e = await this.getCsrfToken());
2217
+ let t = { ...this.headers };
2218
+ e && (t[this.csrfHeader] = e);
2370
2219
  try {
2371
- const resp = await fetch(this.tokensUrl, {
2220
+ const o = await fetch(this.tokensUrl, {
2372
2221
  method: "POST",
2373
- headers,
2222
+ headers: t,
2374
2223
  mode: this.mode,
2375
2224
  credentials: this.credentials
2376
2225
  });
2377
- if (resp.status == 204) {
2378
- return {};
2379
- }
2380
- const body = await resp.json();
2381
- return body;
2382
- } catch (e) {
2383
- throw g.asCrossauthError(e);
2226
+ return o.status == 204 ? {} : await o.json();
2227
+ } catch (o) {
2228
+ throw g.asCrossauthError(o);
2384
2229
  }
2385
2230
  }
2386
2231
  /**
@@ -2388,8 +2233,8 @@ class OAuthBffClient {
2388
2233
  * @param tokensToFetch which tokens to fetch
2389
2234
  * @param errorFn what to call in case of error
2390
2235
  */
2391
- async startAutoRefresh(tokensToFetch = ["access", "id"], errorFn) {
2392
- return this.autoRefresher.startAutoRefresh(tokensToFetch, errorFn);
2236
+ async startAutoRefresh(e = ["access", "id"], t) {
2237
+ return this.autoRefresher.startAutoRefresh(e, t);
2393
2238
  }
2394
2239
  /**
2395
2240
  * Turns auto refresh of tokens off
@@ -2402,8 +2247,8 @@ class OAuthBffClient {
2402
2247
  * @param tokensToFetch which tokens to fetch
2403
2248
  * @param errorFn what to call in case of error
2404
2249
  */
2405
- async startDeviceCodePolling(deviceCode, pollResultFn, interval = 5) {
2406
- return this.deviceCodePoller.startPolling(deviceCode, pollResultFn, interval);
2250
+ async startDeviceCodePolling(e, t, o = 5) {
2251
+ return this.deviceCodePoller.startPolling(e, t, o);
2407
2252
  }
2408
2253
  /**
2409
2254
  * Turns off polling for a device code
@@ -2421,27 +2266,13 @@ class OAuthBffClient {
2421
2266
  * @returns for each token, either the expiry, `null` if it does not
2422
2267
  * expire, or `undefined` if the token does not exist
2423
2268
  */
2424
- async getTokenExpiries(tokensToFetch, csrfToken) {
2425
- const tokens = await this.getTokens(csrfToken);
2426
- const idToken = tokensToFetch.includes("id") ? (tokens == null ? void 0 : tokens.id_token) ?? null : null;
2427
- const accessToken = tokensToFetch.includes("access") ? (tokens == null ? void 0 : tokens.access_token) ?? null : null;
2428
- const refreshToken = tokensToFetch.includes("refresh") ? (tokens == null ? void 0 : tokens.refresh_token) ?? null : null;
2429
- let idTokenExpiry = void 0;
2430
- let accessTokenExpiry = void 0;
2431
- let refreshTokenExpiry = void 0;
2432
- if (idToken) {
2433
- idTokenExpiry = idToken.exp ? idToken.exp : null;
2434
- }
2435
- if (accessToken) {
2436
- accessTokenExpiry = accessToken.exp ? accessToken.exp : null;
2437
- }
2438
- if (refreshToken) {
2439
- refreshTokenExpiry = refreshToken.exp ? refreshToken.exp : null;
2440
- }
2441
- return {
2442
- id: idTokenExpiry,
2443
- access: accessTokenExpiry,
2444
- refresh: refreshTokenExpiry
2269
+ async getTokenExpiries(e, t) {
2270
+ const o = await this.getTokens(t), s = e.includes("id") ? (o == null ? void 0 : o.id_token) ?? null : null, n = e.includes("access") ? (o == null ? void 0 : o.access_token) ?? null : null, i = e.includes("refresh") ? (o == null ? void 0 : o.refresh_token) ?? null : null;
2271
+ let a, h, u;
2272
+ return s && (a = s.exp ? s.exp : null), n && (h = n.exp ? n.exp : null), i && (u = i.exp ? i.exp : null), {
2273
+ id: a,
2274
+ access: h,
2275
+ refresh: u
2445
2276
  };
2446
2277
  }
2447
2278
  /**
@@ -2451,30 +2282,27 @@ class OAuthBffClient {
2451
2282
  * @param token which token to add
2452
2283
  * @returns parsed JSON response
2453
2284
  */
2454
- async jsonFetchWithToken(url, params, _token) {
2455
- if (typeof params.body != "string") params.body = JSON.stringify(params.body);
2456
- return await fetch(url, params);
2285
+ async jsonFetchWithToken(e, t, o) {
2286
+ return typeof t.body != "string" && (t.body = JSON.stringify(t.body)), await fetch(e, t);
2457
2287
  }
2458
- receiveTokens(_tokens) {
2459
- return new Promise((_resolve) => {
2288
+ receiveTokens(e) {
2289
+ return new Promise((t) => {
2460
2290
  });
2461
2291
  }
2462
2292
  }
2463
- class OAuthTokenConsumer extends Le {
2293
+ class hr extends dr {
2464
2294
  /**
2465
2295
  * SHA256 and Base64-url-encodes the given test
2466
2296
  * @param plaintext the text to encode
2467
2297
  * @returns the SHA256 hash, Base64-url-encode
2468
2298
  */
2469
- async hash(plaintext) {
2470
- const encoder = new TextEncoder();
2471
- const data = encoder.encode(plaintext);
2472
- const hash = await crypto.subtle.digest("SHA-256", data);
2473
- const hashArray = Array.from(new Uint8Array(hash));
2474
- return btoa(hashArray.reduce((acc, current) => acc + String.fromCharCode(current), "")).replace(/\//g, "_").replace(/\+/g, "-").replace(/=+$/, "");
2299
+ async hash(e) {
2300
+ const o = new TextEncoder().encode(e), s = await crypto.subtle.digest("SHA-256", o), n = Array.from(new Uint8Array(s));
2301
+ return btoa(n.reduce((i, a) => i + String.fromCharCode(a), "")).replace(/\//g, "_").replace(/\+/g, "-").replace(/=+$/, "");
2475
2302
  }
2476
2303
  }
2477
- class OAuthClient extends Be {
2304
+ var j, O, R, K, z, B, L;
2305
+ class fr extends cr {
2478
2306
  /**
2479
2307
  * Constructor
2480
2308
  *
@@ -2515,129 +2343,71 @@ class OAuthClient extends Be {
2515
2343
  * Default is `/devicecodepoll`
2516
2344
  * For other options see {@link @crossauth/common/OAuthClientBase}.
2517
2345
  */
2518
- constructor(options) {
2519
- if (!options.tokenConsumer) {
2520
- options.tokenConsumer = new OAuthTokenConsumer(
2521
- options.client_id,
2522
- {
2523
- authServerBaseUrl: options.authServerBaseUrl
2524
- }
2525
- );
2526
- }
2527
- super(options);
2528
- __publicField(this, "resServerBaseUrl", "");
2529
- __publicField(this, "resServerHeaders", {});
2530
- __publicField(this, "resServerMode", "cors");
2531
- __publicField(this, "resServerCredentials", "same-origin");
2532
- __publicField(this, "accessTokenResponseType", "memory");
2533
- __publicField(this, "refreshTokenResponseType", "memory");
2534
- __publicField(this, "idTokenResponseType", "memory");
2535
- __publicField(this, "accessTokenName", "CROSSAUTH_AT");
2536
- __publicField(this, "refreshTokenName", "CROSSAUTH_RT");
2537
- __publicField(this, "idTokenName", "CROSSAUTH_IT");
2538
- __privateAdd(this, _accessToken);
2539
- __privateAdd(this, _refreshToken);
2540
- __privateAdd(this, _idTokenPayload);
2541
- __privateAdd(this, _accessTokenPayload);
2542
- __privateAdd(this, _refreshTokenPayload);
2543
- __privateAdd(this, _client_id);
2544
- __privateAdd(this, _client_secret);
2545
- __publicField(this, "autoRefresher");
2546
- __publicField(this, "deviceCodePoller");
2547
- __publicField(this, "deviceAuthorizationUrl", "device_authorization");
2548
- if (this.resServerBaseUrl != void 0) {
2549
- this.resServerBaseUrl = options.resServerBaseUrl ?? "";
2550
- if (this.resServerBaseUrl.length > 0 && !this.resServerBaseUrl.endsWith("/")) {
2551
- this.resServerBaseUrl += "/";
2346
+ constructor(t) {
2347
+ t.tokenConsumer || (t.tokenConsumer = new hr(
2348
+ t.client_id,
2349
+ {
2350
+ authServerBaseUrl: t.authServerBaseUrl
2552
2351
  }
2553
- }
2554
- if (options.accessTokenResponseType) this.accessTokenResponseType = options.accessTokenResponseType;
2555
- if (options.idTokenResponseType) this.idTokenResponseType = options.idTokenResponseType;
2556
- if (options.refreshTokenResponseType) this.refreshTokenResponseType = options.refreshTokenResponseType;
2557
- if (options.accessTokenName) this.accessTokenName = options.accessTokenName;
2558
- if (options.idTokenName) this.idTokenName = options.idTokenName;
2559
- if (options.refreshTokenName) this.refreshTokenName = options.refreshTokenName;
2560
- if (options.resServerHeaders) this.resServerHeaders = options.resServerHeaders;
2561
- if (options.resServerMode) this.resServerMode = options.resServerMode;
2562
- if (options.resServerCredentials) this.resServerCredentials = options.resServerCredentials;
2563
- if (options.client_id) __privateSet(this, _client_id, options.client_id);
2564
- if (options.client_secret) __privateSet(this, _client_secret, options.client_secret);
2565
- if (options.deviceAuthorizationUrl) this.deviceAuthorizationUrl = options.deviceAuthorizationUrl;
2566
- this.autoRefresher = new OAuthAutoRefresher({
2567
- ...options,
2352
+ ));
2353
+ super(t);
2354
+ f(this, "resServerBaseUrl", "");
2355
+ f(this, "resServerHeaders", {});
2356
+ f(this, "resServerMode", "cors");
2357
+ f(this, "resServerCredentials", "same-origin");
2358
+ f(this, "accessTokenResponseType", "memory");
2359
+ f(this, "refreshTokenResponseType", "memory");
2360
+ f(this, "idTokenResponseType", "memory");
2361
+ f(this, "accessTokenName", "CROSSAUTH_AT");
2362
+ f(this, "refreshTokenName", "CROSSAUTH_RT");
2363
+ f(this, "idTokenName", "CROSSAUTH_IT");
2364
+ N(this, j);
2365
+ N(this, O);
2366
+ N(this, R);
2367
+ N(this, K);
2368
+ N(this, z);
2369
+ N(this, B);
2370
+ N(this, L);
2371
+ f(this, "autoRefresher");
2372
+ f(this, "deviceCodePoller");
2373
+ f(this, "deviceAuthorizationUrl", "device_authorization");
2374
+ this.resServerBaseUrl != null && (this.resServerBaseUrl = t.resServerBaseUrl ?? "", this.resServerBaseUrl.length > 0 && !this.resServerBaseUrl.endsWith("/") && (this.resServerBaseUrl += "/")), t.accessTokenResponseType && (this.accessTokenResponseType = t.accessTokenResponseType), t.idTokenResponseType && (this.idTokenResponseType = t.idTokenResponseType), t.refreshTokenResponseType && (this.refreshTokenResponseType = t.refreshTokenResponseType), t.accessTokenName && (this.accessTokenName = t.accessTokenName), t.idTokenName && (this.idTokenName = t.idTokenName), t.refreshTokenName && (this.refreshTokenName = t.refreshTokenName), t.resServerHeaders && (this.resServerHeaders = t.resServerHeaders), t.resServerMode && (this.resServerMode = t.resServerMode), t.resServerCredentials && (this.resServerCredentials = t.resServerCredentials), t.client_id && b(this, B, t.client_id), t.client_secret && b(this, L, t.client_secret), t.deviceAuthorizationUrl && (this.deviceAuthorizationUrl = t.deviceAuthorizationUrl), this.autoRefresher = new Ae({
2375
+ ...t,
2568
2376
  autoRefreshUrl: this.authServerBaseUrl + "/token",
2569
2377
  tokenProvider: this
2570
- });
2571
- this.deviceCodePoller = new OAuthDeviceCodePoller({ ...options, oauthClient: this, deviceCodePollUrl: null });
2572
- let idToken;
2573
- let accessToken;
2574
- let refreshToken;
2575
- if (this.idTokenResponseType == "sessionStorage") {
2576
- idToken = sessionStorage.getItem(this.idTokenName);
2577
- } else if (this.idTokenResponseType == "localStorage") {
2578
- idToken = localStorage.getItem(this.idTokenName);
2378
+ }), this.deviceCodePoller = new Pe({ ...t, oauthClient: this, deviceCodePollUrl: null });
2379
+ let o, s, n;
2380
+ if (this.idTokenResponseType == "sessionStorage" ? o = sessionStorage.getItem(this.idTokenName) : this.idTokenResponseType == "localStorage" && (o = localStorage.getItem(this.idTokenName)), this.accessTokenResponseType == "sessionStorage" ? s = sessionStorage.getItem(this.accessTokenName) : this.accessTokenResponseType == "localStorage" && (s = localStorage.getItem(this.accessTokenName)), this.refreshTokenResponseType == "sessionStorage" ? n = sessionStorage.getItem(this.refreshTokenName) : this.refreshTokenResponseType == "localStorage" && (n = localStorage.getItem(this.refreshTokenName)), this.receiveTokens({
2381
+ access_token: s,
2382
+ id_token: o,
2383
+ refresh_token: n
2384
+ }), s) {
2385
+ const i = this.getTokenPayload(s);
2386
+ i && (b(this, j, s), b(this, K, i));
2579
2387
  }
2580
- if (this.accessTokenResponseType == "sessionStorage") {
2581
- accessToken = sessionStorage.getItem(this.accessTokenName);
2582
- } else if (this.accessTokenResponseType == "localStorage") {
2583
- accessToken = localStorage.getItem(this.accessTokenName);
2584
- }
2585
- if (this.refreshTokenResponseType == "sessionStorage") {
2586
- refreshToken = sessionStorage.getItem(this.refreshTokenName);
2587
- } else if (this.refreshTokenResponseType == "localStorage") {
2588
- refreshToken = localStorage.getItem(this.refreshTokenName);
2589
- }
2590
- this.receiveTokens({
2591
- access_token: accessToken,
2592
- id_token: idToken,
2593
- refresh_token: refreshToken
2594
- });
2595
- if (accessToken) {
2596
- const payload = this.getTokenPayload(accessToken);
2597
- if (payload) {
2598
- __privateSet(this, _accessToken, accessToken);
2599
- __privateSet(this, _accessTokenPayload, payload);
2600
- }
2601
- }
2602
- if (refreshToken) {
2603
- const payload = this.getTokenPayload(refreshToken);
2604
- if (payload) {
2605
- __privateSet(this, _refreshToken, refreshToken);
2606
- __privateSet(this, _refreshTokenPayload, payload);
2607
- }
2388
+ if (n) {
2389
+ const i = this.getTokenPayload(n);
2390
+ i && (b(this, O, n), b(this, z, i));
2608
2391
  }
2609
- if (idToken) {
2610
- this.validateIdToken(idToken).then((payload) => {
2611
- __privateSet(this, _idTokenPayload, payload);
2612
- if (options.autoRefresh) {
2613
- this.startAutoRefresh(options.autoRefresh).then().catch((err) => {
2614
- d.logger.debug(h({ err, msg: "Couldn't start auto refresh" }));
2615
- });
2616
- }
2617
- }).catch((err) => {
2618
- d.logger.debug(h({ err, msg: "Couldn't validate ID token" }));
2392
+ o ? this.validateIdToken(o).then((i) => {
2393
+ b(this, R, i), t.autoRefresh && this.startAutoRefresh(t.autoRefresh).then().catch((a) => {
2394
+ c.logger.debug(d({ err: a, msg: "Couldn't start auto refresh" }));
2619
2395
  });
2620
- } else if (__privateGet(this, _accessToken) && options.autoRefresh && refreshToken) {
2621
- this.startAutoRefresh(options.autoRefresh).then().catch((err) => {
2622
- d.logger.debug(h({ err, msg: "Couldn't start auto refresh" }));
2396
+ }).catch((i) => {
2397
+ c.logger.debug(d({ err: i, msg: "Couldn't validate ID token" }));
2398
+ }) : w(this, j) && t.autoRefresh && n ? this.startAutoRefresh(t.autoRefresh).then().catch((i) => {
2399
+ c.logger.debug(d({ err: i, msg: "Couldn't start auto refresh" }));
2400
+ }) : n && !s && this.refreshTokenFlow(n).then((i) => {
2401
+ c.logger.debug(d({ msg: "Refreshed tokens" })), t.autoRefresh && this.startAutoRefresh(t.autoRefresh).then().catch((a) => {
2402
+ c.logger.debug(d({ err: a, msg: "Couldn't start auto refresh" }));
2623
2403
  });
2624
- } else if (refreshToken && !accessToken) {
2625
- this.refreshTokenFlow(refreshToken).then((_resp) => {
2626
- d.logger.debug(h({ msg: "Refreshed tokens" }));
2627
- if (options.autoRefresh) {
2628
- this.startAutoRefresh(options.autoRefresh).then().catch((err) => {
2629
- d.logger.debug(h({ err, msg: "Couldn't start auto refresh" }));
2630
- });
2631
- }
2632
- }).catch((err) => {
2633
- const ce2 = g.asCrossauthError(err);
2634
- d.logger.debug(h({ err: ce2 }));
2635
- d.logger.error(h({ msg: "failed refreshing tokens", cerr: ce2 }));
2636
- });
2637
- }
2404
+ }).catch((i) => {
2405
+ const a = g.asCrossauthError(i);
2406
+ c.logger.debug(d({ err: a })), c.logger.error(d({ msg: "failed refreshing tokens", cerr: a }));
2407
+ });
2638
2408
  }
2639
2409
  get idTokenPayload() {
2640
- return __privateGet(this, _idTokenPayload);
2410
+ return w(this, R);
2641
2411
  }
2642
2412
  /**
2643
2413
  * Processes the query parameters for a Redirect URI request if they
@@ -2667,43 +2437,31 @@ class OAuthClient extends Be {
2667
2437
  *
2668
2438
  */
2669
2439
  async handleRedirectUri() {
2670
- const url = new URL(window.location.href);
2671
- if (url.origin + url.pathname != this.redirect_uri) return void 0;
2672
- const params = new URLSearchParams(window.location.search);
2673
- let code = void 0;
2674
- let state = void 0;
2675
- let error = void 0;
2676
- let error_description = void 0;
2677
- for (const [key, value] of params) {
2678
- if (key == "code") code = value;
2679
- if (key == "state") state = value;
2680
- if (key == "error") error = value;
2681
- if (key == "error_description") error_description = value;
2682
- }
2683
- if (!error && !code) return void 0;
2684
- if (error) {
2685
- const cerr = g.fromOAuthError(error, error_description);
2686
- d.logger.debug(h({ err: cerr }));
2687
- d.logger.error(h({ cerr, msg: "Error from authorize endpoint: " + error }));
2688
- throw cerr;
2440
+ const t = new URL(window.location.href);
2441
+ if (t.origin + t.pathname != this.redirect_uri) return;
2442
+ const o = new URLSearchParams(window.location.search);
2443
+ let s, n, i, a;
2444
+ for (const [u, y] of o)
2445
+ u == "code" && (s = y), u == "state" && (n = y), u == "error" && (i = y), u == "error_description" && (a = y);
2446
+ if (!i && !s) return;
2447
+ if (i) {
2448
+ const u = g.fromOAuthError(i, a);
2449
+ throw c.logger.debug(d({ err: u })), c.logger.error(d({ cerr: u, msg: "Error from authorize endpoint: " + i })), u;
2689
2450
  }
2690
- const resp = await this.redirectEndpoint(code, state, error, error_description);
2691
- if (resp.error) {
2692
- const cerr = g.fromOAuthError(resp.error, error_description);
2693
- d.logger.debug(h({ err: cerr }));
2694
- d.logger.error(h({ cerr, msg: "Error from redirect endpoint: " + resp.error }));
2695
- throw cerr;
2451
+ const h = await this.redirectEndpoint(s, n, i, a);
2452
+ if (h.error) {
2453
+ const u = g.fromOAuthError(h.error, a);
2454
+ throw c.logger.debug(d({ err: u })), c.logger.error(d({ cerr: u, msg: "Error from redirect endpoint: " + h.error })), u;
2696
2455
  }
2697
- await this.receiveTokens(resp);
2698
- return resp;
2456
+ return await this.receiveTokens(h), h;
2699
2457
  }
2700
2458
  /**
2701
2459
  * Turns auto refresh of tokens on
2702
2460
  * @param tokensToFetch which tokens to fetch
2703
2461
  * @param errorFn what to call in case of error
2704
2462
  */
2705
- async startAutoRefresh(tokensToFetch = ["access", "id"], errorFn) {
2706
- return this.autoRefresher.startAutoRefresh(tokensToFetch, errorFn);
2463
+ async startAutoRefresh(t = ["access", "id"], o) {
2464
+ return this.autoRefresher.startAutoRefresh(t, o);
2707
2465
  }
2708
2466
  /**
2709
2467
  * Turns auto refresh of tokens off
@@ -2716,8 +2474,8 @@ class OAuthClient extends Be {
2716
2474
  * @param tokensToFetch which tokens to fetch
2717
2475
  * @param errorFn what to call in case of error
2718
2476
  */
2719
- async startDeviceCodePolling(deviceCode, pollResultFn, interval = 5) {
2720
- return this.deviceCodePoller.startPolling(deviceCode, pollResultFn, interval);
2477
+ async startDeviceCodePolling(t, o, s = 5) {
2478
+ return this.deviceCodePoller.startPolling(t, o, s);
2721
2479
  }
2722
2480
  /**
2723
2481
  * Turns off polling for a device code
@@ -2734,7 +2492,7 @@ class OAuthClient extends Be {
2734
2492
  * @returns the payload as an object
2735
2493
  */
2736
2494
  getIdToken() {
2737
- return __privateGet(this, _idTokenPayload);
2495
+ return w(this, R);
2738
2496
  }
2739
2497
  ///////
2740
2498
  // Implementation of abstract methods
@@ -2744,22 +2502,18 @@ class OAuthClient extends Be {
2744
2502
  * @param length the length of the random array before base64-url-encoding.
2745
2503
  * @returns the random value as a Base64-url-encoded srting
2746
2504
  */
2747
- randomValue(length) {
2748
- const array = new Uint8Array(length);
2749
- self.crypto.getRandomValues(array);
2750
- return btoa(array.reduce((acc, current) => acc + String.fromCharCode(current), "")).replace(/\//g, "_").replace(/\+/g, "-").replace(/=+$/, "");
2505
+ randomValue(t) {
2506
+ const o = new Uint8Array(t);
2507
+ return self.crypto.getRandomValues(o), btoa(o.reduce((s, n) => s + String.fromCharCode(n), "")).replace(/\//g, "_").replace(/\+/g, "-").replace(/=+$/, "");
2751
2508
  }
2752
2509
  /**
2753
2510
  * SHA256 and Base64-url-encodes the given test
2754
2511
  * @param plaintext the text to encode
2755
2512
  * @returns the SHA256 hash, Base64-url-encode
2756
2513
  */
2757
- async sha256(plaintext) {
2758
- const encoder = new TextEncoder();
2759
- const data = encoder.encode(plaintext);
2760
- const hash = await crypto.subtle.digest("SHA-256", data);
2761
- const hashArray = Array.from(new Uint8Array(hash));
2762
- return btoa(hashArray.reduce((acc, current) => acc + String.fromCharCode(current), "")).replace(/\//g, "_").replace(/\+/g, "-").replace(/=+$/, "");
2514
+ async sha256(t) {
2515
+ const s = new TextEncoder().encode(t), n = await crypto.subtle.digest("SHA-256", s), i = Array.from(new Uint8Array(n));
2516
+ return btoa(i.reduce((a, h) => a + String.fromCharCode(h), "")).replace(/\//g, "_").replace(/\+/g, "-").replace(/=+$/, "");
2763
2517
  }
2764
2518
  /**
2765
2519
  * Calls an API endpoint on the resource server
@@ -2768,31 +2522,25 @@ class OAuthClient extends Be {
2768
2522
  * @param body : the body to pass to the call
2769
2523
  * @returns the HTTP status code and the body or null
2770
2524
  */
2771
- async api(method, endpoint, body) {
2772
- let headers = { ...this.resServerHeaders };
2773
- if (endpoint.startsWith("/")) endpoint = endpoint.substring(1);
2774
- let params = {};
2775
- if (body) params.body = JSON.stringify(body);
2776
- let accessToken;
2777
- if (this.accessTokenResponseType == "sessionStorage") {
2778
- accessToken = sessionStorage.getItem(this.accessTokenName);
2779
- } else if (this.accessTokenResponseType == "localStorage") {
2780
- accessToken = localStorage.getItem(this.accessTokenName);
2781
- }
2782
- headers.authorization = "Bearer " + accessToken;
2783
- const resp = await fetch(
2784
- this.resServerBaseUrl + endpoint,
2525
+ async api(t, o, s) {
2526
+ let n = { ...this.resServerHeaders };
2527
+ o.startsWith("/") && (o = o.substring(1));
2528
+ let i = {};
2529
+ s && (i.body = JSON.stringify(s));
2530
+ let a;
2531
+ this.accessTokenResponseType == "sessionStorage" ? a = sessionStorage.getItem(this.accessTokenName) : this.accessTokenResponseType == "localStorage" && (a = localStorage.getItem(this.accessTokenName)), n.authorization = "Bearer " + a;
2532
+ const h = await fetch(
2533
+ this.resServerBaseUrl + o,
2785
2534
  {
2786
- headers,
2787
- method,
2535
+ headers: n,
2536
+ method: t,
2788
2537
  mode: this.resServerMode,
2789
2538
  credentials: this.resServerCredentials,
2790
- ...params
2539
+ ...i
2791
2540
  }
2792
2541
  );
2793
- let responseBody = null;
2794
- if (resp.body) responseBody = await resp.json();
2795
- return { status: resp.status, body: responseBody };
2542
+ let u = null;
2543
+ return h.body && (u = await h.json()), { status: h.status, body: u };
2796
2544
  }
2797
2545
  ///////////////////////////////////////////////////////////
2798
2546
  // OAuthTokenProvider interface
@@ -2804,23 +2552,12 @@ class OAuthClient extends Be {
2804
2552
  * @returns for each token, either the expiry, `null` if it does not
2805
2553
  * expire, or `undefined` if the token does not exist
2806
2554
  */
2807
- async getTokenExpiries(_tokensToFetch, _csrfToken) {
2808
- let idTokenExpiry = void 0;
2809
- let accessTokenExpiry = void 0;
2810
- let refreshTokenExpiry = void 0;
2811
- if (__privateGet(this, _idTokenPayload)) {
2812
- idTokenExpiry = __privateGet(this, _idTokenPayload).exp ? __privateGet(this, _idTokenPayload).exp : null;
2813
- }
2814
- if (__privateGet(this, _accessTokenPayload)) {
2815
- accessTokenExpiry = __privateGet(this, _accessTokenPayload).exp ? __privateGet(this, _accessTokenPayload).exp : null;
2816
- }
2817
- if (__privateGet(this, _refreshTokenPayload)) {
2818
- refreshTokenExpiry = __privateGet(this, _refreshTokenPayload).exp ? __privateGet(this, _refreshTokenPayload).exp : null;
2819
- }
2820
- return {
2821
- id: idTokenExpiry,
2822
- access: accessTokenExpiry,
2823
- refresh: refreshTokenExpiry
2555
+ async getTokenExpiries(t, o) {
2556
+ let s, n, i;
2557
+ return w(this, R) && (s = w(this, R).exp ? w(this, R).exp : null), w(this, K) && (n = w(this, K).exp ? w(this, K).exp : null), w(this, z) && (i = w(this, z).exp ? w(this, z).exp : null), {
2558
+ id: s,
2559
+ access: n,
2560
+ refresh: i
2824
2561
  };
2825
2562
  }
2826
2563
  /**
@@ -2833,71 +2570,36 @@ class OAuthClient extends Be {
2833
2570
  * @param token which token to add
2834
2571
  * @returns parsed JSON response
2835
2572
  */
2836
- async jsonFetchWithToken(url, params, token) {
2837
- if (token == "access") {
2838
- if (!__privateGet(this, _accessToken)) {
2839
- throw new g(y.InvalidToken, "Cannot make fetch with access token - no access token defined");
2840
- }
2841
- if (!params.headers) params.headers = {};
2842
- params.headers.authorization = "Bearer " + __privateGet(this, _accessToken);
2573
+ async jsonFetchWithToken(t, o, s) {
2574
+ if (s == "access") {
2575
+ if (!w(this, j))
2576
+ throw new g(m.InvalidToken, "Cannot make fetch with access token - no access token defined");
2577
+ o.headers || (o.headers = {}), o.headers.authorization = "Bearer " + w(this, j);
2843
2578
  } else {
2844
- if (!params.body) params.body = {};
2845
- if (!__privateGet(this, _refreshToken)) {
2846
- throw new g(y.InvalidToken, "Cannot make fetch with refresh token - no refresh token defined");
2847
- }
2848
- params.body.refresh_token = __privateGet(this, _refreshToken);
2849
- params.body.grant_type = "refresh_token";
2579
+ if (o.body || (o.body = {}), !w(this, O))
2580
+ throw new g(m.InvalidToken, "Cannot make fetch with refresh token - no refresh token defined");
2581
+ o.body.refresh_token = w(this, O), o.body.grant_type = "refresh_token";
2850
2582
  }
2851
- if (__privateGet(this, _client_id)) {
2852
- if (!params.body) params.body = {};
2853
- params.body.client_id = __privateGet(this, _client_id);
2854
- if (__privateGet(this, _client_secret)) {
2855
- params.body.client_secret = __privateGet(this, _client_secret);
2856
- }
2857
- }
2858
- if (typeof params.body != "string") params.body = JSON.stringify(params.body);
2859
- return await fetch(url, params);
2583
+ return w(this, B) && (o.body || (o.body = {}), o.body.client_id = w(this, B), w(this, L) && (o.body.client_secret = w(this, L))), typeof o.body != "string" && (o.body = JSON.stringify(o.body)), await fetch(t, o);
2860
2584
  }
2861
2585
  /**
2862
2586
  * Does nothing as CSRF tokens are not needed for this class
2863
2587
  * @returns `undefined`
2864
2588
  */
2865
2589
  async getCsrfToken() {
2866
- return void 0;
2867
- }
2868
- async receiveTokens(tokens) {
2869
- if (tokens.access_token) {
2870
- const payload = this.getTokenPayload(tokens.access_token);
2871
- if (payload) {
2872
- __privateSet(this, _accessToken, tokens.access_token);
2873
- __privateSet(this, _accessTokenPayload, payload);
2874
- }
2875
- if (this.accessTokenResponseType == "localStorage") {
2876
- localStorage.setItem(this.accessTokenName, tokens.access_token);
2877
- } else if (this.accessTokenResponseType == "sessionStorage") {
2878
- sessionStorage.setItem(this.accessTokenName, tokens.access_token);
2879
- }
2590
+ }
2591
+ async receiveTokens(t) {
2592
+ if (t.access_token) {
2593
+ const o = this.getTokenPayload(t.access_token);
2594
+ o && (b(this, j, t.access_token), b(this, K, o)), this.accessTokenResponseType == "localStorage" ? localStorage.setItem(this.accessTokenName, t.access_token) : this.accessTokenResponseType == "sessionStorage" && sessionStorage.setItem(this.accessTokenName, t.access_token);
2880
2595
  }
2881
- if (tokens.refresh_token) {
2882
- const payload = this.getTokenPayload(tokens.refresh_token);
2883
- if (payload) {
2884
- __privateSet(this, _refreshToken, tokens.refresh_token);
2885
- __privateSet(this, _refreshTokenPayload, payload);
2886
- }
2887
- if (this.refreshTokenResponseType == "localStorage") {
2888
- localStorage.setItem(this.refreshTokenName, tokens.refresh_token);
2889
- } else if (this.accessTokenResponseType == "sessionStorage") {
2890
- sessionStorage.setItem(this.refreshTokenName, tokens.refresh_token);
2891
- }
2596
+ if (t.refresh_token) {
2597
+ const o = this.getTokenPayload(t.refresh_token);
2598
+ o && (b(this, O, t.refresh_token), b(this, z, o)), this.refreshTokenResponseType == "localStorage" ? localStorage.setItem(this.refreshTokenName, t.refresh_token) : this.accessTokenResponseType == "sessionStorage" && sessionStorage.setItem(this.refreshTokenName, t.refresh_token);
2892
2599
  }
2893
- if (tokens.id_token) {
2894
- const payload = await this.validateIdToken(tokens.id_token);
2895
- __privateSet(this, _idTokenPayload, payload);
2896
- if (this.idTokenResponseType == "localStorage") {
2897
- localStorage.setItem(this.idTokenName, tokens.id_token);
2898
- } else if (this.idTokenResponseType == "sessionStorage") {
2899
- sessionStorage.setItem(this.idTokenName, tokens.id_token);
2900
- }
2600
+ if (t.id_token) {
2601
+ const o = await this.validateIdToken(t.id_token);
2602
+ b(this, R, o), this.idTokenResponseType == "localStorage" ? localStorage.setItem(this.idTokenName, t.id_token) : this.idTokenResponseType == "sessionStorage" && sessionStorage.setItem(this.idTokenName, t.id_token);
2901
2603
  }
2902
2604
  }
2903
2605
  /////////
@@ -2907,99 +2609,82 @@ class OAuthClient extends Be {
2907
2609
  * then saves the tokens, as per the requested method
2908
2610
  * @param scope
2909
2611
  */
2910
- async clientCredentialsFlow(scope) {
2911
- const resp = await super.clientCredentialsFlow(scope);
2912
- await this.receiveTokens(resp);
2913
- return resp;
2612
+ async clientCredentialsFlow(t) {
2613
+ const o = await super.clientCredentialsFlow(t);
2614
+ return await this.receiveTokens(o), o;
2914
2615
  }
2915
2616
  /**
2916
2617
  * See {@link @crossuath/common!OAuthClientBase}. Calls the base function
2917
2618
  * then saves the tokens, as per the requested method
2918
2619
  * @param scope
2919
2620
  */
2920
- async passwordFlow(username, password, scope) {
2921
- const resp = await super.passwordFlow(username, password, scope);
2922
- await this.receiveTokens(resp);
2923
- return resp;
2621
+ async passwordFlow(t, o, s) {
2622
+ const n = await super.passwordFlow(t, o, s);
2623
+ return await this.receiveTokens(n), n;
2924
2624
  }
2925
2625
  /**
2926
2626
  * See {@link @crossuath/common!OAuthClientBase}. Calls the base function
2927
2627
  * then saves the tokens, as per the requested method
2928
2628
  * @param scope
2929
2629
  */
2930
- async deviceCodeFlow(scope) {
2931
- let url = this.authServerBaseUrl;
2932
- if (!url.endsWith("/")) url += "/";
2933
- url += this.deviceAuthorizationUrl;
2934
- const resp = await super.startDeviceCodeFlow(url, scope);
2935
- return resp;
2630
+ async deviceCodeFlow(t) {
2631
+ let o = this.authServerBaseUrl;
2632
+ return o.endsWith("/") || (o += "/"), o += this.deviceAuthorizationUrl, await super.startDeviceCodeFlow(o, t);
2936
2633
  }
2937
2634
  /**
2938
2635
  * See {@link @crossuath/common!OAuthClientBase}. Calls the base function
2939
2636
  * then saves the tokens, as per the requested method
2940
2637
  * @param scope
2941
2638
  */
2942
- async mfaOtpComplete(mfaToken, otp) {
2943
- const resp = await super.mfaOtpComplete(mfaToken, otp);
2944
- await this.receiveTokens(resp);
2945
- return resp;
2639
+ async mfaOtpComplete(t, o) {
2640
+ const s = await super.mfaOtpComplete(t, o);
2641
+ return await this.receiveTokens(s), s;
2946
2642
  }
2947
2643
  /**
2948
2644
  * See {@link @crossuath/common!OAuthClientBase}. Calls the base function
2949
2645
  * then saves the tokens, as per the requested method
2950
2646
  * @param scope
2951
2647
  */
2952
- async mfaOobComplete(mfaToken, oobCode, bindingCode) {
2953
- const resp = await super.mfaOobComplete(mfaToken, oobCode, bindingCode);
2954
- await this.receiveTokens(resp);
2955
- return resp;
2648
+ async mfaOobComplete(t, o, s) {
2649
+ const n = await super.mfaOobComplete(t, o, s);
2650
+ return await this.receiveTokens(n), n;
2956
2651
  }
2957
2652
  /**
2958
2653
  * See {@link @crossuath/common!OAuthClientBase}. Calls the base function
2959
2654
  * then saves the tokens, as per the requested method
2960
2655
  * @param scope
2961
2656
  */
2962
- async refreshTokenFlow(refreshToken) {
2963
- if (!refreshToken) {
2964
- if (__privateGet(this, _refreshToken)) {
2965
- refreshToken = __privateGet(this, _refreshToken);
2966
- } else {
2967
- throw new g(y.InvalidToken, "Cannot refresh tokens: no refresh token present");
2968
- }
2969
- }
2970
- const resp = await super.refreshTokenFlow(refreshToken);
2971
- await this.receiveTokens(resp);
2972
- return resp;
2657
+ async refreshTokenFlow(t) {
2658
+ if (!t)
2659
+ if (w(this, O))
2660
+ t = w(this, O);
2661
+ else
2662
+ throw new g(m.InvalidToken, "Cannot refresh tokens: no refresh token present");
2663
+ const o = await super.refreshTokenFlow(t);
2664
+ return await this.receiveTokens(o), o;
2973
2665
  }
2974
2666
  /**
2975
2667
  * Executes the authorization code flow
2976
2668
  * @param scope the scope to request
2977
2669
  * @param pkce whether or not to use PKCE.
2978
2670
  */
2979
- async authorizationCodeFlow(scope, pkce = false) {
2980
- const resp = await super.startAuthorizationCodeFlow(scope, pkce);
2981
- if (resp.error || !resp.url) {
2982
- const cerr = g.fromOAuthError(
2983
- resp.error ?? "Couldn't create URL for authorization code flow",
2984
- resp.error_description
2671
+ async authorizationCodeFlow(t, o = !1) {
2672
+ const s = await super.startAuthorizationCodeFlow(t, o);
2673
+ if (s.error || !s.url) {
2674
+ const n = g.fromOAuthError(
2675
+ s.error ?? "Couldn't create URL for authorization code flow",
2676
+ s.error_description
2985
2677
  );
2986
- d.logger.debug(h({ err: cerr }));
2987
- throw cerr;
2678
+ throw c.logger.debug(d({ err: n })), n;
2988
2679
  }
2989
- location.href = resp.url;
2680
+ location.href = s.url;
2990
2681
  }
2991
2682
  }
2992
- _accessToken = new WeakMap();
2993
- _refreshToken = new WeakMap();
2994
- _idTokenPayload = new WeakMap();
2995
- _accessTokenPayload = new WeakMap();
2996
- _refreshTokenPayload = new WeakMap();
2997
- _client_id = new WeakMap();
2998
- _client_secret = new WeakMap();
2683
+ j = new WeakMap(), O = new WeakMap(), R = new WeakMap(), K = new WeakMap(), z = new WeakMap(), B = new WeakMap(), L = new WeakMap();
2999
2684
  export {
3000
2685
  g as CrossauthError,
3001
- d as CrossauthLogger,
3002
- OAuthBffClient,
3003
- OAuthClient,
3004
- h as j
2686
+ c as CrossauthLogger,
2687
+ ur as OAuthBffClient,
2688
+ fr as OAuthClient,
2689
+ d as j
3005
2690
  };