fix: team token auth (#6734)

* fix: team token auth

* fix: Authentication escape

* fix: cr

* Apply suggestions from code review

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* .claude doc

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Archer
2026-04-09 18:55:10 +08:00
committed by GitHub
parent e3b5b3788f
commit cd75ee160e
23 changed files with 190 additions and 90 deletions
+61 -29
View File
@@ -2,22 +2,16 @@
本文件为 Claude Code (claude.ai/code) 在本仓库中工作时提供指导说明。
## 输出要求
1. 输出语言:中文
2. 输出文档位置:
1. 设计文档:.claude/designtodo 跟在设计文档后面。
2. 问题分析文档: .claude/issue
3. 相同需求文档,尽量写在一起(内容超过 300 行,可以分批写入),或者创建要给目录一起管理,不要随意平铺一堆不同版本的相同问题的文档。
4. 文件输出,使用正确的编码格式,例如UTF-8。
5. 如果用户未指明,不要随意编写总结报告。
## 项目概述
FastGPT 是一个 AI Agent 构建平台,通过 Flow 提供开箱即用的数据处理、模型调用能力和可视化工作流编排。这是一个基于 NextJS 构建的全栈 TypeScript 应用,后端使用 MongoDB/PostgreSQL。
**技术栈**: NextJS + TypeScript + ChakraUI + MongoDB + PostgreSQL (PG Vector)/Milvus
## 设计文档
你可以参考 [项目设计文档](./design/) 来了解 FastGPT 已有的设计方案。
## 架构
这是一个使用 pnpm workspaces 的 monorepo,主要结构如下:
@@ -26,7 +20,6 @@ FastGPT 是一个 AI Agent 构建平台,通过 Flow 提供开箱即用的数据
- `packages/global/` - 所有项目共享的类型、常量、工具函数
- `packages/service/` - 后端服务、数据库模型、API 控制器、工作流引擎
- `packages/web/` - 共享的前端组件、hooks、样式、国际化
- `packages/templates/` - 模板市场的应用模板
### Projects (应用程序)
- `projects/app/` - 主 NextJS Web 应用(前端 + API 路由)
@@ -41,14 +34,6 @@ FastGPT 是一个 AI Agent 构建平台,通过 Flow 提供开箱即用的数据
## 开发命令
### 主要命令(从项目根目录运行)
- `pnpm dev` - 启动所有项目的开发环境(使用 package.json 的 workspace 脚本)
- `pnpm build` - 构建所有项目
- `pnpm test` - 使用 Vitest 运行测试
- `pnpm test:workflow` - 运行工作流相关测试
- `pnpm lint` - 对所有 TypeScript 文件运行 ESLint 并自动修复
- `pnpm format-code` - 使用 Prettier 格式化代码
### 项目专用命令
**主应用 (projects/app/)**:
- `cd projects/app && pnpm dev` - 启动 NextJS 开发服务器
@@ -66,8 +51,7 @@ FastGPT 是一个 AI Agent 构建平台,通过 Flow 提供开箱即用的数据
- `cd projects/mcp_server && bun start` - 启动 MCP 服务器
### 工具命令
- `pnpm create:i18n` - 生成国际化翻译文件
- `pnpm api:gen` - 生成 OpenAPI 文档
- `pnpm lint` - 对所有 TypeScript 文件运行 ESLint 并自动修复
- `pnpm initIcon` - 初始化图标资源
- `pnpm gen:theme-typings` - 生成 Chakra UI 主题类型定义
@@ -75,8 +59,8 @@ FastGPT 是一个 AI Agent 构建平台,通过 Flow 提供开箱即用的数据
项目使用 Vitest 进行测试并生成覆盖率报告。主要测试命令:
- `pnpm test` - 运行所有测试
- `pnpm test:workflow` - 专门运行工作流测试
- 测试文件位于 `test/` 目录和 `projects/app/test/`
- `pnpm test {file-path}` - 使用 Vitest 运行指定测试文件的指定测试
- 测试文件位于 `test/` 目录和 `projects/{{name}}/test/`,代表这`packages``单个 project`的测试文件目录。
- 覆盖率报告生成在 `coverage/` 目录
## 代码组织模式
@@ -101,7 +85,7 @@ FastGPT 是一个 AI Agent 构建平台,通过 Flow 提供开箱即用的数据
## 开发注意事项
- **包管理器**: 使用 pnpm 及 workspace 配置
- **Node 版本**: 需要 Node.js >=18.16.0, pnpm >=9.0.0
- **Node 版本**: 需要 Node.js >=20.x, pnpm >=9.x
- **数据库**: 支持 MongoDB、带 pgvector 的 PostgreSQL 或 Milvus 向量存储
- **AI 集成**: 通过统一接口支持多个 AI 提供商
- **国际化**: 完整支持中文、英文和日文
@@ -112,7 +96,7 @@ FastGPT 是一个 AI Agent 构建平台,通过 Flow 提供开箱即用的数据
- 数据库模型使用 Mongoose 配合 TypeScript
- API 路由遵循 NextJS 约定
- 组件文件使用 React 函数式组件和 hooks
- 共享类型定义在 `packages/global/``.d.ts` 文件
- 共享类型定义在 `packages/global/`
## 环境配置
@@ -122,9 +106,57 @@ FastGPT 是一个 AI Agent 构建平台,通过 Flow 提供开箱即用的数据
## 代码规范
- 尽可能使用 type 进行类型声明,而不是 interface
- 采用 DDD 架构 + 模块划分的代码风格,按业务进行划分,然后再按 controller + service + entity 划分
- 使用 type 进行类型声明。
- function props 数量不能超过 2 个,多参数采用对象传递。
## Agent 设计规范
## 运行要求
1. 对于功能的实习和复杂问题修复,优先进行文档设计,并于让用户确认后,再进行执行修复。
2. 采用"设计文档-测试示例-代码编写-测试运行-修正代码/文档"的工作模式,以测试为核心来确保设计的正确性。
### 性格
1. 保持怀疑态度,要深入思考和分析现有代码,提出问题,并让用户确认。
2. 编写单个需求时,运行测试命令,中途不要运行全量测试,只需局部测试即可,只需最后运行全量测试,确保没有问题。
### 工作流程
对于简单任务,可以直接进行编写实现,对于复杂任务,遵循以下流程:
function agent_loop(用户需求){
// 1. 需求文档编写
while(需求文档编写未完成){
用户需求分析
编写需求分析文档;
提出问题,让用户提供答案;
调整需求文档;
}
// 2. 开发文档编写
while(开发文档编写未完成){
编写开发文档;
提出问题,让用户提供答案;
调整开发文档;
}
// 3. 列出 TODO
while(TODO 列表编写未完成){
编写 TODO 列表; // 包含写代码,运行测试等,需要与开发文档对应
提出问题,让用户提供答案;
调整 TODO 列表;
}
// 4. 执行 TODO List
while(TODO List 执行未完成){
执行 TODO List;
更新 TODO List 状态;
}
}
### 输出规范
1. 输出语言:中文
2. 输出文档位置:
2.1. 设计文档:.claude/designtodo 跟在设计文档后面。
2.2. 问题分析文档: .claude/issue
3. 相同需求文档,尽量写在一起(内容超过 300 行,可以分批写入),或者创建要给目录一起管理,不要随意平铺一堆不同版本的相同问题的文档。
4. 文件输出,使用正确的编码格式,例如UTF-8。
5. 除非用户指明,否则不要编写总结报告。
-29
View File
@@ -1,29 +0,0 @@
---
name: fastgpt-design-skill
description: 当用户需要设计 FastGPT 的代码时,可调用此 Skill。
---
## 目录
### AI
* [AI 虚拟机设计文档](./core/ai/sandbox/prd.md)
### Agent 构建
* [微信个人号发布渠道设计文档](./support/outlink/wechat-clawbot.md)
### 工作流
* [工作流设计文档](./core/workflow/index.md)
* [交互节点设计文档](./core/workflow/interactive.md)
### 对话
* [对话暂停设计文档](./core/chat/stop.md)
### 知识库
* [知识库设计文档](./core/dataset/index.md)
### 日志记录
* [日志记录设计文档](./common/logger/index.md)
@@ -24,7 +24,7 @@ async function handler(
appId,
per: WritePermissionVal
});
const result = await MongoAppVersion.findById(versionId).lean();
const result = await MongoAppVersion.findOne({ _id: versionId, appId }).lean();
if (!result) {
return Promise.reject('version not found');
@@ -14,12 +14,7 @@ async function handler(req: ApiRequestProps<UpdateAppVersionBody>) {
const { appId, versionId, versionName } = req.body;
await authApp({ appId, req, per: WritePermissionVal, authToken: true });
await MongoAppVersion.findByIdAndUpdate(
{ _id: versionId },
{
versionName
}
);
await MongoAppVersion.updateOne({ _id: versionId, appId }, { $set: { versionName } });
return {};
}
@@ -13,6 +13,7 @@ import {
import { parsePaginationRequest } from '@fastgpt/service/common/api/pagination';
import { addMonths } from 'date-fns';
import { ObjectIdSchema } from '@fastgpt/global/common/type/mongo';
import { MongoApp } from '@fastgpt/service/core/app/schema';
/* get chat histories list */
export async function handler(
@@ -46,7 +47,19 @@ export async function handler(
};
}
if (appId && teamId && teamToken) {
const { uid } = await authTeamSpaceToken({ teamId, teamToken });
const { uid, tags } = await authTeamSpaceToken({ teamId, teamToken });
const app = await MongoApp.findOne({
_id: appId,
teamId,
$or: [
{ teamTags: { $size: 0 } },
{ teamTags: { $exists: false } },
{ teamTags: { $in: tags } }
]
}).lean();
if (!app) return undefined;
return {
appId,
outLinkUid: uid,
@@ -22,23 +22,32 @@ async function handler(req: ApiRequestProps<InitTeamChatProps>, res: NextApiResp
return Promise.reject('teamId, appId, teamToken are required');
}
const { uid } = await authTeamSpaceToken({
const { uid, tags } = await authTeamSpaceToken({
teamId,
teamToken
});
const [team, chat, app] = await Promise.all([
const [team, app] = await Promise.all([
MongoTeam.findById(teamId, 'name avatar').lean(),
MongoChat.findOne({ appId, chatId }).lean(),
MongoApp.findById(appId).lean()
MongoApp.findOne({
_id: appId,
teamId,
$or: [
{ teamTags: { $size: 0 } },
{ teamTags: { $exists: false } },
{ teamTags: { $in: tags } }
]
}).lean()
]);
if (!app) {
return Promise.reject(AppErrEnum.unExist);
}
const chat = chatId ? await MongoChat.findOne({ appId, chatId }).lean() : null;
// auth chat permission
if (chat && chat.outLinkUid !== uid) {
if (chat && (String(chat.teamId) !== teamId || chat.outLinkUid !== uid)) {
return Promise.reject(ChatErrEnum.unAuthChat);
}
@@ -602,17 +602,21 @@ const authTeamSpaceChat = async ({
teamToken: string;
chatId?: string;
}): Promise<AuthResponseType> => {
const { uid } = await authTeamSpaceToken({
const { uid, tags } = await authTeamSpaceToken({
teamId,
teamToken
});
const app = await MongoApp.findById(appId).lean();
const app = await MongoApp.findOne({
_id: appId,
teamId,
$or: [{ teamTags: { $size: 0 } }, { teamTags: { $exists: false } }, { teamTags: { $in: tags } }]
}).lean();
if (!app) {
return Promise.reject('app is empty');
return Promise.reject(ChatErrEnum.unAuthChat);
}
const chat = await MongoChat.findOne({ appId, chatId }).lean();
const chat = chatId ? await MongoChat.findOne({ appId, chatId }).lean() : null;
if (chat && (String(chat.teamId) !== teamId || chat.outLinkUid !== uid)) {
return Promise.reject(ChatErrEnum.unAuthChat);
@@ -660,7 +664,7 @@ const authHeaderRequest = async ({
'Key is error. You need to use the app key rather than the account key.'
);
}
const app = await MongoApp.findById(currentAppId);
const app = await MongoApp.findOne({ _id: currentAppId, teamId });
if (!app) {
return Promise.reject('app is empty');
@@ -575,17 +575,21 @@ const authTeamSpaceChat = async ({
teamToken: string;
chatId?: string;
}): Promise<AuthResponseType> => {
const { uid } = await authTeamSpaceToken({
const { uid, tags } = await authTeamSpaceToken({
teamId,
teamToken
});
const app = await MongoApp.findById(appId).lean();
const app = await MongoApp.findOne({
_id: appId,
teamId,
$or: [{ teamTags: { $size: 0 } }, { teamTags: { $exists: false } }, { teamTags: { $in: tags } }]
}).lean();
if (!app) {
return Promise.reject('app is empty');
return Promise.reject(ChatErrEnum.unAuthChat);
}
const chat = await MongoChat.findOne({ appId, chatId }).lean();
const chat = chatId ? await MongoChat.findOne({ appId, chatId }).lean() : null;
if (chat && (String(chat.teamId) !== teamId || chat.outLinkUid !== uid)) {
return Promise.reject(ChatErrEnum.unAuthChat);
@@ -632,7 +636,7 @@ const authHeaderRequest = async ({
'Key is error. You need to use the app key rather than the account key.'
);
}
const app = await MongoApp.findById(currentAppId);
const app = await MongoApp.findOne({ _id: currentAppId, teamId });
if (!app) {
return Promise.reject('app is empty');
@@ -14,6 +14,7 @@ import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import type { HelperBotTypeEnum } from '@fastgpt/global/core/chat/helperBot/type';
import { MongoHelperBotChat } from '@fastgpt/service/core/chat/HelperBot/chatSchema';
import { authCert } from '@fastgpt/service/support/permission/auth/common';
import { MongoApp } from '@fastgpt/service/core/app/schema';
/*
检查chat的权限:
@@ -69,7 +70,28 @@ export async function authChatCrud({
if (!appId) return Promise.reject(ChatErrEnum.unAuthChat);
if (spaceTeamId && teamToken) {
const { uid, tmbId } = await authTeamSpaceToken({ teamId: spaceTeamId, teamToken });
const { uid, tmbId, tags } = await authTeamSpaceToken({
teamId: spaceTeamId,
teamToken
});
// Verify app belongs to the authenticated team and tag-based access
const app = await MongoApp.findOne(
{
_id: appId,
teamId: spaceTeamId,
$or: [
{ teamTags: { $size: 0 } },
{ teamTags: { $exists: false } },
{ teamTags: { $in: tags } }
]
},
'teamId'
).lean();
if (!app) {
return Promise.reject(ChatErrEnum.unAuthChat);
}
if (!chatId) {
return {
teamId: spaceTeamId,
@@ -91,7 +113,8 @@ export async function authChatCrud({
};
}
if (chat.outLinkUid !== uid) return Promise.reject(ChatErrEnum.unAuthChat);
if (String(chat.teamId) !== spaceTeamId || chat.outLinkUid !== uid)
return Promise.reject(ChatErrEnum.unAuthChat);
return {
teamId: spaceTeamId,
@@ -16,14 +16,15 @@ export async function authTeamSpaceToken({
teamId: string;
teamToken: string;
}) {
// get outLink and app
const [{ uid }, member] = await Promise.all([
// authenticate the team token, get uid/tags, and load the owner member
const [{ uid, tags }, member] = await Promise.all([
authTeamTagToken({ teamId, teamToken }),
MongoTeamMember.findOne({ teamId, role: TeamMemberRoleEnum.owner }, 'tmbId').lean()
]);
return {
uid,
tmbId: member?._id!
tmbId: member?._id!,
tags
};
}
@@ -9,6 +9,7 @@ import { DatasetErrEnum } from '@fastgpt/global/common/error/code/dataset';
import { authApp } from '@fastgpt/service/support/permission/app/auth';
import { authOutLink } from '@/service/support/permission/auth/outLink';
import { authTeamSpaceToken } from '@/service/support/permission/auth/team';
import { MongoApp } from '@fastgpt/service/core/app/schema';
import type { ChatHistoryItemResType } from '@fastgpt/global/core/chat/type';
import { getFlatAppResponses } from '@fastgpt/global/core/chat/utils';
import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
@@ -35,6 +36,16 @@ vi.mock('@fastgpt/service/core/chat/chatItemResponseSchema', () => ({
}
}));
vi.mock('@fastgpt/service/core/app/schema', async (importOriginal) => {
const actual = await importOriginal<typeof import('@fastgpt/service/core/app/schema')>();
return {
...actual,
MongoApp: {
findOne: vi.fn()
}
};
});
vi.mock('@fastgpt/service/support/permission/app/auth');
vi.mock('@/service/support/permission/auth/outLink');
vi.mock('@/service/support/permission/auth/team');
@@ -118,8 +129,12 @@ describe('authChatCrud', () => {
it('should auth with teamId and teamToken without chatId', async () => {
vi.mocked(authTeamSpaceToken).mockResolvedValue({
uid: 'user1',
tmbId: 'tmb1'
tmbId: 'tmb1',
tags: ['tag1']
});
vi.mocked(MongoApp.findOne).mockReturnValue({
lean: () => Promise.resolve({ _id: 'app1', teamId: 'team1' })
} as any);
const result = await authChatCrud({
appId: 'app1',
@@ -142,6 +157,27 @@ describe('authChatCrud', () => {
});
});
it('should reject if app does not belong to team or tags mismatch', async () => {
vi.mocked(authTeamSpaceToken).mockResolvedValue({
uid: 'user1',
tmbId: 'tmb1',
tags: ['tag1']
});
vi.mocked(MongoApp.findOne).mockReturnValue({
lean: () => Promise.resolve(null)
} as any);
await expect(
authChatCrud({
appId: 'app1',
teamId: 'team1',
teamToken: 'token1',
req: {} as any,
authToken: true
})
).rejects.toBe(ChatErrEnum.unAuthChat);
});
it('should auth with teamId and teamToken with valid chatId', async () => {
const mockChat = {
appId: 'app1',
@@ -151,8 +187,12 @@ describe('authChatCrud', () => {
vi.mocked(authTeamSpaceToken).mockResolvedValue({
uid: 'user1',
tmbId: 'tmb1'
tmbId: 'tmb1',
tags: ['tag1']
});
vi.mocked(MongoApp.findOne).mockReturnValue({
lean: () => Promise.resolve({ _id: 'app1', teamId: 'team1' })
} as any);
vi.mocked(MongoChat.findOne).mockReturnValue({
lean: () => Promise.resolve(mockChat)
} as any);
@@ -183,8 +223,12 @@ describe('authChatCrud', () => {
it('should handle missing chat for teamDomain auth', async () => {
vi.mocked(authTeamSpaceToken).mockResolvedValue({
uid: 'user1',
tmbId: 'tmb1'
tmbId: 'tmb1',
tags: ['tag1']
});
vi.mocked(MongoApp.findOne).mockReturnValue({
lean: () => Promise.resolve({ _id: 'app1', teamId: 'team1' })
} as any);
vi.mocked(MongoChat.findOne).mockReturnValue({
lean: () => Promise.resolve(null)
} as any);
@@ -220,8 +264,12 @@ describe('authChatCrud', () => {
vi.mocked(authTeamSpaceToken).mockResolvedValue({
uid: 'user1',
tmbId: 'tmb1'
tmbId: 'tmb1',
tags: ['tag1']
});
vi.mocked(MongoApp.findOne).mockReturnValue({
lean: () => Promise.resolve({ _id: 'app1', teamId: 'team1' })
} as any);
vi.mocked(MongoChat.findOne).mockReturnValue({
lean: () => Promise.resolve(mockChat)
} as any);