-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathutils.ts
More file actions
389 lines (351 loc) · 10.1 KB
/
Copy pathutils.ts
File metadata and controls
389 lines (351 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import { db } from '@sim/db'
import { document, embedding, knowledgeBase } from '@sim/db/schema'
import { and, eq, isNull } from 'drizzle-orm'
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
interface KnowledgeBaseData {
id: string
userId: string
workspaceId?: string | null
name: string
description?: string | null
tokenCount: number
embeddingModel: string
embeddingDimension: number
chunkingConfig: unknown
deletedAt?: Date | null
createdAt: Date
updatedAt: Date
}
interface DocumentData {
id: string
knowledgeBaseId: string
filename: string
fileUrl: string
fileSize: number
mimeType: string
chunkCount: number
tokenCount: number
characterCount: number
processingStatus: string
processingStartedAt?: Date | null
processingCompletedAt?: Date | null
processingError?: string | null
enabled: boolean
deletedAt?: Date | null
uploadedAt: Date
// Text tags
tag1?: string | null
tag2?: string | null
tag3?: string | null
tag4?: string | null
tag5?: string | null
tag6?: string | null
tag7?: string | null
// Number tags (5 slots)
number1?: number | null
number2?: number | null
number3?: number | null
number4?: number | null
number5?: number | null
// Date tags (2 slots)
date1?: Date | null
date2?: Date | null
// Boolean tags (3 slots)
boolean1?: boolean | null
boolean2?: boolean | null
boolean3?: boolean | null
// Connector fields
connectorId?: string | null
sourceUrl?: string | null
externalId?: string | null
}
interface EmbeddingData {
id: string
knowledgeBaseId: string
documentId: string
chunkIndex: number
chunkHash: string
content: string
contentLength: number
tokenCount: number
embedding?: number[] | null
embeddingModel: string
startOffset: number
endOffset: number
// Text tags
tag1?: string | null
tag2?: string | null
tag3?: string | null
tag4?: string | null
tag5?: string | null
tag6?: string | null
tag7?: string | null
// Number tags (5 slots)
number1?: number | null
number2?: number | null
number3?: number | null
number4?: number | null
number5?: number | null
// Date tags (2 slots)
date1?: Date | null
date2?: Date | null
// Boolean tags (3 slots)
boolean1?: boolean | null
boolean2?: boolean | null
boolean3?: boolean | null
enabled: boolean
createdAt: Date
updatedAt: Date
}
export interface KnowledgeBaseAccessResult {
hasAccess: true
knowledgeBase: Pick<
KnowledgeBaseData,
'id' | 'userId' | 'workspaceId' | 'name' | 'embeddingModel'
>
}
interface KnowledgeBaseAccessDenied {
hasAccess: false
notFound?: boolean
reason?: string
}
export type KnowledgeBaseAccessCheck = KnowledgeBaseAccessResult | KnowledgeBaseAccessDenied
interface DocumentAccessResult {
hasAccess: true
document: DocumentData
knowledgeBase: Pick<
KnowledgeBaseData,
'id' | 'userId' | 'workspaceId' | 'name' | 'embeddingModel'
>
}
interface DocumentAccessDenied {
hasAccess: false
notFound?: boolean
reason: string
}
export type DocumentAccessCheck = DocumentAccessResult | DocumentAccessDenied
interface ChunkAccessResult {
hasAccess: true
chunk: EmbeddingData
document: DocumentData
knowledgeBase: Pick<
KnowledgeBaseData,
'id' | 'userId' | 'workspaceId' | 'name' | 'embeddingModel'
>
}
interface ChunkAccessDenied {
hasAccess: false
notFound?: boolean
reason: string
}
export type ChunkAccessCheck = ChunkAccessResult | ChunkAccessDenied
/**
* Resolve knowledge-base access for a user, gated by read or write permission.
*
* Read (`requireWrite: false`) grants on any workspace permission; write
* (`requireWrite: true`) requires `write`/`admin`. Legacy non-workspace KBs grant
* to the owning user in both modes.
*/
async function resolveKnowledgeBaseAccess(
knowledgeBaseId: string,
userId: string,
requireWrite: boolean
): Promise<KnowledgeBaseAccessCheck> {
const kb = await db
.select({
id: knowledgeBase.id,
userId: knowledgeBase.userId,
workspaceId: knowledgeBase.workspaceId,
name: knowledgeBase.name,
embeddingModel: knowledgeBase.embeddingModel,
})
.from(knowledgeBase)
.where(and(eq(knowledgeBase.id, knowledgeBaseId), isNull(knowledgeBase.deletedAt)))
.limit(1)
if (kb.length === 0) {
return { hasAccess: false, notFound: true }
}
const kbData = kb[0]
if (kbData.workspaceId) {
// Workspace KB: use workspace permissions only
const userPermission = await getUserEntityPermissions(userId, 'workspace', kbData.workspaceId)
const permitted = requireWrite
? userPermission === 'write' || userPermission === 'admin'
: userPermission !== null
return permitted ? { hasAccess: true, knowledgeBase: kbData } : { hasAccess: false }
}
// Legacy non-workspace KB: allow owner access
if (kbData.userId === userId) {
return { hasAccess: true, knowledgeBase: kbData }
}
return { hasAccess: false }
}
/**
* Check if a user has read access to a knowledge base.
*/
export async function checkKnowledgeBaseAccess(
knowledgeBaseId: string,
userId: string
): Promise<KnowledgeBaseAccessCheck> {
return resolveKnowledgeBaseAccess(knowledgeBaseId, userId, false)
}
/**
* Check if a user has write access to a knowledge base.
*
* Write access is granted if:
* 1. KB has a workspace: user has write or admin permissions on that workspace
* 2. KB has no workspace (legacy): user owns the KB directly
*/
export async function checkKnowledgeBaseWriteAccess(
knowledgeBaseId: string,
userId: string
): Promise<KnowledgeBaseAccessCheck> {
return resolveKnowledgeBaseAccess(knowledgeBaseId, userId, true)
}
/**
* Resolve document access within a knowledge base, gated by read or write
* permission on the KB (see {@link resolveKnowledgeBaseAccess}).
*/
async function resolveDocumentAccess(
knowledgeBaseId: string,
documentId: string,
userId: string,
requireWrite: boolean
): Promise<DocumentAccessCheck> {
const kbAccess = await resolveKnowledgeBaseAccess(knowledgeBaseId, userId, requireWrite)
if (!kbAccess.hasAccess) {
return {
hasAccess: false,
notFound: kbAccess.notFound,
reason: kbAccess.notFound ? 'Knowledge base not found' : 'Unauthorized knowledge base access',
}
}
const doc = await db
.select()
.from(document)
.where(
and(
eq(document.id, documentId),
eq(document.knowledgeBaseId, knowledgeBaseId),
eq(document.userExcluded, false),
isNull(document.archivedAt),
isNull(document.deletedAt)
)
)
.limit(1)
if (doc.length === 0) {
return { hasAccess: false, notFound: true, reason: 'Document not found' }
}
return {
hasAccess: true,
document: doc[0] as DocumentData,
knowledgeBase: kbAccess.knowledgeBase!,
}
}
/**
* Check if a user has read access to a document within a knowledge base.
*/
export async function checkDocumentAccess(
knowledgeBaseId: string,
documentId: string,
userId: string
): Promise<DocumentAccessCheck> {
return resolveDocumentAccess(knowledgeBaseId, documentId, userId, false)
}
/**
* Check if a user has write access to a specific document.
* Write access is granted if user has write access to the knowledge base.
*/
export async function checkDocumentWriteAccess(
knowledgeBaseId: string,
documentId: string,
userId: string
): Promise<DocumentAccessCheck> {
return resolveDocumentAccess(knowledgeBaseId, documentId, userId, true)
}
/**
* Resolve chunk access within a document/knowledge base, gated by read or write
* permission on the KB. The document must exist and be fully processed
* (`processingStatus === 'completed'`) before its chunks are accessible.
*/
async function resolveChunkAccess(
knowledgeBaseId: string,
documentId: string,
chunkId: string,
userId: string,
requireWrite: boolean
): Promise<ChunkAccessCheck> {
const kbAccess = await resolveKnowledgeBaseAccess(knowledgeBaseId, userId, requireWrite)
if (!kbAccess.hasAccess) {
return {
hasAccess: false,
notFound: kbAccess.notFound,
reason: kbAccess.notFound ? 'Knowledge base not found' : 'Unauthorized knowledge base access',
}
}
const doc = await db
.select()
.from(document)
.where(
and(
eq(document.id, documentId),
eq(document.knowledgeBaseId, knowledgeBaseId),
eq(document.userExcluded, false),
isNull(document.archivedAt),
isNull(document.deletedAt)
)
)
.limit(1)
if (doc.length === 0) {
return { hasAccess: false, notFound: true, reason: 'Document not found' }
}
const docData = doc[0] as DocumentData
// Chunks are only accessible once the document has finished processing.
if (docData.processingStatus !== 'completed') {
return {
hasAccess: false,
reason: `Document is not ready for access (status: ${docData.processingStatus})`,
}
}
const chunk = await db
.select()
.from(embedding)
.where(and(eq(embedding.id, chunkId), eq(embedding.documentId, documentId)))
.limit(1)
if (chunk.length === 0) {
return { hasAccess: false, notFound: true, reason: 'Chunk not found' }
}
return {
hasAccess: true,
chunk: chunk[0] as EmbeddingData,
document: docData,
knowledgeBase: kbAccess.knowledgeBase!,
}
}
/**
* Check if a user has read access to a chunk within a document and knowledge base.
*/
export async function checkChunkAccess(
knowledgeBaseId: string,
documentId: string,
chunkId: string,
userId: string
): Promise<ChunkAccessCheck> {
return resolveChunkAccess(knowledgeBaseId, documentId, chunkId, userId, false)
}
/**
* Check if a user has write access to a chunk.
*
* Mirrors {@link checkChunkAccess} but requires write/admin on the knowledge
* base's workspace (or KB ownership for legacy KBs), matching the permission
* needed to create chunks. Used for chunk mutation (update and delete) so those
* operations require the same permission as creation rather than read.
*/
export async function checkChunkWriteAccess(
knowledgeBaseId: string,
documentId: string,
chunkId: string,
userId: string
): Promise<ChunkAccessCheck> {
return resolveChunkAccess(knowledgeBaseId, documentId, chunkId, userId, true)
}