Spaces:
Runtime error
Runtime error
Download apps/api/src/middleware/auth.ts from ClaraSu/llm-router: direct link, hf CLI and curl.
- Browser
- Download file 1.97 kB
-
https://huggingface.co/spaces/ClaraSu/llm-router/resolve/main/apps/api/src/middleware/auth.ts
- Command line
-
hf download hf://spaces/ClaraSu/llm-router/apps/api/src/middleware/auth.ts
-
curl -L -o auth.ts https://huggingface.co/spaces/ClaraSu/llm-router/resolve/main/apps/api/src/middleware/auth.ts
1.97 kB
| import type { Response, NextFunction, RequestHandler } from 'express' | |
| import { requireAuth, type AuthenticatedRequest } from '@llm-router/auth-client' | |
| /** | |
| * Wraps a JWT-verifying middleware (e.g. `requireAuth()` from | |
| * `@llm-router/auth-client`) with the pre-existing exemptions: | |
| * | |
| * - `/health` never requires auth. | |
| * - A request presenting `INTERNAL_SECRET` (via `x-internal-key` or as the | |
| * bearer token) bypasses JWT verification entirely — this is the trusted | |
| * internal-service path (e.g. the slip-queue GitHub Actions worker). It | |
| * still populates `req.auth` with a full-access synthetic identity so | |
| * downstream `requirePermission()` checks (e.g. on `/chat/completions`) | |
| * pass instead of rejecting an unauthenticated-looking request. | |
| * | |
| * Everything else is delegated to `jwtVerifier`, which is responsible for | |
| * populating `req.auth` on success or responding 401 on failure. | |
| */ | |
| export function createAuthMiddleware(jwtVerifier: RequestHandler): RequestHandler { | |
| return async (req: AuthenticatedRequest, res: Response, next: NextFunction) => { | |
| if (req.path === '/health') { | |
| next() | |
| return | |
| } | |
| const key = req.headers['x-internal-key'] as string | undefined | |
| const bearerToken = (req.headers['authorization'] as string | undefined) | |
| ?.replace(/^Bearer\s+/i, '') | |
| .trim() | |
| const expectedKey = process.env['INTERNAL_SECRET'] | |
| if (expectedKey && (key === expectedKey || bearerToken === expectedKey)) { | |
| req.auth = { userId: 'internal-service', tenantId: 'internal-service', role: 'admin' } | |
| next() | |
| return | |
| } | |
| await jwtVerifier(req, res, next) | |
| } | |
| } | |
| const PORT = parseInt(process.env['PORT'] ?? '7860', 10) | |
| const jwksUrl = process.env['AUTH_JWKS_URL'] ?? `http://localhost:${PORT}/auth/jwks` | |
| /** The auth middleware wired into `proxy.ts`, backed by the real auth service's JWKS endpoint. */ | |
| export const auth: RequestHandler = createAuthMiddleware(requireAuth({ jwksUrl })) | |