UNPKG

@kya-os/mcp-i

Version:

The TypeScript MCP framework with identity features built-in

52 lines (51 loc) 1.73 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.jwtAuthMiddleware = jwtAuthMiddleware; const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); /** * Middleware to authenticate requests using a JWT. * @param config - Configuration object containing the JWT secret and verify options. * @returns Express middleware function. * * @example * ```ts * const middleware = jwtAuthMiddleware({ * secret: process.env.JWT_SECRET!, * algorithms: ["HS256"], * issuer: "https://example.com", * audience: "https://example.com", * subject: "user-id", * expiresIn: "1h", * notBefore: "1h", * clockTolerance: 30, * }); * ``` */ function jwtAuthMiddleware(config) { return (req, res, next) => { const authHeader = req.header("Authorization"); if (!authHeader || !authHeader.startsWith("Bearer ")) { res.status(401).json({ error: "Unauthorized: Missing or malformed Authorization header", }); return; } const token = authHeader.slice("Bearer ".length).trim(); if (!token) { res.status(401).json({ error: "Unauthorized: Missing access token" }); return; } try { const { secret, ...verifyOptions } = config; const decoded = jsonwebtoken_1.default.verify(token, secret, verifyOptions); req.user = decoded; next(); } catch { res.status(401).json({ error: "Unauthorized: Invalid or expired token" }); } }; }