chore: remove Mintlify AI chat from CMD+K widget (#26485)
* chore: remove Mintlify AI chat from CMD+K widget - Remove MintlifyChat component and related state from Kbar.tsx - Delete packages/features/mintlify-chat directory (MintlifyChat.tsx, util.ts) - Delete apps/web/app/api/mintlify-chat API routes and tests - Delete packages/lib/server/mintlifyChatValidation.ts - Remove Mintlify-related env vars from .env.example and turbo.json - Refactor Kbar.tsx to fix lint issues (explicit types, exports at end) Co-Authored-By: [email protected] <[email protected]> * fix: use ReactNode import instead of JSX from react The JSX type is not exported from 'react' module. Use the global JSX.Element type (available in React projects) and import ReactNode for the children prop type. Co-Authored-By: [email protected] <[email protected]> * feat: add all event-types and upcoming bookings to KBar - Increase event types limit from 10 to 100 to show more event types - Add useUpcomingBookingsAction hook to fetch and display upcoming bookings - Bookings show title, date, and time in KBar search results - Navigate to booking details page when selecting a booking Co-Authored-By: [email protected] <[email protected]> * Revert "feat: add all event-types and upcoming bookings to KBar" This reverts commit 69d03397e3820e45e7207eb55b38117d269eae5e. --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
9 files changed
+136
-1344
No files matched your search
@@ -1,101 +0,0 @@
|
||||
/* eslint-disable react/no-danger */
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { SkeletonText, SkeletonContainer } from "@calcom/ui/components/skeleton";
|
||||
|
||||
import { getFormattedCitations, handleAiChat, optionallyAddBaseUrl } from "../mintlify-chat/util";
|
||||
|
||||
interface MintlifyChatProps {
|
||||
searchText: string;
|
||||
aiResponse: string;
|
||||
setAiResponse: Dispatch<SetStateAction<string>>;
|
||||
}
|
||||
|
||||
export const MintlifyChat = ({ searchText, aiResponse, setAiResponse }: MintlifyChatProps) => {
|
||||
const { t } = useLocale();
|
||||
const [topicId, setTopicId] = useState("");
|
||||
const [baseUrl, setBaseUrl] = useState(process.env.NEXT_PUBLIC_DOCS_URL ?? "");
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const onChunkReceived = (chunk: string, baseUrl?: string, finalChunk?: boolean) => {
|
||||
setAiResponse((prev) => {
|
||||
return prev + chunk;
|
||||
});
|
||||
if (baseUrl) {
|
||||
setBaseUrl(baseUrl);
|
||||
}
|
||||
if (finalChunk) {
|
||||
setIsGenerating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const citations = getFormattedCitations(aiResponse.split("||")[1]) ?? [];
|
||||
const answer = aiResponse.split("||")[0] ?? "";
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
onClick={async () => {
|
||||
if (isGenerating) return;
|
||||
setIsGenerating(true);
|
||||
setAiResponse("");
|
||||
setError("");
|
||||
const { id, error } = await handleAiChat(onChunkReceived, searchText, topicId);
|
||||
if (id) {
|
||||
setTopicId(id);
|
||||
} else if (error) {
|
||||
setIsGenerating(false);
|
||||
setError(error);
|
||||
}
|
||||
}}
|
||||
className={classNames(
|
||||
"hover:bg-subtle flex items-center gap-3 px-4 py-2 transition",
|
||||
isGenerating ? "cursor-not-allowed" : "cursor-pointer"
|
||||
)}>
|
||||
<div>
|
||||
<Icon name="star" />
|
||||
</div>
|
||||
<div>
|
||||
<div>
|
||||
{t("can_you_tell_me_about")} <span className="font-bold">{searchText}</span>
|
||||
</div>
|
||||
<div className="text-subtle text-sm">{t("use_ai_to_answer_your_questions")}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-2 px-4 text-sm">
|
||||
{error && <p className="mt-1 text-xs text-red-500">{error}</p>}
|
||||
{isGenerating && aiResponse === "" ? (
|
||||
<SkeletonContainer>
|
||||
<SkeletonText className="h-12 w-full" />
|
||||
</SkeletonContainer>
|
||||
) : (
|
||||
<>
|
||||
<div dangerouslySetInnerHTML={{ __html: markdownToSafeHTML(answer) }} />
|
||||
<div className="my-1 flex flex-wrap gap-2">
|
||||
{baseUrl &&
|
||||
citations.map((citation) => {
|
||||
if (citation.title) {
|
||||
const url = optionallyAddBaseUrl(baseUrl, citation.url);
|
||||
return (
|
||||
<a key={url} href={url} target="_blank">
|
||||
<div className="flex h-6 items-center gap-1 rounded-md bg-gray-100 px-1.5 text-xs text-gray-700 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
{citation.title}
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,205 +0,0 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Mintlify chat topic via our internal proxy
|
||||
*/
|
||||
export const createChat = async () => {
|
||||
try {
|
||||
const topicResponse = await fetch("/api/mintlify-chat/topic", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!topicResponse.ok) {
|
||||
console.error("Failed to create chat topic:", topicResponse.statusText);
|
||||
return;
|
||||
}
|
||||
|
||||
const topic: unknown = await topicResponse.json();
|
||||
|
||||
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,
|
||||
onChunkReceived,
|
||||
}: {
|
||||
topicId: string;
|
||||
userQuery: string;
|
||||
onChunkReceived: (chunk: string, baseUrl?: string, finalChunk?: boolean) => void;
|
||||
}) => {
|
||||
try {
|
||||
const queryResponse = await fetch("/api/mintlify-chat/message", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ message: userQuery, topicId }),
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
const newValue = new TextDecoder().decode(value);
|
||||
onChunkReceived(newValue);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error generating response:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const handleAiChat = async (
|
||||
onChunkReceived: (chunk: string, baseUrl?: string, finalChunk?: boolean) => void,
|
||||
userQuery: string,
|
||||
topicId?: string
|
||||
) => {
|
||||
let id = null;
|
||||
let error = "";
|
||||
try {
|
||||
if (!topicId) {
|
||||
id = await createChat();
|
||||
}
|
||||
|
||||
if (!id)
|
||||
return {
|
||||
id,
|
||||
error: "Error creating topic. Please try again later",
|
||||
};
|
||||
|
||||
await generateResponse({
|
||||
topicId: id,
|
||||
onChunkReceived,
|
||||
userQuery,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof Error) {
|
||||
error = err.message;
|
||||
} else {
|
||||
error = "k_bar_ai_error";
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
error,
|
||||
};
|
||||
};
|
||||
|
||||
type ChunkMetadata = {
|
||||
id: string;
|
||||
link?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
chunk_html?: string;
|
||||
};
|
||||
|
||||
export const generateDeeplink = (chunkMetadata: ChunkMetadata) => {
|
||||
if (
|
||||
!(
|
||||
"metadata" in chunkMetadata &&
|
||||
!!chunkMetadata.metadata &&
|
||||
"title" in chunkMetadata.metadata &&
|
||||
"link" in chunkMetadata &&
|
||||
typeof chunkMetadata.link === "string"
|
||||
)
|
||||
)
|
||||
return "";
|
||||
const section = chunkMetadata.metadata.title;
|
||||
const link = optionallyAddLeadingSlash(chunkMetadata.link);
|
||||
if (section && typeof section === "string") {
|
||||
const sectionSlug = section
|
||||
.toLowerCase()
|
||||
.replaceAll(" ", "-")
|
||||
.replaceAll(/[^a-zA-Z0-9-_#]/g, "");
|
||||
|
||||
return `${link}#${sectionSlug}`;
|
||||
}
|
||||
|
||||
return link;
|
||||
};
|
||||
|
||||
type UnformattedCitation = {
|
||||
id: string;
|
||||
link: string;
|
||||
chunk_html: string;
|
||||
metadata: Record<string, string>;
|
||||
};
|
||||
|
||||
export type Citation = {
|
||||
citationNumber: number;
|
||||
title: string;
|
||||
url: string;
|
||||
rootRecordId?: number;
|
||||
rootRecordType?: string;
|
||||
};
|
||||
|
||||
export function getFormattedCitations(rawContent?: string): Citation[] {
|
||||
try {
|
||||
const citations: UnformattedCitation[] = JSON.parse(rawContent ?? "[]");
|
||||
|
||||
const uniqueCitations = new Map(
|
||||
citations.map((citation, index) => {
|
||||
const title = citation.metadata.title ?? "";
|
||||
const formattedCitation = {
|
||||
citationNumber: index,
|
||||
title: citation.metadata.title ?? "",
|
||||
url: generateDeeplink(citation),
|
||||
};
|
||||
|
||||
return [title, formattedCitation];
|
||||
})
|
||||
);
|
||||
|
||||
return Array.from(uniqueCitations.values());
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function optionallyRemoveLeadingSlash(path: string) {
|
||||
return path.startsWith("/") ? path.substring(1) : path;
|
||||
}
|
||||
|
||||
export function optionallyAddLeadingSlash(path: string) {
|
||||
return path.startsWith("/") ? path : `/${path}`;
|
||||
}
|
||||
|
||||
export function optionallyAddBaseUrl(baseUrl: string, url: string) {
|
||||
// absolute urls
|
||||
if (url.startsWith("https://")) return url;
|
||||
|
||||
const urlWithLeadingSlash = optionallyAddLeadingSlash(url);
|
||||
return `${baseUrl}${urlWithLeadingSlash}`;
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user