🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(knowledge): business knowledge access seam with caller-scoped content reads (#22863)
Mocha50caca20e72f
diff --git a/apps/server/src/routers/lambda/__tests__/integration/knowledgeContentAccess.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/knowledgeContentAccess.integration.test.tsnew file mode 100644index 00000000000..afb1cad5ca9--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/integration/knowledgeContentAccess.integration.test.ts@@ -0,0 +1,431 @@+// @vitest-environment node+import * as business from '@lobechat/business-knowledge';+import { drizzle } from 'drizzle-orm/pglite';+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++import { GET } from '@/app/(backend)/f/[id]/route';+import { createPGlite, readPGliteSnapshot } from '@/database/core/pgliteSnapshot';+import * as schema from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { KnowledgeBaseSearchService } from '@/server/services/knowledgeBase';+import { attachmentsRuntime } from '@/server/services/toolExecution/serverRuntimes/attachments';+import { knowledgeBaseRuntime } from '@/server/services/toolExecution/serverRuntimes/knowledgeBase';++import { chunkRouter } from '../../chunk';++const boundary = vi.hoisted(() => ({+ db: undefined as LobeChatDatabase | undefined,+ identity: undefined as string | undefined,+ credential: {} as Record<string, unknown>,+ sign: vi.fn(async () => 'https://storage.example/temporary'),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: () => boundary.db }));+vi.mock('@/database/server', () => ({ getServerDB: () => boundary.db }));+vi.mock('@/libs/trpc/lambda/context', () => ({+ createLambdaContext: vi.fn(async () => ({ userId: boundary.identity, ...boundary.credential })),+}));+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return { createCachedPreSignedUrlForPreview: boundary.sign, createDownloadUrl: boundary.sign };+ }),+}));+vi.mock('@lobechat/business-knowledge', async (original) => ({+ ...(await original<typeof business>()),+ isEnterpriseKnowledgeEnabled: vi.fn(() => false),+ listEnterpriseKbIds: vi.fn(),+ resolveEnterpriseKbAccess: vi.fn(),+}));+vi.mock('@/server/services/workspacePermission', () => ({+ getWorkspaceScopedPermissionMatches: vi.fn(async () => ({+ hasAllScope: false,+ hasOwnerScope: true,+ })),+}));++let client: ReturnType<typeof createPGlite>;+let db: LobeChatDatabase;+const owner = 'content-owner';+const viewer = 'content-viewer';+const outsider = 'content-outsider';+const caller = (userId?: string, workspaceId?: string) =>+ chunkRouter.createCaller({ userId, workspaceId });+const contents = (userId: string, ids: string[], workspaceId?: string) =>+ caller(userId, workspaceId).getFileContents({ fileIds: ids });+const proxy = (id: string, download = false) =>+ GET(new Request(`https://app.example/f/${id}${download ? '?download=1' : ''}`), {+ params: Promise.resolve({ id }),+ });++const enablePolicy = () => {+ vi.mocked(business.isEnterpriseKnowledgeEnabled).mockReturnValue(true);+ vi.mocked(business.listEnterpriseKbIds).mockImplementation(async (_db, ids) =>+ (ids ?? ['content-kb-a', 'content-kb-b']).filter(+ (id) => id === 'content-kb-a' || id === 'content-kb-b',+ ),+ );+ vi.mocked(business.resolveEnterpriseKbAccess).mockImplementation(+ async (_db, userId, knowledgeBaseId) => ({+ enterprise: true,+ access:+ userId === owner || (userId === viewer && knowledgeBaseId === 'content-kb-a')+ ? { knowledgeBaseId, ownerId: owner, level: userId === owner ? 'owner' : 'view' }+ : null,+ }),+ );+};++beforeAll(async () => {+ client = createPGlite(readPGliteSnapshot());+ db = drizzle({ client, schema }) as unknown as LobeChatDatabase;+ boundary.db = db;+ await db.insert(schema.users).values([owner, viewer, outsider].map((id) => ({ id })));+ await db.insert(schema.workspaces).values({+ id: 'content-workspace',+ name: 'Content workspace',+ slug: 'content-workspace',+ primaryOwnerId: owner,+ });+ await db.insert(schema.knowledgeBases).values([+ { id: 'content-kb-a', name: 'Library A', userId: owner },+ { id: 'content-kb-b', name: 'Library B', userId: owner },+ {+ id: 'content-kb-workspace',+ name: 'Restricted library',+ userId: owner,+ workspaceId: 'content-workspace',+ },+ ]);+ await db.insert(schema.files).values(+ [+ { id: 'file_content_a', userId: owner },+ { id: 'file_content_b', userId: owner },+ { id: 'file_content_personal', userId: owner },+ { id: 'file_content_deleted', userId: owner, isDeleted: true },+ { id: 'file_content_workspace', userId: owner, workspaceId: 'content-workspace' },+ ].map((file) => ({+ ...file,+ fileType: 'text/plain',+ name: `${file.id}.txt`,+ size: 10,+ url: `storage/${file.id}`,+ })),+ );+ await db.insert(schema.knowledgeBaseFiles).values([+ { fileId: 'file_content_a', knowledgeBaseId: 'content-kb-a', userId: owner },+ { fileId: 'file_content_b', knowledgeBaseId: 'content-kb-b', userId: owner },+ { fileId: 'file_content_deleted', knowledgeBaseId: 'content-kb-a', userId: owner },+ { fileId: 'file_content_workspace', knowledgeBaseId: 'content-kb-workspace', userId: owner },+ ]);+ await db.insert(schema.documents).values(+ [+ {+ id: 'docs_content_a',+ userId: owner,+ knowledgeBaseId: 'content-kb-a',+ content: 'library A text',+ },+ {+ id: 'docs_content_b',+ userId: owner,+ knowledgeBaseId: 'content-kb-b',+ content: 'library B text',+ },+ {+ id: 'docs_content_parsed',+ userId: owner,+ fileId: 'file_content_a',+ content: 'parsed library A',+ },+ { id: 'docs_content_personal', userId: owner, content: 'personal text' },+ { id: 'docs_content_viewer', userId: viewer, content: 'viewer text' },+ {+ id: 'docs_content_deleted',+ userId: owner,+ knowledgeBaseId: 'content-kb-a',+ content: 'deleted text',+ isDeleted: true,+ },+ {+ id: 'docs_content_deleted_backing',+ userId: owner,+ fileId: 'file_content_deleted',+ content: 'parsed deleted text',+ },+ {+ id: 'docs_content_workspace',+ userId: owner,+ fileId: 'file_content_workspace',+ content: 'restricted text',+ workspaceId: 'content-workspace',+ },+ ].map((doc) => ({+ ...doc,+ fileType: 'text/plain',+ source: 'test',+ sourceType: 'file' as const,+ totalCharCount: 10,+ totalLineCount: 1,+ })),+ );+ await db.insert(schema.resourcePermissions).values({+ workspaceId: 'content-workspace',+ resourceType: 'knowledgeBase',+ resourceId: 'content-kb-workspace',+ accessLevel: 'use',+ });+}, 30000);++afterAll(async () => {+ await client?.close();+});+beforeEach(() => {+ vi.clearAllMocks();+ boundary.credential = {};+ boundary.identity = undefined;+ vi.mocked(business.isEnterpriseKnowledgeEnabled).mockReturnValue(false);+});++describe('knowledge content read boundaries', () => {+ it('preserves default anonymous public-by-id preview and download', async () => {+ for (const download of [false, true]) {+ const response = await proxy('file_content_personal', download);+ expect(response.status).toBe(302);+ expect(response.headers.get('location')).toBe('https://storage.example/temporary');+ }+ });++ it('keeps ordinary personal reads owner-scoped, including mixed ids and deleted content', async () => {+ const result = await contents(owner, [+ 'docs_content_personal',+ 'file_content_a',+ 'docs_content_deleted',+ ]);+ expect(result.map((row) => row.content)).toEqual(['personal text', 'parsed library A', '']);+ expect(+ (await contents(viewer, ['docs_content_personal', 'file_content_a'])).every(+ (row) => row.content === '',+ ),+ ).toBe(true);+ });++ it.each([false, true])(+ 'does not return ordinary owner content to a different explicit caller (policy enabled: %s)',+ async (policyEnabled) => {+ if (policyEnabled) enablePolicy();+ const result = await new KnowledgeBaseSearchService(+ db,+ owner,+ undefined,+ undefined,+ viewer,+ ).getFileContents(['docs_content_personal']);+ expect(result[0].content).toBe('');+ expect(result[0].error).toBe('Document not found');+ },+ );++ it.each([false, true])(+ 'reads ordinary content in the explicit caller scope (policy enabled: %s)',+ async (policyEnabled) => {+ if (policyEnabled) enablePolicy();+ const result = await new KnowledgeBaseSearchService(+ db,+ owner,+ undefined,+ undefined,+ viewer,+ ).getFileContents(['docs_content_viewer']);+ expect(result[0].content).toBe('viewer text');+ },+ );++ it.each([false, true])(+ 'preserves ordinary owner reads without an explicit caller (policy enabled: %s)',+ async (policyEnabled) => {+ if (policyEnabled) enablePolicy();+ const result = await new KnowledgeBaseSearchService(db, owner).getFileContents([+ 'docs_content_personal',+ 'docs_content_viewer',+ ]);+ expect(result.map((row) => row.content)).toEqual(['personal text', '']);+ },+ );++ it('permits a current viewer to read only exact granted items and their parsed pages', async () => {+ enablePolicy();+ const result = await contents(viewer, [+ 'docs_content_viewer',+ 'docs_content_a',+ 'file_content_a',+ 'docs_content_parsed',+ ]);+ expect(result.map((row) => row.content)).toEqual([+ 'viewer text',+ 'library A text',+ 'parsed library A',+ 'parsed library A',+ ]);+ });++ it('server tool runtimes read managed content as the executing user, not as anonymous', async () => {+ enablePolicy();+ const context = { serverDB: db, userId: viewer } as any;+ const knowledge = (await knowledgeBaseRuntime.factory(context)) as any;+ const attachments = (await attachmentsRuntime.factory(context)) as any;+ const read = await knowledge.readKnowledge({ fileIds: ['file_content_a'] });+ expect(read.success).toBe(true);+ expect(read.content).toContain('parsed library A');+ const attachment = await attachments.readAttachment({ fileId: 'file_content_a' });+ expect(attachment.success).toBe(true);+ expect(attachment.content).toContain('parsed library A');+ const visitor = (await attachmentsRuntime.factory({+ ...context,+ agentShareVisitor: { shareId: 'share' },+ })) as any;+ expect((await visitor.readAttachment({ fileId: 'file_content_a' })).success).toBe(false);+ });++ it('rejects a whole mixed batch when any enterprise item is denied', async () => {+ enablePolicy();+ await expect(contents(viewer, ['docs_content_a', 'file_content_b'])).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ await expect(contents(outsider, ['docs_content_a'])).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });++ it('does not use an implicit data owner as the authenticated caller for direct service reads', async () => {+ enablePolicy();+ await expect(+ new KnowledgeBaseSearchService(db, owner).getFileContents(['docs_content_a']),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(+ (+ await new KnowledgeBaseSearchService(+ db,+ owner,+ undefined,+ undefined,+ viewer,+ ).getFileContents(['docs_content_a'])+ )[0].content,+ ).toBe('library A text');+ const mixed = await new KnowledgeBaseSearchService(+ db,+ owner,+ undefined,+ undefined,+ viewer,+ ).getFileContents(['docs_content_a', 'docs_content_personal']);+ expect(mixed.map((row) => row.content)).toEqual(['library A text', '']);+ });++ it('rejects an anonymous chunk request', async () => {+ await expect(caller().getFileContents({ fileIds: ['docs_content_a'] })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+ });++ it('denies enterprise proxy preview/download without ever signing for anonymous or unauthorized users', async () => {+ enablePolicy();+ for (const identity of [undefined, outsider]) {+ boundary.identity = identity;+ for (const download of [false, true]) {+ const response = await proxy('file_content_a', download);+ expect(response.status).toBe(404);+ expect(response.headers.get('location')).toBeNull();+ expect(await response.text()).toBe('File not found');+ }+ }+ expect(boundary.sign).not.toHaveBeenCalled();+ });++ it('allows authorized enterprise preview and keeps non-enterprise anonymous links working when policies are enabled', async () => {+ enablePolicy();+ boundary.identity = viewer;+ expect((await proxy('file_content_a')).status).toBe(302);+ boundary.identity = undefined;+ expect((await proxy('file_content_personal')).status).toBe(302);+ });++ it('refuses operation-scoped tokens and API keys without file read scope at the file proxy', async () => {+ enablePolicy();+ boundary.identity = viewer;+ boundary.credential = { oidcAuth: { purpose: 'hetero-operation', sub: viewer } };+ expect((await proxy('file_content_a')).status).toBe(404);+ boundary.credential = { apiKeyScopes: ['agent:read'] };+ expect((await proxy('file_content_a')).status).toBe(404);+ boundary.credential = { apiKeyScopes: ['file:read'] };+ expect((await proxy('file_content_a')).status).not.toBe(404);+ boundary.credential = { apiKeyScopes: ['file:read'], workspaceId: 'ws-bound' };+ expect((await proxy('file_content_a')).status).toBe(404);+ boundary.credential = { oidcAuth: { purpose: 'hetero-operation', sub: viewer } };+ boundary.identity = undefined;+ expect((await proxy('file_content_personal')).status).toBe(302);+ });++ it('hides deleted enterprise items without granting access to unrelated private siblings', async () => {+ enablePolicy();+ boundary.identity = owner;+ expect((await proxy('file_content_deleted')).status).toBe(404);+ expect(boundary.sign).not.toHaveBeenCalled();+ await expect(contents(owner, ['docs_content_deleted'])).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ await expect(contents(owner, ['docs_content_deleted_backing'])).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ const personal = await contents(viewer, ['docs_content_personal']);+ expect(personal[0].content).toBe('');+ });++ it('rechecks access on every read and fails closed when access resolution throws', async () => {+ enablePolicy();+ const currentCaller = caller(viewer);+ expect((await currentCaller.getFileContents({ fileIds: ['docs_content_a'] }))[0].content).toBe(+ 'library A text',+ );+ vi.mocked(business.resolveEnterpriseKbAccess).mockResolvedValue({+ enterprise: true,+ access: null,+ });+ await expect(+ currentCaller.getFileContents({ fileIds: ['docs_content_a'] }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ vi.mocked(business.resolveEnterpriseKbAccess).mockRejectedValue(+ new Error('resolution unavailable'),+ );+ boundary.identity = viewer;+ expect((await proxy('file_content_a')).status).toBe(404);+ await expect(contents(viewer, ['docs_content_a'])).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(boundary.sign).not.toHaveBeenCalled();+ });++ it('fails closed on policy errors and on mismatched owner metadata', async () => {+ enablePolicy();+ boundary.identity = owner;+ vi.mocked(business.listEnterpriseKbIds).mockRejectedValue(new Error('policy unavailable'));+ expect((await proxy('file_content_a')).status).toBe(404);+ await expect(contents(owner, ['docs_content_a'])).rejects.toMatchObject({ code: 'NOT_FOUND' });+ enablePolicy();+ vi.mocked(business.resolveEnterpriseKbAccess).mockResolvedValue({+ enterprise: true,+ access: { knowledgeBaseId: 'content-kb-a', ownerId: outsider, level: 'view' },+ });+ await expect(contents(viewer, ['docs_content_a'])).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(boundary.sign).not.toHaveBeenCalled();+ });++ it('applies the existing workspace no-browse rule to full file and parsed-document reads', async () => {+ for (const id of ['file_content_workspace', 'docs_content_workspace']) {+ await expect(contents(viewer, [id], 'content-workspace')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ }+ expect(+ (await contents(owner, ['docs_content_workspace'], 'content-workspace'))[0].content,+ ).toBe('restricted text');+ });+});diff --git a/apps/server/src/routers/lambda/chunk.ts b/apps/server/src/routers/lambda/chunk.tsindex fa14026b5f8..44a30dd1a76 100644--- a/apps/server/src/routers/lambda/chunk.ts+++ b/apps/server/src/routers/lambda/chunk.ts@@ -34,7 +34,13 @@ const chunkProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>documentService: new DocumentService(ctx.serverDB, ctx.userId, wsId),embeddingModel: new EmbeddingModel(ctx.serverDB, ctx.userId, wsId),fileModel: new FileModel(ctx.serverDB, ctx.userId, wsId),- knowledgeBaseSearchService: new KnowledgeBaseSearchService(ctx.serverDB, ctx.userId, wsId),+ knowledgeBaseSearchService: new KnowledgeBaseSearchService(+ ctx.serverDB,+ ctx.userId,+ wsId,+ undefined,+ ctx.userId,+ ),messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),},});diff --git a/apps/server/src/services/enterpriseKnowledge/contentAccess.ts b/apps/server/src/services/enterpriseKnowledge/contentAccess.tsnew file mode 100644index 00000000000..2c2ec9ffbf7--- /dev/null+++ b/apps/server/src/services/enterpriseKnowledge/contentAccess.ts@@ -0,0 +1,172 @@+import {+ isEnterpriseKnowledgeEnabled,+ listEnterpriseKbIds,+ resolveEnterpriseKbAccess,+} from '@lobechat/business-knowledge';+import { hasApiKeyScope, isFullAccessApiKey } from '@lobechat/const/apiKeyScope';+import { TRPCError } from '@trpc/server';+import { and, eq, inArray, isNull } from 'drizzle-orm';+import pMap from 'p-map';++import { documents, files, knowledgeBaseFiles, knowledgeBases } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++/**+ * Caller eligible to read managed content on surfaces that bypass the tRPC credential+ * middleware, such as the file proxy. Managed content is personal-scope: sessions,+ * ordinary OIDC and full-access or `file:read` API keys qualify; sandbox operation+ * tokens and any workspace-bound identity never do.+ */+export const resolveManagedContentReader = (identity: {+ apiKeyScopes?: string[] | null;+ oidcAuth?: object | null;+ userId?: string | null;+ workspaceId?: string | null;+}): string | undefined => {+ if (!identity.userId || identity.workspaceId) return undefined;+ const purpose = (identity.oidcAuth as { purpose?: unknown } | null | undefined)?.purpose;+ if (purpose === 'hetero-operation') return undefined;+ const scopes = identity.apiKeyScopes;+ if (scopes && !isFullAccessApiKey(scopes) && !hasApiKeyScope(scopes, 'file:read'))+ return undefined;+ return identity.userId;+};++interface ContentAccessContext {+ serverDB: LobeChatDatabase;+ /** Authenticated caller, distinct from the data owner's scope. */+ userId?: string | null;+ workspaceId?: string | null;+}++/**+ * Resolve exact enterprise file/document ids before signing URLs or reading bodies.+ * Non-enterprise ids keep the existing model scope (and public-by-id proxy behavior).+ * A granted library never grants access to its owner's unrelated personal content.+ */+export const resolveEnterpriseContentScopes = async (+ ctx: ContentAccessContext,+ ids: string[],+): Promise<Map<string, string>> => {+ const scopes = new Map<string, string>();+ if (ctx.workspaceId || ids.length === 0 || !isEnterpriseKnowledgeEnabled()) return scopes;++ try {+ const documentIds = ids.filter((id) => id.startsWith('docs_'));+ const pages = documentIds.length+ ? await ctx.serverDB+ .select({+ id: documents.id,+ fileId: documents.fileId,+ knowledgeBaseId: documents.knowledgeBaseId,+ userId: documents.userId,+ isDeleted: documents.isDeleted,+ })+ .from(documents)+ .where(and(inArray(documents.id, documentIds), isNull(documents.workspaceId)))+ : [];+ const fileIds = [+ ...new Set([+ ...ids.filter((id) => !id.startsWith('docs_')),+ ...pages.flatMap((page) => (page.fileId ? [page.fileId] : [])),+ ]),+ ];+ const fileRows = fileIds.length+ ? await ctx.serverDB+ .select({+ id: files.id,+ userId: files.userId,+ isDeleted: files.isDeleted,+ knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,+ })+ .from(files)+ .leftJoin(knowledgeBaseFiles, eq(knowledgeBaseFiles.fileId, files.id))+ .where(and(inArray(files.id, fileIds), isNull(files.workspaceId)))+ : [];+ const items = new Map<+ string,+ { userId: string; isDeleted: boolean | null; knowledgeBaseIds: Set<string> }+ >();+ for (const file of fileRows) {+ const item = items.get(file.id) ?? {+ userId: file.userId,+ isDeleted: file.isDeleted,+ knowledgeBaseIds: new Set<string>(),+ };+ if (file.knowledgeBaseId) item.knowledgeBaseIds.add(file.knowledgeBaseId);+ items.set(file.id, item);+ }+ for (const page of pages) {+ const backing = page.fileId ? items.get(page.fileId) : undefined;+ items.set(page.id, {+ userId: page.userId,+ isDeleted:+ page.isDeleted ||+ (!!page.fileId && (!backing || backing.isDeleted || backing.userId !== page.userId)),+ knowledgeBaseIds: new Set([+ ...(page.knowledgeBaseId ? [page.knowledgeBaseId] : []),+ ...(backing?.knowledgeBaseIds ?? []),+ ]),+ });+ }++ const candidates = [+ ...new Set([...items.values()].flatMap((item) => [...item.knowledgeBaseIds])),+ ];+ if (candidates.length === 0) return scopes;+ const enterpriseIds = await listEnterpriseKbIds(ctx.serverDB, candidates);+ if (enterpriseIds.length === 0) return scopes;+ const libraries = await ctx.serverDB+ .select({+ id: knowledgeBases.id,+ userId: knowledgeBases.userId,+ isDeleted: knowledgeBases.isDeleted,+ })+ .from(knowledgeBases)+ .where(and(inArray(knowledgeBases.id, enterpriseIds), isNull(knowledgeBases.workspaceId)));+ const enterpriseSet = new Set(enterpriseIds);+ const resolutions = new Map(+ await pMap(+ enterpriseIds,+ async (id) =>+ [+ id,+ ctx.userId+ ? await resolveEnterpriseKbAccess(ctx.serverDB, ctx.userId, id)+ : { enterprise: true as const, access: null },+ ] as const,+ { concurrency: 10 },+ ),+ );++ for (const id of ids) {+ const item = items.get(id);+ if (!item) continue;+ const governedIds = [...item.knowledgeBaseIds].filter((kbId) => enterpriseSet.has(kbId));+ if (governedIds.length === 0) continue;+ const permitted =+ !item.isDeleted &&+ governedIds.some((kbId) => {+ const resolution = resolutions.get(kbId);+ const library = libraries.find((row) => row.id === kbId);+ return (+ resolution?.enterprise &&+ resolution.access &&+ library &&+ !library.isDeleted &&+ resolution.access.knowledgeBaseId === kbId &&+ resolution.access.ownerId === library.userId &&+ library.userId === item.userId &&+ ['owner', 'edit', 'view'].includes(resolution.access.level)+ );+ });+ if (!permitted) throw new TRPCError({ code: 'NOT_FOUND' });+ scopes.set(id, item.userId);+ }+ return scopes;+ } catch (error) {+ if (error instanceof TRPCError && error.code === 'NOT_FOUND') throw error;+ console.error('[enterpriseKnowledge] content access resolution failed', error);+ throw new TRPCError({ code: 'NOT_FOUND' });+ }+};diff --git a/apps/server/src/services/knowledgeBase/index.ts b/apps/server/src/services/knowledgeBase/index.tsindex ded68d39579..1cfece43954 100644--- a/apps/server/src/services/knowledgeBase/index.ts+++ b/apps/server/src/services/knowledgeBase/index.ts@@ -20,7 +20,9 @@ import { buildWorkspaceWhere } from '@/database/utils/workspace';import { getServerDefaultFilesConfig } from '@/server/globalConfig';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { DocumentService } from '@/server/services/document';+import { resolveEnterpriseContentScopes } from '@/server/services/enterpriseKnowledge/contentAccess';import { createFtsSearchRepo } from '@/server/services/ftsSearch';+import { assertContentsNotInRestrictedKnowledgeBase } from '@/server/services/knowledgeBaseAccess';export interface FileContentResult {content: string;@@ -102,6 +104,7 @@ export class KnowledgeBaseSearchService {userId: string,workspaceId?: string,callerAgentVisibility?: 'private' | 'public' | null,+ private readonly askerId?: string | null,) {this.serverDB = serverDB;this.userId = userId;@@ -230,6 +233,51 @@ export class KnowledgeBaseSearchService {}async getFileContents(ids: string[]): Promise<FileContentResult[]> {+ await assertContentsNotInRestrictedKnowledgeBase(+ {+ serverDB: this.serverDB,+ userId: this.askerId ?? this.userId,+ workspaceId: this.workspaceId,+ },+ ids,+ );+ const scopes = await resolveEnterpriseContentScopes(+ { serverDB: this.serverDB, userId: this.askerId, workspaceId: this.workspaceId },+ ids,+ );+ // Validate the complete batch before reading or parsing any content.+ if (scopes.size > 0) {+ return (+ await pMap(+ ids,+ (id) => {+ // An enterprise owner's scope applies only to that exact item.+ // Ordinary siblings in a mixed batch stay in the caller's scope.+ const ownerId = scopes.get(id) ?? this.askerId ?? this.userId;+ return new KnowledgeBaseSearchService(+ this.serverDB,+ ownerId,+ undefined,+ this.callerAgentVisibility,+ this.askerId,+ ).readScopedContents([id]);+ },+ { concurrency: 3 },+ )+ ).flat();+ }+ if (this.askerId && this.askerId !== this.userId)+ return new KnowledgeBaseSearchService(+ this.serverDB,+ this.askerId,+ this.workspaceId,+ this.callerAgentVisibility,+ this.askerId,+ ).readScopedContents(ids);+ return this.readScopedContents(ids);+ }++ private async readScopedContents(ids: string[]): Promise<FileContentResult[]> {return pMap(ids,async (id) => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/attachments.ts b/apps/server/src/services/toolExecution/serverRuntimes/attachments.tsindex 5c1e74f7d68..1eb6c0f64bf 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/attachments.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/attachments.ts@@ -21,6 +21,8 @@ export const attachmentsRuntime: ServerRuntimeRegistration = {userId,workspaceId,agentVisibility,+ // A share visitor runs under the agent owner's scope but is not that owner.+ context.agentShareVisitor ? null : userId,);return new AttachmentsExecutionRuntime({diff --git a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.tsindex c47dc006345..ae5b13c8c29 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts@@ -31,6 +31,8 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {userId,workspaceId,agentVisibility,+ // A share visitor runs under the agent owner's scope but is not that owner.+ context.agentShareVisitor ? null : userId,);const agentModel = agentId ? new AgentModel(serverDB, userId, workspaceId) : null;diff --git a/package.json b/package.jsonindex 649a14fb0d7..646d2cfaf76 100644--- a/package.json+++ b/package.json@@ -285,6 +285,7 @@"@lobechat/builtin-tools": "workspace:*","@lobechat/business-config": "workspace:*","@lobechat/business-const": "workspace:*",+ "@lobechat/business-knowledge": "workspace:*","@lobechat/business-model-bank": "workspace:*","@lobechat/business-model-runtime": "workspace:*","@lobechat/canvas": "workspace:*",diff --git a/packages/business/knowledge/package.json b/packages/business/knowledge/package.jsonnew file mode 100644index 00000000000..9a330826732--- /dev/null+++ b/packages/business/knowledge/package.json@@ -0,0 +1,9 @@+{+ "name": "@lobechat/business-knowledge",+ "version": "1.0.0",+ "private": true,+ "exports": {+ ".": "./src/index.ts"+ },+ "main": "./src/index.ts"+}diff --git a/packages/business/knowledge/src/index.ts b/packages/business/knowledge/src/index.tsnew file mode 100644index 00000000000..f70f7e656c4--- /dev/null+++ b/packages/business/knowledge/src/index.ts@@ -0,0 +1,226 @@+/**+ * Distribution seam: enterprise knowledge bases.+ *+ * An enterprise knowledge base is an ordinary personal-scope knowledge base+ * (`knowledge_bases.workspace_id IS NULL`) owned by one member, which a+ * distribution additionally shares with departments and members at a `view`+ * or `edit` level. The open-source build has no such sharing: every function+ * here reports "not an enterprise knowledge base", so behavior is unchanged.+ *+ * `db` is the request-scoped database handle (or a transaction on it).+ */++export type EnterpriseKbGrantLevel = 'edit' | 'view';+export type EnterpriseKbLevel = EnterpriseKbGrantLevel | 'owner';+export type EnterpriseKbPrincipalType = 'department' | 'user';+export type EnterpriseKbEventAction = 'access_updated' | 'created' | 'deleted' | 'transferred';++export type EnterpriseKbErrorCode =+ 'INVALID_PRINCIPAL' | 'NOT_ENABLED' | 'NOT_ENTERPRISE' | 'STALE_VERSION';++export class EnterpriseKbError extends Error {+ code: EnterpriseKbErrorCode;++ constructor(code: EnterpriseKbErrorCode, message?: string) {+ super(message ?? code);+ this.name = 'EnterpriseKbError';+ this.code = code;+ }+}++/** Who performed a change: a back-office administrator or a front-end member. */+export interface EnterpriseKbActor {+ id: string;+ kind: 'admin' | 'member';+ name: string;+}++export interface EnterpriseKbAccess {+ knowledgeBaseId: string;+ level: EnterpriseKbLevel;+ /** `knowledge_bases.user_id` — every row inside the knowledge base carries this user id. */+ ownerId: string;+}++export type EnterpriseKbAccessResolution =+ | { enterprise: false }+ /** `access: null` — an enterprise knowledge base the user may not see. */+ | { access: EnterpriseKbAccess | null; enterprise: true };++export interface EnterpriseKbGrantInput {+ accessLevel: EnterpriseKbGrantLevel;+ principalId: string;+ principalType: EnterpriseKbPrincipalType;+}++export interface EnterpriseKbGrant extends EnterpriseKbGrantInput {+ /** The department or member no longer exists. */+ deleted: boolean;+ /** For a member: the name of their department, when they have one. */+ departmentName?: string | null;+ /** Members covered, sub-departments included; `null` for a member or a deleted principal. */+ memberCount: number | null;+ name: string;+}++export interface EnterpriseKbAccessState {+ grants: EnterpriseKbGrant[];+ version: number;+}++export interface EnterpriseKbEstimate {+ /** Members that would move from `edit` to `view`. */+ downgraded: number;+ edit: number;+ /** Members that have access today and would have none. */+ lost: number;+ /** Distinct members with access, the owner excluded. */+ total: number;+ view: number;+}++export interface EnterpriseKbAccessSummary {+ departmentCount: number;+ /** Granted to the root department, i.e. to every member. */+ everyone: boolean;+ userCount: number;+}++export interface EnterpriseKbDirectory {+ departments: { id: string; memberCount: number; name: string; parentId: string | null }[];+ users: { departmentName: string | null; email: string | null; id: string; name: string }[];+}++export interface EnterpriseKbMember {+ departmentName: string | null;+ disabled: boolean;+ email: string | null;+ id: string;+ name: string;+}++export interface EnterpriseKbEvent {+ action: EnterpriseKbEventAction;+ actor: EnterpriseKbActor;+ /** ISO 8601. */+ createdAt: string;+ detail: Record<string, unknown>;+ id: string;+}++const disabled = (): never => {+ throw new EnterpriseKbError('NOT_ENABLED');+};++export const isEnterpriseKnowledgeEnabled = (): boolean => false;++export const resolveEnterpriseKbAccess = async (+ _db: unknown,+ _userId: string,+ _knowledgeBaseId: string,+): Promise<EnterpriseKbAccessResolution> => ({ enterprise: false });++/** Every enterprise knowledge base the user can see, own ones included. */+export const listAccessibleEnterpriseKbs = async (+ _db: unknown,+ _userId: string,+): Promise<EnterpriseKbAccess[]> => [];++/** The enterprise ones among `knowledgeBaseIds`; all of them when the list is omitted. */+export const listEnterpriseKbIds = async (+ _db: unknown,+ _knowledgeBaseIds?: string[],+): Promise<string[]> => [];++export const markEnterpriseKb = async (+ _db: unknown,+ _params: { actor: EnterpriseKbActor; knowledgeBaseId: string; name: string },+): Promise<void> => disabled();++/** Drops the grants and uploader records; the change log is kept. */+export const unmarkEnterpriseKb = async (+ _db: unknown,+ _params: { actor: EnterpriseKbActor; knowledgeBaseId: string; name: string },+): Promise<void> => disabled();++export const getEnterpriseKbAccessState = async (+ _db: unknown,+ _knowledgeBaseId: string,+): Promise<EnterpriseKbAccessState> => disabled();++/** Replaces the whole grant list. Throws `STALE_VERSION` when `version` is not the stored one. */+export const updateEnterpriseKbAccess = async (+ _db: unknown,+ _params: {+ actor: EnterpriseKbActor;+ grants: EnterpriseKbGrantInput[];+ knowledgeBaseId: string;+ version: number;+ },+): Promise<EnterpriseKbAccessState> => disabled();++/** What `grants` would mean, compared with the stored list. Writes nothing. */+export const estimateEnterpriseKbAccess = async (+ _db: unknown,+ _params: { grants: EnterpriseKbGrantInput[]; knowledgeBaseId: string },+): Promise<EnterpriseKbEstimate> => disabled();++export const summarizeEnterpriseKbAccess = async (+ _db: unknown,+ _knowledgeBaseIds: string[],+): Promise<Record<string, EnterpriseKbAccessSummary>> => ({});++/** All departments; `users` is filled only when `keyword` is given (at most 20). */+export const getEnterpriseKbDirectory = async (+ _db: unknown,+ _params: { keyword?: string },+): Promise<EnterpriseKbDirectory> => disabled();++export const searchEnterpriseKbMembers = async (+ _db: unknown,+ _params: { keyword: string; limit?: number },+): Promise<EnterpriseKbMember[]> => disabled();++export const findEnterpriseKbMember = async (+ _db: unknown,+ _by: { email: string } | { id: string },+): Promise<EnterpriseKbMember | null> => disabled();++/**+ * Bookkeeping for an ownership transfer; the caller moves the rows themselves.+ * Removes the new owner's own grant, optionally grants the previous owner `edit`,+ * bumps the version and records the event.+ */+export const recordEnterpriseKbTransfer = async (+ _db: unknown,+ _params: {+ actor: EnterpriseKbActor;+ fileCount: number;+ fromUserId: string;+ keepPreviousOwnerEdit: boolean;+ knowledgeBaseId: string;+ toUserId: string;+ },+): Promise<void> => disabled();++/** Newest first. */+export const listEnterpriseKbEvents = async (+ _db: unknown,+ _params: { knowledgeBaseId: string; limit?: number },+): Promise<EnterpriseKbEvent[]> => disabled();++/** Remembers who uploaded or created an item (file id or document id). */+export const recordEnterpriseKbItemUploaders = async (+ _db: unknown,+ _items: { actor: EnterpriseKbActor; itemId: string; knowledgeBaseId: string }[],+): Promise<void> => {};++export const getEnterpriseKbItemUploaders = async (+ _db: unknown,+ _itemIds: string[],+): Promise<Record<string, EnterpriseKbActor>> => ({});++export const removeEnterpriseKbItemUploaders = async (+ _db: unknown,+ _itemIds: string[],+): Promise<void> => {};diff --git a/src/app/(backend)/f/[id]/route.ts b/src/app/(backend)/f/[id]/route.tsindex 22aa8340c08..5f55bee59fa 100644--- a/src/app/(backend)/f/[id]/route.ts+++ b/src/app/(backend)/f/[id]/route.ts@@ -1,7 +1,13 @@import debug from 'debug';+import { NextRequest } from 'next/server';import { FileModel } from '@/database/models/file';import { getServerDB } from '@/database/server';+import { createLambdaContext } from '@/libs/trpc/lambda/context';+import {+ resolveEnterpriseContentScopes,+ resolveManagedContentReader,+} from '@/server/services/enterpriseKnowledge/contentAccess';import { FileService } from '@/server/services/file';const log = debug('lobe-file:proxy');@@ -17,10 +23,11 @@ type Params = Promise<{ id: string }>;* - Generate a temporary S3 presigned preview URL* - Return 302 redirect*- * NOTE: This endpoint is intentionally unauthenticated. The proxy URL is+ * Non-enterprise links remain public by id. The proxy URL is* embedded in bare `<img>` tags, download links, and links shared to AI — none* of which can attach auth headers/cookies. Adding `checkAuth` here would break- * every previously-shared `/f/:id` link, so access stays public by id.+ * every previously-shared `/f/:id` link. Distribution-managed enterprise+ * content requires the current authenticated caller's library access.*/export const GET = async (req: Request, segmentData: { params: Params }) => {try {@@ -42,6 +49,21 @@ export const GET = async (req: Request, segmentData: { params: Params }) => {});}+ // Classify with the owner's scope, then authorize the actual request. No+ // storage URL may be created before the enterprise policy has passed.+ try {+ const scopes = await resolveEnterpriseContentScopes({ serverDB: db, userId: file.userId }, [+ id,+ ]);+ if (scopes.has(id)) {+ const reader = resolveManagedContentReader(await createLambdaContext(new NextRequest(req)));+ if (!reader) return new Response('File not found', { status: 404 });+ await resolveEnterpriseContentScopes({ serverDB: db, userId: reader }, [id]);+ }+ } catch {+ return new Response('File not found', { status: 404 });+ }+// Create file service with file owner's userIdconst fileService = new FileService(db, file.userId);