@crossauth/common 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Indicates the type of error reported by {@link @crossauth/common!CrossauthError}
3
+ */
4
+ export declare enum ErrorCode {
5
+ /** Thrown when a given username does not exist, eg during login */
6
+ UserNotExist = 0,
7
+ /** Thrown when a password does not match, eg during login or signup */
8
+ PasswordInvalid = 1,
9
+ /** Thrown when a a password reset is requested and the email does not exist */
10
+ EmailNotExist = 2,
11
+ /** For endpoints provided by servers in this package, this is returned instead of
12
+ * UserNotExist or PasswordNotMatch, for security reasons */
13
+ UsernameOrPasswordInvalid = 3,
14
+ /** This is returned if an OAuth2 client id is invalid */
15
+ InvalidClientId = 4,
16
+ /** This is returned if attempting to make a client which already exists (client_id or name/userid) */
17
+ ClientExists = 5,
18
+ /** This is returned if an OAuth2 client secret is invalid */
19
+ InvalidClientSecret = 6,
20
+ /** Server endpoints in this package will return this instead of InvalidClientId or InvalidClientSecret for security purposes */
21
+ InvalidClientIdOrSecret = 7,
22
+ /** This is returned a request is made with a redirect Uri that is not registered */
23
+ InvalidRedirectUri = 8,
24
+ /** This is returned a request is made with a an oauth flow name that is not recognized */
25
+ InvalidOAuthFlow = 9,
26
+ /** Thrown on login attempt with a user account marked inactive */
27
+ UserNotActive = 10,
28
+ /** Thrown on login attempt with a user account marked not having had the email address validated */
29
+ EmailNotVerified = 11,
30
+ /** Thrown on login attempt with a user account marked not having completed 2FA setup */
31
+ TwoFactorIncomplete = 12,
32
+ /** Thrown when a resource expecting user authorization was access and authorization not provided or wrong */
33
+ Unauthorized = 13,
34
+ /** Thrown for the OAuth unauthorized_client error (when the client is unauthorized as opposed to the user) */
35
+ UnauthorizedClient = 14,
36
+ /** Thrown for the OAuth invalid_scope error */
37
+ InvalidScope = 15,
38
+ /** Thrown for the OAuth insufficient_scope error */
39
+ InsufficientScope = 16,
40
+ /** Returned if user is valid but doesn't have permission to access resource */
41
+ InsufficientPriviledges = 17,
42
+ /** Returned with an HTTP 403 response */
43
+ Forbidden = 18,
44
+ /** Thrown when a session or API key was provided that is not in the key table.
45
+ * For CSRF and sesison keys, an InvalidCsrf or InvalidSession will be thrown instead
46
+ */
47
+ InvalidKey = 19,
48
+ /** Thrown if the CSRF token is invalid
49
+ */
50
+ InvalidCsrf = 20,
51
+ /** Thrown if the session cookie is invalid
52
+ */
53
+ InvalidSession = 21,
54
+ /** Thrown when a session or API key has expired */
55
+ Expired = 22,
56
+ /** Thrown when there is a connection error, eg to a database */
57
+ Connection = 23,
58
+ /** Thrown when a hash, eg password, is not in the given format */
59
+ InvalidHash = 24,
60
+ /** Thrown when an algorithm is requested but not supported, eg hashing algorithm */
61
+ UnsupportedAlgorithm = 25,
62
+ /** Thrown if you try to create a key which already exists in key storage */
63
+ KeyExists = 26,
64
+ /** Thrown if the user needs to reset his or her password */
65
+ PasswordChangeNeeded = 27,
66
+ /** Thrown if the user needs to reset his or her password */
67
+ PasswordResetNeeded = 28,
68
+ /** Thrown if the user needs to reset factor2 before logging in */
69
+ Factor2ResetNeeded = 29,
70
+ /** Thrown when something is missing or inconsistent in configuration */
71
+ Configuration = 30,
72
+ /** Thrown if an email address in invalid */
73
+ InvalidEmail = 31,
74
+ /** Thrown if a phone number in invalid */
75
+ InvalidPhoneNumber = 32,
76
+ /** Thrown if an email address in invalid */
77
+ InvalidUsername = 33,
78
+ /** Thrown when two passwords do not match each other (eg signup) */
79
+ PasswordMatch = 34,
80
+ /** Thrown when a token (eg TOTP or OTP) is invalid */
81
+ InvalidToken = 35,
82
+ /** Thrown during OAuth password flow if an MFA step is needed */
83
+ MfaRequired = 36,
84
+ /** Thrown when a password does not match rules (length, uppercase/lowercase/digits) */
85
+ PasswordFormat = 37,
86
+ /** Thrown when a the data field of key storage is not valid json */
87
+ DataFormat = 38,
88
+ /** Thrown if a fetch failed */
89
+ FetchError = 39,
90
+ /** Thrown when attempting to create a user that already exists */
91
+ UserExists = 40,
92
+ /** Thrown by user-supplied validation functions if a user details form was incorrectly filled out */
93
+ FormEntry = 41,
94
+ /** Thrown when an invalid request is made, eg configure 2FA when 2FA is switched off for user */
95
+ BadRequest = 42,
96
+ /** Thrown in the OAuth device code flow */
97
+ AuthorizationPending = 43,
98
+ /** Thrown in the OAuth device code flow */
99
+ SlowDown = 44,
100
+ /** Thrown in the OAuth device code flow */
101
+ ExpiredToken = 45,
102
+ /** Thrown in database handlers where an insert causes a constraint violation */
103
+ ConstraintViolation = 46,
104
+ /** Thrown if a method is unimplemented, typically when a feature
105
+ * is not yet supported in this language. */
106
+ NotImplemented = 47,
107
+ /** Thrown for an condition not convered above. */
108
+ UnknownError = 48
109
+ }
110
+ /**
111
+ * Thrown by Crossauth functions whenever it encounters an error.
112
+ */
113
+ export declare class CrossauthError extends Error {
114
+ /** `typeof` won't work on this class. To determine if the
115
+ * object is a `CrossauthError`, check for presence of this member.
116
+ */
117
+ isCrossauthError: boolean;
118
+ /** The best HTTP status to report */
119
+ readonly httpStatus: number;
120
+ /** All Crossauth errors have an error code */
121
+ readonly code: ErrorCode;
122
+ /** All Crossauth errors have an error code */
123
+ readonly codeName: string;
124
+ /** A vector of error messages. If there was only one, it will still be in this array.
125
+ * The inherited property `message` is also always available. If there were multiple messages,
126
+ * it will be a concatenation of them with `". "` in between.
127
+ */
128
+ readonly messages: string[];
129
+ /**
130
+ * Creates a new error to throw,
131
+ *
132
+ * @param code describes the type of error
133
+ * @param message if provided, this error will display. Otherwise a default one for the error code will be used.
134
+ */
135
+ constructor(code: ErrorCode, message?: string | string[] | undefined);
136
+ /**
137
+ * OAuth defines certain error types. To convert the error in an OAuth
138
+ * response into a CrossauthError object, call this function.
139
+ *
140
+ * @param error as returned by an OAuth call (converted to an {@link @crossauth/common!ErrorCode}).
141
+ * @param error_description as returned by an OAuth call (put in the `message`)
142
+ * @returns a `CrossauthError` instance.
143
+ */
144
+ static fromOAuthError(error: string, error_description?: string): CrossauthError;
145
+ get oauthErrorCode(): "invalid_request" | "unauthorized_client" | "access_denied" | "invalid_scope" | "server_error" | "temporarily_unavailable" | "invalid_token" | "expired_token" | "mfa_required" | "authorization_pending" | "slow_down";
146
+ /**
147
+ * If the passed object is a `CrossauthError` instance, simply returns
148
+ * it.
149
+ * If not and it is an object with `errorCode` in it, creates a
150
+ * CrossauthError from that and `errorMessage`, if present.
151
+ * Otherwise creates a `CrossauthError` object with {@link @crossauth/common!ErrorCode}
152
+ * of `Unknown` from it, setting the `message` if possible.
153
+ *
154
+ * @param e the error to convert.
155
+ * @returns a `CrossauthError` instance.
156
+ */
157
+ static asCrossauthError(e: any, defaultMessage?: string): CrossauthError;
158
+ }
159
+ /**
160
+ * Returns the friendly name for an HTTP response code.
161
+ *
162
+ * If it is not a recognized one, returns the friendly name for 500.
163
+ * @param status the HTTP response code, which, while being numeric,
164
+ * can be in a string or number.
165
+ * @returns the string version of the response code.
166
+ */
167
+ export declare function httpStatus(status: string | number): string;
168
+ //# sourceMappingURL=error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AACA;;GAEG;AACH,oBAAY,SAAS;IAEjB,mEAAmE;IACtE,YAAY,IAAI;IAEb,uEAAuE;IACvE,eAAe,IAAA;IAEf,+EAA+E;IAC/E,aAAa,IAAA;IAEb;iEAC6D;IAC7D,yBAAyB,IAAA;IAEzB,yDAAyD;IACzD,eAAe,IAAA;IAEf,sGAAsG;IACtG,YAAY,IAAA;IAEZ,6DAA6D;IAC7D,mBAAmB,IAAA;IAEnB,gIAAgI;IAChI,uBAAuB,IAAA;IAEvB,oFAAoF;IACpF,kBAAkB,IAAA;IAElB,0FAA0F;IAC1F,gBAAgB,IAAA;IAEhB,kEAAkE;IAClE,aAAa,KAAA;IAEb,oGAAoG;IACpG,gBAAgB,KAAA;IAEhB,wFAAwF;IACxF,mBAAmB,KAAA;IAEnB,6GAA6G;IAC7G,YAAY,KAAA;IAEZ,8GAA8G;IAC9G,kBAAkB,KAAA;IAElB,gDAAgD;IAChD,YAAY,KAAA;IAEZ,qDAAqD;IACrD,iBAAiB,KAAA;IAEjB,+EAA+E;IAC/E,uBAAuB,KAAA;IAEvB,yCAAyC;IACzC,SAAS,KAAA;IAET;;OAEG;IACH,UAAU,KAAA;IAEV;OACG;IACH,WAAW,KAAA;IAEX;OACG;IACH,cAAc,KAAA;IAEd,mDAAmD;IACnD,OAAO,KAAA;IAEP,gEAAgE;IACnE,UAAU,KAAA;IAEP,kEAAkE;IAClE,WAAW,KAAA;IAEX,oFAAoF;IACpF,oBAAoB,KAAA;IAEpB,4EAA4E;IAC5E,SAAS,KAAA;IAET,4DAA4D;IAC5D,oBAAoB,KAAA;IAEpB,4DAA4D;IAC5D,mBAAmB,KAAA;IAEnB,kEAAkE;IAClE,kBAAkB,KAAA;IAElB,wEAAwE;IACxE,aAAa,KAAA;IAEb,4CAA4C;IAC5C,YAAY,KAAA;IAEZ,0CAA0C;IAC1C,kBAAkB,KAAA;IAElB,4CAA4C;IAC5C,eAAe,KAAA;IAEf,oEAAoE;IACpE,aAAa,KAAA;IAEb,sDAAsD;IACtD,YAAY,KAAA;IAEZ,iEAAiE;IACjE,WAAW,KAAA;IAEX,uFAAuF;IACvF,cAAc,KAAA;IAEd,oEAAoE;IACpE,UAAU,KAAA;IAEV,+BAA+B;IAC/B,UAAU,KAAA;IAEV,kEAAkE;IAClE,UAAU,KAAA;IAEV,qGAAqG;IACrG,SAAS,KAAA;IAET,iGAAiG;IACjG,UAAU,KAAA;IAEV,2CAA2C;IAC3C,oBAAoB,KAAA;IAEpB,2CAA2C;IAC3C,QAAQ,KAAA;IAER,2CAA2C;IAC3C,YAAY,KAAA;IAEZ,gFAAgF;IAChF,mBAAmB,KAAA;IAEnB;gDAC4C;IAC5C,cAAc,KAAA;IAEd,kDAAkD;IAClD,YAAY,KAAA;CACf;AAED;;GAEG;AACH,qBAAa,cAAe,SAAQ,KAAK;IAErC;;OAEG;IACH,gBAAgB,UAAQ;IAExB,qCAAqC;IACrC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAE5B,8CAA8C;IAC9C,QAAQ,CAAC,IAAI,EAAG,SAAS,CAAC;IAE1B,8CAA8C;IAC9C,QAAQ,CAAC,QAAQ,EAAG,MAAM,CAAC;IAE3B;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAG,MAAM,EAAE,CAAC;IAE7B;;;;;OAKG;gBACS,IAAI,EAAG,SAAS,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,EAAE,GAAG,SAAqB;IA8JjF;;;;;;;OAOG;IACH,MAAM,CAAC,cAAc,CAAC,KAAK,EAAG,MAAM,EAAE,iBAAiB,CAAC,EAAE,MAAM,GAAI,cAAc;IAsBlF,IAAI,cAAc,4NAejB;IAED;;;;;;;;;;OAUG;IACH,MAAM,CAAC,gBAAgB,CAAC,CAAC,EAAE,GAAG,EAAE,cAAc,CAAC,EAAG,MAAM,GAAI,cAAc;CAoB7E;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAC,MAAM,GAAI,MAAM,CAIzD"}
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var fe=Object.defineProperty;var X=e=>{throw TypeError(e)};var pe=(e,t,r)=>t in e?fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var a=(e,t,r)=>pe(e,typeof t!="symbol"?t+"":t,r),Q=(e,t,r)=>t.has(e)||X("Cannot "+r);var u=(e,t,r)=>(Q(e,t,"read from private field"),r?r.call(e):t.get(e)),O=(e,t,r)=>t.has(e)?X("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),_=(e,t,r,n)=>(Q(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class P{}a(P,"active","active"),a(P,"disabled","disabled"),a(P,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),a(P,"awaitingEmailVerification","awaitingemailverification"),a(P,"passwordChangeNeeded","passwordchangeneeded"),a(P,"passwordResetNeeded","passwordresetneeded"),a(P,"factor2ResetNeeded","factor2resetneeded"),a(P,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class C{}a(C,"session","s:"),a(C,"passwordResetToken","p:"),a(C,"emailVerificationToken","e:"),a(C,"apiKey","api:"),a(C,"authorizationCode","authz:"),a(C,"accessToken","access:"),a(C,"refreshToken","refresh:"),a(C,"mfaToken","omfa:"),a(C,"deviceCode","dc:"),a(C,"userCode","uc:");var y=(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||{});class g extends Error{constructor(r,n=void 0){let i,s=500;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(". "));super(i);a(this,"isCrossauthError",!0);a(this,"httpStatus");a(this,"code");a(this,"codeName");a(this,"messages");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)}static fromOAuthError(r,n){let i;switch(r){case"invalid_request":i=42;break;case"unauthorized_client":i=14;break;case"access_denied":i=13;break;case"unsupported_response_type":i=42;break;case"invalid_scope":i=15;break;case"server_error":i=48;break;case"temporarily_unavailable":i=23;break;case"invalid_token":i=35;break;case"expired_token":i=45;break;case"insufficient_scope":i=35;break;case"mfa_required":i=36;break;case"authorization_pending":i=43;break;case"slow_down":i=44;break;default:i=48}return new g(i,n)}get oauthErrorCode(){switch(this.code){case 42:return"invalid_request";case 14:return"unauthorized_client";case 13:return"access_denied";case 15:return"invalid_scope";case 23:return"temporarily_unavailable";case 35:return"invalid_token";case 36:return"mfa_required";case 43:return"authorization_pending";case 44:return"slow_down";case 45:return"expired_token";case 22:return"expired_token";default:return"server_error"}}static asCrossauthError(r,n){if(r instanceof Error)return"isCrossauthError"in r?r:new g(48,r.message);if("errorCode"in r){let s=48;try{s=Number(r.errorCode)??48}catch{}let o=n??y[s];return"errorMessage"in r?o=r.errorMessage:"message"in r&&(o=r.message),new g(s,o)}let i=n??y[48];return"message"in r&&(i=r.message),new g(48,i)}}function ge(e){return typeof e=="number"&&(e=""+e),e in B?B[e]:B[500]}const B={200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Unused",307:"Temporary Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Required",413:"Request Entry Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",429:"Too Many Requests",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},m=class m{constructor(t){a(this,"level");if(t)this.level=t;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const r=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();m.levelName.includes(r)?this.level=m.levelName.indexOf(r):this.level=m.Error}else this.level=m.Error}static get logger(){return globalThis.crossauthLogger}setLevel(t){this.level=t}log(t,r){t<=this.level&&(typeof r=="string"?console.log("Crossauth "+m.levelName[t]+" "+new Date().toISOString(),r):console.log(JSON.stringify({level:m.levelName[t],time:new Date().toISOString(),...r})))}error(t){this.log(m.Error,t)}warn(t){this.log(m.Warn,t)}info(t){this.log(m.Info,t)}debug(t){this.log(m.Debug,t)}static setLogger(t,r){globalThis.crossauthLogger=t,globalThis.crossauthLoggerAcceptsJson=r}};a(m,"None",0),a(m,"Error",1),a(m,"Warn",2),a(m,"Info",3),a(m,"Debug",4),a(m,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let c=m;function h(e){let t;typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(t=e.err.stack);try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&e.err&&"message"in e.err&&!("msg"in e)&&(e.msg=e.err.message)}catch{}try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(e.err={...e.err,stack:t})}catch{}try{typeof e=="object"&&"err"in e&&!("msg"in e)&&(e.msg=e.msg="An unknown error occurred")}catch{}try{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)}catch{}return typeof e=="string"||globalThis.crossauthLoggerAcceptsJson?e:JSON.stringify(e)}globalThis.crossauthLogger=new c(c.None);globalThis.crossauthLoggerAcceptsJson=!0;const Y={issuer:"",authorization_endpoint:"",token_endpoint:"",jwks_uri:"",response_types_supported:[],subject_types_supported:[],response_modes_supported:["query","fragment"],grant_types_supported:["authorization_code","implicit"],id_token_signing_alg_values_supported:[],claim_types_supported:["normal"],claims_parameter_supported:!1,request_parameter_supported:!1,request_uri_parameter_supported:!0,require_request_uri_registration:!1},M=crypto,re=e=>e instanceof CryptoKey,H=new TextEncoder,z=new TextDecoder;function ye(...e){const t=e.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r}const me=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},K=e=>{let t=e;t instanceof Uint8Array&&(t=z.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return me(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class $ extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)==null||r.call(Error,this,this.constructor)}}class b extends ${constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class v extends ${constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class E extends ${constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}class we extends ${constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function A(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function J(e,t){return e.name===t}function L(e){return parseInt(e.name.slice(4),10)}function ve(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Se(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function _e(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!J(e.algorithm,"HMAC"))throw A("HMAC");const n=parseInt(t.slice(2),10);if(L(e.algorithm.hash)!==n)throw A(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!J(e.algorithm,"RSASSA-PKCS1-v1_5"))throw A("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(L(e.algorithm.hash)!==n)throw A(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!J(e.algorithm,"RSA-PSS"))throw A("RSA-PSS");const n=parseInt(t.slice(2),10);if(L(e.algorithm.hash)!==n)throw A(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw A("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!J(e.algorithm,"ECDSA"))throw A("ECDSA");const n=ve(t);if(e.algorithm.namedCurve!==n)throw A(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Se(e,r)}function ie(e,t,...r){var n;if(r.length>2){const i=r.pop();e+=`one of type ${r.join(", ")}, or ${i}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;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}const Z=(e,...t)=>ie("Key must be ",e,...t);function ne(e,t,...r){return ie(`Key for the ${e} algorithm must be `,t,...r)}const se=e=>re(e)?!0:(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",F=["CryptoKey"],Ce=(...e)=>{const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(const s of i){if(r.has(s))return!1;r.add(s)}}return!0};function be(e){return typeof e=="object"&&e!==null}function x(e){if(!be(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}const Ae=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function Pe(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new b('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new b('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new b('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new b('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}const oe=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=Pe(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,M.subtle.importKey("jwk",i,...n)},ae=e=>K(e);let V,j;const ce=e=>(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",de=async(e,t,r,n)=>{let i=e.get(t);if(i!=null&&i[n])return i[n];const s=await oe({...r,alg:n});return i?i[n]=s:e.set(t,{[n]:s}),s},ke=(e,t)=>{if(ce(e)){let r=e.export({format:"jwk"});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=new WeakMap),de(j,e,r,t))}return e},Te=(e,t)=>{if(ce(e)){let r=e.export({format:"jwk"});return r.k?ae(r.k):(V||(V=new WeakMap),de(V,e,r,t))}return e},Ie={normalizePublicKey:ke,normalizePrivateKey:Te},T=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],r);if(n===-1)return!1;const i=e.subarray(n,n+t.length);return i.length!==t.length?!1:i.every((s,o)=>s===t[o])||T(e,t,n+1)},ee=e=>{switch(!0){case T(e,[42,134,72,206,61,3,1,7]):return"P-256";case T(e,[43,129,4,0,34]):return"P-384";case T(e,[43,129,4,0,35]):return"P-521";case T(e,[43,101,110]):return"X25519";case T(e,[43,101,111]):return"X448";case T(e,[43,101,112]):return"Ed25519";case T(e,[43,101,113]):return"Ed448";default:throw new b("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},le=async(e,t,r,n,i)=>{let s,o;const l=new Uint8Array(atob(r.replace(e,"")).split("").map(p=>p.charCodeAt(0))),f=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},o=f?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},o=f?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},o=f?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},o=f?["verify"]:["sign"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},o=f?["verify"]:["sign"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},o=f?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const p=ee(l);s=p.startsWith("P-")?{name:"ECDH",namedCurve:p}:{name:p},o=f?[]:["deriveBits"];break}case"EdDSA":s={name:ee(l)},o=f?["verify"]:["sign"];break;default:throw new b('Invalid or unsupported "alg" (Algorithm) value')}return M.subtle.importKey(t,l,s,!1,o)},Re=(e,t,r)=>le(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t),Ee=(e,t,r)=>le(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t);async function Oe(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Ee(e,t)}async function Ke(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Re(e,t)}async function te(e,t){if(!x(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return K(e.k);case"RSA":if(e.oth!==void 0)throw new b('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return oe({...e,alg:t});default:throw new b('Unsupported "kty" (Key Type) Parameter value')}}const q=e=>e==null?void 0:e[Symbol.toStringTag],Ue=(e,t)=>{if(!(t instanceof Uint8Array)){if(!se(t))throw new TypeError(ne(e,t,...F,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${q(t)} instances for symmetric algorithms must be of type "secret"`)}},Ne=(e,t,r)=>{if(!se(t))throw new TypeError(ne(e,t,...F));if(t.type==="secret")throw new TypeError(`${q(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${q(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${q(t)} instances for asymmetric algorithm encryption must be of type "public"`)},xe=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Ue(e,t):Ne(e,t,r)};function ze(e,t,r,n,i){if(i.crit!==void 0&&(n==null?void 0:n.crit)===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(o=>typeof o!="string"||o.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;s=t;for(const o of n.crit){if(!s.has(o))throw new b(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new e(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new e(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}function De(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new b(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function We(e,t,r){if(t=await Ie.normalizePublicKey(t,e),re(t))return _e(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Z(t,...F));return M.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(Z(t,...F,"Uint8Array"))}const He=async(e,t,r,n)=>{const i=await We(e,t,"verify");Ae(e,i);const s=De(e,i.algorithm);try{return await M.subtle.verify(s,i,r,n)}catch{return!1}};async function Je(e,t,r){if(!x(e))throw new v("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new v('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new v("JWS Protected Header incorrect type");if(e.payload===void 0)throw new v("JWS Payload missing");if(typeof e.signature!="string")throw new v("JWS Signature missing or incorrect type");if(e.header!==void 0&&!x(e.header))throw new v("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const ue=K(e.protected);n=JSON.parse(z.decode(ue))}catch{throw new v("JWS Protected Header is invalid")}if(!Ce(n,e.header))throw new v("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header},s=ze(v,new Map([["b64",!0]]),r==null?void 0:r.crit,n,i);let o=!0;if(s.has("b64")&&(o=n.b64,typeof o!="boolean"))throw new v('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:l}=i;if(typeof l!="string"||!l)throw new v('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(o){if(typeof e.payload!="string")throw new v("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new v("JWS Payload must be a string or an Uint8Array instance");let f=!1;typeof t=="function"&&(t=await t(n,e),f=!0),xe(l,t,"verify");const p=ye(H.encode(e.protected??""),H.encode("."),typeof e.payload=="string"?H.encode(e.payload):e.payload);let k;try{k=K(e.signature)}catch{throw new v("Failed to base64url decode the signature")}if(!await He(l,t,k,p))throw new we;let D;if(o)try{D=K(e.payload)}catch{throw new v("Failed to base64url decode the payload")}else typeof e.payload=="string"?D=H.encode(e.payload):D=e.payload;const W={payload:D};return e.protected!==void 0&&(W.protectedHeader=n),e.header!==void 0&&(W.unprotectedHeader=e.header),f?{...W,key:t}:W}async function qe(e,t,r){if(e instanceof Uint8Array&&(e=z.decode(e)),typeof e!="string")throw new v("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:s,length:o}=e.split(".");if(o!==3)throw new v("Invalid Compact JWS");const l=await Je({payload:i,protected:n,signature:s},t,r),f={payload:l.payload,protectedHeader:l.protectedHeader};return typeof t=="function"?{...f,key:l.key}:f}const he=K;function Fe(e){let t;if(typeof e=="string"){const r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;const r=JSON.parse(z.decode(he(t)));if(!x(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function Me(e){if(typeof e!="string")throw new E("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(r===5)throw new E("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new E("Invalid JWT");if(!t)throw new E("JWTs must contain a payload");let n;try{n=he(t)}catch{throw new E("Failed to base64url decode the payload")}let i;try{i=JSON.parse(z.decode(n))}catch{throw new E("Failed to parse the decoded payload as JSON")}if(!x(i))throw new E("Invalid JWT Claims Set");return i}const d=class d{static flowNames(t){let r={};return t.forEach(n=>{n in d.flowName&&(r[n]=d.flowName[n])}),r}static isValidFlow(t){return d.allFlows().includes(t)}static areAllValidFlows(t){let r=!0;return t.forEach(n=>{d.isValidFlow(n)||(r=!1)}),r}static allFlows(){return[d.AuthorizationCode,d.AuthorizationCodeWithPKCE,d.ClientCredentials,d.RefreshToken,d.DeviceCode,d.Password,d.PasswordMfa,d.OidcAuthorizationCode]}static grantType(t){switch(t){case d.AuthorizationCode:case d.AuthorizationCodeWithPKCE:case d.OidcAuthorizationCode:return["authorization_code"];case d.ClientCredentials:return["client_credentials"];case d.RefreshToken:return["refresh_token"];case d.Password:return["password"];case d.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case d.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};a(d,"All","all"),a(d,"AuthorizationCode","authorizationCode"),a(d,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),a(d,"ClientCredentials","clientCredentials"),a(d,"RefreshToken","refreshToken"),a(d,"DeviceCode","deviceCode"),a(d,"Password","password"),a(d,"PasswordMfa","passwordMfa"),a(d,"OidcAuthorizationCode","oidcAuthorizationCode"),a(d,"flowName",{[d.AuthorizationCode]:"Authorization Code",[d.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[d.ClientCredentials]:"Client Credentials",[d.RefreshToken]:"Refresh Token",[d.DeviceCode]:"Device Code",[d.Password]:"Password",[d.PasswordMfa]:"Password MFA",[d.OidcAuthorizationCode]:"OIDC Authorization Code"});let G=d;var w,S,U,I,R;class $e{constructor({authServerBaseUrl:t,client_id:r,client_secret:n,redirect_uri:i,codeChallengeMethod:s,stateLength:o,verifierLength:l,tokenConsumer:f,authServerCredentials:p,authServerMode:k,authServerHeaders:N}){a(this,"authServerBaseUrl","");O(this,w);O(this,S);O(this,U);a(this,"codeChallengeMethod","S256");O(this,I);a(this,"verifierLength",32);a(this,"redirect_uri");O(this,R,"");a(this,"stateLength",32);a(this,"authzCode","");a(this,"oidcConfig");a(this,"tokenConsumer");a(this,"authServerHeaders",{});a(this,"authServerMode");a(this,"authServerCredentials");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),k&&(this.authServerMode=k),N&&(this.authServerHeaders=N)}set client_id(t){_(this,w,t)}set client_secret(t){_(this,S,t)}set codeVerifier(t){_(this,I,t)}set codeChallenge(t){_(this,U,t)}set state(t){_(this,R,t)}async loadConfig(t){if(t){c.logger.debug(h({msg:"Reading OIDC config locally"})),this.oidcConfig=t;return}let r;try{const n=new URL(this.authServerBaseUrl+"/.well-known/openid-configuration");c.logger.debug(h({msg:`Fetching OIDC config from ${n}`}));let i={headers:this.authServerHeaders};this.authServerMode&&(i.mode=this.authServerMode),this.authServerCredentials&&(i.credentials=this.authServerCredentials),r=await fetch(n,i)}catch(n){c.logger.error(h({err:n}))}if(!r||!r.ok)throw new g(y.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...Y};try{const n=await r.json();for(const[i,s]of Object.entries(n))this.oidcConfig[i]=s}catch{throw new g(y.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(t,r=!1){var s,o,l;if(c.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")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((l=this.oidcConfig)!=null&&l.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(_(this,R,this.randomValue(this.stateLength)),!u(this,w))return{error:"invalid_request",error_description:"Cannot make authorization code flow without client id"};if(!this.redirect_uri)return{error:"invalid_request",error_description:"Cannot make authorization code flow without Redirect Uri"};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);return t&&(i+="&scope="+encodeURIComponent(t)),r&&(_(this,I,this.randomValue(this.verifierLength)),_(this,U,this.codeChallengeMethod=="plain"?u(this,I):await this.sha256(u(this,I))),i+="&code_challenge="+u(this,U)),{url:i}}async redirectEndpoint(t,r,n,i){var p,k;if(this.oidcConfig||await this.loadConfig(),n||!t)return n||(n="server_error"),i||(i="Unknown error"),{error:n,error_description:i};if(u(this,R)&&r!=u(this,R))return{error:"access_denied",error_description:"State is not valid"};if(this.authzCode=t,!((p=this.oidcConfig)!=null&&p.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((k=this.oidcConfig)!=null&&k.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let o,l;o="authorization_code",l=u(this,S);let f={grant_type:o,client_id:u(this,w),code:this.authzCode};l&&(f.client_secret=l),f.code_verifier=u(this,I);try{return this.post(s,f,this.authServerHeaders)}catch(N){return c.logger.error(h({err:N})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(t){var i,s;if(c.logger.debug(h({msg:"Starting client credentials flow"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.grant_types_supported.includes("client_credentials")))return{error:"invalid_request",error_description:"Server does not support client credentials grant"};if(!((s=this.oidcConfig)!=null&&s.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};if(!u(this,w))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const r=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:u(this,w),client_secret:u(this,S)};t&&(n.scope=t);try{return await this.post(r,n,this.authServerHeaders)}catch(o){return c.logger.error(h({err:o})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(t,r,n){var o,l;if(c.logger.debug(h({msg:"Starting password flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("password")))return{error:"invalid_request",error_description:"Server does not support password grant"};if(!((l=this.oidcConfig)!=null&&l.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const i=this.oidcConfig.token_endpoint;let s={grant_type:"password",client_id:u(this,w),client_secret:u(this,S),username:t,password:r};n&&(s.scope=n);try{return await this.post(i,s,this.authServerHeaders)}catch(f){return c.logger.error(h({err:f})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(t){var s,o,l;if(c.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")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((l=this.oidcConfig)!=null&&l.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const r=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",n=await this.get(r,{authorization:"Bearer "+t,...this.authServerHeaders});if(!Array.isArray(n))return{error:"server_error",error_description:"Expected array of authenticators in mfa/authenticators response"};let i=[];for(let f=0;f<n.length;++f){const p=n[f];if(!p.id||!p.authenticator_type||!p.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};i.push({id:p.id,authenticator_type:p.authenticator_type,active:p.active,name:p.name,oob_channel:p.oob_channel})}return{authenticators:i}}async mfaOtpRequest(t,r){var s,o;if(c.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")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((o=this.oidcConfig)!=null&&o.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:u(this,w),client_secret:u(this,S),challenge_type:"otp",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(t,r,n){var o,l;if(c.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")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((l=this.oidcConfig)!=null&&l.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const i=this.oidcConfig.token_endpoint,s=await this.post(i,{grant_type:"http://auth0.com/oauth/grant-type/mfa-otp",client_id:u(this,w),client_secret:u(this,S),challenge_type:"otp",mfa_token:t,otp:r,scope:n},this.authServerHeaders);return{id_token:s.id_token,access_token:s.access_token,refresh_token:s.refresh_token,expires_in:Number(s.expires_in),scope:s.scope,token_type:s.token_type,error:s.error,error_description:s.error_description}}async mfaOobRequest(t,r){var s,o;if(c.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")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((o=this.oidcConfig)!=null&&o.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:u(this,w),client_secret:u(this,S),challenge_type:"oob",mfa_token:t,authenticator_id:r},this.authServerHeaders);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"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(t,r,n,i){var l,f;if(c.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")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((f=this.oidcConfig)!=null&&f.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const s=this.oidcConfig.token_endpoint,o=await this.post(s,{grant_type:"http://auth0.com/oauth/grant-type/mfa-oob",client_id:u(this,w),client_secret:u(this,S),challenge_type:"otp",mfa_token:t,oob_code:r,binding_code:n,scope:i},this.authServerHeaders);return o.error?{error:o.error,error_description:o.error_description}:{id_token:o.id_token,access_token:o.access_token,refresh_token:o.refresh_token,expires_in:"expires_in"in o?Number(o.expires_in):void 0,scope:o.scope,token_type:o.token_type}}async refreshTokenFlow(t){var s,o;if(c.logger.debug(h({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.token_endpoint;let n;n=u(this,S);let i={grant_type:"refresh_token",refresh_token:t,client_id:u(this,w)};n&&(i.client_secret=n);try{return await this.post(r,i,this.authServerHeaders)}catch(l){return c.logger.error(h({err:l})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(t,r){var i;if(c.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")))return{error:"invalid_request",error_description:"Server does not support device code grant"};let n={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:u(this,w),client_secret:u(this,S)};r&&(n.scope=r);try{return await this.post(t,n,this.authServerHeaders)}catch(s){return c.logger.error(h({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(t){var n,i,s;if(c.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")))return{error:"invalid_request",error_description:"Server does not support device code grant"};if(!((i=this.oidcConfig)!=null&&i.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};let r={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:u(this,w),client_secret:u(this,S),device_code:t};try{const o=await this.post((s=this.oidcConfig)==null?void 0:s.token_endpoint,r,this.authServerHeaders);return o.error,o}catch(o){return c.logger.error(h({err:o})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async post(t,r,n={}){c.logger.debug(h({msg:"Fetch POST",url:t,params:Object.keys(r)}));let i={};return this.authServerCredentials&&(i.credentials=this.authServerCredentials),this.authServerMode&&(i.mode=this.authServerMode),await(await fetch(t,{method:"POST",...i,headers:{Accept:"application/json","Content-Type":"application/json",...n},body:JSON.stringify(r)})).json()}async get(t,r={}){c.logger.debug(h({msg:"Fetch GET",url:t}));let n={};return this.authServerCredentials&&(n.credentials=this.authServerCredentials),this.authServerMode&&(n.mode=this.authServerMode),await(await fetch(t,{method:"GET",...n,headers:{Accept:"application/json","Content-Type":"application/json",...r}})).json()}async validateIdToken(t){try{return await this.tokenConsumer.tokenAuthorized(t,"id")}catch{return}}async idTokenAuthorized(t){try{return await this.tokenConsumer.tokenAuthorized(t,"id")}catch(r){c.logger.warn(h({err:r}));return}}getTokenPayload(t){return Me(t)}}w=new WeakMap,S=new WeakMap,U=new WeakMap,I=new WeakMap,R=new WeakMap;class Be{constructor(t,r={}){a(this,"audience");a(this,"jwtKeyType");a(this,"jwtSecretKey");a(this,"jwtPublicKey");a(this,"clockTolerance",10);a(this,"authServerBaseUrl","");a(this,"oidcConfig");a(this,"keys",{});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)throw new g(y.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new g(y.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await Ke(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new g(y.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const t=await Oe(this.jwtPublicKey,this.jwtKeyType);this.keys._default=t}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new g(y.Connection,"Load OIDC config before Jwks");await this.loadJwks()}}catch(t){throw c.logger.debug(h({err:t})),new g(y.Connection,"Couldn't load keys")}}async loadConfig(t){if(t){this.oidcConfig=t;return}if(!this.authServerBaseUrl)throw new g(y.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let r;try{r=await fetch(new URL("/.well-known/openid-configuration",this.authServerBaseUrl))}catch(n){c.logger.error(h({err:n}))}if(!r||!r.ok)throw new g(y.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...Y};try{const n=await r.json();for(const[i,s]of Object.entries(n))this.oidcConfig[i]=s}catch{throw new g(y.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(t){if(t){this.keys={};for(let r=0;r<t.keys.length;++r){const n=t.keys[r];this.keys[n.kid??"_default"]=await te(t.keys[r])}}else{if(!this.oidcConfig)throw new g(y.Connection,"Load OIDC config before Jwks");let r;try{r=await fetch(new URL(this.oidcConfig.jwks_uri))}catch(n){c.logger.error(h({err:n}))}if(!r||!r.ok)throw new g(y.Connection,"Couldn't get OIDC configuration");this.keys={};try{const n=await r.json();if(!("keys"in n)||!Array.isArray(n.keys))throw new g(y.Connection,"Couldn't fetch keys");for(let i=0;i<n.keys.length;++i)try{let s="_default";"kid"in n.keys[i]&&typeof n.keys[i]=="string"&&(s=String(n.keys[i]));const o=await te(n.keys[i]);this.keys[s]=o}catch(s){throw c.logger.error(h({err:s})),new g(y.Connection,"Couldn't load keys")}}catch(n){throw c.logger.error(h({err:n})),new g(y.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(t,r){(!this.keys||Object.keys(this.keys).length==0)&&await this.loadKeys();const n=await this.validateToken(t);if(n){if(n.type!=r&&c.logger.error(h({msg:r+" expected but got "+n.type})),n.iss!=this.authServerBaseUrl){c.logger.error(h({msg:`Invalid issuer ${n.iss} in access token`,hashedAccessToken:await this.hash(n.jti)}));return}if(n.aud&&(Array.isArray(n.aud)&&!n.aud.includes(this.audience)||!Array.isArray(n.aud)&&n.aud!=this.audience)){c.logger.error(h({msg:`Invalid audience ${n.aud} in access token`,hashedAccessToken:await this.hash(n.jti)}));return}return n}}async validateToken(t){(!this.keys||Object.keys(this.keys).length==0)&&c.logger.warn("No keys loaded so cannot validate tokens");let r;try{r=Fe(t).kid}catch{c.logger.warn(h({msg:"Invalid access token format"}));return}let n;"_default"in this.keys&&(n=this.keys._default);for(let i in this.keys)if(r==i){n=this.keys[i];break}if(!n){c.logger.warn(h({msg:"No matching keys found for access token"}));return}try{const{payload:i}=await qe(t,n),s=JSON.parse(new TextDecoder().decode(i));if(s.exp*1e3<Date.now()+this.clockTolerance){c.logger.warn(h({msg:"Access token has expired"}));return}return s}catch{c.logger.warn(h({msg:"Access token did not validate"}));return}}}exports.CrossauthError=g;exports.CrossauthLogger=c;exports.DEFAULT_OIDCCONFIG=Y;exports.ErrorCode=y;exports.KeyPrefix=C;exports.OAuthClientBase=$e;exports.OAuthFlows=G;exports.OAuthTokenConsumerBase=Be;exports.UserState=P;exports.httpStatus=ge;exports.j=h;
@@ -0,0 +1,10 @@
1
+ export { UserState, KeyPrefix } from './interfaces';
2
+ export type { Key, ApiKey, User, UserSecrets, UserInputFields, UserSecretsInputFields, OAuthClient, } from './interfaces';
3
+ export { CrossauthError, ErrorCode, httpStatus } from './error';
4
+ export { CrossauthLogger, j, type CrossauthLoggerInterface } from './logger';
5
+ export type { TokenEndpointAuthMethod, ResponseMode, GrantType, SubjectType, ClaimType, OpenIdConfiguration, Jwks } from './oauth/wellknown';
6
+ export { DEFAULT_OIDCCONFIG } from './oauth/wellknown';
7
+ export { OAuthClientBase, OAuthFlows, type OAuthTokenResponse, type MfaAuthenticatorResponse, type OAuthDeviceAuthorizationResponse, type OAuthDeviceResponse } from './oauth/client';
8
+ export { OAuthTokenConsumerBase } from './oauth/tokenconsumer';
9
+ export type { OAuthTokenConsumerBaseOptions, EncryptionKey } from './oauth/tokenconsumer';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACH,SAAS,EACT,SAAS,EACZ,MAAM,cAAc,CAAC;AACtB,YAAY,EACR,GAAG,EACH,MAAM,EACN,IAAI,EACJ,WAAW,EACX,eAAe,EACf,sBAAsB,EACtB,WAAW,GACd,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,CAAC,EAAE,KAAK,wBAAwB,EAAE,MAAM,UAAU,CAAC;AAC7E,YAAY,EAAE,uBAAuB,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,mBAAmB,EAAE,IAAI,EAAG,MAAM,mBAAmB,CAAC;AAC9I,OAAO,EAAG,kBAAkB,EAAG,MAAM,mBAAmB,CAAC;AACzD,OAAO,EACH,eAAe,EACf,UAAU,EACV,KAAK,kBAAkB,EACvB,KAAK,wBAAwB,EAC7B,KAAK,gCAAgC,EACrC,KAAK,mBAAmB,EAAC,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,YAAY,EAAE,6BAA6B,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC"}