@auth0/auth0-express 1.0.0-beta.0 → 1.0.0-beta.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/README.md +2 -2
- package/dist/index.cjs +172 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +69 -23
- package/dist/index.d.ts +69 -23
- package/dist/index.js +164 -18
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Request, Response, Router, NextFunction } from 'express';
|
|
2
|
-
import { SessionStore, SessionConfiguration, ServerClient } from '@auth0/auth0-server-js';
|
|
2
|
+
import { DomainResolver, SessionStore, SessionConfiguration, DiscoveryCacheOptions, ServerClient } from '@auth0/auth0-server-js';
|
|
3
|
+
export { DiscoveryCacheOptions, DomainResolver, InvalidConfigurationError } from '@auth0/auth0-server-js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Options passed to custom session store implementations.
|
|
@@ -46,8 +47,14 @@ interface StoreOptions {
|
|
|
46
47
|
* ```
|
|
47
48
|
*/
|
|
48
49
|
interface Auth0Options {
|
|
49
|
-
/**
|
|
50
|
-
|
|
50
|
+
/**
|
|
51
|
+
* Auth0 domain (e.g., 'tenant.auth0.com') without protocol.
|
|
52
|
+
*
|
|
53
|
+
* Provide a `DomainResolver` function to resolve the Auth0 custom domain
|
|
54
|
+
* per request (Multiple Custom Domains). The resolver receives the Express
|
|
55
|
+
* request context (`{ request, response }`) and returns the domain string.
|
|
56
|
+
*/
|
|
57
|
+
domain: string | DomainResolver<StoreOptions>;
|
|
51
58
|
/** Auth0 application client ID */
|
|
52
59
|
clientId: string;
|
|
53
60
|
/** Auth0 application client secret (required for token exchange) */
|
|
@@ -58,8 +65,16 @@ interface Auth0Options {
|
|
|
58
65
|
clientAssertionSigningAlg?: string;
|
|
59
66
|
/** API audience for requesting access tokens */
|
|
60
67
|
audience?: string;
|
|
61
|
-
/**
|
|
62
|
-
|
|
68
|
+
/**
|
|
69
|
+
* Base URL of your application (e.g., 'http://localhost:3000').
|
|
70
|
+
*
|
|
71
|
+
* - Provide a single URL string for a static base URL (default behavior).
|
|
72
|
+
* - Provide an array of allowed URLs to validate the incoming request origin
|
|
73
|
+
* against an allow-list (recommended for dynamic/preview deployments).
|
|
74
|
+
* - Omit it (or set `APP_BASE_URL`/`BASE_URL` empty) to infer the base URL
|
|
75
|
+
* from the incoming request host at runtime.
|
|
76
|
+
*/
|
|
77
|
+
appBaseUrl?: string | string[];
|
|
63
78
|
/** Enable Pushed Authorization Requests (PAR) for enhanced security */
|
|
64
79
|
pushedAuthorizationRequests?: boolean;
|
|
65
80
|
/** Secret for encrypting session cookies (minimum 32 characters recommended) */
|
|
@@ -79,6 +94,13 @@ interface Auth0Options {
|
|
|
79
94
|
* Useful for proxies, custom headers, or testing.
|
|
80
95
|
*/
|
|
81
96
|
customFetch?: typeof fetch;
|
|
97
|
+
/**
|
|
98
|
+
* Optional discovery cache configuration for OIDC metadata and JWKS.
|
|
99
|
+
* `ttl` is in seconds. Cache entries are scoped per resolved domain, which
|
|
100
|
+
* matters for MCD deployments serving many domains. Defaults to the
|
|
101
|
+
* `ServerClient` defaults (TTL 600s, max 100 entries) when omitted.
|
|
102
|
+
*/
|
|
103
|
+
discoveryCache?: DiscoveryCacheOptions;
|
|
82
104
|
/** Custom paths for authentication routes (only used if mountRoutes is true) */
|
|
83
105
|
routes?: {
|
|
84
106
|
/** Login route path @default '/auth/login' */
|
|
@@ -134,9 +156,9 @@ declare global {
|
|
|
134
156
|
declare function createAuth0(opts?: Partial<Auth0Options>): Router;
|
|
135
157
|
|
|
136
158
|
/**
|
|
137
|
-
* Options for the
|
|
159
|
+
* Options for the requiresAuth middleware.
|
|
138
160
|
*/
|
|
139
|
-
interface
|
|
161
|
+
interface RequiresAuthOptions {
|
|
140
162
|
/**
|
|
141
163
|
* If true, returns a 401 status instead of redirecting to login.
|
|
142
164
|
* Useful for API routes that should not redirect.
|
|
@@ -158,28 +180,32 @@ interface RequireAuthOptions {
|
|
|
158
180
|
* @example
|
|
159
181
|
* ```typescript
|
|
160
182
|
* // Protect a route
|
|
161
|
-
* app.get('/profile',
|
|
183
|
+
* app.get('/profile', requiresAuth(), (req, res) => {
|
|
162
184
|
* res.json({ user: await req.auth0.client.getUser() });
|
|
163
185
|
* });
|
|
164
186
|
*
|
|
165
187
|
* // Protect an API route (returns 401 instead of redirecting)
|
|
166
|
-
* app.get('/api/me',
|
|
188
|
+
* app.get('/api/me', requiresAuth(), async (req, res) => {
|
|
167
189
|
* const user = await req.auth0.client.getUser();
|
|
168
190
|
* res.json({ user });
|
|
169
191
|
* });
|
|
170
192
|
*
|
|
171
193
|
* // Custom return URL after login
|
|
172
|
-
* app.get('/admin',
|
|
194
|
+
* app.get('/admin', requiresAuth({ returnTo: '/admin' }), (req, res) => {
|
|
173
195
|
* res.send('Admin page');
|
|
174
196
|
* });
|
|
175
197
|
* ```
|
|
176
198
|
*/
|
|
177
|
-
declare function
|
|
199
|
+
declare function requiresAuth(options?: RequiresAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<void | Response<any, Record<string, any>>>;
|
|
178
200
|
|
|
179
201
|
/**
|
|
180
202
|
* Type for a function that checks claims and returns true if authorized.
|
|
203
|
+
*
|
|
204
|
+
* @param req - The Express request, for authorization logic that depends on the
|
|
205
|
+
* request (e.g. route params, query, headers).
|
|
206
|
+
* @param claims - The authenticated user's claims.
|
|
181
207
|
*/
|
|
182
|
-
type ClaimCheckFunction = (claims: Record<string, unknown>) => boolean | Promise<boolean>;
|
|
208
|
+
type ClaimCheckFunction = (req: Request, claims: Record<string, unknown>) => boolean | Promise<boolean>;
|
|
183
209
|
/**
|
|
184
210
|
* Options for claim-based authorization middleware.
|
|
185
211
|
*/
|
|
@@ -200,13 +226,17 @@ interface ClaimAuthOptions {
|
|
|
200
226
|
type JSONPrimitive = string | number | boolean | null;
|
|
201
227
|
|
|
202
228
|
/**
|
|
203
|
-
* Middleware to check if
|
|
229
|
+
* Middleware to check if a claim includes specific values.
|
|
230
|
+
*
|
|
231
|
+
* The claim may be an array, or a space-delimited string (such as a
|
|
232
|
+
* scope-style `"read:users delete:users"` claim), which is split on spaces
|
|
233
|
+
* before checking.
|
|
204
234
|
*
|
|
205
235
|
* Returns 403 Forbidden if the claim doesn't include all required values
|
|
206
236
|
* or user is not authenticated.
|
|
207
237
|
*
|
|
208
|
-
* @param claim - The name of the
|
|
209
|
-
* @param values - The values that must be present in the claim
|
|
238
|
+
* @param claim - The name of the claim to check
|
|
239
|
+
* @param values - The values that must be present in the claim
|
|
210
240
|
* @param options - Optional configuration
|
|
211
241
|
* @returns Express middleware function
|
|
212
242
|
*
|
|
@@ -261,23 +291,23 @@ declare function claimEquals(claim: string, value: JSONPrimitive, options?: Clai
|
|
|
261
291
|
* Returns 403 Forbidden if the validation function returns false
|
|
262
292
|
* or user is not authenticated.
|
|
263
293
|
*
|
|
264
|
-
* @param checkFn - A function that receives the
|
|
294
|
+
* @param checkFn - A function that receives the Express request and the user
|
|
295
|
+
* claims and returns true if authorized
|
|
265
296
|
* @param options - Optional configuration
|
|
266
297
|
* @returns Express middleware function
|
|
267
298
|
*
|
|
268
299
|
* @example
|
|
269
300
|
* ```typescript
|
|
270
301
|
* // Custom claim validation
|
|
271
|
-
* app.get('/premium', claimCheck((claims) => {
|
|
302
|
+
* app.get('/premium', claimCheck((req, claims) => {
|
|
272
303
|
* return claims.subscription === 'premium' && !claims.subscription_expired;
|
|
273
304
|
* }), (req, res) => {
|
|
274
305
|
* res.send('Premium content');
|
|
275
306
|
* });
|
|
276
307
|
*
|
|
277
|
-
* // Complex authorization logic
|
|
278
|
-
* app.delete('/posts/:id', claimCheck(async (claims) => {
|
|
279
|
-
* const
|
|
280
|
-
* const post = await getPost(postId);
|
|
308
|
+
* // Complex authorization logic using the request
|
|
309
|
+
* app.delete('/posts/:id', claimCheck(async (req, claims) => {
|
|
310
|
+
* const post = await getPost(req.params.id);
|
|
281
311
|
* return claims.sub === post.authorId || claims.role === 'admin';
|
|
282
312
|
* }), (req, res) => {
|
|
283
313
|
* res.send('Post deleted');
|
|
@@ -285,7 +315,7 @@ declare function claimEquals(claim: string, value: JSONPrimitive, options?: Clai
|
|
|
285
315
|
*
|
|
286
316
|
* // With custom error message
|
|
287
317
|
* app.get('/beta', claimCheck(
|
|
288
|
-
* (claims) => claims.beta_access === true,
|
|
318
|
+
* (req, claims) => claims.beta_access === true,
|
|
289
319
|
* { errorMessage: 'Beta access required' }
|
|
290
320
|
* ), (req, res) => {
|
|
291
321
|
* res.send('Beta features');
|
|
@@ -294,4 +324,20 @@ declare function claimEquals(claim: string, value: JSONPrimitive, options?: Clai
|
|
|
294
324
|
*/
|
|
295
325
|
declare function claimCheck(checkFn: ClaimCheckFunction, options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
|
|
296
326
|
|
|
297
|
-
|
|
327
|
+
/**
|
|
328
|
+
* Checks if a string is a valid HTTP or HTTPS URL.
|
|
329
|
+
*/
|
|
330
|
+
declare function isUrl(value: string): boolean;
|
|
331
|
+
/**
|
|
332
|
+
* Resolves the application base URL for the current request.
|
|
333
|
+
*
|
|
334
|
+
* - `string`: used as-is (static configuration).
|
|
335
|
+
* - `undefined`: inferred from the request host (dynamic mode).
|
|
336
|
+
* - `string[]`: the request origin is matched against the allow-list; the
|
|
337
|
+
* matching origin is returned, otherwise an error is thrown.
|
|
338
|
+
*
|
|
339
|
+
* @throws {InvalidConfigurationError} When the base URL cannot be resolved.
|
|
340
|
+
*/
|
|
341
|
+
declare function resolveAppBaseUrl(appBaseUrl: string | string[] | undefined, req?: Request): string;
|
|
342
|
+
|
|
343
|
+
export { type Auth0Options, type ClaimAuthOptions, type ClaimCheckFunction, type RequiresAuthOptions, type StoreOptions, claimCheck, claimEquals, claimIncludes, createAuth0, isUrl, requiresAuth, resolveAppBaseUrl };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Request, Response, Router, NextFunction } from 'express';
|
|
2
|
-
import { SessionStore, SessionConfiguration, ServerClient } from '@auth0/auth0-server-js';
|
|
2
|
+
import { DomainResolver, SessionStore, SessionConfiguration, DiscoveryCacheOptions, ServerClient } from '@auth0/auth0-server-js';
|
|
3
|
+
export { DiscoveryCacheOptions, DomainResolver, InvalidConfigurationError } from '@auth0/auth0-server-js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Options passed to custom session store implementations.
|
|
@@ -46,8 +47,14 @@ interface StoreOptions {
|
|
|
46
47
|
* ```
|
|
47
48
|
*/
|
|
48
49
|
interface Auth0Options {
|
|
49
|
-
/**
|
|
50
|
-
|
|
50
|
+
/**
|
|
51
|
+
* Auth0 domain (e.g., 'tenant.auth0.com') without protocol.
|
|
52
|
+
*
|
|
53
|
+
* Provide a `DomainResolver` function to resolve the Auth0 custom domain
|
|
54
|
+
* per request (Multiple Custom Domains). The resolver receives the Express
|
|
55
|
+
* request context (`{ request, response }`) and returns the domain string.
|
|
56
|
+
*/
|
|
57
|
+
domain: string | DomainResolver<StoreOptions>;
|
|
51
58
|
/** Auth0 application client ID */
|
|
52
59
|
clientId: string;
|
|
53
60
|
/** Auth0 application client secret (required for token exchange) */
|
|
@@ -58,8 +65,16 @@ interface Auth0Options {
|
|
|
58
65
|
clientAssertionSigningAlg?: string;
|
|
59
66
|
/** API audience for requesting access tokens */
|
|
60
67
|
audience?: string;
|
|
61
|
-
/**
|
|
62
|
-
|
|
68
|
+
/**
|
|
69
|
+
* Base URL of your application (e.g., 'http://localhost:3000').
|
|
70
|
+
*
|
|
71
|
+
* - Provide a single URL string for a static base URL (default behavior).
|
|
72
|
+
* - Provide an array of allowed URLs to validate the incoming request origin
|
|
73
|
+
* against an allow-list (recommended for dynamic/preview deployments).
|
|
74
|
+
* - Omit it (or set `APP_BASE_URL`/`BASE_URL` empty) to infer the base URL
|
|
75
|
+
* from the incoming request host at runtime.
|
|
76
|
+
*/
|
|
77
|
+
appBaseUrl?: string | string[];
|
|
63
78
|
/** Enable Pushed Authorization Requests (PAR) for enhanced security */
|
|
64
79
|
pushedAuthorizationRequests?: boolean;
|
|
65
80
|
/** Secret for encrypting session cookies (minimum 32 characters recommended) */
|
|
@@ -79,6 +94,13 @@ interface Auth0Options {
|
|
|
79
94
|
* Useful for proxies, custom headers, or testing.
|
|
80
95
|
*/
|
|
81
96
|
customFetch?: typeof fetch;
|
|
97
|
+
/**
|
|
98
|
+
* Optional discovery cache configuration for OIDC metadata and JWKS.
|
|
99
|
+
* `ttl` is in seconds. Cache entries are scoped per resolved domain, which
|
|
100
|
+
* matters for MCD deployments serving many domains. Defaults to the
|
|
101
|
+
* `ServerClient` defaults (TTL 600s, max 100 entries) when omitted.
|
|
102
|
+
*/
|
|
103
|
+
discoveryCache?: DiscoveryCacheOptions;
|
|
82
104
|
/** Custom paths for authentication routes (only used if mountRoutes is true) */
|
|
83
105
|
routes?: {
|
|
84
106
|
/** Login route path @default '/auth/login' */
|
|
@@ -134,9 +156,9 @@ declare global {
|
|
|
134
156
|
declare function createAuth0(opts?: Partial<Auth0Options>): Router;
|
|
135
157
|
|
|
136
158
|
/**
|
|
137
|
-
* Options for the
|
|
159
|
+
* Options for the requiresAuth middleware.
|
|
138
160
|
*/
|
|
139
|
-
interface
|
|
161
|
+
interface RequiresAuthOptions {
|
|
140
162
|
/**
|
|
141
163
|
* If true, returns a 401 status instead of redirecting to login.
|
|
142
164
|
* Useful for API routes that should not redirect.
|
|
@@ -158,28 +180,32 @@ interface RequireAuthOptions {
|
|
|
158
180
|
* @example
|
|
159
181
|
* ```typescript
|
|
160
182
|
* // Protect a route
|
|
161
|
-
* app.get('/profile',
|
|
183
|
+
* app.get('/profile', requiresAuth(), (req, res) => {
|
|
162
184
|
* res.json({ user: await req.auth0.client.getUser() });
|
|
163
185
|
* });
|
|
164
186
|
*
|
|
165
187
|
* // Protect an API route (returns 401 instead of redirecting)
|
|
166
|
-
* app.get('/api/me',
|
|
188
|
+
* app.get('/api/me', requiresAuth(), async (req, res) => {
|
|
167
189
|
* const user = await req.auth0.client.getUser();
|
|
168
190
|
* res.json({ user });
|
|
169
191
|
* });
|
|
170
192
|
*
|
|
171
193
|
* // Custom return URL after login
|
|
172
|
-
* app.get('/admin',
|
|
194
|
+
* app.get('/admin', requiresAuth({ returnTo: '/admin' }), (req, res) => {
|
|
173
195
|
* res.send('Admin page');
|
|
174
196
|
* });
|
|
175
197
|
* ```
|
|
176
198
|
*/
|
|
177
|
-
declare function
|
|
199
|
+
declare function requiresAuth(options?: RequiresAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<void | Response<any, Record<string, any>>>;
|
|
178
200
|
|
|
179
201
|
/**
|
|
180
202
|
* Type for a function that checks claims and returns true if authorized.
|
|
203
|
+
*
|
|
204
|
+
* @param req - The Express request, for authorization logic that depends on the
|
|
205
|
+
* request (e.g. route params, query, headers).
|
|
206
|
+
* @param claims - The authenticated user's claims.
|
|
181
207
|
*/
|
|
182
|
-
type ClaimCheckFunction = (claims: Record<string, unknown>) => boolean | Promise<boolean>;
|
|
208
|
+
type ClaimCheckFunction = (req: Request, claims: Record<string, unknown>) => boolean | Promise<boolean>;
|
|
183
209
|
/**
|
|
184
210
|
* Options for claim-based authorization middleware.
|
|
185
211
|
*/
|
|
@@ -200,13 +226,17 @@ interface ClaimAuthOptions {
|
|
|
200
226
|
type JSONPrimitive = string | number | boolean | null;
|
|
201
227
|
|
|
202
228
|
/**
|
|
203
|
-
* Middleware to check if
|
|
229
|
+
* Middleware to check if a claim includes specific values.
|
|
230
|
+
*
|
|
231
|
+
* The claim may be an array, or a space-delimited string (such as a
|
|
232
|
+
* scope-style `"read:users delete:users"` claim), which is split on spaces
|
|
233
|
+
* before checking.
|
|
204
234
|
*
|
|
205
235
|
* Returns 403 Forbidden if the claim doesn't include all required values
|
|
206
236
|
* or user is not authenticated.
|
|
207
237
|
*
|
|
208
|
-
* @param claim - The name of the
|
|
209
|
-
* @param values - The values that must be present in the claim
|
|
238
|
+
* @param claim - The name of the claim to check
|
|
239
|
+
* @param values - The values that must be present in the claim
|
|
210
240
|
* @param options - Optional configuration
|
|
211
241
|
* @returns Express middleware function
|
|
212
242
|
*
|
|
@@ -261,23 +291,23 @@ declare function claimEquals(claim: string, value: JSONPrimitive, options?: Clai
|
|
|
261
291
|
* Returns 403 Forbidden if the validation function returns false
|
|
262
292
|
* or user is not authenticated.
|
|
263
293
|
*
|
|
264
|
-
* @param checkFn - A function that receives the
|
|
294
|
+
* @param checkFn - A function that receives the Express request and the user
|
|
295
|
+
* claims and returns true if authorized
|
|
265
296
|
* @param options - Optional configuration
|
|
266
297
|
* @returns Express middleware function
|
|
267
298
|
*
|
|
268
299
|
* @example
|
|
269
300
|
* ```typescript
|
|
270
301
|
* // Custom claim validation
|
|
271
|
-
* app.get('/premium', claimCheck((claims) => {
|
|
302
|
+
* app.get('/premium', claimCheck((req, claims) => {
|
|
272
303
|
* return claims.subscription === 'premium' && !claims.subscription_expired;
|
|
273
304
|
* }), (req, res) => {
|
|
274
305
|
* res.send('Premium content');
|
|
275
306
|
* });
|
|
276
307
|
*
|
|
277
|
-
* // Complex authorization logic
|
|
278
|
-
* app.delete('/posts/:id', claimCheck(async (claims) => {
|
|
279
|
-
* const
|
|
280
|
-
* const post = await getPost(postId);
|
|
308
|
+
* // Complex authorization logic using the request
|
|
309
|
+
* app.delete('/posts/:id', claimCheck(async (req, claims) => {
|
|
310
|
+
* const post = await getPost(req.params.id);
|
|
281
311
|
* return claims.sub === post.authorId || claims.role === 'admin';
|
|
282
312
|
* }), (req, res) => {
|
|
283
313
|
* res.send('Post deleted');
|
|
@@ -285,7 +315,7 @@ declare function claimEquals(claim: string, value: JSONPrimitive, options?: Clai
|
|
|
285
315
|
*
|
|
286
316
|
* // With custom error message
|
|
287
317
|
* app.get('/beta', claimCheck(
|
|
288
|
-
* (claims) => claims.beta_access === true,
|
|
318
|
+
* (req, claims) => claims.beta_access === true,
|
|
289
319
|
* { errorMessage: 'Beta access required' }
|
|
290
320
|
* ), (req, res) => {
|
|
291
321
|
* res.send('Beta features');
|
|
@@ -294,4 +324,20 @@ declare function claimEquals(claim: string, value: JSONPrimitive, options?: Clai
|
|
|
294
324
|
*/
|
|
295
325
|
declare function claimCheck(checkFn: ClaimCheckFunction, options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
|
|
296
326
|
|
|
297
|
-
|
|
327
|
+
/**
|
|
328
|
+
* Checks if a string is a valid HTTP or HTTPS URL.
|
|
329
|
+
*/
|
|
330
|
+
declare function isUrl(value: string): boolean;
|
|
331
|
+
/**
|
|
332
|
+
* Resolves the application base URL for the current request.
|
|
333
|
+
*
|
|
334
|
+
* - `string`: used as-is (static configuration).
|
|
335
|
+
* - `undefined`: inferred from the request host (dynamic mode).
|
|
336
|
+
* - `string[]`: the request origin is matched against the allow-list; the
|
|
337
|
+
* matching origin is returned, otherwise an error is thrown.
|
|
338
|
+
*
|
|
339
|
+
* @throws {InvalidConfigurationError} When the base URL cannot be resolved.
|
|
340
|
+
*/
|
|
341
|
+
declare function resolveAppBaseUrl(appBaseUrl: string | string[] | undefined, req?: Request): string;
|
|
342
|
+
|
|
343
|
+
export { type Auth0Options, type ClaimAuthOptions, type ClaimCheckFunction, type RequiresAuthOptions, type StoreOptions, claimCheck, claimEquals, claimIncludes, createAuth0, isUrl, requiresAuth, resolveAppBaseUrl };
|
package/dist/index.js
CHANGED
|
@@ -49,6 +49,12 @@ function ensureTrailingSlash(value) {
|
|
|
49
49
|
function ensureNoLeadingSlash(value) {
|
|
50
50
|
return value.replace(/^\/+/, "");
|
|
51
51
|
}
|
|
52
|
+
function wrapDomainResolver(domain) {
|
|
53
|
+
if (typeof domain === "string") {
|
|
54
|
+
return domain;
|
|
55
|
+
}
|
|
56
|
+
return (storeOptions) => domain(storeOptions ?? getRequestContext());
|
|
57
|
+
}
|
|
52
58
|
function createRouteUrl(url, base) {
|
|
53
59
|
const baseUrl = new URL(ensureTrailingSlash(base));
|
|
54
60
|
const normalized = ensureNoLeadingSlash(url);
|
|
@@ -75,16 +81,17 @@ function toSafeRedirect(dangerousRedirect, safeBaseUrl) {
|
|
|
75
81
|
}
|
|
76
82
|
function createServerClientInstance(options) {
|
|
77
83
|
const callbackPath = options.routes?.callback ?? "/auth/callback";
|
|
78
|
-
const
|
|
84
|
+
const staticAppBaseUrl = typeof options.appBaseUrl === "string" ? options.appBaseUrl : void 0;
|
|
85
|
+
const redirectUri = staticAppBaseUrl ? createRouteUrl(callbackPath, staticAppBaseUrl).toString() : void 0;
|
|
79
86
|
return new ServerClient({
|
|
80
|
-
domain: options.domain,
|
|
87
|
+
domain: wrapDomainResolver(options.domain),
|
|
81
88
|
clientId: options.clientId,
|
|
82
89
|
clientSecret: options.clientSecret,
|
|
83
90
|
clientAssertionSigningKey: options.clientAssertionSigningKey,
|
|
84
91
|
clientAssertionSigningAlg: options.clientAssertionSigningAlg,
|
|
85
92
|
authorizationParams: {
|
|
86
93
|
audience: options.audience,
|
|
87
|
-
redirect_uri: redirectUri
|
|
94
|
+
redirect_uri: redirectUri
|
|
88
95
|
},
|
|
89
96
|
transactionStore: new CookieTransactionStore({ secret: options.sessionSecret }, new ExpressCookieHandler()),
|
|
90
97
|
stateStore: options.sessionStore ? new StatefulStateStore(
|
|
@@ -102,8 +109,84 @@ function createServerClientInstance(options) {
|
|
|
102
109
|
new ExpressCookieHandler()
|
|
103
110
|
),
|
|
104
111
|
stateIdentifier: options.sessionConfiguration?.cookie?.name,
|
|
105
|
-
customFetch: options.customFetch
|
|
112
|
+
customFetch: options.customFetch,
|
|
113
|
+
discoveryCache: options.discoveryCache
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// src/errors/index.ts
|
|
118
|
+
import { InvalidConfigurationError } from "@auth0/auth0-server-js";
|
|
119
|
+
|
|
120
|
+
// src/app-base-url.ts
|
|
121
|
+
var HTTP_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
|
|
122
|
+
function isUrl(value) {
|
|
123
|
+
try {
|
|
124
|
+
const parsed = new URL(value);
|
|
125
|
+
return HTTP_PROTOCOLS.has(parsed.protocol);
|
|
126
|
+
} catch {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function getFirstHeaderValue(value) {
|
|
131
|
+
if (!value) {
|
|
132
|
+
return void 0;
|
|
133
|
+
}
|
|
134
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
135
|
+
if (!raw) {
|
|
136
|
+
return void 0;
|
|
137
|
+
}
|
|
138
|
+
const [first] = raw.split(",");
|
|
139
|
+
return first?.trim() || void 0;
|
|
140
|
+
}
|
|
141
|
+
function isProxyTrusted(req) {
|
|
142
|
+
const trust = req.app?.get("trust proxy fn");
|
|
143
|
+
return typeof trust === "function" && trust(req.socket?.remoteAddress, 0);
|
|
144
|
+
}
|
|
145
|
+
function inferBaseUrlFromRequest(req) {
|
|
146
|
+
const trusted = isProxyTrusted(req);
|
|
147
|
+
const forwardedHost = trusted ? getFirstHeaderValue(req.headers["x-forwarded-host"]) : void 0;
|
|
148
|
+
const host = forwardedHost || getFirstHeaderValue(req.headers["host"]);
|
|
149
|
+
const proto = req.protocol;
|
|
150
|
+
if (!host || !proto) {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
const candidate = `${proto}://${host}`;
|
|
154
|
+
return isUrl(candidate) ? candidate : null;
|
|
155
|
+
}
|
|
156
|
+
function resolveAppBaseUrl(appBaseUrl, req) {
|
|
157
|
+
const staticAppBaseUrl = typeof appBaseUrl === "string" ? appBaseUrl : void 0;
|
|
158
|
+
const allowedAppBaseUrls = typeof appBaseUrl === "string" ? void 0 : appBaseUrl;
|
|
159
|
+
if (staticAppBaseUrl) {
|
|
160
|
+
return staticAppBaseUrl;
|
|
161
|
+
}
|
|
162
|
+
if (!req) {
|
|
163
|
+
throw new InvalidConfigurationError(
|
|
164
|
+
"APP_BASE_URL is not configured as a static string, and a request context is not available."
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
const inferred = inferBaseUrlFromRequest(req);
|
|
168
|
+
if (!inferred) {
|
|
169
|
+
throw new InvalidConfigurationError(
|
|
170
|
+
"APP_BASE_URL is not configured as a static string, and the request origin could not be determined from the request context."
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
if (!allowedAppBaseUrls) {
|
|
174
|
+
return inferred;
|
|
175
|
+
}
|
|
176
|
+
const requestOrigin = new URL(inferred).origin;
|
|
177
|
+
const matchedEntry = allowedAppBaseUrls.find((allowedUrl) => {
|
|
178
|
+
try {
|
|
179
|
+
return new URL(allowedUrl).origin === requestOrigin;
|
|
180
|
+
} catch {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
106
183
|
});
|
|
184
|
+
if (matchedEntry !== void 0) {
|
|
185
|
+
return matchedEntry;
|
|
186
|
+
}
|
|
187
|
+
throw new InvalidConfigurationError(
|
|
188
|
+
"APP_BASE_URL is not configured as a static string, and the APP_BASE_URL configuration does not contain a match for the current request origin."
|
|
189
|
+
);
|
|
107
190
|
}
|
|
108
191
|
|
|
109
192
|
// src/handlers/login-handler.ts
|
|
@@ -135,13 +218,19 @@ function filterAuthorizationParams(params, disallowed) {
|
|
|
135
218
|
}
|
|
136
219
|
async function handleLogin(req, res, options) {
|
|
137
220
|
try {
|
|
221
|
+
const appBaseUrl = resolveAppBaseUrl(options.appBaseUrl, req);
|
|
222
|
+
const callbackPath = options.routes?.callback ?? "/auth/callback";
|
|
223
|
+
const redirectUri = createRouteUrl(callbackPath, appBaseUrl);
|
|
138
224
|
const query = req.query;
|
|
139
225
|
const dangerousReturnTo = query.returnTo;
|
|
140
|
-
const sanitizedReturnTo = toSafeRedirect(dangerousReturnTo || "/",
|
|
226
|
+
const sanitizedReturnTo = toSafeRedirect(dangerousReturnTo || "/", appBaseUrl);
|
|
141
227
|
const authorizationUrl = await req.auth0.client.startInteractiveLogin({
|
|
142
228
|
pushedAuthorizationRequests: options.pushedAuthorizationRequests,
|
|
143
229
|
appState: { returnTo: sanitizedReturnTo },
|
|
144
|
-
authorizationParams:
|
|
230
|
+
authorizationParams: {
|
|
231
|
+
...filterAuthorizationParams(query, ["returnTo"]),
|
|
232
|
+
redirect_uri: redirectUri.toString()
|
|
233
|
+
}
|
|
145
234
|
});
|
|
146
235
|
res.redirect(authorizationUrl.href);
|
|
147
236
|
} catch (error) {
|
|
@@ -155,10 +244,11 @@ async function handleLogin(req, res, options) {
|
|
|
155
244
|
// src/handlers/callback-handler.ts
|
|
156
245
|
async function handleCallback(req, res, options) {
|
|
157
246
|
try {
|
|
247
|
+
const appBaseUrl = resolveAppBaseUrl(options.appBaseUrl, req);
|
|
158
248
|
const { appState } = await req.auth0.client.completeInteractiveLogin(
|
|
159
|
-
createRouteUrl(req.url,
|
|
249
|
+
createRouteUrl(req.url, appBaseUrl)
|
|
160
250
|
);
|
|
161
|
-
res.redirect(appState?.returnTo ??
|
|
251
|
+
res.redirect(appState?.returnTo ?? appBaseUrl);
|
|
162
252
|
} catch (e) {
|
|
163
253
|
const error = e;
|
|
164
254
|
res.status(500).json({
|
|
@@ -171,8 +261,8 @@ async function handleCallback(req, res, options) {
|
|
|
171
261
|
// src/handlers/logout-handler.ts
|
|
172
262
|
async function handleLogout(req, res, options) {
|
|
173
263
|
try {
|
|
174
|
-
const returnTo = options.appBaseUrl;
|
|
175
|
-
const logoutUrl = await req.auth0.client.logout({ returnTo
|
|
264
|
+
const returnTo = resolveAppBaseUrl(options.appBaseUrl, req);
|
|
265
|
+
const logoutUrl = await req.auth0.client.logout({ returnTo });
|
|
176
266
|
res.redirect(logoutUrl.href);
|
|
177
267
|
} catch (error) {
|
|
178
268
|
res.status(500).json({
|
|
@@ -202,28 +292,80 @@ import { MissingRequiredArgumentError } from "@auth0/auth0-server-js";
|
|
|
202
292
|
function stripProtocol(url) {
|
|
203
293
|
return url ? url.replace(/^https?:\/\//, "") : url;
|
|
204
294
|
}
|
|
295
|
+
function parseAppBaseUrlEnv(value) {
|
|
296
|
+
if (!value) {
|
|
297
|
+
return void 0;
|
|
298
|
+
}
|
|
299
|
+
if (value.includes(",")) {
|
|
300
|
+
const entries = value.split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
301
|
+
return entries.length === 1 ? entries[0] : entries;
|
|
302
|
+
}
|
|
303
|
+
return value;
|
|
304
|
+
}
|
|
305
|
+
function validateAppBaseUrl(appBaseUrl) {
|
|
306
|
+
if (appBaseUrl === void 0) {
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
if (Array.isArray(appBaseUrl)) {
|
|
310
|
+
if (appBaseUrl.length === 0) {
|
|
311
|
+
throw new InvalidConfigurationError("APP_BASE_URL array configuration cannot be empty.");
|
|
312
|
+
}
|
|
313
|
+
const invalid = appBaseUrl.filter((url) => !isUrl(url));
|
|
314
|
+
if (invalid.length > 0) {
|
|
315
|
+
throw new InvalidConfigurationError(
|
|
316
|
+
`APP_BASE_URL array contains invalid URLs: ${invalid.join(", ")}`
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
if (!isUrl(appBaseUrl)) {
|
|
322
|
+
throw new InvalidConfigurationError(`APP_BASE_URL must be a valid http(s) URL: ${appBaseUrl}`);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
function enforceSecureCookies(config) {
|
|
326
|
+
const isProduction = process.env.NODE_ENV === "production";
|
|
327
|
+
const isDynamic = typeof config.appBaseUrl !== "string";
|
|
328
|
+
if (!isProduction || !isDynamic) {
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
const explicitSecure = config.sessionConfiguration?.cookie?.secure;
|
|
332
|
+
if (explicitSecure === false) {
|
|
333
|
+
throw new InvalidConfigurationError(
|
|
334
|
+
"Secure cookies are required when relying on dynamic base URLs in production. Remove the explicit `sessionConfiguration.cookie.secure = false` or set a static APP_BASE_URL."
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
config.sessionConfiguration = {
|
|
338
|
+
...config.sessionConfiguration,
|
|
339
|
+
cookie: {
|
|
340
|
+
...config.sessionConfiguration?.cookie,
|
|
341
|
+
secure: true
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
}
|
|
205
345
|
function getConfig(config = {}) {
|
|
206
346
|
const mergedConfig = {
|
|
207
347
|
domain: process.env.AUTH0_DOMAIN || stripProtocol(process.env.ISSUER_BASE_URL),
|
|
208
348
|
clientId: process.env.AUTH0_CLIENT_ID || process.env.CLIENT_ID,
|
|
209
349
|
clientSecret: process.env.AUTH0_CLIENT_SECRET || process.env.CLIENT_SECRET,
|
|
210
|
-
appBaseUrl: process.env.APP_BASE_URL || process.env.BASE_URL,
|
|
350
|
+
appBaseUrl: parseAppBaseUrlEnv(process.env.APP_BASE_URL || process.env.BASE_URL),
|
|
211
351
|
sessionSecret: process.env.AUTH0_SESSION_SECRET || process.env.SECRET,
|
|
212
352
|
audience: process.env.AUTH0_AUDIENCE,
|
|
213
353
|
...config
|
|
214
354
|
};
|
|
355
|
+
if (typeof mergedConfig.appBaseUrl === "string") {
|
|
356
|
+
mergedConfig.appBaseUrl = parseAppBaseUrlEnv(mergedConfig.appBaseUrl);
|
|
357
|
+
}
|
|
215
358
|
if (!mergedConfig.domain) {
|
|
216
359
|
throw new MissingRequiredArgumentError("domain");
|
|
217
360
|
}
|
|
218
361
|
if (!mergedConfig.clientId) {
|
|
219
362
|
throw new MissingRequiredArgumentError("clientId");
|
|
220
363
|
}
|
|
221
|
-
|
|
222
|
-
throw new MissingRequiredArgumentError("appBaseUrl");
|
|
223
|
-
}
|
|
364
|
+
validateAppBaseUrl(mergedConfig.appBaseUrl);
|
|
224
365
|
if (!mergedConfig.sessionSecret) {
|
|
225
366
|
throw new MissingRequiredArgumentError("sessionSecret");
|
|
226
367
|
}
|
|
368
|
+
enforceSecureCookies(mergedConfig);
|
|
227
369
|
return mergedConfig;
|
|
228
370
|
}
|
|
229
371
|
|
|
@@ -261,7 +403,7 @@ function createAuth0(opts = {}) {
|
|
|
261
403
|
}
|
|
262
404
|
|
|
263
405
|
// src/middleware/require-auth.ts
|
|
264
|
-
function
|
|
406
|
+
function requiresAuth(options) {
|
|
265
407
|
return async (req, res, next) => {
|
|
266
408
|
try {
|
|
267
409
|
const user = await req.auth0.client.getUser();
|
|
@@ -296,7 +438,8 @@ function claimIncludes(claim, values, options) {
|
|
|
296
438
|
message: "Authentication required"
|
|
297
439
|
});
|
|
298
440
|
}
|
|
299
|
-
const
|
|
441
|
+
const rawClaim = user[claim];
|
|
442
|
+
const claimValue = typeof rawClaim === "string" ? rawClaim.split(" ") : rawClaim;
|
|
300
443
|
if (!Array.isArray(claimValue)) {
|
|
301
444
|
return res.status(options?.statusCode || 403).json({
|
|
302
445
|
error: "forbidden",
|
|
@@ -353,7 +496,7 @@ function claimCheck(checkFn, options) {
|
|
|
353
496
|
message: "Authentication required"
|
|
354
497
|
});
|
|
355
498
|
}
|
|
356
|
-
const isAuthorized = await checkFn(user);
|
|
499
|
+
const isAuthorized = await checkFn(req, user);
|
|
357
500
|
if (!isAuthorized) {
|
|
358
501
|
return res.status(options?.statusCode || 403).json({
|
|
359
502
|
error: "forbidden",
|
|
@@ -367,10 +510,13 @@ function claimCheck(checkFn, options) {
|
|
|
367
510
|
};
|
|
368
511
|
}
|
|
369
512
|
export {
|
|
513
|
+
InvalidConfigurationError,
|
|
370
514
|
claimCheck,
|
|
371
515
|
claimEquals,
|
|
372
516
|
claimIncludes,
|
|
373
517
|
createAuth0,
|
|
374
|
-
|
|
518
|
+
isUrl,
|
|
519
|
+
requiresAuth,
|
|
520
|
+
resolveAppBaseUrl
|
|
375
521
|
};
|
|
376
522
|
//# sourceMappingURL=index.js.map
|