π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(security): remove `/webapi/proxy` and dead URL-manifest plugin code (#14549)
Arvin Xucb8645f65a1c
diff --git a/packages/model-runtime/src/providers/newapi/index.test.ts b/packages/model-runtime/src/providers/newapi/index.test.tsindex 89e8284540a..2872cf2f1d1 100644--- a/packages/model-runtime/src/providers/newapi/index.test.ts+++ b/packages/model-runtime/src/providers/newapi/index.test.ts@@ -14,7 +14,6 @@ vi.mock('../../utils/modelParse');// Mock console methodsvi.spyOn(console, 'error').mockImplementation(() => {});-vi.spyOn(console, 'debug').mockImplementation(() => {});// Type definitions for test datainterface MockPricingResponse {@@ -242,14 +241,9 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {});it('should handle network error (Branch 3.18: error handling)', () => {- let errorCaught = false;- try {+ expect(() => {throw new Error('Network error');- } catch (error) {- errorCaught = true;- expect(error).toBeInstanceOf(Error);- }- expect(errorCaught).toBe(true);+ }).toThrow(Error);});});@@ -1076,10 +1070,6 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {const result = await params.models({ client: mockClient as any });- expect(console.debug).toHaveBeenCalledWith(- 'Failed to fetch NewAPI pricing info:',- expect.any(Error),- );expect(result[0].pricing).toBeUndefined();});diff --git a/packages/model-runtime/src/providers/newapi/index.ts b/packages/model-runtime/src/providers/newapi/index.tsindex 40fa7e27e2a..627463e7bff 100644--- a/packages/model-runtime/src/providers/newapi/index.ts+++ b/packages/model-runtime/src/providers/newapi/index.ts@@ -26,59 +26,23 @@ export interface NewAPIPricing {supported_endpoint_types?: string[];}-/**- * Detect if running in browser environment- */-const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';--/**- * Parse a pricing API HTTP response into a `NewAPIPricing[] | null`.- * Shared between browser and server branches to avoid duplicated logic.- */-const parsePricingResponse = async (res: Response): Promise<NewAPIPricing[] | null> => {- if (!res.ok) {- return null;- }-- try {- const body = await res.json();- return body?.success && body?.data ? (body.data as NewAPIPricing[]) : null;- } catch {- return null;- }-};--/**- * Fetch pricing information with CORS bypass for client-side requests- * In browser environment, use /webapi/proxy to avoid CORS errors- */const fetchPricing = async (pricingUrl: string,apiKey: string,): Promise<NewAPIPricing[] | null> => {try {- if (isBrowser()) {- // In browser environment, use the proxy endpoint to avoid CORS- // The proxy endpoint expects the URL as the request body- const proxyResponse = await fetch('/webapi/proxy', {- body: pricingUrl,- method: 'POST',- });+ const res = await fetch(pricingUrl, {+ headers: {+ Accept: 'application/json; charset=utf-8',+ Authorization: `Bearer ${apiKey}`,+ },+ });- return await parsePricingResponse(proxyResponse);- } else {- // In server environment, fetch directly with proper encoding headers- const pricingResponse = await fetch(pricingUrl, {- headers: {- Accept: 'application/json; charset=utf-8',- Authorization: `Bearer ${apiKey}`,- },- });+ if (!res.ok) return null;- return await parsePricingResponse(pricingResponse);- }- } catch (error) {- console.debug('Failed to fetch NewAPI pricing info:', error);+ const body = await res.json();+ return body?.success && body?.data ? (body.data as NewAPIPricing[]) : null;+ } catch {return null;}};diff --git a/packages/utils/src/toolManifest.ts b/packages/utils/src/toolManifest.tsdeleted file mode 100644index 114509aca45..00000000000--- a/packages/utils/src/toolManifest.ts+++ /dev/null@@ -1,54 +0,0 @@-import type { ToolManifest } from '@lobechat/types';-import { ToolManifestSchema } from '@lobechat/types';--import { API_ENDPOINTS } from '@/services/_url';--const fetchJSON = async <T = any>(url: string, proxy = false): Promise<T> => {- let res: Response;- try {- res = await (proxy ? fetch(API_ENDPOINTS.proxy, { body: url, method: 'POST' }) : fetch(url));- } catch {- throw new TypeError('fetchError');- }-- if (!res.ok) {- throw new TypeError('fetchError');- }-- let data;- const contentType = res.headers.get('Content-Type');-- try {- if (contentType === 'application/json') {- data = await res.json();- } else {- const { default: YAML } = await import('yaml');-- const yaml = await res.text();- data = YAML.parse(yaml);- }- } catch {- throw new TypeError('urlError');- }-- return data;-};--export const getToolManifest = async (- url?: string,- useProxy: boolean = false,-): Promise<ToolManifest> => {- if (!url) {- throw new TypeError('noManifest');- }-- const data = await fetchJSON<ToolManifest>(url, useProxy);-- const parser = ToolManifestSchema.safeParse(data);-- if (!parser.success) {- throw new TypeError('manifestInvalid', { cause: parser.error });- }-- return data;-};diff --git a/src/app/(backend)/webapi/proxy/route.ts b/src/app/(backend)/webapi/proxy/route.tsdeleted file mode 100644index 4888d32f94f..00000000000--- a/src/app/(backend)/webapi/proxy/route.ts+++ /dev/null@@ -1,24 +0,0 @@-import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';-import { NextResponse } from 'next/server';--/**- * just for a proxy- */-export const POST = async (req: Request) => {- const url = await req.text();-- try {- const res = await ssrfSafeFetch(url);-- // Clone headers and remove Content-Encoding because fetch() automatically- // decompresses the response body, so we should not forward this header- const headers = new Headers(res.headers);- headers.delete('Content-Encoding');- headers.delete('Content-Length'); // Length changes after decompression-- return new Response(await res.arrayBuffer(), { headers });- } catch (err) {- console.error(err); // DNS lookup 127.0.0.1(family:4, host:127.0.0.1.nip.io) is not allowed. Because, It is private IP address.- return NextResponse.json({ error: 'Not support internal host proxy' }, { status: 400 });- }-};diff --git a/src/features/PluginDevModal/UrlManifestForm.tsx b/src/features/PluginDevModal/UrlManifestForm.tsxdeleted file mode 100644index 2395a66284c..00000000000--- a/src/features/PluginDevModal/UrlManifestForm.tsx+++ /dev/null@@ -1,135 +0,0 @@-import { BRANDING_NAME } from '@lobechat/business-const';-import { type ToolManifest } from '@lobechat/types';-import { ActionIcon, Checkbox, Flexbox, FormItem, Input } from '@lobehub/ui';-import { type FormInstance } from 'antd';-import { Form } from 'antd';-import { FileCode, RotateCwIcon } from 'lucide-react';-import { memo, useState } from 'react';-import { useTranslation } from 'react-i18next';--import ManifestPreviewer from '@/components/ManifestPreviewer';-import { toolService } from '@/services/tool';-import { useToolStore } from '@/store/tool';-import { pluginSelectors } from '@/store/tool/selectors';-import { type PluginInstallError } from '@/types/tool/plugin';--interface ProxyCheckerProps {- onChange?: (value: boolean) => void;- value?: boolean;-}--const ProxyChecker = memo<ProxyCheckerProps>(({ value, onChange }) => {- const { t } = useTranslation('plugin');-- return (- <Flexbox- horizontal- gap={8}- style={{ cursor: 'pointer' }}- onClick={() => {- onChange?.(!value);- }}- >- <Checkbox checked={value} /> {t('dev.customParams.useProxy.label')}- </Flexbox>- );-});--const UrlManifestForm = memo<{ form: FormInstance; isEditMode: boolean }>(- ({ form, isEditMode }) => {- const { t } = useTranslation('plugin');-- const [manifest, setManifest] = useState<ToolManifest>();-- const urlKey = ['customParams', 'manifestUrl'];- const proxyKey = ['customParams', 'useProxy'];- const pluginIds = useToolStore(pluginSelectors.storeAndInstallPluginsIdList);-- return (- <Form form={form} layout={'vertical'}>- <FormItem- hasFeedback- required- label={t('dev.meta.manifest.label')}- name={urlKey}- style={{ marginBottom: 0 }}- desc={- <Flexbox horizontal justify={'space-between'} style={{ marginTop: 8 }}>- {t('dev.meta.manifest.desc', { appName: BRANDING_NAME })}- {manifest && (- <ManifestPreviewer manifest={manifest}>- <ActionIcon- icon={FileCode}- size={'small'}- title={t('dev.meta.manifest.preview')}- />- </ManifestPreviewer>- )}- </Flexbox>- }- rules={[- { required: true },- {- message: t('error.urlError'),- pattern: /^https?:\/\/.*/,- },- {- validator: async (_, value) => {- if (!value) return true;-- try {- const useProxy = form.getFieldValue(proxyKey);- const data = await toolService.getToolManifest(value, useProxy);- setManifest(data);-- form.setFieldsValue({ identifier: data.identifier, manifest: data });- } catch (error) {- const err = error as PluginInstallError;- throw t(`error.${err.message}`, { error: err.cause! });- }- },- },- // In edit mode, skip duplicate validation- isEditMode- ? {}- : {- message: t('dev.meta.identifier.errorDuplicate'),- validator: async () => {- const id = form.getFieldValue('identifier');- if (!id) return true;-- if (pluginIds.includes(id)) {- throw new Error('Duplicate');- }- },- },- ]}- >- <Input- placeholder={'http://localhost:3400/manifest-dev.json'}- suffix={- <ActionIcon- icon={RotateCwIcon}- size={'small'}- title={t('dev.meta.manifest.refresh')}- onClick={(e) => {- e.stopPropagation();- form.validateFields([urlKey, 'identifier']);- }}- />- }- />- </FormItem>-- <FormItem noStyle name={proxyKey}>- <ProxyChecker />- </FormItem>-- <FormItem noStyle name={'identifier'} />- <FormItem noStyle name={'manifest'} />- </Form>- );- },-);--export default UrlManifestForm;diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex 5d9fa76b492..be7d7eb499b 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -359,8 +359,6 @@ export default {'detailModal.tabs.settings': 'Settings','detailModal.title': 'Skill details','dev.confirmDeleteDevPlugin': 'This local Skill will be deleted permanently. Continue?',- 'dev.customParams.useProxy.label':- 'Install via proxy (enable if encountering CORS errors, then retry)','dev.deleteSuccess': 'Skill deleted','dev.manifest.identifier.desc': 'Unique identifier for the Skill','dev.manifest.identifier.label': 'Identifier',diff --git a/src/server/services/discover/index.test.ts b/src/server/services/discover/index.test.tsindex e72e0be0e11..f28955ac75d 100644--- a/src/server/services/discover/index.test.ts+++ b/src/server/services/discover/index.test.ts@@ -11,7 +11,6 @@ import { DiscoverService } from './index';vi.mock('@/server/modules/AssistantStore');vi.mock('@/server/modules/PluginStore');vi.mock('@lobehub/market-sdk');-vi.mock('@/utils/toolManifest');vi.mock('@/locales/resources', () => ({normalizeLocale: vi.fn((locale) => {if (locale === 'en-US') return 'en';diff --git a/src/services/__tests__/_url.test.ts b/src/services/__tests__/_url.test.tsindex e4d5718c4ab..24ae71fc515 100644--- a/src/services/__tests__/_url.test.ts+++ b/src/services/__tests__/_url.test.ts@@ -5,7 +5,6 @@ import { API_ENDPOINTS } from '../_url';describe('API_ENDPOINTS', () => {it('should return correct basePath URLs', () => {expect(API_ENDPOINTS.oauth).toBe('/api/auth');- expect(API_ENDPOINTS.proxy).toBe('/webapi/proxy');expect(API_ENDPOINTS.trace).toBe('/webapi/trace');expect(API_ENDPOINTS.stt).toBe('/webapi/stt/openai');expect(API_ENDPOINTS.edge).toBe('/webapi/tts/edge');diff --git a/src/services/__tests__/tool.test.ts b/src/services/__tests__/tool.test.tsdeleted file mode 100644index de821b62255..00000000000--- a/src/services/__tests__/tool.test.ts+++ /dev/null@@ -1,137 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { toolService } from '../tool';--// Mocking modules and functions--vi.mock('@/store/global/helpers', () => ({- globalHelpers: {- getCurrentLanguage: vi.fn(),- },-}));--vi.mock('@/libs/trpc/client', () => ({- edgeClient: {- market: {- getLegacyPluginList: {- query: vi.fn(),- },- },- },-}));--beforeEach(() => {- vi.resetAllMocks();-});--describe('ToolService', () => {- describe('getToolManifest', () => {- it('should return manifest', async () => {- const manifestUrl = 'http://fake-url.com/manifest.json';-- const fakeManifest = {- api: [- {- url: 'https://realtime-weather.chat-plugin.lobehub.com/api/v1',- name: 'fetchCurrentWeather',- description: 'θ·εε½ε倩ζ°ζ ε΅',- parameters: {- properties: {- city: {- description: 'εεΈεη§°',- type: 'string',- },- },- required: ['city'],- type: 'object',- },- },- ],- author: 'LobeHub',- createAt: '2023-08-12',- homepage: 'https://github.com/lobehub/chat-plugin-realtime-weather',- identifier: 'realtime-weather',- meta: {- avatar: 'π',- tags: ['weather', 'realtime'],- title: 'Realtime Weather',- description: 'Get realtime weather information',- },- ui: {- url: 'https://realtime-weather.chat-plugin.lobehub.com/iframe',- height: 310,- },- version: '1',- };-- global.fetch = vi.fn(() =>- Promise.resolve({- headers: new Headers({ 'content-type': 'application/json' }),- ok: true,- json: () => Promise.resolve(fakeManifest),- }),- ) as any;-- const manifest = await toolService.getToolManifest(manifestUrl);-- expect(fetch).toHaveBeenCalledWith(manifestUrl);- expect(manifest).toEqual(fakeManifest);- });-- it('should return error on noManifest', async () => {- try {- await toolService.getToolManifest();- } catch (e) {- expect(e).toEqual(new TypeError('noManifest'));- }- });-- it('should return error on manifestInvalid', async () => {- const fakeManifest = { name: 'TestPlugin', version: '1.0.0' };- const manifestUrl = 'http://fake-url.com/manifest.json';- global.fetch = vi.fn(() =>- Promise.resolve({- headers: new Headers({ 'content-type': 'application/json' }),- ok: true,- json: () => Promise.resolve(fakeManifest),- }),- ) as any;-- try {- await toolService.getToolManifest(manifestUrl);- } catch (e) {- expect(e).toEqual(new TypeError('manifestInvalid'));- }- });-- it('should return error on fetchError', async () => {- const manifestUrl = 'http://fake-url.com/manifest.json';- global.fetch = vi.fn(() => Promise.reject(new Error('Network error')));-- try {- await toolService.getToolManifest(manifestUrl);- } catch (e) {- expect(e).toEqual(new TypeError('fetchError'));- }- expect(fetch).toHaveBeenCalledWith(manifestUrl);- });-- it('should return error on manifestInvalid', async () => {- const fakeManifest = { name: 'TestPlugin', version: '1.0.0' };- const manifestUrl = 'http://fake-url.com/manifest.json';- global.fetch = vi.fn(() =>- Promise.resolve({- ok: false,- headers: new Headers({ 'content-type': 'application/json' }),- json: () => Promise.resolve(fakeManifest),- }),- ) as any;-- try {- await toolService.getToolManifest(manifestUrl);- } catch (e) {- expect(e).toEqual(new TypeError('fetchError'));- }- });- });-});diff --git a/src/services/__tests__/upload.test.ts b/src/services/__tests__/upload.test.tsindex 446897f73a3..08829021f8d 100644--- a/src/services/__tests__/upload.test.ts+++ b/src/services/__tests__/upload.test.ts@@ -2,7 +2,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { fileEnv } from '@/envs/file';import { lambdaClient } from '@/libs/trpc/client';-import { API_ENDPOINTS } from '@/services/_url';import { UPLOAD_NETWORK_ERROR, uploadService } from '../upload';@@ -365,45 +364,4 @@ describe('UploadService', () => {expect(result.path).toBe(customPath);});});-- describe('getImageFileByUrlWithCORS', () => {- beforeEach(() => {- global.fetch = vi.fn();- });-- it('should fetch and create file from URL', async () => {- const url = 'https://example.com/image.png';- const filename = 'test.png';- const mockArrayBuffer = new ArrayBuffer(8);-- vi.mocked(global.fetch).mockResolvedValue({- arrayBuffer: () => Promise.resolve(mockArrayBuffer),- } as Response);-- const result = await uploadService.getImageFileByUrlWithCORS(url, filename);-- expect(global.fetch).toHaveBeenCalledWith(API_ENDPOINTS.proxy, {- body: url,- method: 'POST',- });- expect(result).toBeInstanceOf(File);- expect(result.name).toBe(filename);- expect(result.type).toBe('image/png');- });-- it('should handle custom file type', async () => {- const url = 'https://example.com/image.jpg';- const filename = 'test.jpg';- const fileType = 'image/jpeg';- const mockArrayBuffer = new ArrayBuffer(8);-- vi.mocked(global.fetch).mockResolvedValue({- arrayBuffer: () => Promise.resolve(mockArrayBuffer),- } as Response);-- const result = await uploadService.getImageFileByUrlWithCORS(url, filename, fileType);-- expect(result.type).toBe(fileType);- });- });});diff --git a/src/services/_url.ts b/src/services/_url.tsindex a6977972045..5f17a4e12df 100644--- a/src/services/_url.ts+++ b/src/services/_url.ts@@ -3,8 +3,6 @@ import { withElectronProtocolIfElectron } from '@/const/protocol';export const API_ENDPOINTS = {oauth: withElectronProtocolIfElectron('/api/auth'),- proxy: withElectronProtocolIfElectron('/webapi/proxy'),-// tracetrace: withElectronProtocolIfElectron('/webapi/trace'),diff --git a/src/services/tool.ts b/src/services/tool.tsindex d343ccc1e31..c699c90fbd9 100644--- a/src/services/tool.ts+++ b/src/services/tool.ts@@ -1,7 +1,6 @@import { lambdaClient } from '@/libs/trpc/client';import { globalHelpers } from '@/store/global/helpers';import { type PluginQueryParams } from '@/types/discover';-import { getToolManifest } from '@/utils/toolManifest';class ToolService {getOldPluginList = async (params: PluginQueryParams): Promise<any> => {@@ -14,8 +13,6 @@ class ToolService {pageSize: params.pageSize ? Number(params.pageSize) : 20,});};-- getToolManifest = getToolManifest;}export const toolService = new ToolService();diff --git a/src/services/upload.ts b/src/services/upload.tsindex fb964b528f9..bb76f7cd3e8 100644--- a/src/services/upload.ts+++ b/src/services/upload.ts@@ -5,7 +5,6 @@ import { sha256 } from 'js-sha256';import { fileEnv } from '@/envs/file';import { lambdaClient } from '@/libs/trpc/client';-import { API_ENDPOINTS } from '@/services/_url';import { type FileMetadata, type UploadBase64ToS3Result } from '@/types/files';import { type FileUploadState, type FileUploadStatus } from '@/types/files/upload';@@ -203,19 +202,6 @@ class UploadService {return result;};- /**- * get image File item with cors image URL- * @param url- * @param filename- * @param fileType- */- getImageFileByUrlWithCORS = async (url: string, filename: string, fileType = 'image/png') => {- const res = await fetch(API_ENDPOINTS.proxy, { body: url, method: 'POST' });- const data = await res.arrayBuffer();-- return new File([data], filename, { lastModified: Date.now(), type: fileType });- };-private getSignedUploadUrl = async (file: File,options: { directory?: string; pathname?: string } = {},diff --git a/src/store/tool/slices/customPlugin/action.test.ts b/src/store/tool/slices/customPlugin/action.test.tsindex ec6083dfe13..85adbeba87a 100644--- a/src/store/tool/slices/customPlugin/action.test.ts+++ b/src/store/tool/slices/customPlugin/action.test.ts@@ -20,12 +20,6 @@ vi.mock('@/services/plugin', () => ({},}));-vi.mock('@/services/tool', () => ({- toolService: {- getToolManifest: vi.fn(),- },-}));-describe('useToolStore:customPlugin', () => {describe('deleteCustomPlugin', () => {it('should delete custom plugin and related settings', async () => {diff --git a/src/store/tool/slices/customPlugin/action.ts b/src/store/tool/slices/customPlugin/action.tsindex 118f0ca2984..76216e0f741 100644--- a/src/store/tool/slices/customPlugin/action.ts+++ b/src/store/tool/slices/customPlugin/action.ts@@ -1,11 +1,9 @@-import { type ToolManifest } from '@lobechat/types';import { merge } from 'es-toolkit/compat';import { t } from 'i18next';import { notification } from '@/components/AntdStaticMethods';import { mcpService } from '@/services/mcp';import { pluginService } from '@/services/plugin';-import { toolService } from '@/services/tool';import { pluginHelpers } from '@/store/tool/helpers';import { type StoreSetter } from '@/store/types';import { type LobeToolCustomPlugin, type PluginInstallError } from '@/types/tool/plugin';@@ -44,30 +42,21 @@ export class CustomPluginActionImpl {const { refreshPlugins, updateInstallLoadingState } = this.#get();+ const url = plugin.customParams?.mcp?.url;+ if (!plugin.customParams?.mcp || !url) return;+try {updateInstallLoadingState(id, true);- let manifest: ToolManifest;- // mean this is a mcp plugin- if (!!plugin.customParams?.mcp) {- const url = plugin.customParams?.mcp?.url;- if (!url) return;-- manifest = await mcpService.getStreamableMcpServerManifest({- auth: plugin.customParams.mcp.auth,- headers: plugin.customParams.mcp.headers,- identifier: plugin.identifier,- metadata: {- avatar: plugin.customParams.avatar,- description: plugin.customParams.description,- },- url,- });- } else {- manifest = await toolService.getToolManifest(- plugin.customParams?.manifestUrl,- plugin.customParams?.useProxy,- );- }+ const manifest = await mcpService.getStreamableMcpServerManifest({+ auth: plugin.customParams.mcp.auth,+ headers: plugin.customParams.mcp.headers,+ identifier: plugin.identifier,+ metadata: {+ avatar: plugin.customParams.avatar,+ description: plugin.customParams.description,+ },+ url,+ });updateInstallLoadingState(id, false);await pluginService.updatePluginManifest(id, manifest);