@auth0/auth0-express 1.0.0-beta.0 → 1.0.0-beta.2
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 +27 -4
- package/dist/app-base-url.d.ts +31 -0
- package/dist/app-base-url.d.ts.map +1 -0
- package/dist/app-base-url.js +102 -0
- package/dist/app-base-url.js.map +1 -0
- package/dist/config.d.ts +15 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +102 -0
- package/dist/config.js.map +1 -0
- package/dist/errors/index.d.ts +6 -0
- package/dist/errors/index.d.ts.map +1 -0
- package/dist/errors/index.js +9 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/handlers/backchannel-logout-handler.d.ts +3 -0
- package/dist/handlers/backchannel-logout-handler.d.ts.map +1 -0
- package/dist/handlers/backchannel-logout-handler.js +15 -0
- package/dist/handlers/backchannel-logout-handler.js.map +1 -0
- package/dist/handlers/callback-handler.d.ts +4 -0
- package/dist/handlers/callback-handler.d.ts.map +1 -0
- package/dist/handlers/callback-handler.js +18 -0
- package/dist/handlers/callback-handler.js.map +1 -0
- package/dist/handlers/login-handler.d.ts +4 -0
- package/dist/handlers/login-handler.d.ts.map +1 -0
- package/dist/handlers/login-handler.js +64 -0
- package/dist/handlers/login-handler.js.map +1 -0
- package/dist/handlers/logout-handler.d.ts +4 -0
- package/dist/handlers/logout-handler.d.ts.map +1 -0
- package/dist/handlers/logout-handler.js +15 -0
- package/dist/handlers/logout-handler.js.map +1 -0
- package/dist/index.d.ts +11 -297
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -375
- package/dist/index.js.map +1 -1
- package/dist/middleware/claim-auth.d.ts +28 -0
- package/dist/middleware/claim-auth.d.ts.map +1 -0
- package/dist/middleware/claim-auth.js +2 -0
- package/dist/middleware/claim-auth.js.map +1 -0
- package/dist/middleware/claim-check.d.ts +41 -0
- package/dist/middleware/claim-check.d.ts.map +1 -0
- package/dist/middleware/claim-check.js +62 -0
- package/dist/middleware/claim-check.js.map +1 -0
- package/dist/middleware/claim-equals.d.ts +27 -0
- package/dist/middleware/claim-equals.d.ts.map +1 -0
- package/dist/middleware/claim-equals.js +48 -0
- package/dist/middleware/claim-equals.js.map +1 -0
- package/dist/middleware/claim-includes.d.ts +37 -0
- package/dist/middleware/claim-includes.d.ts.map +1 -0
- package/dist/middleware/claim-includes.js +68 -0
- package/dist/middleware/claim-includes.js.map +1 -0
- package/dist/middleware/require-auth.d.ts +44 -0
- package/dist/middleware/require-auth.d.ts.map +1 -0
- package/dist/middleware/require-auth.js +57 -0
- package/dist/middleware/require-auth.js.map +1 -0
- package/dist/router.d.ts +34 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +76 -0
- package/dist/router.js.map +1 -0
- package/dist/store/express-cookie-handler.d.ts +17 -0
- package/dist/store/express-cookie-handler.d.ts.map +1 -0
- package/dist/store/express-cookie-handler.js +30 -0
- package/dist/store/express-cookie-handler.js.map +1 -0
- package/dist/store/request-context.d.ts +36 -0
- package/dist/store/request-context.d.ts.map +1 -0
- package/dist/store/request-context.js +49 -0
- package/dist/store/request-context.js.map +1 -0
- package/dist/types/express.d.ts +13 -0
- package/dist/types/express.d.ts.map +1 -0
- package/dist/types/express.js +2 -0
- package/dist/types/express.js.map +1 -0
- package/dist/types.d.ts +125 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils.d.ts +35 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +146 -0
- package/dist/utils.js.map +1 -0
- package/package.json +10 -9
- package/dist/index.cjs +0 -417
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -297
package/dist/index.d.ts
CHANGED
|
@@ -1,297 +1,11 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
*
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
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 };
|
|
1
|
+
export { createAuth0 } from './router.js';
|
|
2
|
+
export { requiresAuth } from './middleware/require-auth.js';
|
|
3
|
+
export { claimIncludes } from './middleware/claim-includes.js';
|
|
4
|
+
export { claimEquals } from './middleware/claim-equals.js';
|
|
5
|
+
export { claimCheck } from './middleware/claim-check.js';
|
|
6
|
+
export type { RequiresAuthOptions } from './middleware/require-auth.js';
|
|
7
|
+
export type { ClaimAuthOptions, ClaimCheckFunction } from './middleware/claim-auth.js';
|
|
8
|
+
export * from './types.js';
|
|
9
|
+
export { InvalidConfigurationError } from './errors/index.js';
|
|
10
|
+
export { resolveAppBaseUrl, isUrl } from './app-base-url.js';
|
|
11
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,YAAY,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACxE,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACvF,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,376 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
10
|
-
var asyncLocalStorage = new AsyncLocalStorage();
|
|
11
|
-
function runWithContext(context, callback) {
|
|
12
|
-
return asyncLocalStorage.run(context, callback);
|
|
13
|
-
}
|
|
14
|
-
function getRequestContext() {
|
|
15
|
-
const context = asyncLocalStorage.getStore();
|
|
16
|
-
if (!context) {
|
|
17
|
-
throw new Error(
|
|
18
|
-
"Request context not available. This error typically occurs when:\n1. Client methods are called outside of a request handler\n2. The auth0 middleware has not been initialized\n3. AsyncLocalStorage context was lost in an async operation\n\nEnsure you are calling client methods within an Express request handler and the auth0 middleware is properly configured."
|
|
19
|
-
);
|
|
20
|
-
}
|
|
21
|
-
return context;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// src/store/express-cookie-handler.ts
|
|
25
|
-
var ExpressCookieHandler = class {
|
|
26
|
-
setCookie(name, value, options, storeOptions) {
|
|
27
|
-
const { response } = storeOptions ?? getRequestContext();
|
|
28
|
-
const maxAge = options?.maxAge != null ? options.maxAge * 1e3 : void 0;
|
|
29
|
-
response.cookie(name, value, { ...options, maxAge });
|
|
30
|
-
}
|
|
31
|
-
getCookie(name, storeOptions) {
|
|
32
|
-
const { request } = storeOptions ?? getRequestContext();
|
|
33
|
-
return request.cookies?.[name];
|
|
34
|
-
}
|
|
35
|
-
getCookies(storeOptions) {
|
|
36
|
-
const { request } = storeOptions ?? getRequestContext();
|
|
37
|
-
return request.cookies;
|
|
38
|
-
}
|
|
39
|
-
deleteCookie(name, storeOptions) {
|
|
40
|
-
const { response } = storeOptions ?? getRequestContext();
|
|
41
|
-
response.clearCookie(name);
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
// src/utils.ts
|
|
46
|
-
function ensureTrailingSlash(value) {
|
|
47
|
-
return value && !value.endsWith("/") ? `${value}/` : value;
|
|
48
|
-
}
|
|
49
|
-
function ensureNoLeadingSlash(value) {
|
|
50
|
-
return value.replace(/^\/+/, "");
|
|
51
|
-
}
|
|
52
|
-
function createRouteUrl(url, base) {
|
|
53
|
-
const baseUrl = new URL(ensureTrailingSlash(base));
|
|
54
|
-
const normalized = ensureNoLeadingSlash(url);
|
|
55
|
-
if (normalized !== url.replace(/^\//, "")) {
|
|
56
|
-
throw new Error(`Invalid route configuration: '${url}' contains multiple leading slashes`);
|
|
57
|
-
}
|
|
58
|
-
const result = new URL(normalized, baseUrl);
|
|
59
|
-
if (result.origin !== baseUrl.origin) {
|
|
60
|
-
throw new Error("URL is not allowed: origin does not match base URL");
|
|
61
|
-
}
|
|
62
|
-
return result;
|
|
63
|
-
}
|
|
64
|
-
function toSafeRedirect(dangerousRedirect, safeBaseUrl) {
|
|
65
|
-
let url;
|
|
66
|
-
try {
|
|
67
|
-
url = createRouteUrl(dangerousRedirect, safeBaseUrl);
|
|
68
|
-
} catch {
|
|
69
|
-
return void 0;
|
|
70
|
-
}
|
|
71
|
-
if (url.origin === new URL(safeBaseUrl).origin) {
|
|
72
|
-
return url.toString();
|
|
73
|
-
}
|
|
74
|
-
return void 0;
|
|
75
|
-
}
|
|
76
|
-
function createServerClientInstance(options) {
|
|
77
|
-
const callbackPath = options.routes?.callback ?? "/auth/callback";
|
|
78
|
-
const redirectUri = createRouteUrl(callbackPath, options.appBaseUrl);
|
|
79
|
-
return new ServerClient({
|
|
80
|
-
domain: options.domain,
|
|
81
|
-
clientId: options.clientId,
|
|
82
|
-
clientSecret: options.clientSecret,
|
|
83
|
-
clientAssertionSigningKey: options.clientAssertionSigningKey,
|
|
84
|
-
clientAssertionSigningAlg: options.clientAssertionSigningAlg,
|
|
85
|
-
authorizationParams: {
|
|
86
|
-
audience: options.audience,
|
|
87
|
-
redirect_uri: redirectUri.toString()
|
|
88
|
-
},
|
|
89
|
-
transactionStore: new CookieTransactionStore({ secret: options.sessionSecret }, new ExpressCookieHandler()),
|
|
90
|
-
stateStore: options.sessionStore ? new StatefulStateStore(
|
|
91
|
-
{
|
|
92
|
-
...options.sessionConfiguration,
|
|
93
|
-
secret: options.sessionSecret,
|
|
94
|
-
store: options.sessionStore
|
|
95
|
-
},
|
|
96
|
-
new ExpressCookieHandler()
|
|
97
|
-
) : new StatelessStateStore(
|
|
98
|
-
{
|
|
99
|
-
...options.sessionConfiguration,
|
|
100
|
-
secret: options.sessionSecret
|
|
101
|
-
},
|
|
102
|
-
new ExpressCookieHandler()
|
|
103
|
-
),
|
|
104
|
-
stateIdentifier: options.sessionConfiguration?.cookie?.name,
|
|
105
|
-
customFetch: options.customFetch
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// src/handlers/login-handler.ts
|
|
110
|
-
var DENIED_KEYS = /* @__PURE__ */ new Set([
|
|
111
|
-
...Object.getOwnPropertyNames(Object.prototype),
|
|
112
|
-
"__proto__",
|
|
113
|
-
"constructor",
|
|
114
|
-
"prototype"
|
|
115
|
-
]);
|
|
116
|
-
var RESERVED_OAUTH_PARAMS = /* @__PURE__ */ new Set([
|
|
117
|
-
"response_type",
|
|
118
|
-
"state",
|
|
119
|
-
"code_challenge",
|
|
120
|
-
"code_challenge_method",
|
|
121
|
-
"client_id",
|
|
122
|
-
"redirect_uri",
|
|
123
|
-
"nonce",
|
|
124
|
-
"scope",
|
|
125
|
-
"audience"
|
|
126
|
-
]);
|
|
127
|
-
function filterAuthorizationParams(params, disallowed) {
|
|
128
|
-
const filtered = /* @__PURE__ */ Object.create(null);
|
|
129
|
-
for (const [key, value] of Object.entries(params)) {
|
|
130
|
-
if (!DENIED_KEYS.has(key) && !disallowed.includes(key) && !RESERVED_OAUTH_PARAMS.has(key)) {
|
|
131
|
-
filtered[key] = value;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
return Object.keys(filtered).length > 0 ? filtered : void 0;
|
|
135
|
-
}
|
|
136
|
-
async function handleLogin(req, res, options) {
|
|
137
|
-
try {
|
|
138
|
-
const query = req.query;
|
|
139
|
-
const dangerousReturnTo = query.returnTo;
|
|
140
|
-
const sanitizedReturnTo = toSafeRedirect(dangerousReturnTo || "/", options.appBaseUrl);
|
|
141
|
-
const authorizationUrl = await req.auth0.client.startInteractiveLogin({
|
|
142
|
-
pushedAuthorizationRequests: options.pushedAuthorizationRequests,
|
|
143
|
-
appState: { returnTo: sanitizedReturnTo },
|
|
144
|
-
authorizationParams: filterAuthorizationParams(query, ["returnTo"])
|
|
145
|
-
});
|
|
146
|
-
res.redirect(authorizationUrl.href);
|
|
147
|
-
} catch (error) {
|
|
148
|
-
res.status(500).json({
|
|
149
|
-
error: error.name,
|
|
150
|
-
message: error.message
|
|
151
|
-
});
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// src/handlers/callback-handler.ts
|
|
156
|
-
async function handleCallback(req, res, options) {
|
|
157
|
-
try {
|
|
158
|
-
const { appState } = await req.auth0.client.completeInteractiveLogin(
|
|
159
|
-
createRouteUrl(req.url, options.appBaseUrl)
|
|
160
|
-
);
|
|
161
|
-
res.redirect(appState?.returnTo ?? options.appBaseUrl);
|
|
162
|
-
} catch (e) {
|
|
163
|
-
const error = e;
|
|
164
|
-
res.status(500).json({
|
|
165
|
-
error: error.cause?.error || error.name,
|
|
166
|
-
message: error.cause?.error_description || error.message
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// src/handlers/logout-handler.ts
|
|
172
|
-
async function handleLogout(req, res, options) {
|
|
173
|
-
try {
|
|
174
|
-
const returnTo = options.appBaseUrl;
|
|
175
|
-
const logoutUrl = await req.auth0.client.logout({ returnTo: returnTo.toString() });
|
|
176
|
-
res.redirect(logoutUrl.href);
|
|
177
|
-
} catch (error) {
|
|
178
|
-
res.status(500).json({
|
|
179
|
-
error: error.name,
|
|
180
|
-
message: error.message
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
// src/handlers/backchannel-logout-handler.ts
|
|
186
|
-
async function handleBackchannelLogout(req, res) {
|
|
187
|
-
const logoutToken = req.body.logout_token;
|
|
188
|
-
if (!logoutToken) {
|
|
189
|
-
res.status(400).send("Missing `logout_token` in the request body.");
|
|
190
|
-
return;
|
|
191
|
-
}
|
|
192
|
-
try {
|
|
193
|
-
await req.auth0.client.handleBackchannelLogout(logoutToken);
|
|
194
|
-
res.status(204).send(null);
|
|
195
|
-
} catch (e) {
|
|
196
|
-
res.status(400).send(e.message);
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
// src/config.ts
|
|
201
|
-
import { MissingRequiredArgumentError } from "@auth0/auth0-server-js";
|
|
202
|
-
function stripProtocol(url) {
|
|
203
|
-
return url ? url.replace(/^https?:\/\//, "") : url;
|
|
204
|
-
}
|
|
205
|
-
function getConfig(config = {}) {
|
|
206
|
-
const mergedConfig = {
|
|
207
|
-
domain: process.env.AUTH0_DOMAIN || stripProtocol(process.env.ISSUER_BASE_URL),
|
|
208
|
-
clientId: process.env.AUTH0_CLIENT_ID || process.env.CLIENT_ID,
|
|
209
|
-
clientSecret: process.env.AUTH0_CLIENT_SECRET || process.env.CLIENT_SECRET,
|
|
210
|
-
appBaseUrl: process.env.APP_BASE_URL || process.env.BASE_URL,
|
|
211
|
-
sessionSecret: process.env.AUTH0_SESSION_SECRET || process.env.SECRET,
|
|
212
|
-
audience: process.env.AUTH0_AUDIENCE,
|
|
213
|
-
...config
|
|
214
|
-
};
|
|
215
|
-
if (!mergedConfig.domain) {
|
|
216
|
-
throw new MissingRequiredArgumentError("domain");
|
|
217
|
-
}
|
|
218
|
-
if (!mergedConfig.clientId) {
|
|
219
|
-
throw new MissingRequiredArgumentError("clientId");
|
|
220
|
-
}
|
|
221
|
-
if (!mergedConfig.appBaseUrl) {
|
|
222
|
-
throw new MissingRequiredArgumentError("appBaseUrl");
|
|
223
|
-
}
|
|
224
|
-
if (!mergedConfig.sessionSecret) {
|
|
225
|
-
throw new MissingRequiredArgumentError("sessionSecret");
|
|
226
|
-
}
|
|
227
|
-
return mergedConfig;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
// src/router.ts
|
|
231
|
-
function createAuth0(opts = {}) {
|
|
232
|
-
const options = getConfig(opts);
|
|
233
|
-
const router = Router();
|
|
234
|
-
router.use(cookieParser());
|
|
235
|
-
router.use((request, response, next) => {
|
|
236
|
-
runWithContext({ request, response }, () => next());
|
|
237
|
-
});
|
|
238
|
-
const auth0Client = createServerClientInstance(options);
|
|
239
|
-
router.use((req, res, next) => {
|
|
240
|
-
req.auth0 = { client: auth0Client };
|
|
241
|
-
req.app.locals.auth0Client = auth0Client;
|
|
242
|
-
req.app.locals.auth0ClientOptions = options;
|
|
243
|
-
req.app.locals.appBaseUrl = options.appBaseUrl;
|
|
244
|
-
req.app.locals.pushedAuthorizationRequests = options.pushedAuthorizationRequests;
|
|
245
|
-
next();
|
|
246
|
-
});
|
|
247
|
-
const shouldMountRoutes = options.mountRoutes ?? true;
|
|
248
|
-
if (shouldMountRoutes) {
|
|
249
|
-
const routes = {
|
|
250
|
-
login: options.routes?.login ?? "/auth/login",
|
|
251
|
-
callback: options.routes?.callback ?? "/auth/callback",
|
|
252
|
-
logout: options.routes?.logout ?? "/auth/logout",
|
|
253
|
-
backchannelLogout: options.routes?.backchannelLogout ?? "/auth/backchannel-logout"
|
|
254
|
-
};
|
|
255
|
-
router.get(routes.login, (req, res) => handleLogin(req, res, options));
|
|
256
|
-
router.get(routes.callback, (req, res) => handleCallback(req, res, options));
|
|
257
|
-
router.get(routes.logout, (req, res) => handleLogout(req, res, options));
|
|
258
|
-
router.post(routes.backchannelLogout, (req, res) => handleBackchannelLogout(req, res));
|
|
259
|
-
}
|
|
260
|
-
return router;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// src/middleware/require-auth.ts
|
|
264
|
-
function requireAuth(options) {
|
|
265
|
-
return async (req, res, next) => {
|
|
266
|
-
try {
|
|
267
|
-
const user = await req.auth0.client.getUser();
|
|
268
|
-
if (!user) {
|
|
269
|
-
const acceptsJson = req.accepts("json") && !req.accepts("html");
|
|
270
|
-
if (acceptsJson) {
|
|
271
|
-
return res.status(401).json({
|
|
272
|
-
error: "unauthorized",
|
|
273
|
-
message: "Authentication required"
|
|
274
|
-
});
|
|
275
|
-
}
|
|
276
|
-
const returnTo = options?.returnTo || req.originalUrl;
|
|
277
|
-
const loginPath = req.app.locals.auth0ClientOptions?.routes?.login || "/auth/login";
|
|
278
|
-
const loginUrl = `${loginPath}?returnTo=${encodeURIComponent(returnTo)}`;
|
|
279
|
-
return res.redirect(loginUrl);
|
|
280
|
-
}
|
|
281
|
-
next();
|
|
282
|
-
} catch (error) {
|
|
283
|
-
next(error);
|
|
284
|
-
}
|
|
285
|
-
};
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
// src/middleware/claim-includes.ts
|
|
289
|
-
function claimIncludes(claim, values, options) {
|
|
290
|
-
return async (req, res, next) => {
|
|
291
|
-
try {
|
|
292
|
-
const user = await req.auth0.client.getUser();
|
|
293
|
-
if (!user) {
|
|
294
|
-
return res.status(401).json({
|
|
295
|
-
error: "unauthorized",
|
|
296
|
-
message: "Authentication required"
|
|
297
|
-
});
|
|
298
|
-
}
|
|
299
|
-
const claimValue = user[claim];
|
|
300
|
-
if (!Array.isArray(claimValue)) {
|
|
301
|
-
return res.status(options?.statusCode || 403).json({
|
|
302
|
-
error: "forbidden",
|
|
303
|
-
message: options?.errorMessage || `Access denied`
|
|
304
|
-
});
|
|
305
|
-
}
|
|
306
|
-
const hasAllValues = values.every((value) => claimValue.includes(value));
|
|
307
|
-
if (!hasAllValues) {
|
|
308
|
-
return res.status(options?.statusCode || 403).json({
|
|
309
|
-
error: "forbidden",
|
|
310
|
-
message: options?.errorMessage || `Access denied`
|
|
311
|
-
});
|
|
312
|
-
}
|
|
313
|
-
next();
|
|
314
|
-
} catch (error) {
|
|
315
|
-
next(error);
|
|
316
|
-
}
|
|
317
|
-
};
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
// src/middleware/claim-equals.ts
|
|
321
|
-
function claimEquals(claim, value, options) {
|
|
322
|
-
return async (req, res, next) => {
|
|
323
|
-
try {
|
|
324
|
-
const user = await req.auth0.client.getUser();
|
|
325
|
-
if (!user) {
|
|
326
|
-
return res.status(401).json({
|
|
327
|
-
error: "unauthorized",
|
|
328
|
-
message: "Authentication required"
|
|
329
|
-
});
|
|
330
|
-
}
|
|
331
|
-
const claimValue = user[claim];
|
|
332
|
-
if (claimValue !== value) {
|
|
333
|
-
return res.status(options?.statusCode || 403).json({
|
|
334
|
-
error: "forbidden",
|
|
335
|
-
message: options?.errorMessage || `Access denied`
|
|
336
|
-
});
|
|
337
|
-
}
|
|
338
|
-
next();
|
|
339
|
-
} catch (error) {
|
|
340
|
-
next(error);
|
|
341
|
-
}
|
|
342
|
-
};
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
// src/middleware/claim-check.ts
|
|
346
|
-
function claimCheck(checkFn, options) {
|
|
347
|
-
return async (req, res, next) => {
|
|
348
|
-
try {
|
|
349
|
-
const user = await req.auth0.client.getUser();
|
|
350
|
-
if (!user) {
|
|
351
|
-
return res.status(401).json({
|
|
352
|
-
error: "unauthorized",
|
|
353
|
-
message: "Authentication required"
|
|
354
|
-
});
|
|
355
|
-
}
|
|
356
|
-
const isAuthorized = await checkFn(user);
|
|
357
|
-
if (!isAuthorized) {
|
|
358
|
-
return res.status(options?.statusCode || 403).json({
|
|
359
|
-
error: "forbidden",
|
|
360
|
-
message: options?.errorMessage || "Access denied"
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
next();
|
|
364
|
-
} catch (error) {
|
|
365
|
-
next(error);
|
|
366
|
-
}
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
|
-
export {
|
|
370
|
-
claimCheck,
|
|
371
|
-
claimEquals,
|
|
372
|
-
claimIncludes,
|
|
373
|
-
createAuth0,
|
|
374
|
-
requireAuth
|
|
375
|
-
};
|
|
1
|
+
export { createAuth0 } from './router.js';
|
|
2
|
+
export { requiresAuth } from './middleware/require-auth.js';
|
|
3
|
+
export { claimIncludes } from './middleware/claim-includes.js';
|
|
4
|
+
export { claimEquals } from './middleware/claim-equals.js';
|
|
5
|
+
export { claimCheck } from './middleware/claim-check.js';
|
|
6
|
+
export * from './types.js';
|
|
7
|
+
export { InvalidConfigurationError } from './errors/index.js';
|
|
8
|
+
export { resolveAppBaseUrl, isUrl } from './app-base-url.js';
|
|
376
9
|
//# sourceMappingURL=index.js.map
|