Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🎨 feat: Theme-Adaptive SVG Support for Custom MCP and Group Icons (#13817)
Marco Beretta10c5c9159420
diff --git a/api/jest.config.js b/api/jest.config.jsindex daa12004d6..f9f03da125 100644--- a/api/jest.config.js+++ b/api/jest.config.js@@ -7,6 +7,13 @@ const esModules = ['@langchain/langgraph-sdk','@mistralai/mistralai','uuid',+ 'sanitize-html',+ 'htmlparser2',+ 'domhandler',+ 'domelementtype',+ 'domutils',+ 'dom-serializer',+ 'entities',].join('|');module.exports = {diff --git a/api/package.json b/api/package.jsonindex bb5fe8efb9..a8eba00ab7 100644--- a/api/package.json+++ b/api/package.json@@ -74,6 +74,7 @@"cookie-parser": "^1.4.7","cors": "^2.8.5","dedent": "^1.5.3",+ "dompurify": "^3.4.12","dotenv": "^16.0.3","eventsource": "^3.0.2","express": "^5.2.1",@@ -89,6 +90,7 @@"https-proxy-agent": "^7.0.6","ioredis": "^5.3.2","js-yaml": "^4.2.0",+ "jsdom": "^26.1.0","jsonwebtoken": "^9.0.0","jszip": "^3.10.1","jwks-rsa": "^3.2.0",diff --git a/api/server/controllers/mcp.js b/api/server/controllers/mcp.jsindex 447c3f1abb..dd871e5731 100644--- a/api/server/controllers/mcp.js+++ b/api/server/controllers/mcp.js@@ -18,6 +18,7 @@ const {normalizeServerName,findShadowedServerNames,redactServerSecrets,+ sanitizeMcpIconPath,redactAllServerSecrets,isMCPDomainNotAllowedError,isMCPInspectionFailedError,@@ -460,6 +461,9 @@ const createMCPServerController = async (req, res) => {errors: validation.error.errors,});}+ if (validation.data.iconPath) {+ validation.data.iconPath = sanitizeMcpIconPath(validation.data.iconPath);+ }if (configHasObo(validation.data) && !(await callerCanConfigureObo(req))) {logger.warn(`[createMCPServer] User ${userId} attempted to configure OBO without ${Permissions.CONFIGURE_OBO} permission`,@@ -549,6 +553,9 @@ const updateMCPServerController = async (req, res) => {errors: validation.error.errors,});}+ if (validation.data.iconPath) {+ validation.data.iconPath = sanitizeMcpIconPath(validation.data.iconPath);+ }/*** On an existing OBO server, lock down every user-input field except thediff --git a/client/src/components/Chat/Menus/Endpoints/components/CustomGroup.tsx b/client/src/components/Chat/Menus/Endpoints/components/CustomGroup.tsxindex 2283174f9d..18eddce5d5 100644--- a/client/src/components/Chat/Menus/Endpoints/components/CustomGroup.tsx+++ b/client/src/components/Chat/Menus/Endpoints/components/CustomGroup.tsx@@ -28,7 +28,7 @@ export function CustomGroup({ groupName, specs, groupIcon }: CustomGroupProps) {<div className="group flex w-full flex-shrink cursor-pointer items-center justify-between rounded-xl px-1 py-1 text-sm"><div className="flex items-center gap-2">{groupIcon && (- <div className="flex-shrink-0">+ <div className="flex-shrink-0" aria-hidden="true"><GroupIcon iconURL={groupIcon} groupName={groupName} /></div>)}diff --git a/client/src/components/Chat/Menus/Endpoints/components/GroupIcon.tsx b/client/src/components/Chat/Menus/Endpoints/components/GroupIcon.tsxindex 41d393c387..2b5980bf92 100644--- a/client/src/components/Chat/Menus/Endpoints/components/GroupIcon.tsx+++ b/client/src/components/Chat/Menus/Endpoints/components/GroupIcon.tsx@@ -3,6 +3,7 @@ import { AlertCircle } from 'lucide-react';import { ProviderIcon } from '@librechat/client';import { resolveProviderId } from 'librechat-data-provider';import { EntityEndpointMark, isEntityEndpoint } from '~/components/Endpoints/EntityEndpointMark';+import CustomIcon from '~/components/ui/CustomIcon';import { isImageURL } from '~/utils/icons';interface GroupIconProps {@@ -44,10 +45,10 @@ const GroupIcon: React.FC<GroupIconProps> = ({ iconURL, groupName }) => {return (<div- className="icon-md shrink-0 overflow-hidden rounded-full"+ className="icon-md shrink-0 overflow-hidden rounded-full text-text-primary"style={{ width: 20, height: 20 }}>- <img+ <CustomIconsrc={iconURL}alt={groupName}className="h-full w-full object-cover"diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsxindex f90dddc493..0c13b73f37 100644--- a/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx+++ b/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx@@ -12,6 +12,7 @@ import {Wrench,} from 'lucide-react';import LangIcon from '~/components/Messages/Content/LangIcon';+import CustomIcon from '~/components/ui/CustomIcon';import { cn } from '~/utils';function BashIcon({ className }: { className?: string }) {@@ -109,15 +110,14 @@ interface ToolIconProps {export default function ToolIcon({ type, iconUrl, isAnimating = false, className }: ToolIconProps) {if (iconUrl) {return (- <img+ <CustomIconsrc={iconUrl}alt=""className={cn(- 'size-4 shrink-0 rounded-full object-cover',+ 'size-4 shrink-0 rounded-full object-cover text-text-secondary',isAnimating && 'animate-pulse',className,)}- aria-hidden="true"/>);}diff --git a/client/src/components/MCP/MCPServerMenuItem.tsx b/client/src/components/MCP/MCPServerMenuItem.tsxindex 3c5cbdcc03..0a77e89f24 100644--- a/client/src/components/MCP/MCPServerMenuItem.tsx+++ b/client/src/components/MCP/MCPServerMenuItem.tsx@@ -10,6 +10,7 @@ import {type ConnectionStatusMap,} from './mcpServerUtils';import MCPServerStatusIcon from './MCPServerStatusIcon';+import CustomIcon from '~/components/ui/CustomIcon';import { useLocalize } from '~/hooks';import { cn } from '~/utils';@@ -58,10 +59,10 @@ export default function MCPServerMenuItem({{/* Server Icon with Status Dot */}<div className="relative flex-shrink-0">{server.config?.iconPath ? (- <img+ <CustomIconsrc={server.config.iconPath}- className="h-8 w-8 rounded-lg object-cover"- alt={displayName}+ className="h-8 w-8 rounded-lg object-cover text-text-primary"+ alt=""/>) : (<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-surface-tertiary">diff --git a/client/src/components/MCP/StackedMCPIcons.tsx b/client/src/components/MCP/StackedMCPIcons.tsxindex fa04928210..e5a02aad39 100644--- a/client/src/components/MCP/StackedMCPIcons.tsx+++ b/client/src/components/MCP/StackedMCPIcons.tsx@@ -2,6 +2,7 @@ import { useMemo } from 'react';import { MCPIcon } from '@librechat/client';import type { MCPServerDefinition } from '~/hooks/MCP/useMCPServerManager';import { getSelectedServerIcons } from './mcpServerUtils';+import CustomIcon from '~/components/ui/CustomIcon';import { cn } from '~/utils';interface StackedMCPIconsProps {@@ -74,10 +75,10 @@ export default function StackedMCPIcons({style={{ zIndex: icons.length - index }}>{icon.iconPath ? (- <img+ <CustomIconsrc={icon.iconPath}alt={icon.displayName}- className={cn('rounded-full object-cover', sizes.icon)}+ className={cn('rounded-full object-cover text-text-primary', sizes.icon)}/>) : (<MCPIcon className={cn('text-text-primary', sizes.icon)} />diff --git a/client/src/components/SidePanel/Agents/MCPIcon.tsx b/client/src/components/SidePanel/Agents/MCPIcon.tsxindex 37c79c8dfd..401eab8d8f 100644--- a/client/src/components/SidePanel/Agents/MCPIcon.tsx+++ b/client/src/components/SidePanel/Agents/MCPIcon.tsx@@ -1,25 +1,19 @@-import { useState, useEffect, useRef } from 'react';+import { useRef } from 'react';import { Button, SquirclePlusIcon } from '@librechat/client';+import CustomIcon from '~/components/ui/CustomIcon';import { useLocalize } from '~/hooks';interface MCPIconProps {icon?: string;onIconChange: (e: React.ChangeEvent<HTMLInputElement>) => void;+ /** Id of the alert explaining a rejected pick. */+ errorId?: string;}-export default function MCPIcon({ icon, onIconChange }: MCPIconProps) {- const [previewUrl, setPreviewUrl] = useState('');+export default function MCPIcon({ icon, onIconChange, errorId }: MCPIconProps) {const fileInputRef = useRef<HTMLInputElement>(null);const localize = useLocalize();- useEffect(() => {- if (icon) {- setPreviewUrl(icon);- } else {- setPreviewUrl('');- }- }, [icon]);-const handleClick = () => {if (fileInputRef.current) {fileInputRef.current.value = '';@@ -33,15 +27,15 @@ export default function MCPIcon({ icon, onIconChange }: MCPIconProps) {variant="ghost"onClick={handleClick}aria-label={localize('com_ui_upload_icon')}+ aria-invalid={errorId != null}+ aria-describedby={errorId}className="flex h-16 w-16 shrink-0 items-center justify-center rounded-xl border-2 border-dashed border-border-medium bg-surface-secondary p-0 hover:bg-surface-hover">- {previewUrl ? (- <img- src={previewUrl}- className="h-full w-full rounded-xl object-cover"- alt="MCP Icon"- width="64"- height="64"+ {icon ? (+ <CustomIcon+ src={icon}+ alt=""+ className="h-full w-full rounded-xl object-cover text-text-primary"/>) : (<SquirclePlusIcon />@@ -54,7 +48,7 @@ export default function MCPIcon({ icon, onIconChange }: MCPIconProps) {<span className="text-xs text-text-secondary">{localize('com_agents_mcp_icon_size')}</span></div><input- accept="image/png,.png,image/jpeg,.jpg,.jpeg,image/gif,.gif,image/webp,.webp"+ accept="image/png,.png,image/jpeg,.jpg,.jpeg,image/gif,.gif,image/webp,.webp,image/svg+xml,.svg"multiple={false}type="file"style={{ display: 'none' }}diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerCard.tsx b/client/src/components/SidePanel/MCPBuilder/MCPServerCard.tsxindex 79b996b695..e93c9781b6 100644--- a/client/src/components/SidePanel/MCPBuilder/MCPServerCard.tsx+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerCard.tsx@@ -5,6 +5,7 @@ import type { MCPServerStatusIconProps } from '~/components/MCP/MCPServerStatusIimport type { MCPServerDefinition } from '~/hooks';import { useMCPServerManager, useLocalize } from '~/hooks';import { getStatusDotColor } from './MCPStatusBadge';+import CustomIcon from '~/components/ui/CustomIcon';import MCPServerDialog from './MCPServerDialog';import MCPCardActions from './MCPCardActions';import { cn } from '~/utils';@@ -99,11 +100,10 @@ export default function MCPServerCard({{/* Server Icon with Status Dot */}<div className="relative flex-shrink-0">{server.config?.iconPath ? (- <img+ <CustomIconsrc={server.config.iconPath}- className="size-8 rounded-lg object-cover"+ className="size-8 rounded-lg object-cover text-text-primary"alt=""- aria-hidden="true"/>) : (<div className="flex size-8 items-center justify-center rounded-lg bg-surface-tertiary">diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/BasicInfoSection.tsx b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/BasicInfoSection.tsxindex d1574336f3..28567b5171 100644--- a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/BasicInfoSection.tsx+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/BasicInfoSection.tsx@@ -1,10 +1,15 @@+import { useState } from 'react';import { useFormContext } from 'react-hook-form';import { Input, Label, Textarea } from '@librechat/client';-import { MCP_SERVER_TITLE_PATTERN } from 'librechat-data-provider';+import { MAX_MCP_ICON_PATH_LENGTH, MCP_SERVER_TITLE_PATTERN } from 'librechat-data-provider';import type { MCPServerFormData } from '../hooks/useMCPServerForm';import MCPIcon from '~/components/SidePanel/Agents/MCPIcon';+import { cn, sanitizeSvg, svgToDataUri } from '~/utils';import { useLocalize } from '~/hooks';-import { cn } from '~/utils';++/** Largest file whose base64 data URI can still fit `MAX_MCP_ICON_PATH_LENGTH`. */+const MAX_ICON_FILE_BYTES = Math.floor((MAX_MCP_ICON_PATH_LENGTH * 3) / 4);+const MAX_ICON_FILE_KB = Math.floor(MAX_ICON_FILE_BYTES / 1024);export default function BasicInfoSection() {const localize = useLocalize();@@ -16,15 +21,42 @@ export default function BasicInfoSection() {} = useFormContext<MCPServerFormData>();const iconValue = watch('icon');+ /* Local rather than a form error: a rejected pick keeps the previous icon, so it+ * must not block saving the rest of the form. */+ const [iconRejected, setIconRejected] = useState(false);++ /* The server drops any icon over the cap, so refuse it here instead of previewing+ * an icon that vanishes on save. */+ const applyIcon = (dataUri: string) => {+ if (dataUri.length > MAX_MCP_ICON_PATH_LENGTH) {+ setIconRejected(true);+ return;+ }+ setIconRejected(false);+ setValue('icon', dataUri);+ };const handleIconChange = (e: React.ChangeEvent<HTMLInputElement>) => {const file = e.target.files?.[0];- if (file) {- const reader = new FileReader();- reader.onloadend = () => {- const base64String = reader.result as string;- setValue('icon', base64String);- };+ if (!file) {+ return;+ }+ if (file.size > MAX_ICON_FILE_BYTES) {+ setIconRejected(true);+ return;+ }++ const reader = new FileReader();+ const isSvg = file.type === 'image/svg+xml' || /\.svg$/i.test(file.name);+ reader.onloadend = () => {+ if (typeof reader.result !== 'string') {+ return;+ }+ applyIcon(isSvg ? svgToDataUri(sanitizeSvg(reader.result)) : reader.result);+ };+ if (isSvg) {+ reader.readAsText(file);+ } else {reader.readAsDataURL(file);}};@@ -33,8 +65,17 @@ export default function BasicInfoSection() {<div className="space-y-3">{/* Icon + Name row */}<div className="flex flex-col gap-4 sm:flex-row sm:items-start">- <div className="flex-shrink-0">- <MCPIcon icon={iconValue} onIconChange={handleIconChange} />+ <div className="flex-shrink-0 space-y-1.5">+ <MCPIcon+ icon={iconValue}+ onIconChange={handleIconChange}+ errorId={iconRejected ? 'mcp-icon-error' : undefined}+ />+ {iconRejected && (+ <p id="mcp-icon-error" role="alert" className="text-xs text-text-destructive">+ {localize('com_ui_icon_too_large', { 0: MAX_ICON_FILE_KB })}+ </p>+ )}</div><div className="w-full space-y-1.5 sm:flex-1"><Label htmlFor="mcp-title" className="text-sm font-medium">diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/__tests__/BasicInfoSection.spec.tsx b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/__tests__/BasicInfoSection.spec.tsxnew file mode 100644index 0000000000..d5de2c4751--- /dev/null+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/__tests__/BasicInfoSection.spec.tsx@@ -0,0 +1,179 @@+import { FormProvider, useForm } from 'react-hook-form';+import { MAX_MCP_ICON_PATH_LENGTH } from 'librechat-data-provider';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import type * as ReactNS from 'react';+import type { MCPServerFormData } from '../../hooks/useMCPServerForm';+import BasicInfoSection from '../BasicInfoSection';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string, values?: Record<string, unknown>) =>+ values ? `${key}:${values[0]}` : key,+}));++jest.mock('~/components/ui/CustomIcon', () => {+ const React = jest.requireActual<typeof ReactNS>('react');+ return {+ __esModule: true,+ default: ({ src }: { src: string }) =>+ React.createElement('img', { alt: '', 'data-testid': 'icon-preview', src }),+ };+});++jest.mock('@librechat/client', () => {+ const React = jest.requireActual<typeof ReactNS>('react');+ return {+ Button: ({ children, ...props }: { children: ReactNode }) =>+ React.createElement('button', { type: 'button', ...props }, children),+ /* `register` hands each field a ref */+ Input: React.forwardRef<HTMLInputElement, Record<string, unknown>>((props, ref) =>+ React.createElement('input', { ...props, ref }),+ ),+ Label: ({ children, ...props }: { children: ReactNode }) =>+ React.createElement('label', props, children),+ Textarea: React.forwardRef<HTMLTextAreaElement, Record<string, unknown>>((props, ref) =>+ React.createElement('textarea', { ...props, ref }),+ ),+ SquirclePlusIcon: () => React.createElement('span'),+ };+});++function renderSection() {+ const onSubmit = jest.fn();+ function Wrapper() {+ const methods = useForm<MCPServerFormData>({+ defaultValues: {+ title: 'Existing',+ description: '',+ icon: 'data:image/png;base64,existing',+ url: '',+ type: 'streamable-http',+ auth: { auth_type: 'none' as MCPServerFormData['auth']['auth_type'] },+ trust: false,+ },+ });+ return (+ <FormProvider {...methods}>+ <form onSubmit={methods.handleSubmit((data) => onSubmit(data))}>+ <BasicInfoSection />+ <button type="submit" aria-label="save" />+ </form>+ </FormProvider>+ );+ }++ const view = render(<Wrapper />);+ const input = view.container.querySelector<HTMLInputElement>('input[type="file"]');+ if (input == null) {+ throw new Error('icon file input not rendered');+ }+ return { ...view, input, onSubmit };+}++function rasterFile(bytes: number): File {+ return new File([new Uint8Array(bytes)], 'icon.png', { type: 'image/png' });+}++describe('BasicInfoSection icon upload', () => {+ it('rejects a file too large to store, explains why, and keeps the current icon', async () => {+ const { input } = renderSection();++ fireEvent.change(input, { target: { files: [rasterFile(MAX_MCP_ICON_PATH_LENGTH)] } });++ const alert = await screen.findByRole('alert');+ expect(alert).toHaveTextContent('com_ui_icon_too_large:192');+ expect(screen.getByTestId('icon-preview')).toHaveAttribute(+ 'src',+ 'data:image/png;base64,existing',+ );+ });++ it('still submits the form after a rejected pick', async () => {+ const { input, onSubmit } = renderSection();++ fireEvent.change(input, { target: { files: [rasterFile(MAX_MCP_ICON_PATH_LENGTH)] } });+ await screen.findByRole('alert');++ fireEvent.click(screen.getByRole('button', { name: 'save' }));++ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));+ expect(onSubmit.mock.calls[0][0].icon).toBe('data:image/png;base64,existing');+ });++ it('refuses an oversized SVG before reading or sanitizing it', async () => {+ const readAsText = jest.spyOn(FileReader.prototype, 'readAsText');+ const { input } = renderSection();+ const svg = new File([new Uint8Array(MAX_MCP_ICON_PATH_LENGTH)], 'icon.svg', {+ type: 'image/svg+xml',+ });++ fireEvent.change(input, { target: { files: [svg] } });++ expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_icon_too_large:192');+ expect(readAsText).not.toHaveBeenCalled();+ readAsText.mockRestore();+ });++ it('sanitizes and previews an SVG that fits', async () => {+ const { input } = renderSection();+ const svg = new File(+ ['<svg><script>alert(1)</script><path d="M0 0h1v1z"/></svg>'],+ 'icon.svg',+ {+ type: 'image/svg+xml',+ },+ );++ fireEvent.change(input, { target: { files: [svg] } });++ await waitFor(() => {+ const src = screen.getByTestId('icon-preview').getAttribute('src') ?? '';+ expect(src.startsWith('data:image/svg+xml;base64,')).toBe(true);+ const markup = atob(src.slice('data:image/svg+xml;base64,'.length));+ expect(markup).not.toContain('script');+ expect(markup).toContain('path');+ });+ });++ it('describes the upload control with the rejection so it is announced', async () => {+ const { input } = renderSection();++ fireEvent.change(input, { target: { files: [rasterFile(MAX_MCP_ICON_PATH_LENGTH)] } });++ const alert = await screen.findByRole('alert');+ const button = screen.getByRole('button', { name: 'com_ui_upload_icon' });+ expect(button).toHaveAttribute('aria-describedby', alert.id);+ expect(button).toHaveAttribute('aria-invalid', 'true');+ });++ it('accepts a file that fits and previews it without an error', async () => {+ const { input } = renderSection();++ fireEvent.change(input, { target: { files: [rasterFile(1024)] } });++ await waitFor(() => {+ expect(screen.getByTestId('icon-preview')).toHaveAttribute(+ 'src',+ expect.stringMatching(/^data:image\/png;base64,A/),+ );+ });+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });++ it('clears a previous rejection once an acceptable file is picked', async () => {+ const { input } = renderSection();++ fireEvent.change(input, { target: { files: [rasterFile(MAX_MCP_ICON_PATH_LENGTH)] } });+ await screen.findByRole('alert');++ fireEvent.change(input, { target: { files: [rasterFile(1024)] } });++ await waitFor(() => {+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });+ expect(screen.getByTestId('icon-preview')).toHaveAttribute(+ 'src',+ expect.stringMatching(/^data:image\/png;base64,A/),+ );+ });+});diff --git a/client/src/components/ui/CustomIcon.tsx b/client/src/components/ui/CustomIcon.tsxnew file mode 100644index 0000000000..dd4ffdd823--- /dev/null+++ b/client/src/components/ui/CustomIcon.tsx@@ -0,0 +1,67 @@+import type { ReactEventHandler } from 'react';+import useAdaptiveIcon from '~/hooks/useAdaptiveIcon';+import { cn } from '~/utils';++interface CustomIconProps {+ src: string;+ alt?: string;+ className?: string;+ monochrome?: boolean;+ onError?: ReactEventHandler<HTMLImageElement>;+}++/**+ * Renders a user-provided icon (MCP `iconPath`, group `groupIcon`). Monochrome+ * SVG glyphs are masked with `currentColor` so they follow the theme; set a+ * `text-*` class to pick the tint. `object-cover` carries over as `mask-size:+ * cover`; anything else letterboxes with `contain`. `custom-icon-tint` repaints+ * the glyph under forced-colors mode (see `style.css`).+ */+export default function CustomIcon({+ src,+ alt = '',+ className,+ monochrome,+ onError,+}: CustomIconProps) {+ const { shouldTint } = useAdaptiveIcon(src, monochrome);+ const decorative = alt === '';++ if (shouldTint) {+ const maskUrl = `url("${src.replace(/["\\\n\r\f]/g, encodeURIComponent)}")`;+ const maskSize = /\bobject-cover\b/.test(className ?? '') ? 'cover' : 'contain';+ return (+ <span+ role={decorative ? undefined : 'img'}+ aria-label={decorative ? undefined : alt}+ aria-hidden={decorative ? true : undefined}+ className={cn('custom-icon-tint inline-block', className)}+ style={{+ backgroundColor: 'currentColor',+ maskImage: maskUrl,+ WebkitMaskImage: maskUrl,+ maskRepeat: 'no-repeat',+ WebkitMaskRepeat: 'no-repeat',+ maskPosition: 'center',+ WebkitMaskPosition: 'center',+ maskSize,+ WebkitMaskSize: maskSize,+ }}+ >+ {onError != null && (+ <img src={src} alt="" aria-hidden="true" className="hidden" onError={onError} />+ )}+ </span>+ );+ }++ return (+ <img+ src={src}+ alt={alt}+ aria-hidden={decorative ? true : undefined}+ className={className}+ onError={onError}+ />+ );+}diff --git a/client/src/components/ui/__tests__/CustomIcon.test.tsx b/client/src/components/ui/__tests__/CustomIcon.test.tsxnew file mode 100644index 0000000000..c4cc685143--- /dev/null+++ b/client/src/components/ui/__tests__/CustomIcon.test.tsx@@ -0,0 +1,92 @@+import { render, screen, fireEvent } from '@testing-library/react';+import CustomIcon from '../CustomIcon';++describe('CustomIcon', () => {+ it('renders a raster image with its source and accessible label', () => {+ render(<CustomIcon src="/assets/logo.png" alt="My Server" className="size-8" />);++ const img = screen.getByRole('img', { name: 'My Server' });+ expect(img.tagName).toBe('IMG');+ expect(img).toHaveAttribute('src', '/assets/logo.png');+ });++ it('hides decorative raster images from assistive technology', () => {+ const { container } = render(<CustomIcon src="/assets/logo.png" alt="" />);++ const img = container.querySelector('img');+ expect(img).not.toBeNull();+ expect(img).toHaveAttribute('aria-hidden', 'true');+ expect(img).toHaveAttribute('src', '/assets/logo.png');+ });++ describe('tinted (masked) rendering', () => {+ it('renders a labeled masked span exposed as an image', () => {+ render(<CustomIcon src="/glyph.svg" alt="My Server" monochrome className="size-8" />);++ const el = screen.getByRole('img', { name: 'My Server' });+ expect(el.tagName).toBe('SPAN');+ expect(el).not.toHaveAttribute('aria-hidden');+ expect(el.style.backgroundColor).toBe('currentcolor');+ expect(el).toHaveClass('custom-icon-tint');+ });++ it('hides a decorative masked span from assistive technology', () => {+ const { container } = render(<CustomIcon src="/glyph.svg" alt="" monochrome />);++ const span = container.querySelector('span');+ expect(span).not.toBeNull();+ expect(span).toHaveAttribute('aria-hidden', 'true');+ expect(span).not.toHaveAttribute('role');+ });++ it('escapes double quotes in the mask URL so the CSS url() stays intact', () => {+ const { container } = render(<CustomIcon src={'/a".svg'} alt="" monochrome />);++ const span = container.querySelector('span');+ expect(span?.style.maskImage).toBe('url("/a%22.svg")');+ });++ it('escapes backslashes and newlines in the mask URL', () => {+ const { container } = render(<CustomIcon src={'/a\\b\nc.svg'} alt="" monochrome />);++ const span = container.querySelector('span');+ expect(span?.style.maskImage).toBe('url("/a%5Cb%0Ac.svg")');+ });++ it('letterboxes with mask-size contain by default', () => {+ const { container } = render(+ <CustomIcon src="/glyph.svg" alt="" monochrome className="size-8" />,+ );++ const span = container.querySelector('span');+ expect(span?.style.maskSize).toBe('contain');+ });++ it('keeps object-cover sizing semantics via mask-size cover', () => {+ const { container } = render(+ <CustomIcon src="/glyph.svg" alt="" monochrome className="h-8 w-8 object-cover" />,+ );++ const span = container.querySelector('span');+ expect(span?.style.maskSize).toBe('cover');+ });++ it('does not render a probe image on the tinted path without an onError handler', () => {+ const { container } = render(<CustomIcon src="/glyph.svg" alt="" monochrome />);++ expect(container.querySelector('span img')).toBeNull();+ });++ it('routes a mask load failure to onError via a hidden probe image', () => {+ const onError = jest.fn();+ const { container } = render(+ <CustomIcon src="/broken.svg" alt="" monochrome onError={onError} />,+ );++ const probe = container.querySelector('span img');+ expect(probe).not.toBeNull();+ fireEvent.error(probe as HTMLImageElement);+ expect(onError).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/client/src/components/ui/index.ts b/client/src/components/ui/index.tsindex 7ee79ebfff..a1ac76edb5 100644--- a/client/src/components/ui/index.ts+++ b/client/src/components/ui/index.ts@@ -1,5 +1,6 @@export { Button, FieldMessage } from '@librechat/client';export { default as Collapse } from './Collapse';+export { default as CustomIcon } from './CustomIcon';export { default as PanelFooter } from './PanelFooter';export { default as PanelContent } from './PanelContent';export { default as TermsAndConditionsModal } from './TermsAndConditionsModal';diff --git a/client/src/hooks/__tests__/useAdaptiveIcon.test.tsx b/client/src/hooks/__tests__/useAdaptiveIcon.test.tsxnew file mode 100644index 0000000000..8001689f84--- /dev/null+++ b/client/src/hooks/__tests__/useAdaptiveIcon.test.tsx@@ -0,0 +1,117 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import {+ installCanvasMock,+ registerFakeIcon,+ resetFakeIcons,+ getImageLoadCount,+} from 'test/canvasMock';+import useAdaptiveIcon from '../useAdaptiveIcon';++const BLACK = { width: 24, height: 24, pixels: [0, 0, 0, 0, 0, 0, 0, 255] };+const RED = { width: 24, height: 24, pixels: [255, 0, 0, 255, 0, 0, 0, 0] };++/** Flushes the detector's microtask and settle timer inside `act`. */+const flush = () => act(() => new Promise<void>((resolve) => setTimeout(resolve, 0)));++describe('useAdaptiveIcon', () => {+ beforeEach(() => {+ resetFakeIcons();+ installCanvasMock();+ });++ it('does not tint a raster image', () => {+ const { result } = renderHook(() => useAdaptiveIcon('/logo-raster.png'));+ expect(result.current.shouldTint).toBe(false);+ });++ it('tints a monochrome svg once resolved', async () => {+ registerFakeIcon('/mono-1.svg', BLACK);+ const { result } = renderHook(() => useAdaptiveIcon('/mono-1.svg'));+ await waitFor(() => expect(result.current.shouldTint).toBe(true));+ });++ it('does not tint a multi-color svg', async () => {+ registerFakeIcon('/color-1.svg', RED);+ const { result } = renderHook(() => useAdaptiveIcon('/color-1.svg'));+ await flush();+ expect(result.current.shouldTint).toBe(false);+ });++ it('does not tint when the icon fails to load', async () => {+ registerFakeIcon('/broken-1.svg', { width: 24, height: 24, error: true });+ const { result } = renderHook(() => useAdaptiveIcon('/broken-1.svg'));+ await flush();+ expect(result.current.shouldTint).toBe(false);+ });++ it('does not tint when a cross-origin icon taints the canvas', async () => {+ registerFakeIcon('/cross-1.svg', { ...BLACK, taint: true });+ const { result } = renderHook(() => useAdaptiveIcon('/cross-1.svg'));+ await flush();+ expect(result.current.shouldTint).toBe(false);+ });++ it('drops the previous tint immediately when src changes to a raster image', async () => {+ registerFakeIcon('/mono-2.svg', BLACK);+ const { result, rerender } = renderHook(({ src }) => useAdaptiveIcon(src), {+ initialProps: { src: '/mono-2.svg' },+ });+ await waitFor(() => expect(result.current.shouldTint).toBe(true));++ rerender({ src: '/logo-raster-2.png' });+ expect(result.current.shouldTint).toBe(false);+ });++ it('does not leak the previous tint to a new, still-resolving svg', async () => {+ registerFakeIcon('/mono-3.svg', BLACK);+ registerFakeIcon('/pending.svg', { width: 24, height: 24, pending: true });+ const { result, rerender } = renderHook(({ src }) => useAdaptiveIcon(src), {+ initialProps: { src: '/mono-3.svg' },+ });+ await waitFor(() => expect(result.current.shouldTint).toBe(true));++ rerender({ src: '/pending.svg' });+ expect(result.current.shouldTint).toBe(false);+ });++ it('samples the icon once for concurrent instances of the same src', async () => {+ registerFakeIcon('/shared.svg', BLACK);+ const first = renderHook(() => useAdaptiveIcon('/shared.svg'));+ const second = renderHook(() => useAdaptiveIcon('/shared.svg'));+ await waitFor(() => expect(first.result.current.shouldTint).toBe(true));+ await waitFor(() => expect(second.result.current.shouldTint).toBe(true));+ expect(getImageLoadCount()).toBe(1);+ });++ it('reuses a cached verdict for a later instance without re-sampling', async () => {+ registerFakeIcon('/cached.svg', BLACK);+ const first = renderHook(() => useAdaptiveIcon('/cached.svg'));+ await waitFor(() => expect(first.result.current.shouldTint).toBe(true));+ first.unmount();+ const sampledOnce = getImageLoadCount();++ const second = renderHook(() => useAdaptiveIcon('/cached.svg'));+ expect(second.result.current.shouldTint).toBe(true);+ expect(getImageLoadCount()).toBe(sampledOnce);+ await flush();+ });++ describe('explicit monochrome flag', () => {+ it('tints without detection when monochrome is true', () => {+ const { result } = renderHook(() => useAdaptiveIcon('/unregistered.svg', true));+ expect(result.current.shouldTint).toBe(true);+ });++ it('does not tint when monochrome is false, skipping detection', async () => {+ registerFakeIcon('/mono-4.svg', BLACK);+ const { result } = renderHook(() => useAdaptiveIcon('/mono-4.svg', false));+ await flush();+ expect(result.current.shouldTint).toBe(false);+ });++ it('applies the explicit flag to non-svg sources', () => {+ const { result } = renderHook(() => useAdaptiveIcon('/logo-raster.png', true));+ expect(result.current.shouldTint).toBe(true);+ });+ });+});diff --git a/client/src/hooks/index.ts b/client/src/hooks/index.tsindex 73450a4bff..78edeec7d3 100644--- a/client/src/hooks/index.ts+++ b/client/src/hooks/index.ts@@ -32,6 +32,7 @@ export { default as useFocusTrap } from './useFocusTrap';export { default as useFavorites } from './useFavorites';export { default as useToolFavorites } from './useToolFavorites';export { default as useChatBadges } from './useChatBadges';+export { default as useAdaptiveIcon } from './useAdaptiveIcon';export { default as useScrollToRef } from './useScrollToRef';export { default as useIsActiveItem } from './useIsActiveItem';export { default as useLocalStorage } from './useLocalStorage';diff --git a/client/src/hooks/useAdaptiveIcon.ts b/client/src/hooks/useAdaptiveIcon.tsnew file mode 100644index 0000000000..28005eb0d2--- /dev/null+++ b/client/src/hooks/useAdaptiveIcon.ts@@ -0,0 +1,70 @@+import { useEffect, useState } from 'react';+import { isSvgIcon, detectMonochrome, isSameOriginOrDataIcon } from '~/utils';++const monochromeCache = new Map<string, boolean>();+const inFlight = new Map<string, Promise<boolean>>();+/** Bounds the cache so a session cycling many unique data-URI icons cannot grow it forever. */+const MAX_MONOCHROME_CACHE = 256;++function resolveMonochrome(src: string): Promise<boolean> {+ const cached = monochromeCache.get(src);+ if (cached !== undefined) {+ return Promise.resolve(cached);+ }+ const existing = inFlight.get(src);+ if (existing) {+ return existing;+ }+ const promise = detectMonochrome(src).then((monochrome) => {+ if (monochromeCache.size >= MAX_MONOCHROME_CACHE) {+ const oldest = monochromeCache.keys().next().value;+ if (oldest !== undefined) {+ monochromeCache.delete(oldest);+ }+ }+ monochromeCache.set(src, monochrome);+ inFlight.delete(src);+ return monochrome;+ });+ inFlight.set(src, promise);+ return promise;+}++/**+ * Whether a custom icon should be tinted to `currentColor`. An explicit+ * `monochrome` flag wins; otherwise same-origin and data-URI SVGs are sampled+ * once per source (see `detectMonochrome`) and the verdict cached.+ */+export default function useAdaptiveIcon(+ src?: string | null,+ monochrome?: boolean,+): { shouldTint: boolean } {+ const key =+ typeof monochrome !== 'boolean' && isSvgIcon(src) && isSameOriginOrDataIcon(src) ? src : null;+ const [state, setState] = useState<{ key: string | null; monochrome: boolean }>(() => ({+ key,+ monochrome: key != null && (monochromeCache.get(key) ?? false),+ }));++ useEffect(() => {+ if (key == null) {+ return;+ }+ let active = true;+ resolveMonochrome(key).then((resolved) => {+ if (active) {+ setState((prev) =>+ prev.key === key && prev.monochrome === resolved ? prev : { key, monochrome: resolved },+ );+ }+ });+ return () => {+ active = false;+ };+ }, [key]);++ if (typeof monochrome === 'boolean') {+ return { shouldTint: monochrome };+ }+ return { shouldTint: state.key === key && state.monochrome };+}diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex bd719a49f6..700ca27855 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1406,6 +1406,7 @@"com_ui_high": "High","com_ui_host": "Host","com_ui_icon": "Icon",+ "com_ui_icon_too_large": "That image is too large to save as an icon. Please choose a file under {{0}} KB.","com_ui_idea": "Ideas","com_ui_image_created": "Image created","com_ui_image_details": "Image Details",diff --git a/client/src/style.css b/client/src/style.cssindex ae0a05dfae..5aa61e98ad 100644--- a/client/src/style.css+++ b/client/src/style.css@@ -432,6 +432,14 @@ html {background-color: rgb(var(--surface-secondary));}+/* Forced-colors overrides the inline `background-color: currentColor` a masked+ * CustomIcon paints with; `!important` is needed to beat that inline style. */+@media (forced-colors: active) {+ .custom-icon-tint {+ background-color: CanvasText !important;+ }+}+.ellipsis {overflow: hidden;white-space: nowrap;diff --git a/client/src/utils/__tests__/icons.test.ts b/client/src/utils/__tests__/icons.test.tsindex ce5687fa08..f34b71bd21 100644--- a/client/src/utils/__tests__/icons.test.ts+++ b/client/src/utils/__tests__/icons.test.ts@@ -1,4 +1,4 @@-import { isImageURL } from '../icons';+import { isImageURL, isSvgIcon, isSameOriginOrDataIcon } from '../icons';describe('isImageURL', () => {it.each([@@ -25,3 +25,58 @@ describe('isImageURL', () => {},);});++describe('isSvgIcon', () => {+ it.each([+ 'https://example.com/icon.svg',+ '/assets/icon.svg',+ '/assets/icon.SVG',+ 'https://example.com/icon.svg?v=2',+ 'https://example.com/icon.svg#hash',+ 'data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=',+ 'data:image/svg+xml,%3Csvg%3E%3C/svg%3E',+ ])('accepts SVG icon %s', (iconURL) => {+ expect(isSvgIcon(iconURL)).toBe(true);+ });++ it.each([+ 'https://example.com/icon.png',+ '/assets/icon.jpg',+ 'data:image/png;base64,abc',+ 'https://example.com/svg-logo.png',+ 'https://example.com/a.svg/b.png',+ '/assets/icon.svgz',+ 'blob:https://example.com/abc-123',+ '/assets/icon.svg/',+ '',+ null,+ undefined,+ ])('rejects non-SVG icon %s', (iconURL) => {+ expect(isSvgIcon(iconURL)).toBe(false);+ });+});++describe('isSameOriginOrDataIcon', () => {+ it.each([+ 'data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=',+ 'data:image/png;base64,abc',+ '/assets/icon.svg',+ `${window.location.origin}/assets/icon.svg`,+ ])('accepts same-origin or data icon %s', (iconURL) => {+ expect(isSameOriginOrDataIcon(iconURL)).toBe(true);+ });++ it.each([+ 'https://evil.example.com/icon.svg',+ '//cdn.example.com/icon.svg',+ 'http://other.example/icon.svg',+ /* a backslash is a separator in http(s) URLs, so these load cross-origin */+ '/\\attacker.example/icon.svg',+ '/\\/attacker.example/icon.svg',+ '',+ null,+ undefined,+ ])('rejects cross-origin or empty icon %s', (iconURL) => {+ expect(isSameOriginOrDataIcon(iconURL)).toBe(false);+ });+});diff --git a/client/src/utils/__tests__/svg.test.ts b/client/src/utils/__tests__/svg.test.tsnew file mode 100644index 0000000000..de8193cf75--- /dev/null+++ b/client/src/utils/__tests__/svg.test.ts@@ -0,0 +1,350 @@+import {+ installCanvasMock,+ registerFakeIcon,+ resetFakeIcons,+ getLastCrossOrigin,+} from 'test/canvasMock';+import { detectMonochrome, sanitizeSvg, scanMonochrome, svgToDataUri } from '../svg';+import { isSvgIcon } from '../icons';++const rgba = (...quads: number[]) => Uint8ClampedArray.from(quads);++describe('scanMonochrome', () => {+ it('treats a black glyph on a transparent background as monochrome', () => {+ expect(scanMonochrome(rgba(0, 0, 0, 0, 0, 0, 0, 255))).toBe(true);+ });++ it('treats a mid-gray glyph as monochrome', () => {+ expect(scanMonochrome(rgba(128, 128, 128, 255, 0, 0, 0, 0))).toBe(true);+ });++ it('allows a channel spread within the tolerance', () => {+ expect(scanMonochrome(rgba(100, 110, 105, 255, 0, 0, 0, 0))).toBe(true);+ });++ it('accepts a channel spread exactly at the tolerance', () => {+ expect(scanMonochrome(rgba(100, 116, 100, 255, 0, 0, 0, 0))).toBe(true);+ });++ it('rejects a channel spread just past the tolerance', () => {+ expect(scanMonochrome(rgba(100, 117, 100, 255, 0, 0, 0, 0))).toBe(false);+ });++ it('rejects a chromatic pixel', () => {+ expect(scanMonochrome(rgba(255, 0, 0, 255, 0, 0, 0, 0))).toBe(false);+ });++ it('ignores transparent pixels when judging tone', () => {+ expect(scanMonochrome(rgba(255, 0, 0, 0, 20, 20, 20, 255))).toBe(true);+ });++ it('skips a chromatic pixel at the alpha threshold', () => {+ expect(scanMonochrome(rgba(255, 0, 0, 8, 20, 20, 20, 255))).toBe(true);+ });++ it('samples a chromatic pixel just above the alpha threshold', () => {+ expect(scanMonochrome(rgba(255, 0, 0, 9, 0, 0, 0, 0))).toBe(false);+ });++ it('is not monochrome when nothing is painted', () => {+ expect(scanMonochrome(rgba(0, 0, 0, 0, 255, 0, 0, 0))).toBe(false);+ });++ it('is not monochrome when any opaque pixel is chromatic', () => {+ expect(scanMonochrome(rgba(10, 10, 10, 255, 200, 10, 10, 255, 0, 0, 0, 0))).toBe(false);+ });++ it('is not monochrome when fully opaque, since a mask would flatten it to a block', () => {+ expect(scanMonochrome(rgba(0, 0, 0, 255, 90, 90, 90, 255))).toBe(false);+ });++ it('is not monochrome when a semi-transparent fill covers every pixel', () => {+ // grayscale but no empty pixel: a mask would paint a full-canvas wash+ expect(scanMonochrome(rgba(128, 128, 128, 128, 90, 90, 90, 200))).toBe(false);+ });++ it('is monochrome when a translucent glyph sits on genuinely empty pixels', () => {+ expect(scanMonochrome(rgba(128, 128, 128, 128, 0, 0, 0, 0))).toBe(true);+ });++ it('rejects two deliberate tones, which one mask would flatten into one color', () => {+ expect(scanMonochrome(rgba(0, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 0))).toBe(false);+ });++ it('allows shading within a single tone', () => {+ expect(scanMonochrome(rgba(34, 34, 34, 255, 85, 85, 85, 255, 0, 0, 0, 0))).toBe(true);+ });++ it('rejects two tones painted at the same partial opacity', () => {+ expect(scanMonochrome(rgba(0, 0, 0, 128, 255, 255, 255, 128, 0, 0, 0, 0))).toBe(false);+ });++ it('tolerates the unpremultiply rounding of a low-alpha edge sample', () => {+ expect(scanMonochrome(rgba(0, 0, 0, 255, 28, 28, 28, 9, 0, 0, 0, 0))).toBe(true);+ });+});++describe('detectMonochrome', () => {+ beforeEach(() => {+ resetFakeIcons();+ installCanvasMock();+ });++ it('detects a grayscale glyph as monochrome', async () => {+ registerFakeIcon('/mono.svg', {+ width: 24,+ height: 24,+ pixels: [0, 0, 0, 0, 0, 0, 0, 255, 90, 90, 90, 255],+ });+ await expect(detectMonochrome('/mono.svg')).resolves.toBe(true);+ });++ it('detects a multi-color icon as not monochrome', async () => {+ registerFakeIcon('/color.svg', {+ width: 24,+ height: 24,+ pixels: [12, 120, 240, 255, 0, 0, 0, 0],+ });+ await expect(detectMonochrome('/color.svg')).resolves.toBe(false);+ });++ it('does not treat a fully-opaque grayscale image as monochrome', async () => {+ registerFakeIcon('/block.svg', {+ width: 24,+ height: 24,+ pixels: [0, 0, 0, 255, 60, 60, 60, 255],+ });+ await expect(detectMonochrome('/block.svg')).resolves.toBe(false);+ });++ it('requests cross-origin access so CORS icons can be sampled', async () => {+ registerFakeIcon('/cors.svg', { width: 8, height: 8, pixels: [0, 0, 0, 255] });+ await detectMonochrome('/cors.svg');+ expect(getLastCrossOrigin()).toBe('anonymous');+ });++ it('falls back to non-monochrome when the image fails to load', async () => {+ registerFakeIcon('/broken.svg', { width: 24, height: 24, error: true });+ await expect(detectMonochrome('/broken.svg')).resolves.toBe(false);+ });++ it('falls back to non-monochrome when the canvas is tainted', async () => {+ registerFakeIcon('/cross-origin.svg', {+ width: 24,+ height: 24,+ pixels: [0, 0, 0, 255],+ taint: true,+ });+ await expect(detectMonochrome('/cross-origin.svg')).resolves.toBe(false);+ });++ it('is not monochrome when the icon reports no intrinsic size', async () => {+ registerFakeIcon('/sizeless.svg', { width: 0, height: 0, pixels: [0, 0, 0, 255] });+ await expect(detectMonochrome('/sizeless.svg')).resolves.toBe(false);+ });++ it('settles a load that never completes so its in-flight entry can be released', async () => {+ jest.useFakeTimers();+ try {+ registerFakeIcon('/stalled.svg', { width: 24, height: 24, pending: true });+ const verdict = detectMonochrome('/stalled.svg');+ jest.advanceTimersByTime(10_000);+ await expect(verdict).resolves.toBe(false);+ } finally {+ jest.useRealTimers();+ }+ });+});++describe('sanitizeSvg', () => {+ it('strips script tags but keeps drawing elements', () => {+ const dirty = '<svg><script>alert(1)</script><path d="M0 0h10v10H0z" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).not.toContain('<script');+ expect(clean).not.toContain('alert(1)');+ expect(clean).toContain('path');+ });++ it('strips inline event handler attributes', () => {+ const dirty = '<svg onload="alert(1)"><circle cx="5" cy="5" r="5" onclick="alert(2)" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).not.toContain('onload');+ expect(clean).not.toContain('onclick');+ expect(clean).toContain('circle');+ });++ it('removes foreignObject and embedded HTML', () => {+ const dirty =+ '<svg><foreignObject><iframe src="javascript:alert(1)"></iframe></foreignObject></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean.toLowerCase()).not.toContain('foreignobject');+ expect(clean.toLowerCase()).not.toContain('iframe');+ });++ it('strips anchors and javascript: URLs', () => {+ const dirty = '<svg><a href="javascript:alert(1)"><rect width="10" height="10" /></a></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).not.toContain('javascript:');+ expect(clean.toLowerCase()).not.toContain('<a');+ expect(clean).toContain('rect');+ });++ it('drops external <image> references so an SVG cannot phone home', () => {+ const dirty =+ '<svg><image href="https://evil.example/track.png" width="10" height="10" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).not.toContain('evil.example');+ expect(clean.toLowerCase()).not.toContain('<image');+ });++ it('strips external <use> references but keeps the element inert', () => {+ const dirty = '<svg><use href="https://evil.example/x.svg#a" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).not.toContain('evil.example');+ expect(clean).not.toContain('href');+ });++ it('strips relative-path and javascript: hrefs from <use>', () => {+ for (const href of ['icons.svg#a', '//evil.example/x.svg#a', 'javascript:alert(1)']) {+ const clean = sanitizeSvg(`<svg><use href="${href}" /></svg>`);+ expect(clean).not.toContain('href');+ }+ });++ it('preserves local <defs>/<use> references', () => {+ const dirty = '<svg><defs><path id="p" d="M0 0h10v10H0z" /></defs><use href="#p" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).toContain('<use href="#p"');+ expect(clean).toContain('d="M0 0h10v10H0z"');+ });++ it('preserves local xlink:href <use> references', () => {+ const dirty = '<svg><defs><path id="p" d="M0 0h1v1z" /></defs><use xlink:href="#p" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).toContain('xlink:href="#p"');+ });++ it('keeps the xmlns:xlink declaration that binds xlink:href prefixes', () => {+ const dirty =+ '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><use xlink:href="#p" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).toContain('xmlns:xlink="http://www.w3.org/1999/xlink"');+ });++ it('preserves safe filter effects and strips external feImage references', () => {+ const dirty =+ '<svg><filter id="f"><feGaussianBlur in="SourceGraphic" stdDeviation="2" result="b" /><feOffset in="b" dx="2" dy="2" /><feImage href="https://evil.example/x.png" /></filter><rect width="10" height="10" filter="url(#f)" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).toContain('feGaussianBlur');+ expect(clean).toContain('stdDeviation="2"');+ expect(clean).toContain('filter="url(#f)"');+ expect(clean).not.toContain('evil.example');+ });++ it('preserves local url() paint and filter references', () => {+ const dirty =+ '<svg><defs><filter id="f"><feGaussianBlur stdDeviation="1" /></filter><linearGradient id="g"><stop offset="0" stop-color="#000" /></linearGradient></defs><rect fill="url(#g)" filter="url(#f)" width="10" height="10" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).toContain('fill="url(#g)"');+ expect(clean).toContain('filter="url(#f)"');+ });++ it('preserves gradient stop inheritance via local href', () => {+ const dirty =+ '<svg><linearGradient id="g"><stop offset="0" stop-color="#000" /></linearGradient><linearGradient id="g2" href="#g" x1="0" x2="1" /><rect fill="url(#g2)" width="10" height="10" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).toContain('href="#g"');+ expect(clean).toContain('x1="0"');+ expect(clean).toContain('fill="url(#g2)"');+ });++ it('strips stylesheet blocks and inline style attributes', () => {+ const dirty =+ '<svg><style>.red{fill:#e00}</style><path class="red" style="stroke:#00f" fill="#e00" d="M0 0h1v1z" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).not.toContain('<style');+ expect(clean).not.toContain('style=');+ expect(clean).toContain('fill="#e00"');+ });++ it('drops href-smuggling animation elements', () => {+ const dirty = '<svg><a><animate attributeName="href" values="javascript:alert(1)" /></a></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).not.toContain('javascript:');+ expect(clean.toLowerCase()).not.toContain('<animate');+ });++ it('drops url() paint, filter, mask, and clip references that leave the document', () => {+ for (const attribute of ['fill', 'stroke', 'filter', 'mask', 'clip-path', 'marker-end']) {+ for (const reference of [+ 'url(https://evil.example/x.svg#a)',+ 'url(//evil.example/x.svg#a)',+ "url('/x.svg#a')",+ ]) {+ const clean = sanitizeSvg(+ `<svg><rect width="9" height="9" ${attribute}="${reference}" /></svg>`,+ );+ expect(clean).not.toContain('evil.example');+ expect(clean).not.toContain(attribute);+ expect(clean).toContain('<rect');+ }+ }+ });++ it('preserves feDropShadow casing so the stored SVG still parses as XML', () => {+ const dirty =+ '<svg><filter id="f"><feDropShadow dx="1" dy="1" stdDeviation="0.5" flood-color="#000" /></filter><rect width="9" height="9" filter="url(#f)" /></svg>';+ const clean = sanitizeSvg(dirty);+ expect(clean).toContain('feDropShadow');+ expect(clean).not.toContain('fedropshadow');+ const parsed = new DOMParser().parseFromString(clean, 'image/svg+xml');+ expect(parsed.querySelector('parsererror')).toBeNull();+ expect(parsed.querySelector('filter')?.children.length).toBe(1);+ });++ it('declares the SVG namespace on a root that omits it so the icon renders standalone', () => {+ const clean = sanitizeSvg('<svg viewBox="0 0 8 8"><path d="M0 0h1v1z" /></svg>');+ expect(clean.startsWith('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8">')).toBe(+ true,+ );+ const root = new DOMParser().parseFromString(clean, 'image/svg+xml').documentElement;+ expect(root.namespaceURI).toBe('http://www.w3.org/2000/svg');+ });++ it('does not duplicate an existing namespace declaration', () => {+ const clean = sanitizeSvg(+ '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M0 0h1v1z" /></svg>',+ );+ expect(clean.match(/xmlns=/g)).toHaveLength(1);+ expect(clean).toContain('xmlns:xlink="http://www.w3.org/1999/xlink"');+ });+});++describe('svgToDataUri', () => {+ const b64Body = (uri: string) => uri.slice('data:image/svg+xml;base64,'.length);++ it('produces a base64 image/svg+xml data URI', () => {+ const uri = svgToDataUri('<svg><path d="M0 0h1v1H0z" /></svg>');+ expect(uri.startsWith('data:image/svg+xml;base64,')).toBe(true);+ });++ it('round-trips through sanitizeSvg into a URI that isSvgIcon accepts', () => {+ const uri = svgToDataUri(sanitizeSvg('<svg><path d="M0 0h1v1H0z" /></svg>'));+ expect(isSvgIcon(uri)).toBe(true);+ const decoded = atob(b64Body(uri));+ expect(decoded).toContain('path');+ expect(decoded.startsWith('<svg')).toBe(true);+ });++ it('encodes non-ASCII markup without throwing and stays decodable', () => {+ const uri = svgToDataUri('<svg><title>café ☕</title><path d="M0 0h1v1H0z" /></svg>');+ expect(uri.startsWith('data:image/svg+xml;base64,')).toBe(true);+ const utf8 = decodeURIComponent(+ atob(b64Body(uri))+ .split('')+ .map((c) => `%${c.charCodeAt(0).toString(16).padStart(2, '0')}`)+ .join(''),+ );+ expect(utf8).toContain('café ☕');+ });+});diff --git a/client/src/utils/icons.ts b/client/src/utils/icons.tsindex d24c14826b..6e933c799d 100644--- a/client/src/utils/icons.ts+++ b/client/src/utils/icons.ts@@ -17,3 +17,41 @@ export function isImageURL(iconURL?: string | null): iconURL is string {return iconURL.startsWith('/') || IMAGE_EXTENSION.test(iconURL);}++export function isSvgIcon(iconURL?: string | null): iconURL is string {+ if (!iconURL) {+ return false;+ }++ if (/^data:image\/svg\+xml/i.test(iconURL)) {+ return true;+ }++ const path = iconURL.split(/[?#]/)[0];+ return /\.svg$/i.test(path);+}++/**+ * True for a `data:` URI or same-origin URL, so theme detection never fetches a+ * remote icon from every viewer's browser. `new URL` resolves every non-`data:`+ * value: `/\attacker.example/icon.svg` looks root-relative but loads cross-origin.+ */+export function isSameOriginOrDataIcon(iconURL?: string | null): iconURL is string {+ if (!iconURL) {+ return false;+ }++ if (/^data:/i.test(iconURL)) {+ return true;+ }++ if (typeof window === 'undefined') {+ return false;+ }++ try {+ return new URL(iconURL, window.location.href).origin === window.location.origin;+ } catch {+ return false;+ }+}diff --git a/client/src/utils/index.ts b/client/src/utils/index.tsindex 9a6706259b..e173bdb5f2 100644--- a/client/src/utils/index.ts+++ b/client/src/utils/index.ts@@ -6,6 +6,7 @@ import logger from './logger';export * from './map';export * from './json';export * from './icons';+export * from './svg';export * from './email';export * from './share';export * from './files';diff --git a/client/src/utils/svg.ts b/client/src/utils/svg.tsnew file mode 100644index 0000000000..a2b0e40a39--- /dev/null+++ b/client/src/utils/svg.ts@@ -0,0 +1,135 @@+import DOMPurify from 'dompurify';+import {+ SVG_SANITIZE_CONFIG,+ restrictSvgReferences,+ finalizeSvgMarkup,+} from 'librechat-data-provider';+import type { DOMPurify as SvgPurifier } from 'dompurify';++/** Largest canvas edge when sampling; keeps the pixel read to one 64 KiB buffer. */+const SAMPLE_SIZE = 128;+/** Per-channel spread (0-255) a pixel may have and still count as grayscale. */+const GRAYSCALE_TOLERANCE = 16;+/** Pixels at or below this alpha paint nothing visible and are skipped. */+const ALPHA_THRESHOLD = 8;+/**+ * Widest gray-level gap between painted pixels that still reads as one tone.+ * Shading within a glyph stays under it; a second deliberate tone (a white+ * knockout at 255, a mid-gray shape at 153) does not. Unpremultiplied rounding+ * at the lowest sampled alpha is under 16 levels, so it never crosses this.+ */+const TONE_SPREAD_LIMIT = 96;+const LOAD_TIMEOUT_MS = 10_000;++/**+ * True when every painted pixel is grayscale, at least one pixel is empty, and+ * the painted pixels carry a single tone. A CSS mask keys on alpha alone, so a+ * fully painted image would flatten to a solid wash and two grayscale tones+ * would collapse into one color.+ */+export function scanMonochrome(data: Uint8ClampedArray): boolean {+ let painted = false;+ let hasEmptyArea = false;+ let minTone = 255;+ let maxTone = 0;+ for (let i = 0; i < data.length; i += 4) {+ if (data[i + 3] <= ALPHA_THRESHOLD) {+ hasEmptyArea = true;+ continue;+ }+ painted = true;+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ if (+ Math.abs(r - g) > GRAYSCALE_TOLERANCE ||+ Math.abs(g - b) > GRAYSCALE_TOLERANCE ||+ Math.abs(r - b) > GRAYSCALE_TOLERANCE+ ) {+ return false;+ }+ const tone = (r + g + b) / 3;+ minTone = Math.min(minTone, tone);+ maxTone = Math.max(maxTone, tone);+ }+ return painted && hasEmptyArea && maxTone - minTone <= TONE_SPREAD_LIMIT;+}++/** Draws the image to an offscreen canvas and reads it back; throws on a tainted canvas. */+function samplePixels(image: HTMLImageElement): Uint8ClampedArray | null {+ const naturalWidth = image.naturalWidth || image.width;+ const naturalHeight = image.naturalHeight || image.height;+ if (!naturalWidth || !naturalHeight) {+ return null;+ }+ const scale = Math.min(1, SAMPLE_SIZE / Math.max(naturalWidth, naturalHeight));+ const width = Math.max(1, Math.round(naturalWidth * scale));+ const height = Math.max(1, Math.round(naturalHeight * scale));+ const canvas = document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;+ const context = canvas.getContext('2d');+ if (!context) {+ return null;+ }+ context.drawImage(image, 0, 0, width, height);+ return context.getImageData(0, 0, width, height).data;+}++/**+ * Loads an icon and resolves whether its rendered pixels are monochrome. Load+ * errors, a tainted canvas, and a load that never settles all resolve to false.+ */+export function detectMonochrome(src: string): Promise<boolean> {+ if (typeof Image === 'undefined') {+ return Promise.resolve(false);+ }+ /* Executor form: Vite's baseline target includes Safari 16; `withResolvers` needs 17.4. */+ return new Promise((resolve) => {+ const image = new Image();+ let timer = 0;+ const settle = (monochrome: boolean) => {+ window.clearTimeout(timer);+ image.onload = null;+ image.onerror = null;+ resolve(monochrome);+ };+ timer = window.setTimeout(() => settle(false), LOAD_TIMEOUT_MS);+ image.crossOrigin = 'anonymous';+ image.onload = () => {+ try {+ const data = samplePixels(image);+ settle(data != null && scanMonochrome(data));+ } catch {+ settle(false);+ }+ };+ image.onerror = () => settle(false);+ image.src = src;+ });+}++let svgPurifier: SvgPurifier | null = null;++/** Dedicated instance so the reference hook never reaches the app's default DOMPurify. */+function getSvgPurifier(): SvgPurifier {+ if (svgPurifier) {+ return svgPurifier;+ }+ svgPurifier = DOMPurify(window);+ svgPurifier.addHook('afterSanitizeAttributes', restrictSvgReferences);+ return svgPurifier;+}++/** Strips active content from SVG markup with the policy the server re-applies. */+export function sanitizeSvg(svg: string): string {+ return finalizeSvgMarkup(getSvgPurifier().sanitize(svg, SVG_SANITIZE_CONFIG));+}++/** Encodes SVG markup as a base64 data URI; the escape round-trip keeps `btoa` UTF-8 safe. */+export function svgToDataUri(svg: string): string {+ const binary = encodeURIComponent(svg).replace(/%([0-9A-F]{2})/g, (_, hex) =>+ String.fromCharCode(parseInt(hex, 16)),+ );+ return `data:image/svg+xml;base64,${btoa(binary)}`;+}diff --git a/client/test/canvasMock.ts b/client/test/canvasMock.tsnew file mode 100644index 0000000000..e76840e799--- /dev/null+++ b/client/test/canvasMock.ts@@ -0,0 +1,107 @@+/**+ * Replaces `Image` and `canvas.getContext('2d')` with fakes driven by a+ * per-source registry, since jsdom decodes no images. `scanMonochrome` still+ * runs against the registered bytes.+ */++export interface FakeIcon {+ width: number;+ height: number;+ /** Flat RGBA quads; omit for a transparent image. */+ pixels?: number[];+ /** Throw from `getImageData` like a tainted canvas. */+ taint?: boolean;+ error?: boolean;+ /** Never fire `onload` or `onerror`. */+ pending?: boolean;+}++const icons = new Map<string, FakeIcon>();+let lastCrossOrigin: string | null = null;+let loadCount = 0;++export function registerFakeIcon(src: string, icon: FakeIcon): void {+ icons.set(src, icon);+}++export function resetFakeIcons(): void {+ icons.clear();+ lastCrossOrigin = null;+ loadCount = 0;+}++export function getLastCrossOrigin(): string | null {+ return lastCrossOrigin;+}++export function getImageLoadCount(): number {+ return loadCount;+}++class MockImage {+ crossOrigin: string | null = null;+ onload: (() => void) | null = null;+ onerror: (() => void) | null = null;+ naturalWidth = 0;+ naturalHeight = 0;+ width = 0;+ height = 0;+ private currentSrc = '';++ get src(): string {+ return this.currentSrc;+ }++ set src(value: string) {+ this.currentSrc = value;+ lastCrossOrigin = this.crossOrigin;+ loadCount += 1;+ const icon = icons.get(value);+ if (icon?.pending === true) {+ return;+ }+ Promise.resolve().then(() => {+ if (!icon || icon.error === true) {+ this.onerror?.();+ return;+ }+ this.naturalWidth = icon.width;+ this.naturalHeight = icon.height;+ this.onload?.();+ });+ }+}++class FakeContext {+ private drawn: MockImage | null = null;++ drawImage(image: MockImage): void {+ this.drawn = image;+ }++ getImageData(): ImageData {+ const icon = this.drawn ? icons.get(this.drawn.src) : undefined;+ if (icon?.taint === true) {+ throw new DOMException('tainted canvas', 'SecurityError');+ }+ if (!icon?.pixels || icon.pixels.length === 0) {+ return new ImageData(1, 1);+ }+ const data = Uint8ClampedArray.from(icon.pixels);+ return new ImageData(data, data.length / 4, 1);+ }+}++/** Call from `beforeEach`; jsdom resets globals per test file, so no teardown. */+export function installCanvasMock(): void {+ Object.defineProperty(global, 'Image', {+ value: MockImage,+ configurable: true,+ writable: true,+ });+ Object.defineProperty(HTMLCanvasElement.prototype, 'getContext', {+ value: () => new FakeContext(),+ configurable: true,+ writable: true,+ });+}diff --git a/package-lock.json b/package-lock.jsonindex 84203145b1..465f677018 100644--- a/package-lock.json+++ b/package-lock.json@@ -91,6 +91,7 @@"cookie-parser": "^1.4.7","cors": "^2.8.5","dedent": "^1.5.3",+ "dompurify": "^3.4.12","dotenv": "^16.0.3","eventsource": "^3.0.2","express": "^5.2.1",@@ -106,6 +107,7 @@"https-proxy-agent": "^7.0.6","ioredis": "^5.3.2","js-yaml": "^4.2.0",+ "jsdom": "^26.1.0","jsonwebtoken": "^9.0.0","jszip": "^3.10.1","jwks-rsa": "^3.2.0",@@ -1374,7 +1376,6 @@"version": "3.2.0","resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz","integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==",- "dev": true,"license": "MIT","dependencies": {"@csstools/css-calc": "^2.1.3",@@ -1388,7 +1389,6 @@"version": "5.1.0","resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz","integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==",- "dev": true,"funding": [{"type": "github",@@ -1408,7 +1408,6 @@"version": "2.1.4","resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz","integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==",- "dev": true,"funding": [{"type": "github",@@ -1432,7 +1431,6 @@"version": "3.1.0","resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz","integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==",- "dev": true,"funding": [{"type": "github",@@ -1460,7 +1458,6 @@"version": "3.0.5","resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz","integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==",- "dev": true,"funding": [{"type": "github",@@ -1483,7 +1480,6 @@"version": "3.0.4","resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz","integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==",- "dev": true,"funding": [{"type": "github",@@ -1503,7 +1499,6 @@"version": "10.4.3","resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz","integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",- "dev": true,"license": "ISC"},"node_modules/@aws-crypto/crc32": {@@ -23380,7 +23375,6 @@"version": "4.6.0","resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz","integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==",- "dev": true,"license": "MIT","dependencies": {"@asamuzakjp/css-color": "^3.2.0",@@ -23937,7 +23931,6 @@"version": "5.0.0","resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz","integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==",- "dev": true,"license": "MIT","dependencies": {"whatwg-mimetype": "^4.0.0",@@ -27450,7 +27443,6 @@"version": "4.0.0","resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz","integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==",- "dev": true,"license": "MIT","dependencies": {"whatwg-encoding": "^3.1.1"@@ -28314,8 +28306,7 @@"node_modules/is-potential-custom-element-name": {"version": "1.0.1","resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",- "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",- "dev": true+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ=="},"node_modules/is-promise": {"version": "4.0.0",@@ -29987,7 +29978,6 @@"version": "26.1.0","resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz","integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",- "dev": true,"license": "MIT","dependencies": {"cssstyle": "^4.2.1",@@ -33896,7 +33886,6 @@"version": "2.2.23","resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.23.tgz","integrity": "sha512-7wfH4sLbt4M0gCDzGE6vzQBo0bfTKjU7Sfpqy/7gs1qBfYz2vEJH6vXcBKpO3+6Yu1telwd0t9HpyOoLEQQbIQ==",- "dev": true,"license": "MIT"},"node_modules/oauth": {@@ -38191,7 +38180,6 @@"version": "0.8.0","resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz","integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",- "dev": true,"license": "MIT"},"node_modules/rrweb-snapshot": {@@ -38455,7 +38443,6 @@"version": "6.0.0","resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz","integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",- "dev": true,"dependencies": {"xmlchars": "^2.2.0"},@@ -39663,8 +39650,7 @@"node_modules/symbol-tree": {"version": "3.2.4","resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",- "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",- "dev": true+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw=="},"node_modules/synckit": {"version": "0.9.2",@@ -40065,7 +40051,6 @@"version": "6.1.86","resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz","integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",- "dev": true,"license": "MIT","dependencies": {"tldts-core": "^6.1.86"@@ -40078,7 +40063,6 @@"version": "6.1.86","resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz","integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",- "dev": true,"license": "MIT"},"node_modules/tmpl": {@@ -40142,7 +40126,6 @@"version": "5.1.2","resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz","integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",- "dev": true,"license": "BSD-3-Clause","dependencies": {"tldts": "^6.1.32"@@ -41479,7 +41462,6 @@"version": "5.0.0","resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz","integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",- "dev": true,"license": "MIT","dependencies": {"xml-name-validator": "^5.0.0"@@ -42393,7 +42375,6 @@"version": "5.0.0","resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz","integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",- "dev": true,"license": "Apache-2.0","engines": {"node": ">=18"@@ -42447,8 +42428,7 @@"node_modules/xmlchars": {"version": "2.2.0","resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",- "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",- "dev": true+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw=="},"node_modules/xpath": {"version": "0.0.33",@@ -42639,6 +42619,7 @@"@types/express": "^5.0.0","@types/express-session": "^1.18.2","@types/jest": "^29.5.2",+ "@types/jsdom": "^21.1.7","@types/jsonwebtoken": "^9.0.0","@types/multer": "^1.4.13","@types/node": "^24.12.4",@@ -42701,6 +42682,7 @@"axios": "^1.20.0","connect-redis": "^8.1.0","dedent": "^1.5.3",+ "dompurify": "^3.4.12","eventsource": "^3.0.2","express": "^5.1.0","express-session": "^1.18.2",@@ -42711,6 +42693,7 @@"https-proxy-agent": "^7.0.6","ioredis": "^5.3.2","js-yaml": "^4.2.0",+ "jsdom": "^26.1.0","jsonwebtoken": "^9.0.0","jszip": "^3.10.1","jwks-rsa": "^3.2.0",diff --git a/packages/api/package.json b/packages/api/package.jsonindex 9e905bbff9..55a48f2495 100644--- a/packages/api/package.json+++ b/packages/api/package.json@@ -68,6 +68,7 @@"@types/express": "^5.0.0","@types/express-session": "^1.18.2","@types/jest": "^29.5.2",+ "@types/jsdom": "^21.1.7","@types/jsonwebtoken": "^9.0.0","@types/multer": "^1.4.13","@types/node": "^24.12.4",@@ -133,6 +134,7 @@"axios": "^1.20.0","connect-redis": "^8.1.0","dedent": "^1.5.3",+ "dompurify": "^3.4.12","eventsource": "^3.0.2","express": "^5.1.0","express-session": "^1.18.2",@@ -143,6 +145,7 @@"https-proxy-agent": "^7.0.6","ioredis": "^5.3.2","js-yaml": "^4.2.0",+ "jsdom": "^26.1.0","jsonwebtoken": "^9.0.0","jszip": "^3.10.1","jwks-rsa": "^3.2.0",diff --git a/packages/api/src/index.ts b/packages/api/src/index.tsindex f78709aca8..914b43a99e 100644--- a/packages/api/src/index.ts+++ b/packages/api/src/index.ts@@ -27,6 +27,7 @@ export * from './mcp/catalog/store';export * from './mcp/catalog/recovery';export * from './mcp/assistants';export * from './mcp/request';+export * from './mcp/icons';/* Utilities */export * from './mcp/utils';export * from './mcp/context';diff --git a/packages/api/src/mcp/icons.spec.ts b/packages/api/src/mcp/icons.spec.tsnew file mode 100644index 0000000000..b35663294d--- /dev/null+++ b/packages/api/src/mcp/icons.spec.ts@@ -0,0 +1,376 @@+import { MAX_MCP_ICON_PATH_LENGTH } from 'librechat-data-provider';+import type * as Icons from './icons';+import { sanitizeMcpIconPath } from './icons';++/** Decode the SVG body `sanitizeMcpIconPath` re-emits (base64 or percent-form). */+function decode(dataUri: string): string {+ const base64Prefix = 'data:image/svg+xml;base64,';+ if (dataUri.startsWith(base64Prefix)) {+ return Buffer.from(dataUri.slice(base64Prefix.length), 'base64').toString('utf-8');+ }+ return decodeURIComponent(dataUri.replace(/^data:image\/svg\+xml,/, ''));+}++describe('sanitizeMcpIconPath', () => {+ it('passes through non-SVG values untouched', () => {+ for (const value of [+ 'https://example.com/icon.png',+ '/assets/icon.png',+ 'data:image/png;base64,abc123',+ '',+ ]) {+ expect(sanitizeMcpIconPath(value)).toBe(value);+ }+ });++ it('strips scripts and event handlers from a percent-encoded SVG data URI', () => {+ const raw = '<svg onload="alert(1)"><script>alert(2)</script><path d="M0 0h1v1H0z"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).not.toContain('<script');+ expect(clean).not.toContain('onload');+ expect(clean).toContain('path');+ });++ it('strips active content from a base64-encoded SVG data URI (client bypass)', () => {+ const raw =+ '<svg><foreignObject><iframe src="javascript:alert(1)"></iframe></foreignObject><circle r="5"/></svg>';+ const input = `data:image/svg+xml;base64,${Buffer.from(raw, 'utf-8').toString('base64')}`;+ const clean = decode(sanitizeMcpIconPath(input)).toLowerCase();+ expect(clean).not.toContain('foreignobject');+ expect(clean).not.toContain('iframe');+ expect(clean).toContain('circle');+ });++ it('percent-decodes a base64 body before decoding it, as browsers do', () => {+ const raw = '<svg><path d="M0 0h1v1z"/></svg>';+ const escaped = encodeURIComponent(Buffer.from(raw, 'utf-8').toString('base64'));+ expect(escaped).toContain('%3D');+ const clean = decode(sanitizeMcpIconPath(`data:image/svg+xml;base64,${escaped}`));+ expect(clean).toBe('<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0h1v1z"></path></svg>');+ });++ it('drops a base64 body with a malformed percent escape', () => {+ expect(sanitizeMcpIconPath('data:image/svg+xml;base64,PHN2Zz48L3N2Zz4%zz')).toBe('');+ });++ it('drops external references that would let an SVG phone home', () => {+ const raw =+ '<svg><image href="https://evil.example/track.png"/><use href="https://evil.example/x.svg#a"/><path d="M0 0h1v1H0z"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).not.toContain('evil.example');+ expect(clean).toContain('path');+ });++ it('strips relative-path and javascript: hrefs from <use>', () => {+ for (const href of ['icons.svg#a', '//evil.example/x.svg#a', 'javascript:alert(1)']) {+ const input = `data:image/svg+xml,${encodeURIComponent(`<svg><use href="${href}"/></svg>`)}`;+ expect(decode(sanitizeMcpIconPath(input))).not.toContain('href');+ }+ });++ it('preserves local <defs>/<use> references', () => {+ const raw = '<svg><defs><path id="p" d="M0 0h10v10H0z"/></defs><use href="#p"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).toContain('<use href="#p"');+ expect(clean).toContain('d="M0 0h10v10H0z"');+ });++ it('preserves local xlink:href references and gradient inheritance', () => {+ const raw =+ '<svg><defs><path id="p" d="M0 0h1v1z"/></defs><use xlink:href="#p"/><linearGradient id="g2" href="#g" x1="0" x2="1"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).toContain('xlink:href="#p"');+ expect(clean).toContain('href="#g"');+ expect(clean).toContain('x1="0"');+ });++ it('keeps the xmlns:xlink declaration that binds preserved xlink:href prefixes', () => {+ const raw =+ '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><path id="p" d="M0 0h1v1z"/></defs><use xlink:href="#p"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).toContain('xmlns:xlink="http://www.w3.org/1999/xlink"');+ expect(clean).toContain('xlink:href="#p"');+ });++ it('preserves textPath labels with fragment-only path references', () => {+ const raw =+ '<svg viewBox="0 0 24 24"><defs><path id="curve" d="M0 10C5 0 15 0 20 10"/></defs><text><textPath href="#curve" startOffset="10%">Hi</textPath></text></svg>';+ const clean = decode(sanitizeMcpIconPath(`data:image/svg+xml,${encodeURIComponent(raw)}`));+ expect(clean).toContain('<textPath href="#curve"');+ expect(clean).toContain('startOffset="10%"');++ const external =+ '<svg><text><textPath href="https://evil.example/x.svg#curve">Hi</textPath></text></svg>';+ const cleanExternal = decode(+ sanitizeMcpIconPath(`data:image/svg+xml,${encodeURIComponent(external)}`),+ );+ expect(cleanExternal).toContain('<textPath');+ expect(cleanExternal).not.toContain('href');+ });++ it('preserves color scopes that feed currentColor paint', () => {+ const raw =+ '<svg color="#e00"><path fill="currentColor" d="M0 0h1v1z"/><g color="#00f"><path stroke="currentColor" d="M2 2h1v1z"/></g></svg>';+ const clean = decode(sanitizeMcpIconPath(`data:image/svg+xml,${encodeURIComponent(raw)}`));+ expect(clean).toContain('color="#e00"');+ expect(clean).toContain('fill="currentColor"');+ expect(clean).toContain('color="#00f"');+ });++ it('preserves marker definitions and fragment-only marker references', () => {+ const raw =+ '<svg viewBox="0 0 24 24"><defs><marker id="arrow" markerWidth="10" markerHeight="10" refX="5" refY="5" orient="auto"><path d="M0 0L10 5L0 10z"/></marker></defs><line x1="2" y1="2" x2="20" y2="20" stroke="#000" marker-end="url(#arrow)"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).toContain('<marker id="arrow"');+ expect(clean).toContain('markerWidth="10"');+ expect(clean).toContain('refX="5"');+ expect(clean).toContain('orient="auto"');+ expect(clean).toContain('marker-end="url(#arrow)"');+ });++ it('drops url() references that leave the document, whichever property carries them', () => {+ for (const attribute of ['marker-end', 'fill', 'stroke', 'filter', 'mask', 'clip-path']) {+ for (const ref of [+ 'url(https://evil.example/m.svg#a)',+ 'url(//evil.example/m.svg#a)',+ "url('/m.svg#a')",+ ]) {+ const raw = `<svg><line x1="0" y1="0" x2="9" y2="9" ${attribute}="${ref}"/></svg>`;+ const clean = decode(sanitizeMcpIconPath(`data:image/svg+xml,${encodeURIComponent(raw)}`));+ expect(clean).not.toContain('evil.example');+ expect(clean).not.toContain(attribute);+ expect(clean).toContain('line');+ }+ }+ });++ it('preserves safe filter effects the client sanitizer allows', () => {+ const raw =+ '<svg><filter id="f"><feDropShadow dx="1" dy="1" stdDeviation="0.5" flood-color="#000" flood-opacity="0.4"/><feGaussianBlur in="SourceGraphic" stdDeviation="2" result="b"/><feOffset in="b" dx="2" dy="2"/><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter><rect width="10" height="10" filter="url(#f)"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).toContain('feDropShadow');+ expect(clean).toContain('feGaussianBlur');+ expect(clean).toContain('stdDeviation="2"');+ expect(clean).toContain('flood-color="#000"');+ expect(clean).toContain('filter="url(#f)"');+ });++ it('strips external feImage references inside filters', () => {+ const raw =+ '<svg><filter id="f"><feImage href="https://evil.example/x.png"/></filter><rect filter="url(#f)"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).not.toContain('evil.example');+ });++ it('strips stylesheet blocks and inline style attributes', () => {+ const raw =+ '<svg><style>.red{fill:#e00}</style><path class="red" style="stroke:#00f" fill="#e00" d="M0 0h1v1z"/></svg>';+ const clean = decode(sanitizeMcpIconPath(`data:image/svg+xml,${encodeURIComponent(raw)}`));+ expect(clean).not.toContain('<style');+ expect(clean).not.toContain('style=');+ expect(clean).toContain('fill="#e00"');+ });++ it('preserves local url() paint and filter references', () => {+ const raw =+ '<svg><defs><filter id="f"><feGaussianBlur stdDeviation="1"/></filter><linearGradient id="g"><stop offset="0" stop-color="#000"/></linearGradient></defs><rect fill="url(#g)" filter="url(#f)" width="10" height="10"/></svg>';+ const clean = decode(sanitizeMcpIconPath(`data:image/svg+xml,${encodeURIComponent(raw)}`));+ expect(clean).toContain('fill="url(#g)"');+ expect(clean).toContain('filter="url(#f)"');+ });++ it('preserves pattern coordinate-system attributes (parity with client SVG profile)', () => {+ const raw =+ '<svg viewBox="0 0 24 24"><defs><pattern id="p" width="4" height="4" patternUnits="userSpaceOnUse" patternContentUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="2" height="2" fill="#000"/></pattern></defs><rect width="24" height="24" fill="url(#p)"/></svg>';+ const clean = decode(sanitizeMcpIconPath(`data:image/svg+xml,${encodeURIComponent(raw)}`));+ expect(clean).toContain('patternUnits="userSpaceOnUse"');+ expect(clean).toContain('patternContentUnits="userSpaceOnUse"');+ expect(clean).toContain('patternTransform="rotate(45)"');+ expect(clean).toContain('fill="url(#p)"');+ });++ it('preserves gradient coordinate-system attributes', () => {+ const raw =+ '<svg><defs><linearGradient id="g" gradientUnits="userSpaceOnUse" gradientTransform="translate(1 2)" x1="0" y1="0" x2="10" y2="10"><stop offset="0" stop-color="#f00"/></linearGradient></defs><rect fill="url(#g)" width="10" height="10"/></svg>';+ const clean = decode(sanitizeMcpIconPath(`data:image/svg+xml,${encodeURIComponent(raw)}`));+ expect(clean).toContain('gradientUnits="userSpaceOnUse"');+ expect(clean).toContain('gradientTransform="translate(1 2)"');+ });++ it('preserves case-sensitive SVG names and multi-color paint', () => {+ const raw =+ '<svg viewBox="0 0 24 24"><linearGradient id="g"><stop offset="0" stop-color="#f00"/></linearGradient><path d="M0 0h24v24H0z" fill="url(#g)"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).toContain('viewBox');+ expect(clean).toContain('linearGradient');+ expect(clean).toContain('fill="url(#g)"');+ });++ it('declares the SVG namespace on a root that omits it', () => {+ const raw = '<svg viewBox="0 0 8 8"><path d="M0 0h1v1z"/></svg>';+ const clean = decode(sanitizeMcpIconPath(`data:image/svg+xml,${encodeURIComponent(raw)}`));+ expect(clean.startsWith('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8">')).toBe(+ true,+ );+ });++ it('does not duplicate an existing namespace declaration', () => {+ const raw = '<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0h1v1z"/></svg>';+ const clean = decode(sanitizeMcpIconPath(`data:image/svg+xml,${encodeURIComponent(raw)}`));+ expect(clean.match(/xmlns=/g)).toHaveLength(1);+ });++ it('sanitizes an SVG data URI hidden behind leading whitespace or controls', () => {+ const evil = '<svg><image href="https://evil.example/x.png"/><path d="M0 0h1v1z"/></svg>';+ const body = `data:image/svg+xml,${encodeURIComponent(evil)}`;+ for (const prefix of ['\n ', '\t', ' \r\n', ' ', ' ']) {+ const clean = decode(sanitizeMcpIconPath(prefix + body));+ expect(clean).not.toContain('evil.example');+ expect(clean).toContain('path');+ }+ });++ it('sanitizes an SVG data URI whose media type hides an embedded newline', () => {+ const evil = '<svg><image href="https://evil.example/x.png"/></svg>';+ const input = `data:image/svg+x\nml,${encodeURIComponent(evil)}`;+ expect(decode(sanitizeMcpIconPath(input))).not.toContain('evil.example');+ });++ it('returns an empty string for a malformed SVG data URI', () => {+ expect(sanitizeMcpIconPath('data:image/svg+xml')).toBe('');+ });++ it('keeps the sanitized output within the schema length cap', () => {+ const raw = `<svg><text>${'A'.repeat(150_000)}</text></svg>`;+ const input = `data:image/svg+xml;base64,${Buffer.from(raw, 'utf-8').toString('base64')}`;+ expect(input.length).toBeLessThanOrEqual(MAX_MCP_ICON_PATH_LENGTH);+ const out = sanitizeMcpIconPath(input);+ expect(out.length).toBeLessThanOrEqual(MAX_MCP_ICON_PATH_LENGTH);+ expect(decode(out)).toContain('AAAA');+ });++ it('never stores an icon over the length cap even when sanitizing grows it', () => {+ // self-closing tags expand to explicit close tags under sanitization+ const cell = '<rect x="1" y="1" width="2" height="2" fill="#abc"/>';+ const raw = `<svg>${cell.repeat(3400)}</svg>`;+ const input = `data:image/svg+xml;base64,${Buffer.from(raw, 'utf-8').toString('base64')}`;+ expect(input.length).toBeLessThanOrEqual(MAX_MCP_ICON_PATH_LENGTH);+ const out = sanitizeMcpIconPath(input);+ expect(out.length).toBeLessThanOrEqual(MAX_MCP_ICON_PATH_LENGTH);+ expect(out).toBe('');+ });++ it('drops an over-cap non-SVG value (raster data URI) that cannot be compacted', () => {+ const huge = `data:image/png;base64,${'A'.repeat(MAX_MCP_ICON_PATH_LENGTH)}`;+ expect(huge.length).toBeGreaterThan(MAX_MCP_ICON_PATH_LENGTH);+ expect(sanitizeMcpIconPath(huge)).toBe('');+ });++ it('passes an under-cap non-SVG value through unchanged', () => {+ const ok = `data:image/png;base64,${'A'.repeat(1000)}`;+ expect(sanitizeMcpIconPath(ok)).toBe(ok);+ });++ it('strips every SMIL animation element so a stored icon cannot loop', () => {+ const raw =+ '<svg><rect width="1" height="1">' ++ '<animate attributeName="x"/><set attributeName="y" to="1"/>' ++ '<animateColor attributeName="fill"/>' ++ '<animateTransform attributeName="transform" type="rotate" repeatCount="indefinite"/>' ++ '<animateMotion dur="2s"><mpath href="#p"/></animateMotion>' ++ '</rect></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input)).toLowerCase();+ for (const tag of [+ '<animate',+ '<animatecolor',+ '<animatetransform',+ '<animatemotion',+ '<mpath',+ '<set',+ ]) {+ expect(clean).not.toContain(tag);+ }+ expect(clean).toContain('rect');+ });++ it('drops an attribute whose later url() leaves the document', () => {+ const raw =+ '<svg><path filter="url(#safe) url(https://evil.example/f.svg#f)" ' ++ 'mask="url(#a), url(https://evil.example/m.svg#b)" d="M0 0h1v1z"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).not.toContain('evil.example');+ expect(clean).toContain('M0 0h1v1z');+ });++ it('drops a CSS-escaped url() the browser would still resolve', () => {+ const raw = '<svg><path fill="u\\72l(https://evil.example/p.svg#x)" d="M0 0h1v1z"/></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).not.toContain('evil.example');+ expect(clean).toContain('M0 0h1v1z');+ });++ it('preserves radial-gradient focal geometry', () => {+ const raw =+ '<svg><radialGradient id="g" fx="0.1" fy="0.2" fr="0.3" spreadMethod="reflect">' ++ '<stop stop-color="#000"/></radialGradient></svg>';+ const input = `data:image/svg+xml,${encodeURIComponent(raw)}`;+ const clean = decode(sanitizeMcpIconPath(input));+ expect(clean).toContain('fr="0.3"');+ expect(clean).toContain('spreadMethod="reflect"');+ });++ it('drops an oversized SVG before building a DOM for it', () => {+ // the payload sanitizes to an empty <svg>, so only a pre-parse size check can reject it+ const raw = `<svg><script>${'a'.repeat(MAX_MCP_ICON_PATH_LENGTH + 1)}</script></svg>`;+ const input = `data:image/svg+xml;base64,${Buffer.from(raw, 'utf-8').toString('base64')}`;+ expect(sanitizeMcpIconPath(input)).toBe('');+ });+});++describe('sanitizeMcpIconPath dependency loading', () => {+ afterEach(() => {+ jest.dontMock('jsdom');+ jest.dontMock('dompurify');+ jest.resetModules();+ });++ it('does not load jsdom or dompurify until an SVG data URI is sanitized', () => {+ jest.resetModules();+ const loadJsdom = jest.fn();+ const loadDompurify = jest.fn();+ jest.doMock('jsdom', () => {+ loadJsdom();+ return jest.requireActual('jsdom');+ });+ jest.doMock('dompurify', () => {+ loadDompurify();+ return jest.requireActual('dompurify');+ });++ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { sanitizeMcpIconPath: sanitize } = require('./icons') as typeof Icons;++ expect(loadJsdom).not.toHaveBeenCalled();+ expect(loadDompurify).not.toHaveBeenCalled();++ sanitize('https://example.com/icon.png');+ expect(loadJsdom).not.toHaveBeenCalled();+ expect(loadDompurify).not.toHaveBeenCalled();++ sanitize(`data:image/svg+xml,${encodeURIComponent('<svg><path d="M0 0h1v1z"/></svg>')}`);+ expect(loadJsdom).toHaveBeenCalledTimes(1);+ expect(loadDompurify).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/api/src/mcp/icons.ts b/packages/api/src/mcp/icons.tsnew file mode 100644index 0000000000..f4f5941a79--- /dev/null+++ b/packages/api/src/mcp/icons.ts@@ -0,0 +1,66 @@+import {+ MAX_MCP_ICON_PATH_LENGTH,+ SVG_SANITIZE_CONFIG,+ restrictSvgReferences,+ finalizeSvgMarkup,+} from 'librechat-data-provider';+import type { DOMPurify } from 'dompurify';+import type { JSDOM } from 'jsdom';++const SVG_DATA_URI = /^data:image\/svg\+xml/i;++let purifier: DOMPurify | null = null;++/** jsdom and dompurify load on first use so the api barrel stays cheap to require. */+function getSvgPurifier(): DOMPurify {+ if (purifier) {+ return purifier;+ }+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const jsdom = require('jsdom') as { JSDOM: typeof JSDOM };+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const loaded = require('dompurify') as DOMPurify | { default: DOMPurify };+ const create = typeof loaded === 'function' ? loaded : loaded.default;+ purifier = create(new jsdom.JSDOM('').window);+ purifier.addHook('afterSanitizeAttributes', restrictSvgReferences);+ return purifier;+}++/** Decodes like the `data:` URL processor: percent-decode, then base64 if flagged. */+function decodeSvgDataUri(iconPath: string): string | null {+ const comma = iconPath.indexOf(',');+ if (comma === -1) {+ return null;+ }+ let body: string;+ try {+ body = decodeURIComponent(iconPath.slice(comma + 1));+ } catch {+ return null;+ }+ return /;base64/i.test(iconPath.slice(0, comma))+ ? Buffer.from(body, 'base64').toString('utf-8')+ : body;+}++/**+ * Sanitizes a user-provided MCP `iconPath` at the trust boundary. SVG data URIs+ * are re-sanitized with the shared policy and re-encoded as base64; other values+ * pass through. Any value still over `MAX_MCP_ICON_PATH_LENGTH` becomes an empty+ * string, so editing a server whose stored icon predates the cap clears the icon+ * instead of failing validation.+ */+export function sanitizeMcpIconPath(iconPath: string): string {+ /* Strip what the browser's URL parser strips, so `\n data:...` cannot dodge the check. */+ const normalized = iconPath.replace(/^[\0-\x20]+|[\0-\x20]+$/g, '').replace(/[\t\n\r]/g, '');+ if (!SVG_DATA_URI.test(normalized)) {+ return iconPath.length > MAX_MCP_ICON_PATH_LENGTH ? '' : iconPath;+ }+ const svg = decodeSvgDataUri(normalized);+ if (svg == null || svg.length > MAX_MCP_ICON_PATH_LENGTH) {+ return '';+ }+ const clean = finalizeSvgMarkup(getSvgPurifier().sanitize(svg, SVG_SANITIZE_CONFIG));+ const encoded = `data:image/svg+xml;base64,${Buffer.from(clean, 'utf-8').toString('base64')}`;+ return encoded.length > MAX_MCP_ICON_PATH_LENGTH ? '' : encoded;+}diff --git a/packages/data-provider/specs/mcp.spec.ts b/packages/data-provider/specs/mcp.spec.tsindex 31c8ac160f..b0e1210b3d 100644--- a/packages/data-provider/specs/mcp.spec.ts+++ b/packages/data-provider/specs/mcp.spec.ts@@ -4,6 +4,7 @@ import {StreamableHTTPOptionsSchema,MCPServerUserInputSchema,MCP_USER_INPUT_FIELDS,+ MAX_MCP_ICON_PATH_LENGTH,} from '../src/mcp';describe('MCP server title validation', () => {@@ -224,6 +225,17 @@ describe('MCP schemas', () => {});});+ describe('iconPath', () => {+ it('accepts an over-limit iconPath so editing a server with a pre-existing oversized icon is not rejected (the cap is enforced server-side by sanitizeMcpIconPath, not at parse time)', () => {+ const result = MCPServerUserInputSchema.safeParse({+ type: 'streamable-http',+ url: 'https://mcp-server.com/http',+ iconPath: `data:image/png;base64,${'A'.repeat(MAX_MCP_ICON_PATH_LENGTH + 1000)}`,+ });+ expect(result.success).toBe(true);+ });+ });+describe('env variable rejection', () => {it('should reject SSE URLs containing env variable patterns', () => {const result = MCPServerUserInputSchema.safeParse({diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.tsindex 6b5e3e5fe2..8d2030b436 100644--- a/packages/data-provider/src/index.ts+++ b/packages/data-provider/src/index.ts@@ -57,6 +57,8 @@ export { dataService };import * as dataService from './data-service';/* provider identity */export * from './providers';+/* icon sanitization policy */+export * from './svg';/* general helpers */export * from './utils';export * from './actions';diff --git a/packages/data-provider/src/mcp.ts b/packages/data-provider/src/mcp.tsindex 50e9dae2b1..b39a4959ea 100644--- a/packages/data-provider/src/mcp.ts+++ b/packages/data-provider/src/mcp.ts@@ -2,6 +2,13 @@ import { z } from 'zod';import { TokenExchangeMethodEnum } from './types/agents';import { extractEnvVariable } from './utils';+/**+ * Upper bound on a stored MCP `iconPath` (URL or data URI). Enforced by+ * `sanitizeMcpIconPath`, not a schema `.max()`, so re-submitting a server whose+ * stored icon predates the cap clears the icon instead of rejecting the update.+ */+export const MAX_MCP_ICON_PATH_LENGTH = 256 * 1024;+const validateOAuthClientCredentials = (oauth: {client_id?: string;diff --git a/packages/data-provider/src/svg.ts b/packages/data-provider/src/svg.tsnew file mode 100644index 0000000000..b1a6131f44--- /dev/null+++ b/packages/data-provider/src/svg.ts@@ -0,0 +1,101 @@+/**+ * DOMPurify policy for user-provided SVG icons, shared by the browser uploader and+ * the server trust boundary so a preview and the persisted icon cannot disagree.+ * `use` is re-added for self-contained `<defs>` references (targets restricted by+ * `restrictSvgReferences`); every SMIL element is forbidden so a stored icon+ * cannot animate forever wherever it renders.+ */+export const SVG_SANITIZE_CONFIG = {+ USE_PROFILES: { svg: true, svgFilters: true },+ ADD_TAGS: ['use'],+ ADD_ATTR: ['fr'],+ FORBID_TAGS: [+ 'script',+ 'foreignObject',+ 'style',+ 'a',+ 'image',+ 'animate',+ 'animateColor',+ 'animateMotion',+ 'animateTransform',+ 'mpath',+ 'set',+ ],+ FORBID_ATTR: ['style'],+};++/** Element surface shared by the browser DOM and the server's jsdom. */+export interface SvgAttributeHost {+ attributes: ArrayLike<{ name: string }>;+ getAttribute(name: string): string | null;+ removeAttribute(name: string): void;+}++const URL_TOKEN_PREFIX = /url\(\s*['"]?\s*/gi;++/**+ * True when every `url()` token targets a fragment. Backslashes reject the value+ * outright: CSS unescapes idents before tokenizing, so `u\72l(...)` is a `url()`.+ */+function referencesOnlyFragments(value: string): boolean {+ if (value.includes('\\')) {+ return false;+ }+ if (!value.toLowerCase().includes('url(')) {+ return true;+ }+ URL_TOKEN_PREFIX.lastIndex = 0;+ while (URL_TOKEN_PREFIX.exec(value) !== null) {+ if (value[URL_TOKEN_PREFIX.lastIndex] !== '#') {+ return false;+ }+ }+ return true;+}++/** DOMPurify hook that drops every attribute referencing outside the document. */+export function restrictSvgReferences(node: SvgAttributeHost): void {+ const names: string[] = [];+ for (let i = 0; i < node.attributes.length; i += 1) {+ names.push(node.attributes[i].name);+ }+ for (const name of names) {+ const value = node.getAttribute(name)?.trim();+ if (value == null) {+ continue;+ }+ if (name === 'href' || name === 'xlink:href') {+ if (!value.startsWith('#')) {+ node.removeAttribute(name);+ }+ continue;+ }+ if (!referencesOnlyFragments(value)) {+ node.removeAttribute(name);+ }+ }+}++/** SVG names the HTML parser lowercases and its adjustment table does not restore. */+const UNADJUSTED_SVG_TAGS: Array<[RegExp, string]> = [[/(<\/?)fedropshadow\b/gi, '$1feDropShadow']];++const SVG_ROOT_TAG = /<svg(\s[^>]*)?>/i;++/**+ * Makes HTML-mode sanitizer output valid as a standalone `image/svg+xml`+ * document: restores camelCase element names the HTML parser lowercased and+ * declares the SVG namespace on the root, without which an XML parser puts the+ * root in no namespace and the icon renders blank.+ */+export function finalizeSvgMarkup(markup: string): string {+ let restored = markup;+ for (const [pattern, canonical] of UNADJUSTED_SVG_TAGS) {+ restored = restored.replace(pattern, canonical);+ }+ return restored.replace(SVG_ROOT_TAG, (tag, attributes: string | undefined) =>+ attributes != null && /\sxmlns\s*=/i.test(attributes)+ ? tag+ : `<svg xmlns="http://www.w3.org/2000/svg"${attributes ?? ''}>`,+ );+}