Commit 0c1840c7 by Archer Committed by GitHub

[codex] secure code sandbox secret isolation (#7173)

* redirect check

* secure python sandbox isolation

* fix sandbox http proxy timeout handling

* limit python native package threads

* fix sandbox allowed module compatibility

* Refine LLM context compression

* chore: harden code sandbox security

* fix issue

* fix: allow python sandbox task directories

* fix: i18n

* compress

* fix: stabilize matplotlib sandbox cache dirs
parent b2ab4b51
......@@ -57,6 +57,8 @@ curl --location --request POST 'https://{{host}}/api/admin/initSandboxArchive' \
4. 知识库训练出现错误时的提示,同时支持一键全部重试。
5. 过滤掉无效的知识库引用角标。
6. 工具运行空响应时候,自动补充 "none",避免部分模型报错。
7. 系统工具运行前,再次进行二次权限校验。
8. 优化重定向后 SSRF 校验。
## 🐛 修复
......
......@@ -133,8 +133,8 @@
"content/guide/version/cloud/privacy.mdx": "2026-05-07T15:06:40+08:00",
"content/guide/version/cloud/terms.en.mdx": "2026-05-07T15:06:40+08:00",
"content/guide/version/cloud/terms.mdx": "2026-05-28T13:54:38+08:00",
"content/guide/version/commercial.en.mdx": "2026-05-07T15:06:40+08:00",
"content/guide/version/commercial.mdx": "2026-05-07T15:06:40+08:00",
"content/guide/version/commercial.en.mdx": "2026-06-23T15:18:25+08:00",
"content/guide/version/commercial.mdx": "2026-06-23T15:18:25+08:00",
"content/guide/version/opensource/intro.en.mdx": "2026-05-07T15:06:40+08:00",
"content/guide/version/opensource/intro.mdx": "2026-05-07T15:06:40+08:00",
"content/guide/version/opensource/license.en.mdx": "2026-05-07T15:06:40+08:00",
......
......@@ -16,7 +16,7 @@ export const SandboxStatusEnum = {
export type SandboxStatusType = (typeof SandboxStatusEnum)[keyof typeof SandboxStatusEnum];
// ---- 暂停阈值(分钟) ----
export const SANDBOX_SUSPEND_MINUTES = 5;
export const SANDBOX_SUSPEND_MINUTES = 10;
// ---- sandboxId 生成 ----
export const generateSandboxId = (appId: string, userId: string, chatId: string): string => {
......
......@@ -28,7 +28,7 @@ export const AgentNode: FlowNodeTemplateType = {
templateType: FlowNodeTemplateTypeEnum.ai,
showSourceHandle: true,
showTargetHandle: true,
avatar: 'core/workflow/template/agent',
avatar: 'core/app/type/agentFill',
avatarLinear: 'core/workflow/template/agentLinear',
colorSchema: 'emerald',
name: i18nT('workflow:template.agent_module'),
......
import _, { type AxiosInstance, type AxiosRequestConfig } from 'axios';
import _, {
type AxiosInstance,
type AxiosRequestConfig,
type AxiosResponse,
type InternalAxiosRequestConfig
} from 'axios';
import { ProxyAgent, type ProxyAgentOptions } from 'proxy-agent';
import { isDevEnv } from '@fastgpt/global/common/system/constants';
import { isInternalAddress, PRIVATE_URL_TEXT } from '../system/utils';
import { isAbsoluteUrl } from '../security/network';
import { SERVICE_LOCAL_HOST } from '../system/tools';
/**
* 给 shared axios 实例添加 SSRF 防护。
*
* 这里同时接管 axios 的重定向逻辑: axios/follow-redirects 的自动跳转发生在
* request interceptor 之后,如果不手动处理,302 Location 指向内网时不会再次进入
* isInternalAddress()。因此 safe axios 会强制关闭底层自动跳转,再在 response
* interceptor 中逐跳解析 Location、复用同一套 SSRF 策略校验后再发起下一跳请求。
*/
const addSSRFInterceptor = (instance: AxiosInstance) => {
instance.interceptors.request.use(async (config) => {
const requestUrl = (() => {
try {
return new URL(config.url || '', config.baseURL).toString();
} catch {
return;
}
})();
instance.interceptors.request.use(async (config): Promise<InternalAxiosRequestConfig> => {
const safeConfig = config as SafeRedirectInternalConfig;
const requestUrl = buildRequestUrl(safeConfig);
if (!requestUrl) return config;
if (await isInternalAddress(requestUrl)) {
return Promise.reject(new Error(PRIVATE_URL_TEXT));
}
return config;
const maxRedirects =
safeConfig.__safeRedirect?.maxRedirects ??
(typeof safeConfig.maxRedirects === 'number'
? safeConfig.maxRedirects
: SAFE_AXIOS_MAX_REDIRECTS);
const nextConfig: SafeRedirectInternalConfig = {
...safeConfig,
// 禁用底层自动跳转,保留调用方 maxRedirects 语义给手动跳转状态使用。
maxRedirects: 0,
validateStatus: getRedirectValidateStatus(safeConfig.validateStatus, maxRedirects),
__safeRedirect: safeConfig.__safeRedirect ?? {
count: 0,
maxRedirects,
validateStatus: safeConfig.validateStatus
}
};
return nextConfig;
});
instance.interceptors.response.use(async (response) => {
if (!shouldRedirect(response)) return response;
const config = response.config as SafeRedirectConfig;
const redirectState = config.__safeRedirect;
const currentUrl = buildRequestUrl(config);
// 理论上 request interceptor 会注入状态;缺失时按普通响应返回,避免误处理其它实例响应。
if (!redirectState || !currentUrl) return response;
if (redirectState.count >= redirectState.maxRedirects) {
return Promise.reject(new Error(`Maximum redirects exceeded: ${redirectState.maxRedirects}`));
}
const redirectUrl = resolveRedirectUrl(response.headers.location, currentUrl);
if (await isInternalAddress(redirectUrl)) {
return Promise.reject(new Error(PRIVATE_URL_TEXT));
}
const redirectConfig = getRedirectConfig(config, response, currentUrl, redirectUrl);
const nextConfig: SafeRedirectConfig = {
...redirectConfig,
validateStatus: redirectState.validateStatus,
__safeRedirect: {
...redirectState,
count: redirectState.count + 1
}
};
return instance.request(nextConfig);
});
return instance;
......@@ -28,6 +86,166 @@ const addSSRFInterceptor = (instance: AxiosInstance) => {
const createProxyAgent = (options?: ProxyAgentOptions) => new ProxyAgent(options);
const SAFE_AXIOS_MAX_REDIRECTS = 5;
const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);
/**
* 手动重定向状态。
*
* count/maxRedirects 用于替代 axios/follow-redirects 的跳转次数控制。
* validateStatus 保存调用方原始成功状态判定,因为 request interceptor 会临时允许
* 3xx 进入 response interceptor,最终非重定向响应仍需按调用方语义判断成功/失败。
*/
type SafeRedirectState = {
count: number;
maxRedirects: number;
validateStatus?: AxiosRequestConfig['validateStatus'];
};
type SafeRedirectConfig = AxiosRequestConfig & {
__safeRedirect?: SafeRedirectState;
};
type SafeRedirectInternalConfig = InternalAxiosRequestConfig & {
__safeRedirect?: {
count: number;
maxRedirects: number;
validateStatus?: AxiosRequestConfig['validateStatus'];
};
};
const shouldRedirect = (response: AxiosResponse): boolean =>
REDIRECT_STATUS_CODES.has(response.status) && typeof response.headers.location === 'string';
/**
* 按 axios baseURL + url 规则合成实际请求 URL。
*
* 失败时返回 undefined,保持旧拦截器对非法/非标准 URL 的宽容行为;
* 真正的请求错误仍交给 axios 自身处理。
*/
const buildRequestUrl = (config: AxiosRequestConfig): string | undefined => {
try {
return new URL(config.url || '', config.baseURL).toString();
} catch {
return;
}
};
/**
* 解析 Location 头为下一跳绝对 URL,并限制协议。
*
* file://、gopher:// 等非 HTTP 协议不能进入后续请求流程,否则 SSRF 防护的
* 地址策略和 axios 出站语义都会变得不明确。
*/
const resolveRedirectUrl = (location: string, currentUrl: string): string => {
const redirectUrl = new URL(location, currentUrl);
if (redirectUrl.protocol !== 'http:' && redirectUrl.protocol !== 'https:') {
throw new Error(`Unsupported redirect protocol: ${redirectUrl.protocol}`);
}
return redirectUrl.toString();
};
/**
* 生成重定向请求头。
*
* 行为对齐 follow-redirects 的安全取向:
* - Host 必须丢弃,由下一跳真实目标重新生成
* - 301/302 POST 和 303 非 GET/HEAD 转 GET 时,不能继续携带 content-* 请求体头
* - 跨 host/protocol 跳转时移除凭证类 header,避免用户配置的密钥被带到新域名
*/
const filterRedirectHeaders = ({
headers,
currentUrl,
redirectUrl,
shouldSwitchToGet
}: {
headers: AxiosRequestConfig['headers'];
currentUrl: string;
redirectUrl: string;
shouldSwitchToGet: boolean;
}): AxiosRequestConfig['headers'] => {
const nextHeaders = { ...(headers as Record<string, any>) };
const current = new URL(currentUrl);
const redirect = new URL(redirectUrl);
const shouldDropSensitiveHeaders =
current.protocol !== redirect.protocol || current.host !== redirect.host;
for (const key of Object.keys(nextHeaders)) {
const normalizedKey = key.toLowerCase();
if (normalizedKey === 'host') {
delete nextHeaders[key];
continue;
}
if (shouldSwitchToGet && normalizedKey.startsWith('content-')) {
delete nextHeaders[key];
continue;
}
if (
shouldDropSensitiveHeaders &&
['authorization', 'cookie', 'proxy-authorization'].includes(normalizedKey)
) {
delete nextHeaders[key];
}
}
return nextHeaders;
};
/**
* 根据 HTTP 重定向响应构造下一跳请求配置。
*
* 仅实现服务端常见 301/302/303/307/308 语义:
* - 301/302 且原方法为 POST 时转 GET
* - 303 且原方法不是 GET/HEAD 时转 GET
* - 307/308 保留原方法和请求体
*/
const getRedirectConfig = (
config: AxiosRequestConfig,
response: AxiosResponse,
currentUrl: string,
redirectUrl: string
): AxiosRequestConfig => {
const currentMethod = (config.method || 'get').toUpperCase();
const shouldSwitchToGet =
((response.status === 301 || response.status === 302) && currentMethod === 'POST') ||
(response.status === 303 && currentMethod !== 'GET' && currentMethod !== 'HEAD');
return {
...config,
baseURL: undefined,
url: redirectUrl,
maxRedirects: 0,
method: shouldSwitchToGet ? 'GET' : config.method,
data: shouldSwitchToGet ? undefined : config.data,
headers: filterRedirectHeaders({
headers: config.headers,
currentUrl,
redirectUrl,
shouldSwitchToGet
})
};
};
/**
* 临时放行重定向状态码,让 response interceptor 能拿到 3xx 响应并校验 Location。
*
* maxRedirects=0 表示调用方明确禁止跟随重定向,此时完全保留调用方 validateStatus,
* 不把 3xx 转成“成功响应”。
*/
const getRedirectValidateStatus = (
validateStatus: AxiosRequestConfig['validateStatus'],
maxRedirects: number
): AxiosRequestConfig['validateStatus'] => {
if (maxRedirects === 0) {
return validateStatus;
}
return (status) => {
if (REDIRECT_STATUS_CODES.has(status)) return true;
return validateStatus ? validateStatus(status) : status >= 200 && status < 300;
};
};
/**
* 工作流 HTTP 节点跳过 HTTPS 证书校验专用 agent。
* 仍复用 ProxyAgent,只调整目标站 TLS 校验策略,避免改变部署环境的代理语义。
......
......@@ -9,7 +9,7 @@ export const AgentUsageModuleName = {
export const AgentNodeResponseDisplay = {
master: {
moduleName: i18nT('chat:master_agent_call'),
moduleLogo: 'core/workflow/template/agent'
moduleLogo: 'core/app/type/agentFill'
},
piMaster: {
moduleName: i18nT('chat:master_agent_call'),
......
......@@ -42,7 +42,7 @@ type RunAgentCallProps<TChildrenResponse = unknown> = {
childrenInteractiveParams?: AgentLoopChildrenInteractiveParams<TChildrenResponse>;
// LLM 压缩后回调
onAfterCompressContext?: (e: {
usage: ChatNodeUsageType;
usage?: ChatNodeUsageType;
requestIds: string[];
seconds: number;
contextCheckpoint?: ContextCheckpointValueType;
......@@ -124,34 +124,50 @@ type RunAgentResponse<TChildrenResponse = unknown> = {
*/
export const onCompressContext = async ({
isAborted,
messageTokens,
requestMessages,
modelData,
reasoningEffort,
tools,
userKey
}: {
isAborted: RunAgentCallProps['isAborted'];
messageTokens?: number;
requestMessages: ChatCompletionMessageParam[];
modelData: LLMModelItemType;
reasoningEffort?: CreateLLMResponseProps['body']['reasoning_effort'];
tools?: ChatCompletionTool[];
userKey: RunAgentCallProps['userKey'];
}) => {
const compressStartTime = Date.now();
const result = await compressRequestMessages({
checkIsStopping: isAborted,
messageTokens,
messages: requestMessages,
model: modelData,
reasoningEffort,
tools,
userKey
});
if (result.usage) {
if (result.usage || result.contextCheckpoint || result.messages !== requestMessages) {
return {
messages: result.messages,
messageTokens: result.messageTokens,
hasCompressedContext: true,
usage: result.usage,
requestIds: result.requestIds ?? [],
seconds: +((Date.now() - compressStartTime) / 1000).toFixed(2),
contextCheckpoint: result.contextCheckpoint
};
}
return {
messages: result.messages,
messageTokens: result.messageTokens,
hasCompressedContext: false,
requestIds: result.requestIds ?? [],
seconds: +((Date.now() - compressStartTime) / 1000).toFixed(2)
};
};
/**
......@@ -210,6 +226,20 @@ export const runAgentLoop = async <TChildrenResponse = unknown>({
}
return item;
});
let requestMessagesTokenCount: number | undefined;
/**
* requestMessages 在未压缩时主要是 append-only。
* 已知基线 token 后,只统计新增 message,避免每轮压缩判断都重复统计完整历史。
*/
const appendRequestMessages = async (...newMessages: ChatCompletionMessageParam[]) => {
requestMessages.push(...newMessages);
if (requestMessagesTokenCount !== undefined && newMessages.length > 0) {
requestMessagesTokenCount += await countGptMessagesTokens({
messages: newMessages
});
}
};
let inputTokens: number = 0;
let outputTokens: number = 0;
......@@ -287,21 +317,28 @@ export const runAgentLoop = async <TChildrenResponse = unknown>({
{
const compressResult = await onCompressContext({
isAborted,
messageTokens: requestMessagesTokenCount,
requestMessages,
modelData,
reasoningEffort: body.reasoning_effort,
tools: body.tools,
userKey
});
if (compressResult) {
requestMessages = compressResult.messages;
contextCheckpoint = compressResult.contextCheckpoint ?? contextCheckpoint;
usagePush?.([compressResult.usage]);
onAfterCompressContext?.({
usage: compressResult.usage,
requestIds: compressResult.requestIds,
seconds: compressResult.seconds,
contextCheckpoint: compressResult.contextCheckpoint
});
requestMessagesTokenCount = compressResult.messageTokens ?? requestMessagesTokenCount;
if (compressResult.hasCompressedContext) {
requestMessages = compressResult.messages;
contextCheckpoint = compressResult.contextCheckpoint ?? contextCheckpoint;
if (compressResult.usage) {
usagePush?.([compressResult.usage]);
}
onAfterCompressContext?.({
usage: compressResult.usage,
requestIds: compressResult.requestIds,
seconds: compressResult.seconds,
contextCheckpoint: compressResult.contextCheckpoint
});
}
}
}
......@@ -408,7 +445,7 @@ export const runAgentLoop = async <TChildrenResponse = unknown>({
// 推送 AI 生成后的 assistantMessages
if (llmAssistantMessage) {
assistantMessages.push(llmAssistantMessage);
requestMessages.push(llmAssistantMessage);
await appendRequestMessages(llmAssistantMessage);
}
}
......@@ -423,11 +460,9 @@ export const runAgentLoop = async <TChildrenResponse = unknown>({
};
const runTool = async ({
tool,
currentMessagesTokens
tool
}: {
tool: ChatCompletionMessageToolCall;
currentMessagesTokens: number;
}): Promise<ToolRunResult> => {
const toolStartTime = Date.now();
let toolErrorMessage: string | undefined;
......@@ -470,8 +505,6 @@ export const runAgentLoop = async <TChildrenResponse = unknown>({
const compressionResult = await compressToolResponse({
response,
model: modelData,
currentMessagesTokens,
toolLength: toolCalls.length,
reasoningEffort: body.reasoning_effort,
userKey
});
......@@ -517,31 +550,35 @@ export const runAgentLoop = async <TChildrenResponse = unknown>({
};
// 按 toolCalls 原始顺序写回工具结果,保证后续 LLM 上下文稳定。
const appendToolRunResults = (toolRunResults: ToolRunResult[]) => {
toolRunResults.forEach(
({ tool, interactive, stopLoop, toolMessage, toolAssistantMessages }) => {
if (interactive) {
interactiveResponse = {
type: 'toolChildrenInteractive',
params: {
childrenResponse: interactive,
toolParams: {
memoryRequestMessages: [],
toolCallId: tool.id
}
const appendToolRunResults = async (toolRunResults: ToolRunResult[]) => {
for (const {
tool,
interactive,
stopLoop,
toolMessage,
toolAssistantMessages
} of toolRunResults) {
if (interactive) {
interactiveResponse = {
type: 'toolChildrenInteractive',
params: {
childrenResponse: interactive,
toolParams: {
memoryRequestMessages: [],
toolCallId: tool.id
}
};
}
if (stopLoop) {
stopAgentLoop = true;
}
assistantMessages.push(toolMessage);
requestMessages.push(toolMessage);
// toolAssistantMessages 也需要记录成 AI 响应,所以这里需要推送。
assistantMessages.push(...toolAssistantMessages);
}
};
}
);
if (stopLoop) {
stopAgentLoop = true;
}
assistantMessages.push(toolMessage);
await appendRequestMessages(toolMessage);
// toolAssistantMessages 也需要记录成 AI 响应,所以这里需要推送。
assistantMessages.push(...toolAssistantMessages);
}
};
const safeBatchToolSize = Math.max(1, batchToolSize);
......@@ -549,17 +586,13 @@ export const runAgentLoop = async <TChildrenResponse = unknown>({
while (toolIndex < toolCalls.length) {
const currentTool = toolCalls[toolIndex];
const currentMessagesTokens = await countGptMessagesTokens({
messages: requestMessages
});
// 只能串行的工具
if (!canBatchTool(currentTool)) {
const result = await runTool({
tool: currentTool,
currentMessagesTokens
tool: currentTool
});
appendToolRunResults([result]);
await appendToolRunResults([result]);
toolIndex++;
continue;
}
......@@ -579,12 +612,11 @@ export const runAgentLoop = async <TChildrenResponse = unknown>({
batchTools,
async (tool) =>
runTool({
tool,
currentMessagesTokens
tool
}),
safeBatchToolSize
);
appendToolRunResults(toolRunResults);
await appendToolRunResults(toolRunResults);
}
}
......@@ -618,7 +650,7 @@ export const runAgentLoop = async <TChildrenResponse = unknown>({
) {
assistantMessages.pop();
}
requestMessages.push(stopResult.feedbackMessage);
await appendRequestMessages(stopResult.feedbackMessage);
continue;
}
}
......
/**
* Agent 上下文压缩配置常量
* request messages checkpoint 的起始标签。
* 用于 compress/index.ts 中识别、规范化和生成隐藏历史 checkpoint。
*/
export const CONTEXT_CHECKPOINT_START_TAG = '<context_checkpoint>';
/**
* request messages checkpoint 的结束标签。
* 用于 compress/index.ts 中识别、规范化和生成隐藏历史 checkpoint。
*/
export const CONTEXT_CHECKPOINT_END_TAG = '</context_checkpoint>';
/**
* token 预算转字符预算时使用的近似换算比例。
* 用于 compress/index.ts 的本地 head-tail 截断、二分缩短和内容分块。
*/
export const APPROX_CHARS_PER_TOKEN = 3;
/**
* LLM 分块压缩合并结果仍超预算时,最多再次压缩合并结果的轮数。
* 用于 compressLargeContent 的 merge compression 阶段。
*/
export const MERGED_COMPRESSION_MAX_ROUNDS = 2;
/**
* 本地 head-tail 截断时,字符预算分配给开头内容的比例。
* 用于 compress/index.ts 的 truncateContentByHeadTail。
*/
export const FINAL_HEAD_RATIO = 0.6;
/**
* request messages 调用 LLM 生成 checkpoint 时的软目标比例。
* 用于 getCompressRequestMessagesUserPrompt 的 output_budget。
*/
export const CHECKPOINT_OUTPUT_TARGET_RATIO = 0.2;
/**
* 压缩相关比例阈值的最小 token 数。
* 用于避免小上下文模型按比例计算出的压缩目标过小;实际值不会超过模型 maxContext。
*/
export const COMPRESSION_MIN_TOKEN_LIMIT = 4096;
/**
* request messages 调用 LLM 生成 checkpoint 时的最小软目标 token 数。
* 保留旧常量名,避免调用方理解成本;实际值与通用压缩最小值一致。
*/
export const CHECKPOINT_OUTPUT_MIN_TOKENS = COMPRESSION_MIN_TOKEN_LIMIT;
/**
* request checkpoint LLM 输出 token 可接受比例。
* 用于判断 completion token 是否明显超过软目标;超过时记录警告但仍以最终 messages token 校验为准。
*/
export const REQUEST_CHECKPOINT_COMPLETION_ACCEPT_CONTEXT_RATIO = 0.5;
/**
* 大内容压缩结果过短时,若压缩结果已占目标预算的该比例以上,则不再追加原文摘录。
* 用于 appendSourceExcerptForUnderfilledCompression。
*/
export const SOURCE_ANCHOR_APPEND_SKIP_RATIO = 0.8;
/**
* 大内容压缩后最多追加的原文结构锚点数量。
* 用于 appendSourceAnchorsWithinBudget,避免锚点列表挤占摘要主体。
*/
export const SOURCE_ANCHOR_APPEND_MAX_COUNT = 12;
/**
* tool response 原文直接返回阈值比例。
* 用于 compressToolResponse:响应不超过 20% context 时不做任何处理。
*/
export const TOOL_RESPONSE_DIRECT_RETURN_CONTEXT_RATIO = 0.2;
/**
* tool response 进入 LLM 压缩的阈值比例。
* 用于 compressToolResponse:本地轻量处理后仍超过 50% context 才调用 LLM 压缩。
*/
export const TOOL_RESPONSE_LIGHT_PROCESS_CONTEXT_RATIO = 0.5;
/**
* 本地截断时插入中间省略内容的标记。
* 用于 head-tail 截断,明确告知后续模型中间内容被省略。
*/
export const TRUNCATED_MARKER =
'\n\n... [content truncated: middle omitted to fit token budget] ...\n\n';
/**
* Depends on(系统提示词中的步骤历史)压缩触发比例。
*
* 拼接依赖步骤完整 response 后,超过模型上下文 15% 时触发压缩。
* 用于 calculateCompressionThresholds().dependsOn。
*/
export const DEPENDS_ON_THRESHOLD_RATIO = 0.15;
/**
* 对话历史压缩触发比例。
*
* ## 设计原则
* messages + tools schema 超过模型上下文 80% 时,尝试压缩成 checkpoint。
* 用于 compressRequestMessages 的触发阈值。
*/
export const MESSAGE_THRESHOLD_RATIO = 0.8;
/**
* 文件读取结果压缩触发比例。
*
* 1. **压缩触发水位**
* - Depends on:超过上下文 15% 后压缩
* - Agent 对话历史:超过上下文 80% 后压缩
* - 单个 tool response / 文件读取结果:超过上下文 50% 后压缩
* - 知识库检索结果:超过上下文 20% 后触发相关性筛选
* 文件解析工具返回的大型文档内容超过模型上下文 50% 时触发压缩。
* 用于 calculateCompressionThresholds().fileReadResponse。
*/
export const FILE_READ_RESPONSE_MAX_RATIO = 0.5;
/**
* 大文本分块压缩的单块比例。
*
* 2. **压缩策略**
* - 触发阈值:接近空间上限时触发
* - 压缩目标:保留可续跑上下文,具体摘要粒度交给模型判断
* - 约束机制:最终结果用真实 token 校验,LLM 输出长度只通过 prompt 软约束
* 分块阶段单块不超过模型上下文 50%,避免单次压缩请求过大。
* 用于 compressLargeContent 的 splitIntoChunks 分块预算。
*/
export const CHUNK_SIZE_RATIO = 0.5;
/**
* 知识库检索结果相关性筛选触发比例。
*
* 3. **协调关系**
* - Depends on 使用完整 response,先在较小水位触发
* - Agent 历史包含多轮 user/assistant/tool 消息,接近上下文上限才整体 checkpoint
* - 单个 tool/file response 不能过大,避免挤占后续对话和模型输出空间
*/
export const COMPRESSION_CONFIG = {
/**
* === Depends on(系统提示词中的步骤历史)===
*
* 触发场景:拼接依赖步骤的完整 response 后,token 数超过阈值
* 内容特点:包含多个步骤的完整执行结果(使用 response 而非 summary)
*
* 示例(maxContext=100k):
* - 依赖 3 个步骤,每个 4k → 12k (12%) ✅ 不触发
* - 依赖 5 个步骤,每个 4k → 20k (20%) ⚠️ 触发压缩
*/
DEPENDS_ON_THRESHOLD: 0.15, // 15% 触发压缩
/**
* === 对话历史 ===
*
* 触发场景:对话历史(含所有 user/assistant/tool 消息)超过阈值
* 内容特点:动态累积,触发后会整体压成 checkpoint string
*
* 示例(maxContext=100k):
* - 初始 20k + 6 轮对话(34k) = 54k (54%) ✅ 不触发
* - 再 1 轮 = 60k (60%) ⚠️ 触发压缩 → checkpoint
* - checkpoint 保存长程上下文、当前任务和未完成工具上下文
*/
MESSAGE_THRESHOLD: 0.8,
/**
* === 单个 tool response ===
*
* 触发场景:单个 tool 返回的内容超过绝对大小限制
* 内容特点:单次 tool 调用的响应(如搜索结果、文件内容等)
*
* 示例(maxContext=100k):
* - tool response = 8k (8%) ✅ 不触发
* - tool response = 15k (15%) ⚠️ 触发压缩
*/
SINGLE_TOOL_MAX: 0.5,
/**
* === 文件读取结果压缩 ===
*
* 触发场景:文件解析工具返回的文件内容超过限制
* 内容特点:通常是大型文档、PDF 等文件的完整文本内容
*
* 示例(maxContext=100k):
* - 文件内容 = 40k (40%) ✅ 不触发
* - 文件内容 = 60k (60%) ⚠️ 触发压缩
*/
FILE_READ_RESPONSE_MAX: 0.5, // 50% 触发压缩
/**
* === 分块压缩 ===
*/
CHUNK_SIZE_RATIO: 0.5, // 单块不超过 maxContext 的 50%
/**
* === 知识库检索工具的压缩阈值 ===
* 策略:使用 LLM 根据查询相关性自动选择最相关的一半分块
*/
DATASET_SEARCH_SELECTION_RATIO: 0.2
} as const;
* 检索片段总 token 超过模型上下文 20% 时,调用 LLM 选择最相关片段。
* 用于 dispatchAgentDatasetSearch 的 chunk selection 触发阈值。
*/
export const DATASET_SEARCH_SELECTION_RATIO = 0.2;
/**
* 计算压缩场景中的比例 token 阈值。
*
* 压缩阈值按比例计算后至少保留 4096 token,避免小上下文模型过早压缩或 output_budget 过小;
* 但阈值不会超过模型 maxContext,避免压缩目标反向大于模型可承载上下文。
*/
export const getCompressionTokenLimit = (maxContext: number, ratio: number) =>
Math.min(maxContext, Math.max(COMPRESSION_MIN_TOKEN_LIMIT, Math.floor(maxContext * ratio)));
/**
* 计算各场景的压缩阈值
......@@ -91,29 +141,27 @@ export const calculateCompressionThresholds = (maxContext: number) => {
return {
// Depends on 压缩阈值
dependsOn: {
threshold: Math.floor(maxContext * COMPRESSION_CONFIG.DEPENDS_ON_THRESHOLD)
threshold: Math.floor(maxContext * DEPENDS_ON_THRESHOLD_RATIO)
},
// 对话历史压缩阈值
messages: {
threshold: Math.floor(maxContext * COMPRESSION_CONFIG.MESSAGE_THRESHOLD)
threshold: getCompressionTokenLimit(maxContext, MESSAGE_THRESHOLD_RATIO)
},
// 单个 tool response 压缩阈值
// 单个 tool response 兼容阈值;新链路直接使用 0.2/0.5 分层常量。
singleTool: {
threshold: Math.floor(maxContext * COMPRESSION_CONFIG.SINGLE_TOOL_MAX)
threshold: getCompressionTokenLimit(maxContext, TOOL_RESPONSE_LIGHT_PROCESS_CONTEXT_RATIO)
},
// 文件读取结果压缩阈值
fileReadResponse: {
threshold: Math.floor(maxContext * COMPRESSION_CONFIG.FILE_READ_RESPONSE_MAX)
threshold: Math.floor(maxContext * FILE_READ_RESPONSE_MAX_RATIO)
},
// 分块压缩中每个分块的分割大小,用来划分原始大块的内容。
chunkSize: Math.floor(maxContext * COMPRESSION_CONFIG.CHUNK_SIZE_RATIO),
chunkSize: Math.floor(maxContext * CHUNK_SIZE_RATIO),
// 知识库检索工具阈值,到达阈值会触发选择最相关的一半分块内容(筛选)
datasetSearchSelection: Math.floor(
maxContext * COMPRESSION_CONFIG.DATASET_SEARCH_SELECTION_RATIO
)
datasetSearchSelection: Math.floor(maxContext * DATASET_SEARCH_SELECTION_RATIO)
};
};
......@@ -70,20 +70,96 @@ ${anchors.map((anchor) => `- ${anchor}`).join('\n')}
/**
* 将历史消息格式化成 checkpoint 压缩模型可读的 JSON。
*
* 这里只暴露压缩需要的协议字段,避免把无关运行时字段塞进 prompt 增加 token 和噪声。
* 这里只保留可继续工作的 user/assistant 文本历史。assistant 发起的 tool 调用会和对应 tool
* 结果合并成一条 assistant content,避免压缩模型看到旧工具协议字段,同时保留函数名、参数和结果绑定。
*/
const formatMessagesForCheckpoint = (messages: ChatCompletionMessageParam[]) =>
JSON.stringify(
messages.map((message) => ({
role: message.role,
content: message.content,
reasoning_content: message.reasoning_content,
tool_calls: message.role === 'assistant' ? message.tool_calls : undefined,
tool_call_id: message.role === 'tool' ? message.tool_call_id : undefined
})),
null,
2
);
const getMessageContentText = (content: ChatCompletionMessageParam['content']) => {
if (typeof content === 'string') return content;
if (Array.isArray(content)) {
return content
.map((item) => {
if (typeof item === 'string') return item;
if (item && typeof item === 'object' && 'text' in item && typeof item.text === 'string') {
return item.text;
}
return '';
})
.filter(Boolean)
.join('\n');
}
return '';
};
const escapeXmlText = (text: string) =>
text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const escapeXmlAttribute = (text: string) =>
escapeXmlText(text).replace(/"/g, '&quot;').replace(/'/g, '&apos;');
const formatMessagesForCheckpoint = (messages: ChatCompletionMessageParam[]) => {
const toolResultByCallId = new Map<string, string>();
for (const message of messages) {
if (message.role !== 'tool' || !message.tool_call_id) continue;
const content = getMessageContentText(message.content).trim();
if (content) {
toolResultByCallId.set(message.tool_call_id, content);
}
}
const consumedToolCallIds = new Set<string>();
const formattedMessages = messages.flatMap((message) => {
const content = getMessageContentText(message.content).trim();
if (message.role === 'user') {
if (!content) return [];
return [{ role: 'user', content }];
}
if (message.role === 'assistant') {
const toolCalls = message.tool_calls ?? [];
const toolCallBlocks = toolCalls.flatMap((toolCall) => {
const functionCall = toolCall.function;
if (!functionCall?.name) return [];
return [
[
`<tool name="${escapeXmlAttribute(functionCall.name)}">`,
`<param>${escapeXmlText(functionCall.arguments || '{}')}</param>`,
toolResultByCallId.has(toolCall.id)
? `<response>${escapeXmlText(toolResultByCallId.get(toolCall.id) || '')}</response>`
: '<response></response>',
'</tool>'
].join('\n')
];
});
toolCalls.forEach((toolCall) => {
if (toolResultByCallId.has(toolCall.id)) {
consumedToolCallIds.add(toolCall.id);
}
});
const toolsContent =
toolCallBlocks.length > 0 ? ['<tools>', ...toolCallBlocks, '</tools>'].join('\n') : '';
const mergedContent = [content, toolsContent].filter(Boolean).join('\n\n').trim();
if (!mergedContent) return [];
return [{ role: 'assistant', content: mergedContent }];
}
if (message.role === 'tool') {
// 已经合并到对应 assistant tool call 中;孤立 tool 结果才作为 assistant 上下文保留。
if (message.tool_call_id && consumedToolCallIds.has(message.tool_call_id)) return [];
if (!content) return [];
return [{ role: 'assistant', content }];
}
return [];
});
return JSON.stringify(formattedMessages, null, 2);
};
export const getCompressRequestMessagesPrompt = async () => {
return `你是 Agent 历史上下文 checkpoint 压缩专家。你的任务是把用户提供的对话历史压缩成一段可继续工作的高保真上下文摘要 string。
......@@ -120,7 +196,8 @@ export const getCompressRequestMessagesPrompt = async () => {
## 结构锚点规则
- 对 structural_anchor_candidates 和 tool_call_memory 里的字段名、函数名、参数名、ID、路径、URL、错误码、数字、日期,优先原样保留。
- 对 histories 和 structural_anchor_candidates 里的字段名、函数名、参数名、ID、路径、URL、错误码、数字、日期,优先原样保留。
- histories 中 assistant content 里的 <tools> 表示已经执行过的工具调用;<tool name="..."> 是工具名,<param> 是调用参数,<response> 是对应结果。压缩时必须保留仍影响后续任务的工具名、参数和关键结果。
- 不要为了保留锚点而堆无关关键词;锚点必须服务于后续执行、定位资源、复现工具结果或理解约束。
- 不要把具体工具名、机构名、文件名、接口名压成“相关工具/某机构/该文件/接口”。
......@@ -165,12 +242,10 @@ export const getCompressRequestMessagesPrompt = async () => {
export const getCompressRequestMessagesUserPrompt = async ({
messages,
outputTokenLimit,
toolCallMemory
outputTokenLimit
}: {
messages: ChatCompletionMessageParam[];
outputTokenLimit?: number;
toolCallMemory?: string;
}) => {
const histories = formatMessagesForCheckpoint(messages);
......@@ -178,7 +253,7 @@ export const getCompressRequestMessagesUserPrompt = async ({
${histories}
</histories>
${outputTokenLimit ? `<output_budget>\nTarget maximum output tokens: ${outputTokenLimit}. Use compact bullets and omit nonessential prose.\n</output_budget>\n\n` : ''}${toolCallMemory ? `${toolCallMemory}\n\n` : ''}${renderExactAnchors(histories, 100)}
${outputTokenLimit ? `<output_budget>\nTarget maximum output tokens: ${outputTokenLimit}. Use compact bullets and omit nonessential prose.\n</output_budget>\n\n` : ''}${renderExactAnchors(histories, 100)}
请执行历史上下文 checkpoint 压缩,只输出 <context_checkpoint>...</context_checkpoint>。
`;
};
......
......@@ -150,7 +150,7 @@ export async function markSandboxResourceStopped(resource: SandboxResourceRef) {
}
/**
* 查询可被 5 分钟 cron 暂停的运行中 sandbox。
* 查询可被 sandbox stop cron 暂停的运行中 sandbox。
*
* 正在归档或已归档的实例由归档流程管理生命周期,stop cron 不能插入中间状态。
*/
......@@ -249,7 +249,7 @@ export async function findSandboxInstanceArchiveState(params: {
/**
* 流式读取待归档 sandbox,避免迁移脚本或 cron 一次性把历史全量记录拉进 Node.js 内存。
*
* 一周后的实例应先由 5 分钟 cron 标记为 stopped,再由归档任务统一处理。
* 一周后的实例应先由 sandbox stop cron 标记为 stopped,再由归档任务统一处理。
* 归档不直接抢 running 实例,避免和 stop cron 操作同一个远端资源。
*/
export function createSandboxResourcesToArchiveCursor(params: {
......
......@@ -23,7 +23,9 @@ export const cronJob = async () => {
);
if (!instances.length) return;
logger.info('Found running sandboxes inactive > 5 min', { count: instances.length });
logger.info(`Found running sandboxes inactive > ${SANDBOX_SUSPEND_MINUTES} min`, {
count: instances.length
});
await stopSandboxResources(instances);
});
......
......@@ -17,12 +17,184 @@ import { isInternalAddress, PRIVATE_URL_TEXT } from '../../common/system/utils';
const logger = getLogger(LogCategories.MODULE.APP.MCP_TOOLS);
const MCP_SAFE_FETCH_MAX_REDIRECTS = 5;
const MCP_REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);
const MCP_SENSITIVE_REDIRECT_HEADERS = new Set(['authorization', 'cookie', 'proxy-authorization']);
type McpFetch = (url: string | URL, init?: RequestInit) => Promise<Response>;
export const assertMCPUrlNotInternal = async (url: string) => {
if (await isInternalAddress(url)) {
return Promise.reject(PRIVATE_URL_TEXT);
}
};
const headersInitToRecord = (headers?: HeadersInit): Record<string, string> => {
const record: Record<string, string> = {};
if (!headers) return record;
if (headers instanceof Headers) {
headers.forEach((value, key) => {
record[key] = value;
});
return record;
}
if (Array.isArray(headers)) {
headers.forEach(([key, value]) => {
record[key] = value;
});
return record;
}
Object.entries(headers).forEach(([key, value]) => {
record[key] = String(value);
});
return record;
};
const isMcpRedirectResponse = (response: Response) => {
return MCP_REDIRECT_STATUS_CODES.has(response.status) && !!response.headers.get('location');
};
const resolveMcpRedirectUrl = (location: string, currentUrl: string) => {
const redirectUrl = new URL(location, currentUrl);
if (redirectUrl.protocol !== 'http:' && redirectUrl.protocol !== 'https:') {
throw new Error('MCP redirect target only supports http/https protocol');
}
return redirectUrl.toString();
};
const getMcpRedirectHeaders = ({
headers,
currentUrl,
redirectUrl,
shouldSwitchToGet
}: {
headers?: HeadersInit;
currentUrl: string;
redirectUrl: string;
shouldSwitchToGet: boolean;
}) => {
const current = new URL(currentUrl);
const redirect = new URL(redirectUrl);
const shouldDropSensitiveHeaders =
current.protocol !== redirect.protocol || current.host !== redirect.host;
return Object.entries(headersInitToRecord(headers)).reduce<Record<string, string>>(
(acc, [key, value]) => {
const lowerKey = key.toLowerCase();
// 301/302 POST 与 303 会转成 GET,继续携带 content-* 容易让目标端误判请求体。
if (shouldSwitchToGet && lowerKey.startsWith('content-')) {
return acc;
}
// MCP header 中常带有鉴权密钥,跨 host/protocol 重定向时不能泄露给新目标。
if (shouldDropSensitiveHeaders && MCP_SENSITIVE_REDIRECT_HEADERS.has(lowerKey)) {
return acc;
}
if (lowerKey === 'host') {
return acc;
}
acc[key] = value;
return acc;
},
{}
);
};
const getMcpRedirectRequestInit = ({
init,
response,
currentUrl,
redirectUrl
}: {
init?: RequestInit;
response: Response;
currentUrl: string;
redirectUrl: string;
}): RequestInit => {
const method = (init?.method || 'GET').toUpperCase();
const shouldSwitchToGet =
((response.status === 301 || response.status === 302) && method === 'POST') ||
(response.status === 303 && method !== 'GET' && method !== 'HEAD');
return {
...init,
// Node fetch 默认会自动跟随重定向;这里必须保持 manual,才能逐跳做 SSRF 校验。
redirect: 'manual',
method: shouldSwitchToGet ? 'GET' : init?.method,
body: shouldSwitchToGet ? undefined : init?.body,
headers: getMcpRedirectHeaders({
headers: init?.headers,
currentUrl,
redirectUrl,
shouldSwitchToGet
})
};
};
/**
* 为 MCP SDK transport 注入安全 fetch。
*
* MCP 连接本身会先校验初始 URL,但 SDK 内部默认使用 fetch 自动跟随重定向。
* 这会让“初始 URL 合法,Location 跳到内网地址”的场景绕过 SSRF 防护。
* 该 fetch 通过 `redirect: manual` 接管重定向流程,并对每一跳目标重新执行
* 内网地址校验;跨 host/protocol 跳转时还会移除鉴权类 header,避免 MCP 密钥泄露。
*/
export const createMcpSafeFetch = ({
maxRedirects = MCP_SAFE_FETCH_MAX_REDIRECTS,
fetchImpl = fetch as McpFetch
}: {
maxRedirects?: number;
fetchImpl?: McpFetch;
} = {}): McpFetch => {
const redirectLimit = Math.max(0, maxRedirects);
return async (url, init) => {
let currentUrl = new URL(url.toString()).toString();
let currentInit: RequestInit = {
...init,
redirect: 'manual'
};
for (let redirectCount = 0; redirectCount <= redirectLimit; redirectCount++) {
await assertMCPUrlNotInternal(currentUrl);
const response = await fetchImpl(currentUrl, currentInit);
if (!isMcpRedirectResponse(response)) {
return response;
}
if (redirectCount === redirectLimit) {
throw new Error(`Maximum MCP redirects exceeded: ${redirectLimit}`);
}
const redirectUrl = resolveMcpRedirectUrl(response.headers.get('location')!, currentUrl);
await assertMCPUrlNotInternal(redirectUrl);
currentInit = getMcpRedirectRequestInit({
init: currentInit,
response,
currentUrl,
redirectUrl
});
currentUrl = redirectUrl;
await response.body?.cancel().catch(() => undefined);
}
throw new Error(`Maximum MCP redirects exceeded: ${redirectLimit}`);
};
};
const shouldFallbackToSSE = (error: unknown): boolean => {
return (
error instanceof StreamableHTTPError &&
......@@ -71,6 +243,7 @@ export class MCPClient {
private async doConnect(): Promise<Client> {
await assertMCPUrlNotInternal(this.url);
const safeFetch = createMcpSafeFetch();
// 避免连接重复,强制关闭一次
await this.client.close().catch(() => {});
......@@ -78,6 +251,7 @@ export class MCPClient {
logger.debug('Start connect mcp client', { url: this.url });
try {
const transport = new StreamableHTTPClientTransport(new URL(this.url), {
fetch: safeFetch,
requestInit: {
headers: this.headers
}
......@@ -92,26 +266,19 @@ export class MCPClient {
try {
await this.client.connect(
new SSEClientTransport(new URL(this.url), {
fetch: safeFetch,
requestInit: {
headers: this.headers
},
eventSourceInit: {
fetch: (url, init) => {
const mergedHeaders: Record<string, string> = {
const mergedHeaders = {
...this.headers
};
if (init?.headers) {
if (init.headers instanceof Headers) {
init.headers.forEach((value, key) => {
mergedHeaders[key] = value;
});
} else if (typeof init.headers === 'object') {
Object.assign(mergedHeaders, init.headers);
}
}
Object.assign(mergedHeaders, headersInitToRecord(init?.headers));
return fetch(url, {
return safeFetch(url, {
...init,
headers: mergedHeaders
});
......
......@@ -23,6 +23,8 @@ import { pluginClient } from '../../../../../../../thirdProvider/fastgptPlugin';
import { SystemToolRepo } from '../../../../../../app/tool/systemTool/systemTool.repo';
import { InvokeProcessor } from '../../../../../../../support/invoke/invoke';
import { getLogger, LogCategories } from '../../../../../../../common/logger';
import { authAppByTmbId } from '../../../../../../../support/permission/app/auth';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
type SystemInputConfigType = {
type: SystemToolSecretInputTypeEnum;
......@@ -85,6 +87,18 @@ export const dispatchTool = async ({
const logger = getLogger(LogCategories.MODULE.APP.TOOL);
try {
/**
* Agent 工具调用也会按持久化 toolId 解析 HTTP/MCP 父工具集。
* 这里必须使用当前运行工作流的 tmbId 做运行时授权,防止绕过保存阶段的脏引用被模型调用执行。
*/
const authRuntimeToolset = async (parentId: string) => {
await authAppByTmbId({
tmbId: runningAppInfo.tmbId,
appId: parentId,
per: ReadPermissionVal
});
};
if (toolConfig?.systemTool?.toolId) {
const systemToolRepo = SystemToolRepo.getInstance();
const tool = await systemToolRepo.getSystemToolRuntime({
......@@ -195,6 +209,7 @@ export const dispatchTool = async ({
if (!parentId || !toolName) {
return Promise.reject(`Invalid MCP tool id: ${toolConfig.mcpTool.toolId}`);
}
await authRuntimeToolset(parentId);
const tool = await getAppVersionById({
appId: parentId,
......@@ -228,6 +243,7 @@ export const dispatchTool = async ({
if (!parentId || !toolName) {
return Promise.reject(`Invalid HTTP tool id: ${toolConfig.httpTool.toolId}`);
}
await authRuntimeToolset(parentId);
const toolset = await getAppVersionById({
appId: parentId,
......
......@@ -159,6 +159,8 @@ export const runToolCall = async (props: DispatchToolModuleProps): Promise<Respo
*/
canBatchTool: () => false,
onAfterCompressContext({ usage, requestIds, seconds }) {
if (!usage) return;
appendContextCompressNodeResponse({
usage,
requestIds,
......
......@@ -24,6 +24,8 @@ import { pluginClient } from '../../../../thirdProvider/fastgptPlugin';
import { SystemToolRepo } from '../../../app/tool/systemTool/systemTool.repo';
import { InvokeProcessor } from '../../../../support/invoke/invoke';
import { getLogger, LogCategories } from '../../../../common/logger';
import { authAppByTmbId } from '../../../../support/permission/app/auth';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
type SystemInputConfigType = {
type: SystemToolSecretInputTypeEnum;
......@@ -66,6 +68,18 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
let toolInput: Record<string, any> = {};
try {
/**
* HTTP/MCP 子工具的 toolId 可由工作流 JSON 持久化,运行时必须用当前工作流执行身份
* 重新校验父工具集权限,避免脏数据或绕过保存接口的跨用户工具集引用被执行。
*/
const authRuntimeToolset = async (parentId: string) => {
await authAppByTmbId({
tmbId: runningAppInfo.tmbId,
appId: parentId,
per: ReadPermissionVal
});
};
// run system tool
if (toolConfig?.systemTool?.toolId) {
const systemToolRepo = SystemToolRepo.getInstance();
......@@ -214,6 +228,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
if (!parentId || !toolName) {
throw new Error(`Invalid MCP tool id: ${toolConfig.mcpTool.toolId}`);
}
await authRuntimeToolset(parentId);
const tool = await getAppVersionById({
appId: parentId,
......@@ -250,6 +265,11 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
};
} else if (toolConfig?.httpTool?.toolId) {
const { parentId, toolName } = parseToolId(toolConfig.httpTool.toolId);
if (!parentId || !toolName) {
throw new Error(`Invalid HTTP tool id: ${toolConfig.httpTool.toolId}`);
}
await authRuntimeToolset(parentId);
const toolset = await getAppVersionById({
appId: parentId,
versionId: version
......
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { createProxyAxios } from '@fastgpt/service/common/api/axios';
import { PRIVATE_URL_TEXT } from '@fastgpt/service/common/system/utils';
import { afterEach, describe, it, expect, vi, beforeEach } from 'vitest';
import http from 'http';
import os from 'os';
import { createProxyAxios } from '../../../common/api/axios';
import { PRIVATE_URL_TEXT } from '../../../common/system/utils';
import { serviceEnv } from '../../../env';
type AxiosRequestConfig = {
timeout?: number;
......@@ -12,6 +15,13 @@ type AxiosRequestConfig = {
};
describe('axios.ts', () => {
const mutableServiceEnv = serviceEnv as { CHECK_INTERNAL_IP: boolean };
const originalCheckInternalIp = serviceEnv.CHECK_INTERNAL_IP;
afterEach(() => {
mutableServiceEnv.CHECK_INTERNAL_IP = originalCheckInternalIp;
});
describe('createProxyAxios', () => {
beforeEach(() => {
vi.clearAllMocks();
......@@ -154,7 +164,7 @@ describe('axios.ts', () => {
describe('axios 导出实例', () => {
it('应该导出一个默认的 axios 实例', async () => {
const { axios } = await import('@fastgpt/service/common/api/axios');
const { axios } = await import('../../../common/api/axios');
expect(axios).toBeDefined();
expect(axios.defaults).toBeDefined();
......@@ -164,6 +174,138 @@ describe('axios.ts', () => {
});
});
describe('safe axios redirect protection', () => {
const listen = (handler: http.RequestListener, host = '127.0.0.1') =>
new Promise<http.Server>((resolve) => {
const server = http.createServer(handler);
server.listen(0, host, () => resolve(server));
});
const closeServer = (server: http.Server) =>
new Promise<void>((resolve, reject) => {
server.close((err) => (err ? reject(err) : resolve()));
});
const getServerPort = (server: http.Server): number => {
const address = server.address();
if (!address || typeof address === 'string') {
throw new Error('Invalid test server address');
}
return address.port;
};
/**
* 构造一个非 loopback 的本机访问地址,用于模拟“初始 URL 通过 SSRF 校验”。
* CHECK_INTERNAL_IP=false 时私网地址会放行,但 loopback/metadata 仍然恒拦截。
*/
const getReachablePrivateHost = () => {
const interfaces = os.networkInterfaces();
for (const items of Object.values(interfaces)) {
for (const item of items || []) {
if (item.family === 'IPv4' && !item.internal) {
return item.address;
}
}
}
return undefined;
};
it('应该逐跳跟随公网重定向', async () => {
mutableServiceEnv.CHECK_INTERNAL_IP = false;
const carrierHost = getReachablePrivateHost();
if (!carrierHost) {
return;
}
const targetServer = await listen((req, res) => {
res.end(JSON.stringify({ ok: true, url: req.url }));
}, '0.0.0.0');
const targetPort = getServerPort(targetServer);
const redirectServer = await listen((req, res) => {
res.statusCode = 302;
res.setHeader('Location', `http://${carrierHost}:${targetPort}/target`);
res.end('redirect');
}, '0.0.0.0');
const redirectPort = getServerPort(redirectServer);
try {
const instance = createProxyAxios();
const response = await instance.get<{ ok: boolean; url: string }>(
`http://${carrierHost}:${redirectPort}/fetch`,
{
httpAgent: new http.Agent()
}
);
expect(response.data).toEqual({ ok: true, url: '/target' });
} finally {
await closeServer(redirectServer);
await closeServer(targetServer);
}
});
it('应该阻止重定向到 loopback 地址', async () => {
mutableServiceEnv.CHECK_INTERNAL_IP = false;
const carrierHost = getReachablePrivateHost();
if (!carrierHost) {
return;
}
const protectedServer = await listen((req, res) => {
res.end('INTERNAL-ONLY-RESPONSE');
});
const protectedPort = getServerPort(protectedServer);
const redirectServer = await listen((req, res) => {
res.statusCode = 302;
res.setHeader('Location', `http://127.0.0.1:${protectedPort}/latest/meta-data/`);
res.end('redirect');
}, '0.0.0.0');
const redirectPort = getServerPort(redirectServer);
try {
const instance = createProxyAxios();
await expect(
instance.get(`http://${carrierHost}:${redirectPort}/fetch`, {
httpAgent: new http.Agent()
})
).rejects.toThrow(PRIVATE_URL_TEXT);
} finally {
await closeServer(redirectServer);
await closeServer(protectedServer);
}
});
it('应该限制最大重定向次数', async () => {
mutableServiceEnv.CHECK_INTERNAL_IP = false;
const carrierHost = getReachablePrivateHost();
if (!carrierHost) {
return;
}
let redirectPort = 0;
const redirectServer = await listen((req, res) => {
res.statusCode = 302;
res.setHeader('Location', `http://${carrierHost}:${redirectPort}/loop`);
res.end('redirect');
}, '0.0.0.0');
redirectPort = getServerPort(redirectServer);
try {
const instance = createProxyAxios();
await expect(
instance.get(`http://${carrierHost}:${redirectPort}/loop`, {
httpAgent: new http.Agent(),
maxRedirects: 1
})
).rejects.toThrow('Maximum redirects exceeded');
} finally {
await closeServer(redirectServer);
}
});
});
describe('pickOutboundAxios', () => {
it.each([
'http://example.com',
......@@ -171,14 +313,14 @@ describe('axios.ts', () => {
'http://169.254.169.254/latest/meta-data/',
'//attacker.example/probe' // protocol-relative 也按绝对处理
])('绝对 URL %j 返回 safe axios 实例', async (url) => {
const { axios, pickOutboundAxios } = await import('@fastgpt/service/common/api/axios');
const { axios, pickOutboundAxios } = await import('../../../common/api/axios');
expect(pickOutboundAxios(url)).toBe(axios);
});
it.each(['/api/foo', 'api/foo', '/support/outLink/feishu/abc'])(
'相对路径 %j 返回内部 axios(baseURL 固定到本机)',
async (url) => {
const { axios, pickOutboundAxios } = await import('@fastgpt/service/common/api/axios');
const { axios, pickOutboundAxios } = await import('../../../common/api/axios');
const client = pickOutboundAxios(url);
expect(client).not.toBe(axios);
expect(client.defaults.baseURL).toMatch(/^http:\/\//);
......@@ -186,7 +328,7 @@ describe('axios.ts', () => {
);
it('多次调用同一类型的 URL,内部 client 应被复用(避免每次新建实例)', async () => {
const { pickOutboundAxios } = await import('@fastgpt/service/common/api/axios');
const { pickOutboundAxios } = await import('../../../common/api/axios');
const a = pickOutboundAxios('/api/a');
const b = pickOutboundAxios('/api/b');
expect(a).toBe(b);
......
......@@ -7,13 +7,17 @@ import type { ChatCompletionTool } from '@fastgpt/global/core/ai/llm/type';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { mockCreateLLMResponseQueue, text, toolCall } from './_mocks/llmQueue';
const { createLLMResponseMock, compressRequestMessagesMock, compressToolResponseMock } = vi.hoisted(
() => ({
createLLMResponseMock: vi.fn(),
compressRequestMessagesMock: vi.fn(),
compressToolResponseMock: vi.fn()
})
);
const {
createLLMResponseMock,
compressRequestMessagesMock,
compressToolResponseMock,
countGptMessagesTokensMock
} = vi.hoisted(() => ({
createLLMResponseMock: vi.fn(),
compressRequestMessagesMock: vi.fn(),
compressToolResponseMock: vi.fn(),
countGptMessagesTokensMock: vi.fn(async () => 100)
}));
vi.mock('@fastgpt/service/core/ai/llm/request', () => ({
createLLMResponse: createLLMResponseMock
......@@ -46,7 +50,7 @@ vi.mock('@fastgpt/service/core/ai/llm/utils', () => ({
}));
vi.mock('@fastgpt/service/common/string/tiktoken/index', () => ({
countGptMessagesTokens: vi.fn(async () => 100)
countGptMessagesTokens: countGptMessagesTokensMock
}));
vi.mock('@fastgpt/service/support/wallet/usage/utils', () => ({
......@@ -77,6 +81,7 @@ const searchTool: ChatCompletionTool = {
describe('runAgentLoop with mocked createLLMResponse', () => {
beforeEach(() => {
vi.clearAllMocks();
countGptMessagesTokensMock.mockResolvedValue(100);
compressRequestMessagesMock.mockImplementation(async ({ messages }) => ({
messages
}));
......@@ -195,6 +200,125 @@ describe('runAgentLoop with mocked createLLMResponse', () => {
expect(usagePush).toHaveBeenCalledWith([compressedUsage]);
});
it('applies local context checkpoint compression even without usage', async () => {
const contextCheckpoint = '<context_checkpoint>local structured history</context_checkpoint>';
const usagePush = vi.fn();
const onAfterCompressContext = vi.fn();
compressRequestMessagesMock.mockImplementation(async () => ({
messages: [
{
role: ChatCompletionRequestMessageRoleEnum.User,
content: contextCheckpoint,
hideInUI: true
}
],
requestIds: [],
contextCheckpoint
}));
mockCreateLLMResponseQueue(createLLMResponseMock, [
text({ requestId: 'req_direct', content: 'direct answer' })
]);
const result = await runAgentLoop({
maxRunAgentTimes: 5,
body: {
model: 'gpt-4',
stream: true,
messages: [
{
role: ChatCompletionRequestMessageRoleEnum.User,
content: 'hello'
}
],
tools: []
},
usagePush,
isAborted: () => false,
onRunTool: vi.fn(),
onRunInteractiveTool: vi.fn(),
onAfterCompressContext
});
expect(result.contextCheckpoint).toEqual(contextCheckpoint);
expect(createLLMResponseMock.mock.calls[0][0].body.messages[0]).toEqual({
role: ChatCompletionRequestMessageRoleEnum.User,
content: contextCheckpoint,
hideInUI: true
});
expect(onAfterCompressContext).toHaveBeenCalledWith(
expect.objectContaining({
usage: undefined,
requestIds: [],
contextCheckpoint
})
);
expect(usagePush).not.toHaveBeenCalledWith([undefined]);
});
it('reuses request message tokens and counts only appended messages between turns', async () => {
countGptMessagesTokensMock
.mockResolvedValueOnce(11)
.mockResolvedValueOnce(17)
.mockResolvedValue(100);
compressRequestMessagesMock.mockImplementation(async ({ messages, messageTokens }) => ({
messages,
messageTokens: messageTokens ?? 1000
}));
const onRunTool = vi.fn(async () => ({
response: 'search result',
assistantMessages: [],
usages: []
}));
mockCreateLLMResponseQueue(createLLMResponseMock, [
toolCall({
id: 'call_search',
name: 'search',
args: {
q: 'FastGPT'
}
}),
text({ requestId: 'req_final', content: 'final answer' })
]);
await runAgentLoop({
maxRunAgentTimes: 5,
body: {
model: 'gpt-4',
stream: true,
messages: [
{
role: ChatCompletionRequestMessageRoleEnum.User,
content: 'search FastGPT'
}
],
tools: [searchTool]
},
usagePush: vi.fn(),
isAborted: () => false,
onRunTool,
onRunInteractiveTool: vi.fn()
});
expect(compressRequestMessagesMock).toHaveBeenCalledTimes(2);
expect(compressRequestMessagesMock.mock.calls[0][0].messageTokens).toBeUndefined();
expect(compressRequestMessagesMock.mock.calls[0][0].tools).toEqual([searchTool]);
expect(compressRequestMessagesMock.mock.calls[1][0].messageTokens).toBe(1028);
expect(compressRequestMessagesMock.mock.calls[1][0].tools).toEqual([searchTool]);
expect(countGptMessagesTokensMock.mock.calls[0][0].messages).toEqual([
expect.objectContaining({
role: ChatCompletionRequestMessageRoleEnum.Assistant
})
]);
expect(countGptMessagesTokensMock.mock.calls[1][0].messages).toEqual([
expect.objectContaining({
role: ChatCompletionRequestMessageRoleEnum.Tool,
content: 'search result'
})
]);
});
it('uses request control tool choice while streaming immediately', async () => {
const streamed: string[] = [];
const order: string[] = [];
......
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const cronMocks = vi.hoisted(() => ({
setCron: vi.fn(),
......@@ -39,10 +39,16 @@ import { cronJob } from '@fastgpt/service/core/ai/sandbox/service/cron';
describe('sandbox cron service', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-06-24T01:00:00.000Z'));
cronMocks.checkTimerLock.mockResolvedValue(true);
cronMocks.archiveInactiveSandboxes.mockResolvedValue(undefined);
});
afterEach(() => {
vi.useRealTimers();
});
it('registers a cron task and skips when no inactive sandbox exists', async () => {
cronMocks.findInactiveRunningSandboxResources.mockResolvedValueOnce([]);
......@@ -51,7 +57,9 @@ describe('sandbox cron service', () => {
await callback();
expect(cronMocks.setCron).toHaveBeenCalledWith('*/5 * * * *', expect.any(Function));
expect(cronMocks.findInactiveRunningSandboxResources).toHaveBeenCalledWith(expect.any(Date));
expect(cronMocks.findInactiveRunningSandboxResources).toHaveBeenCalledWith(
new Date('2026-06-24T00:50:00.000Z')
);
expect(cronMocks.stopSandboxResources).not.toHaveBeenCalled();
});
......
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { afterEach, describe, it, expect, vi, beforeEach } from 'vitest';
import http from 'http';
import os from 'os';
// --- Hoisted mocks ---
const { mockDereference, mockMongoAppFind } = vi.hoisted(() => ({
......@@ -12,15 +14,22 @@ vi.mock('@apidevtools/json-schema-ref-parser', () => ({
}
}));
vi.mock('@fastgpt/service/core/app/schema', () => ({
vi.mock('../../../core/app/schema', () => ({
MongoApp: {
find: mockMongoAppFind
}
}));
import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { MCPClient, assertMCPUrlNotInternal, getMCPChildren } from '@fastgpt/service/core/app/mcp';
import {
MCPClient,
assertMCPUrlNotInternal,
createMcpSafeFetch,
getMCPChildren
} from '../../../core/app/mcp';
import type { AppSchemaType } from '@fastgpt/global/core/app/type';
import { PRIVATE_URL_TEXT } from '../../../common/system/utils';
import { serviceEnv } from '../../../env';
// Access private client via prototype for spying
const getPrivateClient = (mcpClient: MCPClient) =>
......@@ -36,6 +45,48 @@ beforeEach(() => {
vi.restoreAllMocks();
});
const mutableServiceEnv = serviceEnv as { CHECK_INTERNAL_IP: boolean };
const originalCheckInternalIp = serviceEnv.CHECK_INTERNAL_IP;
afterEach(() => {
mutableServiceEnv.CHECK_INTERNAL_IP = originalCheckInternalIp;
});
const listen = (handler: http.RequestListener, host = '127.0.0.1') =>
new Promise<http.Server>((resolve) => {
const server = http.createServer(handler);
server.listen(0, host, () => resolve(server));
});
const closeServer = (server: http.Server) =>
new Promise<void>((resolve, reject) => {
server.close((err) => (err ? reject(err) : resolve()));
});
const getServerPort = (server: http.Server): number => {
const address = server.address();
if (!address || typeof address === 'string') {
throw new Error('Invalid test server address');
}
return address.port;
};
/**
* 构造一个非 loopback 的本机访问地址,用于模拟“初始 MCP URL 通过 SSRF 校验”。
* CHECK_INTERNAL_IP=false 时私网地址会放行,但 loopback/metadata 仍然恒拦截。
*/
const getReachablePrivateHost = () => {
const interfaces = os.networkInterfaces();
for (const items of Object.values(interfaces)) {
for (const item of items || []) {
if (item.family === 'IPv4' && !item.internal) {
return item.address;
}
}
}
return undefined;
};
describe('MCPClient', () => {
const config = { url: 'https://example.com/mcp', headers: { Authorization: 'Bearer test' } };
......@@ -200,7 +251,9 @@ describe('MCPClient', () => {
const tools = await mcpClient.getTools();
const homeSchema = tools[0].inputSchema.properties!['home'] as any;
expect(tools[0]).toBeDefined();
const inputSchema = tools[0]!.inputSchema!;
const homeSchema = inputSchema.properties!['home'] as any;
expect(homeSchema).toEqual({
type: 'object',
properties: { street: { type: 'string' }, city: { type: 'string' } }
......@@ -271,7 +324,9 @@ describe('MCPClient', () => {
const tools = await mcpClient.getTools();
// Verify nested refs are fully resolved
const ownerProps = (tools[0].inputSchema.properties!['owner'] as any).properties;
expect(tools[0]).toBeDefined();
const inputSchema = tools[0]!.inputSchema!;
const ownerProps = (inputSchema.properties!['owner'] as any).properties;
expect(ownerProps.name.properties).toEqual({
first: { type: 'string' },
last: { type: 'string' }
......@@ -311,7 +366,9 @@ describe('MCPClient', () => {
const tools = await mcpClient.getTools();
const tagsSchema = tools[0].inputSchema.properties!['tags'] as any;
expect(tools[0]).toBeDefined();
const inputSchema = tools[0]!.inputSchema!;
const tagsSchema = inputSchema.properties!['tags'] as any;
expect(tagsSchema.items).toEqual({
type: 'object',
properties: { label: { type: 'string' } }
......@@ -485,6 +542,130 @@ describe('MCPClient', () => {
});
});
describe('createMcpSafeFetch', () => {
it('should follow safe redirects hop by hop', async () => {
mutableServiceEnv.CHECK_INTERNAL_IP = false;
const carrierHost = getReachablePrivateHost();
if (!carrierHost) {
return;
}
const targetServer = await listen((req, res) => {
res.end(JSON.stringify({ ok: true, url: req.url }));
}, '0.0.0.0');
const targetPort = getServerPort(targetServer);
const redirectServer = await listen((req, res) => {
res.statusCode = 302;
res.setHeader('Location', `http://${carrierHost}:${targetPort}/mcp-target`);
res.end('redirect');
}, '0.0.0.0');
const redirectPort = getServerPort(redirectServer);
try {
const response = await createMcpSafeFetch()(`http://${carrierHost}:${redirectPort}/mcp`);
expect(await response.json()).toEqual({ ok: true, url: '/mcp-target' });
} finally {
await closeServer(redirectServer);
await closeServer(targetServer);
}
});
it('should block redirects to loopback addresses', async () => {
mutableServiceEnv.CHECK_INTERNAL_IP = false;
const carrierHost = getReachablePrivateHost();
if (!carrierHost) {
return;
}
const protectedServer = await listen((req, res) => {
res.end('INTERNAL-ONLY-RESPONSE');
});
const protectedPort = getServerPort(protectedServer);
const redirectServer = await listen((req, res) => {
res.statusCode = 302;
res.setHeader('Location', `http://127.0.0.1:${protectedPort}/mcp`);
res.end('redirect');
}, '0.0.0.0');
const redirectPort = getServerPort(redirectServer);
try {
await expect(createMcpSafeFetch()(`http://${carrierHost}:${redirectPort}/mcp`)).rejects.toBe(
PRIVATE_URL_TEXT
);
} finally {
await closeServer(redirectServer);
await closeServer(protectedServer);
}
});
it('should enforce max redirect count', async () => {
mutableServiceEnv.CHECK_INTERNAL_IP = false;
const carrierHost = getReachablePrivateHost();
if (!carrierHost) {
return;
}
let redirectPort = 0;
const redirectServer = await listen((req, res) => {
res.statusCode = 302;
res.setHeader('Location', `http://${carrierHost}:${redirectPort}/loop`);
res.end('redirect');
}, '0.0.0.0');
redirectPort = getServerPort(redirectServer);
try {
await expect(
createMcpSafeFetch({ maxRedirects: 1 })(`http://${carrierHost}:${redirectPort}/loop`)
).rejects.toThrow('Maximum MCP redirects exceeded');
} finally {
await closeServer(redirectServer);
}
});
it('should drop sensitive headers when redirect target changes', async () => {
mutableServiceEnv.CHECK_INTERNAL_IP = false;
const carrierHost = getReachablePrivateHost();
if (!carrierHost) {
return;
}
let receivedAuthorization: string | undefined;
let receivedCookie: string | undefined;
const targetServer = await listen((req, res) => {
receivedAuthorization = req.headers.authorization;
receivedCookie = req.headers.cookie;
res.end('ok');
}, '0.0.0.0');
const targetPort = getServerPort(targetServer);
const redirectServer = await listen((req, res) => {
res.statusCode = 302;
res.setHeader('Location', `http://${carrierHost}:${targetPort}/mcp-target`);
res.end('redirect');
}, '0.0.0.0');
const redirectPort = getServerPort(redirectServer);
try {
const response = await createMcpSafeFetch()(`http://${carrierHost}:${redirectPort}/mcp`, {
headers: {
Authorization: 'Bearer secret',
Cookie: 'token=secret'
}
});
expect(await response.text()).toBe('ok');
expect(receivedAuthorization).toBeUndefined();
expect(receivedCookie).toBeUndefined();
} finally {
await closeServer(redirectServer);
await closeServer(targetServer);
}
});
});
describe('getMCPChildren', () => {
it('should return tool list from new MCP format', async () => {
const app = {
......
......@@ -241,7 +241,7 @@ describe('createWorkflowAgentLoopRuntime', () => {
nodeId: 'agent_node-main_agent-1',
moduleName: 'chat:master_agent_call',
moduleType: FlowNodeTypeEnum.agent,
moduleLogo: 'core/workflow/template/agent',
moduleLogo: 'core/app/type/agentFill',
model: 'GPT-4',
llmRequestIds: ['req_1'],
inputTokens: 10,
......@@ -257,7 +257,7 @@ describe('createWorkflowAgentLoopRuntime', () => {
nodeId: 'agent_node-main_agent-2',
moduleName: 'chat:master_agent_call',
moduleType: FlowNodeTypeEnum.agent,
moduleLogo: 'core/workflow/template/agent',
moduleLogo: 'core/app/type/agentFill',
model: 'GPT-4',
llmRequestIds: ['req_2'],
inputTokens: 6,
......@@ -392,19 +392,19 @@ describe('createWorkflowAgentLoopRuntime', () => {
expect.objectContaining({
id: 'agent_node-1-req_empty_start',
moduleName: 'chat:master_agent_call',
moduleLogo: 'core/workflow/template/agent',
moduleLogo: 'core/app/type/agentFill',
llmRequestIds: ['req_empty_start']
}),
expect.objectContaining({
id: 'agent_node-2-req_tool_round',
moduleName: 'chat:master_agent_call',
moduleLogo: 'core/workflow/template/agent',
moduleLogo: 'core/app/type/agentFill',
llmRequestIds: ['req_tool_round']
}),
expect.objectContaining({
id: 'agent_node-3-req_empty_end',
moduleName: 'chat:master_agent_call',
moduleLogo: 'core/workflow/template/agent',
moduleLogo: 'core/app/type/agentFill',
llmRequestIds: ['req_empty_end']
})
]);
......
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { dispatchTool } from '@fastgpt/service/core/workflow/dispatch/ai/agent/sub/tool';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
const { authAppByTmbIdMock, getAppVersionByIdMock, runHTTPToolMock, mcpToolCallMock } = vi.hoisted(
() => ({
authAppByTmbIdMock: vi.fn(),
getAppVersionByIdMock: vi.fn(),
runHTTPToolMock: vi.fn(),
mcpToolCallMock: vi.fn()
})
);
vi.mock('@fastgpt/service/support/permission/app/auth', () => ({
authAppByTmbId: authAppByTmbIdMock
}));
vi.mock('@fastgpt/service/core/app/version/controller', () => ({
getAppVersionById: getAppVersionByIdMock
}));
vi.mock('@fastgpt/service/core/app/http', () => ({
runHTTPTool: runHTTPToolMock
}));
vi.mock('@fastgpt/service/core/app/mcp', () => ({
assertMCPUrlNotInternal: vi.fn(),
MCPClient: vi.fn().mockImplementation(() => ({
toolCall: mcpToolCallMock
}))
}));
vi.mock('@fastgpt/service/common/logger', () => ({
LogCategories: {
MODULE: {
APP: {
TOOL: 'tool'
},
AI: {
LLM: 'llm'
}
}
},
getLogger: vi.fn(() => ({
error: vi.fn()
}))
}));
vi.mock('@fastgpt/service/common/middle/tracks/utils', () => ({
pushTrack: {
runSystemTool: vi.fn()
}
}));
vi.mock('@fastgpt/service/thirdProvider/fastgptPlugin', () => ({
pluginClient: {
runToolStream: vi.fn()
}
}));
vi.mock('@fastgpt/service/core/app/tool/systemTool/systemTool.repo', () => ({
SystemToolRepo: {
getInstance: vi.fn(() => ({
getSystemToolRuntime: vi.fn()
}))
}
}));
const createDispatchToolProps = (toolConfig: Record<string, any>) =>
({
tool: {
name: 'Agent tool',
avatar: '',
toolConfig
},
params: {
keyword: 'fastgpt'
},
runningAppInfo: {
id: 'attacker-app',
teamId: 'attacker-team',
tmbId: 'attacker-tmb',
name: 'Attacker workflow'
},
runningUserInfo: {
username: 'attacker',
teamName: 'Attacker team',
memberName: 'Attacker member',
contact: '',
teamId: 'attacker-team',
tmbId: 'attacker-tmb'
},
chatId: 'chat',
uid: 'uid',
variableState: {
get: vi.fn()
}
}) as any;
describe('dispatchTool runtime toolset auth', () => {
beforeEach(() => {
vi.clearAllMocks();
authAppByTmbIdMock.mockResolvedValue({
app: {
_id: 'victim-toolset'
}
});
});
it('should reject HTTP agent tool execution when running app tmb has no parent toolset permission', async () => {
authAppByTmbIdMock.mockRejectedValueOnce(new Error('unAuthApp'));
const result = await dispatchTool(
createDispatchToolProps({
httpTool: {
toolId: 'http-victim-toolset/sandbox_echo'
}
})
);
expect(authAppByTmbIdMock).toHaveBeenCalledWith({
tmbId: 'attacker-tmb',
appId: 'victim-toolset',
per: ReadPermissionVal
});
expect(getAppVersionByIdMock).not.toHaveBeenCalled();
expect(runHTTPToolMock).not.toHaveBeenCalled();
expect(result.response).toBeTruthy();
});
it('should authorize HTTP parent toolset before agent tool execution', async () => {
getAppVersionByIdMock.mockResolvedValueOnce({
nodes: [
{
toolConfig: {
httpToolSet: {
baseUrl: 'https://example.com',
toolList: [
{
name: 'sandbox_echo',
path: '/echo',
method: 'post'
}
]
}
}
}
]
});
runHTTPToolMock.mockResolvedValueOnce({
data: {
ok: true
}
});
const result = await dispatchTool(
createDispatchToolProps({
httpTool: {
toolId: 'http-victim-toolset/sandbox_echo'
}
})
);
expect(authAppByTmbIdMock).toHaveBeenCalledWith({
tmbId: 'attacker-tmb',
appId: 'victim-toolset',
per: ReadPermissionVal
});
expect(getAppVersionByIdMock).toHaveBeenCalledWith({
appId: 'victim-toolset',
versionId: undefined
});
expect(runHTTPToolMock).toHaveBeenCalledWith(
expect.objectContaining({
baseUrl: 'https://example.com',
toolPath: '/echo',
method: 'post'
})
);
expect(result.response).toBe(JSON.stringify({ ok: true }));
});
it('should reject MCP agent tool execution when running app tmb has no parent toolset permission', async () => {
authAppByTmbIdMock.mockRejectedValueOnce(new Error('unAuthApp'));
const result = await dispatchTool(
createDispatchToolProps({
mcpTool: {
toolId: 'mcp-victim-toolset/search'
}
})
);
expect(authAppByTmbIdMock).toHaveBeenCalledWith({
tmbId: 'attacker-tmb',
appId: 'victim-toolset',
per: ReadPermissionVal
});
expect(getAppVersionByIdMock).not.toHaveBeenCalled();
expect(mcpToolCallMock).not.toHaveBeenCalled();
expect(result.response).toBeTruthy();
});
});
......@@ -333,6 +333,32 @@ describe('runToolCall compression node responses', () => {
);
});
it('ignores context compression callbacks without usage', async () => {
runAgentLoopMock.mockImplementation(async (options) => {
options.onAfterCompressContext({
requestIds: [],
seconds: 0.1
});
return createLoopResult();
});
const nodeResponseWriter = createWriter();
const result = await runToolCall(createProps({ nodeResponseWriter }));
await Promise.resolve();
expect(result.requestIds).toEqual(['req_main']);
expect(nodeResponseWriter.recordWithParent).not.toHaveBeenCalled();
expect(result.toolTotalPoints).toBe(0);
expect(result.runtimeNodeResponseSummary).toEqual(
expect.objectContaining({
responseIds: [],
finishedNodeIds: [],
runningTime: 0
})
);
});
it('records only the compression child after onAfterToolCall when the tool workflow wrote details', async () => {
const toolResponseCompressUsage = {
moduleName: 'account_usage:tool_response_compress',
......
import { describe, it, expect } from 'vitest';
import { parseToolId } from '@fastgpt/service/core/workflow/dispatch/child/runTool';
import { beforeEach, describe, it, expect, vi } from 'vitest';
import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import {
dispatchRunTool,
parseToolId
} from '@fastgpt/service/core/workflow/dispatch/child/runTool';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
import { NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants';
const { authAppByTmbIdMock, getAppVersionByIdMock, runHTTPToolMock, mcpToolCallMock } = vi.hoisted(
() => ({
authAppByTmbIdMock: vi.fn(),
getAppVersionByIdMock: vi.fn(),
runHTTPToolMock: vi.fn(),
mcpToolCallMock: vi.fn()
})
);
vi.mock('@fastgpt/service/support/permission/app/auth', () => ({
authAppByTmbId: authAppByTmbIdMock
}));
vi.mock('@fastgpt/service/core/app/version/controller', () => ({
getAppVersionById: getAppVersionByIdMock
}));
vi.mock('@fastgpt/service/core/app/http', () => ({
runHTTPTool: runHTTPToolMock
}));
vi.mock('@fastgpt/service/core/app/mcp', () => ({
assertMCPUrlNotInternal: vi.fn(),
MCPClient: vi.fn().mockImplementation(() => ({
toolCall: mcpToolCallMock
}))
}));
vi.mock('@fastgpt/service/common/logger', () => ({
LogCategories: {
MODULE: {
APP: {
TOOL: 'tool'
},
AI: {
LLM: 'llm'
}
}
},
getLogger: vi.fn(() => ({
error: vi.fn()
}))
}));
vi.mock('@fastgpt/service/common/middle/tracks/utils', () => ({
pushTrack: {
runSystemTool: vi.fn()
}
}));
vi.mock('@fastgpt/service/thirdProvider/fastgptPlugin', () => ({
pluginClient: {
runToolStream: vi.fn()
}
}));
vi.mock('@fastgpt/service/core/app/tool/systemTool/systemTool.repo', () => ({
SystemToolRepo: {
getInstance: vi.fn(() => ({
getSystemToolRuntime: vi.fn()
}))
}
}));
vi.mock('@fastgpt/service/core/workflow/utils/context', () => ({
getWorkflowContext: vi.fn(() => ({}))
}));
const createRunToolProps = (toolConfig: Record<string, any>) =>
({
params: {
keyword: 'fastgpt'
},
runningAppInfo: {
id: 'attacker-app',
teamId: 'attacker-team',
tmbId: 'attacker-tmb',
name: 'Attacker workflow'
},
runningUserInfo: {
username: 'attacker',
teamName: 'Attacker team',
memberName: 'Attacker member',
contact: '',
teamId: 'attacker-team',
tmbId: 'attacker-tmb'
},
variableState: {
get: vi.fn()
},
node: {
nodeId: 'tool-node',
flowNodeType: FlowNodeTypeEnum.tool,
name: 'Tool node',
avatar: '',
toolConfig,
inputs: [],
outputs: []
},
uid: 'uid',
chatId: 'chat',
responseChatItemId: 'response',
usagePush: vi.fn()
}) as any;
describe('dispatchRunTool runtime toolset auth', () => {
beforeEach(() => {
vi.clearAllMocks();
authAppByTmbIdMock.mockResolvedValue({
app: {
_id: 'victim-toolset'
}
});
});
it('should reject HTTP tool execution when running app tmb has no parent toolset permission', async () => {
authAppByTmbIdMock.mockRejectedValueOnce(new Error('unAuthApp'));
const result = await dispatchRunTool(
createRunToolProps({
httpTool: {
toolId: 'http-victim-toolset/sandbox_echo'
}
})
);
expect(authAppByTmbIdMock).toHaveBeenCalledWith({
tmbId: 'attacker-tmb',
appId: 'victim-toolset',
per: ReadPermissionVal
});
expect(getAppVersionByIdMock).not.toHaveBeenCalled();
expect(runHTTPToolMock).not.toHaveBeenCalled();
expect(result.error?.[NodeOutputKeyEnum.errorText]).toBeTruthy();
});
it('should authorize HTTP parent toolset before loading version and running tool', async () => {
getAppVersionByIdMock.mockResolvedValueOnce({
nodes: [
{
toolConfig: {
httpToolSet: {
baseUrl: 'https://example.com',
toolList: [
{
name: 'sandbox_echo',
path: '/echo',
method: 'post'
}
]
}
}
}
]
});
runHTTPToolMock.mockResolvedValueOnce({
data: {
ok: true
}
});
const result = await dispatchRunTool(
createRunToolProps({
httpTool: {
toolId: 'http-victim-toolset/sandbox_echo'
}
})
);
expect(authAppByTmbIdMock).toHaveBeenCalledWith({
tmbId: 'attacker-tmb',
appId: 'victim-toolset',
per: ReadPermissionVal
});
expect(getAppVersionByIdMock).toHaveBeenCalledWith({
appId: 'victim-toolset',
versionId: undefined
});
expect(runHTTPToolMock).toHaveBeenCalledWith(
expect.objectContaining({
baseUrl: 'https://example.com',
toolPath: '/echo',
method: 'post'
})
);
expect(result.data).toEqual({
[NodeOutputKeyEnum.rawResponse]: {
ok: true
},
ok: true
});
});
it('should reject MCP tool execution when running app tmb has no parent toolset permission', async () => {
authAppByTmbIdMock.mockRejectedValueOnce(new Error('unAuthApp'));
const result = await dispatchRunTool(
createRunToolProps({
mcpTool: {
toolId: 'mcp-victim-toolset/search'
}
})
);
expect(authAppByTmbIdMock).toHaveBeenCalledWith({
tmbId: 'attacker-tmb',
appId: 'victim-toolset',
per: ReadPermissionVal
});
expect(getAppVersionByIdMock).not.toHaveBeenCalled();
expect(mcpToolCallMock).not.toHaveBeenCalled();
expect(result.error?.[NodeOutputKeyEnum.errorText]).toBeTruthy();
});
});
describe('parseToolId', () => {
describe('新版格式: source-appId/toolName', () => {
......
import React from 'react';
import { Box, Input, VStack, type StackProps } from '@chakra-ui/react';
import { Trans, useTranslation } from 'next-i18next';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
type Props = Omit<StackProps, 'onChange'> & {
value: string;
......@@ -21,7 +22,7 @@ const DeleteConfirmInput = ({ value, confirmText, onChange, placeholder, ...prop
<VStack align={'stretch'} spacing={'10px'} {...props}>
<Box fontSize={'14px'} lineHeight={'20px'} color={'myGray.900'}>
<Trans
i18nKey={'common:confirm_input_delete_tip'}
i18nKey={i18nT('common:confirm_input_delete_tip')}
values={{ confirmText }}
components={{
bold: <Box as={'span'} fontWeight={'500'} userSelect={'all'} />
......
......@@ -6,6 +6,7 @@ import {
type FileExtensionKeyType
} from '@fastgpt/global/core/app/constants';
import MyIcon from '../../../common/Icon';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
type FileTypeSelectorValue = {
canSelectFile?: boolean;
......@@ -17,11 +18,14 @@ type FileTypeSelectorValue = {
};
const fileExtensionTypeTranslationMap = new Map<FileExtensionKeyType, string>([
['canSelectFile', 'app:upload_file_extension_type_canSelectFile'],
['canSelectImg', 'app:upload_file_extension_type_canSelectImg'],
['canSelectVideo', 'app:upload_file_extension_type_canSelectVideo'],
['canSelectAudio', 'app:upload_file_extension_type_canSelectAudio'],
['canSelectCustomFileExtension', 'app:upload_file_extension_type_canSelectCustomFileExtension']
['canSelectFile', i18nT('app:upload_file_extension_type_canSelectFile')],
['canSelectImg', i18nT('app:upload_file_extension_type_canSelectImg')],
['canSelectVideo', i18nT('app:upload_file_extension_type_canSelectVideo')],
['canSelectAudio', i18nT('app:upload_file_extension_type_canSelectAudio')],
[
'canSelectCustomFileExtension',
i18nT('app:upload_file_extension_type_canSelectCustomFileExtension')
]
]);
export const FileTypeSelectorPanel = ({
......
......@@ -250,9 +250,9 @@
"logs_source_count": "Channel users",
"logs_source_count_description": "Number of users across channels",
"logs_timespan_day": "Day",
"logs_timespan_week": "Week",
"logs_timespan_month": "Month",
"logs_timespan_quarter": "Quarter",
"logs_timespan_week": "Week",
"logs_title": "Title",
"logs_total": "Grand total",
"logs_total_avg_duration": "Avg. duration",
......@@ -285,6 +285,7 @@
"my_agents": "my agents",
"new_input_guide_lexicon": "New Lexicon",
"no_mcp_tools_list": "No data yet, the MCP address needs to be parsed first",
"node_not_intro": "Node lacks introduction",
"not_json_file": "Please select a JSON file",
"not_the_newest": "Not the latest",
"open_auto_execute": "Enable automatic execution",
......@@ -497,8 +498,12 @@
"unnamed_app": "Unnamed",
"upgrade": "Upgrade",
"upload_file_exists_filtered": "Duplicate files have been automatically filtered.",
"upload_file_extension_type_canSelectAudio": "Audio",
"upload_file_extension_type_canSelectCustomFileExtension": "Custom file extension type",
"upload_file_extension_type_canSelectCustomFileExtension_placeholder": "file extension name",
"upload_file_extension_type_canSelectFile": "Documents",
"upload_file_extension_type_canSelectImg": "Images",
"upload_file_extension_type_canSelectVideo": "Videos",
"upload_file_extension_types": "Supported file types",
"upload_file_max_amount": "Maximum File Quantity",
"upload_file_max_amount_tip": "Maximum number of files uploaded in a single round of conversation",
......
......@@ -250,9 +250,9 @@
"logs_source_count": "渠道用户",
"logs_source_count_description": "各渠道用户的数量",
"logs_timespan_day": "按天",
"logs_timespan_week": "按周",
"logs_timespan_month": "按月",
"logs_timespan_quarter": "按季度",
"logs_timespan_week": "按周",
"logs_title": "标题",
"logs_total": "累计",
"logs_total_avg_duration": "平均时长",
......@@ -285,6 +285,7 @@
"my_agents": "我的 agents",
"new_input_guide_lexicon": "新词库",
"no_mcp_tools_list": "暂无数据,需先解析 MCP 地址",
"node_not_intro": "节点缺少介绍",
"not_json_file": "请选择JSON文件",
"not_the_newest": "非最新版",
"open_auto_execute": "启用自动执行",
......@@ -497,8 +498,12 @@
"unnamed_app": "未命名",
"upgrade": "去升级",
"upload_file_exists_filtered": "已自动过滤重复文件",
"upload_file_extension_type_canSelectAudio": "音频",
"upload_file_extension_type_canSelectCustomFileExtension": "自定义文件扩展类型",
"upload_file_extension_type_canSelectCustomFileExtension_placeholder": "文件扩展名",
"upload_file_extension_type_canSelectFile": "文档",
"upload_file_extension_type_canSelectImg": "图片",
"upload_file_extension_type_canSelectVideo": "视频",
"upload_file_extension_types": "支持上传的类型",
"upload_file_max_amount": "最大文件数量",
"upload_file_max_amount_tip": "单轮对话中最大上传文件数量",
......
......@@ -244,9 +244,9 @@
"logs_source": "來源",
"logs_source_count_description": "各渠道用戶的數量",
"logs_timespan_day": "按天",
"logs_timespan_week": "按週",
"logs_timespan_month": "按月",
"logs_timespan_quarter": "按季度",
"logs_timespan_week": "按週",
"logs_title": "標題",
"logs_total": "累計",
"logs_total_avg_points": "平均消耗",
......@@ -277,6 +277,7 @@
"my_agents": "我的 agents",
"new_input_guide_lexicon": "新增詞彙庫",
"no_mcp_tools_list": "暫無數據,需先解析 MCP 地址",
"node_not_intro": "節點缺少介紹",
"not_json_file": "請選擇 JSON 檔案",
"not_the_newest": "非最新版",
"open_auto_execute": "啟用自動執行",
......@@ -300,6 +301,7 @@
"publish.show_whole_response": "顯示完整回應",
"publish.show_whole_response_tip": "開啟後,聊天頁面可查看每個模組的詳細回應流程",
"publish_channel": "發布通道",
"publish_channel.wecom.empty": "發布到企業微信機器人,請先 <a>綁定自定義域名</a>,並且通過域名校驗。",
"publish_success": "發布成功",
"question_guide_tip": "對話結束後,會為你產生 3 個引導性問題。",
"raw_params": "原始參數",
......@@ -483,8 +485,12 @@
"unnamed_app": "未命名",
"upgrade": "去升級",
"upload_file_exists_filtered": "已自動過濾重複檔案",
"upload_file_extension_type_canSelectAudio": "音頻",
"upload_file_extension_type_canSelectCustomFileExtension": "自定義文件擴展類型",
"upload_file_extension_type_canSelectCustomFileExtension_placeholder": "文件擴展名",
"upload_file_extension_type_canSelectFile": "文件",
"upload_file_extension_type_canSelectImg": "圖片",
"upload_file_extension_type_canSelectVideo": "視頻",
"upload_file_extension_types": "支持上傳的類型",
"upload_file_max_amount": "最大檔案數量",
"upload_file_max_amount_tip": "單輪對話中最大上傳檔案數量",
......
Subproject commit 1f9f0765e34037205ca59b453658b8a3caf2558a
Subproject commit 0103ae5b530380c8452abb2a479b49a3e767bf8d
......@@ -69,6 +69,12 @@ const VariableEditModal = ({
) {
setValue('defaultValue', '');
}
if (
(typeEnum === VariableInputEnum.select || typeEnum === VariableInputEnum.multipleSelect) &&
!value.list?.length
) {
setValue('list', [{ label: '', value: '' }]);
}
if (typeEnum === VariableInputEnum.datasetSelect && !value.datasetOptions) {
setValue('datasetOptions', []);
}
......
import Markdown from '@/components/Markdown';
import { Box } from '@chakra-ui/react';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
import type { AIChatItemValueItemType } from '@fastgpt/global/core/chat/type';
import { useSize } from 'ahooks';
import React, { useEffect, useMemo, useRef } from 'react';
......@@ -106,11 +107,8 @@ const ProcessingPreviewBody = React.memo(function ProcessingPreviewBody({
export const getProcessingPreviewLabelKey = (value: AIChatItemValueItemType) => {
const tool = value.tools?.[value.tools.length - 1] || value.tool;
if (tool) return tool.toolName;
if (
(value.reasoning?.content || value.agentPlanUpdate?.reasoningText) &&
!value.hideReason
) {
return 'chat:history_generating';
if ((value.reasoning?.content || value.agentPlanUpdate?.reasoningText) && !value.hideReason) {
return i18nT('chat:history_generating');
}
return '';
......
import MyModal from '@fastgpt/web/components/common/MyModal';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation, Trans } from 'next-i18next';
import { Box, ModalBody, Flex, Button, Text, Link } from '@chakra-ui/react';
import { Box, ModalBody, Flex, Button, Link } from '@chakra-ui/react';
import { checkBalancePayResult, putUpdatePayment } from '@/web/support/wallet/bill/api';
import LightTip from '@fastgpt/web/components/common/LightTip';
import QRCode from 'qrcode';
......@@ -16,6 +16,7 @@ import Markdown from '@/components/Markdown';
import MyIcon from '@fastgpt/web/components/common/Icon';
import { useToast } from '@fastgpt/web/hooks/useToast';
import type { CreateBillResponseType } from '@fastgpt/global/openapi/support/wallet/bill/api';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
export type QRPayProps = CreateBillResponseType & {
billId: string;
......@@ -284,7 +285,7 @@ const QRCodePayModal = ({
{feConfigs.payFormUrl && (
<Box mt={4} textAlign="center" fontSize="sm">
<Trans
i18nKey="common:pay.payment_form_tip"
i18nKey={i18nT('common:pay.payment_form_tip')}
components={{
payLink: <Link href={feConfigs.payFormUrl} target="_blank" color="primary.600" />
}}
......
......@@ -36,6 +36,7 @@ import {
createCustomDomain
} from '@/web/support/customDomain/api';
import { getDocPath } from '@/web/common/system/doc';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
const ProviderItem = ({
icon,
......@@ -92,16 +93,21 @@ function CreateCustomDomainModal<T extends 'create' | 'refresh'>({
const { feConfigs } = useSystemStore();
const { copyData } = useCopyData();
const [provider, setProvider] = useState<ProviderEnum>('tencent');
const [domain, setDomain] = useState<string>('');
const [provider, setProvider] = useState<ProviderEnum>(() =>
type === 'refresh' ? data?.provider || 'tencent' : 'tencent'
);
const [domain, setDomain] = useState<string>(() =>
type === 'refresh' ? data?.domain || '' : ''
);
const [editDomain, setEditDomain] = useState<boolean>(true);
useEffect(() => {
if (type === 'refresh') {
setProvider(data?.provider || 'tencent');
setDomain(data?.domain || '');
}
}, [data, type]);
const updateProvider = (provider: ProviderEnum) => {
setProvider(provider);
setDnsResolved(false);
};
const updateDomain = (domain: string) => {
setDomain(domain);
setDnsResolved(false);
};
const cnameDomain = useMemo(() => {
if (type === 'refresh') {
......@@ -151,12 +157,6 @@ function CreateCustomDomainModal<T extends 'create' | 'refresh'>({
return () => clearInterval(intervalId);
}, [DnsResolved, checkDNSResolve, cnameDomain, domain, editDomain, startDnsResolve]);
useEffect(() => {
if (domain && provider) {
setDnsResolved(false);
}
}, [domain, provider]);
const loading = loadingCreatingDomain;
return (
......@@ -175,25 +175,25 @@ function CreateCustomDomainModal<T extends 'create' | 'refresh'>({
<ProviderItem
icon="support/account/customDomain/provider/tencent"
selected={provider === 'tencent'}
onClick={() => setProvider('tencent')}
onClick={() => updateProvider('tencent')}
isDisabled={!editDomain || type === 'refresh'}
/>
<ProviderItem
icon="support/account/customDomain/provider/aliyun"
selected={provider === 'aliyun'}
onClick={() => setProvider('aliyun')}
onClick={() => updateProvider('aliyun')}
isDisabled={!editDomain || type === 'refresh'}
/>
<ProviderItem
icon="support/account/customDomain/provider/volcengine"
selected={provider === 'volcengine'}
onClick={() => setProvider('volcengine')}
onClick={() => updateProvider('volcengine')}
isDisabled={!editDomain || type === 'refresh'}
/>
</Flex>
<Box marginTop={'16px'} fontSize={'sm'} color={'gray.600'}>
<Trans
i18nKey="account_custom_domain:registration_hint"
i18nKey={i18nT('account_custom_domain:registration_hint')}
values={{ provider: t(providerMap[provider]) }}
components={{ bold: <Text as="span" fontWeight="bold" color="gray.900" /> }}
/>
......@@ -204,7 +204,7 @@ function CreateCustomDomainModal<T extends 'create' | 'refresh'>({
h="40px"
placeholder="www.example.com"
value={domain}
onChange={(e) => setDomain(e.target.value)}
onChange={(e) => updateDomain(e.target.value)}
isDisabled={!editDomain || type === 'refresh'}
/>
<InputRightElement width="auto" paddingRight={'8px'}>
......@@ -258,7 +258,7 @@ function CreateCustomDomainModal<T extends 'create' | 'refresh'>({
</Box>
<Box marginTop={'16px'} fontSize={'sm'} color={'gray.600'}>
<Trans
i18nKey="account_custom_domain:DNS_resolve_hint"
i18nKey={i18nT('account_custom_domain:DNS_resolve_hint')}
values={{ domain: cnameDomain }}
components={{ bold: <Text as="span" fontWeight="bold" color="gray.900" /> }}
/>
......
......@@ -28,6 +28,7 @@ import PopoverConfirm from '@fastgpt/web/components/common/MyPopover/PopoverConf
import { useRequest } from '@fastgpt/web/hooks/useRequest';
import { downloadFetch } from '@/web/common/system/utils';
import { useSafeTranslation } from '@fastgpt/web/hooks/useSafeTranslation';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
const UsageDetail = dynamic(() => import('./UsageDetail'));
const RechargeModal = dynamic(() =>
......@@ -92,14 +93,14 @@ const UsageTableList = ({
...requestParams,
appNameMap: {
['core.app.Question Guide']: t('common:core.app.Question Guide'),
['common:support.wallet.usage.Audio Speech']: t(
[i18nT('common:support.wallet.usage.Audio Speech')]: t(
'common:support.wallet.usage.Audio Speech'
),
['support.wallet.usage.Whisper']: t('common:support.wallet.usage.Whisper'),
['account_usage:embedding_index']: t('account_usage:embedding_index'),
['account_usage:qa']: t('account_usage:qa'),
[i18nT('account_usage:embedding_index')]: t('account_usage:embedding_index'),
[i18nT('account_usage:qa')]: t('account_usage:qa'),
['core.dataset.training.Auto mode']: t('common:core.dataset.training.Auto mode'),
['common:core.module.template.ai_chat']: t('common:core.module.template.ai_chat')
[i18nT('common:core.module.template.ai_chat')]: t('common:core.module.template.ai_chat')
},
sourcesMap: Object.fromEntries(
Object.entries(UsageSourceMap).map(([key, config]) => [
......
......@@ -29,6 +29,7 @@ import EmptyTip from '@fastgpt/web/components/common/EmptyTip';
import { useRequest } from '@fastgpt/web/hooks/useRequest';
import { getDocPath } from '@/web/common/system/doc';
import { listCustomDomain } from '@/web/support/customDomain/api';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
const WecomEditModal = dynamic(() => import('./WecomEditModal'));
const ShowShareLinkModal = dynamic(() => import('../components/showShareLinkModal'));
......@@ -252,7 +253,7 @@ const Wecom = ({ appId }: { appId: string }) => {
: {
text: (
<Trans
i18nKey="app:publish_channel.wecom.empty"
i18nKey={i18nT('app:publish_channel.wecom.empty')}
components={{
a: (
<Link
......
......@@ -29,6 +29,7 @@ import { WorkflowBufferDataContext } from '../../../context/workflowInitContext'
import { WorkflowInitContext } from '../../../context/workflowInitContext';
import { nodeTemplate2FlowNode } from '@/web/core/workflow/utils';
import { useMemoEnhance } from '@fastgpt/web/hooks/useMemoEnhance';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
const NodeLoopRun = ({ data, selected }: NodeProps<FlowNodeItemType>) => {
const { t } = useTranslation();
......@@ -39,7 +40,10 @@ const NodeLoopRun = ({ data, selected }: NodeProps<FlowNodeItemType>) => {
WorkflowBufferDataContext,
(v) => v
);
const childNodeIds = childrenNodeIdListMap[nodeId] ?? [];
const childNodeIds = useMemo(
() => childrenNodeIdListMap[nodeId] ?? [],
[childrenNodeIdListMap, nodeId]
);
const getRawNodeById = useContextSelector(WorkflowInitContext, (v) => v.getRawNodeById);
const mode =
......@@ -111,8 +115,8 @@ const NodeLoopRun = ({ data, selected }: NodeProps<FlowNodeItemType>) => {
value: {
id: NodeOutputKeyEnum.currentIndex,
key: NodeOutputKeyEnum.currentIndex,
label: 'workflow:current_index',
description: 'workflow:current_index_desc',
label: i18nT('workflow:current_index'),
description: i18nT('workflow:current_index_desc'),
type: FlowNodeOutputTypeEnum.static,
valueType: WorkflowIOValueTypeEnum.number
}
......@@ -125,8 +129,8 @@ const NodeLoopRun = ({ data, selected }: NodeProps<FlowNodeItemType>) => {
value: {
id: NodeOutputKeyEnum.currentItem,
key: NodeOutputKeyEnum.currentItem,
label: 'workflow:current_item',
description: 'workflow:current_item_desc',
label: i18nT('workflow:current_item'),
description: i18nT('workflow:current_item_desc'),
type: FlowNodeOutputTypeEnum.static,
valueType: WorkflowIOValueTypeEnum.any
}
......@@ -154,8 +158,8 @@ const NodeLoopRun = ({ data, selected }: NodeProps<FlowNodeItemType>) => {
value: {
id: NodeOutputKeyEnum.currentIteration,
key: NodeOutputKeyEnum.currentIteration,
label: 'workflow:current_iteration',
description: 'workflow:current_iteration_desc',
label: i18nT('workflow:current_iteration'),
description: i18nT('workflow:current_iteration_desc'),
type: FlowNodeOutputTypeEnum.static,
valueType: WorkflowIOValueTypeEnum.number
}
......
......@@ -123,6 +123,13 @@ const InputFormEditModal = ({
onTypeChange={(type) => {
setValue('type', type as FlowNodeInputTypeEnum);
setValue('defaultValue', '');
if (
(type === FlowNodeInputTypeEnum.select ||
type === FlowNodeInputTypeEnum.multipleSelect) &&
!form.getValues('list')?.length
) {
setValue('list', [{ label: '', value: '' }]);
}
}}
/>
</Stack>
......
......@@ -192,6 +192,13 @@ const FieldEditModal = ({
if (targetItem) {
setValue('renderTypeList', targetItem.value);
setValue('defaultValue', '');
if (
(type === FlowNodeInputTypeEnum.select ||
type === FlowNodeInputTypeEnum.multipleSelect) &&
!form.getValues('list')?.length
) {
setValue('list', [{ label: '', value: '' }]);
}
}
}}
/>
......
......@@ -159,9 +159,21 @@ const InputTypeConfig = ({
name: 'list'
});
const mergedSelectEnums = selectEnums.map((field, index) => ({
...field,
...listValue[index]
const isSelectInput =
inputType === FlowNodeInputTypeEnum.select || inputType === VariableInputEnum.select;
const isMultipleSelectInput =
inputType === FlowNodeInputTypeEnum.multipleSelect ||
inputType === VariableInputEnum.multipleSelect;
const isOptionInput = isSelectInput || isMultipleSelectInput;
const optionFields = (listValue.length ? listValue : selectEnums) as {
id?: string;
label?: string;
value?: string;
}[];
const optionDragList = optionFields.map((item, index) => ({
id: item.id || `${index}`,
label: item.label || '',
value: item.value || item.label || ''
}));
const handleRemoveEnum = useCallback(
......@@ -171,7 +183,7 @@ const InputTypeConfig = ({
if (!removedValue) return;
if (inputType === FlowNodeInputTypeEnum.multipleSelect) {
if (isMultipleSelectInput) {
const cur = getValues('defaultValue');
if (Array.isArray(cur) && cur.includes(removedValue)) {
setValue(
......@@ -179,16 +191,16 @@ const InputTypeConfig = ({
cur.filter((v: string) => v !== removedValue)
);
}
} else if (inputType === FlowNodeInputTypeEnum.select) {
} else if (isSelectInput) {
if (getValues('defaultValue') === removedValue) {
setValue('defaultValue', '');
}
}
},
[removeEnums, inputType, getValues, setValue]
[removeEnums, isMultipleSelectInput, isSelectInput, getValues, setValue]
);
const isLastEnumEmpty = !mergedSelectEnums[mergedSelectEnums.length - 1]?.label;
const isOptionLimitReached = optionFields.length >= 50;
const valueTypeSelectList = Object.values(FlowValueTypeMap)
.filter((item) => !item.abandon)
......@@ -255,8 +267,8 @@ const InputTypeConfig = ({
[VariableInputEnum.datasetSelect]: true
};
return map[inputType as keyof typeof map];
}, [inputType]);
return isOptionInput || map[inputType as keyof typeof map];
}, [inputType, isOptionInput]);
const showIsToolInput = useMemo(() => {
const list = [
......@@ -287,6 +299,21 @@ const InputTypeConfig = ({
defaultValue: data.defaultValue
};
if (isOptionInput) {
const cleanList = (data.list ?? []).filter(
(item: { label?: string; value?: string }) => !!item?.label
);
commonData.list = cleanList;
const validValues = new Set(cleanList.map((item: { value: string }) => item.value));
if (isMultipleSelectInput) {
commonData.defaultValue = Array.isArray(commonData.defaultValue)
? commonData.defaultValue.filter((v: string) => validValues.has(v))
: commonData.defaultValue;
} else if (commonData.defaultValue && !validValues.has(commonData.defaultValue)) {
commonData.defaultValue = '';
}
}
switch (inputType) {
case FlowNodeInputTypeEnum.input:
case FlowNodeInputTypeEnum.textarea:
......@@ -296,22 +323,6 @@ const InputTypeConfig = ({
commonData.max = data.max;
commonData.min = data.min;
break;
case FlowNodeInputTypeEnum.select:
case FlowNodeInputTypeEnum.multipleSelect: {
const cleanList = (data.list ?? []).filter(
(item: { label?: string; value?: string }) => !!item?.label
);
commonData.list = cleanList;
const validValues = new Set(cleanList.map((item: { value: string }) => item.value));
if (inputType === FlowNodeInputTypeEnum.multipleSelect) {
commonData.defaultValue = Array.isArray(commonData.defaultValue)
? commonData.defaultValue.filter((v: string) => validValues.has(v))
: commonData.defaultValue;
} else if (commonData.defaultValue && !validValues.has(commonData.defaultValue)) {
commonData.defaultValue = '';
}
break;
}
case FlowNodeInputTypeEnum.addInputParam:
commonData.customInputConfig = data.customInputConfig;
break;
......@@ -372,7 +383,7 @@ const InputTypeConfig = ({
return commonData;
},
[inputType]
[inputType, isMultipleSelectInput, isOptionInput]
);
return (
......@@ -615,7 +626,7 @@ const InputTypeConfig = ({
<Switch {...register('defaultValue')} />
</Flex>
)}
{inputType === FlowNodeInputTypeEnum.select && (
{isSelectInput && (
<MySelect<string>
list={[defaultListValue, ...listValue]
.filter((item) => item.label !== '')
......@@ -634,7 +645,7 @@ const InputTypeConfig = ({
w={'200px'}
/>
)}
{inputType === FlowNodeInputTypeEnum.multipleSelect && (
{isMultipleSelectInput && (
<MultipleSelect<string>
flex={'1 0 0'}
size={'md'}
......@@ -799,18 +810,13 @@ const InputTypeConfig = ({
</>
)}
{(inputType === FlowNodeInputTypeEnum.select ||
inputType == FlowNodeInputTypeEnum.multipleSelect) && (
{isOptionInput && (
<>
<DndDrag<{ id: string; value: string }>
<DndDrag<{ id: string; label: string; value: string }>
onDragEndCb={(list) => {
const newOrder = list.map((item) => item.id);
const newSelectEnums = newOrder
.map((id) => mergedSelectEnums.find((item) => item.id === id))
.filter(Boolean) as { id: string; value: string }[];
removeEnums();
newSelectEnums.forEach((item) =>
appendEnums({ label: item.value, value: item.value })
list.forEach((item) =>
appendEnums({ label: item.label || item.value, value: item.value || item.label })
);
// 防止最后一个元素被focus
......@@ -820,7 +826,7 @@ const InputTypeConfig = ({
}
}, 0);
}}
dataList={mergedSelectEnums}
dataList={optionDragList}
renderClone={(provided, snapshot, rubric) => {
return (
<Box
......@@ -833,7 +839,7 @@ const InputTypeConfig = ({
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{mergedSelectEnums[rubric.source.index].value}
{optionDragList[rubric.source.index]?.value}
</Box>
);
}}
......@@ -846,7 +852,7 @@ const InputTypeConfig = ({
flexDirection={'column'}
gap={4}
>
{mergedSelectEnums.map((item, i) => (
{optionFields.map((item, i) => (
<Draggable key={i} draggableId={i.toString()} index={i}>
{(provided, snapshot) => (
<Box
......@@ -915,10 +921,10 @@ const InputTypeConfig = ({
variant={'whiteBase'}
leftIcon={<MyIcon name={'common/addLight'} w={'16px'} />}
onClick={() => {
if (isLastEnumEmpty) return;
if (isOptionLimitReached) return;
appendEnums({ label: '', value: '' });
}}
isDisabled={isLastEnumEmpty}
isDisabled={isOptionLimitReached}
fontWeight={'medium'}
fontSize={'12px'}
w={'24'}
......
......@@ -560,6 +560,7 @@ const NodeIntro = React.memo(function NodeIntro({
nodeId: string;
intro?: string;
}) {
const { t } = useTranslation();
const onChangeNode = useContextSelector(WorkflowActionsContext, (v) => v.onChangeNode);
const handleSave = useCallback(
......@@ -585,7 +586,7 @@ const NodeIntro = React.memo(function NodeIntro({
onSave={handleSave}
type={'textarea'}
maxLength={500}
placeholder={'app:node_not_intro'}
placeholder={t('app:node_not_intro')}
fontSize={'sm'}
lineHeight={'short'}
color={'myGray.500'}
......
......@@ -15,6 +15,7 @@ import MyTooltip from '@fastgpt/web/components/common/MyTooltip';
import { Trans, useTranslation } from 'next-i18next';
import { useToast } from '@fastgpt/web/hooks/useToast';
import { getErrText } from '@fastgpt/global/common/error/utils';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
import {
DndContext,
useSensor,
......@@ -153,7 +154,6 @@ const DroppableRootBox = ({
};
const FileTree = ({
width = 250,
filteredTree,
searchQuery,
setSearchQuery,
......@@ -525,7 +525,7 @@ const FileTree = ({
title: t('chat:sandbox_confirm_delete_title'),
customContent: (
<Trans
i18nKey="chat:sandbox_confirm_delete_content"
i18nKey={i18nT('chat:sandbox_confirm_delete_content')}
values={{ name: node.name }}
components={{
name: <Text as="span" fontWeight="600" color="red.600" />
......
......@@ -15,6 +15,7 @@ import dynamic from 'next/dynamic';
import { AppTypeEnum } from '@fastgpt/global/core/app/constants';
import { useSystemStore } from '@/web/common/system/useSystemStore';
import { useTranslation } from 'next-i18next';
import { resolveDashboardAppListTypes } from './utils/appListTypes';
const MoveModal = dynamic(() => import('@/components/common/folder/MoveModal'));
type AppListContextType = {
......@@ -72,35 +73,10 @@ const AppListContextProvider = ({ children }: { children: ReactNode }) => {
loading: isFetchingApps
} = useRequest(
() => {
const formatType = (() => {
// chat page show all apps
if (router.pathname.includes('/chat')) {
return [
AppTypeEnum.folder,
AppTypeEnum.toolFolder,
AppTypeEnum.simple,
AppTypeEnum.workflow,
AppTypeEnum.workflowTool
];
}
// agent page
if (router.pathname.includes('/agent')) {
return !type || type === 'all'
? [AppTypeEnum.folder, AppTypeEnum.simple, AppTypeEnum.workflow, AppTypeEnum.chatAgent]
: [AppTypeEnum.folder, type];
}
// tool page
return !type || type === 'all'
? [
AppTypeEnum.toolFolder,
AppTypeEnum.workflowTool,
AppTypeEnum.mcpToolSet,
AppTypeEnum.httpToolSet
]
: [AppTypeEnum.toolFolder, type];
})();
const formatType = resolveDashboardAppListTypes({
pathname: router.pathname,
type
});
return getMyApps({ parentId, type: formatType, searchKey });
},
......
import { AppTypeEnum } from '@fastgpt/global/core/app/constants';
type ResolveDashboardAppListTypesParams = {
pathname: string;
type?: AppTypeEnum | 'all';
};
const allAgentAppTypes = [
AppTypeEnum.folder,
AppTypeEnum.simple,
AppTypeEnum.workflow,
AppTypeEnum.chatAgent
];
const allToolAppTypes = [
AppTypeEnum.toolFolder,
AppTypeEnum.workflowTool,
AppTypeEnum.mcpToolSet,
AppTypeEnum.httpToolSet,
AppTypeEnum.httpPlugin
];
/**
* 根据 dashboard 当前页面和类型筛选,生成 `/core/app/list` 的类型过滤条件。
*
* `httpPlugin` 是旧版 HTTP 工具类型,工具页的“全部”和新版 HTTP 工具筛选都要带上它,
* 否则历史团队升级后仍存在的旧版 HTTP 工具不会出现在 dashboard/tool 列表里。
*/
export const resolveDashboardAppListTypes = ({
pathname,
type
}: ResolveDashboardAppListTypesParams): AppTypeEnum[] => {
// 聊天页只展示可直接对话/运行的应用和工具。
if (pathname.includes('/chat')) {
return [
AppTypeEnum.folder,
AppTypeEnum.toolFolder,
AppTypeEnum.simple,
AppTypeEnum.workflow,
AppTypeEnum.workflowTool
];
}
// Agent 页保留原有 Agent 类型筛选行为。
if (pathname.includes('/agent')) {
return !type || type === 'all' ? allAgentAppTypes : [AppTypeEnum.folder, type];
}
// 工具页需要兼容旧版工具类型。
if (!type || type === 'all') {
return allToolAppTypes;
}
if (type === AppTypeEnum.httpToolSet) {
return [AppTypeEnum.toolFolder, AppTypeEnum.httpToolSet, AppTypeEnum.httpPlugin];
}
return [AppTypeEnum.toolFolder, type];
};
......@@ -48,6 +48,7 @@ import ListCreateCard from '@/pageComponents/dashboard/ListCreateCard';
import { useVirtualGridList } from '@fastgpt/web/hooks/useVirtualGridList';
import { getWebReqUrl } from '@fastgpt/web/common/system/utils';
import MyTooltip from '@fastgpt/web/components/common/MyTooltip';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
const EditResourceModal = dynamic(() => import('@/components/common/Modal/EditResourceModal'));
const MoveModal = dynamic(() => import('@/components/common/folder/MoveModal'));
......@@ -367,7 +368,7 @@ const List = ({
openConfirmDelete({
customContent: (
<Trans
i18nKey={'skill:confirm_delete_with_refs'}
i18nKey={i18nT('skill:confirm_delete_with_refs')}
values={{ count: isFolder ? 0 : relatedAppsCount }}
components={{ bold: <Box as={'span'} fontWeight={'600'} /> }}
/>
......
......@@ -31,6 +31,7 @@ import dynamic from 'next/dynamic';
import type { EditResourceInfoFormType } from '@/components/common/Modal/EditResourceModal';
import { useConfirm } from '@fastgpt/web/hooks/useConfirm';
import MyTooltip from '@fastgpt/web/components/common/MyTooltip';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
const EditResourceModal = dynamic(() => import('@/components/common/Modal/EditResourceModal'));
const ConfigPerModal = dynamic(() => import('@/components/support/permission/ConfigPerModal'));
......@@ -225,7 +226,7 @@ export const LeftHeader = () => {
openConfirmDelete({
customContent: (
<Trans
i18nKey={'skill:confirm_delete_with_refs'}
i18nKey={i18nT('skill:confirm_delete_with_refs')}
values={{ count: skillDetail?.appCount ?? 0 }}
components={{ bold: <Box as={'span'} fontWeight={'600'} /> }}
/>
......
......@@ -11,6 +11,7 @@ import { DatasetPageContext } from '@/web/core/dataset/context/datasetPageContex
import { useContextSelector } from 'use-context-selector';
import { getDocPath } from '@/web/common/system/doc';
import { Trans } from 'next-i18next';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
const TemplateImportModal = ({
onFinish,
......@@ -104,7 +105,7 @@ const TemplateImportModal = ({
FileTypeNode={
<Box fontSize={'xs'}>
<Trans
i18nKey="file:template_csv_file_select_tip"
i18nKey={i18nT('file:template_csv_file_select_tip')}
values={{
fileType: '.csv'
}}
......
......@@ -3,6 +3,7 @@ import { useSystemStore } from '@/web/common/system/useSystemStore';
import { Box, Link } from '@chakra-ui/react';
import React, { useEffect, useRef, useState } from 'react';
import { Trans, useTranslation } from 'next-i18next';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
const PolicyTip = () => {
const { feConfigs } = useSystemStore();
......@@ -50,7 +51,7 @@ const PolicyTip = () => {
whiteSpace={'pre-wrap'}
>
<Trans
i18nKey="login:policy_tip"
i18nKey={i18nT('login:policy_tip')}
components={{
lineBreak: isMultiline ? <br /> : <span />,
termsLink: (
......@@ -79,7 +80,7 @@ const PolicyTip = () => {
aria-hidden
>
<Trans
i18nKey="login:policy_tip"
i18nKey={i18nT('login:policy_tip')}
components={{
lineBreak: <span />,
termsLink: <Link />,
......
......@@ -46,6 +46,7 @@ import MyDivider from '@fastgpt/web/components/common/MyDivider';
import { useUploadAvatar } from '@fastgpt/web/common/file/hooks/useUploadAvatar';
import { getUploadAvatarPresignedUrl } from '@/web/common/file/api';
import { TeamErrEnum } from '@fastgpt/global/common/error/code/team';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
const RedeemCouponModal = dynamic(() => import('@/pageComponents/account/info/RedeemCouponModal'), {
ssr: false
......@@ -384,7 +385,7 @@ const PlanUsage = () => {
const planName = useMemo(() => {
if (!teamPlanStatus?.standard?.currentSubLevel) return '';
if (isWecomTeam && teamPlanStatus.standard.currentSubLevel === StandardSubLevelEnum.free)
return 'common:support.wallet.subscription.standardSubLevel.trial';
return i18nT('common:support.wallet.subscription.standardSubLevel.trial');
return (
subPlans?.standard?.[teamPlanStatus.standard.currentSubLevel]?.name ||
......
......@@ -108,6 +108,7 @@ async function handleInitialLoad({
}): Promise<GetCollectionQuoteResType> {
const centerNode = await MongoDatasetData.findOne(
{
...baseMatch,
_id: new Types.ObjectId(initialId)
},
quoteDataFieldSelector
......
......@@ -5,7 +5,7 @@ import { Box, Button, Flex, Input, VStack } from '@chakra-ui/react';
import { useRouter } from 'next/router';
import { serviceSideProps } from '@/web/common/i18n/utils';
import AIModelSelector from '@/components/Select/AIModelSelector';
import { useForm } from 'react-hook-form';
import { useForm, useWatch } from 'react-hook-form';
import { useSystemStore } from '@/web/common/system/useSystemStore';
import FormLabel from '@fastgpt/web/components/common/MyBox/FormLabel';
import AppSelect from '@/components/Select/AppSelect';
......@@ -19,12 +19,13 @@ import { useToast } from '@fastgpt/web/hooks/useToast';
import QuestionTip from '@fastgpt/web/components/common/MyTooltip/QuestionTip';
import { fileDownload } from '@/web/common/file/utils';
import { postCreateEvaluation } from '@/web/core/app/api/evaluation';
import { useMemo, useState } from 'react';
import { useState } from 'react';
import Markdown from '@/components/Markdown';
import { getEvaluationFileHeader } from '@fastgpt/global/core/app/evaluation/utils';
import { evaluationFileErrors } from '@fastgpt/global/core/app/evaluation/constants';
import { TeamErrEnum } from '@fastgpt/global/common/error/code/team';
import { getErrText } from '@fastgpt/global/common/error/utils';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
type EvaluationFormType = {
name: string;
......@@ -43,7 +44,7 @@ const EvaluationCreating = () => {
const { llmModelList } = useSystemStore();
const { register, setValue, watch, handleSubmit } = useForm<EvaluationFormType>({
const { register, setValue, control, handleSubmit } = useForm<EvaluationFormType>({
defaultValues: {
name: '',
evalModel: llmModelList[0]?.model,
......@@ -52,10 +53,10 @@ const EvaluationCreating = () => {
}
});
const name = watch('name');
const evalModel = watch('evalModel');
const appId = watch('appId');
const evaluationFiles = watch('evaluationFiles');
const name = useWatch({ control, name: 'name' });
const evalModel = useWatch({ control, name: 'evalModel' });
const appId = useWatch({ control, name: 'appId' });
const evaluationFiles = useWatch({ control, name: 'evaluationFiles' });
const { runAsync: getAppDetail, loading: isLoadingAppDetail } = useRequest(() => {
if (appId) return getAppDetailById(appId);
......@@ -254,7 +255,7 @@ const EvaluationCreating = () => {
FileTypeNode={
<Box fontSize={'xs'}>
<Trans
i18nKey="dashboard_evaluation:template_csv_file_select_tip"
i18nKey={i18nT('dashboard_evaluation:template_csv_file_select_tip')}
values={{
fileType: '.csv'
}}
......
......@@ -352,7 +352,7 @@ export const getEmptyAppsTemplate = (t: any) => {
{
id: 'userChatInput',
key: 'userChatInput',
label: 'common:core.module.input.label.user question',
label: i18nT('common:core.module.input.label.user question'),
type: FlowNodeOutputTypeEnum.static,
valueType: WorkflowIOValueTypeEnum.string
}
......@@ -656,7 +656,7 @@ export const parsePluginFromCurlString = (
label: '',
description:
'自定义请求头,请严格填入 JSON 字符串。\n1. 确保最后一个属性没有逗号\n2. 确保 key 包含双引号\n例如:{"Authorization":"Bearer xxx"}',
placeholder: 'common:core.module.input.description.Http Request Header',
placeholder: i18nT('common:core.module.input.description.Http Request Header'),
required: false,
valueDesc: '',
debugLabel: '',
......
......@@ -3,7 +3,6 @@ import type { FlowNodeTemplateType } from '@fastgpt/global/core/workflow/type/no
import type { Edge, Node, XYPosition } from 'reactflow';
import { moduleTemplatesFlat } from '@fastgpt/global/core/workflow/template/constants';
import {
AppNodeFlowNodeTypeMap,
EDGE_TYPE,
FlowNodeInputTypeEnum,
FlowNodeOutputTypeEnum,
......@@ -11,6 +10,7 @@ import {
} from '@fastgpt/global/core/workflow/node/constant';
import { EmptyNode } from '@fastgpt/global/core/workflow/template/system/emptyNode';
import { type StoreEdgeItemType } from '@fastgpt/global/core/workflow/type/edge';
import { i18nT } from '@fastgpt/global/common/i18n/utils';
import { getNanoid } from '@fastgpt/global/common/string/tools';
import { getGlobalVariableNode } from './adapt';
import { VARIABLE_NODE_ID, WorkflowIOValueTypeEnum } from '@fastgpt/global/core/workflow/constants';
......@@ -61,7 +61,7 @@ export const adaptStoreNodeInputs = (storeNode: StoreNodeItemType): FlowNodeInpu
return {
...input,
key: NodeInputKeyEnum.datasetSearchInput,
label: 'workflow:search_query',
label: i18nT('workflow:search_query'),
value: isReferenceValue ? [input.value] : input.value,
valueType: WorkflowIOValueTypeEnum.arrayString,
selectedTypeIndex: isReferenceValue ? 0 : 1
......@@ -879,8 +879,6 @@ export const checkWorkflowNodeAndConnection = ({
continue;
}
const hasIncoming = (incoming.get(nodeId) || []).length > 0;
const hasOutgoing = (outgoing.get(nodeId) || []).length > 0;
const isStartNode = [
FlowNodeTypeEnum.workflowStart,
FlowNodeTypeEnum.pluginInput,
......
import type { ApiRequestProps } from '@fastgpt/service/type/next';
import { Types } from 'mongoose';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
authChatCrud: vi.fn(),
authCollectionInChat: vi.fn(),
getCollectionWithDataset: vi.fn(),
findChatItem: vi.fn(),
findDatasetDataByInitialId: vi.fn(),
findDatasetDataList: vi.fn()
}));
vi.mock('@/service/middleware/entry', () => ({
NextAPI: (handler: unknown) => handler
}));
vi.mock('@/service/support/permission/auth/chat', () => ({
authChatCrud: mocks.authChatCrud,
authCollectionInChat: mocks.authCollectionInChat
}));
vi.mock('@fastgpt/service/core/dataset/controller', () => ({
getCollectionWithDataset: mocks.getCollectionWithDataset
}));
vi.mock('@fastgpt/service/core/chat/chatItemSchema', () => ({
MongoChatItem: {
findOne: mocks.findChatItem
}
}));
vi.mock('@fastgpt/service/core/dataset/data/schema', () => ({
MongoDatasetData: {
findOne: mocks.findDatasetDataByInitialId,
find: mocks.findDatasetDataList
}
}));
import handler from '@/pages/api/core/chat/record/getCollectionQuote';
const appId = '68ad85a7463006c963799a05';
const chatId = 'chat_quote_auth_regression';
const chatItemDataId = 'quote_ai_response';
const collectionId = '68ad85a7463006c963799a06';
const teamId = '68ad85a7463006c963799a07';
const datasetId = '68ad85a7463006c963799a08';
const initialId = '68ad85a7463006c963799a09';
const chatTime = new Date('2026-06-06T10:14:40.000Z');
const callHandler = () =>
handler({
body: {
appId,
chatId,
chatItemDataId,
collectionId,
initialId,
anchor: 0,
pageSize: 5
}
} as ApiRequestProps);
const createDatasetData = ({
id,
q,
dataTeamId = teamId,
dataDatasetId = datasetId,
dataCollectionId = collectionId,
chunkIndex = 0
}: {
id: string;
q: string;
dataTeamId?: string;
dataDatasetId?: string;
dataCollectionId?: string;
chunkIndex?: number;
}) => ({
_id: new Types.ObjectId(id),
teamId: dataTeamId,
datasetId: dataDatasetId,
collectionId: dataCollectionId,
q,
a: '',
history: [],
updateTime: new Date('2026-06-06T10:00:00.000Z'),
chunkIndex
});
const mockFindDatasetDataList = (list: unknown[]) => {
const query = {
sort: vi.fn().mockReturnThis(),
limit: vi.fn().mockReturnThis(),
lean: vi.fn().mockResolvedValue(list)
};
mocks.findDatasetDataList.mockReturnValue(query);
return query;
};
describe('getCollectionQuote handler', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.authChatCrud.mockResolvedValue({ chat: { _id: chatId }, showFullText: true });
mocks.authCollectionInChat.mockResolvedValue(undefined);
mocks.getCollectionWithDataset.mockResolvedValue({
_id: collectionId,
teamId,
datasetId
});
mocks.findChatItem.mockReturnValue({
lean: () => Promise.resolve({ time: chatTime })
});
mocks.findDatasetDataByInitialId.mockReturnValue({
lean: () => Promise.resolve(null)
});
mockFindDatasetDataList([]);
});
it('binds initialId center-node lookup to the authorized team, dataset and collection', async () => {
mocks.findDatasetDataByInitialId.mockReturnValue({
lean: () =>
Promise.resolve(
createDatasetData({
id: initialId,
q: 'authorized quote text'
})
)
});
await expect(callHandler()).resolves.toMatchObject({
list: [expect.objectContaining({ q: 'authorized quote text' })],
hasMorePrev: false,
hasMoreNext: false
});
expect(mocks.authCollectionInChat).toHaveBeenCalledWith({
appId,
chatId,
collectionIds: [collectionId]
});
expect(mocks.findDatasetDataByInitialId).toHaveBeenCalledWith(
expect.objectContaining({
teamId,
datasetId,
collectionId,
_id: new Types.ObjectId(initialId)
}),
expect.any(String)
);
});
it('does not return a foreign initialId when it is outside the authorized baseMatch', async () => {
const authorizedFallback = createDatasetData({
id: '68ad85a7463006c963799a10',
q: 'tenant B authorized quote'
});
mockFindDatasetDataList([authorizedFallback]);
const result = await callHandler();
expect(result.list.map((item) => item.q)).toEqual(['tenant B authorized quote']);
expect(result.list.map((item) => item.q)).not.toContain('tenant A secret quote');
expect(mocks.findDatasetDataByInitialId).toHaveBeenCalledWith(
expect.objectContaining({
teamId,
datasetId,
collectionId,
_id: new Types.ObjectId(initialId)
}),
expect.any(String)
);
expect(mocks.findDatasetDataList).toHaveBeenCalledWith(
expect.objectContaining({
teamId,
datasetId,
collectionId
}),
expect.any(String)
);
});
});
import { describe, expect, it } from 'vitest';
import { AppTypeEnum } from '@fastgpt/global/core/app/constants';
import { resolveDashboardAppListTypes } from '@/pageComponents/dashboard/agent/utils/appListTypes';
describe('resolveDashboardAppListTypes', () => {
it('should include legacy HTTP plugin apps in the dashboard tool all list', () => {
expect(
resolveDashboardAppListTypes({
pathname: '/dashboard/tool',
type: 'all'
})
).toEqual([
AppTypeEnum.toolFolder,
AppTypeEnum.workflowTool,
AppTypeEnum.mcpToolSet,
AppTypeEnum.httpToolSet,
AppTypeEnum.httpPlugin
]);
});
it('should include legacy HTTP plugin apps when filtering dashboard tools by HTTP toolset', () => {
expect(
resolveDashboardAppListTypes({
pathname: '/dashboard/tool',
type: AppTypeEnum.httpToolSet
})
).toEqual([AppTypeEnum.toolFolder, AppTypeEnum.httpToolSet, AppTypeEnum.httpPlugin]);
});
it('should keep agent page type filters unchanged', () => {
expect(
resolveDashboardAppListTypes({
pathname: '/dashboard/agent',
type: AppTypeEnum.workflow
})
).toEqual([AppTypeEnum.folder, AppTypeEnum.workflow]);
});
});
# --------- Build Stage -----------
FROM node:24-alpine AS builder
FROM golang:1.22-bookworm AS go-runtime
FROM node:24-bookworm-slim AS builder
WORKDIR /app
ARG proxy
COPY --from=go-runtime /usr/local/go /usr/local/go
ENV PATH="/usr/local/go/bin:${PATH}"
# 安装 pnpm
RUN npm install -g pnpm@10.33.2
......@@ -14,8 +19,11 @@ COPY packages/service ./packages/service
COPY sdk ./sdk
COPY projects/code-sandbox/ ./projects/code-sandbox/
RUN [ -z "$proxy" ] || sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
RUN apk add --no-cache curl ca-certificates && update-ca-certificates
RUN [ -z "$proxy" ] || sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list.d/debian.sources
RUN apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 update && \
apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 install -y --no-install-recommends \
curl ca-certificates libseccomp-dev pkg-config gcc libc6-dev && \
rm -rf /var/lib/apt/lists/*
# 安装所有依赖(包括 devDependencies 用于编译)
RUN if [ -z "$proxy" ]; then \
......@@ -27,16 +35,16 @@ RUN if [ -z "$proxy" ]; then \
# 先构建 SDK workspace 包,确保 dist 入口可被打包工具解析
RUN pnpm --filter @fastgpt-sdk/otel --filter @fastgpt-sdk/storage build
# 编译主入口文件
RUN cd /app/projects/code-sandbox && pnpm build
# 编译主入口文件和 Python native 隔离库
RUN cd /app/projects/code-sandbox && SANDBOX_BUILD_NATIVE_PYTHON=true pnpm build
# ===== Runner Stage =====
FROM node:24-alpine AS runner
FROM node:24-bookworm-slim AS runner
WORKDIR /app/code-sandbox
ARG proxy
RUN [ -z "$proxy" ] || sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
RUN [ -z "$proxy" ] || sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list.d/debian.sources
# 安装 pnpm(用于 runner 阶段安装 prod 依赖)
RUN npm install -g pnpm@10.33.2
......@@ -58,18 +66,60 @@ RUN if [ -z "$proxy" ]; then \
pnpm store prune || true
# 安装 Python、依赖包及工具
RUN apk add --no-cache python3 py3-pip libffi util-linux && \
apk add --no-cache --virtual .build-deps gcc g++ musl-dev python3-dev libffi-dev
RUN apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 update && \
apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 install -y --no-install-recommends \
python3 python3-pip libffi8 util-linux libseccomp2 \
gcc g++ python3-dev libffi-dev patch git && \
rm -rf /var/lib/apt/lists/*
COPY projects/code-sandbox/requirements.txt /tmp/requirements.txt
RUN pip3 install --no-cache-dir --break-system-packages -r /tmp/requirements.txt && \
rm /tmp/requirements.txt && \
apk del .build-deps
# 创建非 root 用户运行沙箱
RUN addgroup -S sandbox && adduser -S sandbox -G sandbox && \
chown -R sandbox:sandbox /app
USER sandbox
rm /tmp/requirements.txt
RUN set -eux; \
root=/tmp/fastgpt-python-sandbox; \
mkdir -p \
"$root/app/code-sandbox" \
"$root/bin" \
"$root/usr/bin" \
"$root/usr/lib" \
"$root/usr/local/lib" \
"$root/lib" \
"$root/lib64" \
"$root/etc" \
"$root/dev" \
"$root/tmp"; \
chmod 755 "$root/tmp"; \
cp -a /app/code-sandbox/. "$root/app/code-sandbox/"; \
cp -a /usr/bin/python3 /usr/bin/python3.* "$root/usr/bin/" 2>/dev/null || true; \
cp -a /usr/lib/python3* "$root/usr/lib/"; \
cp -a /usr/local/lib/python3* "$root/usr/local/lib/" 2>/dev/null || true; \
cp -a /usr/lib/aarch64-linux-gnu "$root/usr/lib/" 2>/dev/null || true; \
cp -a /lib/aarch64-linux-gnu "$root/lib/" 2>/dev/null || true; \
cp -a /lib/ld-linux-aarch64.so.1 "$root/lib/" 2>/dev/null || true; \
cp -a /usr/lib/x86_64-linux-gnu "$root/usr/lib/" 2>/dev/null || true; \
cp -a /lib/x86_64-linux-gnu "$root/lib/" 2>/dev/null || true; \
cp -a /lib64/ld-linux-x86-64.so.2 "$root/lib64/" 2>/dev/null || true; \
cp -a /etc/ssl "$root/etc/" 2>/dev/null || true; \
cp -a /etc/ca-certificates "$root/etc/" 2>/dev/null || true; \
cp -a /etc/resolv.conf /etc/hosts /etc/nsswitch.conf "$root/etc/" 2>/dev/null || true; \
mkdir -p "$root/dev"; \
mknod -m 666 "$root/dev/null" c 1 3 || true; \
mknod -m 666 "$root/dev/zero" c 1 5 || true; \
mknod -m 666 "$root/dev/random" c 1 8 || true; \
mknod -m 666 "$root/dev/urandom" c 1 9 || true; \
chmod -R a+rX "$root"; \
chmod 755 "$root/tmp"
# 创建沙箱用户。code-sandbox 主进程默认保留 root,以便 Python 子进程
# 在 native 隔离初始化阶段执行 chroot/setuid;用户代码会降权到 sandbox。
RUN groupadd -g 65537 sandbox && useradd -u 65537 -g 65537 -M -r -s /usr/sbin/nologin sandbox && \
mkdir -p /tmp/fastgpt-python-sandbox && \
chown -R sandbox:sandbox /app && \
chown root:root /tmp/fastgpt-python-sandbox && \
chmod 755 /tmp/fastgpt-python-sandbox && \
chown root:root /tmp/fastgpt-python-sandbox/tmp && \
chmod 755 /tmp/fastgpt-python-sandbox/tmp
ENV NODE_ENV=production
ENV SANDBOX_PORT=3000
......
# FastGPT Code Sandbox
基于 Node + Hono 的代码执行沙盒,支持 JS 和 Python。采用进程池架构,预热长驻 worker 进程,通过 stdin/stdout JSON 协议通信,消除每次请求的进程启动开销。
基于 Node + Hono 的代码执行沙盒,支持 JS 和 Python。JS 采用长驻 worker 进程池;Python 采用 one-shot 预热进程池,Linux/Docker 环境固定启用 chroot、seccomp、setuid/setgid 隔离。
## 架构
```
HTTP Request → Hono Server → Process Pool → Worker (long-lived) → Result
↓
┌──────────────┐
│ JS Workers │ node worker.js (×N)
│ Py Workers │ python3 worker.py (×N)
└──────────────┘
stdin: JSON task → stdout: JSON result
HTTP Request → Hono Server
├─ JS Process Pool → node worker.js (long-lived) → Result
└─ Python One-shot Warm Pool → clean python3 bootstrap → one task → exit
```
- **进程池**:启动时预热 N 个 worker 进程(默认 20),请求到达时直接分配空闲 worker,执行完归还池中
- **JS 进程池**:启动时预热 N 个 worker 进程(默认 20),请求到达时直接分配空闲 worker,执行完归还池中
- **JS 执行**:Node worker 进程 + 安全 shim(冻结 Function 构造器、危险全局对象遮蔽、require 白名单)
- **Python 执行**:python3 worker 进程 + `__import__` 拦截 + resource 资源限制
- **Python 执行**:预热 `SANDBOX_POOL_SIZE` 个干净 python3 进程,进程进入 native seccomp/chroot/降权后等待一条任务;执行用户代码后立即销毁并异步补充新的干净进程
- **网络请求**:统一通过 `SystemHelper.httpRequest()` / `system_helper.http_request()` 收口,内置 SSRF 防护
- **并发控制**:请求数超过池大小时自动排队,worker 崩溃自动重启补充
- **并发控制**:JS 请求超过池大小时自动排队;Python 同时运行的独立子进程数复用 `SANDBOX_POOL_SIZE`
## 性能
进程池 vs 旧版 spawn-per-request 对比(SANDBOX_POOL_SIZE=20):
JS 仍保留进程池收益。Python 为了多租户安全改为 one-shot 预热池:空闲进程只在执行用户代码前复用,执行用户代码后立即销毁。它能降低 Python 冷启动成本,但吞吐仍会低于旧长驻 worker。
| 场景 | 旧版 QPS / P50 | 进程池 QPS / P50 | 提升 |
|------|----------------|------------------|------|
......@@ -30,12 +26,7 @@ HTTP Request → Hono Server → Process Pool → Worker (long-lived) → Result
| JS IO 500ms (c50) | 22 / 2,107ms | 38 / 1,005ms | 1.7x |
| JS 高 CPU (c10) | 9 / 1,079ms | 12 / 796ms | 1.3x |
| JS 高内存 (c10) | — | 13 / 787ms | — |
| Python 简单函数 (c50) | 14.7 / 2,897ms | 4,247 / 4ms | **289x** |
| Python IO 500ms (c50) | 14.2 / 3,066ms | 38 / 1,003ms | 2.7x |
| Python 高 CPU (c10) | 3.1 / 2,845ms | 4 / 2,191ms | 1.3x |
| Python 高内存 (c10) | — | 11 / 893ms | — |
资源占用(20+20 workers):空闲 ~1.5GB RSS,压测峰值 ~2GB RSS。
资源占用由 `SANDBOX_POOL_SIZE`、Python 预热空闲进程、Python 包加载情况和 `SANDBOX_MAX_MEMORY_MB` 共同决定。
## 快速开始
......@@ -96,14 +87,23 @@ docker run -p 3000:3000 \
### `GET /health`
健康检查,返回进程池状态。
健康检查,返回 JS 进程池和 Python isolated runner 状态。
```json
{
"status": "ok",
"version": "5.0.0",
"jsPool": { "total": 20, "idle": 18, "busy": 2, "queued": 0 },
"pythonPool": { "total": 20, "idle": 20, "busy": 0, "queued": 0 }
"pools": {
"js": { "total": 20, "idle": 18, "busy": 2, "queued": 0, "poolSize": 20 },
"python": {
"total": 20,
"idle": 18,
"busy": 2,
"warming": 0,
"queued": 0,
"poolSize": 20,
"ready": true
}
}
}
```
......@@ -139,13 +139,17 @@ docker run -p 3000:3000 \
| `SANDBOX_PORT` | 服务端口 | `3000` |
| `SANDBOX_TOKEN` | Bearer Token 认证密钥 | 空(不鉴权) |
### 进程池
### 并发控制
| 变量 | 说明 | 默认值 |
|------|------|--------|
| `SANDBOX_POOL_SIZE` | 每种语言的 worker 进程数 | `20` |
| `SANDBOX_POOL_SIZE` | JS worker 进程数;也是 Python 同时运行和空闲预热的进程数 | `20` |
| `SANDBOX_QUEUE_ID_CONCURRENCY` | 同一 `queueId` 同时可进入执行流程的请求数,空值表示不按 `queueId` 排队 | 空 |
### Python 隔离
Python 隔离不再提供运行时关闭开关。Linux 环境固定启用 native seccomp/chroot/降权,chroot 根目录固定为 `/tmp/fastgpt-python-sandbox`,用户代码进程固定降权到 `65537:65537`。Python 子进程不允许直接网络 syscall,外部请求必须通过父进程代理的 `http_request` 能力,并受请求次数、超时、请求体和响应体大小限制。
### 资源限制
| 变量 | 说明 | 默认值 |
......@@ -153,6 +157,7 @@ docker run -p 3000:3000 \
| `SANDBOX_API_MAX_BODY_MB` | API JSON 请求体总大小上限(包含 variables) | `8` |
| `SANDBOX_MAX_TIMEOUT` | 超时上限(ms),请求不可超过此值 | `60000` |
| `SANDBOX_MAX_MEMORY_MB` | 内存上限(MB) | `256` |
| `SANDBOX_MAX_TMP_MB` | Python 单任务临时目录写入上限(MB) | `16` |
| `SANDBOX_MAX_OUTPUT_MB` | 单次执行输出 JSON 大小上限(包含返回值和日志) | `10` |
### 网络请求限制
......@@ -174,9 +179,10 @@ src/
├── types.ts # 类型定义
├── pool/
│ ├── process-pool.ts # JS 进程池管理
│ ├── python-process-pool.ts # Python 进程池管理
│ ├── worker.ts # JS worker(长驻进程,含安全 shim)
│ └── worker.py # Python worker(长驻进程,含安全沙箱)
│ └── worker.ts # JS worker(长驻进程,含安全 shim)
├── isolated/
│ ├── python-isolated-runner.ts # Python 独立进程执行器
│ └── python-bootstrap.py # Python 单次执行 bootstrap
└── utils/
└── semaphore.ts # 信号量(通用并发控制)
......
......@@ -6,6 +6,11 @@ echo "Building sandbox..."
# 清理旧的构建产物
rm -rf dist
if [ "${SANDBOX_BUILD_NATIVE_PYTHON:-}" = "true" ]; then
echo "Building native Python sandbox library..."
pnpm run build:native:python
fi
# 编译入口(配置见 tsdown.config.ts):
# - 同时打包 index 和 worker 两个独立 bundle
# - 所有 npm 依赖均打入 bundle(noExternal),仅保留 Node 内置模块外部化
......@@ -16,16 +21,24 @@ pnpm exec tsdown
# package.json 已声明 type:module,直接改后缀为 .js
mv dist/index.mjs dist/index.js
mv dist/worker.mjs dist/worker.js
mv dist/python-isolated-runner.mjs dist/python-isolated-runner.js
# Python worker 不需要编译,直接复制
echo "Copying Python worker..."
cp src/pool/worker.py dist/worker.py
# Python bootstrap 不需要编译,直接复制
echo "Copying Python runtime files..."
cp src/isolated/python-bootstrap.py dist/python-bootstrap.py
if [ -f src/isolated/fastgpt_python_sandbox.so ]; then
cp src/isolated/fastgpt_python_sandbox.so dist/fastgpt_python_sandbox.so
fi
echo ""
echo "Build complete!"
echo " - index.js: $(du -h dist/index.js | cut -f1)"
echo " - worker.js: $(du -h dist/worker.js | cut -f1)"
echo " - worker.py: $(du -h dist/worker.py | cut -f1)"
echo " - python-isolated-runner.js: $(du -h dist/python-isolated-runner.js | cut -f1)"
echo " - python-bootstrap.py: $(du -h dist/python-bootstrap.py | cut -f1)"
if [ -f dist/fastgpt_python_sandbox.so ]; then
echo " - fastgpt_python_sandbox.so: $(du -h dist/fastgpt_python_sandbox.so | cut -f1)"
fi
echo ""
echo "ℹ️ worker 通过 safeRequire(name) 在运行时动态加载白名单模块"
echo " (lodash/dayjs/moment/uuid/crypto-js/qs),这些依赖必须以 node_modules"
......
package main
// FastGPT Python native sandbox.
//
// This package is project-local FastGPT glue code, not copied from Dify or any
// other sandbox project. It exposes a tiny C ABI for python-bootstrap.py and
// relies on the open-source github.com/seccomp/libseccomp-golang and
// golang.org/x/sys packages for Linux seccomp/prctl/syscall bindings.
/*
#include <stdlib.h>
*/
import "C"
import (
"sync"
"unsafe"
"fastgpt-python-sandbox/internal/sandbox"
)
var (
lastErrMu sync.Mutex
lastErr string
)
func setLastErr(err error) {
lastErrMu.Lock()
defer lastErrMu.Unlock()
if err == nil {
lastErr = ""
return
}
lastErr = err.Error()
}
//export FastGPTInitPythonSandbox
func FastGPTInitPythonSandbox(uid C.int, gid C.int, enableNetwork C.int) C.int {
err := sandbox.Init(int(uid), int(gid), enableNetwork != 0)
setLastErr(err)
if err != nil {
return 1
}
return 0
}
//export FastGPTLastError
func FastGPTLastError() *C.char {
lastErrMu.Lock()
defer lastErrMu.Unlock()
return C.CString(lastErr)
}
//export FastGPTFreeCString
func FastGPTFreeCString(value *C.char) {
C.free(unsafe.Pointer(value))
}
func main() {}
module fastgpt-python-sandbox
go 1.22
require (
github.com/seccomp/libseccomp-golang v0.11.0
golang.org/x/sys v0.29.0
)
github.com/seccomp/libseccomp-golang v0.11.0 h1:SDkcBRqGLP+sezmMACkxO1EfgbghxIxnRKfd6mHUEis=
github.com/seccomp/libseccomp-golang v0.11.0/go.mod h1:5m1Lk8E9OwgZTTVz4bBOer7JuazaBa+xTkM895tDiWc=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
//go:build linux
package sandbox
import (
"fmt"
"syscall"
)
// Init installs the OS-level restrictions for the current Python process.
//
// The caller must load this shared library, open all required task fds, and set
// cwd to the prepared sandbox root before calling Init. After chroot/seccomp and
// uid/gid drop, the process cannot recover its previous privileges.
func Init(uid, gid int, enableNetwork bool) error {
if uid <= 0 || gid <= 0 {
return fmt.Errorf("uid/gid must be positive")
}
if err := syscall.Chroot("."); err != nil {
return fmt.Errorf("chroot: %w", err)
}
if err := syscall.Chdir("/"); err != nil {
return fmt.Errorf("chdir: %w", err)
}
if err := setNoNewPrivs(); err != nil {
return err
}
if err := loadSeccomp(enableNetwork); err != nil {
return err
}
if err := syscall.Setgroups([]int{}); err != nil {
return fmt.Errorf("setgroups: %w", err)
}
if err := syscall.Setgid(gid); err != nil {
return fmt.Errorf("setgid: %w", err)
}
if err := syscall.Setuid(uid); err != nil {
return fmt.Errorf("setuid: %w", err)
}
return nil
}
//go:build !linux
package sandbox
import "fmt"
func Init(uid, gid int, enableNetwork bool) error {
return fmt.Errorf("fastgpt python sandbox native isolation only supports linux")
}
//go:build linux
package sandbox
import (
"fmt"
"golang.org/x/sys/unix"
)
func setNoNewPrivs() error {
if err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil {
return fmt.Errorf("prctl(PR_SET_NO_NEW_PRIVS): %w", err)
}
return nil
}
//go:build linux
package sandbox
import (
"fmt"
"syscall"
seccomp "github.com/seccomp/libseccomp-golang"
)
func loadSeccomp(enableNetwork bool) error {
filter, err := seccomp.NewFilter(seccomp.ActErrno.SetReturnCode(int16(syscall.EPERM)))
if err != nil {
return fmt.Errorf("create seccomp filter: %w", err)
}
for _, syscallID := range allowBaseSyscalls {
if err := filter.AddRule(seccomp.ScmpSyscall(syscallID), seccomp.ActAllow); err != nil {
return fmt.Errorf("allow syscall %d: %w", syscallID, err)
}
}
if enableNetwork {
for _, syscallID := range allowNetworkSyscalls {
if err := filter.AddRule(seccomp.ScmpSyscall(syscallID), seccomp.ActAllow); err != nil {
return fmt.Errorf("allow network syscall %d: %w", syscallID, err)
}
}
}
if err := filter.Load(); err != nil {
return fmt.Errorf("load seccomp filter: %w", err)
}
return nil
}
//go:build linux && amd64
package sandbox
import "syscall"
const (
sysGetrandom = 318
sysRseq = 334
sysClone3 = 435
sysSendmmsg = 307
)
var allowBaseSyscalls = []int{
syscall.SYS_READ, syscall.SYS_WRITE, syscall.SYS_CLOSE,
syscall.SYS_NEWFSTATAT, syscall.SYS_FSTAT, syscall.SYS_FCNTL, syscall.SYS_IOCTL,
syscall.SYS_OPENAT, syscall.SYS_FACCESSAT, syscall.SYS_PREAD64, syscall.SYS_LSEEK, syscall.SYS_GETDENTS64,
// Python tempfile/matplotlib 需要在每个 task 临时目录内建目录;路径边界由 Python guard 和 chroot 权限控制。
syscall.SYS_MKDIR, syscall.SYS_MKDIRAT,
syscall.SYS_MMAP, syscall.SYS_MPROTECT, syscall.SYS_MUNMAP, syscall.SYS_BRK,
syscall.SYS_MREMAP, syscall.SYS_MADVISE,
syscall.SYS_RT_SIGACTION, syscall.SYS_RT_SIGPROCMASK, syscall.SYS_SIGALTSTACK, syscall.SYS_RT_SIGRETURN,
syscall.SYS_CLOCK_GETTIME, syscall.SYS_GETTIMEOFDAY, syscall.SYS_NANOSLEEP, syscall.SYS_CLOCK_NANOSLEEP,
syscall.SYS_GETPID, syscall.SYS_GETPPID, syscall.SYS_GETTID,
syscall.SYS_GETUID, syscall.SYS_GETEUID, syscall.SYS_GETGID, syscall.SYS_GETEGID, syscall.SYS_GETGROUPS,
syscall.SYS_GETCWD, syscall.SYS_UNAME, syscall.SYS_SETITIMER,
syscall.SYS_SETGROUPS, syscall.SYS_SETGID, syscall.SYS_SETUID,
syscall.SYS_FUTEX, syscall.SYS_SCHED_GETAFFINITY, syscall.SYS_SCHED_YIELD,
syscall.SYS_EXIT, syscall.SYS_EXIT_GROUP, syscall.SYS_TGKILL,
sysGetrandom, syscall.SYS_EVENTFD2,
syscall.SYS_EPOLL_CREATE1, syscall.SYS_EPOLL_CTL, syscall.SYS_PSELECT6,
syscall.SYS_SET_ROBUST_LIST, syscall.SYS_GET_ROBUST_LIST, sysRseq,
}
var errnoSyscalls = []int{
syscall.SYS_CLONE, sysClone3, syscall.SYS_FORK, syscall.SYS_VFORK,
}
var allowNetworkSyscalls = []int{
syscall.SYS_SOCKET, syscall.SYS_CONNECT, syscall.SYS_BIND, syscall.SYS_LISTEN, syscall.SYS_ACCEPT,
syscall.SYS_SENDTO, syscall.SYS_RECVFROM, syscall.SYS_SENDMSG, sysSendmmsg, syscall.SYS_RECVMSG,
syscall.SYS_GETSOCKNAME, syscall.SYS_GETPEERNAME, syscall.SYS_SETSOCKOPT, syscall.SYS_GETSOCKOPT,
syscall.SYS_POLL, syscall.SYS_PPOLL, syscall.SYS_EPOLL_PWAIT,
}
//go:build linux && arm64
package sandbox
import "syscall"
const (
sysRseq = 293
sysClone3 = 435
)
var allowBaseSyscalls = []int{
syscall.SYS_READ, syscall.SYS_WRITE, syscall.SYS_CLOSE,
syscall.SYS_FSTATAT, syscall.SYS_FSTAT, syscall.SYS_FCNTL, syscall.SYS_IOCTL,
syscall.SYS_OPENAT, syscall.SYS_FACCESSAT, syscall.SYS_READLINKAT,
// Python tempfile/matplotlib 需要在每个 task 临时目录内建目录;路径边界由 Python guard 和 chroot 权限控制。
syscall.SYS_MKDIRAT,
syscall.SYS_PREAD64, syscall.SYS_LSEEK, syscall.SYS_GETDENTS64,
syscall.SYS_MMAP, syscall.SYS_MPROTECT, syscall.SYS_MUNMAP, syscall.SYS_BRK,
syscall.SYS_MREMAP, syscall.SYS_MADVISE,
syscall.SYS_RT_SIGACTION, syscall.SYS_RT_SIGPROCMASK, syscall.SYS_SIGALTSTACK, syscall.SYS_RT_SIGRETURN,
syscall.SYS_CLOCK_GETTIME, syscall.SYS_GETTIMEOFDAY, syscall.SYS_NANOSLEEP, syscall.SYS_CLOCK_NANOSLEEP,
syscall.SYS_GETPID, syscall.SYS_GETPPID, syscall.SYS_GETTID,
syscall.SYS_GETUID, syscall.SYS_GETEUID, syscall.SYS_GETGID, syscall.SYS_GETEGID, syscall.SYS_GETGROUPS,
syscall.SYS_GETCWD, syscall.SYS_UNAME, syscall.SYS_SETITIMER,
syscall.SYS_SETGROUPS, syscall.SYS_SETGID, syscall.SYS_SETUID,
syscall.SYS_FUTEX, syscall.SYS_SCHED_GETAFFINITY, syscall.SYS_SCHED_YIELD,
syscall.SYS_EXIT, syscall.SYS_EXIT_GROUP, syscall.SYS_TGKILL,
syscall.SYS_GETRANDOM, syscall.SYS_EVENTFD2,
syscall.SYS_EPOLL_CREATE1, syscall.SYS_EPOLL_CTL, syscall.SYS_PSELECT6,
syscall.SYS_SET_ROBUST_LIST, syscall.SYS_GET_ROBUST_LIST, sysRseq,
}
var errnoSyscalls = []int{
syscall.SYS_CLONE, sysClone3,
}
var allowNetworkSyscalls = []int{
syscall.SYS_SOCKET, syscall.SYS_CONNECT, syscall.SYS_BIND, syscall.SYS_LISTEN, syscall.SYS_ACCEPT,
syscall.SYS_SENDTO, syscall.SYS_RECVFROM, syscall.SYS_SENDMSG, syscall.SYS_SENDMMSG, syscall.SYS_RECVMSG,
syscall.SYS_GETSOCKNAME, syscall.SYS_GETPEERNAME, syscall.SYS_SETSOCKOPT, syscall.SYS_GETSOCKOPT,
syscall.SYS_PPOLL, syscall.SYS_EPOLL_PWAIT,
}
......@@ -9,6 +9,7 @@
"scripts": {
"dev": "tsx watch src/index.ts",
"start": "node dist/index.js",
"build:native:python": "cd native/python-sandbox && go build -buildmode=c-shared -o ../../src/isolated/fastgpt_python_sandbox.so ./cmd/lib",
"build": "sh build.sh",
"test": "vitest run",
"test:watch": "vitest"
......
......@@ -54,6 +54,7 @@ export const env = createEnv({
SANDBOX_API_MAX_BODY_MB: IntSchema.min(1).max(100).default(8),
SANDBOX_MAX_TIMEOUT: IntSchema.min(1000).max(600000).default(60000),
SANDBOX_MAX_MEMORY_MB: IntSchema.min(32).max(4096).default(256),
SANDBOX_MAX_TMP_MB: IntSchema.min(1).max(1024).default(16),
SANDBOX_MAX_OUTPUT_MB: IntSchema.min(1).max(100).default(10),
// ===== 网络请求限制 =====
......@@ -81,7 +82,7 @@ export const env = createEnv({
'json,csv,base64,binascii,struct,' +
'hashlib,hmac,secrets,uuid,' +
'typing,abc,enum,dataclasses,contextlib,' +
'pprint,' +
'pprint,weakref,' +
'numpy,pandas,matplotlib'
)
.transform(parseAllowedModules)
......
......@@ -4,7 +4,7 @@ import { bearerAuth } from 'hono/bearer-auth';
import { serve } from '@hono/node-server';
import { z } from 'zod';
import { ProcessPool } from './pool/process-pool';
import { PythonProcessPool } from './pool/python-process-pool';
import { PythonIsolatedRunner } from './isolated/python-isolated-runner';
import type { ExecuteOptions } from './types';
import { getErrText } from './utils';
import { configureLogger, getLogger, LogCategories } from './utils/logger';
......@@ -91,7 +91,7 @@ const app = new Hono();
/** 进程池 */
const jsPool = new ProcessPool(env.SANDBOX_POOL_SIZE);
const pythonPool = new PythonProcessPool(env.SANDBOX_POOL_SIZE);
const pythonRunner = new PythonIsolatedRunner();
const queueIdLimiter = new QueueIdLimiter(env.SANDBOX_QUEUE_ID_CONCURRENCY);
if (queueIdLimiter.enabled) {
......@@ -100,11 +100,9 @@ if (queueIdLimiter.enabled) {
);
}
const poolReady = Promise.all([jsPool.init(), pythonPool.init()])
const poolReady = Promise.all([jsPool.init(), pythonRunner.init()])
.then(() => {
serverLogger.info(
`Process pools ready: JS=${env.SANDBOX_POOL_SIZE}, Python=${env.SANDBOX_POOL_SIZE} workers`
);
serverLogger.info(`Process pools ready: JS=${env.SANDBOX_POOL_SIZE}, Python=isolated`);
})
.catch((err) => {
serverLogger.error('Failed to init process pool:', err.message);
......@@ -114,9 +112,18 @@ const poolReady = Promise.all([jsPool.init(), pythonPool.init()])
/** 健康检查(不需要认证) */
app.get('/health', (c) => {
const jsStats = jsPool.stats;
const pyStats = pythonPool.stats;
const isReady = jsStats.total > 0 && pyStats.total > 0;
return c.json({ status: isReady ? 'ok' : 'degraded' }, isReady ? 200 : 503);
const pythonStats = pythonRunner.stats;
const isReady = jsStats.total > 0 && pythonStats.ready;
return c.json(
{
status: isReady ? 'ok' : 'degraded',
pools: {
js: jsStats,
python: pythonStats
}
},
isReady ? 200 : 503
);
});
// 增加日志中间件,打印请求信息
......@@ -219,7 +226,7 @@ app.post('/sandbox/python', async (c) => {
);
}
const result = await queueIdLimiter.run(parsed.data.queueId, () =>
pythonPool.execute(parsed.data as ExecuteOptions)
pythonRunner.execute(parsed.data as ExecuteOptions)
);
return c.json(result);
} catch (err: any) {
......
import { existsSync } from 'fs';
import { platform } from 'os';
import { join } from 'path';
export const PYTHON_SANDBOX_ROOT = '/tmp/fastgpt-python-sandbox';
export const PYTHON_SANDBOX_UID = 65537;
export const PYTHON_SANDBOX_GID = 65537;
export const PYTHON_ENABLE_NETWORK_SYSCALLS = false;
export function shouldEnablePythonNativeIsolation(): boolean {
return platform() === 'linux';
}
/**
* Python native 隔离是 Linux 多租户安全边界的一部分。
*
* Linux 环境固定启用 seccomp/chroot/setuid,缺失 native 库或 chroot 根目录时
* 直接 fail-closed;macOS/Windows 仅保留本地开发兼容路径,不声明具备 OS 隔离。
*/
export function assertPythonNativeIsolationReady(libraryPath: string) {
if (!shouldEnablePythonNativeIsolation()) return;
if (!existsSync(libraryPath)) {
throw new Error(`Python native sandbox library does not exist: ${libraryPath}`);
}
if (!existsSync(PYTHON_SANDBOX_ROOT)) {
throw new Error(`Python sandbox root does not exist: ${PYTHON_SANDBOX_ROOT}`);
}
}
export function getBundledPythonNativeLibraryPath(dirname: string) {
return join(dirname, 'fastgpt_python_sandbox.so');
}
/**
* PythonProcessPool - Python 子进程池
*
* 继承 BaseProcessPool,提供 Python worker 的 spawn 配置。
*/
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { env } from '../env';
import { BaseProcessPool } from './base-process-pool';
const __dirname = dirname(fileURLToPath(import.meta.url));
const WORKER_SCRIPT = join(__dirname, 'worker.py');
const RECYCLE_AFTER_TASK_MODULES = new Set([
'subprocess',
'multiprocessing',
'threading',
'concurrent'
]);
function shouldRecycleAfterTask(allowedModules: readonly string[]): boolean {
return allowedModules.some((moduleName) => RECYCLE_AFTER_TASK_MODULES.has(moduleName));
}
export class PythonProcessPool extends BaseProcessPool {
constructor(poolSize?: number) {
super(poolSize, {
name: 'Python',
workerScript: WORKER_SCRIPT,
spawnCommand: (script) => `exec python3 -u ${script}`,
allowedModules: env.SANDBOX_PYTHON_ALLOWED_MODULES,
recycleAfterTask: shouldRecycleAfterTask(env.SANDBOX_PYTHON_ALLOWED_MODULES)
});
}
}
......@@ -369,8 +369,8 @@ const earlyDangerousMethods = [
'initgroups'
];
// 延迟删除:会被 https/dns/tsx 等内部使用,要等 hardenRuntime 预加载完白名单后再删
const lateDangerousMethods = ['kill', 'exit', 'emitWarning', 'abort'];
// 延迟处理:会被 https/dns/tsx/url 等内部使用,要等 hardenRuntime 预加载完白名单后再收紧。
const lateDangerousMethods = ['kill', 'exit', 'abort'];
function deleteProcessMethods(methods: readonly string[]): void {
for (const method of methods) {
......@@ -384,6 +384,18 @@ function deleteProcessMethods(methods: readonly string[]): void {
}
}
function stubProcessMethods(methods: readonly string[]): void {
for (const method of methods) {
try {
Object.defineProperty(process, method, {
value: () => undefined,
writable: false,
configurable: false
});
} catch {}
}
}
if (typeof process !== 'undefined') {
deleteProcessMethods(earlyDangerousMethods);
......@@ -466,15 +478,6 @@ const SystemHelper = {
if (!REQUEST_LIMITS.allowedProtocols.includes(parsed.protocol)) {
throw new Error('Protocol not allowed');
}
// 先检查 URL 是否指向内部地址
if (await isInternalAddress(url)) {
throw new Error('Request to private network not allowed');
}
const ips = await dnsResolve(parsed.hostname);
// 防 DNS rebinding TOCTOU:对真正用于建连的 IP 再次校验
if (ips.length === 0 || ips.some((ip) => isInternalResolvedIP(ip))) {
throw new Error('Request to private network not allowed');
}
const method = (opts.method || 'GET').toUpperCase();
const headers = opts.headers || {};
const body =
......@@ -486,11 +489,26 @@ const SystemHelper = {
if (body && body.length > REQUEST_LIMITS.maxRequestBodySize) {
throw new Error('Request body too large');
}
const timeoutSeconds =
typeof opts.timeout === 'number' && Number.isFinite(opts.timeout) && opts.timeout > 0
? opts.timeout
: REQUEST_LIMITS.timeoutMs / 1000;
const timeout = Math.min(Math.ceil(timeoutSeconds * 1000), REQUEST_LIMITS.timeoutMs);
// 先完成协议和请求体大小校验,再解析网络目标,避免本地错误被外部网络状态掩盖。
if (await isInternalAddress(url)) {
throw new Error('Request to private network not allowed');
}
const ips = await dnsResolve(parsed.hostname);
// 防 DNS rebinding TOCTOU:对真正用于建连的 IP 再次校验
if (ips.length === 0 || ips.some((ip) => isInternalResolvedIP(ip))) {
throw new Error('Request to private network not allowed');
}
const timeout =
typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
? Math.min(Math.ceil(opts.timeoutMs), REQUEST_LIMITS.timeoutMs)
: Math.min(
Math.ceil(
typeof opts.timeout === 'number' && Number.isFinite(opts.timeout) && opts.timeout > 0
? opts.timeout * 1000
: REQUEST_LIMITS.timeoutMs
),
REQUEST_LIMITS.timeoutMs
);
if (body && !headers['Content-Type'] && !headers['content-type']) {
headers['Content-Type'] = 'application/json';
}
......@@ -559,9 +577,12 @@ function hardenRuntime(): void {
} catch {}
}
// 白名单模块已加载完毕,此时再删除 kill/exit/emitWarning/abort:
// 白名单模块已加载完毕,此时再删除 kill/exit/abort:
// 这些方法仅在模块初始化时被 https/dns/tsx 等使用,预加载后不再需要。
deleteProcessMethods(lateDangerousMethods);
// Node 内置 url.parse 在运行时仍会调用 process.emitWarning。
// 用户代码拿到的是下方 _sandboxProcess,这里只给真实 process 保留不可写 no-op 兼容内置模块。
stubProcessMethods(['emitWarning']);
for (const intrinsic of hardenedIntrinsics) {
if (intrinsic) _ObjectFreeze(intrinsic);
......@@ -885,13 +906,10 @@ rl.on('line', async (line: string) => {
})();
const timeoutPromise = new _OriginalPromise((_, reject) => {
timer = _workerSetTimeout(
() => {
timedOut = true;
reject(new _OriginalError(`Script execution timed out after ${timeoutMs}ms`));
},
timeoutMs || 10000
);
timer = _workerSetTimeout(() => {
timedOut = true;
reject(new _OriginalError(`Script execution timed out after ${timeoutMs}ms`));
}, timeoutMs || 10000);
});
const result = await _PromiseRace([resultPromise, timeoutPromise]);
......
......@@ -2,11 +2,15 @@ import {
createInternalAddressChecker,
PRIVATE_URL_TEXT
} from '@fastgpt/global/common/system/network';
import { env } from '../env';
const truthyEnvValues = new Set(['true', '1', 'yes', 'y']);
const { isInternalAddress, isInternalResolvedIP } = createInternalAddressChecker({
checkInternalIp: () => truthyEnvValues.has((process.env.CHECK_INTERNAL_IP || '').toLowerCase())
checkInternalIp: () => {
const raw = process.env.CHECK_INTERNAL_IP;
return raw === undefined ? env.CHECK_INTERNAL_IP : truthyEnvValues.has(raw.toLowerCase());
}
});
export { isInternalAddress, isInternalResolvedIP, PRIVATE_URL_TEXT };
import { execFile, execFileSync } from 'child_process';
import { platform } from 'os';
import { readdirSync, readFileSync } from 'fs';
import { promisify } from 'util';
const execFileAsync = promisify(execFile);
export const PROCESS_GROUP_SUPPORTED = platform() !== 'win32';
export function readLinuxRSSKB(pid: number): number | null {
try {
const status = readFileSync(`/proc/${pid}/status`, 'utf-8');
const match = status.match(/VmRSS:\s+(\d+)\s+kB/);
return match ? parseInt(match[1], 10) : null;
} catch {
return null;
}
}
export function getLinuxChildPids(pid: number): number[] {
const children = new Set<number>();
try {
const taskIds = readdirSync(`/proc/${pid}/task`);
for (const taskId of taskIds) {
try {
const content = readFileSync(`/proc/${pid}/task/${taskId}/children`, 'utf-8');
for (const child of content.trim().split(/\s+/)) {
const childPid = Number(child);
if (Number.isInteger(childPid) && childPid > 0) {
children.add(childPid);
}
}
} catch {}
}
} catch {}
return [...children];
}
export function getChildPids(pid: number): number[] {
if (platform() === 'linux') {
return getLinuxChildPids(pid);
}
try {
const stdout = execFileSync('pgrep', ['-P', String(pid)], {
encoding: 'utf-8',
timeout: 1000
});
return stdout
.split(/\s+/)
.map((value) => Number(value))
.filter((value) => Number.isInteger(value) && value > 0);
} catch {
return [];
}
}
export function getDescendantPids(rootPid: number): number[] {
const descendants: number[] = [];
const queue = [rootPid];
const seen = new Set<number>(queue);
while (queue.length > 0) {
const parentPid = queue.shift()!;
for (const childPid of getChildPids(parentPid)) {
if (seen.has(childPid)) continue;
seen.add(childPid);
descendants.push(childPid);
queue.push(childPid);
}
}
return descendants;
}
export async function getProcessTreeRSSMB(pid: number): Promise<number | null> {
const pids = [pid, ...getDescendantPids(pid)];
if (pids.length === 0) return null;
try {
if (platform() === 'linux') {
let totalKB = 0;
for (const currentPid of pids) {
const rssKB = readLinuxRSSKB(currentPid);
if (rssKB !== null) totalKB += rssKB;
}
return totalKB > 0 ? totalKB / 1024 : null;
}
const { stdout } = await execFileAsync('ps', ['-o', 'rss=', '-p', pids.join(',')], {
timeout: 2000
});
const totalKB = stdout
.split('\n')
.map((line) => parseInt(line.trim(), 10))
.filter((rssKB) => !isNaN(rssKB))
.reduce((sum, rssKB) => sum + rssKB, 0);
return totalKB > 0 ? totalKB / 1024 : null;
} catch {
return null;
}
}
export function killProcessTree(pid?: number): void {
if (!pid) return;
const descendantPids = getDescendantPids(pid).reverse();
for (const childPid of descendantPids) {
try {
process.kill(childPid, 'SIGKILL');
} catch {}
}
if (PROCESS_GROUP_SUPPORTED) {
try {
process.kill(-pid, 'SIGKILL');
} catch {}
}
try {
process.kill(pid, 'SIGKILL');
} catch {}
}
import http from 'http';
import https from 'https';
import { isIP } from 'net';
import dns from 'dns/promises';
import { isInternalAddress, isInternalResolvedIP } from './ipCheck.util';
export type SandboxHttpLimits = {
maxRequests: number;
timeoutMs: number;
maxResponseSize: number;
maxRequestBodySize: number;
allowedProtocols?: string[];
};
export type SandboxHttpState = {
requestCount: number;
};
export type SandboxHttpRequestPayload = {
url: string;
method?: string;
headers?: Record<string, any>;
body?: any;
timeout?: number;
timeoutMs?: number;
};
const dnsResolve = async (hostname: string) => {
const res = await dns.lookup(hostname, { all: true });
return res.map((r) => r.address);
};
/**
* 执行受控 HTTP 请求。
*
* 该函数用于 sandbox 代理出网,集中维护协议、SSRF、DNS pinning、请求次数、
* 请求体大小、响应大小和超时限制。调用方应为每次代码执行创建独立 state。
*/
export async function runSandboxHttpRequest({
payload,
limits,
state
}: {
payload: SandboxHttpRequestPayload;
limits: SandboxHttpLimits;
state: SandboxHttpState;
}): Promise<any> {
if (++state.requestCount > limits.maxRequests) {
throw new Error('Request limit exceeded');
}
const allowedProtocols = limits.allowedProtocols ?? ['http:', 'https:'];
const parsed = new URL(payload.url);
if (!allowedProtocols.includes(parsed.protocol)) {
throw new Error('Protocol not allowed');
}
const method = (payload.method || 'GET').toUpperCase();
const headers = { ...(payload.headers || {}) };
const body =
payload.body != null
? typeof payload.body === 'string'
? payload.body
: JSON.stringify(payload.body)
: null;
if (body && Buffer.byteLength(body, 'utf8') > limits.maxRequestBodySize) {
throw new Error('Request body too large');
}
if (await isInternalAddress(payload.url)) {
throw new Error('Request to private network not allowed');
}
const ips = await dnsResolve(parsed.hostname);
if (ips.length === 0 || ips.some((ip) => isInternalResolvedIP(ip))) {
throw new Error('Request to private network not allowed');
}
const timeout = (() => {
if (typeof payload.timeoutMs === 'number' && Number.isFinite(payload.timeoutMs)) {
return Math.min(Math.ceil(payload.timeoutMs), limits.timeoutMs);
}
if (
typeof payload.timeout === 'number' &&
Number.isFinite(payload.timeout) &&
payload.timeout > 0
) {
return Math.min(Math.ceil(payload.timeout * 1000), limits.timeoutMs);
}
return limits.timeoutMs;
})();
if (body && !headers['Content-Type'] && !headers['content-type']) {
headers['Content-Type'] = 'application/json';
}
const resolvedIP = ips[0];
if (!headers['Host'] && !headers['host']) {
headers['Host'] = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
}
const lib = parsed.protocol === 'https:' ? https : http;
return new Promise((resolve, reject) => {
const req = lib.request(
{
method,
headers,
timeout,
hostname: resolvedIP,
port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
path: parsed.pathname + parsed.search,
...(isIP(parsed.hostname) ? {} : { servername: parsed.hostname })
},
(res: any) => {
const chunks: Buffer[] = [];
let size = 0;
res.on('data', (chunk: Buffer) => {
size += chunk.length;
if (size > limits.maxResponseSize) {
req.destroy();
reject(new Error('Response too large'));
return;
}
chunks.push(chunk);
});
res.on('end', () => {
const data = Buffer.concat(chunks).toString('utf-8');
const h: Record<string, any> = {};
for (const [k, v] of Object.entries(res.headers)) h[k] = v;
resolve({ status: res.statusCode, statusText: res.statusMessage, headers: h, data });
});
res.on('error', reject);
}
);
req.on('timeout', () => {
req.destroy();
reject(new Error('Request timeout'));
});
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
import { join } from 'path';
import { BaseProcessPool } from '../../src/pool/base-process-pool';
export type SandboxLanguage = 'JS' | 'Python';
export class CustomModuleProcessPool extends BaseProcessPool {
constructor(
language: SandboxLanguage,
language: 'JS',
allowedModules: readonly string[],
options: { recycleAfterTask?: boolean } = {}
) {
super(1, {
name: `Custom${language}`,
workerScript: join(process.cwd(), 'src/pool', language === 'JS' ? 'worker.ts' : 'worker.py'),
spawnCommand: (script) =>
language === 'JS' ? `exec tsx ${script}` : `exec python3 -u ${script}`,
workerScript: join(process.cwd(), 'src/pool', 'worker.ts'),
spawnCommand: (script) => `exec tsx ${script}`,
allowedModules,
recycleAfterTask: options.recycleAfterTask
});
......
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { env } from '../../src/env';
import { ProcessPool } from '../../src/pool/process-pool';
import { PythonIsolatedRunner } from '../../src/isolated/python-isolated-runner';
type ModuleCase = {
code: string;
timeoutMs?: number;
};
const jsModuleCases: Record<string, ModuleCase> = {
lodash: {
code: `async function main() {
const _ = require('lodash');
return { ok: _.sum([1, 2, 3]) === 6 };
}`
},
dayjs: {
code: `async function main() {
const dayjs = require('dayjs');
return { ok: dayjs('2024-01-01').add(1, 'day').format('YYYY-MM-DD') === '2024-01-02' };
}`
},
moment: {
code: `async function main() {
const moment = require('moment');
return { ok: moment.utc('2024-01-01').add(1, 'day').format('YYYY-MM-DD') === '2024-01-02' };
}`
},
uuid: {
code: `async function main() {
const { v5, validate } = require('uuid');
return { ok: validate(v5('fastgpt', v5.URL)) };
}`
},
'crypto-js': {
code: `async function main() {
const CryptoJS = require('crypto-js');
return { ok: CryptoJS.SHA256('fastgpt').toString().length === 64 };
}`
},
qs: {
code: `async function main() {
const qs = require('qs');
return { ok: qs.parse('a%5Bb%5D=1').a.b === '1' };
}`
},
url: {
code: `async function main() {
const url = require('url');
const parsed = url.parse('https://example.com/a?b=1', true);
return { ok: parsed.hostname === 'example.com' && parsed.query.b === '1' };
}`
},
querystring: {
code: `async function main() {
const querystring = require('querystring');
return { ok: querystring.parse('a=1').a === '1' };
}`
}
};
const pythonModuleCases: Record<string, ModuleCase> = {
math: { code: `import math\ndef main():\n return {'ok': math.sqrt(9) == 3}` },
cmath: { code: `import cmath\ndef main():\n return {'ok': cmath.sqrt(-1) == 1j}` },
decimal: {
code: `import decimal\ndef main():\n return {'ok': str(decimal.Decimal('0.1') + decimal.Decimal('0.2')) == '0.3'}`
},
fractions: {
code: `import fractions\ndef main():\n return {'ok': str(fractions.Fraction(1, 3) + fractions.Fraction(1, 6)) == '1/2'}`
},
random: {
code: `import random\ndef main():\n random.seed(1)\n return {'ok': random.randint(1, 10) == 3}`
},
statistics: {
code: `import statistics\ndef main():\n return {'ok': statistics.mean([1, 2, 3]) == 2}`
},
collections: {
code: `import collections\ndef main():\n return {'ok': collections.Counter(['a', 'a'])['a'] == 2}`
},
array: {
code: `import array\ndef main():\n return {'ok': array.array('i', [1, 2]).tolist() == [1, 2]}`
},
heapq: {
code: `import heapq\ndef main():\n h = [3, 1, 2]\n heapq.heapify(h)\n return {'ok': heapq.heappop(h) == 1}`
},
bisect: {
code: `import bisect\ndef main():\n return {'ok': bisect.bisect_left([1, 3, 5], 3) == 1}`
},
queue: {
code: `import queue\ndef main():\n q = queue.Queue()\n q.put('ok')\n return {'ok': q.get() == 'ok'}`
},
copy: {
code: `import copy\ndef main():\n a = {'x': [1]}\n b = copy.deepcopy(a)\n b['x'].append(2)\n return {'ok': a['x'] == [1]}`
},
itertools: {
code: `import itertools\ndef main():\n return {'ok': list(itertools.combinations([1, 2, 3], 2))[0] == (1, 2)}`
},
functools: {
code: `import functools\ndef main():\n return {'ok': functools.reduce(lambda a, b: a + b, [1, 2, 3], 0) == 6}`
},
operator: {
code: `import operator\ndef main():\n return {'ok': operator.itemgetter('a')({'a': 1}) == 1}`
},
string: {
code: `import string\ndef main():\n return {'ok': string.ascii_lowercase[:3] == 'abc'}`
},
re: {
code: `import re\ndef main():\n return {'ok': re.search(r'\\d+', 'a123').group(0) == '123'}`
},
difflib: {
code: `import difflib\ndef main():\n return {'ok': list(difflib.ndiff(['a'], ['b']))[0][0] == '-'}`
},
textwrap: {
code: `import textwrap\ndef main():\n return {'ok': textwrap.shorten('hello world', width=8, placeholder='...') == 'hello...'}`
},
unicodedata: {
code: `import unicodedata\ndef main():\n return {'ok': unicodedata.name('A') == 'LATIN CAPITAL LETTER A'}`
},
codecs: {
code: `import codecs\ndef main():\n return {'ok': codecs.decode(b'Zm9v', 'base64').decode() == 'foo'}`
},
datetime: {
code: `import datetime\ndef main():\n return {'ok': datetime.datetime(2024, 1, 1).year == 2024}`
},
time: { code: `import time\ndef main():\n return {'ok': isinstance(time.time(), float)}` },
calendar: {
code: `import calendar\ndef main():\n return {'ok': calendar.monthrange(2024, 2)[1] == 29}`
},
_strptime: {
code: `import _strptime\ndef main():\n return {'ok': _strptime._strptime_time('2024-01-02', '%Y-%m-%d').tm_year == 2024}`
},
json: { code: `import json\ndef main():\n return {'ok': json.loads('{"a":1}')['a'] == 1}` },
csv: {
code: `import csv, io\ndef main():\n s = io.StringIO()\n csv.writer(s).writerow(['a', 'b'])\n return {'ok': s.getvalue().strip() == 'a,b'}`
},
base64: {
code: `import base64\ndef main():\n return {'ok': base64.b64encode(b'ok').decode() == 'b2s='}`
},
binascii: {
code: `import binascii\ndef main():\n return {'ok': binascii.hexlify(b'ok').decode() == '6f6b'}`
},
struct: {
code: `import struct\ndef main():\n return {'ok': struct.unpack('>I', bytes([0, 0, 0, 42]))[0] == 42}`
},
hashlib: {
code: `import hashlib\ndef main():\n return {'ok': hashlib.sha256(b'fastgpt').hexdigest().startswith('046ca27')}`
},
hmac: {
code: `import hmac, hashlib\ndef main():\n return {'ok': len(hmac.new(b'k', b'v', hashlib.sha256).hexdigest()) == 64}`
},
secrets: {
code: `import secrets\ndef main():\n return {'ok': len(secrets.token_hex(4)) == 8}`
},
uuid: {
code: `import uuid\ndef main():\n return {'ok': str(uuid.uuid5(uuid.NAMESPACE_DNS, 'fastgpt')) == '8df8855a-2990-5a63-831d-be4be1d105bb'}`
},
typing: {
code: `import typing\ndef main():\n return {'ok': str(typing.List[int]) == 'typing.List[int]'}`
},
abc: {
code: `import abc\nclass Base(metaclass=abc.ABCMeta): pass\ndef main():\n return {'ok': isinstance(Base, abc.ABCMeta)}`
},
enum: {
code: `import enum\nclass Color(enum.Enum):\n RED = 1\ndef main():\n return {'ok': Color.RED.name == 'RED'}`
},
dataclasses: {
code: `import dataclasses\n@dataclasses.dataclass\nclass Item:\n name: str\ndef main():\n return {'ok': dataclasses.asdict(Item('ok')) == {'name': 'ok'}}`
},
contextlib: {
code: `import contextlib\ndef main():\n with contextlib.suppress(ValueError):\n int('x')\n return {'ok': True}`
},
pprint: {
code: `import pprint\ndef main():\n return {'ok': "'a': 1" in pprint.pformat({'b': 2, 'a': 1})}`
},
weakref: {
code: `import weakref\nclass Box: pass\ndef main():\n b = Box()\n r = weakref.ref(b)\n return {'ok': r() is b}`
},
numpy: {
code: `import numpy as np\ndef main():\n a = np.array([[1, 2, 3], [4, 5, 6]])\n return {'ok': list(a.shape) == [2, 3] and float(a.mean()) == 3.5 and int(np.dot(np.array([1, 2, 3]), np.array([4, 5, 6]))) == 32}`
},
pandas: {
code: `import pandas as pd\ndef main():\n df = pd.DataFrame([{'team': 'a', 'score': 1}, {'team': 'a', 'score': 3}, {'team': 'b', 'score': 2}])\n grouped = df.groupby('team')['score'].sum().to_dict()\n return {'ok': int(grouped['a']) == 4 and int(grouped['b']) == 2}`
},
matplotlib: {
code: `import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\ndef main():\n fig, ax = plt.subplots(figsize=(2, 1))\n ax.plot([1, 2, 3], [1, 4, 9])\n axes_count = len(fig.axes)\n plt.close(fig)\n return {'ok': bool(matplotlib.__version__) and matplotlib.get_backend().lower() == 'agg' and axes_count == 1}`,
timeoutMs: 30000
}
};
function expectSameMembers(actual: readonly string[], expected: Record<string, unknown>) {
expect([...actual].sort()).toEqual(Object.keys(expected).sort());
}
describe('Sandbox allowed modules availability', () => {
let jsPool: ProcessPool;
let pyRunner: PythonIsolatedRunner;
beforeAll(async () => {
jsPool = new ProcessPool(1);
await jsPool.init();
pyRunner = new PythonIsolatedRunner(1);
await pyRunner.init();
});
afterAll(async () => {
await jsPool?.shutdown();
await pyRunner?.shutdown();
});
it('JS 白名单中的每个模块都有本地可用性用例', () => {
expectSameMembers(env.SANDBOX_JS_ALLOWED_MODULES, jsModuleCases);
});
it('Python 白名单中的每个模块都有本地可用性用例', () => {
expectSameMembers(env.SANDBOX_PYTHON_ALLOWED_MODULES, pythonModuleCases);
});
it.each(env.SANDBOX_JS_ALLOWED_MODULES)(
'JS 白名单模块 %s 可 require 并执行',
async (moduleName) => {
const result = await jsPool.execute({
code: jsModuleCases[moduleName].code,
variables: {},
timeoutMs: jsModuleCases[moduleName].timeoutMs
});
expect(result.success, result.message).toBe(true);
expect(result.data?.codeReturn?.ok).toBe(true);
}
);
it.each(env.SANDBOX_PYTHON_ALLOWED_MODULES)(
'Python 白名单模块 %s 可 import 并执行',
async (moduleName) => {
const result = await pyRunner.execute({
code: pythonModuleCases[moduleName].code,
variables: {},
timeoutMs: pythonModuleCases[moduleName].timeoutMs
});
expect(result.success, result.message).toBe(true);
expect(result.data?.codeReturn?.ok).toBe(true);
}
);
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment