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
This commit is contained in:
Thomas Camlong committed 2026-06-07 01:45:28 +02:00
1 parent 873444fe48
commit 311fd2356a
8 files changed
+176 -146

No files matched your search

+4 -4
View File
@@ -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:"
@@ -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
<TableTr key={tool.name}>
{isDesktop && (
<TableTd>
<Badge size="xs" radius="xs" variant="light" color={tool.type === "query" ? "blue" : "orange"}>
{tool.type === "query" ? "GET" : "POST"}
<Badge size="xs" radius="xs" variant="light" color={toolTypeDisplay[tool.type].color}>
{toolTypeDisplay[tool.type].method}
</Badge>
</TableTd>
)}
@@ -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<string, { _def?: { type?: string } }>;
@@ -17,19 +17,40 @@ import packageJson from "../../../../../../../package.json";
const logger = createLogger({ module: "mcpRoute" });
const authFailures = new Map<string, { count: number; resetAt: number }>();
const AUTH_RATE_WINDOW_MS = 60_000;
const AUTH_MAX_FAILURES = 10;
interface RateLimitStore {
authFailures: Map<string, { count: number; resetAt: number }>;
cleanupTimer: ReturnType<typeof setInterval> | 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<ReturnType<typeof mcpRouter.createCaller>>();
@@ -81,6 +97,30 @@ function getTools() {
return toolsCache;
}
const SAFE_ERROR_MESSAGES: Record<string, string> = {
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<any>((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<string, string>, extraHeaders: Record<string, string> = {}) {
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 '<id>.<token>'.",
}),
{ status: 401, headers: { "Content-Type": "application/json" } },
);
return jsonErrorResponse(401, { error: "invalid_token", hint: "The token must be in the format '<id>.<token>'." });
}
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 });
@@ -1,15 +1,30 @@
import { registerClient } from "../_store";
const registerAttempts = new Map<string, { count: number; resetAt: number }>();
interface RateLimitStore {
attempts: Map<string, { count: number; resetAt: number }>;
timer: ReturnType<typeof setInterval> | 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 },
);
}
@@ -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<string, { count: number; resetAt: number }>();
const logger = createLogger({ module: "mcpOAuthToken" });
interface RateLimitStore {
failures: Map<string, { count: number; resetAt: number }>;
timer: ReturnType<typeof setInterval> | 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<string, string>;
try {
const body = await req.formData().catch(() => null);
@@ -55,10 +71,7 @@ export async function POST(req: Request) {
: ((await req.json()) as Record<string, string>);
} 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 },
);
}
}
@@ -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");
@@ -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();
}),
});