From 311fd2356a9a6566996e116b14bd690b1043723e Mon Sep 17 00:00:00 2001 From: Thomas Camlong Date: Sun, 7 Jun 2026 01:45:28 +0200 Subject: [PATCH] fix(mcp): harden MCP route security and code quality - Sanitize error messages to prevent leaking internal details - Add isError flag to tool-not-found and no-caller responses - Guard against undefined procedure before invocation - Clear auth rate limit on successful authentication - Move setInterval timers to globalThis to prevent dev hot-reload leaks - Add try/catch + logging to OAuth token exchange - Deduplicate auth error responses with helper function - Replace ternary operators with lookup tables in UI - Remove console.error monkey-patch for trpc-to-mcp warnings - Use lookup table for media request answer actions --- apps/nextjs/package.json | 8 +- .../tools/api/components/mcp-instructions.tsx | 9 +- .../app/[locale]/manage/tools/api/page.tsx | 7 - .../src/app/api/mcp/[transport]/route.ts | 141 ++++++++++-------- .../src/app/api/mcp/oauth/register/route.ts | 54 +++---- .../src/app/api/mcp/oauth/token/route.ts | 89 ++++++----- .../router/integration/integration-router.ts | 2 - .../api/src/router/widgets/media-requests.ts | 12 +- 8 files changed, 176 insertions(+), 146 deletions(-) diff --git a/apps/nextjs/package.json b/apps/nextjs/package.json index ea3a268c6..61377ff7e 100644 --- a/apps/nextjs/package.json +++ b/apps/nextjs/package.json @@ -56,6 +56,8 @@ "@mantine/hooks": "catalog:", "@mantine/modals": "catalog:", "@mantine/tiptap": "catalog:", + "@modelcontextprotocol/sdk": "catalog:", + "@scalar/api-reference-react": "catalog:", "@tabler/icons-react": "catalog:", "@tanstack/react-query": "catalog:", "@tanstack/react-query-devtools": "catalog:", @@ -76,10 +78,8 @@ "glob": "catalog:", "isomorphic-dompurify": "catalog:", "jotai": "catalog:", - "mcp-handler": "catalog:", - "@modelcontextprotocol/sdk": "catalog:", - "trpc-to-mcp": "catalog:", "mantine-react-table": "catalog:", + "mcp-handler": "catalog:", "next": "catalog:", "postcss-preset-mantine": "catalog:", "prismjs": "catalog:", @@ -89,7 +89,7 @@ "react-simple-code-editor": "catalog:", "sass": "catalog:", "superjson": "catalog:", - "@scalar/api-reference-react": "catalog:", + "trpc-to-mcp": "catalog:", "use-deep-compare-effect": "catalog:", "yaml": "catalog:", "zod": "catalog:" diff --git a/apps/nextjs/src/app/[locale]/manage/tools/api/components/mcp-instructions.tsx b/apps/nextjs/src/app/[locale]/manage/tools/api/components/mcp-instructions.tsx index b697d020a..6c862cdb0 100644 --- a/apps/nextjs/src/app/[locale]/manage/tools/api/components/mcp-instructions.tsx +++ b/apps/nextjs/src/app/[locale]/manage/tools/api/components/mcp-instructions.tsx @@ -51,6 +51,11 @@ import { useScopedI18n } from "@homarr/translation/client"; import { CopyApiKeyModal } from "./copy-api-key-modal"; import type { McpToolGroup } from "./api-page-tabs"; +const toolTypeDisplay: Record<"query" | "mutation", { color: string; method: string }> = { + query: { color: "blue", method: "GET" }, + mutation: { color: "orange", method: "POST" }, +}; + interface McpInstructionsProps { baseUrl: string; hasApiKeys: boolean; @@ -313,8 +318,8 @@ export function McpInstructions({ baseUrl, hasApiKeys, toolGroups }: McpInstruct {isDesktop && ( - - {tool.type === "query" ? "GET" : "POST"} + + {toolTypeDisplay[tool.type].method} )} diff --git a/apps/nextjs/src/app/[locale]/manage/tools/api/page.tsx b/apps/nextjs/src/app/[locale]/manage/tools/api/page.tsx index 7df6c1707..fe0a4f248 100644 --- a/apps/nextjs/src/app/[locale]/manage/tools/api/page.tsx +++ b/apps/nextjs/src/app/[locale]/manage/tools/api/page.tsx @@ -22,14 +22,7 @@ let cachedToolGroups: McpToolGroup[] | null = null; function getMcpToolGroups(): McpToolGroup[] { if (cachedToolGroups) return cachedToolGroups; - const originalError = console.error; - console.error = (...args: unknown[]) => { - if (typeof args[0] === "string" && args[0].includes("[TRPC-TO-MCP]")) return; - originalError(...args); - }; - const tools = extractToolsFromProcedures(mcpRouter); - console.error = originalError; // eslint-disable-next-line @typescript-eslint/no-explicit-any const procedures = (mcpRouter as any)._def.procedures as Record; diff --git a/apps/nextjs/src/app/api/mcp/[transport]/route.ts b/apps/nextjs/src/app/api/mcp/[transport]/route.ts index 0b5aeb416..a1f22839f 100644 --- a/apps/nextjs/src/app/api/mcp/[transport]/route.ts +++ b/apps/nextjs/src/app/api/mcp/[transport]/route.ts @@ -17,19 +17,40 @@ import packageJson from "../../../../../../../package.json"; const logger = createLogger({ module: "mcpRoute" }); -const authFailures = new Map(); const AUTH_RATE_WINDOW_MS = 60_000; const AUTH_MAX_FAILURES = 10; +interface RateLimitStore { + authFailures: Map; + cleanupTimer: ReturnType | null; +} + +const globalRateLimit = globalThis as unknown as { mcpRateLimit?: RateLimitStore }; +if (!globalRateLimit.mcpRateLimit) { + globalRateLimit.mcpRateLimit = { + authFailures: new Map(), + cleanupTimer: null, + }; +} +// eslint-disable-next-line @typescript-eslint/no-non-null-assertion +const rateLimitStore = globalRateLimit.mcpRateLimit!; +const authFailures = rateLimitStore.authFailures; + +if (!rateLimitStore.cleanupTimer) { + rateLimitStore.cleanupTimer = setInterval(() => { + const now = Date.now(); + for (const [key, entry] of authFailures) { + if (entry.resetAt < now) authFailures.delete(key); + } + }, AUTH_RATE_WINDOW_MS); + rateLimitStore.cleanupTimer.unref(); +} + function checkAuthRateLimit(ip: string | null): boolean { const key = ip ?? "unknown"; const now = Date.now(); const entry = authFailures.get(key); - - if (!entry || entry.resetAt < now) { - return true; - } - + if (!entry || entry.resetAt < now) return true; return entry.count < AUTH_MAX_FAILURES; } @@ -37,21 +58,16 @@ function recordAuthFailure(ip: string | null) { const key = ip ?? "unknown"; const now = Date.now(); const entry = authFailures.get(key); - if (!entry || entry.resetAt < now) { authFailures.set(key, { count: 1, resetAt: now + AUTH_RATE_WINDOW_MS }); return; } - entry.count++; } -setInterval(() => { - const now = Date.now(); - for (const [key, entry] of authFailures) { - if (entry.resetAt < now) authFailures.delete(key); - } -}, AUTH_RATE_WINDOW_MS); +function clearAuthFailures(ip: string | null) { + authFailures.delete(ip ?? "unknown"); +} const callerStorage = new AsyncLocalStorage>(); @@ -81,6 +97,30 @@ function getTools() { return toolsCache; } +const SAFE_ERROR_MESSAGES: Record = { + UNAUTHORIZED: "You do not have permission to perform this action", + FORBIDDEN: "Access denied", + NOT_FOUND: "The requested resource was not found", + BAD_REQUEST: "Invalid request parameters", + INTERNAL_SERVER_ERROR: "An internal error occurred", + TIMEOUT: "The operation timed out", + TOO_MANY_REQUESTS: "Rate limit exceeded, try again later", + CONFLICT: "A conflict occurred with the current state", + PRECONDITION_FAILED: "A precondition for this operation was not met", +}; + +function sanitizeErrorMessage(error: unknown): string { + if (error instanceof Error && "code" in error) { + const trpcCode = (error as Error & { code: string }).code; + const safeMessage = SAFE_ERROR_MESSAGES[trpcCode]; + if (safeMessage) return safeMessage; + } + if (error instanceof Error && error.message.length < 200 && !error.message.includes("/")) { + return error.message; + } + return "Tool execution failed"; +} + const SERVER_INSTRUCTIONS = `You are connected to Homarr, a self-hosted homelab dashboard. ## Key Concepts @@ -137,35 +177,35 @@ const mcpHandler = createMcpHandler( if (!tool) { return { content: [{ type: "text" as const, text: `Tool "${name}" not found` }], + isError: true, }; } const caller = callerStorage.getStore(); if (!caller) { return { - content: [ - { - type: "text" as const, - text: "Authentication context not available", - }, - ], + content: [{ type: "text" as const, text: "Authentication context not available" }], + isError: true, }; } try { // eslint-disable-next-line @typescript-eslint/no-explicit-any const procedure = tool.pathInRouter.reduce((acc, part) => acc?.[part], caller); + if (typeof procedure !== "function") { + return { + content: [{ type: "text" as const, text: `Tool "${name}" is not callable` }], + isError: true, + }; + } const input = args && Object.keys(args).length > 0 ? args : undefined; const result = await procedure(input); return { content: [{ type: "text" as const, text: JSON.stringify(result) }], }; } catch (error) { - const message = error instanceof Error ? error.message : "Unknown error"; - logger.warn("MCP tool execution failed", { - tool: name, - error: message, - }); + const message = sanitizeErrorMessage(error); + logger.warn("MCP tool execution failed", { tool: name, error: error instanceof Error ? error.message : String(error) }); return { content: [{ type: "text" as const, text: JSON.stringify({ error: message }) }], isError: true, @@ -197,66 +237,45 @@ function extractApiKeyValue(req: NextRequest): string | null { return null; } +function jsonErrorResponse(status: number, body: Record, extraHeaders: Record = {}) { + return new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json", ...extraHeaders }, + }); +} + const handler = async (req: NextRequest) => { const apiKeyValue = extractApiKeyValue(req); const ipAddress = ipAddressFromHeaders(req.headers); const { ua } = userAgent(req); if (!checkAuthRateLimit(ipAddress)) { - return new Response( - JSON.stringify({ - error: "rate_limited", - hint: "Too many failed authentication attempts. Try again later.", - }), - { - status: 429, - headers: { "Content-Type": "application/json", "Retry-After": "60" }, - }, - ); + return jsonErrorResponse(429, { error: "rate_limited", hint: "Too many failed authentication attempts. Try again later." }, { "Retry-After": "60" }); } if (!apiKeyValue) { recordAuthFailure(ipAddress); const baseUrl = extractBaseUrlFromHeaders(req.headers); - return new Response( - JSON.stringify({ - error: "unauthorized", - hint: "Authenticate with an ApiKey header or via OAuth at /.well-known/oauth-authorization-server", - }), - { - status: 401, - headers: { - "Content-Type": "application/json", - "WWW-Authenticate": `Bearer resource_metadata="${baseUrl}/.well-known/oauth-protected-resource"`, - }, - }, + return jsonErrorResponse( + 401, + { error: "unauthorized", hint: "Authenticate with an ApiKey header or via OAuth at /.well-known/oauth-authorization-server" }, + { "WWW-Authenticate": `Bearer resource_metadata="${baseUrl}/.well-known/oauth-protected-resource"` }, ); } if (!apiKeyValue.includes(".")) { recordAuthFailure(ipAddress); - return new Response( - JSON.stringify({ - error: "invalid_token", - hint: "The token must be in the format '.'.", - }), - { status: 401, headers: { "Content-Type": "application/json" } }, - ); + return jsonErrorResponse(401, { error: "invalid_token", hint: "The token must be in the format '.'." }); } const session = await getSessionFromApiKeyAsync(db, apiKeyValue, ipAddress, ua); if (!session) { recordAuthFailure(ipAddress); - return new Response( - JSON.stringify({ - error: "invalid_token", - hint: "The API key was not found or the token is incorrect.", - }), - { status: 401, headers: { "Content-Type": "application/json" } }, - ); + return jsonErrorResponse(401, { error: "invalid_token", hint: "The API key was not found or the token is incorrect." }); } + clearAuthFailures(ipAddress); logger.info("MCP request authenticated", { userId: session.user.id }); const ctx = createTRPCContext({ session, headers: req.headers }); diff --git a/apps/nextjs/src/app/api/mcp/oauth/register/route.ts b/apps/nextjs/src/app/api/mcp/oauth/register/route.ts index 5c7a3f34a..47f00a4f7 100644 --- a/apps/nextjs/src/app/api/mcp/oauth/register/route.ts +++ b/apps/nextjs/src/app/api/mcp/oauth/register/route.ts @@ -1,15 +1,30 @@ import { registerClient } from "../_store"; -const registerAttempts = new Map(); +interface RateLimitStore { + attempts: Map; + timer: ReturnType | null; +} + const REGISTER_RATE_WINDOW_MS = 60_000; const REGISTER_MAX_ATTEMPTS = 5; -setInterval(() => { - const now = Date.now(); - for (const [key, entry] of registerAttempts) { - if (entry.resetAt < now) registerAttempts.delete(key); - } -}, REGISTER_RATE_WINDOW_MS); +const globalStore = globalThis as unknown as { mcpRegisterRateLimit?: RateLimitStore }; +if (!globalStore.mcpRegisterRateLimit) { + globalStore.mcpRegisterRateLimit = { attempts: new Map(), timer: null }; +} +// eslint-disable-next-line @typescript-eslint/no-non-null-assertion +const store = globalStore.mcpRegisterRateLimit!; +const registerAttempts = store.attempts; + +if (!store.timer) { + store.timer = setInterval(() => { + const now = Date.now(); + for (const [key, entry] of registerAttempts) { + if (entry.resetAt < now) registerAttempts.delete(key); + } + }, REGISTER_RATE_WINDOW_MS); + store.timer.unref(); +} function getClientIp(req: Request): string { const forwarded = req.headers.get("x-forwarded-for"); @@ -32,20 +47,14 @@ export async function POST(req: Request) { if (entry && entry.resetAt >= now && entry.count >= REGISTER_MAX_ATTEMPTS) { return Response.json( - { - error: "rate_limited", - error_description: "Too many registration attempts, try again later", - }, + { error: "rate_limited", error_description: "Too many registration attempts, try again later" }, { status: 429, headers: { "Retry-After": "60" } }, ); } const existing = registerAttempts.get(ip); if (!existing || existing.resetAt < now) { - registerAttempts.set(ip, { - count: 1, - resetAt: now + REGISTER_RATE_WINDOW_MS, - }); + registerAttempts.set(ip, { count: 1, resetAt: now + REGISTER_RATE_WINDOW_MS }); } else { existing.count++; } @@ -60,10 +69,7 @@ export async function POST(req: Request) { if (!Array.isArray(redirectUris) || redirectUris.length === 0 || redirectUris.length > 10) { return Response.json( - { - error: "invalid_client_metadata", - error_description: "redirect_uris must be an array of 1-10 URIs", - }, + { error: "invalid_client_metadata", error_description: "redirect_uris must be an array of 1-10 URIs" }, { status: 400 }, ); } @@ -71,10 +77,7 @@ export async function POST(req: Request) { const validUris = redirectUris.filter((uri): uri is string => typeof uri === "string" && isValidRedirectUri(uri)); if (validUris.length !== redirectUris.length) { return Response.json( - { - error: "invalid_client_metadata", - error_description: "All redirect_uris must be valid http or https URLs", - }, + { error: "invalid_client_metadata", error_description: "All redirect_uris must be valid http or https URLs" }, { status: 400 }, ); } @@ -82,10 +85,7 @@ export async function POST(req: Request) { const result = registerClient(validUris, clientName); if (!result) { return Response.json( - { - error: "server_error", - error_description: "Too many registered clients, please try again later", - }, + { error: "server_error", error_description: "Too many registered clients, please try again later" }, { status: 503 }, ); } diff --git a/apps/nextjs/src/app/api/mcp/oauth/token/route.ts b/apps/nextjs/src/app/api/mcp/oauth/token/route.ts index 8c07aa6e6..6153d1cf6 100644 --- a/apps/nextjs/src/app/api/mcp/oauth/token/route.ts +++ b/apps/nextjs/src/app/api/mcp/oauth/token/route.ts @@ -2,21 +2,39 @@ import { randomBytes } from "crypto"; import { hashPasswordAsync } from "@homarr/auth"; import { generateSecureRandomToken } from "@homarr/common/server"; +import { createLogger } from "@homarr/core/infrastructure/logs"; import { db } from "@homarr/db"; import { apiKeys } from "@homarr/db/schema"; import { consumeAuthCode, verifyPkce } from "../_store"; -const tokenFailures = new Map(); +const logger = createLogger({ module: "mcpOAuthToken" }); + +interface RateLimitStore { + failures: Map; + timer: ReturnType | null; +} + const TOKEN_RATE_WINDOW_MS = 60_000; const TOKEN_MAX_FAILURES = 10; -setInterval(() => { - const now = Date.now(); - for (const [key, entry] of tokenFailures) { - if (entry.resetAt < now) tokenFailures.delete(key); - } -}, TOKEN_RATE_WINDOW_MS); +const globalStore = globalThis as unknown as { mcpTokenRateLimit?: RateLimitStore }; +if (!globalStore.mcpTokenRateLimit) { + globalStore.mcpTokenRateLimit = { failures: new Map(), timer: null }; +} +// eslint-disable-next-line @typescript-eslint/no-non-null-assertion +const store = globalStore.mcpTokenRateLimit!; +const tokenFailures = store.failures; + +if (!store.timer) { + store.timer = setInterval(() => { + const now = Date.now(); + for (const [key, entry] of tokenFailures) { + if (entry.resetAt < now) tokenFailures.delete(key); + } + }, TOKEN_RATE_WINDOW_MS); + store.timer.unref(); +} function getClientIp(req: Request): string { const forwarded = req.headers.get("x-forwarded-for"); @@ -40,13 +58,11 @@ export async function POST(req: Request) { if (entry && entry.resetAt >= now && entry.count >= TOKEN_MAX_FAILURES) { return Response.json( - { - error: "rate_limited", - error_description: "Too many requests, try again later", - }, + { error: "rate_limited", error_description: "Too many requests, try again later" }, { status: 429, headers: { "Retry-After": "60" } }, ); } + let params: Record; try { const body = await req.formData().catch(() => null); @@ -55,10 +71,7 @@ export async function POST(req: Request) { : ((await req.json()) as Record); } catch { return Response.json( - { - error: "invalid_request", - error_description: "Could not parse request body", - }, + { error: "invalid_request", error_description: "Could not parse request body" }, { status: 400 }, ); } @@ -71,10 +84,7 @@ export async function POST(req: Request) { if (!code || !code_verifier) { return Response.json( - { - error: "invalid_request", - error_description: "Missing code or code_verifier", - }, + { error: "invalid_request", error_description: "Missing code or code_verifier" }, { status: 400 }, ); } @@ -87,10 +97,7 @@ export async function POST(req: Request) { if (!authCode) { recordTokenFailure(ip); return Response.json( - { - error: "invalid_grant", - error_description: "Invalid or expired authorization code", - }, + { error: "invalid_grant", error_description: "Invalid or expired authorization code" }, { status: 400 }, ); } @@ -105,21 +112,29 @@ export async function POST(req: Request) { return Response.json({ error: "invalid_grant", error_description: "PKCE verification failed" }, { status: 400 }); } - const id = randomBytes(4).toString("hex"); - const randomToken = generateSecureRandomToken(24); - const hashedToken = await hashPasswordAsync(randomToken); + try { + const id = randomBytes(4).toString("hex"); + const randomToken = generateSecureRandomToken(24); + const hashedToken = await hashPasswordAsync(randomToken); - await db.insert(apiKeys).values({ - id, - apiKey: hashedToken, - userId: authCode.userId, - }); + await db.insert(apiKeys).values({ + id, + apiKey: hashedToken, + userId: authCode.userId, + }); - const accessToken = `${id}.${randomToken}`; + const accessToken = `${id}.${randomToken}`; - return Response.json({ - access_token: accessToken, - token_type: "Bearer", - scope: "mcp:tools", - }); + return Response.json({ + access_token: accessToken, + token_type: "Bearer", + scope: "mcp:tools", + }); + } catch (error) { + logger.error("Failed to create API key during OAuth token exchange", { error: error instanceof Error ? error.message : String(error) }); + return Response.json( + { error: "server_error", error_description: "Failed to issue access token" }, + { status: 500 }, + ); + } } diff --git a/packages/api/src/router/integration/integration-router.ts b/packages/api/src/router/integration/integration-router.ts index 784445721..c5dd9a9b6 100644 --- a/packages/api/src/router/integration/integration-router.ts +++ b/packages/api/src/router/integration/integration-router.ts @@ -367,8 +367,6 @@ export const integrationRouter = createTRPCRouter({ kind: input.kind, url: input.url, }); - - // Media request search is a first-class Spotlight action. Do not create a search engine for it. }), update: protectedProcedure.input(integrationUpdateSchema).mutation(async ({ ctx, input }) => { await throwIfActionForbiddenAsync(ctx, eq(integrations.id, input.id), "full"); diff --git a/packages/api/src/router/widgets/media-requests.ts b/packages/api/src/router/widgets/media-requests.ts index 9e7278ea8..715ae1327 100644 --- a/packages/api/src/router/widgets/media-requests.ts +++ b/packages/api/src/router/widgets/media-requests.ts @@ -141,12 +141,12 @@ export const mediaRequestsRouter = createTRPCRouter({ const integrationInstance = await createIntegrationAsync(integration); const innerHandler = mediaRequestListRequestHandler.handler(integration, {}); - if (input.answer === "approve") { - await integrationInstance.approveRequestAsync(input.requestId); - await innerHandler.invalidateAsync(); - return; - } - await integrationInstance.declineRequestAsync(input.requestId); + const answerActions = { + approve: (id: number) => integrationInstance.approveRequestAsync(id), + decline: (id: number) => integrationInstance.declineRequestAsync(id), + } as const; + + await answerActions[input.answer](input.requestId); await innerHandler.invalidateAsync(); }), });