@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.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router.ts","../src/utils.ts","../src/store/request-context.ts","../src/store/express-cookie-handler.ts","../src/handlers/login-handler.ts","../src/handlers/callback-handler.ts","../src/handlers/logout-handler.ts","../src/handlers/backchannel-logout-handler.ts","../src/config.ts","../src/middleware/require-auth.ts","../src/middleware/claim-includes.ts","../src/middleware/claim-equals.ts","../src/middleware/claim-check.ts"],"sourcesContent":["import { Router, Request, Response, NextFunction } from 'express';\nimport cookieParser from 'cookie-parser';\nimport type { Auth0Options } from './types.js';\nimport { createServerClientInstance } from './utils.js';\nimport { handleLogin } from './handlers/login-handler.js';\nimport { handleCallback } from './handlers/callback-handler.js';\nimport { handleLogout } from './handlers/logout-handler.js';\nimport { handleBackchannelLogout } from './handlers/backchannel-logout-handler.js';\nimport { runWithContext } from './store/request-context.js';\nimport { getConfig } from './config.js';\nimport './types/express.js';\n\n/**\n * Creates an Express router with Auth0 authentication middleware.\n *\n * This is the main entry point for the Auth0 Express SDK. It configures\n * authentication routes and attaches the Auth0 client to the request object.\n *\n * @param opts - Configuration options for Auth0 authentication\n * @returns Express Router configured with Auth0 authentication\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { createAuth0 } from '@auth0/auth0-express';\n *\n * const app = express();\n *\n * // Using environment variables (AUTH0_DOMAIN, AUTH0_CLIENT_ID, etc.)\n * app.use(createAuth0());\n *\n * // Or with explicit configuration\n * app.use(createAuth0({\n * domain: 'tenant.auth0.com',\n * clientId: 'your_client_id',\n * clientSecret: 'your_client_secret',\n * appBaseUrl: 'http://localhost:3000',\n * sessionSecret: process.env.SESSION_SECRET\n * }));\n * ```\n */\nexport function createAuth0(opts: Partial<Auth0Options> = {}): Router {\n const options = getConfig(opts);\n const router = Router();\n\n // Cookie parsing\n router.use(cookieParser());\n\n // Establish AsyncLocalStorage context for the request lifecycle\n router.use((request: Request, response: Response, next: NextFunction) => {\n runWithContext({ request, response }, () => next());\n });\n\n // Initialize auth0Client\n const auth0Client = createServerClientInstance(options);\n\n // Attach to request\n router.use((req: Request, res: Response, next: NextFunction) => {\n req.auth0 = { client: auth0Client };\n req.app.locals.auth0Client = auth0Client;\n req.app.locals.auth0ClientOptions = options;\n req.app.locals.appBaseUrl = options.appBaseUrl;\n req.app.locals.pushedAuthorizationRequests = options.pushedAuthorizationRequests;\n next();\n });\n\n // Mount routes\n const shouldMountRoutes = options.mountRoutes ?? true;\n\n if (shouldMountRoutes) {\n const routes = {\n login: options.routes?.login ?? '/auth/login',\n callback: options.routes?.callback ?? '/auth/callback',\n logout: options.routes?.logout ?? '/auth/logout',\n backchannelLogout: options.routes?.backchannelLogout ?? '/auth/backchannel-logout',\n };\n\n router.get(routes.login, (req, res) => handleLogin(req, res, options));\n router.get(routes.callback, (req, res) => handleCallback(req, res, options));\n router.get(routes.logout, (req, res) => handleLogout(req, res, options));\n router.post(routes.backchannelLogout, (req, res) => handleBackchannelLogout(req, res));\n }\n\n return router;\n}\n","import { CookieTransactionStore, ServerClient, StatefulStateStore, StatelessStateStore } from '@auth0/auth0-server-js';\nimport { Auth0Options, StoreOptions } from './types.js';\nimport { ExpressCookieHandler } from './store/express-cookie-handler.js';\n\n/**\n * Ensures the value has a trailing slash.\n * If it does not, it will append one.\n * @param value The value to ensure has a trailing slash.\n * @returns The value with a trailing slash.\n */\nfunction ensureTrailingSlash(value: string) {\n return value && !value.endsWith('/') ? `${value}/` : value;\n}\n\n/**\n * Ensures the value does not have any leading slashes.\n * If it does, it will trim all of them.\n * @param value The value to ensure has no leading slashes.\n * @returns The value without leading slashes.\n */\nfunction ensureNoLeadingSlash(value: string) {\n return value.replace(/^\\/+/, '');\n}\n\n/**\n * Utility function to ensure Route URLs are created correctly when using both the root and subpath as base URL.\n * Validates that the constructed URL has the same origin as the base URL to prevent host override attacks.\n * @param url The URL to use.\n * @param base The base URL to use.\n * @returns A URL object, combining the base and url.\n * @throws {Error} If the constructed URL origin does not match the base URL origin.\n */\nexport function createRouteUrl(url: string, base: string) {\n const baseUrl = new URL(ensureTrailingSlash(base));\n const normalized = ensureNoLeadingSlash(url);\n\n if (normalized !== url.replace(/^\\//, '')) {\n throw new Error(`Invalid route configuration: '${url}' contains multiple leading slashes`);\n }\n\n const result = new URL(normalized, baseUrl);\n if (result.origin !== baseUrl.origin) {\n throw new Error('URL is not allowed: origin does not match base URL');\n }\n return result;\n}\n\n/**\n * Function to ensure a redirect URL is safe to use, as in, it has the same origin as the safeBaseUrl.\n * @param dangerousRedirect The redirect URL to check.\n * @param safeBaseUrl The base URL to check against.\n * @returns A safe redirect URL or undefined if the redirect URL is not safe.\n */\nexport function toSafeRedirect(dangerousRedirect: string, safeBaseUrl: string): string | undefined {\n let url: URL;\n\n try {\n url = createRouteUrl(dangerousRedirect, safeBaseUrl);\n } catch {\n return undefined;\n }\n\n if (url.origin === new URL(safeBaseUrl).origin) {\n return url.toString();\n }\n\n return undefined;\n}\n\nexport function createServerClientInstance(options: Auth0Options) {\n const callbackPath = options.routes?.callback ?? '/auth/callback';\n const redirectUri = createRouteUrl(callbackPath, options.appBaseUrl);\n \n return new ServerClient<StoreOptions>({\n domain: options.domain,\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n clientAssertionSigningKey: options.clientAssertionSigningKey,\n clientAssertionSigningAlg: options.clientAssertionSigningAlg,\n authorizationParams: {\n audience: options.audience,\n redirect_uri: redirectUri.toString(),\n },\n transactionStore: new CookieTransactionStore({ secret: options.sessionSecret }, new ExpressCookieHandler()),\n stateStore: options.sessionStore\n ? new StatefulStateStore(\n {\n ...options.sessionConfiguration,\n secret: options.sessionSecret,\n store: options.sessionStore,\n },\n new ExpressCookieHandler()\n )\n : new StatelessStateStore(\n {\n ...options.sessionConfiguration,\n secret: options.sessionSecret,\n },\n new ExpressCookieHandler()\n ),\n stateIdentifier: options.sessionConfiguration?.cookie?.name,\n customFetch: options.customFetch,\n });\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { StoreOptions } from 'src/types.js';\n\n/**\n * Context containing Express request and response objects.\n * Available within the AsyncLocalStorage scope established by the auth0 middleware.\n */\nexport type RequestContext = StoreOptions;\n\n/**\n * AsyncLocalStorage instance for storing request context.\n * @internal\n */\nconst asyncLocalStorage = new AsyncLocalStorage<RequestContext>();\n\n/**\n * Runs a callback within an AsyncLocalStorage context containing the request and response.\n * This establishes the context for the entire request lifecycle.\n *\n * @param request - Express request object\n * @param response - Express response object\n * @param callback - Function to execute within the context\n * @returns The result of the callback\n *\n * @example\n * ```typescript\n * app.use((req, res, next) => {\n * runWithContext(req, res, () => next());\n * });\n * ```\n */\nexport function runWithContext<T>(\n context: RequestContext,\n callback: () => T\n): T {\n return asyncLocalStorage.run(context, callback);\n}\n\n/**\n * Retrieves the current request context from AsyncLocalStorage.\n *\n * @returns The current RequestContext\n * @throws {Error} If called outside of a request context\n *\n * @example\n * ```typescript\n * const { request, response } = getRequestContext();\n * ```\n */\nexport function getRequestContext(): RequestContext {\n const context = asyncLocalStorage.getStore();\n\n if (!context) {\n throw new Error(\n 'Request context not available. This error typically occurs when:\\n' +\n '1. Client methods are called outside of a request handler\\n' +\n '2. The auth0 middleware has not been initialized\\n' +\n '3. AsyncLocalStorage context was lost in an async operation\\n\\n' +\n 'Ensure you are calling client methods within an Express request handler ' +\n 'and the auth0 middleware is properly configured.'\n );\n }\n\n return context;\n}\n","import { CookieHandler, CookieSerializeOptions } from '@auth0/auth0-server-js';\nimport { StoreOptions } from '../types.js';\nimport { getRequestContext } from './request-context.js';\n\n/**\n * Express-specific cookie handler that uses AsyncLocalStorage to automatically\n * access the current request and response objects.\n *\n * This implementation supports both explicit storeOptions and AsyncLocalStorage context.\n * When storeOptions are provided, they take precedence. Otherwise, it falls back to\n * retrieving the request context from AsyncLocalStorage.\n */\nexport class ExpressCookieHandler implements CookieHandler<StoreOptions> {\n setCookie(name: string, value: string, options?: CookieSerializeOptions, storeOptions?: StoreOptions): void {\n const { response } = storeOptions ?? getRequestContext();\n\n // options.maxAge is in seconds, but Express expects milliseconds\n const maxAge = options?.maxAge != null ? options.maxAge * 1000 : undefined;\n\n response.cookie(name, value, { ...options, maxAge });\n }\n\n getCookie(name: string, storeOptions?: StoreOptions): string | undefined {\n const { request } = storeOptions ?? getRequestContext();\n return request.cookies?.[name];\n }\n\n getCookies(storeOptions?: StoreOptions): Record<string, string> {\n const { request } = storeOptions ?? getRequestContext();\n return request.cookies as Record<string, string>;\n }\n\n deleteCookie(name: string, storeOptions?: StoreOptions): void {\n const { response } = storeOptions ?? getRequestContext();\n response.clearCookie(name);\n }\n}\n","import { Request, Response } from 'express';\nimport { toSafeRedirect } from '../utils.js';\nimport { Auth0Options } from '../index.js';\n\n// Block both Object.prototype own-property names and commonly abused\n// prototype-pollution keys that are not own-properties of Object.prototype.\nconst DENIED_KEYS = new Set([\n ...Object.getOwnPropertyNames(Object.prototype),\n '__proto__',\n 'constructor',\n 'prototype',\n]);\n\n// OAuth/OIDC protocol parameters that must be SDK-controlled, not user-supplied\nconst RESERVED_OAUTH_PARAMS = new Set([\n 'response_type',\n 'state',\n 'code_challenge',\n 'code_challenge_method',\n 'client_id',\n 'redirect_uri',\n 'nonce',\n 'scope',\n 'audience',\n]);\n\n/**\n * Filters out reserved OAuth parameters and any additional disallowed parameters from the input record.\n * This ensures that only safe, non-reserved parameters are included in the authorization request.\n * @param params The record of parameters to filter.\n * @param disallowed An array of parameter names that should be excluded.\n * @returns An object containing only the allowed parameters, or undefined if none are allowed.\n */\nfunction filterAuthorizationParams(\n params: Record<string, unknown>,\n disallowed: string[]\n): Record<string, unknown> | undefined {\n const filtered: Record<string, unknown> = Object.create(null);\n for (const [key, value] of Object.entries(params)) {\n if (!DENIED_KEYS.has(key) && !disallowed.includes(key) && !RESERVED_OAUTH_PARAMS.has(key)) {\n filtered[key] = value;\n }\n }\n return Object.keys(filtered).length > 0 ? filtered : undefined;\n}\n\nexport async function handleLogin(req: Request, res: Response, options: Auth0Options): Promise<void> {\n try {\n const query = req.query as Record<string, unknown>;\n const dangerousReturnTo = query.returnTo as string | undefined;\n const sanitizedReturnTo = toSafeRedirect(dangerousReturnTo || '/', options.appBaseUrl);\n const authorizationUrl = await req.auth0.client.startInteractiveLogin({\n pushedAuthorizationRequests: options.pushedAuthorizationRequests,\n appState: { returnTo: sanitizedReturnTo },\n authorizationParams: filterAuthorizationParams(query, ['returnTo']),\n });\n\n res.redirect(authorizationUrl.href);\n } catch (error) {\n res.status(500).json({\n error: (error as Error).name,\n message: (error as Error).message,\n });\n }\n}\n","import { Request, Response } from 'express';\nimport { createRouteUrl } from '../utils.js';\nimport { Auth0Options } from '../types.js';\n\nexport async function handleCallback(req: Request, res: Response, options: Auth0Options): Promise<void> {\n try {\n const { appState } = await req.auth0.client.completeInteractiveLogin<{ returnTo: string } | undefined>(\n createRouteUrl(req.url, options.appBaseUrl)\n );\n\n res.redirect(appState?.returnTo ?? options.appBaseUrl);\n } catch (e: unknown) {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n const error = e as any;\n\n res.status(500).json({\n error: error.cause?.error || error.name,\n message: error.cause?.error_description || error.message,\n });\n }\n}\n","import { Request, Response } from 'express';\nimport { Auth0Options } from '../types.js';\n\nexport async function handleLogout(req: Request, res: Response, options: Auth0Options): Promise<void> {\n try {\n const returnTo = options.appBaseUrl;\n const logoutUrl = await req.auth0.client.logout({ returnTo: returnTo.toString() });\n\n res.redirect(logoutUrl.href);\n } catch (error) {\n res.status(500).json({\n error: (error as Error).name,\n message: (error as Error).message,\n });\n }\n}\n","import { Request, Response } from 'express';\n\nexport async function handleBackchannelLogout(req: Request, res: Response): Promise<void> {\n const logoutToken = req.body.logout_token;\n\n if (!logoutToken) {\n res.status(400).send('Missing `logout_token` in the request body.');\n return;\n }\n\n try {\n await req.auth0.client.handleBackchannelLogout(logoutToken);\n res.status(204).send(null);\n } catch (e) {\n res.status(400).send((e as Error).message);\n }\n}\n","import { MissingRequiredArgumentError } from '@auth0/auth0-server-js';\nimport type { Auth0Options } from './types.js';\n\nfunction stripProtocol(url: string | undefined): string | undefined {\n return url ? url.replace(/^https?:\\/\\//, '') : url;\n}\n\n/**\n * Merges environment variables with provided configuration options.\n * Environment variables are used as defaults and can be overridden by explicitly provided options.\n *\n * Supported environment variables:\n * - AUTH0_DOMAIN or ISSUER_BASE_URL\n * - AUTH0_CLIENT_ID or CLIENT_ID: Auth0 application client ID\n * - AUTH0_CLIENT_SECRET or CLIENT_SECRET: Auth0 application client secret\n * - APP_BASE_URL or BASE_URL: Application base URL\n * - AUTH0_SESSION_SECRET or SECRET: Session secret for cookie signing\n * - AUTH0_AUDIENCE: Optional API audience\n */\nexport function getConfig(config: Partial<Auth0Options> = {}): Auth0Options {\n const mergedConfig = {\n domain: process.env.AUTH0_DOMAIN || stripProtocol(process.env.ISSUER_BASE_URL),\n clientId: process.env.AUTH0_CLIENT_ID || process.env.CLIENT_ID,\n clientSecret: process.env.AUTH0_CLIENT_SECRET || process.env.CLIENT_SECRET,\n appBaseUrl: process.env.APP_BASE_URL || process.env.BASE_URL,\n sessionSecret: process.env.AUTH0_SESSION_SECRET || process.env.SECRET,\n audience: process.env.AUTH0_AUDIENCE,\n ...config,\n } as Auth0Options;\n\n if (!mergedConfig.domain) {\n throw new MissingRequiredArgumentError('domain');\n }\n\n if (!mergedConfig.clientId) {\n throw new MissingRequiredArgumentError('clientId');\n }\n\n if (!mergedConfig.appBaseUrl) {\n throw new MissingRequiredArgumentError('appBaseUrl');\n }\n\n if (!mergedConfig.sessionSecret) {\n throw new MissingRequiredArgumentError('sessionSecret');\n }\n\n return mergedConfig;\n}\n","import { Request, Response, NextFunction } from 'express';\n\n/**\n * Options for the requireAuth middleware.\n */\nexport interface RequireAuthOptions {\n /**\n * If true, returns a 401 status instead of redirecting to login.\n * Useful for API routes that should not redirect.\n *\n * Default: false (redirects to login)\n */\n returnTo?: string;\n}\n\n/**\n * Middleware to require authentication for a route.\n *\n * If the user is not authenticated:\n * - For HTML requests (browser): Redirects to /auth/login with returnTo parameter\n * - For API requests (JSON): Returns 401 Unauthorized\n *\n * @param options - Optional configuration for the middleware\n * @returns Express middleware function\n *\n * @example\n * ```typescript\n * // Protect a route\n * app.get('/profile', requireAuth(), (req, res) => {\n * res.json({ user: await req.auth0.client.getUser() });\n * });\n *\n * // Protect an API route (returns 401 instead of redirecting)\n * app.get('/api/me', requireAuth(), async (req, res) => {\n * const user = await req.auth0.client.getUser();\n * res.json({ user });\n * });\n *\n * // Custom return URL after login\n * app.get('/admin', requireAuth({ returnTo: '/admin' }), (req, res) => {\n * res.send('Admin page');\n * });\n * ```\n */\nexport function requireAuth(options?: RequireAuthOptions) {\n return async (req: Request, res: Response, next: NextFunction) => {\n try {\n const user = await req.auth0.client.getUser();\n\n if (!user) {\n // Check if this is an API request (wants JSON response)\n const acceptsJson = req.accepts('json') && !req.accepts('html');\n\n if (acceptsJson) {\n return res.status(401).json({\n error: 'unauthorized',\n message: 'Authentication required',\n });\n }\n\n // For HTML requests, redirect to login with returnTo\n const returnTo = options?.returnTo || req.originalUrl;\n const loginPath = req.app.locals.auth0ClientOptions?.routes?.login || '/auth/login';\n const loginUrl = `${loginPath}?returnTo=${encodeURIComponent(returnTo)}`;\n return res.redirect(loginUrl);\n }\n\n // User is authenticated, continue\n next();\n } catch (error) {\n next(error);\n }\n };\n}\n","import { Request, Response, NextFunction } from 'express';\nimport { ClaimAuthOptions } from './claim-auth.js';\n\n/**\n * Middleware to check if an array claim includes specific values.\n *\n * Returns 403 Forbidden if the claim doesn't include all required values\n * or user is not authenticated.\n *\n * @param claim - The name of the array claim to check\n * @param values - The values that must be present in the claim array\n * @param options - Optional configuration\n * @returns Express middleware function\n *\n * @example\n * ```typescript\n * // Require user to have specific permissions\n * app.delete('/users/:id', claimIncludes('permissions', ['delete:users']), (req, res) => {\n * res.send('User deleted');\n * });\n *\n * // Require multiple permissions\n * app.post('/admin/users', claimIncludes('permissions', ['create:users', 'admin:access']), (req, res) => {\n * res.send('User created');\n * });\n *\n * // Check roles\n * app.get('/dashboard', claimIncludes('roles', ['editor', 'admin']), (req, res) => {\n * res.send('Dashboard');\n * });\n * ```\n */\nexport function claimIncludes(claim: string, values: unknown[], options?: ClaimAuthOptions) {\n return async (req: Request, res: Response, next: NextFunction) => {\n try {\n const user = await req.auth0.client.getUser();\n\n if (!user) {\n return res.status(401).json({\n error: 'unauthorized',\n message: 'Authentication required',\n });\n }\n\n const claimValue = (user as Record<string, unknown>)[claim];\n\n if (!Array.isArray(claimValue)) {\n return res.status(options?.statusCode || 403).json({\n error: 'forbidden',\n message: options?.errorMessage || `Access denied`,\n });\n }\n\n const hasAllValues = values.every((value) => claimValue.includes(value));\n\n if (!hasAllValues) {\n return res.status(options?.statusCode || 403).json({\n error: 'forbidden',\n message: options?.errorMessage || `Access denied`,\n });\n }\n\n next();\n } catch (error) {\n next(error);\n }\n };\n}\n","import { Request, Response, NextFunction } from 'express';\nimport { ClaimAuthOptions, JSONPrimitive } from './claim-auth.js';\n\n/**\n * Middleware to check if a claim equals a specific value.\n *\n * Returns 403 Forbidden if the claim doesn't match or user is not authenticated.\n *\n * @param claim - The name of the claim to check\n * @param value - The expected value of the claim\n * @param options - Optional configuration\n * @returns Express middleware function\n *\n * @example\n * ```typescript\n * // Require user to be an admin\n * app.get('/admin', claimEquals('role', 'admin'), (req, res) => {\n * res.send('Admin dashboard');\n * });\n *\n * // Check organization membership\n * app.get('/org', claimEquals('org_id', 'org_123'), (req, res) => {\n * res.send('Organization page');\n * });\n * ```\n */\nexport function claimEquals(claim: string, value: JSONPrimitive, options?: ClaimAuthOptions) {\n return async (req: Request, res: Response, next: NextFunction) => {\n try {\n const user = await req.auth0.client.getUser();\n\n if (!user) {\n return res.status(401).json({\n error: 'unauthorized',\n message: 'Authentication required',\n });\n }\n\n const claimValue = (user as Record<string, unknown>)[claim];\n\n if (claimValue !== value) {\n return res.status(options?.statusCode || 403).json({\n error: 'forbidden',\n message: options?.errorMessage || `Access denied`,\n });\n }\n\n next();\n } catch (error) {\n next(error);\n }\n };\n}","import { Request, Response, NextFunction } from 'express';\nimport { ClaimAuthOptions, ClaimCheckFunction } from './claim-auth.js';\n\n/**\n * Middleware to check claims using a custom validation function.\n *\n * Returns 403 Forbidden if the validation function returns false\n * or user is not authenticated.\n *\n * @param checkFn - A function that receives the user claims and returns true if authorized\n * @param options - Optional configuration\n * @returns Express middleware function\n *\n * @example\n * ```typescript\n * // Custom claim validation\n * app.get('/premium', claimCheck((claims) => {\n * return claims.subscription === 'premium' && !claims.subscription_expired;\n * }), (req, res) => {\n * res.send('Premium content');\n * });\n *\n * // Complex authorization logic\n * app.delete('/posts/:id', claimCheck(async (claims) => {\n * const postId = req.params.id;\n * const post = await getPost(postId);\n * return claims.sub === post.authorId || claims.role === 'admin';\n * }), (req, res) => {\n * res.send('Post deleted');\n * });\n *\n * // With custom error message\n * app.get('/beta', claimCheck(\n * (claims) => claims.beta_access === true,\n * { errorMessage: 'Beta access required' }\n * ), (req, res) => {\n * res.send('Beta features');\n * });\n * ```\n */\nexport function claimCheck(checkFn: ClaimCheckFunction, options?: ClaimAuthOptions) {\n return async (req: Request, res: Response, next: NextFunction) => {\n try {\n const user = await req.auth0.client.getUser();\n\n if (!user) {\n return res.status(401).json({\n error: 'unauthorized',\n message: 'Authentication required',\n });\n }\n\n const isAuthorized = await checkFn(user as Record<string, unknown>);\n\n if (!isAuthorized) {\n return res.status(options?.statusCode || 403).json({\n error: 'forbidden',\n message: options?.errorMessage || 'Access denied',\n });\n }\n\n next();\n } catch (error) {\n next(error);\n }\n };\n}"],"mappings":";AAAA,SAAS,cAA+C;AACxD,OAAO,kBAAkB;;;ACDzB,SAAS,wBAAwB,cAAc,oBAAoB,2BAA2B;;;ACA9F,SAAS,yBAAyB;AAalC,IAAM,oBAAoB,IAAI,kBAAkC;AAkBzD,SAAS,eACd,SACA,UACG;AACH,SAAO,kBAAkB,IAAI,SAAS,QAAQ;AAChD;AAaO,SAAS,oBAAoC;AAClD,QAAM,UAAU,kBAAkB,SAAS;AAE3C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IAMF;AAAA,EACF;AAEA,SAAO;AACT;;;ACpDO,IAAM,uBAAN,MAAkE;AAAA,EACvE,UAAU,MAAc,OAAe,SAAkC,cAAmC;AAC1G,UAAM,EAAE,SAAS,IAAI,gB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O;AAAA,UACP,SAAS,SAAS,gBAAgB;AAAA,QACpC,CAAC;AAAA,MACH;AAEA,WAAK;AAAA,IACP,SAAS,OAAO;AACd,WAAK,KAAK;AAAA,IACZ;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"file":"index.js","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;AAGzD,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Request } from 'express';
|
|
2
|
+
/**
|
|
3
|
+
* Type for a function that checks claims and returns true if authorized.
|
|
4
|
+
*
|
|
5
|
+
* @param req - The Express request, for authorization logic that depends on the
|
|
6
|
+
* request (e.g. route params, query, headers).
|
|
7
|
+
* @param claims - The authenticated user's claims.
|
|
8
|
+
*/
|
|
9
|
+
export type ClaimCheckFunction = (req: Request, claims: Record<string, unknown>) => boolean | Promise<boolean>;
|
|
10
|
+
/**
|
|
11
|
+
* Options for claim-based authorization middleware.
|
|
12
|
+
*/
|
|
13
|
+
export interface ClaimAuthOptions {
|
|
14
|
+
/**
|
|
15
|
+
* Custom error message to send when authorization fails.
|
|
16
|
+
*/
|
|
17
|
+
errorMessage?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Custom status code to return when authorization fails.
|
|
20
|
+
* Default: 403 (Forbidden)
|
|
21
|
+
*/
|
|
22
|
+
statusCode?: number;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Primitive JSON types that can be compared.
|
|
26
|
+
*/
|
|
27
|
+
export type JSONPrimitive = string | number | boolean | null;
|
|
28
|
+
//# sourceMappingURL=claim-auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claim-auth.d.ts","sourceRoot":"","sources":["../../src/middleware/claim-auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAEvC;;;;;;GAMG;AACH,MAAM,MAAM,kBAAkB,GAAG,CAC/B,GAAG,EAAE,OAAO,EACZ,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC5B,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAEhC;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claim-auth.js","sourceRoot":"","sources":["../../src/middleware/claim-auth.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Request, Response, NextFunction } from 'express';
|
|
2
|
+
import { ClaimAuthOptions, ClaimCheckFunction } from './claim-auth.js';
|
|
3
|
+
/**
|
|
4
|
+
* Middleware to check claims using a custom validation function.
|
|
5
|
+
*
|
|
6
|
+
* Returns 403 Forbidden if the validation function returns false
|
|
7
|
+
* or user is not authenticated.
|
|
8
|
+
*
|
|
9
|
+
* @param checkFn - A function that receives the Express request and the user
|
|
10
|
+
* claims and returns true if authorized
|
|
11
|
+
* @param options - Optional configuration
|
|
12
|
+
* @returns Express middleware function
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* // Custom claim validation
|
|
17
|
+
* app.get('/premium', claimCheck((req, claims) => {
|
|
18
|
+
* return claims.subscription === 'premium' && !claims.subscription_expired;
|
|
19
|
+
* }), (req, res) => {
|
|
20
|
+
* res.send('Premium content');
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* // Complex authorization logic using the request
|
|
24
|
+
* app.delete('/posts/:id', claimCheck(async (req, claims) => {
|
|
25
|
+
* const post = await getPost(req.params.id);
|
|
26
|
+
* return claims.sub === post.authorId || claims.role === 'admin';
|
|
27
|
+
* }), (req, res) => {
|
|
28
|
+
* res.send('Post deleted');
|
|
29
|
+
* });
|
|
30
|
+
*
|
|
31
|
+
* // With custom error message
|
|
32
|
+
* app.get('/beta', claimCheck(
|
|
33
|
+
* (req, claims) => claims.beta_access === true,
|
|
34
|
+
* { errorMessage: 'Beta access required' }
|
|
35
|
+
* ), (req, res) => {
|
|
36
|
+
* res.send('Beta features');
|
|
37
|
+
* });
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare function claimCheck(checkFn: ClaimCheckFunction, options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
|
|
41
|
+
//# sourceMappingURL=claim-check.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claim-check.d.ts","sourceRoot":"","sources":["../../src/middleware/claim-check.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,kBAAkB,EAAE,OAAO,CAAC,EAAE,gBAAgB,IAClE,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,6DAyB9D"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Middleware to check claims using a custom validation function.
|
|
3
|
+
*
|
|
4
|
+
* Returns 403 Forbidden if the validation function returns false
|
|
5
|
+
* or user is not authenticated.
|
|
6
|
+
*
|
|
7
|
+
* @param checkFn - A function that receives the Express request and the user
|
|
8
|
+
* claims and returns true if authorized
|
|
9
|
+
* @param options - Optional configuration
|
|
10
|
+
* @returns Express middleware function
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* // Custom claim validation
|
|
15
|
+
* app.get('/premium', claimCheck((req, claims) => {
|
|
16
|
+
* return claims.subscription === 'premium' && !claims.subscription_expired;
|
|
17
|
+
* }), (req, res) => {
|
|
18
|
+
* res.send('Premium content');
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* // Complex authorization logic using the request
|
|
22
|
+
* app.delete('/posts/:id', claimCheck(async (req, claims) => {
|
|
23
|
+
* const post = await getPost(req.params.id);
|
|
24
|
+
* return claims.sub === post.authorId || claims.role === 'admin';
|
|
25
|
+
* }), (req, res) => {
|
|
26
|
+
* res.send('Post deleted');
|
|
27
|
+
* });
|
|
28
|
+
*
|
|
29
|
+
* // With custom error message
|
|
30
|
+
* app.get('/beta', claimCheck(
|
|
31
|
+
* (req, claims) => claims.beta_access === true,
|
|
32
|
+
* { errorMessage: 'Beta access required' }
|
|
33
|
+
* ), (req, res) => {
|
|
34
|
+
* res.send('Beta features');
|
|
35
|
+
* });
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export function claimCheck(checkFn, options) {
|
|
39
|
+
return async (req, res, next) => {
|
|
40
|
+
try {
|
|
41
|
+
const user = await req.auth0.client.getUser();
|
|
42
|
+
if (!user) {
|
|
43
|
+
return res.status(401).json({
|
|
44
|
+
error: 'unauthorized',
|
|
45
|
+
message: 'Authentication required',
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
const isAuthorized = await checkFn(req, user);
|
|
49
|
+
if (!isAuthorized) {
|
|
50
|
+
return res.status(options?.statusCode || 403).json({
|
|
51
|
+
error: 'forbidden',
|
|
52
|
+
message: options?.errorMessage || 'Access denied',
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
next();
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
next(error);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=claim-check.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claim-check.js","sourceRoot":"","sources":["../../src/middleware/claim-check.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,MAAM,UAAU,UAAU,CAAC,OAA2B,EAAE,OAA0B;IAChF,OAAO,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;QAC/D,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YAE9C,IAAI,CAAC,IAAI,EAAE,CAAC;gBACV,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;oBAC1B,KAAK,EAAE,cAAc;oBACrB,OAAO,EAAE,yBAAyB;iBACnC,CAAC,CAAC;YACL,CAAC;YAED,MAAM,YAAY,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE,IAA+B,CAAC,CAAC;YAEzE,IAAI,CAAC,YAAY,EAAE,CAAC;gBAClB,OAAO,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,UAAU,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC;oBACjD,KAAK,EAAE,WAAW;oBAClB,OAAO,EAAE,OAAO,EAAE,YAAY,IAAI,eAAe;iBAClD,CAAC,CAAC;YACL,CAAC;YAED,IAAI,EAAE,CAAC;QACT,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,KAAK,CAAC,CAAC;QACd,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Request, Response, NextFunction } from 'express';
|
|
2
|
+
import { ClaimAuthOptions, JSONPrimitive } from './claim-auth.js';
|
|
3
|
+
/**
|
|
4
|
+
* Middleware to check if a claim equals a specific value.
|
|
5
|
+
*
|
|
6
|
+
* Returns 403 Forbidden if the claim doesn't match or user is not authenticated.
|
|
7
|
+
*
|
|
8
|
+
* @param claim - The name of the claim to check
|
|
9
|
+
* @param value - The expected value of the claim
|
|
10
|
+
* @param options - Optional configuration
|
|
11
|
+
* @returns Express middleware function
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* // Require user to be an admin
|
|
16
|
+
* app.get('/admin', claimEquals('role', 'admin'), (req, res) => {
|
|
17
|
+
* res.send('Admin dashboard');
|
|
18
|
+
* });
|
|
19
|
+
*
|
|
20
|
+
* // Check organization membership
|
|
21
|
+
* app.get('/org', claimEquals('org_id', 'org_123'), (req, res) => {
|
|
22
|
+
* res.send('Organization page');
|
|
23
|
+
* });
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export declare function claimEquals(claim: string, value: JSONPrimitive, options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
|
|
27
|
+
//# sourceMappingURL=claim-equals.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claim-equals.d.ts","sourceRoot":"","sources":["../../src/middleware/claim-equals.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAElE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,OAAO,CAAC,EAAE,gBAAgB,IAC3E,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,6DAyB9D"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Middleware to check if a claim equals a specific value.
|
|
3
|
+
*
|
|
4
|
+
* Returns 403 Forbidden if the claim doesn't match or user is not authenticated.
|
|
5
|
+
*
|
|
6
|
+
* @param claim - The name of the claim to check
|
|
7
|
+
* @param value - The expected value of the claim
|
|
8
|
+
* @param options - Optional configuration
|
|
9
|
+
* @returns Express middleware function
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```typescript
|
|
13
|
+
* // Require user to be an admin
|
|
14
|
+
* app.get('/admin', claimEquals('role', 'admin'), (req, res) => {
|
|
15
|
+
* res.send('Admin dashboard');
|
|
16
|
+
* });
|
|
17
|
+
*
|
|
18
|
+
* // Check organization membership
|
|
19
|
+
* app.get('/org', claimEquals('org_id', 'org_123'), (req, res) => {
|
|
20
|
+
* res.send('Organization page');
|
|
21
|
+
* });
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export function claimEquals(claim, value, options) {
|
|
25
|
+
return async (req, res, next) => {
|
|
26
|
+
try {
|
|
27
|
+
const user = await req.auth0.client.getUser();
|
|
28
|
+
if (!user) {
|
|
29
|
+
return res.status(401).json({
|
|
30
|
+
error: 'unauthorized',
|
|
31
|
+
message: 'Authentication required',
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
const claimValue = user[claim];
|
|
35
|
+
if (claimValue !== value) {
|
|
36
|
+
return res.status(options?.statusCode || 403).json({
|
|
37
|
+
error: 'forbidden',
|
|
38
|
+
message: options?.errorMessage || `Access denied`,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
next();
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
next(error);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=claim-equals.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claim-equals.js","sourceRoot":"","sources":["../../src/middleware/claim-equals.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa,EAAE,KAAoB,EAAE,OAA0B;IACzF,OAAO,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;QAC/D,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YAE9C,IAAI,CAAC,IAAI,EAAE,CAAC;gBACV,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;oBAC1B,KAAK,EAAE,cAAc;oBACrB,OAAO,EAAE,yBAAyB;iBACnC,CAAC,CAAC;YACL,CAAC;YAED,MAAM,UAAU,GAAI,IAAgC,CAAC,KAAK,CAAC,CAAC;YAE5D,IAAI,UAAU,KAAK,KAAK,EAAE,CAAC;gBACzB,OAAO,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,UAAU,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC;oBACjD,KAAK,EAAE,WAAW;oBAClB,OAAO,EAAE,OAAO,EAAE,YAAY,IAAI,eAAe;iBAClD,CAAC,CAAC;YACL,CAAC;YAED,IAAI,EAAE,CAAC;QACT,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,KAAK,CAAC,CAAC;QACd,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Request, Response, NextFunction } from 'express';
|
|
2
|
+
import { ClaimAuthOptions } from './claim-auth.js';
|
|
3
|
+
/**
|
|
4
|
+
* Middleware to check if a claim includes specific values.
|
|
5
|
+
*
|
|
6
|
+
* The claim may be an array, or a space-delimited string (such as a
|
|
7
|
+
* scope-style `"read:users delete:users"` claim), which is split on spaces
|
|
8
|
+
* before checking.
|
|
9
|
+
*
|
|
10
|
+
* Returns 403 Forbidden if the claim doesn't include all required values
|
|
11
|
+
* or user is not authenticated.
|
|
12
|
+
*
|
|
13
|
+
* @param claim - The name of the claim to check
|
|
14
|
+
* @param values - The values that must be present in the claim
|
|
15
|
+
* @param options - Optional configuration
|
|
16
|
+
* @returns Express middleware function
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```typescript
|
|
20
|
+
* // Require user to have specific permissions
|
|
21
|
+
* app.delete('/users/:id', claimIncludes('permissions', ['delete:users']), (req, res) => {
|
|
22
|
+
* res.send('User deleted');
|
|
23
|
+
* });
|
|
24
|
+
*
|
|
25
|
+
* // Require multiple permissions
|
|
26
|
+
* app.post('/admin/users', claimIncludes('permissions', ['create:users', 'admin:access']), (req, res) => {
|
|
27
|
+
* res.send('User created');
|
|
28
|
+
* });
|
|
29
|
+
*
|
|
30
|
+
* // Check roles
|
|
31
|
+
* app.get('/dashboard', claimIncludes('roles', ['editor', 'admin']), (req, res) => {
|
|
32
|
+
* res.send('Dashboard');
|
|
33
|
+
* });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export declare function claimIncludes(claim: string, values: unknown[], options?: ClaimAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
|
|
37
|
+
//# sourceMappingURL=claim-includes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claim-includes.d.ts","sourceRoot":"","sources":["../../src/middleware/claim-includes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,OAAO,CAAC,EAAE,gBAAgB,IAC1E,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,6DAuC9D"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Middleware to check if a claim includes specific values.
|
|
3
|
+
*
|
|
4
|
+
* The claim may be an array, or a space-delimited string (such as a
|
|
5
|
+
* scope-style `"read:users delete:users"` claim), which is split on spaces
|
|
6
|
+
* before checking.
|
|
7
|
+
*
|
|
8
|
+
* Returns 403 Forbidden if the claim doesn't include all required values
|
|
9
|
+
* or user is not authenticated.
|
|
10
|
+
*
|
|
11
|
+
* @param claim - The name of the claim to check
|
|
12
|
+
* @param values - The values that must be present in the claim
|
|
13
|
+
* @param options - Optional configuration
|
|
14
|
+
* @returns Express middleware function
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* // Require user to have specific permissions
|
|
19
|
+
* app.delete('/users/:id', claimIncludes('permissions', ['delete:users']), (req, res) => {
|
|
20
|
+
* res.send('User deleted');
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* // Require multiple permissions
|
|
24
|
+
* app.post('/admin/users', claimIncludes('permissions', ['create:users', 'admin:access']), (req, res) => {
|
|
25
|
+
* res.send('User created');
|
|
26
|
+
* });
|
|
27
|
+
*
|
|
28
|
+
* // Check roles
|
|
29
|
+
* app.get('/dashboard', claimIncludes('roles', ['editor', 'admin']), (req, res) => {
|
|
30
|
+
* res.send('Dashboard');
|
|
31
|
+
* });
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export function claimIncludes(claim, values, options) {
|
|
35
|
+
return async (req, res, next) => {
|
|
36
|
+
try {
|
|
37
|
+
const user = await req.auth0.client.getUser();
|
|
38
|
+
if (!user) {
|
|
39
|
+
return res.status(401).json({
|
|
40
|
+
error: 'unauthorized',
|
|
41
|
+
message: 'Authentication required',
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
const rawClaim = user[claim];
|
|
45
|
+
// Accept both array claims and space-delimited string claims
|
|
46
|
+
// (e.g. scope-style `"read:users delete:users"`).
|
|
47
|
+
const claimValue = typeof rawClaim === 'string' ? rawClaim.split(' ') : rawClaim;
|
|
48
|
+
if (!Array.isArray(claimValue)) {
|
|
49
|
+
return res.status(options?.statusCode || 403).json({
|
|
50
|
+
error: 'forbidden',
|
|
51
|
+
message: options?.errorMessage || `Access denied`,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
const hasAllValues = values.every((value) => claimValue.includes(value));
|
|
55
|
+
if (!hasAllValues) {
|
|
56
|
+
return res.status(options?.statusCode || 403).json({
|
|
57
|
+
error: 'forbidden',
|
|
58
|
+
message: options?.errorMessage || `Access denied`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
next();
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
next(error);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=claim-includes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claim-includes.js","sourceRoot":"","sources":["../../src/middleware/claim-includes.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa,EAAE,MAAiB,EAAE,OAA0B;IACxF,OAAO,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;QAC/D,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YAE9C,IAAI,CAAC,IAAI,EAAE,CAAC;gB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requiresAuth middleware.
|
|
4
|
+
*/
|
|
5
|
+
export interface RequiresAuthOptions {
|
|
6
|
+
/**
|
|
7
|
+
* If true, returns a 401 status instead of redirecting to login.
|
|
8
|
+
* Useful for API routes that should not redirect.
|
|
9
|
+
*
|
|
10
|
+
* Default: false (redirects to login)
|
|
11
|
+
*/
|
|
12
|
+
returnTo?: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Middleware to require authentication for a route.
|
|
16
|
+
*
|
|
17
|
+
* If the user is not authenticated:
|
|
18
|
+
* - For HTML requests (browser): Redirects to /auth/login with returnTo parameter
|
|
19
|
+
* - For API requests (JSON): Returns 401 Unauthorized
|
|
20
|
+
*
|
|
21
|
+
* @param options - Optional configuration for the middleware
|
|
22
|
+
* @returns Express middleware function
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```typescript
|
|
26
|
+
* // Protect a route
|
|
27
|
+
* app.get('/profile', requiresAuth(), (req, res) => {
|
|
28
|
+
* res.json({ user: await req.auth0.client.getUser() });
|
|
29
|
+
* });
|
|
30
|
+
*
|
|
31
|
+
* // Protect an API route (returns 401 instead of redirecting)
|
|
32
|
+
* app.get('/api/me', requiresAuth(), async (req, res) => {
|
|
33
|
+
* const user = await req.auth0.client.getUser();
|
|
34
|
+
* res.json({ user });
|
|
35
|
+
* });
|
|
36
|
+
*
|
|
37
|
+
* // Custom return URL after login
|
|
38
|
+
* app.get('/admin', requiresAuth({ returnTo: '/admin' }), (req, res) => {
|
|
39
|
+
* res.send('Admin page');
|
|
40
|
+
* });
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export declare function requiresAuth(options?: RequiresAuthOptions): (req: Request, res: Response, next: NextFunction) => Promise<void | Response<any, Record<string, any>>>;
|
|
44
|
+
//# sourceMappingURL=require-auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"require-auth.d.ts","sourceRoot":"","sources":["../../src/middleware/require-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE1D;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,YAAY,CAAC,OAAO,CAAC,EAAE,mBAAmB,IAC1C,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,wDA4B9D"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Middleware to require authentication for a route.
|
|
3
|
+
*
|
|
4
|
+
* If the user is not authenticated:
|
|
5
|
+
* - For HTML requests (browser): Redirects to /auth/login with returnTo parameter
|
|
6
|
+
* - For API requests (JSON): Returns 401 Unauthorized
|
|
7
|
+
*
|
|
8
|
+
* @param options - Optional configuration for the middleware
|
|
9
|
+
* @returns Express middleware function
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```typescript
|
|
13
|
+
* // Protect a route
|
|
14
|
+
* app.get('/profile', requiresAuth(), (req, res) => {
|
|
15
|
+
* res.json({ user: await req.auth0.client.getUser() });
|
|
16
|
+
* });
|
|
17
|
+
*
|
|
18
|
+
* // Protect an API route (returns 401 instead of redirecting)
|
|
19
|
+
* app.get('/api/me', requiresAuth(), async (req, res) => {
|
|
20
|
+
* const user = await req.auth0.client.getUser();
|
|
21
|
+
* res.json({ user });
|
|
22
|
+
* });
|
|
23
|
+
*
|
|
24
|
+
* // Custom return URL after login
|
|
25
|
+
* app.get('/admin', requiresAuth({ returnTo: '/admin' }), (req, res) => {
|
|
26
|
+
* res.send('Admin page');
|
|
27
|
+
* });
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export function requiresAuth(options) {
|
|
31
|
+
return async (req, res, next) => {
|
|
32
|
+
try {
|
|
33
|
+
const user = await req.auth0.client.getUser();
|
|
34
|
+
if (!user) {
|
|
35
|
+
// Check if this is an API request (wants JSON response)
|
|
36
|
+
const acceptsJson = req.accepts('json') && !req.accepts('html');
|
|
37
|
+
if (acceptsJson) {
|
|
38
|
+
return res.status(401).json({
|
|
39
|
+
error: 'unauthorized',
|
|
40
|
+
message: 'Authentication required',
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
// For HTML requests, redirect to login with returnTo
|
|
44
|
+
const returnTo = options?.returnTo || req.originalUrl;
|
|
45
|
+
const loginPath = req.app.locals.auth0ClientOptions?.routes?.login || '/auth/login';
|
|
46
|
+
const loginUrl = `${loginPath}?returnTo=${encodeURIComponent(returnTo)}`;
|
|
47
|
+
return res.redirect(loginUrl);
|
|
48
|
+
}
|
|
49
|
+
// User is authenticated, continue
|
|
50
|
+
next();
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
next(error);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=require-auth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"require-auth.js","sourceRoot":"","sources":["../../src/middleware/require-auth.ts"],"names":[],"mappings":"AAeA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,UAAU,YAAY,CAAC,OAA6B;IACxD,OAAO,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;QAC/D,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YAE9C,IAAI,CAAC,IAAI,EAAE,CAAC;gBACV,wDAAwD;gBACxD,MAAM,WAAW,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;gBAEhE,IAAI,WAAW,EAAE,CAAC;oBAChB,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;wBAC1B,KAAK,EAAE,cAAc;wBACrB,OAAO,EAAE,yBAAyB;qBACnC,CAAC,CAAC;gBACL,CAAC;gBAED,qDAAqD;gBACrD,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,GAAG,CAAC,WAAW,CAAC;gBACtD,MAAM,SAAS,GAAG,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,kBAAkB,EAAE,MAAM,EAAE,KAAK,IAAI,aAAa,CAAC;gBACpF,MAAM,QAAQ,GAAG,GAAG,SAAS,aAAa,kBAAkB,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACzE,OAAO,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;YAChC,CAAC;YAED,kCAAkC;YAClC,IAAI,EAAE,CAAC;QACT,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,KAAK,CAAC,CAAC;QACd,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
|
package/dist/router.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import type { Auth0Options } from './types.js';
|
|
3
|
+
import './types/express.js';
|
|
4
|
+
/**
|
|
5
|
+
* Creates an Express router with Auth0 authentication middleware.
|
|
6
|
+
*
|
|
7
|
+
* This is the main entry point for the Auth0 Express SDK. It configures
|
|
8
|
+
* authentication routes and attaches the Auth0 client to the request object.
|
|
9
|
+
*
|
|
10
|
+
* @param opts - Configuration options for Auth0 authentication
|
|
11
|
+
* @returns Express Router configured with Auth0 authentication
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import express from 'express';
|
|
16
|
+
* import { createAuth0 } from '@auth0/auth0-express';
|
|
17
|
+
*
|
|
18
|
+
* const app = express();
|
|
19
|
+
*
|
|
20
|
+
* // Using environment variables (AUTH0_DOMAIN, AUTH0_CLIENT_ID, etc.)
|
|
21
|
+
* app.use(createAuth0());
|
|
22
|
+
*
|
|
23
|
+
* // Or with explicit configuration
|
|
24
|
+
* app.use(createAuth0({
|
|
25
|
+
* domain: 'tenant.auth0.com',
|
|
26
|
+
* clientId: 'your_client_id',
|
|
27
|
+
* clientSecret: 'your_client_secret',
|
|
28
|
+
* appBaseUrl: 'http://localhost:3000',
|
|
29
|
+
* sessionSecret: process.env.SESSION_SECRET
|
|
30
|
+
* }));
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare function createAuth0(opts?: Partial<Auth0Options>): Router;
|
|
34
|
+
//# sourceMappingURL=router.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAmC,MAAM,SAAS,CAAC;AAElE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAQ/C,OAAO,oBAAoB,CAAC;AAE5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,WAAW,CAAC,IAAI,GAAE,OAAO,CAAC,YAAY,CAAM,GAAG,MAAM,CA2CpE"}
|