fix: Proxy Mintlify traffic through a Next.js API route (#25320)

* hotfix

* type fix and test fix

* update env example

* improvements

* more fix

* tada

---------

Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
Syed Ali ShahbazandKeith Williams authored and GitHub committed 2025-11-21 18:43:09 +00:00
1 parent 0d77fc8474
commit a7d87fc5be
8 files changed
+853 -48

No files matched your search

+3 -6
View File
@@ -17,7 +17,6 @@ import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { isMac } from "@calcom/lib/isMac";
import { trpc } from "@calcom/trpc/react";
import type { RouterOutputs } from "@calcom/trpc/react";
import { Icon } from "@calcom/ui/components/icon";
import { Tooltip } from "@calcom/ui/components/tooltip";
@@ -27,9 +26,6 @@ type shortcutArrayType = {
shortcuts?: string[];
};
type EventTypeGroups = RouterOutputs["viewer"]["eventTypes"]["getByViewer"]["eventTypeGroups"];
type EventTypeGroup = EventTypeGroups[number];
const getApps = Object.values(appStoreMetadata).map(({ name, slug }) => ({
id: slug,
name,
@@ -242,7 +238,6 @@ export const KBarRoot = ({ children }: { children: React.ReactNode }) => {
},
...appStoreActions,
];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <KBarProvider actions={actions}>{children}</KBarProvider>;
@@ -253,7 +248,9 @@ export const KBarContent = () => {
useEventTypesAction();
const [inputText, setInputText] = useState("");
const [aiResponse, setAiResponse] = useState("");
const showAiChat = process.env.NEXT_PUBLIC_MINTLIFY_CHAT_API_KEY && process.env.NEXT_PUBLIC_CHAT_API_URL;
const showAiChat =
process.env.NEXT_PUBLIC_ENABLE_MINTLIFY_CHAT === "true" &&
!!process.env.NEXT_PUBLIC_CHAT_API_URL;
return (
<KBarPortal>
+48 -40
View File
@@ -1,35 +1,45 @@
/**
* This file contains utility functions for interacting with the Mintlify chat API.
* The code was adapted from https://mintlify.com/docs/advanced/rest-api/overview#getting-started. The original source can be found at https://github.com/mintlify/discovery-api-example/tree/main/src/utils.
*
* NOTE: These functions now call our internal proxy API routes at /api/mintlify-chat/*
* instead of calling Mintlify directly. This keeps the API key secure on the server side.
*/
const API_KEY = process.env.NEXT_PUBLIC_MINTLIFY_CHAT_API_KEY;
const apiBaseUrl = process.env.NEXT_PUBLIC_CHAT_API_URL;
/**
* Creates a new Mintlify chat topic via our internal proxy
*/
export const createChat = async () => {
if (!API_KEY || !apiBaseUrl) return;
try {
const topicResponse = await fetch("/api/mintlify-chat/topic", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const topicResponse = await fetch(`${apiBaseUrl}/topic`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
});
if (!topicResponse.ok) {
console.error("Failed to create chat topic:", topicResponse.statusText);
return;
}
if (!topicResponse.ok) {
return;
}
const topic: unknown = await topicResponse.json();
const topic: unknown = await topicResponse.json();
if (topic && typeof topic === "object" && "topicId" in topic && typeof topic.topicId === "string") {
return topic.topicId;
} else {
if (topic && typeof topic === "object" && "topicId" in topic && typeof topic.topicId === "string") {
return topic.topicId;
} else {
return undefined;
}
} catch (error) {
console.error("Error creating chat topic:", error);
return undefined;
}
};
/**
* Generates a response from Mintlify via our internal proxy
* Streams the response back to the caller in chunks
*/
export const generateResponse = async ({
topicId,
userQuery,
@@ -39,37 +49,35 @@ export const generateResponse = async ({
userQuery: string;
onChunkReceived: (chunk: string, baseUrl?: string, finalChunk?: boolean) => void;
}) => {
if (!API_KEY || !apiBaseUrl) return;
const queryResponse = await fetch(
`
${apiBaseUrl}/message`,
{
try {
const queryResponse = await fetch("/api/mintlify-chat/message", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
body: JSON.stringify({ message: userQuery, topicId }),
});
if (!queryResponse.ok || !queryResponse.body) {
throw Error(queryResponse.statusText);
}
);
const streamReader = queryResponse.body.getReader();
if (!queryResponse.ok || !queryResponse.body) {
throw Error(queryResponse.statusText);
}
const streamReader = queryResponse.body.getReader();
for (;;) {
const { done, value } = await streamReader.read();
if (done) {
onChunkReceived("", queryResponse.headers.get("x-mintlify-base-url") ?? "", true);
return;
}
for (;;) {
const { done, value } = await streamReader.read();
if (done) {
const newValue = new TextDecoder().decode(value);
onChunkReceived(newValue, queryResponse.headers.get("X-Mintlify-Base-Url") ?? "", true);
return;
onChunkReceived(newValue);
}
const newValue = new TextDecoder().decode(value);
onChunkReceived(newValue);
} catch (error) {
console.error("Error generating response:", error);
throw error;
}
};
@@ -0,0 +1,147 @@
/**
* Validation and sanitization helpers for Mintlify chat proxy
*
* This module provides security utilities to validate user input before
* proxying requests to the Mintlify API, preventing:
* - Path traversal attacks
* - Control character injection
* - Malicious payloads
* - Oversized requests
*/
const MAX_MESSAGE_LENGTH = 10000; // 10KB max message length
const MAX_TOPIC_ID_LENGTH = 200;
const PATH_TRAVERSAL_PATTERNS = ["../", "..\\"]; // basic sequences we never expect inside identifiers
const stripControlCharacters = (input: string) => {
if (typeof input !== "string") {
throw new Error("Input must be a string");
}
// Remove null bytes
let sanitized = input.replace(/\0/g, "");
// Remove other control characters (except newlines, tabs, carriage returns which might be needed in messages)
// eslint-disable-next-line no-control-regex
sanitized = sanitized.replace(/[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F]/g, "");
return sanitized;
};
/**
* Sanitizes free-form user messages by stripping control characters.
* This intentionally does not reject path-like substrings so users can ask about "../".
*/
export function sanitizeMessageString(input: string): string {
return stripControlCharacters(input);
}
/**
* Sanitizes identifiers (topic IDs) and rejects path traversal attempts.
*/
export function sanitizeTopicIdentifier(input: string): string {
const sanitized = stripControlCharacters(input);
// Check for path traversal attempts
if (PATH_TRAVERSAL_PATTERNS.some((pattern) => sanitized.includes(pattern))) {
throw new Error("Path traversal detected");
}
return sanitized;
}
/**
* Validates a chat message payload for the /message endpoint
*/
export function validateChatMessage(payload: unknown): {
message: string;
topicId: string;
} {
if (!payload || typeof payload !== "object") {
throw new Error("Invalid payload: must be an object");
}
const { message, topicId } = payload as Record<string, unknown>;
// Validate message
if (typeof message !== "string") {
throw new Error("Invalid message: must be a string");
}
if (message.length === 0) {
throw new Error("Invalid message: cannot be empty");
}
if (message.length > MAX_MESSAGE_LENGTH) {
throw new Error(`Invalid message: exceeds maximum length of ${MAX_MESSAGE_LENGTH} characters`);
}
// Validate topicId
if (typeof topicId !== "string") {
throw new Error("Invalid topicId: must be a string");
}
if (topicId.length === 0) {
throw new Error("Invalid topicId: cannot be empty");
}
if (topicId.length > MAX_TOPIC_ID_LENGTH) {
throw new Error(`Invalid topicId: exceeds maximum length of ${MAX_TOPIC_ID_LENGTH} characters`);
}
// Sanitize both fields
const sanitizedMessage = sanitizeMessageString(message);
const sanitizedTopicId = sanitizeTopicIdentifier(topicId);
// Validate topicId format (alphanumeric, dashes, underscores only)
if (!/^[a-zA-Z0-9_-]+$/.test(sanitizedTopicId)) {
throw new Error("Invalid topicId: must contain only alphanumeric characters, dashes, and underscores");
}
return {
message: sanitizedMessage,
topicId: sanitizedTopicId,
};
}
/**
* Validates that the API key and base URL are configured
*/
export function validateMintlifyConfig(): {
apiKey: string;
apiBaseUrl: string;
} {
const apiKey = process.env.MINTLIFY_CHAT_API_KEY;
const rawApiBaseUrl = process.env.NEXT_PUBLIC_CHAT_API_URL;
const apiBaseUrl = rawApiBaseUrl?.replace(/\/+$/, "");
if (!apiKey) {
throw new Error("MINTLIFY_CHAT_API_KEY is not configured");
}
if (!apiBaseUrl) {
throw new Error("NEXT_PUBLIC_CHAT_API_URL is not configured");
}
return { apiKey, apiBaseUrl };
}
/**
* Sanitizes response headers before sending to client
* Only allows safe headers through
*/
export function sanitizeResponseHeaders(headers: Headers): Record<string, string> {
const allowedHeaders = ["content-type", "x-mintlify-base-url"];
const sanitized: Record<string, string> = {};
allowedHeaders.forEach((header) => {
const value = headers.get(header);
if (value) {
sanitized[header] = value;
}
});
return sanitized;
}