Skip to content

🤯 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.

✨ feat(knowledge): per-item access lists in the business knowledge seam, enforced on content reads (#22905)

Mocha5a67c2f463a7
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.ts
index afb1cad5ca9..35d0711e21e 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/knowledgeContentAccess.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/knowledgeContentAccess.integration.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import * as business from '@lobechat/business-knowledge';
+import { eq } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/pglite';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -7,6 +8,7 @@ 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 { resolveEnterpriseContentScopes } from '@/server/services/enterpriseKnowledge/contentAccess';
import { KnowledgeBaseSearchService } from '@/server/services/knowledgeBase';
import { attachmentsRuntime } from '@/server/services/toolExecution/serverRuntimes/attachments';
import { knowledgeBaseRuntime } from '@/server/services/toolExecution/serverRuntimes/knowledgeBase';
@@ -35,6 +37,7 @@ vi.mock('@lobechat/business-knowledge', async (original) => ({
isEnterpriseKnowledgeEnabled: vi.fn(() => false),
listEnterpriseKbIds: vi.fn(),
resolveEnterpriseKbAccess: vi.fn(),
+ resolveEnterpriseKbUserTree: vi.fn(async () => null),
}));
vi.mock('@/server/services/workspacePermission', () => ({
getWorkspaceScopedPermissionMatches: vi.fn(async () => ({
@@ -69,7 +72,12 @@ const enablePolicy = () => {
enterprise: true,
access:
userId === owner || (userId === viewer && knowledgeBaseId === 'content-kb-a')
- ? { knowledgeBaseId, ownerId: owner, level: userId === owner ? 'owner' : 'view' }
+ ? {
+ hasNodePolicies: false,
+ knowledgeBaseId,
+ ownerId: owner,
+ level: userId === owner ? 'owner' : 'view',
+ }
: null,
}),
);
@@ -174,16 +182,321 @@ beforeAll(async () => {
resourceId: 'content-kb-workspace',
accessLevel: 'use',
});
+
+ await db.insert(schema.documents).values(
+ [
+ { id: 'docs_node_root', fileType: 'custom/folder' },
+ { id: 'docs_node_nested', fileType: 'custom/folder', parentId: 'docs_node_root' },
+ { id: 'docs_node_leaf', parentId: 'docs_node_nested', content: 'nested page' },
+ { id: 'docs_node_sibling', content: 'sibling page' },
+ { id: 'docs_node_granted', content: 'granted page' },
+ { id: 'docs_node_page', parentId: 'docs_node_nested', content: 'editable page' },
+ { id: 'docs_node_html', content: 'html page', fileType: 'custom/html' },
+ ].map((doc) => ({
+ fileType: 'custom/document',
+ sourceType: 'api' as const,
+ source: 'test',
+ totalCharCount: 10,
+ totalLineCount: 1,
+ userId: owner,
+ knowledgeBaseId: 'content-kb-a',
+ ...doc,
+ })),
+ );
+ await db.insert(schema.files).values(
+ [
+ { id: 'file_node_nested', parentId: 'docs_node_nested' },
+ { id: 'file_node_page', parentId: null },
+ { id: 'file_node_html', parentId: null },
+ ].map((file) => ({
+ ...file,
+ userId: owner,
+ fileType: 'text/plain',
+ name: `${file.id}.txt`,
+ size: 10,
+ url: `storage/${file.id}`,
+ })),
+ );
+ await db.insert(schema.knowledgeBaseFiles).values(
+ ['file_node_nested', 'file_node_page', 'file_node_html'].map((fileId) => ({
+ fileId,
+ knowledgeBaseId: 'content-kb-a',
+ userId: owner,
+ })),
+ );
+ await db
+ .update(schema.documents)
+ .set({ fileId: 'file_node_page' })
+ .where(eq(schema.documents.id, 'docs_node_page'));
+ await db
+ .update(schema.documents)
+ .set({ fileId: 'file_node_html' })
+ .where(eq(schema.documents.id, 'docs_node_html'));
+ await db.insert(schema.documents).values({
+ id: 'docs_node_mirror',
+ userId: owner,
+ fileId: 'file_node_nested',
+ fileType: 'text/plain',
+ sourceType: 'file',
+ source: 'test',
+ content: 'nested file text',
+ totalCharCount: 10,
+ totalLineCount: 1,
+ });
}, 30000);
afterAll(async () => {
await client?.close();
});
+
+describe('knowledge content node policies', () => {
+ const nodePolicies = (
+ level: business.EnterpriseKbAccessLevel,
+ nodes: business.EnterpriseKbUserTree['nodes'],
+ ) => {
+ enablePolicy();
+ vi.mocked(business.resolveEnterpriseKbAccess).mockResolvedValue({
+ enterprise: true,
+ access: { hasNodePolicies: true, knowledgeBaseId: 'content-kb-a', ownerId: owner, level },
+ });
+ vi.mocked(business.resolveEnterpriseKbUserTree).mockResolvedValue({
+ knowledgeBaseId: 'content-kb-a',
+ ownerId: owner,
+ owner: false,
+ libraryLevel: level === 'view' || level === 'edit' ? level : null,
+ nodes,
+ });
+ };
+
+ it('denies a library viewer excluded by a folder list at both content read entry points', async () => {
+ nodePolicies('view', [{ nodeId: 'docs_node_root', level: null }]);
+ boundary.identity = viewer;
+ for (const id of ['file_node_nested', 'docs_node_mirror']) {
+ await expect(contents(viewer, [id])).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ }
+ for (const download of [false, true]) {
+ expect((await proxy('file_node_nested', download)).status).toBe(404);
+ }
+ expect(boundary.sign).not.toHaveBeenCalled();
+ });
+
+ it('lets a path-only library caller read a separately granted page but not a sibling', async () => {
+ nodePolicies('path', [{ nodeId: 'docs_node_granted', level: 'view' }]);
+ expect((await contents(viewer, ['docs_node_granted']))[0].content).toBe('granted page');
+ await expect(contents(viewer, ['docs_node_sibling'])).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ await expect(contents(viewer, ['docs_node_root'])).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it.each(['view', 'edit'] as const)(
+ 'uses the nearest ancestor grant (%s) for pages and files',
+ async (level) => {
+ nodePolicies('path', [
+ { nodeId: 'docs_node_root', level: null },
+ { nodeId: 'docs_node_nested', level },
+ ]);
+ const result = await contents(viewer, [
+ 'docs_node_leaf',
+ 'file_node_nested',
+ 'docs_node_mirror',
+ ]);
+ expect(result.map((row) => row.content)).toEqual([
+ 'nested page',
+ 'nested file text',
+ 'nested file text',
+ ]);
+ boundary.identity = viewer;
+ expect((await proxy('file_node_nested')).status).toBe(302);
+ await expect(contents(viewer, ['docs_node_sibling'])).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ },
+ );
+
+ it('does not fall back to a more distant ancestor or library grant after a nearer denial', async () => {
+ nodePolicies('view', [
+ { nodeId: 'docs_node_root', level: 'view' },
+ { nodeId: 'docs_node_nested', level: null },
+ ]);
+ await expect(contents(viewer, ['docs_node_leaf', 'file_node_nested'])).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+
+ it('uses the item list before its parent list', async () => {
+ nodePolicies('view', [
+ { nodeId: 'docs_node_root', level: null },
+ { nodeId: 'docs_node_leaf', level: 'edit' },
+ { nodeId: 'file_node_nested', level: 'view' },
+ ]);
+ expect((await contents(viewer, ['docs_node_leaf']))[0].content).toBe('nested page');
+ expect((await contents(viewer, ['file_node_nested']))[0].content).toBe('nested file text');
+ });
+
+ it('makes parsed mirrors follow the file list, ignoring an independent mirror grant', async () => {
+ nodePolicies('view', [
+ { nodeId: 'file_node_nested', level: null },
+ { nodeId: 'docs_node_mirror', level: 'view' },
+ ]);
+ await expect(contents(viewer, ['docs_node_mirror'])).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+
+ it('makes a page backing file follow the page list and its folder location', async () => {
+ nodePolicies('view', [{ nodeId: 'docs_node_nested', level: null }]);
+ boundary.identity = viewer;
+ expect((await proxy('file_node_page')).status).toBe(404);
+ await expect(contents(viewer, ['docs_node_page'])).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ nodePolicies('path', [{ nodeId: 'docs_node_page', level: 'view' }]);
+ expect((await proxy('file_node_page')).status).toBe(302);
+ expect((await contents(viewer, ['docs_node_page']))[0].content).toBe('editable page');
+ });
+
+ it('applies an HTML page list to the page and its backing file, like any authored page', async () => {
+ nodePolicies('view', [{ nodeId: 'docs_node_html', level: null }]);
+ boundary.identity = viewer;
+ expect((await proxy('file_node_html')).status).toBe(404);
+ await expect(contents(viewer, ['docs_node_html'])).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ nodePolicies('path', [{ nodeId: 'docs_node_html', level: 'view' }]);
+ expect((await proxy('file_node_html')).status).toBe(302);
+ expect((await contents(viewer, ['docs_node_html']))[0].content).toBe('html page');
+ });
+
+ it('falls back to the library level only when no node list applies', async () => {
+ nodePolicies('view', [{ nodeId: 'docs_node_root', level: null }]);
+ expect((await contents(viewer, ['docs_node_sibling']))[0].content).toBe('sibling page');
+ });
+
+ it('rechecks node grants on subsequent reads and rejects mixed batches after revocation', async () => {
+ nodePolicies('view', [{ nodeId: 'docs_node_nested', level: 'edit' }]);
+ expect((await contents(viewer, ['docs_node_leaf']))[0].content).toBe('nested page');
+ nodePolicies('view', [{ nodeId: 'docs_node_nested', level: null }]);
+ await expect(contents(viewer, ['docs_node_sibling', 'docs_node_leaf'])).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ boundary.identity = viewer;
+ expect((await proxy('file_node_nested')).status).toBe(404);
+ expect(boundary.sign).not.toHaveBeenCalled();
+ });
+
+ it.each(['deleted', 'cycle', 'outside library', 'non-folder'])(
+ 'denies descendants of an invalid ancestor even with an explicit item grant: %s',
+ async (failure) => {
+ nodePolicies('view', [{ nodeId: 'docs_node_leaf', level: 'edit' }]);
+ await db
+ .update(schema.documents)
+ .set(
+ failure === 'deleted'
+ ? { isDeleted: true }
+ : {
+ parentId:
+ failure === 'cycle'
+ ? 'docs_node_nested'
+ : failure === 'outside library'
+ ? 'docs_content_b'
+ : 'docs_node_sibling',
+ },
+ )
+ .where(eq(schema.documents.id, 'docs_node_root'));
+ try {
+ await expect(contents(viewer, ['docs_node_leaf'])).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ boundary.identity = viewer;
+ expect((await proxy('file_node_nested')).status).toBe(404);
+ expect(boundary.sign).not.toHaveBeenCalled();
+ } finally {
+ await db
+ .update(schema.documents)
+ .set({ isDeleted: false, parentId: null })
+ .where(eq(schema.documents.id, 'docs_node_root'));
+ }
+ },
+ );
+
+ it('preserves full owner access without resolving a node tree', async () => {
+ nodePolicies('owner', [{ nodeId: 'docs_node_root', level: null }]);
+ vi.mocked(business.resolveEnterpriseKbUserTree).mockRejectedValue(new Error('unused'));
+ expect((await contents(owner, ['docs_node_leaf']))[0].content).toBe('nested page');
+ boundary.identity = owner;
+ expect((await proxy('file_node_nested')).status).toBe(302);
+ expect(business.resolveEnterpriseKbUserTree).not.toHaveBeenCalled();
+ });
+
+ it('does not resolve node policies or add queries when the library has none', async () => {
+ enablePolicy();
+ const select = vi.spyOn(db, 'select');
+ try {
+ expect(
+ await resolveEnterpriseContentScopes({ serverDB: db, userId: viewer }, [
+ 'file_node_nested',
+ ]),
+ ).toEqual(new Map([['file_node_nested', owner]]));
+ expect(select).toHaveBeenCalledTimes(2);
+ expect(business.resolveEnterpriseKbUserTree).not.toHaveBeenCalled();
+ } finally {
+ select.mockRestore();
+ }
+ });
+
+ it('keeps the default disabled seam at the original early return with no queries', async () => {
+ const actual = await vi.importActual<typeof business>('@lobechat/business-knowledge');
+ vi.mocked(business.isEnterpriseKnowledgeEnabled).mockImplementation(
+ actual.isEnterpriseKnowledgeEnabled,
+ );
+ const select = vi.spyOn(db, 'select');
+ try {
+ expect(
+ await resolveEnterpriseContentScopes({ serverDB: db, userId: viewer }, [
+ 'file_node_nested',
+ ]),
+ ).toEqual(new Map());
+ expect(select).not.toHaveBeenCalled();
+ expect(business.resolveEnterpriseKbUserTree).not.toHaveBeenCalled();
+ expect(business.resolveEnterpriseKbAccess).not.toHaveBeenCalled();
+ expect(business.listEnterpriseKbIds).not.toHaveBeenCalled();
+ } finally {
+ select.mockRestore();
+ }
+ expect((await contents(owner, ['docs_node_leaf']))[0].content).toBe('nested page');
+ expect((await proxy('file_node_nested')).status).toBe(302);
+ });
+
+ it.each(['missing', 'wrong library', 'wrong owner', 'unexpected owner', 'throws'])(
+ 'fails closed when the node tree is invalid: %s',
+ async (failure) => {
+ nodePolicies('view', []);
+ if (failure === 'missing')
+ vi.mocked(business.resolveEnterpriseKbUserTree).mockResolvedValue(null);
+ else if (failure === 'throws')
+ vi.mocked(business.resolveEnterpriseKbUserTree).mockRejectedValue(
+ new Error('tree unavailable'),
+ );
+ else
+ vi.mocked(business.resolveEnterpriseKbUserTree).mockResolvedValue({
+ knowledgeBaseId: failure === 'wrong library' ? 'content-kb-b' : 'content-kb-a',
+ ownerId: failure === 'wrong owner' ? outsider : owner,
+ owner: failure === 'unexpected owner',
+ libraryLevel: 'view',
+ nodes: [],
+ });
+ await expect(contents(viewer, ['docs_node_leaf'])).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ boundary.identity = viewer;
+ expect((await proxy('file_node_nested')).status).toBe(404);
+ expect(boundary.sign).not.toHaveBeenCalled();
+ },
+ );
+});
beforeEach(() => {
vi.clearAllMocks();
boundary.credential = {};
boundary.identity = undefined;
vi.mocked(business.isEnterpriseKnowledgeEnabled).mockReturnValue(false);
+ vi.mocked(business.resolveEnterpriseKbUserTree).mockResolvedValue(null);
});
describe('knowledge content read boundaries', () => {
@@ -412,7 +725,12 @@ describe('knowledge content read boundaries', () => {
enablePolicy();
vi.mocked(business.resolveEnterpriseKbAccess).mockResolvedValue({
enterprise: true,
- access: { knowledgeBaseId: 'content-kb-a', ownerId: outsider, level: 'view' },
+ access: {
+ hasNodePolicies: false,
+ 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();
diff --git a/apps/server/src/services/enterpriseKnowledge/contentAccess.ts b/apps/server/src/services/enterpriseKnowledge/contentAccess.ts
index 2c2ec9ffbf7..74d2c62ca5b 100644
--- a/apps/server/src/services/enterpriseKnowledge/contentAccess.ts
+++ b/apps/server/src/services/enterpriseKnowledge/contentAccess.ts
@@ -1,11 +1,13 @@
+import type { EnterpriseKbAccess, EnterpriseKbAccessLevel } from '@lobechat/business-knowledge';
import {
isEnterpriseKnowledgeEnabled,
listEnterpriseKbIds,
resolveEnterpriseKbAccess,
+ resolveEnterpriseKbUserTree,
} 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 { and, eq, inArray, isNull, or } from 'drizzle-orm';
import pMap from 'p-map';
import { documents, files, knowledgeBaseFiles, knowledgeBases } from '@/database/schemas';
@@ -39,6 +41,111 @@ interface ContentAccessContext {
workspaceId?: string | null;
}
+/** Load the authoritative directory only for libraries that have node policies. */
+const resolveContentNodeLevels = async (
+ db: LobeChatDatabase,
+ userId: string,
+ access: EnterpriseKbAccess,
+): Promise<Map<string, EnterpriseKbAccessLevel | null>> => {
+ const tree = await resolveEnterpriseKbUserTree(db, userId, access.knowledgeBaseId);
+ if (
+ !tree ||
+ tree.knowledgeBaseId !== access.knowledgeBaseId ||
+ tree.ownerId !== access.ownerId ||
+ tree.owner !== false
+ )
+ throw new Error('Invalid enterprise node tree');
+
+ const fileRows = await db
+ .select({ id: files.id, parentId: files.parentId, isDeleted: files.isDeleted })
+ .from(files)
+ .innerJoin(knowledgeBaseFiles, eq(knowledgeBaseFiles.fileId, files.id))
+ .where(
+ and(
+ eq(knowledgeBaseFiles.knowledgeBaseId, access.knowledgeBaseId),
+ eq(files.userId, access.ownerId),
+ isNull(files.workspaceId),
+ ),
+ );
+ const documentRows = await db
+ .select({
+ id: documents.id,
+ fileId: documents.fileId,
+ fileType: documents.fileType,
+ sourceType: documents.sourceType,
+ parentId: documents.parentId,
+ isDeleted: documents.isDeleted,
+ })
+ .from(documents)
+ .where(
+ and(
+ eq(documents.userId, access.ownerId),
+ isNull(documents.workspaceId),
+ or(
+ eq(documents.knowledgeBaseId, access.knowledgeBaseId),
+ fileRows.length
+ ? inArray(
+ documents.fileId,
+ fileRows.map((row) => row.id),
+ )
+ : undefined,
+ ),
+ ),
+ );
+ // A page authored in the library (markdown, HTML, ...) owns its backing file's location and
+ // policy. Parsed mirrors (`sourceType: 'file'`) instead follow the file, and never become
+ // independent permission nodes.
+ const pageByFile = new Map(
+ documentRows
+ .filter((row) => row.fileId && row.sourceType !== 'file')
+ .map((row) => [row.fileId, row.id]),
+ );
+ const nodes = new Map(
+ [
+ ...fileRows.map((row) => ({ ...row, isFolder: false, aliasOf: pageByFile.get(row.id) })),
+ ...documentRows.map((row) => ({
+ ...row,
+ isFolder: row.fileType === 'custom/folder',
+ aliasOf: row.fileId && pageByFile.get(row.fileId) !== row.id ? row.fileId : undefined,
+ })),
+ ].map((row) => [row.id, row]),
+ );
+ const policies = new Map(tree.nodes.map((row) => [row.nodeId, row.level]));
+ const live = new Map<string, boolean>();
+ const visiting = new Set<string>();
+ const isLive = (id: string): boolean => {
+ if (live.has(id)) return live.get(id)!;
+ const row = nodes.get(id);
+ if (!row || row.isDeleted || visiting.has(id)) return false;
+ visiting.add(id);
+ const valid = row.aliasOf
+ ? isLive(row.aliasOf)
+ : !row.parentId || (nodes.get(row.parentId)?.isFolder === true && isLive(row.parentId));
+ visiting.delete(id);
+ live.set(id, valid);
+ return valid;
+ };
+ const levels = new Map<string, EnterpriseKbAccessLevel | null>();
+ const level = (id: string): EnterpriseKbAccessLevel | null => {
+ if (levels.has(id)) return levels.get(id)!;
+ const row = nodes.get(id);
+ const resolved =
+ !row || !isLive(id)
+ ? null
+ : row.aliasOf
+ ? level(row.aliasOf)
+ : policies.has(id)
+ ? policies.get(id)!
+ : row.parentId
+ ? level(row.parentId)
+ : tree.libraryLevel;
+ levels.set(id, resolved);
+ return resolved;
+ };
+ for (const id of nodes.keys()) level(id);
+ return levels;
+};
+
/**
* 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).
@@ -128,13 +235,25 @@ export const resolveEnterpriseContentScopes = async (
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,
+ async (id) => {
+ const resolution = ctx.userId
+ ? await resolveEnterpriseKbAccess(ctx.serverDB, ctx.userId, id)
+ : { enterprise: true as const, access: null };
+ const library = libraries.find((row) => row.id === id);
+ const access = resolution.enterprise ? resolution.access : null;
+ const valid = !!(
+ access &&
+ library &&
+ !library.isDeleted &&
+ access.knowledgeBaseId === id &&
+ access.ownerId === library.userId
+ );
+ const nodeLevels =
+ valid && access && access.hasNodePolicies && access.level !== 'owner' && ctx.userId
+ ? await resolveContentNodeLevels(ctx.serverDB, ctx.userId, access)
+ : undefined;
+ return [id, { access, valid, nodeLevels }] as const;
+ },
{ concurrency: 10 },
),
);
@@ -148,16 +267,15 @@ export const resolveEnterpriseContentScopes = async (
!item.isDeleted &&
governedIds.some((kbId) => {
const resolution = resolutions.get(kbId);
- const library = libraries.find((row) => row.id === kbId);
return (
- resolution?.enterprise &&
+ resolution?.valid &&
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)
+ resolution.access.ownerId === item.userId &&
+ ['owner', 'edit', 'view'].includes(
+ resolution.nodeLevels
+ ? (resolution.nodeLevels.get(id) ?? '')
+ : resolution.access.level,
+ )
);
});
if (!permitted) throw new TRPCError({ code: 'NOT_FOUND' });
diff --git a/packages/business/knowledge/src/index.ts b/packages/business/knowledge/src/index.ts
index f70f7e656c4..9bbebc335f9 100644
--- a/packages/business/knowledge/src/index.ts
+++ b/packages/business/knowledge/src/index.ts
@@ -13,7 +13,19 @@
export type EnterpriseKbGrantLevel = 'edit' | 'view';
export type EnterpriseKbLevel = EnterpriseKbGrantLevel | 'owner';
export type EnterpriseKbPrincipalType = 'department' | 'user';
-export type EnterpriseKbEventAction = 'access_updated' | 'created' | 'deleted' | 'transferred';
+/**
+ * `path`: the caller holds nothing on this library (or folder) itself, but holds a level on
+ * something below it, so only the way down to those items is visible.
+ */
+export type EnterpriseKbAccessLevel = EnterpriseKbLevel | 'path';
+export type EnterpriseKbEventAction =
+ | 'access_updated'
+ | 'created'
+ | 'deleted'
+ | 'moved_in'
+ | 'moved_out'
+ | 'node_access_updated'
+ | 'transferred';
export type EnterpriseKbErrorCode =
'INVALID_PRINCIPAL' | 'NOT_ENABLED' | 'NOT_ENTERPRISE' | 'STALE_VERSION';
@@ -36,8 +48,13 @@ export interface EnterpriseKbActor {
}
export interface EnterpriseKbAccess {
+ /**
+ * Some folder, page or file in this library has its own grant list. When false the
+ * library level applies to every item and no per-item work is needed.
+ */
+ hasNodePolicies: boolean;
knowledgeBaseId: string;
- level: EnterpriseKbLevel;
+ level: EnterpriseKbAccessLevel;
/** `knowledge_bases.user_id` — every row inside the knowledge base carries this user id. */
ownerId: string;
}
@@ -74,6 +91,11 @@ export interface EnterpriseKbEstimate {
edit: number;
/** Members that have access today and would have none. */
lost: number;
+ /**
+ * Item estimates only: submitted principals that hold nothing on the item's parent, so they
+ * will also see the path down to the item.
+ */
+ pathOnly?: { principalId: string; principalType: EnterpriseKbPrincipalType }[];
/** Distinct members with access, the owner excluded. */
total: number;
view: number;
@@ -137,7 +159,7 @@ export const markEnterpriseKb = async (
_params: { actor: EnterpriseKbActor; knowledgeBaseId: string; name: string },
): Promise<void> => disabled();
-/** Drops the grants and uploader records; the change log is kept. */
+/** Drops the library's and every node's grants and the uploader records; keeps the change log. */
export const unmarkEnterpriseKb = async (
_db: unknown,
_params: { actor: EnterpriseKbActor; knowledgeBaseId: string; name: string },
@@ -209,6 +231,24 @@ export const listEnterpriseKbEvents = async (
_params: { knowledgeBaseId: string; limit?: number },
): Promise<EnterpriseKbEvent[]> => disabled();
+/** One content move event, in the same transaction as copying and deleting the originals. */
+export interface EnterpriseKbContentMoveItem {
+ kind: 'document' | 'file' | 'folder';
+ name: string;
+ sourceId: string;
+ targetId: string;
+}
+
+export const recordEnterpriseKbContentMove = async (
+ _db: unknown,
+ _params: {
+ actor: EnterpriseKbActor;
+ direction: 'in' | 'out';
+ items: EnterpriseKbContentMoveItem[];
+ knowledgeBaseId: string;
+ },
+): Promise<void> => disabled();
+
/** Remembers who uploaded or created an item (file id or document id). */
export const recordEnterpriseKbItemUploaders = async (
_db: unknown,
@@ -224,3 +264,100 @@ export const removeEnterpriseKbItemUploaders = async (
_db: unknown,
_itemIds: string[],
): Promise<void> => {};
+
+/* ---------------------------------------------------------------------------------------------
+ * Folders, pages and files with their own grant list.
+ *
+ * A node is identified by the id the library's content list uses for it: the document id of a
+ * folder or page, the file id of a file. The application owns the tree; every function that
+ * needs to know what a node inherits receives the node's ancestors, nearest first (parent first,
+ * the library itself not included).
+ * ------------------------------------------------------------------------------------------- */
+
+export interface EnterpriseKbUserTree {
+ knowledgeBaseId: string;
+ /** What the library's own list grants the user; `null` when it grants nothing. */
+ libraryLevel: EnterpriseKbGrantLevel | null;
+ /** Every node with its own list, and what that list grants the user (`null` = nothing). */
+ nodes: { level: EnterpriseKbGrantLevel | null; nodeId: string }[];
+ /** The user owns the library: full control everywhere, `libraryLevel` and `nodes` unused. */
+ owner: boolean;
+ ownerId: string;
+}
+
+export interface EnterpriseKbNodeAccessState {
+ /**
+ * `custom`: the node's own list. `inherit`: the list of `inheritedFromNodeId` (the nearest
+ * ancestor with its own list), or of the library when that is `null`; read-only.
+ */
+ grants: EnterpriseKbGrant[];
+ inheritedFromNodeId: string | null;
+ mode: 'custom' | 'inherit';
+ /** Optimistic lock of the node's own list; 0 while the node inherits. */
+ version: number;
+}
+
+/** `null` when the library is not an enterprise knowledge base. Never throws for "no access". */
+export const resolveEnterpriseKbUserTree = async (
+ _db: unknown,
+ _userId: string,
+ _knowledgeBaseId: string,
+): Promise<EnterpriseKbUserTree | null> => null;
+
+/** Nodes of the library that have their own list. */
+export const listEnterpriseKbNodePolicies = async (
+ _db: unknown,
+ _knowledgeBaseId: string,
+): Promise<{ nodeId: string; version: number }[]> => [];
+
+export const getEnterpriseKbNodeAccessState = async (
+ _db: unknown,
+ _params: { ancestorIds: string[]; knowledgeBaseId: string; nodeId: string },
+): Promise<EnterpriseKbNodeAccessState> => disabled();
+
+/**
+ * `custom` replaces the node's own list (created on first save); `inherit` removes it, `grants`
+ * ignored. `version` must equal the stored one (0 while inheriting), else `STALE_VERSION`.
+ * Records a `node_access_updated` event unless nothing changed.
+ */
+export const updateEnterpriseKbNodeAccess = async (
+ _db: unknown,
+ _params: {
+ actor: EnterpriseKbActor;
+ ancestorIds: string[];
+ grants: EnterpriseKbGrantInput[];
+ knowledgeBaseId: string;
+ mode: 'custom' | 'inherit';
+ nodeId: string;
+ nodeKind: 'document' | 'file' | 'folder';
+ nodeName: string;
+ version: number;
+ },
+): Promise<EnterpriseKbNodeAccessState> => disabled();
+
+/** Compared with what the node uses today (its own list or the inherited one). Writes nothing. */
+export const estimateEnterpriseKbNodeAccess = async (
+ _db: unknown,
+ _params: {
+ ancestorIds: string[];
+ grants: EnterpriseKbGrantInput[];
+ knowledgeBaseId: string;
+ mode: 'custom' | 'inherit';
+ nodeId: string;
+ },
+): Promise<EnterpriseKbEstimate> => disabled();
+
+/** Drops the own lists of permanently deleted nodes. No event. */
+export const removeEnterpriseKbNodePolicies = async (
+ _db: unknown,
+ _params: { knowledgeBaseId: string; nodeIds: string[] },
+): Promise<void> => {};
+
+/**
+ * A transfer that had to copy shared rows gives some nodes new ids: move their own lists to
+ * the new ids (same versions, no event). Ids not in the map are left alone.
+ */
+export const remapEnterpriseKbNodePolicies = async (
+ _db: unknown,
+ _params: { idMap: Record<string, string>; knowledgeBaseId: string },
+): Promise<void> => {};