@auth0/auth0-express 1.0.0-beta.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.
@@ -0,0 +1,297 @@
1
+ import { Request, Response, Router, NextFunction } from 'express';
2
+ import { SessionStore, SessionConfiguration, ServerClient } from '@auth0/auth0-server-js';
3
+
4
+ /**
5
+ * Options passed to custom session store implementations.
6
+ *
7
+ * These options provide access to the Express request and response objects,
8
+ * which are needed for cookie and session management operations.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * class CustomSessionStore implements SessionStore<StoreOptions> {
13
+ * async get(id: string, options: StoreOptions) {
14
+ * const { request, response } = options;
15
+ * // Access cookies, headers, etc.
16
+ * }
17
+ * }
18
+ * ```
19
+ */
20
+ interface StoreOptions {
21
+ /** Express request object */
22
+ request: Request;
23
+ /** Express response object */
24
+ response: Response;
25
+ }
26
+ /**
27
+ * Configuration options for Auth0 authentication in Express applications.
28
+ *
29
+ * Environment variable support:
30
+ * - AUTH0_DOMAIN or ISSUER_BASE_URL: Auth0 domain
31
+ * - AUTH0_CLIENT_ID or CLIENT_ID: Client ID
32
+ * - AUTH0_CLIENT_SECRET or CLIENT_SECRET: Client secret
33
+ * - APP_BASE_URL or BASE_URL: Application base URL
34
+ * - AUTH0_SESSION_SECRET or SECRET: Session encryption secret
35
+ * - AUTH0_AUDIENCE: Optional API audience
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const options: Auth0Options = {
40
+ * domain: 'tenant.auth0.com',
41
+ * clientId: 'your_client_id',
42
+ * clientSecret: 'your_client_secret',
43
+ * appBaseUrl: 'http://localhost:3000',
44
+ * sessionSecret: process.env.SESSION_SECRET
45
+ * };
46
+ * ```
47
+ */
48
+ interface Auth0Options {
49
+ /** Auth0 domain (e.g., 'tenant.auth0.com') without protocol */
50
+ domain: string;
51
+ /** Auth0 application client ID */
52
+ clientId: string;
53
+ /** Auth0 application client secret (required for token exchange) */
54
+ clientSecret?: string;
55
+ /** Private key for client assertion authentication (alternative to clientSecret) */
56
+ clientAssertionSigningKey?: string | CryptoKey;
57
+ /** Algorithm for client assertion signing (e.g., 'RS256') */
58
+ clientAssertionSigningAlg?: string;
59
+ /** API audience for requesting access tokens */
60
+ audience?: string;
61
+ /** Base URL of your application (e.g., 'http://localhost:3000') */
62
+ appBaseUrl: string;
63
+ /** Enable Pushed Authorization Requests (PAR) for enhanced security */
64
+ pushedAuthorizationRequests?: boolean;
65
+ /** Secret for encrypting session cookies (minimum 32 characters recommended) */
66
+ sessionSecret: string;
67
+ /** Custom session store implementation (defaults to cookie-based sessions) */
68
+ sessionStore?: SessionStore<StoreOptions>;
69
+ /** Advanced session configuration (cookie settings, timeouts, etc.) */
70
+ sessionConfiguration?: SessionConfiguration;
71
+ /**
72
+ * Whether to mount the default routes for login, logout, callback and backchannel logout.
73
+ * Routes: /auth/login, /auth/callback, /auth/logout, /auth/backchannel-logout
74
+ * @default true
75
+ */
76
+ mountRoutes?: boolean;
77
+ /**
78
+ * Custom fetch implementation for HTTP requests.
79
+ * Useful for proxies, custom headers, or testing.
80
+ */
81
+ customFetch?: typeof fetch;
82
+ /** Custom paths for authentication routes (only used if mountRoutes is true) */
83
+ routes?: {
84
+ /** Login route path @default '/auth/login' */
85
+ login?: string;
86
+ /** OAuth callback route path @default '/auth/callback' */
87
+ callback?: string;
88
+ /** Logout route path @default '/auth/logout' */
89
+ logout?: string;
90
+ /** Backchannel logout route path @default '/auth/backchannel-logout' */
91
+ backchannelLogout?: string;
92
+ };
93
+ }
94
+
95
+ declare global {
96
+ namespace Express {
97
+ interface Request {
98
+ auth0: {
99
+ client: ServerClient<StoreOptions>;
100
+ };
101
+ }
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Creates an Express router with Auth0 authentication middleware.
107
+ *
108
+ * This is the main entry point for the Auth0 Express SDK. It configures
109
+ * authentication routes and attaches the Auth0 client to the request object.
110
+ *
111
+ * @param opts - Configuration options for Auth0 authentication
112
+ * @returns Express Router configured with Auth0 authentication
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * import express from 'express';
117
+ * import { createAuth0 } from '@auth0/auth0-express';
118
+ *
119
+ * const app = express();
120
+ *
121
+ * // Using environment variables (AUTH0_DOMAIN, AUTH0_CLIENT_ID, etc.)
122
+ * app.use(createAuth0());
123
+ *
124
+ * // Or with explicit configuration
125
+ * app.use(createAuth0({
126
+ * domain: 'tenant.auth0.com',
127
+ * clientId: 'your_client_id',
128
+ * clientSecret: 'your_client_secret',
129
+ * appBaseUrl: 'http://localhost:3000',
130
+ * sessionSecret: process.env.SESSION_SECRET
131
+ * }));
132
+ * ```
133
+ */
134
+ declare function createAuth0(opts?: Partial<Auth0Options>): Router;
135
+
136
+ /**
137
+ * Options for the requireAuth middleware.
138
+ */
139
+ interface RequireAuthOptions {
140
+ /**
141
+ * If true, returns a 401 status instead of redirecting to login.
142
+ * Useful for API routes that should not redirect.
143
+ *
144
+ * Default: false (redirects to login)
145
+ */
146
+ returnTo?: string;
147
+ }
148
+ /**
149
+ * Middleware to require authentication for a route.
150
+ *
151
+ * If the user is not authenticated:
152
+ * - For HTML requests (browser): Redirects to /auth/login with returnTo parameter
153
+ * - For API requests (JSON): Returns 401 Unauthorized
154
+ *
155
+ * @param options - Optional configuration for the middleware
156
+ * @returns Express middleware function
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * // Protect a route
161
+ * app.get('/profile', requireAuth(), (req, res) => {
162
+ * res.json({ user: await req.auth0.client.getUser() });
163
+ * });
164
+ *
165
+ * // Protect an API route (returns 401 instead of redirecting)
166
+ * app.get('/api/me', requireAuth(), async (req, res) => {
167
+ * const user = await req.auth0.client.getUser();
168
+ * res.json({ user });
169
+ * });
170
+ *
171
+ * // Custom return URL after login
172
+ * app.get('/admin', requireAuth({ returnTo: '/admin' }), (req, res) => {
173
+ * res.send('Admin page');
174
+ * });
175
+ * ```
176
+ */
177
+ declare function requireAuth(options?: RequireAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<void | Response<any, Record<string, any>>>;
178
+
179
+ /**
180
+ * Type for a function that checks claims and returns true if authorized.
181
+ */
182
+ type ClaimCheckFunction = (claims: Record<string, unknown>) => boolean | Promise<boolean>;
183
+ /**
184
+ * Options for claim-based authorization middleware.
185
+ */
186
+ interface ClaimAuthOptions {
187
+ /**
188
+ * Custom error message to send when authorization fails.
189
+ */
190
+ errorMessage?: string;
191
+ /**
192
+ * Custom status code to return when authorization fails.
193
+ * Default: 403 (Forbidden)
194
+ */
195
+ statusCode?: number;
196
+ }
197
+ /**
198
+ * Primitive JSON types that can be compared.
199
+ */
200
+ type JSONPrimitive = string | number | boolean | null;
201
+
202
+ /**
203
+ * Middleware to check if an array claim includes specific values.
204
+ *
205
+ * Returns 403 Forbidden if the claim doesn't include all required values
206
+ * or user is not authenticated.
207
+ *
208
+ * @param claim - The name of the array claim to check
209
+ * @param values - The values that must be present in the claim array
210
+ * @param options - Optional configuration
211
+ * @returns Express middleware function
212
+ *
213
+ * @example
214
+ * ```typescript
215
+ * // Require user to have specific permissions
216
+ * app.delete('/users/:id', claimIncludes('permissions', ['delete:users']), (req, res) => {
217
+ * res.send('User deleted');
218
+ * });
219
+ *
220
+ * // Require multiple permissions
221
+ * app.post('/admin/users', claimIncludes('permissions', ['create:users', 'admin:access']), (req, res) => {
222
+ * res.send('User created');
223
+ * });
224
+ *
225
+ * // Check roles
226
+ * app.get('/dashboard', claimIncludes('roles', ['editor', 'admin']), (req, res) => {
227
+ * res.send('Dashboard');
228
+ * });
229
+ * ```
230
+ */
231
+ declare function claimIncludes(claim: string, values: unknown[], options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
232
+
233
+ /**
234
+ * Middleware to check if a claim equals a specific value.
235
+ *
236
+ * Returns 403 Forbidden if the claim doesn't match or user is not authenticated.
237
+ *
238
+ * @param claim - The name of the claim to check
239
+ * @param value - The expected value of the claim
240
+ * @param options - Optional configuration
241
+ * @returns Express middleware function
242
+ *
243
+ * @example
244
+ * ```typescript
245
+ * // Require user to be an admin
246
+ * app.get('/admin', claimEquals('role', 'admin'), (req, res) => {
247
+ * res.send('Admin dashboard');
248
+ * });
249
+ *
250
+ * // Check organization membership
251
+ * app.get('/org', claimEquals('org_id', 'org_123'), (req, res) => {
252
+ * res.send('Organization page');
253
+ * });
254
+ * ```
255
+ */
256
+ declare function claimEquals(claim: string, value: JSONPrimitive, options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
257
+
258
+ /**
259
+ * Middleware to check claims using a custom validation function.
260
+ *
261
+ * Returns 403 Forbidden if the validation function returns false
262
+ * or user is not authenticated.
263
+ *
264
+ * @param checkFn - A function that receives the user claims and returns true if authorized
265
+ * @param options - Optional configuration
266
+ * @returns Express middleware function
267
+ *
268
+ * @example
269
+ * ```typescript
270
+ * // Custom claim validation
271
+ * app.get('/premium', claimCheck((claims) => {
272
+ * return claims.subscription === 'premium' && !claims.subscription_expired;
273
+ * }), (req, res) => {
274
+ * res.send('Premium content');
275
+ * });
276
+ *
277
+ * // Complex authorization logic
278
+ * app.delete('/posts/:id', claimCheck(async (claims) => {
279
+ * const postId = req.params.id;
280
+ * const post = await getPost(postId);
281
+ * return claims.sub === post.authorId || claims.role === 'admin';
282
+ * }), (req, res) => {
283
+ * res.send('Post deleted');
284
+ * });
285
+ *
286
+ * // With custom error message
287
+ * app.get('/beta', claimCheck(
288
+ * (claims) => claims.beta_access === true,
289
+ * { errorMessage: 'Beta access required' }
290
+ * ), (req, res) => {
291
+ * res.send('Beta features');
292
+ * });
293
+ * ```
294
+ */
295
+ declare function claimCheck(checkFn: ClaimCheckFunction, options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
296
+
297
+ export { type Auth0Options, type ClaimAuthOptions, type ClaimCheckFunction, type RequireAuthOptions, type StoreOptions, claimCheck, claimEquals, claimIncludes, createAuth0, requireAuth };
@@ -0,0 +1,297 @@
1
+ import { Request, Response, Router, NextFunction } from 'express';
2
+ import { SessionStore, SessionConfiguration, ServerClient } from '@auth0/auth0-server-js';
3
+
4
+ /**
5
+ * Options passed to custom session store implementations.
6
+ *
7
+ * These options provide access to the Express request and response objects,
8
+ * which are needed for cookie and session management operations.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * class CustomSessionStore implements SessionStore<StoreOptions> {
13
+ * async get(id: string, options: StoreOptions) {
14
+ * const { request, response } = options;
15
+ * // Access cookies, headers, etc.
16
+ * }
17
+ * }
18
+ * ```
19
+ */
20
+ interface StoreOptions {
21
+ /** Express request object */
22
+ request: Request;
23
+ /** Express response object */
24
+ response: Response;
25
+ }
26
+ /**
27
+ * Configuration options for Auth0 authentication in Express applications.
28
+ *
29
+ * Environment variable support:
30
+ * - AUTH0_DOMAIN or ISSUER_BASE_URL: Auth0 domain
31
+ * - AUTH0_CLIENT_ID or CLIENT_ID: Client ID
32
+ * - AUTH0_CLIENT_SECRET or CLIENT_SECRET: Client secret
33
+ * - APP_BASE_URL or BASE_URL: Application base URL
34
+ * - AUTH0_SESSION_SECRET or SECRET: Session encryption secret
35
+ * - AUTH0_AUDIENCE: Optional API audience
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const options: Auth0Options = {
40
+ * domain: 'tenant.auth0.com',
41
+ * clientId: 'your_client_id',
42
+ * clientSecret: 'your_client_secret',
43
+ * appBaseUrl: 'http://localhost:3000',
44
+ * sessionSecret: process.env.SESSION_SECRET
45
+ * };
46
+ * ```
47
+ */
48
+ interface Auth0Options {
49
+ /** Auth0 domain (e.g., 'tenant.auth0.com') without protocol */
50
+ domain: string;
51
+ /** Auth0 application client ID */
52
+ clientId: string;
53
+ /** Auth0 application client secret (required for token exchange) */
54
+ clientSecret?: string;
55
+ /** Private key for client assertion authentication (alternative to clientSecret) */
56
+ clientAssertionSigningKey?: string | CryptoKey;
57
+ /** Algorithm for client assertion signing (e.g., 'RS256') */
58
+ clientAssertionSigningAlg?: string;
59
+ /** API audience for requesting access tokens */
60
+ audience?: string;
61
+ /** Base URL of your application (e.g., 'http://localhost:3000') */
62
+ appBaseUrl: string;
63
+ /** Enable Pushed Authorization Requests (PAR) for enhanced security */
64
+ pushedAuthorizationRequests?: boolean;
65
+ /** Secret for encrypting session cookies (minimum 32 characters recommended) */
66
+ sessionSecret: string;
67
+ /** Custom session store implementation (defaults to cookie-based sessions) */
68
+ sessionStore?: SessionStore<StoreOptions>;
69
+ /** Advanced session configuration (cookie settings, timeouts, etc.) */
70
+ sessionConfiguration?: SessionConfiguration;
71
+ /**
72
+ * Whether to mount the default routes for login, logout, callback and backchannel logout.
73
+ * Routes: /auth/login, /auth/callback, /auth/logout, /auth/backchannel-logout
74
+ * @default true
75
+ */
76
+ mountRoutes?: boolean;
77
+ /**
78
+ * Custom fetch implementation for HTTP requests.
79
+ * Useful for proxies, custom headers, or testing.
80
+ */
81
+ customFetch?: typeof fetch;
82
+ /** Custom paths for authentication routes (only used if mountRoutes is true) */
83
+ routes?: {
84
+ /** Login route path @default '/auth/login' */
85
+ login?: string;
86
+ /** OAuth callback route path @default '/auth/callback' */
87
+ callback?: string;
88
+ /** Logout route path @default '/auth/logout' */
89
+ logout?: string;
90
+ /** Backchannel logout route path @default '/auth/backchannel-logout' */
91
+ backchannelLogout?: string;
92
+ };
93
+ }
94
+
95
+ declare global {
96
+ namespace Express {
97
+ interface Request {
98
+ auth0: {
99
+ client: ServerClient<StoreOptions>;
100
+ };
101
+ }
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Creates an Express router with Auth0 authentication middleware.
107
+ *
108
+ * This is the main entry point for the Auth0 Express SDK. It configures
109
+ * authentication routes and attaches the Auth0 client to the request object.
110
+ *
111
+ * @param opts - Configuration options for Auth0 authentication
112
+ * @returns Express Router configured with Auth0 authentication
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * import express from 'express';
117
+ * import { createAuth0 } from '@auth0/auth0-express';
118
+ *
119
+ * const app = express();
120
+ *
121
+ * // Using environment variables (AUTH0_DOMAIN, AUTH0_CLIENT_ID, etc.)
122
+ * app.use(createAuth0());
123
+ *
124
+ * // Or with explicit configuration
125
+ * app.use(createAuth0({
126
+ * domain: 'tenant.auth0.com',
127
+ * clientId: 'your_client_id',
128
+ * clientSecret: 'your_client_secret',
129
+ * appBaseUrl: 'http://localhost:3000',
130
+ * sessionSecret: process.env.SESSION_SECRET
131
+ * }));
132
+ * ```
133
+ */
134
+ declare function createAuth0(opts?: Partial<Auth0Options>): Router;
135
+
136
+ /**
137
+ * Options for the requireAuth middleware.
138
+ */
139
+ interface RequireAuthOptions {
140
+ /**
141
+ * If true, returns a 401 status instead of redirecting to login.
142
+ * Useful for API routes that should not redirect.
143
+ *
144
+ * Default: false (redirects to login)
145
+ */
146
+ returnTo?: string;
147
+ }
148
+ /**
149
+ * Middleware to require authentication for a route.
150
+ *
151
+ * If the user is not authenticated:
152
+ * - For HTML requests (browser): Redirects to /auth/login with returnTo parameter
153
+ * - For API requests (JSON): Returns 401 Unauthorized
154
+ *
155
+ * @param options - Optional configuration for the middleware
156
+ * @returns Express middleware function
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * // Protect a route
161
+ * app.get('/profile', requireAuth(), (req, res) => {
162
+ * res.json({ user: await req.auth0.client.getUser() });
163
+ * });
164
+ *
165
+ * // Protect an API route (returns 401 instead of redirecting)
166
+ * app.get('/api/me', requireAuth(), async (req, res) => {
167
+ * const user = await req.auth0.client.getUser();
168
+ * res.json({ user });
169
+ * });
170
+ *
171
+ * // Custom return URL after login
172
+ * app.get('/admin', requireAuth({ returnTo: '/admin' }), (req, res) => {
173
+ * res.send('Admin page');
174
+ * });
175
+ * ```
176
+ */
177
+ declare function requireAuth(options?: RequireAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<void | Response<any, Record<string, any>>>;
178
+
179
+ /**
180
+ * Type for a function that checks claims and returns true if authorized.
181
+ */
182
+ type ClaimCheckFunction = (claims: Record<string, unknown>) => boolean | Promise<boolean>;
183
+ /**
184
+ * Options for claim-based authorization middleware.
185
+ */
186
+ interface ClaimAuthOptions {
187
+ /**
188
+ * Custom error message to send when authorization fails.
189
+ */
190
+ errorMessage?: string;
191
+ /**
192
+ * Custom status code to return when authorization fails.
193
+ * Default: 403 (Forbidden)
194
+ */
195
+ statusCode?: number;
196
+ }
197
+ /**
198
+ * Primitive JSON types that can be compared.
199
+ */
200
+ type JSONPrimitive = string | number | boolean | null;
201
+
202
+ /**
203
+ * Middleware to check if an array claim includes specific values.
204
+ *
205
+ * Returns 403 Forbidden if the claim doesn't include all required values
206
+ * or user is not authenticated.
207
+ *
208
+ * @param claim - The name of the array claim to check
209
+ * @param values - The values that must be present in the claim array
210
+ * @param options - Optional configuration
211
+ * @returns Express middleware function
212
+ *
213
+ * @example
214
+ * ```typescript
215
+ * // Require user to have specific permissions
216
+ * app.delete('/users/:id', claimIncludes('permissions', ['delete:users']), (req, res) => {
217
+ * res.send('User deleted');
218
+ * });
219
+ *
220
+ * // Require multiple permissions
221
+ * app.post('/admin/users', claimIncludes('permissions', ['create:users', 'admin:access']), (req, res) => {
222
+ * res.send('User created');
223
+ * });
224
+ *
225
+ * // Check roles
226
+ * app.get('/dashboard', claimIncludes('roles', ['editor', 'admin']), (req, res) => {
227
+ * res.send('Dashboard');
228
+ * });
229
+ * ```
230
+ */
231
+ declare function claimIncludes(claim: string, values: unknown[], options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
232
+
233
+ /**
234
+ * Middleware to check if a claim equals a specific value.
235
+ *
236
+ * Returns 403 Forbidden if the claim doesn't match or user is not authenticated.
237
+ *
238
+ * @param claim - The name of the claim to check
239
+ * @param value - The expected value of the claim
240
+ * @param options - Optional configuration
241
+ * @returns Express middleware function
242
+ *
243
+ * @example
244
+ * ```typescript
245
+ * // Require user to be an admin
246
+ * app.get('/admin', claimEquals('role', 'admin'), (req, res) => {
247
+ * res.send('Admin dashboard');
248
+ * });
249
+ *
250
+ * // Check organization membership
251
+ * app.get('/org', claimEquals('org_id', 'org_123'), (req, res) => {
252
+ * res.send('Organization page');
253
+ * });
254
+ * ```
255
+ */
256
+ declare function claimEquals(claim: string, value: JSONPrimitive, options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
257
+
258
+ /**
259
+ * Middleware to check claims using a custom validation function.
260
+ *
261
+ * Returns 403 Forbidden if the validation function returns false
262
+ * or user is not authenticated.
263
+ *
264
+ * @param checkFn - A function that receives the user claims and returns true if authorized
265
+ * @param options - Optional configuration
266
+ * @returns Express middleware function
267
+ *
268
+ * @example
269
+ * ```typescript
270
+ * // Custom claim validation
271
+ * app.get('/premium', claimCheck((claims) => {
272
+ * return claims.subscription === 'premium' && !claims.subscription_expired;
273
+ * }), (req, res) => {
274
+ * res.send('Premium content');
275
+ * });
276
+ *
277
+ * // Complex authorization logic
278
+ * app.delete('/posts/:id', claimCheck(async (claims) => {
279
+ * const postId = req.params.id;
280
+ * const post = await getPost(postId);
281
+ * return claims.sub === post.authorId || claims.role === 'admin';
282
+ * }), (req, res) => {
283
+ * res.send('Post deleted');
284
+ * });
285
+ *
286
+ * // With custom error message
287
+ * app.get('/beta', claimCheck(
288
+ * (claims) => claims.beta_access === true,
289
+ * { errorMessage: 'Beta access required' }
290
+ * ), (req, res) => {
291
+ * res.send('Beta features');
292
+ * });
293
+ * ```
294
+ */
295
+ declare function claimCheck(checkFn: ClaimCheckFunction, options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
296
+
297
+ export { type Auth0Options, type ClaimAuthOptions, type ClaimCheckFunction, type RequireAuthOptions, type StoreOptions, claimCheck, claimEquals, claimIncludes, createAuth0, requireAuth };