@melara/auth 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that is necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Melara
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,126 @@
1
- # Temporary Holding Version
1
+ # @melara/auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official Sign in with Melara library for web and server applications. Built purely on Web-Standard `fetch` and Web Crypto (`crypto.subtle`) with zero runtime npm dependencies, so it runs identically in Node.js 22+, Edge runtimes, Workers, Bun, and Deno.
4
+
5
+ ```bash
6
+ npm install @melara/auth
7
+ ```
8
+
9
+ ## Security model
10
+
11
+ - **Identity only**: Requests OpenID Connect identity scopes (`openid`, `profile`, `email`) and forbids API credit audiences (`melara-api`), so signing in never grants access to spend a visitor's Melara credits.
12
+ - **PKCE `S256` and browser-bound state**: Every login flow generates a cryptographic `code_verifier`, `state`, and OIDC `nonce` sealed inside an `HttpOnly; SameSite=Lax` cookie to prevent login CSRF and session fixation.
13
+ - **Asymmetric JWKS verification**: Verifies `RS256` and `ES256` signatures, `iss`, `aud`, `exp`, `iat`, and `nonce` directly with `crypto.subtle`, with key-rotation refresh protection.
14
+ - **Stateless `AES-GCM` sessions**: Derives encryption keys with `HKDF-SHA256` from a `>= 32` character `sessionSecret` and binds the cookie name as Additional Authenticated Data (`AAD`), with `Origin` and double-submit CSRF verification on `POST /logout`.
15
+
16
+ ## Environment variables
17
+
18
+ Create an OAuth client in your Melara Account Settings and configure:
19
+
20
+ - `MELARA_ISSUER`: Melara OpenID Connect issuer URL (`https://...`, or `http://localhost:...` during local development).
21
+ - `MELARA_CLIENT_ID`: Your OAuth client ID.
22
+ - `MELARA_CLIENT_SECRET`: Your OAuth client secret (optional only for public PKCE clients).
23
+ - `MELARA_SESSION_SECRET`: Random secret of at least 32 characters used to seal session cookies.
24
+
25
+ ## Hono quick start
26
+
27
+ ```ts
28
+ import { Hono } from 'hono';
29
+ import { melaraAuth, requireRole, requireUser, type MelaraHonoEnv } from '@melara/auth/hono';
30
+
31
+ const app = new Hono<MelaraHonoEnv>();
32
+
33
+ app.use(
34
+ '/api/auth/*',
35
+ melaraAuth({
36
+ adminEmails: ['admin@example.com'],
37
+ }),
38
+ );
39
+
40
+ app.get('/api/me', requireUser(), (c) => {
41
+ return c.json({ user: c.get('melaraUser') });
42
+ });
43
+
44
+ app.get('/api/admin/audit', requireRole(['admin']), (c) => {
45
+ return c.json({ ok: true, actor: c.get('melaraUser').sub });
46
+ });
47
+ ```
48
+
49
+ Mounted routes under `/api/auth`:
50
+
51
+ - `GET /api/auth/login`: Starts PKCE sign-in and redirects to Melara.
52
+ - `GET /api/auth/callback`: Validates state cookie, exchanges code, verifies ID token, and sets the session cookie.
53
+ - `GET /api/auth/session`: Returns `{ authenticated, user, csrfToken, expiresAt }`.
54
+ - `POST /api/auth/logout`: Verifies CSRF and clears the session cookie.
55
+
56
+ ## Next.js App Router
57
+
58
+ In `app/api/auth/[...melara]/route.ts`:
59
+
60
+ ```ts
61
+ import { createMelaraNextHandlers } from '@melara/auth/next';
62
+
63
+ export const { GET, POST } = createMelaraNextHandlers({
64
+ basePath: '/api/auth',
65
+ });
66
+ ```
67
+
68
+ Read the signed-in user in a Server Component or Route Handler without extra runtime dependencies:
69
+
70
+ ```ts
71
+ import { getMelaraServerSession } from '@melara/auth/next';
72
+
73
+ export async function loadCurrentUser(request: Request) {
74
+ const session = await getMelaraServerSession(request);
75
+ return session?.user ?? null;
76
+ }
77
+ ```
78
+
79
+ ## React components
80
+
81
+ ```tsx
82
+ import {
83
+ MelaraAuthProvider,
84
+ SignInWithMelaraButton,
85
+ useMelaraAuth,
86
+ } from '@melara/auth/react';
87
+
88
+ function AccountBadge() {
89
+ const { user, status, signOut } = useMelaraAuth();
90
+ if (status === 'loading') {
91
+ return null;
92
+ }
93
+ if (!user) {
94
+ return <SignInWithMelaraButton theme='auto' />;
95
+ }
96
+ return (
97
+ <button type='button' onClick={() => void signOut()}>
98
+ {user.email ?? user.sub}
99
+ </button>
100
+ );
101
+ }
102
+
103
+ export function App() {
104
+ return (
105
+ <MelaraAuthProvider basePath='/api/auth'>
106
+ <AccountBadge />
107
+ </MelaraAuthProvider>
108
+ );
109
+ }
110
+ ```
111
+
112
+ Pass custom `labels` to `<MelaraAuthProvider>` or `<SignInWithMelaraButton>` to localize every UI message.
113
+
114
+ ## Core API (`@melara/auth`)
115
+
116
+ For custom frameworks, import the building blocks directly from `@melara/auth`:
117
+
118
+ - `discoverOidcConfiguration`
119
+ - `generateCodeVerifier`, `computeS256Challenge`, `buildAuthorizationUrl`, `exchangeAuthorizationCode`
120
+ - `createJwksVerifier`, `verifyIdToken`
121
+ - `sealSession`, `unsealSession`
122
+ - `createMelaraAuthHandler`
123
+
124
+ ## License
125
+
126
+ Apache-2.0
@@ -0,0 +1,169 @@
1
+ var errors = {
2
+ missingIssuer: "Melara sign-in requires a valid issuer URL (issuer option or MELARA_ISSUER).",
3
+ insecureIssuer: "Melara sign-in URLs must use HTTPS (plain HTTP is allowed only on localhost).",
4
+ missingClientId: "Melara sign-in requires a non-empty clientId (clientId option or MELARA_CLIENT_ID).",
5
+ shortSessionSecret: "Melara sessionSecret must be at least 32 characters.",
6
+ forbiddenAudience: "Sign in with Melara forbids API audiences such as melara-api; request identity scopes only.",
7
+ forbiddenScope: "Unsupported OAuth scope requested for Sign in with Melara.",
8
+ redirectRefused: "Refused an unexpected HTTP redirect from the Melara sign-in server.",
9
+ discoveryFailed: "Could not load OpenID Connect discovery metadata from the Melara sign-in server.",
10
+ issuerMismatch: "OpenID Connect discovery issuer does not match the configured issuer.",
11
+ tokenExchangeFailed: "Authorization code exchange with the Melara sign-in server failed.",
12
+ jwksFetchFailed: "Could not load JSON Web Key Set from the Melara sign-in server.",
13
+ invalidJwt: "ID token is malformed or failed cryptographic verification.",
14
+ unsupportedAlg: "ID token uses a disallowed signing algorithm.",
15
+ unknownKeyId: "ID token key identifier was not found in the active key set.",
16
+ invalidClaims: "ID token claims failed issuer, audience, expiration, or nonce validation.",
17
+ csrfMismatch: "Invalid, expired, or replayed OAuth state cookie.",
18
+ logoutCsrfFailed: "Cross-site logout request was rejected.",
19
+ invalidSession: "Session cookie is missing, expired, or failed authentication.",
20
+ unauthorized: "Authentication is required.",
21
+ forbidden: "You do not have permission to access this resource.",
22
+ missingAuthContext: "useMelaraAuth must be used inside MelaraAuthProvider.",
23
+ invalidBase64Url: "Invalid base64url encoding.",
24
+ nonCanonicalBase64Url: "Non-canonical base64url encoding.",
25
+ invalidRandomLength: "Random token byteLength must be an integer between 16 and 128.",
26
+ invalidPkceLength: "PKCE code verifier byteLength must be an integer between 32 and 96.",
27
+ invalidPkceVerifier: "PKCE code verifier must be 43 to 128 RFC 7636 unreserved characters.",
28
+ invalidAuthRequest: "Authorization URL requires non-empty state, nonce, and codeChallenge values.",
29
+ reservedAuthParam: "extraParams cannot override reserved OAuth parameters.",
30
+ invalidCookieName: "Cookie name must be a non-empty string.",
31
+ invalidSessionUser: "Session user requires a non-empty sub identifier.",
32
+ signOutFailed: "Sign out request failed."
33
+ };
34
+ var en = {
35
+ errors: errors
36
+ };
37
+
38
+ interface MelaraAuthUiLabels {
39
+ readonly signInButton: string;
40
+ readonly signingInButton: string;
41
+ readonly signOutButton: string;
42
+ readonly markLabel: string;
43
+ }
44
+ type MelaraAuthErrorKey = keyof typeof en.errors;
45
+ interface MelaraAuthLabels {
46
+ readonly ui: MelaraAuthUiLabels;
47
+ readonly errors: Readonly<Record<MelaraAuthErrorKey, string>>;
48
+ }
49
+
50
+ type MelaraUserRole = 'admin' | 'member' | 'blocked' | (string & {});
51
+ interface MelaraUser {
52
+ readonly id: string;
53
+ readonly sub: string;
54
+ readonly email: string | null;
55
+ readonly emailVerified: boolean;
56
+ readonly name: string | null;
57
+ readonly picture: string | null;
58
+ readonly role: MelaraUserRole;
59
+ }
60
+ interface MelaraVerifiedIdToken {
61
+ readonly sub: string;
62
+ readonly iss: string;
63
+ readonly aud: string | readonly string[];
64
+ readonly exp: number;
65
+ readonly iat: number;
66
+ readonly nbf?: number;
67
+ readonly nonce?: string;
68
+ readonly azp?: string;
69
+ readonly email?: string;
70
+ readonly email_verified?: boolean;
71
+ readonly name?: string;
72
+ readonly given_name?: string;
73
+ readonly family_name?: string;
74
+ readonly picture?: string;
75
+ readonly claims: Readonly<Record<string, unknown>>;
76
+ }
77
+ interface MelaraTokenSet {
78
+ readonly accessToken: string;
79
+ readonly idToken: string;
80
+ readonly refreshToken?: string;
81
+ readonly expiresIn?: number;
82
+ readonly tokenType: string;
83
+ readonly scope?: string;
84
+ }
85
+ interface MelaraSessionData {
86
+ readonly v: 1;
87
+ readonly user: MelaraUser;
88
+ readonly iat: number;
89
+ readonly exp: number;
90
+ readonly csrf: string;
91
+ }
92
+ interface MelaraRoleConfig {
93
+ readonly adminSubList?: readonly string[];
94
+ readonly adminEmails?: readonly string[];
95
+ readonly defaultRole?: MelaraUserRole;
96
+ }
97
+ interface MelaraAuthenticatedEvent {
98
+ readonly request: Request;
99
+ readonly user: MelaraUser;
100
+ readonly idToken: MelaraVerifiedIdToken;
101
+ readonly tokens: MelaraTokenSet;
102
+ readonly returnTo: string;
103
+ }
104
+ interface MelaraAuthOptions {
105
+ readonly issuer?: string;
106
+ readonly internalUrl?: string;
107
+ readonly clientId?: string;
108
+ readonly clientSecret?: string;
109
+ readonly tokenEndpointAuthMethod?: 'client_secret_post' | 'client_secret_basic' | 'none';
110
+ readonly sessionSecret?: string;
111
+ readonly previousSessionSecrets?: readonly string[];
112
+ readonly redirectUri?: string;
113
+ readonly basePath?: string;
114
+ readonly scopes?: readonly string[];
115
+ readonly sessionCookieName?: string;
116
+ readonly stateCookieName?: string;
117
+ readonly sessionTtlSeconds?: number;
118
+ readonly stateTtlSeconds?: number;
119
+ readonly discoveryTtlMs?: number;
120
+ readonly jwksCooldownMs?: number;
121
+ readonly clockSkewSeconds?: number;
122
+ readonly adminSubList?: readonly string[];
123
+ readonly adminEmails?: readonly string[];
124
+ readonly roles?: MelaraRoleConfig;
125
+ readonly env?: Readonly<Record<string, unknown>>;
126
+ readonly fetch?: typeof fetch;
127
+ readonly now?: () => number;
128
+ readonly labels?: Partial<{
129
+ readonly ui: Partial<MelaraAuthUiLabels>;
130
+ readonly errors: Partial<MelaraAuthLabels['errors']>;
131
+ }>;
132
+ readonly onConsumeState?: (state: string, expiresAtSeconds: number) => Promise<boolean> | boolean;
133
+ readonly resolveUser?: (baseUser: MelaraUser, context: {
134
+ readonly idToken: MelaraVerifiedIdToken;
135
+ readonly tokens: MelaraTokenSet;
136
+ readonly request: Request;
137
+ }) => Promise<MelaraUser> | MelaraUser;
138
+ readonly onAuthenticated?: (event: MelaraAuthenticatedEvent) => Promise<void> | void;
139
+ }
140
+
141
+ interface MelaraHonoVariables {
142
+ melaraUser: MelaraUser;
143
+ melaraSession: MelaraSessionData;
144
+ user: MelaraUser;
145
+ }
146
+ interface MelaraHonoEnv {
147
+ Bindings: Record<string, unknown>;
148
+ Variables: MelaraHonoVariables;
149
+ }
150
+ interface MelaraHonoRequestContext {
151
+ readonly req: {
152
+ readonly raw: Request;
153
+ };
154
+ readonly env?: unknown;
155
+ }
156
+ interface MelaraHonoContext extends MelaraHonoRequestContext {
157
+ get(key: 'melaraSession'): MelaraSessionData | undefined;
158
+ set(key: 'melaraSession', value: MelaraSessionData): void;
159
+ set(key: 'melaraUser', value: MelaraUser): void;
160
+ set(key: 'user', value: MelaraUser): void;
161
+ }
162
+ type MelaraHonoAuthMiddleware = <C extends MelaraHonoRequestContext>(c: C, next: () => Promise<void>) => Promise<Response | undefined>;
163
+ type MelaraHonoGuardMiddleware = <C extends MelaraHonoContext>(c: C, next: () => Promise<void>) => Promise<Response | undefined>;
164
+ type MelaraHonoOptions = MelaraAuthOptions | ((env: Readonly<Record<string, unknown>>) => MelaraAuthOptions);
165
+ declare function melaraAuth(options?: MelaraHonoOptions): MelaraHonoAuthMiddleware;
166
+ declare function requireUser(options?: MelaraHonoOptions): MelaraHonoGuardMiddleware;
167
+ declare function requireRole(roles: MelaraUserRole | readonly MelaraUserRole[], options?: MelaraHonoOptions): MelaraHonoGuardMiddleware;
168
+
169
+ export { type MelaraHonoAuthMiddleware, type MelaraHonoContext, type MelaraHonoEnv, type MelaraHonoGuardMiddleware, type MelaraHonoOptions, type MelaraHonoRequestContext, type MelaraHonoVariables, melaraAuth, requireRole, requireUser };
@@ -0,0 +1,2 @@
1
+ var en_default={ui:{signInButton:"Sign in with Melara",signingInButton:"Redirecting to Melara...",signOutButton:"Sign out",markLabel:"Melara"},errors:{missingIssuer:"Melara sign-in requires a valid issuer URL (issuer option or MELARA_ISSUER).",insecureIssuer:"Melara sign-in URLs must use HTTPS (plain HTTP is allowed only on localhost).",missingClientId:"Melara sign-in requires a non-empty clientId (clientId option or MELARA_CLIENT_ID).",shortSessionSecret:"Melara sessionSecret must be at least 32 characters.",forbiddenAudience:"Sign in with Melara forbids API audiences such as melara-api; request identity scopes only.",forbiddenScope:"Unsupported OAuth scope requested for Sign in with Melara.",redirectRefused:"Refused an unexpected HTTP redirect from the Melara sign-in server.",discoveryFailed:"Could not load OpenID Connect discovery metadata from the Melara sign-in server.",issuerMismatch:"OpenID Connect discovery issuer does not match the configured issuer.",tokenExchangeFailed:"Authorization code exchange with the Melara sign-in server failed.",jwksFetchFailed:"Could not load JSON Web Key Set from the Melara sign-in server.",invalidJwt:"ID token is malformed or failed cryptographic verification.",unsupportedAlg:"ID token uses a disallowed signing algorithm.",unknownKeyId:"ID token key identifier was not found in the active key set.",invalidClaims:"ID token claims failed issuer, audience, expiration, or nonce validation.",csrfMismatch:"Invalid, expired, or replayed OAuth state cookie.",logoutCsrfFailed:"Cross-site logout request was rejected.",invalidSession:"Session cookie is missing, expired, or failed authentication.",unauthorized:"Authentication is required.",forbidden:"You do not have permission to access this resource.",missingAuthContext:"useMelaraAuth must be used inside MelaraAuthProvider.",invalidBase64Url:"Invalid base64url encoding.",nonCanonicalBase64Url:"Non-canonical base64url encoding.",invalidRandomLength:"Random token byteLength must be an integer between 16 and 128.",invalidPkceLength:"PKCE code verifier byteLength must be an integer between 32 and 96.",invalidPkceVerifier:"PKCE code verifier must be 43 to 128 RFC 7636 unreserved characters.",invalidAuthRequest:"Authorization URL requires non-empty state, nonce, and codeChallenge values.",reservedAuthParam:"extraParams cannot override reserved OAuth parameters.",invalidCookieName:"Cookie name must be a non-empty string.",invalidSessionUser:"Session user requires a non-empty sub identifier.",signOutFailed:"Sign out request failed."}};var DEFAULT_MELARA_AUTH_LABELS=en_default;function errorMessage(key,overrides){return overrides?.[key]??DEFAULT_MELARA_AUTH_LABELS.errors[key]}var utf8Encoder=new TextEncoder;var utf8Decoder=new TextDecoder("utf-8",{fatal:true});var BASE64URL_PATTERN=/^[A-Za-z0-9_-]*$/;function encodeUtf8(value){return new Uint8Array(utf8Encoder.encode(value))}function decodeUtf8(bytes){return utf8Decoder.decode(bytes)}function toBase64Url(bytes){let binary="";const chunkSize=32768;for(let offset=0;offset<bytes.length;offset+=chunkSize){const slice=bytes.subarray(offset,offset+chunkSize);binary+=String.fromCharCode(...slice)}return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fromBase64Url(input){if(!BASE64URL_PATTERN.test(input)||input.length%4===1){throw new Error(errorMessage("invalidBase64Url"))}const remainder=input.length%4;const padded=remainder===0?input:`${input}${"=".repeat(4-remainder)}`;const binary=atob(padded.replace(/-/g,"+").replace(/_/g,"/"));const output=new Uint8Array(binary.length);for(let i=0;i<binary.length;i+=1){output[i]=binary.charCodeAt(i)}if(toBase64Url(output)!==input){throw new Error(errorMessage("nonCanonicalBase64Url"))}return output}function decodeBase64UrlJson(segment){const bytes=fromBase64Url(segment);return JSON.parse(decodeUtf8(bytes))}function randomBytes(byteLength){if(!Number.isInteger(byteLength)||byteLength<16||byteLength>128){throw new RangeError(errorMessage("invalidRandomLength"))}const bytes=new Uint8Array(byteLength);crypto.getRandomValues(bytes);return bytes}function randomBase64Url(byteLength=32){return toBase64Url(randomBytes(byteLength))}async function sha256Bytes(data){const digest=await crypto.subtle.digest("SHA-256",new Uint8Array(data));return new Uint8Array(digest)}function constantTimeEqual(left,right){const leftBytes=encodeUtf8(left);const rightBytes=encodeUtf8(right);const maxLength=Math.max(leftBytes.length,rightBytes.length,1);let diff=leftBytes.length^rightBytes.length;const leftMod=Math.max(leftBytes.length,1);const rightMod=Math.max(rightBytes.length,1);for(let i=0;i<maxLength;i+=1){diff|=(leftBytes[i%leftMod]??0)^(rightBytes[i%rightMod]??0)}return diff===0}var MelaraAuthError=class extends Error{code;status;constructor(code,message,status=400,options){super(message,options);this.name="MelaraAuthError";this.code=code;this.status=status}};var MelaraAuthConfigError=class extends MelaraAuthError{constructor(code,message,options){super(code,message,500,options);this.name="MelaraAuthConfigError"}};var MelaraAuthVerificationError=class extends MelaraAuthError{constructor(code,message,options){super(code,message,401,options);this.name="MelaraAuthVerificationError"}};var MelaraAuthCsrfError=class extends MelaraAuthError{constructor(code,message,status=403,options){super(code,message,status,options);this.name="MelaraAuthCsrfError"}};var DEFAULT_IDENTITY_SCOPES=["openid","profile","email"];var ALLOWED_IDENTITY_SCOPES=new Set(DEFAULT_IDENTITY_SCOPES);var PKCE_VERIFIER_PATTERN=/^[A-Za-z0-9._~-]+$/;var AUDIENCE_AUTH_PARAMS=new Set(["audience","resource"]);var RESERVED_AUTH_PARAMS=new Set(["response_type","client_id","redirect_uri","scope","state","nonce","code_challenge","code_challenge_method"]);var DISCOVERY_CACHE_MAX=64;var DEFAULT_DISCOVERY_TTL_MS=3e5;var discoveryCache=new Map;function isLoopbackHostname(hostname){return hostname==="localhost"||hostname==="127.0.0.1"||hostname==="[::1]"||hostname==="::1"}function assertSafeOAuthUrl(rawUrl,errorOverrides){if(typeof rawUrl!=="string"||rawUrl.trim().length===0){throw new MelaraAuthConfigError("missing_issuer",errorMessage("missingIssuer",errorOverrides))}let parsed;try{parsed=new URL(rawUrl.trim())}catch(cause){throw new MelaraAuthConfigError("missing_issuer",errorMessage("missingIssuer",errorOverrides),{cause})}if(parsed.username||parsed.password||parsed.hash){throw new MelaraAuthConfigError("insecure_issuer",errorMessage("insecureIssuer",errorOverrides))}if(parsed.protocol==="https:"){return parsed}if(parsed.protocol==="http:"&&isLoopbackHostname(parsed.hostname)){return parsed}throw new MelaraAuthConfigError("insecure_issuer",errorMessage("insecureIssuer",errorOverrides))}function normalizeIssuer(rawIssuer,errorOverrides){const parsed=assertSafeOAuthUrl(rawIssuer,errorOverrides);if(parsed.search){throw new MelaraAuthConfigError("missing_issuer",errorMessage("missingIssuer",errorOverrides))}const cleanPath=parsed.pathname.replace(/\/+$/,"");return cleanPath.length===0?parsed.origin:`${parsed.origin}${cleanPath}`}function rewriteOriginIfMatching(endpoint,publicOrigin,internalOrigin,errorOverrides){const validated=assertSafeOAuthUrl(endpoint,errorOverrides);if(!internalOrigin||validated.origin!==publicOrigin){return validated.toString()}return`${internalOrigin}${validated.pathname}${validated.search}`}async function fetchNoRedirect(fetchImpl,url,init,errorOverrides){const response=await fetchImpl(url,{...init,redirect:"manual"});if(response.status>=300&&response.status<400){throw new MelaraAuthVerificationError("redirect_refused",errorMessage("redirectRefused",errorOverrides))}return response}function generateCodeVerifier(byteLength=32){if(!Number.isInteger(byteLength)||byteLength<32||byteLength>96){throw new MelaraAuthConfigError("invalid_pkce_length",errorMessage("invalidPkceLength"))}return randomBase64Url(byteLength)}async function computeS256Challenge(codeVerifier){if(typeof codeVerifier!=="string"||codeVerifier.length<43||codeVerifier.length>128||!PKCE_VERIFIER_PATTERN.test(codeVerifier)){throw new MelaraAuthConfigError("invalid_pkce_verifier",errorMessage("invalidPkceVerifier"))}const digest=await sha256Bytes(encodeUtf8(codeVerifier));return toBase64Url(digest)}function generateState(byteLength=32){return randomBase64Url(byteLength)}function generateNonce(byteLength=32){return randomBase64Url(byteLength)}function buildAuthorizationUrl(input){const authEndpoint=assertSafeOAuthUrl(input.authorizationEndpoint);const redirectUri=assertSafeOAuthUrl(input.redirectUri);if(typeof input.clientId!=="string"||input.clientId.trim().length===0){throw new MelaraAuthConfigError("missing_client_id",errorMessage("missingClientId"))}if(typeof input.state!=="string"||input.state.trim().length===0||typeof input.nonce!=="string"||input.nonce.trim().length===0||typeof input.codeChallenge!=="string"||input.codeChallenge.trim().length===0){throw new MelaraAuthConfigError("invalid_auth_request",errorMessage("invalidAuthRequest"))}const hasAudienceValue=typeof input.audience==="string"&&input.audience.trim().length>0||Array.isArray(input.audience)&&input.audience.length>0;if(hasAudienceValue){throw new MelaraAuthConfigError("forbidden_audience",errorMessage("forbiddenAudience"))}if(input.extraParams){for(const key of Object.keys(input.extraParams)){const normalizedKey=key.trim().toLowerCase();if(AUDIENCE_AUTH_PARAMS.has(normalizedKey)){throw new MelaraAuthConfigError("forbidden_audience",errorMessage("forbiddenAudience"))}if(RESERVED_AUTH_PARAMS.has(normalizedKey)){throw new MelaraAuthConfigError("invalid_auth_request",errorMessage("reservedAuthParam"))}}}const rawScopes=input.scopes??DEFAULT_IDENTITY_SCOPES;const resolvedScopes=[];for(const item of rawScopes){for(const token of item.split(/\s+/)){const trimmed=token.trim();if(!trimmed){continue}if(trimmed==="melara-api"||trimmed.includes("melara-api")){throw new MelaraAuthConfigError("forbidden_audience",errorMessage("forbiddenAudience"))}if(!ALLOWED_IDENTITY_SCOPES.has(trimmed)){throw new MelaraAuthConfigError("forbidden_scope",errorMessage("forbiddenScope"))}if(!resolvedScopes.includes(trimmed)){resolvedScopes.push(trimmed)}}}if(!resolvedScopes.includes("openid")){throw new MelaraAuthConfigError("forbidden_scope",errorMessage("forbiddenScope"))}const url=new URL(authEndpoint.toString());for(const key of new Set(url.searchParams.keys())){const normalizedKey=key.trim().toLowerCase();if(AUDIENCE_AUTH_PARAMS.has(normalizedKey)||RESERVED_AUTH_PARAMS.has(normalizedKey)){url.searchParams.delete(key)}}url.searchParams.set("response_type","code");url.searchParams.set("client_id",input.clientId.trim());url.searchParams.set("redirect_uri",redirectUri.toString());url.searchParams.set("scope",resolvedScopes.join(" "));url.searchParams.set("state",input.state);url.searchParams.set("nonce",input.nonce);url.searchParams.set("code_challenge",input.codeChallenge);url.searchParams.set("code_challenge_method","S256");if(input.prompt&&input.prompt.trim().length>0){url.searchParams.set("prompt",input.prompt.trim())}if(input.extraParams){for(const[key,value]of Object.entries(input.extraParams)){url.searchParams.set(key,value)}}return url.toString()}async function discoverOidcConfiguration(issuer,options){const errorOverrides=options?.errorLabels;const normalizedIssuer=normalizeIssuer(issuer,errorOverrides);const issuerUrl=new URL(normalizedIssuer);const internalOrigin=options?.internalUrl?assertSafeOAuthUrl(options.internalUrl,errorOverrides).origin:void 0;const cacheKey=`${normalizedIssuer}|${internalOrigin??""}`;const nowMs=options?.now?options.now():Date.now();const cached=discoveryCache.get(cacheKey);if(cached&&nowMs<cached.expiresAtMs){return cached.document}const discoveryBase=internalOrigin?`${internalOrigin}${issuerUrl.pathname.replace(/\/+$/,"")}`:normalizedIssuer;const discoveryUrl=`${discoveryBase}/.well-known/openid-configuration`;const fetchImpl=options?.fetch??globalThis.fetch;let response;try{response=await fetchNoRedirect(fetchImpl,discoveryUrl,{method:"GET",headers:{accept:"application/json"}},errorOverrides)}catch(cause){if(cause instanceof MelaraAuthError){throw cause}throw new MelaraAuthError("discovery_failed",errorMessage("discoveryFailed",errorOverrides),502,{cause})}if(!response.ok){throw new MelaraAuthError("discovery_failed",errorMessage("discoveryFailed",errorOverrides),502)}let body;try{body=await response.json()}catch(cause){throw new MelaraAuthError("discovery_failed",errorMessage("discoveryFailed",errorOverrides),502,{cause})}if(!body||typeof body!=="object"){throw new MelaraAuthError("discovery_failed",errorMessage("discoveryFailed",errorOverrides),502)}const record=body;if(typeof record.issuer!=="string"){throw new MelaraAuthVerificationError("issuer_mismatch",errorMessage("issuerMismatch",errorOverrides))}const discoveredIssuer=normalizeIssuer(record.issuer,errorOverrides);if(discoveredIssuer!==normalizedIssuer){throw new MelaraAuthVerificationError("issuer_mismatch",errorMessage("issuerMismatch",errorOverrides))}if(typeof record.authorization_endpoint!=="string"||typeof record.token_endpoint!=="string"||typeof record.jwks_uri!=="string"){throw new MelaraAuthError("discovery_failed",errorMessage("discoveryFailed",errorOverrides),502)}const publicOrigin=issuerUrl.origin;const authEndpoint=assertSafeOAuthUrl(record.authorization_endpoint,errorOverrides).toString();const tokenEndpoint=rewriteOriginIfMatching(record.token_endpoint,publicOrigin,internalOrigin,errorOverrides);const jwksUri=rewriteOriginIfMatching(record.jwks_uri,publicOrigin,internalOrigin,errorOverrides);const userinfoEndpoint=typeof record.userinfo_endpoint==="string"?rewriteOriginIfMatching(record.userinfo_endpoint,publicOrigin,internalOrigin,errorOverrides):void 0;const revocationEndpoint=typeof record.revocation_endpoint==="string"?rewriteOriginIfMatching(record.revocation_endpoint,publicOrigin,internalOrigin,errorOverrides):void 0;const endSessionEndpoint=typeof record.end_session_endpoint==="string"?assertSafeOAuthUrl(record.end_session_endpoint,errorOverrides).toString():void 0;const document=Object.freeze({issuer:normalizedIssuer,authorization_endpoint:authEndpoint,token_endpoint:tokenEndpoint,jwks_uri:jwksUri,...userinfoEndpoint?{userinfo_endpoint:userinfoEndpoint}:{},...revocationEndpoint?{revocation_endpoint:revocationEndpoint}:{},...endSessionEndpoint?{end_session_endpoint:endSessionEndpoint}:{}});const ttlMs=Math.max(0,options?.ttlMs??DEFAULT_DISCOVERY_TTL_MS);if(ttlMs>0){if(discoveryCache.size>=DISCOVERY_CACHE_MAX){const oldestKey=discoveryCache.keys().next().value;if(oldestKey!==void 0){discoveryCache.delete(oldestKey)}}discoveryCache.set(cacheKey,{document,expiresAtMs:nowMs+ttlMs})}return document}async function exchangeAuthorizationCode(input){const errorOverrides=input.errorLabels;const tokenUrl=assertSafeOAuthUrl(input.tokenEndpoint,errorOverrides).toString();const redirectUrl=assertSafeOAuthUrl(input.redirectUri,errorOverrides).toString();if(typeof input.clientId!=="string"||input.clientId.trim().length===0){throw new MelaraAuthConfigError("missing_client_id",errorMessage("missingClientId",errorOverrides))}if(typeof input.code!=="string"||input.code.trim().length===0||typeof input.codeVerifier!=="string"||input.codeVerifier.trim().length===0){throw new MelaraAuthVerificationError("token_exchange_failed",errorMessage("tokenExchangeFailed",errorOverrides))}const params=new URLSearchParams;params.set("grant_type","authorization_code");params.set("code",input.code);params.set("redirect_uri",redirectUrl);params.set("code_verifier",input.codeVerifier);params.set("client_id",input.clientId.trim());const headers={accept:"application/json","content-type":"application/x-www-form-urlencoded"};const authMethod=input.tokenEndpointAuthMethod??(input.clientSecret?"client_secret_post":"none");if(authMethod==="client_secret_post"){if(input.clientSecret){params.set("client_secret",input.clientSecret)}}else if(authMethod==="client_secret_basic"){const basicRaw=`${encodeURIComponent(input.clientId.trim())}:${encodeURIComponent(input.clientSecret??"")}`;headers.authorization=`Basic ${btoa(basicRaw)}`}const fetchImpl=input.fetch??globalThis.fetch;let response;try{response=await fetchNoRedirect(fetchImpl,tokenUrl,{method:"POST",headers,body:params.toString()},errorOverrides)}catch(cause){if(cause instanceof MelaraAuthError){throw cause}throw new MelaraAuthVerificationError("token_exchange_failed",errorMessage("tokenExchangeFailed",errorOverrides),{cause})}if(!response.ok){throw new MelaraAuthVerificationError("token_exchange_failed",errorMessage("tokenExchangeFailed",errorOverrides))}let data;try{data=await response.json()}catch(cause){throw new MelaraAuthVerificationError("token_exchange_failed",errorMessage("tokenExchangeFailed",errorOverrides),{cause})}if(!data||typeof data!=="object"){throw new MelaraAuthVerificationError("token_exchange_failed",errorMessage("tokenExchangeFailed",errorOverrides))}const tokenObj=data;if(typeof tokenObj.access_token!=="string"||tokenObj.access_token.length===0||typeof tokenObj.id_token!=="string"||tokenObj.id_token.length===0){throw new MelaraAuthVerificationError("token_exchange_failed",errorMessage("tokenExchangeFailed",errorOverrides))}return Object.freeze({accessToken:tokenObj.access_token,idToken:tokenObj.id_token,tokenType:typeof tokenObj.token_type==="string"?tokenObj.token_type:"Bearer",...typeof tokenObj.refresh_token==="string"?{refreshToken:tokenObj.refresh_token}:{},...typeof tokenObj.expires_in==="number"&&Number.isFinite(tokenObj.expires_in)?{expiresIn:tokenObj.expires_in}:{},...typeof tokenObj.scope==="string"?{scope:tokenObj.scope}:{}})}var DEFAULT_JWKS_CACHE_TTL_MS=3e5;var MIN_JWKS_REFRESH_COOLDOWN_MS=6e4;var MAX_CLOCK_SKEW_SECONDS=30;var DEFAULT_CLOCK_SKEW_SECONDS=15;var ALLOWED_JWT_TYPES=new Set(["jwt","id_token+jwt"]);async function importSanitizedPublicKey(rawKey){if(rawKey.use!==void 0&&rawKey.use!=="sig"){return null}if(Array.isArray(rawKey.key_ops)&&!rawKey.key_ops.includes("verify")){return null}const kid=typeof rawKey.kid==="string"&&rawKey.kid.length>0?rawKey.kid:"__default__";if(rawKey.kty==="RSA"){if(rawKey.alg!==void 0&&rawKey.alg!=="RS256"){return null}if(typeof rawKey.n!=="string"||typeof rawKey.e!=="string"){return null}try{const modulus=fromBase64Url(rawKey.n);const exponent=fromBase64Url(rawKey.e);if(modulus.length<256||exponent.length===0){return null}const key=await crypto.subtle.importKey("jwk",{kty:"RSA",n:rawKey.n,e:rawKey.e,ext:true},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},false,["verify"]);return{kid,entry:{alg:"RS256",key}}}catch{return null}}if(rawKey.kty==="EC"){if(rawKey.alg!==void 0&&rawKey.alg!=="ES256"){return null}if(rawKey.crv!=="P-256"||typeof rawKey.x!=="string"||typeof rawKey.y!=="string"){return null}try{const xCoord=fromBase64Url(rawKey.x);const yCoord=fromBase64Url(rawKey.y);if(xCoord.length!==32||yCoord.length!==32){return null}const key=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:rawKey.x,y:rawKey.y,ext:true},{name:"ECDSA",namedCurve:"P-256"},false,["verify"]);return{kid,entry:{alg:"ES256",key}}}catch{return null}}return null}function parseJwsEnvelope(idToken){if(typeof idToken!=="string"||idToken.length===0){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"))}const segments=idToken.split(".");if(segments.length!==3){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"))}const[headerSeg,payloadSeg,signatureSeg]=segments;if(!headerSeg||!payloadSeg){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"))}let rawHeader;try{rawHeader=decodeBase64UrlJson(headerSeg)}catch(cause){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"),{cause})}if(!rawHeader||typeof rawHeader!=="object"||Array.isArray(rawHeader)){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"))}const header=rawHeader;if(header.alg!=="RS256"&&header.alg!=="ES256"){throw new MelaraAuthVerificationError("unsupported_alg",errorMessage("unsupportedAlg"))}if(header.crit!==void 0){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"))}if(header.typ!==void 0&&(typeof header.typ!=="string"||!ALLOWED_JWT_TYPES.has(header.typ.toLowerCase()))){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"))}if(!signatureSeg){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"))}let signatureBytes;try{signatureBytes=fromBase64Url(signatureSeg)}catch(cause){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"),{cause})}if(header.alg==="ES256"&&signatureBytes.length!==64){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"))}const kid=typeof header.kid==="string"&&header.kid.length>0?header.kid:"__default__";return{alg:header.alg,kid,headerSeg,payloadSeg,signatureBytes}}async function verifyJwsAndDecodePayload(envelope,keyEntry){const signingInput=encodeUtf8(`${envelope.headerSeg}.${envelope.payloadSeg}`);const verified=await crypto.subtle.verify(envelope.alg==="RS256"?{name:"RSASSA-PKCS1-v1_5"}:{name:"ECDSA",hash:"SHA-256"},keyEntry.key,envelope.signatureBytes,signingInput);if(!verified){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"))}let rawClaims;try{rawClaims=decodeBase64UrlJson(envelope.payloadSeg)}catch(cause){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"),{cause})}if(!rawClaims||typeof rawClaims!=="object"||Array.isArray(rawClaims)){throw new MelaraAuthVerificationError("invalid_jwt",errorMessage("invalidJwt"))}return rawClaims}function validateAudienceAndAzp(claims,expectedClientId){let audList;if(typeof claims.aud==="string"&&claims.aud.length>0){audList=[claims.aud]}else if(Array.isArray(claims.aud)&&claims.aud.length>0&&claims.aud.every(item=>typeof item==="string"&&item.length>0)){audList=claims.aud}else{throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}if(audList.includes("melara-api")||claims.azp==="melara-api"){throw new MelaraAuthVerificationError("forbidden_audience",errorMessage("forbiddenAudience"))}if(!audList.includes(expectedClientId)){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}if(audList.length>1&&claims.azp!==expectedClientId){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}if(claims.azp!==void 0&&claims.azp!==expectedClientId){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}return audList}function validateTimestampsAndNonce(claims,verifyOptions,nowFn){const nowSec=verifyOptions.nowSeconds??Math.floor(nowFn()/1e3);const skew=Math.min(MAX_CLOCK_SKEW_SECONDS,Math.max(0,verifyOptions.clockSkewSeconds??DEFAULT_CLOCK_SKEW_SECONDS));if(typeof claims.exp!=="number"||!Number.isFinite(claims.exp)){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}if(typeof claims.iat!=="number"||!Number.isFinite(claims.iat)){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}if(nowSec>=claims.exp+skew||claims.iat>nowSec+skew||claims.iat>claims.exp){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}if(claims.nbf!==void 0){if(typeof claims.nbf!=="number"||!Number.isFinite(claims.nbf)||nowSec+skew<claims.nbf){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}}if(verifyOptions.expectedNonce!==void 0){if(typeof claims.nonce!=="string"||claims.nonce.length===0||!constantTimeEqual(claims.nonce,verifyOptions.expectedNonce)){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}}return{exp:claims.exp,iat:claims.iat}}function buildVerifiedTokenResult(claims,sub,iss,audList,exp,iat){return Object.freeze({sub,iss,aud:typeof claims.aud==="string"?claims.aud:Object.freeze([...audList]),exp,iat,...typeof claims.nbf==="number"?{nbf:claims.nbf}:{},...typeof claims.nonce==="string"?{nonce:claims.nonce}:{},...typeof claims.azp==="string"?{azp:claims.azp}:{},...typeof claims.email==="string"?{email:claims.email}:{},...typeof claims.email_verified==="boolean"?{email_verified:claims.email_verified}:{},...typeof claims.name==="string"?{name:claims.name}:{},...typeof claims.given_name==="string"?{given_name:claims.given_name}:{},...typeof claims.family_name==="string"?{family_name:claims.family_name}:{},...typeof claims.picture==="string"?{picture:claims.picture}:{},claims:Object.freeze({...claims})})}function createJwksVerifier(options){const jwksUrl=assertSafeOAuthUrl(options.jwksUri).toString();const fetchImpl=options.fetch??globalThis.fetch;const cacheTtlMs=Math.max(MIN_JWKS_REFRESH_COOLDOWN_MS,options.cacheTtlMs??DEFAULT_JWKS_CACHE_TTL_MS);const refreshCooldownMs=Math.max(MIN_JWKS_REFRESH_COOLDOWN_MS,options.refreshCooldownMs??MIN_JWKS_REFRESH_COOLDOWN_MS);const nowFn=options.now??Date.now;let keyMap=new Map;let lastFetchedAtMs=-Infinity;let expiresAtMs=-Infinity;let inflightRefresh=null;async function refreshKeys(){if(inflightRefresh){return inflightRefresh}inflightRefresh=(async()=>{const fetchedAt=nowFn();let response;try{response=await fetchNoRedirect(fetchImpl,jwksUrl,{method:"GET",headers:{accept:"application/json"}})}catch(cause){if(cause instanceof MelaraAuthError){throw cause}throw new MelaraAuthError("jwks_fetch_failed",errorMessage("jwksFetchFailed"),502,{cause})}if(!response.ok){throw new MelaraAuthError("jwks_fetch_failed",errorMessage("jwksFetchFailed"),502)}let parsed;try{parsed=await response.json()}catch(cause){throw new MelaraAuthError("jwks_fetch_failed",errorMessage("jwksFetchFailed"),502,{cause})}if(!parsed||typeof parsed!=="object"||!Array.isArray(parsed.keys)){throw new MelaraAuthError("jwks_fetch_failed",errorMessage("jwksFetchFailed"),502)}const rawKeys=parsed.keys;const nextMap=new Map;for(const item of rawKeys){if(!item||typeof item!=="object"){continue}const imported=await importSanitizedPublicKey(item);if(imported){nextMap.set(imported.kid,imported.entry)}}keyMap=nextMap;lastFetchedAtMs=fetchedAt;expiresAtMs=fetchedAt+cacheTtlMs})();try{await inflightRefresh}finally{inflightRefresh=null}}async function resolveKey(kid,alg){const nowMs=nowFn();if(keyMap.size===0||nowMs>=expiresAtMs){await refreshKeys()}let found=keyMap.get(kid);if(!found&&nowMs-lastFetchedAtMs>=refreshCooldownMs){await refreshKeys();found=keyMap.get(kid)}if(!found){throw new MelaraAuthVerificationError("unknown_kid",errorMessage("unknownKeyId"))}if(found.alg!==alg){throw new MelaraAuthVerificationError("unsupported_alg",errorMessage("unsupportedAlg"))}return found}return{clearCache(){keyMap.clear();lastFetchedAtMs=-Infinity;expiresAtMs=-Infinity},async verifyIdToken(idToken,verifyOptions){const expectedIssuer=normalizeIssuer(verifyOptions.issuer);if(typeof verifyOptions.clientId!=="string"||verifyOptions.clientId.trim().length===0){throw new MelaraAuthConfigError("missing_client_id",errorMessage("missingClientId"))}const expectedClientId=verifyOptions.clientId.trim();const envelope=parseJwsEnvelope(idToken);const keyEntry=await resolveKey(envelope.kid,envelope.alg);const claims=await verifyJwsAndDecodePayload(envelope,keyEntry);if(typeof claims.iss!=="string"){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}let tokenIssuer;try{tokenIssuer=normalizeIssuer(claims.iss)}catch(cause){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"),{cause})}if(tokenIssuer!==expectedIssuer){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}if(typeof claims.sub!=="string"||claims.sub.trim().length===0||claims.sub.length>255){throw new MelaraAuthVerificationError("invalid_claims",errorMessage("invalidClaims"))}const audList=validateAudienceAndAzp(claims,expectedClientId);const{exp,iat}=validateTimestampsAndNonce(claims,verifyOptions,nowFn);return buildVerifiedTokenResult(claims,claims.sub,claims.iss,audList,exp,iat)}}}var DEFAULT_BASE_PATH="/api/auth";var RETURN_TO_SENTINEL_ORIGIN="https://melara-return-check.invalid";var RETURN_TO_DECODE_ROUNDS=3;function normalizeBasePath(rawBasePath){if(!rawBasePath||rawBasePath.trim().length===0){return DEFAULT_BASE_PATH}const trimmed=rawBasePath.trim();const withLeading=trimmed.startsWith("/")?trimmed:`/${trimmed}`;const withoutTrailing=withLeading.replace(/\/+$/,"");return withoutTrailing.length===0?DEFAULT_BASE_PATH:withoutTrailing}function pathLeavesOrigin(pathname){let current=pathname;for(let round=0;round<=RETURN_TO_DECODE_ROUNDS;round+=1){if(current.includes("\\")){return true}const resolved=new URL(current,RETURN_TO_SENTINEL_ORIGIN);if(resolved.origin!==RETURN_TO_SENTINEL_ORIGIN||resolved.pathname.startsWith("//")){return true}let decoded;try{decoded=decodeURIComponent(current)}catch{return false}if(decoded===current){return false}current=decoded}return true}function sanitizeReturnTo(raw){if(typeof raw!=="string"||raw.length===0||raw.length>2048){return"/"}if(!raw.startsWith("/")||raw.startsWith("//")||raw.includes("\\")){return"/"}for(let i=0;i<raw.length;i+=1){const code=raw.charCodeAt(i);if(code<=31||code===127){return"/"}}try{const parsed=new URL(raw,RETURN_TO_SENTINEL_ORIGIN);if(parsed.origin!==RETURN_TO_SENTINEL_ORIGIN||pathLeavesOrigin(parsed.pathname)){return"/"}return`${parsed.pathname}${parsed.search}${parsed.hash}`}catch{return"/"}}var MIN_SESSION_SECRET_LENGTH=32;var DEFAULT_SESSION_TTL_SECONDS=60*60*24*7;var HKDF_SALT=encodeUtf8("melara-auth-hkdf-salt-v1");var SESSION_KEY_PURPOSE="melara-auth-session-v1";var OAUTH_STATE_KEY_PURPOSE="melara-auth-oauth-state-v1";var DERIVED_KEY_CACHE_MAX=32;var derivedKeyCache=new Map;function assertValidSessionSecret(sessionSecret){if(typeof sessionSecret!=="string"||sessionSecret.length<MIN_SESSION_SECRET_LENGTH){throw new MelaraAuthConfigError("short_session_secret",errorMessage("shortSessionSecret"))}return sessionSecret}function assertValidCookieName(cookieName){if(typeof cookieName!=="string"||cookieName.trim().length===0){throw new MelaraAuthConfigError("invalid_cookie_name",errorMessage("invalidCookieName"))}return cookieName.trim()}function deriveAesGcmKey(secret,purpose){const cacheKey=`${purpose}:${secret}`;const existing=derivedKeyCache.get(cacheKey);if(existing){return existing}const derivation=(async()=>{const baseKey=await crypto.subtle.importKey("raw",encodeUtf8(secret),"HKDF",false,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:HKDF_SALT,info:encodeUtf8(purpose)},baseKey,{name:"AES-GCM",length:256},false,["encrypt","decrypt"])})();if(derivedKeyCache.size>=DERIVED_KEY_CACHE_MAX){const oldest=derivedKeyCache.keys().next().value;if(oldest!==void 0){derivedKeyCache.delete(oldest)}}derivedKeyCache.set(cacheKey,derivation);return derivation}async function sealPayload(payload,options){const secret=assertValidSessionSecret(options.secret);const cookieName=assertValidCookieName(options.cookieName);const key=await deriveAesGcmKey(secret,options.purpose);const iv=new Uint8Array(12);crypto.getRandomValues(iv);const additionalData=encodeUtf8(`v1:${cookieName}`);const plaintext=encodeUtf8(JSON.stringify(payload));const encrypted=await crypto.subtle.encrypt({name:"AES-GCM",iv,additionalData,tagLength:128},key,plaintext);return`v1.${toBase64Url(iv)}.${toBase64Url(new Uint8Array(encrypted))}`}async function unsealPayload(token,options){const primarySecret=assertValidSessionSecret(options.secret);const cookieName=assertValidCookieName(options.cookieName);if(typeof token!=="string"||token.length===0){throw new MelaraAuthVerificationError("invalid_session",errorMessage("invalidSession"))}const segments=token.split(".");if(segments.length!==3||segments[0]!=="v1"||!segments[1]||!segments[2]){throw new MelaraAuthVerificationError("invalid_session",errorMessage("invalidSession"))}let iv;let ciphertext;try{iv=fromBase64Url(segments[1]);ciphertext=fromBase64Url(segments[2])}catch(cause){throw new MelaraAuthVerificationError("invalid_session",errorMessage("invalidSession"),{cause})}if(iv.length!==12||ciphertext.length<=16){throw new MelaraAuthVerificationError("invalid_session",errorMessage("invalidSession"))}const additionalData=encodeUtf8(`v1:${cookieName}`);const candidateSecrets=[primarySecret,...(options.previousSecrets??[]).filter(item=>typeof item==="string"&&item.length>=MIN_SESSION_SECRET_LENGTH&&item!==primarySecret)];for(const secret of candidateSecrets){try{const key=await deriveAesGcmKey(secret,options.purpose);const plaintextBuffer=await crypto.subtle.decrypt({name:"AES-GCM",iv,additionalData,tagLength:128},key,ciphertext);const parsed=JSON.parse(decodeUtf8(new Uint8Array(plaintextBuffer)));if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed)){return parsed}}catch{}}throw new MelaraAuthVerificationError("invalid_session",errorMessage("invalidSession"))}async function sealSession(user,options){assertValidSessionSecret(options.sessionSecret);if(!user||typeof user.sub!=="string"||user.sub.trim().length===0){throw new MelaraAuthConfigError("invalid_session_user",errorMessage("invalidSessionUser"))}const nowSec=options.nowSeconds??Math.floor(Date.now()/1e3);const ttl=Math.max(1,Math.floor(options.ttlSeconds??DEFAULT_SESSION_TTL_SECONDS));const csrf=options.csrfToken&&options.csrfToken.length>=32?options.csrfToken:randomBase64Url(32);const normalizedUser=Object.freeze({id:user.id||user.sub,sub:user.sub,email:user.email??null,emailVerified:Boolean(user.emailVerified),name:user.name??null,picture:user.picture??null,role:user.role||"member"});const session=Object.freeze({v:1,user:normalizedUser,iat:nowSec,exp:nowSec+ttl,csrf});const token=await sealPayload(session,{secret:options.sessionSecret,cookieName:options.cookieName,purpose:SESSION_KEY_PURPOSE});return{token,session}}async function unsealSession(token,options){const payload=await unsealPayload(token,{secret:options.sessionSecret,previousSecrets:options.previousSessionSecrets,cookieName:options.cookieName,purpose:SESSION_KEY_PURPOSE});const nowSec=options.nowSeconds??Math.floor(Date.now()/1e3);if(payload.v!==1||typeof payload.iat!=="number"||!Number.isFinite(payload.iat)||typeof payload.exp!=="number"||!Number.isFinite(payload.exp)||nowSec>=payload.exp||payload.iat>payload.exp||typeof payload.csrf!=="string"||payload.csrf.length<16||!payload.user||typeof payload.user!=="object"){throw new MelaraAuthVerificationError("invalid_session",errorMessage("invalidSession"))}const rawUser=payload.user;if(typeof rawUser.sub!=="string"||rawUser.sub.trim().length===0){throw new MelaraAuthVerificationError("invalid_session",errorMessage("invalidSession"))}const user=Object.freeze({id:typeof rawUser.id==="string"&&rawUser.id.length>0?rawUser.id:rawUser.sub,sub:rawUser.sub,email:typeof rawUser.email==="string"?rawUser.email:null,emailVerified:rawUser.emailVerified===true,name:typeof rawUser.name==="string"?rawUser.name:null,picture:typeof rawUser.picture==="string"?rawUser.picture:null,role:typeof rawUser.role==="string"&&rawUser.role.length>0?rawUser.role:"member"});return Object.freeze({v:1,user,iat:payload.iat,exp:payload.exp,csrf:payload.csrf})}async function sealOAuthState(payload,options){return sealPayload(payload,{secret:options.sessionSecret,cookieName:options.cookieName,purpose:OAUTH_STATE_KEY_PURPOSE})}async function unsealOAuthState(token,options){const payload=await unsealPayload(token,{secret:options.sessionSecret,previousSecrets:options.previousSessionSecrets,cookieName:options.cookieName,purpose:OAUTH_STATE_KEY_PURPOSE});const nowSec=options.nowSeconds??Math.floor(Date.now()/1e3);if(payload.v!==1||typeof payload.state!=="string"||payload.state.length===0||typeof payload.nonce!=="string"||payload.nonce.length===0||typeof payload.codeVerifier!=="string"||payload.codeVerifier.length===0||typeof payload.redirectUri!=="string"||payload.redirectUri.length===0||typeof payload.returnTo!=="string"||payload.returnTo.length===0||typeof payload.iat!=="number"||!Number.isFinite(payload.iat)||typeof payload.exp!=="number"||!Number.isFinite(payload.exp)||nowSec>=payload.exp||payload.iat>payload.exp){throw new MelaraAuthVerificationError("csrf_mismatch",errorMessage("csrfMismatch"))}return Object.freeze({v:1,state:payload.state,nonce:payload.nonce,codeVerifier:payload.codeVerifier,redirectUri:payload.redirectUri,returnTo:payload.returnTo,iat:payload.iat,exp:payload.exp})}var DEFAULT_STATE_TTL_SECONDS=600;var MAX_CONSUMED_STATES=4096;var HTTPS_SESSION_COOKIE="__Host-melara_session";var LOCAL_SESSION_COOKIE="melara_session";var HTTPS_STATE_COOKIE="__Host-melara_oauth_state";var LOCAL_STATE_COOKIE="melara_oauth_state";function createMelaraAuthSharedState(){return{consumedStates:new Map,jwksVerifiers:new Map}}function readGlobalEnv(key){const proc=globalThis.process;const val=proc?.env?.[key];return typeof val==="string"&&val.trim().length>0?val.trim():void 0}function readEnvValue(key,optionsEnv,runtimeEnv){const fromRuntime=runtimeEnv?.[key];if(typeof fromRuntime==="string"&&fromRuntime.trim().length>0){return fromRuntime.trim()}const fromOptions=optionsEnv?.[key];if(typeof fromOptions==="string"&&fromOptions.trim().length>0){return fromOptions.trim()}return readGlobalEnv(key)}function splitCsv(raw){if(!raw){return[]}return raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0)}function parseCookieHeader(cookieHeader){const cookies=new Map;if(!cookieHeader){return cookies}for(const part of cookieHeader.split(";")){const trimmed=part.trim();if(!trimmed){continue}const eqIndex=trimmed.indexOf("=");if(eqIndex<=0){continue}const name=trimmed.slice(0,eqIndex).trim();const value=trimmed.slice(eqIndex+1).trim();if(name&&!cookies.has(name)){cookies.set(name,value)}}return cookies}function serializeCookie(name,value,options){const secure=options.isHttps||name.startsWith("__Host-")||name.startsWith("__Secure-");const maxAge=Math.max(0,Math.floor(options.maxAgeSeconds));return`${name}=${value}; Path=/; Max-Age=${maxAge}; HttpOnly; SameSite=Lax${secure?"; Secure":""}`}function jsonResponse(body,status,extraHeaders){const headers=new Headers({"cache-control":"no-store","content-type":"application/json; charset=utf-8",...extraHeaders});return new Response(JSON.stringify(body),{status,headers})}function resolveSessionConfig(options,env){const rawSecret=options?.sessionSecret??readEnvValue("MELARA_SESSION_SECRET",options?.env,env)??readEnvValue("APP_SESSION_SECRET",options?.env,env);const sessionSecret=assertValidSessionSecret(rawSecret);const nowMs=options?.now?options.now():Date.now();return{sessionSecret,previousSessionSecrets:options?.previousSessionSecrets??[],sessionCookieName:options?.sessionCookieName,nowSeconds:Math.floor(nowMs/1e3),errorLabels:options?.labels?.errors}}function resolveOAuthEndpoints(options,env,errorLabels){const rawIssuer=options?.issuer??readEnvValue("MELARA_ISSUER",options?.env,env)??readEnvValue("MELARA_HYDRA_ISSUER",options?.env,env);if(!rawIssuer){throw new MelaraAuthConfigError("missing_issuer",errorMessage("missingIssuer",errorLabels))}const rawClientId=options?.clientId??readEnvValue("MELARA_CLIENT_ID",options?.env,env);if(!rawClientId){throw new MelaraAuthConfigError("missing_client_id",errorMessage("missingClientId",errorLabels))}return{rawIssuer,rawClientId,clientSecret:options?.clientSecret??readEnvValue("MELARA_CLIENT_SECRET",options?.env,env),internalUrl:options?.internalUrl??readEnvValue("MELARA_HYDRA_INTERNAL_URL",options?.env,env)}}async function readSessionFromLookup(getCookie,knownHttps,options,env){const cfg=resolveSessionConfig(options,env);const candidateNames=cfg.sessionCookieName?[cfg.sessionCookieName]:knownHttps===true?[HTTPS_SESSION_COOKIE]:knownHttps===false?[LOCAL_SESSION_COOKIE]:[HTTPS_SESSION_COOKIE,LOCAL_SESSION_COOKIE];for(const cookieName of candidateNames){const rawToken=getCookie(cookieName);if(!rawToken){continue}try{return await unsealSession(rawToken,{sessionSecret:cfg.sessionSecret,previousSessionSecrets:cfg.previousSessionSecrets,cookieName,nowSeconds:cfg.nowSeconds})}catch(err){if(err instanceof MelaraAuthConfigError){throw err}}}return null}async function handleSessionRoute(request,env,readSession){if(request.method!=="GET"){return jsonResponse({error:"method_not_allowed"},405,{allow:"GET"})}const session=await readSession(request,env);if(!session){return jsonResponse({authenticated:false,user:null,csrfToken:null,expiresAt:null},200)}return jsonResponse({authenticated:true,user:session.user,csrfToken:session.csrf,expiresAt:session.exp},200)}function verifyLogoutSameOrigin(request,expectedOrigin){const originHeader=request.headers.get("origin");if(originHeader!==null){return originHeader===expectedOrigin}const refererHeader=request.headers.get("referer");if(refererHeader!==null){try{return new URL(refererHeader).origin===expectedOrigin}catch{return false}}return null}async function handleLogoutRoute(params){const{request,requestUrl,env,sessionCookieName,isHttps,errorLabels,readSession}=params;if(request.method!=="POST"){return jsonResponse({error:"method_not_allowed"},405,{allow:"POST"})}const rejectCsrf=()=>jsonResponse({error:"logout_csrf_failed",message:errorMessage("logoutCsrfFailed",errorLabels)},403);const sameOriginCheck=verifyLogoutSameOrigin(request,requestUrl.origin);if(sameOriginCheck===false){return rejectCsrf()}const csrfHeader=request.headers.get("x-melara-csrf");const activeSession=await readSession(request,env);let csrfVerified=false;if(csrfHeader!==null){if(!activeSession||!constantTimeEqual(csrfHeader,activeSession.csrf)){return rejectCsrf()}csrfVerified=true}if(sameOriginCheck!==true&&!csrfVerified){return rejectCsrf()}const headers=new Headers({"cache-control":"no-store","content-type":"application/json; charset=utf-8"});headers.append("set-cookie",serializeCookie(sessionCookieName,"",{maxAgeSeconds:0,isHttps}));return new Response(JSON.stringify({ok:true}),{status:200,headers})}async function handleLoginRoute(params){const{request,requestUrl,basePath,stateCookieName,isHttps,sessionCfg,endpoints,options,errorLabels}=params;if(request.method!=="GET"){return jsonResponse({error:"method_not_allowed"},405,{allow:"GET"})}const discovery=await discoverOidcConfiguration(endpoints.rawIssuer,{internalUrl:endpoints.internalUrl,fetch:options?.fetch,ttlMs:options?.discoveryTtlMs,now:options?.now,errorLabels});const redirectUri=options?.redirectUri??`${requestUrl.origin}${basePath}/callback`;const state=generateState();const nonce=generateNonce();const codeVerifier=generateCodeVerifier();const codeChallenge=await computeS256Challenge(codeVerifier);const returnTo=sanitizeReturnTo(requestUrl.searchParams.get("returnTo"));const stateTtl=Math.max(60,Math.floor(options?.stateTtlSeconds??DEFAULT_STATE_TTL_SECONDS));const sealedState=await sealOAuthState({v:1,state,nonce,codeVerifier,redirectUri,returnTo,iat:sessionCfg.nowSeconds,exp:sessionCfg.nowSeconds+stateTtl},{sessionSecret:sessionCfg.sessionSecret,cookieName:stateCookieName});const authorizationUrl=buildAuthorizationUrl({authorizationEndpoint:discovery.authorization_endpoint,clientId:endpoints.rawClientId,redirectUri,state,nonce,codeChallenge,scopes:options?.scopes});const headers=new Headers({"cache-control":"no-store",location:authorizationUrl});headers.append("set-cookie",serializeCookie(stateCookieName,sealedState,{maxAgeSeconds:stateTtl,isHttps}));return new Response(null,{status:302,headers})}function buildAuthenticatedUser(verified,options,env){const adminEmails=new Set([...options?.adminEmails??[],...options?.roles?.adminEmails??[],...splitCsv(readEnvValue("MELARA_ADMIN_EMAILS",options?.env,env)),...splitCsv(readEnvValue("OWNER_EMAIL",options?.env,env))].map(email=>email.trim().toLowerCase()));const adminSubs=new Set([...options?.adminSubList??[],...options?.roles?.adminSubList??[],...splitCsv(readEnvValue("MELARA_ADMIN_SUBS",options?.env,env))].map(sub=>sub.trim()));const normalizedEmail=typeof verified.email==="string"&&verified.email.trim().length>0?verified.email.trim():null;const emailVerified=verified.email_verified===true;const defaultRole=options?.roles?.defaultRole??"member";const isPromotedAdmin=adminSubs.has(verified.sub)||emailVerified&&normalizedEmail!==null&&adminEmails.has(normalizedEmail.toLowerCase());return Object.freeze({id:verified.sub,sub:verified.sub,email:normalizedEmail,emailVerified,name:typeof verified.name==="string"&&verified.name.trim().length>0?verified.name.trim():null,picture:typeof verified.picture==="string"&&verified.picture.trim().length>0?verified.picture.trim():null,role:isPromotedAdmin?"admin":defaultRole})}function pruneConsumedStates(consumedStates,nowSec){for(const[key,exp]of consumedStates){if(exp<=nowSec){consumedStates.delete(key)}}while(consumedStates.size>=MAX_CONSUMED_STATES){const oldest=consumedStates.keys().next().value;if(oldest===void 0){break}consumedStates.delete(oldest)}}async function verifyAndConsumeCallbackState(params){const{request,requestUrl,stateCookieName,sessionCfg,sharedState,options,errorLabels,rejectCallback}=params;if(requestUrl.searchParams.get("error")){return{errorResponse:rejectCallback("oauth_error",errorMessage("tokenExchangeFailed",errorLabels),401)}}const stateParam=requestUrl.searchParams.get("state");const codeParam=requestUrl.searchParams.get("code");const cookies=parseCookieHeader(request.headers.get("cookie"));const rawStateCookie=cookies.get(stateCookieName);if(!stateParam||!rawStateCookie){return{errorResponse:rejectCallback("csrf_mismatch",errorMessage("csrfMismatch",errorLabels),403)}}let statePayload;try{statePayload=await unsealOAuthState(rawStateCookie,{sessionSecret:sessionCfg.sessionSecret,previousSessionSecrets:sessionCfg.previousSessionSecrets,cookieName:stateCookieName,nowSeconds:sessionCfg.nowSeconds})}catch(err){if(err instanceof MelaraAuthConfigError){throw err}return{errorResponse:rejectCallback("csrf_mismatch",errorMessage("csrfMismatch",errorLabels),403)}}if(!constantTimeEqual(stateParam,statePayload.state)){return{errorResponse:rejectCallback("csrf_mismatch",errorMessage("csrfMismatch",errorLabels),403)}}pruneConsumedStates(sharedState.consumedStates,sessionCfg.nowSeconds);if(sharedState.consumedStates.has(statePayload.state)){return{errorResponse:rejectCallback("csrf_mismatch",errorMessage("csrfMismatch",errorLabels),403)}}if(options?.onConsumeState){const permitted=await options.onConsumeState(statePayload.state,statePayload.exp);if(!permitted){return{errorResponse:rejectCallback("csrf_mismatch",errorMessage("csrfMismatch",errorLabels),403)}}}sharedState.consumedStates.set(statePayload.state,statePayload.exp);if(!codeParam||codeParam.trim().length===0){return{errorResponse:rejectCallback("missing_code",errorMessage("tokenExchangeFailed",errorLabels),400)}}return{codeParam,statePayload}}function getOrCreateJwksVerifier(sharedState,jwksUri,options){const cacheKey=`${jwksUri}|${options?.jwksCooldownMs??""}`;const existing=sharedState.jwksVerifiers.get(cacheKey);if(existing){return existing}const created=createJwksVerifier({jwksUri,fetch:options?.fetch,refreshCooldownMs:options?.jwksCooldownMs,now:options?.now});sharedState.jwksVerifiers.set(cacheKey,created);return created}async function handleCallbackRoute(params){const{request,requestUrl,env,sessionCookieName,stateCookieName,isHttps,sessionCfg,endpoints,sharedState,options,errorLabels}=params;if(request.method!=="GET"){return jsonResponse({error:"method_not_allowed"},405,{allow:"GET"})}const clearStateHeader=serializeCookie(stateCookieName,"",{maxAgeSeconds:0,isHttps});const rejectCallback=(code,message,status)=>{const headers=new Headers({"cache-control":"no-store","content-type":"application/json; charset=utf-8"});headers.append("set-cookie",clearStateHeader);return new Response(JSON.stringify({error:code,message}),{status,headers})};const stateCheck=await verifyAndConsumeCallbackState({request,requestUrl,stateCookieName,sessionCfg,sharedState,options,errorLabels,rejectCallback});if("errorResponse"in stateCheck){return stateCheck.errorResponse}const{codeParam,statePayload}=stateCheck;try{const discovery=await discoverOidcConfiguration(endpoints.rawIssuer,{internalUrl:endpoints.internalUrl,fetch:options?.fetch,ttlMs:options?.discoveryTtlMs,now:options?.now,errorLabels});const tokens=await exchangeAuthorizationCode({tokenEndpoint:discovery.token_endpoint,clientId:endpoints.rawClientId,clientSecret:endpoints.clientSecret,tokenEndpointAuthMethod:options?.tokenEndpointAuthMethod,code:codeParam,redirectUri:statePayload.redirectUri,codeVerifier:statePayload.codeVerifier,fetch:options?.fetch,errorLabels});const verifier=getOrCreateJwksVerifier(sharedState,discovery.jwks_uri,options);const verified=await verifier.verifyIdToken(tokens.idToken,{issuer:discovery.issuer,clientId:endpoints.rawClientId,expectedNonce:statePayload.nonce,clockSkewSeconds:options?.clockSkewSeconds,nowSeconds:sessionCfg.nowSeconds});const baseUser=buildAuthenticatedUser(verified,options,env);const resolvedUser=options?.resolveUser?await options.resolveUser(baseUser,{idToken:verified,tokens,request}):baseUser;const safeReturnTo=sanitizeReturnTo(statePayload.returnTo);if(options?.onAuthenticated){await options.onAuthenticated({request,user:resolvedUser,idToken:verified,tokens,returnTo:safeReturnTo})}const sessionTtl=Math.max(60,Math.floor(options?.sessionTtlSeconds??DEFAULT_SESSION_TTL_SECONDS));const{token:sessionToken}=await sealSession(resolvedUser,{sessionSecret:sessionCfg.sessionSecret,cookieName:sessionCookieName,ttlSeconds:sessionTtl,nowSeconds:sessionCfg.nowSeconds});const headers=new Headers({"cache-control":"no-store",location:safeReturnTo});headers.append("set-cookie",clearStateHeader);headers.append("set-cookie",serializeCookie(sessionCookieName,sessionToken,{maxAgeSeconds:sessionTtl,isHttps}));return new Response(null,{status:303,headers})}catch(err){if(err instanceof MelaraAuthConfigError){throw err}if(err instanceof MelaraAuthCsrfError||err instanceof MelaraAuthError){return rejectCallback(err.code,err.message,err.status)}throw err}}function createMelaraAuthHandler(options,sharedState=createMelaraAuthSharedState()){async function readSession(requestOrHeaders,env){if(requestOrHeaders instanceof Request){const reqUrl=new URL(requestOrHeaders.url);const cookies2=parseCookieHeader(requestOrHeaders.headers.get("cookie"));return readSessionFromLookup(name=>cookies2.get(name),reqUrl.protocol==="https:",options,env)}const cookieHeader=requestOrHeaders instanceof Headers?requestOrHeaders.get("cookie"):requestOrHeaders;const cookies=parseCookieHeader(cookieHeader);return readSessionFromLookup(name=>cookies.get(name),void 0,options,env)}async function handleRequest(request,env){const requestUrl=new URL(request.url);const basePath=normalizeBasePath(options?.basePath);const pathname=requestUrl.pathname;const isLogin=pathname===`${basePath}/login`;const isCallback=pathname===`${basePath}/callback`;const isSession=pathname===`${basePath}/session`;const isLogout=pathname===`${basePath}/logout`;if(!isLogin&&!isCallback&&!isSession&&!isLogout){return null}const errorLabels=options?.labels?.errors;const isHttps=requestUrl.protocol==="https:";const sessionCookieName=options?.sessionCookieName??(isHttps?HTTPS_SESSION_COOKIE:LOCAL_SESSION_COOKIE);const stateCookieName=options?.stateCookieName??(isHttps?HTTPS_STATE_COOKIE:LOCAL_STATE_COOKIE);if(isSession){return handleSessionRoute(request,env,readSession)}if(isLogout){return handleLogoutRoute({request,requestUrl,env,sessionCookieName,isHttps,errorLabels,readSession})}assertSafeOAuthUrl(requestUrl.origin,errorLabels);const sessionCfg=resolveSessionConfig(options,env);const endpoints=resolveOAuthEndpoints(options,env,errorLabels);if(isLogin){return handleLoginRoute({request,requestUrl,basePath,stateCookieName,isHttps,sessionCfg,endpoints,options,errorLabels})}return handleCallbackRoute({request,requestUrl,env,sessionCookieName,stateCookieName,isHttps,sessionCfg,endpoints,sharedState,options,errorLabels})}return{handleRequest,readSession}}function resolveHonoEnv(c){const raw=c.env;if(raw&&typeof raw==="object"){return raw}return{}}function jsonGuardError(error,message,status){return new Response(JSON.stringify({error,message}),{status,headers:{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}})}function createHandlerResolver(options){const sharedState=createMelaraAuthSharedState();const staticHandler=typeof options==="function"?null:createMelaraAuthHandler(options,sharedState);return c=>{const env=resolveHonoEnv(c);if(staticHandler){return{handler:staticHandler,env,errorLabels:options&&typeof options!=="function"?options.labels?.errors:void 0}}const resolvedOptions=options(env);return{handler:createMelaraAuthHandler(resolvedOptions,sharedState),env,errorLabels:resolvedOptions.labels?.errors}}}async function authenticateHonoRequest(c,resolve){const{handler,env,errorLabels}=resolve(c);const existing=c.get("melaraSession");const session=existing??await handler.readSession(c.req.raw,env);if(!session){return{response:jsonGuardError("unauthorized",errorMessage("unauthorized",errorLabels),401)}}if(session.user.role==="blocked"){return{response:jsonGuardError("forbidden",errorMessage("forbidden",errorLabels),403)}}return{session,errorLabels}}function setHonoSessionVariables(c,session){c.set("melaraSession",session);c.set("melaraUser",session.user);c.set("user",session.user)}function melaraAuth(options){const resolve=createHandlerResolver(options);return async(c,next)=>{const{handler,env}=resolve(c);const response=await handler.handleRequest(c.req.raw,env);if(response){return response}await next();return void 0}}function requireUser(options){const resolve=createHandlerResolver(options);return async(c,next)=>{const auth=await authenticateHonoRequest(c,resolve);if("response"in auth){return auth.response}setHonoSessionVariables(c,auth.session);await next();return void 0}}function requireRole(roles,options){const allowedRoles=new Set(Array.isArray(roles)?roles:[roles]);const resolve=createHandlerResolver(options);return async(c,next)=>{const auth=await authenticateHonoRequest(c,resolve);if("response"in auth){return auth.response}if(!allowedRoles.has(auth.session.user.role)){return jsonGuardError("forbidden",errorMessage("forbidden",auth.errorLabels),403)}setHonoSessionVariables(c,auth.session);await next();return void 0}}export{melaraAuth,requireRole,requireUser};
2
+ //# sourceMappingURL=index.js.map