@exulu/backend 5.21.0 → 5.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-43QIPMLT.js → chunk-BFIDSFRQ.js} +132 -0
- package/dist/{chunk-Q4DFJFUI.js → chunk-DAVYWGEE.js} +17 -3
- package/dist/{chunk-YTW26TUA.js → chunk-K7CGLUW4.js} +176 -132
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-4TT2M2JH.js → convert-exulu-tools-to-ai-sdk-tools-XEPIBTZT.js} +2 -2
- package/dist/{doc_processor-VCFQZ5WI.js → doc_processor-SR7ZCECL.js} +2 -2
- package/dist/index.cjs +844 -214
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +550 -105
- package/ee/python/documents/processing/doc_processor.presentations.test.ts +55 -0
- package/ee/python/documents/processing/doc_processor.ts +17 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "dotenv/config";
|
|
2
2
|
import {
|
|
3
3
|
documentProcessor
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-DAVYWGEE.js";
|
|
5
5
|
import {
|
|
6
6
|
getPackageRoot,
|
|
7
7
|
getPythonSetupInstructions,
|
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
EDGE_LIMIT_DEFAULT,
|
|
30
30
|
EDGE_LIMIT_MAX,
|
|
31
31
|
EDGE_QUERY_TERMS,
|
|
32
|
+
EXTERNAL_SUPER_ADMIN_ONLY,
|
|
32
33
|
ExuluContext,
|
|
33
34
|
ExuluStorage,
|
|
34
35
|
ExuluTokenizer,
|
|
@@ -74,6 +75,7 @@ import {
|
|
|
74
75
|
UMAP_NEIGHBORS,
|
|
75
76
|
VALID_RIGHTS_MODES,
|
|
76
77
|
VIEW_DOCUMENT_PAGE_TOOL_NAME,
|
|
78
|
+
agentAllowsGuestFiles,
|
|
77
79
|
applyAccessControl,
|
|
78
80
|
applyFilters,
|
|
79
81
|
applyFiltersGrouped,
|
|
@@ -137,6 +139,8 @@ import {
|
|
|
137
139
|
estimateMessageTokens,
|
|
138
140
|
estimateTokens,
|
|
139
141
|
exchangeCodeForTokens,
|
|
142
|
+
externalAccessCheckApplies,
|
|
143
|
+
externalAccessNeedsTeams,
|
|
140
144
|
extractClientInfo,
|
|
141
145
|
extractDocument,
|
|
142
146
|
exuluApp,
|
|
@@ -164,9 +168,13 @@ import {
|
|
|
164
168
|
getTableName,
|
|
165
169
|
getToken,
|
|
166
170
|
guardExtractedFileText,
|
|
171
|
+
guestFileTooLarge,
|
|
172
|
+
guestFilesEnabled,
|
|
173
|
+
guestUploadRefusal,
|
|
167
174
|
handleRBACUpdate,
|
|
168
175
|
hasAgentsReadAccess,
|
|
169
176
|
hasAgentsWriteAccess,
|
|
177
|
+
hasCompanionWriteGrant,
|
|
170
178
|
hasProjectAccess,
|
|
171
179
|
hashSharePassword,
|
|
172
180
|
hydrateContextEmbedders,
|
|
@@ -177,6 +185,7 @@ import {
|
|
|
177
185
|
isExternalOrAnonymousUser,
|
|
178
186
|
isInterimToolStatus,
|
|
179
187
|
isPreviewRequest,
|
|
188
|
+
isProjectKey,
|
|
180
189
|
isPublicSurface,
|
|
181
190
|
isRunSessionMetadata,
|
|
182
191
|
l2normalize,
|
|
@@ -185,7 +194,10 @@ import {
|
|
|
185
194
|
loadSessionFileListing,
|
|
186
195
|
mapStreamErrorMessage,
|
|
187
196
|
mapType,
|
|
197
|
+
mayChangeExternalRelease,
|
|
198
|
+
mayReadGenericS3Key,
|
|
188
199
|
mayResignStoredFileKey,
|
|
200
|
+
mayUseGenericS3Route,
|
|
189
201
|
maybePruneJobResults,
|
|
190
202
|
meanVector,
|
|
191
203
|
microCall,
|
|
@@ -247,6 +259,7 @@ import {
|
|
|
247
259
|
shouldShowSourcesToUser,
|
|
248
260
|
sliceHistoryAtCheckpoint,
|
|
249
261
|
slugifyShareName,
|
|
262
|
+
teamNamesByIds,
|
|
250
263
|
treatAsGuest,
|
|
251
264
|
truncateToolOutput,
|
|
252
265
|
updateStatistic,
|
|
@@ -255,6 +268,8 @@ import {
|
|
|
255
268
|
userIdOf,
|
|
256
269
|
validateAttachmentsConfig,
|
|
257
270
|
validateCreateInput,
|
|
271
|
+
validateExternalAccess,
|
|
272
|
+
validateExternalAccessUpdate,
|
|
258
273
|
validateUpdateInput,
|
|
259
274
|
vectorSearch,
|
|
260
275
|
verifyCredentialNonce,
|
|
@@ -264,7 +279,7 @@ import {
|
|
|
264
279
|
willEmbedOnQueue,
|
|
265
280
|
withRunSession,
|
|
266
281
|
workflowTemplatesSchema
|
|
267
|
-
} from "./chunk-
|
|
282
|
+
} from "./chunk-K7CGLUW4.js";
|
|
268
283
|
import {
|
|
269
284
|
LITELLM_UI_PATH,
|
|
270
285
|
ResolveModelError,
|
|
@@ -291,7 +306,7 @@ import {
|
|
|
291
306
|
tagInfo,
|
|
292
307
|
upsertBudget,
|
|
293
308
|
waitForLiteLLMReady
|
|
294
|
-
} from "./chunk-
|
|
309
|
+
} from "./chunk-BFIDSFRQ.js";
|
|
295
310
|
import {
|
|
296
311
|
findLiteLLMModel
|
|
297
312
|
} from "./chunk-F534XOQR.js";
|
|
@@ -413,6 +428,151 @@ async function redisClient() {
|
|
|
413
428
|
// src/exulu/app/index.ts
|
|
414
429
|
import "express";
|
|
415
430
|
|
|
431
|
+
// src/exulu/companion/operation-guard.ts
|
|
432
|
+
import {
|
|
433
|
+
GraphQLError,
|
|
434
|
+
Kind
|
|
435
|
+
} from "graphql";
|
|
436
|
+
var companionAllowedOperations = (tables) => {
|
|
437
|
+
const allowed = /* @__PURE__ */ new Set();
|
|
438
|
+
for (const table of tables) {
|
|
439
|
+
const plural = table.name.plural.toLowerCase();
|
|
440
|
+
const singular = table.name.singular.toLowerCase();
|
|
441
|
+
allowed.add(`${plural}Pagination`);
|
|
442
|
+
allowed.add(`${singular}ById`);
|
|
443
|
+
allowed.add(`${plural}UpdateOneById`);
|
|
444
|
+
}
|
|
445
|
+
return allowed;
|
|
446
|
+
};
|
|
447
|
+
var fieldNamesOf = (operation, document) => {
|
|
448
|
+
const fragments = /* @__PURE__ */ new Map();
|
|
449
|
+
for (const def of document.definitions) {
|
|
450
|
+
if (def.kind === Kind.FRAGMENT_DEFINITION) fragments.set(def.name.value, def.selectionSet);
|
|
451
|
+
}
|
|
452
|
+
const names = [];
|
|
453
|
+
const seen = /* @__PURE__ */ new Set();
|
|
454
|
+
const walk = (set) => {
|
|
455
|
+
for (const selection of set.selections) {
|
|
456
|
+
if (selection.kind === Kind.FIELD) names.push(selection.name.value);
|
|
457
|
+
else if (selection.kind === Kind.INLINE_FRAGMENT) walk(selection.selectionSet);
|
|
458
|
+
else {
|
|
459
|
+
const name = selection.name.value;
|
|
460
|
+
const fragment = fragments.get(name);
|
|
461
|
+
if (fragment && !seen.has(name)) {
|
|
462
|
+
seen.add(name);
|
|
463
|
+
walk(fragment);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
};
|
|
468
|
+
walk(operation.selectionSet);
|
|
469
|
+
return names;
|
|
470
|
+
};
|
|
471
|
+
var companionOperationGuard = (allowed) => ({
|
|
472
|
+
async requestDidStart() {
|
|
473
|
+
return {
|
|
474
|
+
async didResolveOperation({ contextValue, document, operation }) {
|
|
475
|
+
if (!contextValue?.user?.via_companion) return;
|
|
476
|
+
const names = operation ? fieldNamesOf(operation, document) : [];
|
|
477
|
+
const permitted = names.length > 0 && names.every((name) => name === "__typename" || allowed.has(name));
|
|
478
|
+
if (!permitted) {
|
|
479
|
+
throw new GraphQLError("This operation is not available through the companion server.", {
|
|
480
|
+
extensions: { code: "FORBIDDEN", http: { status: 403 } }
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
// src/exulu/companion/request.ts
|
|
489
|
+
import { timingSafeEqual } from "crypto";
|
|
490
|
+
import { GraphQLError as GraphQLError2 } from "graphql";
|
|
491
|
+
|
|
492
|
+
// src/exulu/external-rate-limit.ts
|
|
493
|
+
var MINUTE_MS = 6e4;
|
|
494
|
+
var HOUR_MS = 36e5;
|
|
495
|
+
var perMinuteLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_MINUTE || "30", 10);
|
|
496
|
+
var perHourLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_HOUR || "300", 10);
|
|
497
|
+
var windows = /* @__PURE__ */ new Map();
|
|
498
|
+
var externalRateLimitExceeded = (userId, now = Date.now()) => {
|
|
499
|
+
const state = windows.get(userId) ?? {
|
|
500
|
+
minuteStart: now,
|
|
501
|
+
minuteCount: 0,
|
|
502
|
+
hourStart: now,
|
|
503
|
+
hourCount: 0,
|
|
504
|
+
lastSeen: now
|
|
505
|
+
};
|
|
506
|
+
if (now - state.minuteStart >= MINUTE_MS) {
|
|
507
|
+
state.minuteStart = now;
|
|
508
|
+
state.minuteCount = 0;
|
|
509
|
+
}
|
|
510
|
+
if (now - state.hourStart >= HOUR_MS) {
|
|
511
|
+
state.hourStart = now;
|
|
512
|
+
state.hourCount = 0;
|
|
513
|
+
}
|
|
514
|
+
state.minuteCount += 1;
|
|
515
|
+
state.hourCount += 1;
|
|
516
|
+
state.lastSeen = now;
|
|
517
|
+
windows.set(userId, state);
|
|
518
|
+
if (windows.size > 1e4) {
|
|
519
|
+
for (const [key, value] of windows) {
|
|
520
|
+
if (now - value.lastSeen >= HOUR_MS) windows.delete(key);
|
|
521
|
+
}
|
|
522
|
+
if (windows.size > 1e4) {
|
|
523
|
+
const sorted = [...windows.entries()].sort(
|
|
524
|
+
(a, b) => a[1].lastSeen - b[1].lastSeen
|
|
525
|
+
);
|
|
526
|
+
for (const [key] of sorted) {
|
|
527
|
+
if (windows.size <= 1e4) break;
|
|
528
|
+
windows.delete(key);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
const minuteLimitExceeded = state.minuteCount > perMinuteLimit();
|
|
533
|
+
const hourLimitExceeded = state.hourCount > perHourLimit();
|
|
534
|
+
const limitExceeded = minuteLimitExceeded || hourLimitExceeded;
|
|
535
|
+
if (limitExceeded) {
|
|
536
|
+
const limits = {
|
|
537
|
+
perMinute: perMinuteLimit(),
|
|
538
|
+
perHour: perHourLimit()
|
|
539
|
+
};
|
|
540
|
+
const current = {
|
|
541
|
+
minute: state.minuteCount,
|
|
542
|
+
hour: state.hourCount
|
|
543
|
+
};
|
|
544
|
+
console.warn(
|
|
545
|
+
`[EXULU] Rate limit exceeded for user ${userId}${minuteLimitExceeded ? ` per-minute (${current.minute}/${limits.perMinute})` : ""}${minuteLimitExceeded && hourLimitExceeded ? " and" : ""}${hourLimitExceeded ? ` per-hour (${current.hour}/${limits.perHour})` : ""}`
|
|
546
|
+
);
|
|
547
|
+
}
|
|
548
|
+
return limitExceeded;
|
|
549
|
+
};
|
|
550
|
+
var isExternalUser = (user) => {
|
|
551
|
+
return user?.role?.name === "external";
|
|
552
|
+
};
|
|
553
|
+
|
|
554
|
+
// src/exulu/companion/request.ts
|
|
555
|
+
var COMPANION_HEADER = "x-exulu-companion";
|
|
556
|
+
var companionRequestState = (headers, env = process.env) => {
|
|
557
|
+
const received = headers[COMPANION_HEADER];
|
|
558
|
+
if (received === void 0) return "absent";
|
|
559
|
+
const expected = env.EXULU_COMPANION_KEY;
|
|
560
|
+
if (typeof received !== "string" || received === "" || !expected) return "invalid";
|
|
561
|
+
const a = Buffer.from(received);
|
|
562
|
+
const b = Buffer.from(expected);
|
|
563
|
+
if (a.length !== b.length) return "invalid";
|
|
564
|
+
return timingSafeEqual(a, b) ? "valid" : "invalid";
|
|
565
|
+
};
|
|
566
|
+
var forbidden = (message) => new GraphQLError2(message, { extensions: { code: "FORBIDDEN", http: { status: 403 } } });
|
|
567
|
+
var admitCompanionUser = (state, user) => {
|
|
568
|
+
if (state === "absent") return user;
|
|
569
|
+
if (state === "invalid") throw forbidden("Companion key rejected.");
|
|
570
|
+
if (user.super_admin || !isExternalUser(user)) {
|
|
571
|
+
throw forbidden("This account cannot be used through the companion server.");
|
|
572
|
+
}
|
|
573
|
+
return { ...user, via_companion: true };
|
|
574
|
+
};
|
|
575
|
+
|
|
416
576
|
// src/exulu/routes.ts
|
|
417
577
|
import "express";
|
|
418
578
|
|
|
@@ -999,7 +1159,7 @@ function createQueueMutationResolvers(deps) {
|
|
|
999
1159
|
import { v4 as uuidv43 } from "uuid";
|
|
1000
1160
|
|
|
1001
1161
|
// src/graphql/types/index.ts
|
|
1002
|
-
import { GraphQLScalarType, Kind } from "graphql";
|
|
1162
|
+
import { GraphQLScalarType, Kind as Kind2 } from "graphql";
|
|
1003
1163
|
var GraphQLDate = new GraphQLScalarType({
|
|
1004
1164
|
name: "Date",
|
|
1005
1165
|
description: "Date custom scalar type",
|
|
@@ -1025,10 +1185,10 @@ var GraphQLDate = new GraphQLScalarType({
|
|
|
1025
1185
|
return value;
|
|
1026
1186
|
},
|
|
1027
1187
|
parseLiteral(ast) {
|
|
1028
|
-
if (ast.kind ===
|
|
1188
|
+
if (ast.kind === Kind2.STRING) {
|
|
1029
1189
|
return new Date(ast.value);
|
|
1030
1190
|
}
|
|
1031
|
-
if (ast.kind ===
|
|
1191
|
+
if (ast.kind === Kind2.INT) {
|
|
1032
1192
|
return new Date(parseInt(ast.value, 10));
|
|
1033
1193
|
}
|
|
1034
1194
|
return null;
|
|
@@ -1100,6 +1260,12 @@ var contextItemsProcessorHandler = async (context, config, items, user, role) =>
|
|
|
1100
1260
|
};
|
|
1101
1261
|
};
|
|
1102
1262
|
|
|
1263
|
+
// src/graphql/schemas/rbac-field.ts
|
|
1264
|
+
var resolveRbacField = async (table, parent, context) => {
|
|
1265
|
+
if (context.user?.via_companion === true) return null;
|
|
1266
|
+
return RBACResolver(context.db, table.name.singular, parent.id, parent.rights_mode);
|
|
1267
|
+
};
|
|
1268
|
+
|
|
1103
1269
|
// src/graphql/utilities/provider-fields.ts
|
|
1104
1270
|
var exuluProviderFields = [
|
|
1105
1271
|
"providerName",
|
|
@@ -1113,6 +1279,64 @@ var exuluProviderFields = [
|
|
|
1113
1279
|
"systemInstructions"
|
|
1114
1280
|
];
|
|
1115
1281
|
|
|
1282
|
+
// src/graphql/resolvers/chunk-source-document.ts
|
|
1283
|
+
function chunkWithItemQuery(db, table, contextId, user, chunkId, itemColumns = []) {
|
|
1284
|
+
const query = db(getChunksTableName(contextId) + " as chunks").select([
|
|
1285
|
+
"chunks.id as chunk_id",
|
|
1286
|
+
"chunks.source as chunk_source",
|
|
1287
|
+
"chunks.content as chunk_content",
|
|
1288
|
+
"chunks.chunk_index",
|
|
1289
|
+
"chunks.metadata as chunk_metadata",
|
|
1290
|
+
db.raw('chunks."createdAt" as chunk_created_at'),
|
|
1291
|
+
db.raw('chunks."updatedAt" as chunk_updated_at'),
|
|
1292
|
+
"items.id as item_id",
|
|
1293
|
+
"items.name as item_name",
|
|
1294
|
+
"items.external_id as item_external_id",
|
|
1295
|
+
db.raw('items."updatedAt" as item_updated_at'),
|
|
1296
|
+
db.raw('items."createdAt" as item_created_at'),
|
|
1297
|
+
...itemColumns.map((column) => `items.${column} as item_file_${column}`)
|
|
1298
|
+
]).join(getTableName(contextId) + " as items", "chunks.source", "items.id").where("chunks.id", chunkId);
|
|
1299
|
+
return applyAccessControl(table, query, user, "items").first();
|
|
1300
|
+
}
|
|
1301
|
+
function fileKeyColumns(fields) {
|
|
1302
|
+
return (fields ?? []).filter((field) => field.type === "file").map((field) => field.name.endsWith("_s3key") ? field.name : `${field.name}_s3key`);
|
|
1303
|
+
}
|
|
1304
|
+
function pickSourceDocumentKey(metadata, itemFileKeys) {
|
|
1305
|
+
if (!metadata || typeof metadata !== "object") return void 0;
|
|
1306
|
+
const { pdf, document } = metadata;
|
|
1307
|
+
const stored = new Set(itemFileKeys.filter((k) => typeof k === "string" && k !== ""));
|
|
1308
|
+
return [pdf, document].find((k) => typeof k === "string" && stored.has(k));
|
|
1309
|
+
}
|
|
1310
|
+
async function chunkSourceDocument(deps) {
|
|
1311
|
+
const columns = fileKeyColumns(deps.context.fields);
|
|
1312
|
+
if (columns.length === 0) return null;
|
|
1313
|
+
const row = await chunkWithItemQuery(
|
|
1314
|
+
deps.db,
|
|
1315
|
+
deps.table,
|
|
1316
|
+
deps.context.id,
|
|
1317
|
+
deps.user,
|
|
1318
|
+
deps.chunkId,
|
|
1319
|
+
columns
|
|
1320
|
+
);
|
|
1321
|
+
if (!row) return null;
|
|
1322
|
+
const stored = pickSourceDocumentKey(
|
|
1323
|
+
row.chunk_metadata,
|
|
1324
|
+
columns.map((column) => row[`item_file_${column}`])
|
|
1325
|
+
);
|
|
1326
|
+
if (!stored) return null;
|
|
1327
|
+
const slash = stored.indexOf("/");
|
|
1328
|
+
if (slash <= 0) return null;
|
|
1329
|
+
const bucket = stored.slice(0, slash);
|
|
1330
|
+
const key = stored.slice(slash + 1);
|
|
1331
|
+
if (!key || isDerivedKey(key, deps.s3prefix) || isProjectKey(key, deps.s3prefix)) return null;
|
|
1332
|
+
const page = Number.parseInt(String(row.chunk_metadata?.page ?? ""), 10);
|
|
1333
|
+
return {
|
|
1334
|
+
url: await deps.sign(bucket, key),
|
|
1335
|
+
filename: key.slice(key.lastIndexOf("/") + 1),
|
|
1336
|
+
page: Number.isFinite(page) && page > 0 ? page : null
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1116
1340
|
// src/graphql/utilities/budget-field.ts
|
|
1117
1341
|
var BUDGET_ENTITY_SINGULARS = /* @__PURE__ */ new Set([
|
|
1118
1342
|
"user",
|
|
@@ -1511,7 +1735,7 @@ var sanitizeRequestedFields = (table, requestedFields) => {
|
|
|
1511
1735
|
}
|
|
1512
1736
|
return requestedFields;
|
|
1513
1737
|
};
|
|
1514
|
-
function createQueries(table, tools, contexts) {
|
|
1738
|
+
function createQueries(table, tools, contexts, config) {
|
|
1515
1739
|
const tableNamePlural = table.name.plural.toLowerCase();
|
|
1516
1740
|
const tableNameSingular = table.name.singular.toLowerCase();
|
|
1517
1741
|
const queries = {
|
|
@@ -1760,23 +1984,7 @@ function createQueries(table, tools, contexts) {
|
|
|
1760
1984
|
if (!exists) {
|
|
1761
1985
|
throw new Error("Context " + table.id + " not found in registry.");
|
|
1762
1986
|
}
|
|
1763
|
-
const
|
|
1764
|
-
const chunksTable = getChunksTableName(exists.id);
|
|
1765
|
-
const mainTable = getTableName(exists.id);
|
|
1766
|
-
const chunk2 = await db(chunksTable + " as chunks").select([
|
|
1767
|
-
"chunks.id as chunk_id",
|
|
1768
|
-
"chunks.source as chunk_source",
|
|
1769
|
-
"chunks.content as chunk_content",
|
|
1770
|
-
"chunks.chunk_index",
|
|
1771
|
-
"chunks.metadata as chunk_metadata",
|
|
1772
|
-
db.raw('chunks."createdAt" as chunk_created_at'),
|
|
1773
|
-
db.raw('chunks."updatedAt" as chunk_updated_at'),
|
|
1774
|
-
"items.id as item_id",
|
|
1775
|
-
"items.name as item_name",
|
|
1776
|
-
"items.external_id as item_external_id",
|
|
1777
|
-
db.raw('items."updatedAt" as item_updated_at'),
|
|
1778
|
-
db.raw('items."createdAt" as item_created_at')
|
|
1779
|
-
]).leftJoin(mainTable + " as items", "chunks.source", "items.id").where("chunks.id", args.id).first();
|
|
1987
|
+
const chunk2 = await chunkWithItemQuery(context.db, table, exists.id, context.user, args.id);
|
|
1780
1988
|
if (!chunk2) {
|
|
1781
1989
|
return null;
|
|
1782
1990
|
}
|
|
@@ -1795,6 +2003,24 @@ function createQueries(table, tools, contexts) {
|
|
|
1795
2003
|
item_created_at: chunk2.item_created_at
|
|
1796
2004
|
};
|
|
1797
2005
|
};
|
|
2006
|
+
queries[`${tableNameSingular}ChunkSourceDocument`] = async (_, args, context) => {
|
|
2007
|
+
const exists = contexts.find((ctx) => ctx.id === table.id);
|
|
2008
|
+
if (!exists) {
|
|
2009
|
+
throw new Error("Context " + table.id + " not found in registry.");
|
|
2010
|
+
}
|
|
2011
|
+
if (!config?.fileUploads) {
|
|
2012
|
+
return null;
|
|
2013
|
+
}
|
|
2014
|
+
return await chunkSourceDocument({
|
|
2015
|
+
db: context.db,
|
|
2016
|
+
table,
|
|
2017
|
+
context: exists,
|
|
2018
|
+
user: context.user,
|
|
2019
|
+
chunkId: args.id,
|
|
2020
|
+
s3prefix: config.fileUploads.s3prefix,
|
|
2021
|
+
sign: (bucket, key) => getPresignedUrl(bucket, key, config)
|
|
2022
|
+
});
|
|
2023
|
+
};
|
|
1798
2024
|
}
|
|
1799
2025
|
return queries;
|
|
1800
2026
|
}
|
|
@@ -1820,6 +2046,28 @@ async function getJobsByQueueName(queueName, statusses, page, limit) {
|
|
|
1820
2046
|
};
|
|
1821
2047
|
}
|
|
1822
2048
|
|
|
2049
|
+
// src/exulu/item-file-keys.ts
|
|
2050
|
+
function unreadableFileKeyColumns(input, user, s3prefix) {
|
|
2051
|
+
const caller = user ?? {};
|
|
2052
|
+
return Object.entries(input).filter(([column, value]) => column.endsWith("_s3key") && typeof value === "string" && value !== "").filter(([, value]) => {
|
|
2053
|
+
const stored = value;
|
|
2054
|
+
const key = stored.slice(stored.indexOf("/") + 1);
|
|
2055
|
+
if (!stored.includes("/") || !key) return true;
|
|
2056
|
+
return !mayUseGenericS3Route(key, caller, s3prefix) || !mayReadGenericS3Key(key, caller, s3prefix);
|
|
2057
|
+
}).map(([column]) => column);
|
|
2058
|
+
}
|
|
2059
|
+
async function assertItemFileKeysReadable(deps) {
|
|
2060
|
+
const flagged = unreadableFileKeyColumns(deps.input, deps.user, deps.s3prefix);
|
|
2061
|
+
if (flagged.length === 0) return;
|
|
2062
|
+
const existing = await deps.loadExisting();
|
|
2063
|
+
const refused = flagged.filter((column) => existing?.[column] !== deps.input[column]);
|
|
2064
|
+
if (refused.length > 0) {
|
|
2065
|
+
throw new Error(
|
|
2066
|
+
`Not allowed to attach the file in ${refused.join(", ")}: it is not one of your own uploads or a shared file.`
|
|
2067
|
+
);
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
|
|
1823
2071
|
// src/auth/generate-key.ts
|
|
1824
2072
|
import bcrypt from "bcryptjs";
|
|
1825
2073
|
var SALT_ROUNDS = 12;
|
|
@@ -2827,7 +3075,8 @@ var publicAgentView = (row, slug) => ({
|
|
|
2827
3075
|
guest_auth_mode: row.guest_auth_mode || "regular",
|
|
2828
3076
|
guest_has_cover: !!row.guest_cover_image,
|
|
2829
3077
|
guest_has_idle_animation: !!row.animation_idle,
|
|
2830
|
-
guest_has_responding_animation: !!row.animation_responding
|
|
3078
|
+
guest_has_responding_animation: !!row.animation_responding,
|
|
3079
|
+
guest_files_enabled: guestFilesEnabled(row)
|
|
2831
3080
|
});
|
|
2832
3081
|
var evaluateGuestChatAccess = async (agent, userId, guestPassword) => {
|
|
2833
3082
|
if (agent.guest_access) {
|
|
@@ -4182,6 +4431,12 @@ function createMutations(table, contexts, tools, config) {
|
|
|
4182
4431
|
const validateWriteAccess = async (id, context) => {
|
|
4183
4432
|
try {
|
|
4184
4433
|
const { db, user } = context;
|
|
4434
|
+
if (user.via_companion === true) {
|
|
4435
|
+
const row = table.RBAC === true ? await db.from(tableNamePlural).select(["rights_mode"]).where({ id }).first() : void 0;
|
|
4436
|
+
const grant = !!row && await hasCompanionWriteGrant(db, table.name.singular, id, user, row.rights_mode);
|
|
4437
|
+
if (grant) return true;
|
|
4438
|
+
throw new Error("Insufficient permissions to edit this record");
|
|
4439
|
+
}
|
|
4185
4440
|
if (user.super_admin === true) {
|
|
4186
4441
|
return true;
|
|
4187
4442
|
}
|
|
@@ -4344,6 +4599,20 @@ function createMutations(table, contexts, tools, config) {
|
|
|
4344
4599
|
if (table.name.singular === "user" && context.user?.super_admin !== true) {
|
|
4345
4600
|
throw new Error("You are not authorized to create users");
|
|
4346
4601
|
}
|
|
4602
|
+
if (table.type === "items") {
|
|
4603
|
+
await assertItemFileKeysReadable({
|
|
4604
|
+
input,
|
|
4605
|
+
user: context.user,
|
|
4606
|
+
s3prefix: config?.fileUploads?.s3prefix,
|
|
4607
|
+
// An upsert may land on an existing row, whose stored keys stay valid.
|
|
4608
|
+
loadExisting: async () => {
|
|
4609
|
+
if (!args.upsert) return null;
|
|
4610
|
+
if (input.id) return db.from(tableNamePlural).where({ id: input.id }).first();
|
|
4611
|
+
if (input.external_id) return db.from(tableNamePlural).where({ external_id: input.external_id }).first();
|
|
4612
|
+
return null;
|
|
4613
|
+
}
|
|
4614
|
+
});
|
|
4615
|
+
}
|
|
4347
4616
|
if (table.name.singular === "user" && input.email) {
|
|
4348
4617
|
input.email = String(input.email).trim().toLowerCase();
|
|
4349
4618
|
}
|
|
@@ -4446,6 +4715,14 @@ function createMutations(table, contexts, tools, config) {
|
|
|
4446
4715
|
throw new Error("Record not found");
|
|
4447
4716
|
}
|
|
4448
4717
|
await validateWriteAccess(item.id, context);
|
|
4718
|
+
if (table.type === "items") {
|
|
4719
|
+
await assertItemFileKeysReadable({
|
|
4720
|
+
input,
|
|
4721
|
+
user: context.user,
|
|
4722
|
+
s3prefix: config?.fileUploads?.s3prefix,
|
|
4723
|
+
loadExisting: () => db.from(tableNamePlural).where({ id: item.id }).first()
|
|
4724
|
+
});
|
|
4725
|
+
}
|
|
4449
4726
|
const existingRow = args.merge?.length ? await db.from(tableNamePlural).where({ id: item.id }).first() : null;
|
|
4450
4727
|
const prepared = prepareItemWrite({
|
|
4451
4728
|
fields: table.fields,
|
|
@@ -4510,8 +4787,24 @@ function createMutations(table, contexts, tools, config) {
|
|
|
4510
4787
|
[`${tableNamePlural}UpdateOneById`]: async (_, args, context, info) => {
|
|
4511
4788
|
const { db, req } = context;
|
|
4512
4789
|
let { id, input } = args;
|
|
4790
|
+
if (context.user?.via_companion === true && ["rights_mode", "RBAC", "created_by", "id"].some(
|
|
4791
|
+
(key) => Object.prototype.hasOwnProperty.call(input ?? {}, key)
|
|
4792
|
+
)) {
|
|
4793
|
+
throw new Error("Access rights of a row cannot be changed through the companion server.");
|
|
4794
|
+
}
|
|
4795
|
+
if (context.user?.via_companion === true && args.generateEmbeddings === true) {
|
|
4796
|
+
throw new Error("Embedding generation cannot be requested through the companion server.");
|
|
4797
|
+
}
|
|
4513
4798
|
await validateCreateOrRemoveSuperAdminPermission(tableNamePlural, input, req);
|
|
4514
4799
|
await validateWriteAccess(id, context);
|
|
4800
|
+
if (table.type === "items") {
|
|
4801
|
+
await assertItemFileKeysReadable({
|
|
4802
|
+
input,
|
|
4803
|
+
user: context.user,
|
|
4804
|
+
s3prefix: config?.fileUploads?.s3prefix,
|
|
4805
|
+
loadExisting: () => db.from(tableNamePlural).where({ id }).first()
|
|
4806
|
+
});
|
|
4807
|
+
}
|
|
4515
4808
|
const rbacData = input.RBAC;
|
|
4516
4809
|
delete input.RBAC;
|
|
4517
4810
|
delete input.created_by;
|
|
@@ -7291,7 +7584,7 @@ var DEFAULT_SENDER_RATE_LIMIT_PER_HOUR = 10;
|
|
|
7291
7584
|
var DEFAULT_FILTERED_RUN_RETENTION = 200;
|
|
7292
7585
|
var FILTER_BODY_BYTE_CAP = 10 * 1024;
|
|
7293
7586
|
var AUTO_REPLY_PRECEDENCE = /* @__PURE__ */ new Set(["bulk", "junk", "list"]);
|
|
7294
|
-
var
|
|
7587
|
+
var HOUR_MS2 = 60 * 60 * 1e3;
|
|
7295
7588
|
var isAutoReply = (email) => {
|
|
7296
7589
|
const autoSubmitted = email.headers.get("auto-submitted");
|
|
7297
7590
|
if (autoSubmitted !== void 0 && autoSubmitted.trim().toLowerCase() !== "no") {
|
|
@@ -7323,7 +7616,7 @@ var senderAllowed = (address, allowedSenders) => {
|
|
|
7323
7616
|
var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
|
|
7324
7617
|
if (!redis) return true;
|
|
7325
7618
|
try {
|
|
7326
|
-
const currentBucket = Math.floor(now /
|
|
7619
|
+
const currentBucket = Math.floor(now / HOUR_MS2);
|
|
7327
7620
|
const currentKey = `${key}:${currentBucket}`;
|
|
7328
7621
|
const previousKey = `${key}:${currentBucket - 1}`;
|
|
7329
7622
|
const count2 = await redis.incr(currentKey);
|
|
@@ -7332,7 +7625,7 @@ var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
|
|
|
7332
7625
|
}
|
|
7333
7626
|
const previousRaw = await redis.get(previousKey);
|
|
7334
7627
|
const previous = previousRaw ? Number(previousRaw) : 0;
|
|
7335
|
-
const elapsedFraction = now %
|
|
7628
|
+
const elapsedFraction = now % HOUR_MS2 / HOUR_MS2;
|
|
7336
7629
|
const weighted = count2 + previous * (1 - elapsedFraction);
|
|
7337
7630
|
return weighted <= limitPerHour;
|
|
7338
7631
|
} catch (err2) {
|
|
@@ -8304,68 +8597,6 @@ var createRunLock = (redis) => ({
|
|
|
8304
8597
|
}
|
|
8305
8598
|
});
|
|
8306
8599
|
|
|
8307
|
-
// src/exulu/external-rate-limit.ts
|
|
8308
|
-
var MINUTE_MS = 6e4;
|
|
8309
|
-
var HOUR_MS2 = 36e5;
|
|
8310
|
-
var perMinuteLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_MINUTE || "30", 10);
|
|
8311
|
-
var perHourLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_HOUR || "300", 10);
|
|
8312
|
-
var windows = /* @__PURE__ */ new Map();
|
|
8313
|
-
var externalRateLimitExceeded = (userId, now = Date.now()) => {
|
|
8314
|
-
const state = windows.get(userId) ?? {
|
|
8315
|
-
minuteStart: now,
|
|
8316
|
-
minuteCount: 0,
|
|
8317
|
-
hourStart: now,
|
|
8318
|
-
hourCount: 0,
|
|
8319
|
-
lastSeen: now
|
|
8320
|
-
};
|
|
8321
|
-
if (now - state.minuteStart >= MINUTE_MS) {
|
|
8322
|
-
state.minuteStart = now;
|
|
8323
|
-
state.minuteCount = 0;
|
|
8324
|
-
}
|
|
8325
|
-
if (now - state.hourStart >= HOUR_MS2) {
|
|
8326
|
-
state.hourStart = now;
|
|
8327
|
-
state.hourCount = 0;
|
|
8328
|
-
}
|
|
8329
|
-
state.minuteCount += 1;
|
|
8330
|
-
state.hourCount += 1;
|
|
8331
|
-
state.lastSeen = now;
|
|
8332
|
-
windows.set(userId, state);
|
|
8333
|
-
if (windows.size > 1e4) {
|
|
8334
|
-
for (const [key, value] of windows) {
|
|
8335
|
-
if (now - value.lastSeen >= HOUR_MS2) windows.delete(key);
|
|
8336
|
-
}
|
|
8337
|
-
if (windows.size > 1e4) {
|
|
8338
|
-
const sorted = [...windows.entries()].sort(
|
|
8339
|
-
(a, b) => a[1].lastSeen - b[1].lastSeen
|
|
8340
|
-
);
|
|
8341
|
-
for (const [key] of sorted) {
|
|
8342
|
-
if (windows.size <= 1e4) break;
|
|
8343
|
-
windows.delete(key);
|
|
8344
|
-
}
|
|
8345
|
-
}
|
|
8346
|
-
}
|
|
8347
|
-
const minuteLimitExceeded = state.minuteCount > perMinuteLimit();
|
|
8348
|
-
const hourLimitExceeded = state.hourCount > perHourLimit();
|
|
8349
|
-
const limitExceeded = minuteLimitExceeded || hourLimitExceeded;
|
|
8350
|
-
if (limitExceeded) {
|
|
8351
|
-
const limits = {
|
|
8352
|
-
perMinute: perMinuteLimit(),
|
|
8353
|
-
perHour: perHourLimit()
|
|
8354
|
-
};
|
|
8355
|
-
const current = {
|
|
8356
|
-
minute: state.minuteCount,
|
|
8357
|
-
hour: state.hourCount
|
|
8358
|
-
};
|
|
8359
|
-
console.warn(
|
|
8360
|
-
`[EXULU] Rate limit exceeded for user ${userId}${minuteLimitExceeded ? ` per-minute (${current.minute}/${limits.perMinute})` : ""}${minuteLimitExceeded && hourLimitExceeded ? " and" : ""}${hourLimitExceeded ? ` per-hour (${current.hour}/${limits.perHour})` : ""}`
|
|
8361
|
-
);
|
|
8362
|
-
}
|
|
8363
|
-
return limitExceeded;
|
|
8364
|
-
};
|
|
8365
|
-
var isExternalUser = (user) => {
|
|
8366
|
-
return user?.role?.name === "external";
|
|
8367
|
-
};
|
|
8368
|
-
|
|
8369
8600
|
// src/exulu/channels/wiring.ts
|
|
8370
8601
|
var channelStoreFromRedis = (client2) => ({
|
|
8371
8602
|
set: (key, value, opts) => client2.set(key, value, opts.NX ? { EX: opts.EX, NX: true } : { EX: opts.EX }),
|
|
@@ -12210,7 +12441,7 @@ async function insertTriggerWithSecretRetry(insertFn, baseRow) {
|
|
|
12210
12441
|
import { randomUUID as randomUUID5 } from "crypto";
|
|
12211
12442
|
|
|
12212
12443
|
// src/exulu/email-inbound/verify-signature.ts
|
|
12213
|
-
import { createHmac, timingSafeEqual } from "crypto";
|
|
12444
|
+
import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
12214
12445
|
var SIGNATURE_REPLAY_WINDOW_SECONDS = 300;
|
|
12215
12446
|
var REPLAY_TTL_SECONDS = 900;
|
|
12216
12447
|
function verifyPayloadSignature(rawBody, signatureHeader, timestampHeader, secret) {
|
|
@@ -12223,7 +12454,7 @@ function verifyPayloadSignature(rawBody, signatureHeader, timestampHeader, secre
|
|
|
12223
12454
|
const expectedBuf = Buffer.from(expected, "utf8");
|
|
12224
12455
|
const providedBuf = Buffer.from(provided.toLowerCase(), "utf8");
|
|
12225
12456
|
if (expectedBuf.length !== providedBuf.length) return false;
|
|
12226
|
-
return
|
|
12457
|
+
return timingSafeEqual2(expectedBuf, providedBuf);
|
|
12227
12458
|
}
|
|
12228
12459
|
async function isReplay(redis, signature, timestamp) {
|
|
12229
12460
|
const ts = Number(timestamp);
|
|
@@ -13714,6 +13945,12 @@ type StatisticsResult {
|
|
|
13714
13945
|
group: String!
|
|
13715
13946
|
count: Int!
|
|
13716
13947
|
}
|
|
13948
|
+
|
|
13949
|
+
type ChunkSourceDocument {
|
|
13950
|
+
url: String!
|
|
13951
|
+
filename: String!
|
|
13952
|
+
page: Int
|
|
13953
|
+
}
|
|
13717
13954
|
`;
|
|
13718
13955
|
}
|
|
13719
13956
|
function createSDL(tables, contexts, tools, config, evals) {
|
|
@@ -13814,6 +14051,7 @@ function createSDL(tables, contexts, tools, config, evals) {
|
|
|
13814
14051
|
typeDefs += `
|
|
13815
14052
|
${tableNamePlural}VectorSearch(limit: Int, query: String!, method: VectorMethodEnum!, itemFilters: [Filter${tableNameSingularUpperCaseFirst}], cutoffs: SearchCutoffs, expand: SearchExpand, entityFilter: ${tableNameSingular}EntityFilterInput): ${tableNameSingular}VectorSearchResult
|
|
13816
14053
|
${tableNameSingular}ChunkById(id: ID!): ${tableNameSingular}VectorSearchChunk
|
|
14054
|
+
${tableNameSingular}ChunkSourceDocument(id: ID!): ChunkSourceDocument
|
|
13817
14055
|
${tableNameSingular}StaleEntityCount: Int
|
|
13818
14056
|
${tableNameSingular}EntityModel: ${tableNameSingular}EntityModelInfo
|
|
13819
14057
|
${tableNameSingular}EntitiesForItem(item: ID!): [${tableNameSingular}ItemEntity!]
|
|
@@ -14110,7 +14348,7 @@ type PageInfo {
|
|
|
14110
14348
|
hasNextPage: Boolean!
|
|
14111
14349
|
}
|
|
14112
14350
|
`;
|
|
14113
|
-
Object.assign(resolvers.Query, createQueries(table, tools, contexts));
|
|
14351
|
+
Object.assign(resolvers.Query, createQueries(table, tools, contexts, config));
|
|
14114
14352
|
Object.assign(
|
|
14115
14353
|
resolvers.Mutation,
|
|
14116
14354
|
createMutations(table, contexts, tools, config)
|
|
@@ -14120,13 +14358,7 @@ type PageInfo {
|
|
|
14120
14358
|
if (!resolvers[rbacResolverName]) {
|
|
14121
14359
|
resolvers[rbacResolverName] = {};
|
|
14122
14360
|
}
|
|
14123
|
-
resolvers[rbacResolverName].RBAC = async (parent, args, context) =>
|
|
14124
|
-
const { db } = context;
|
|
14125
|
-
const resourceId = parent.id;
|
|
14126
|
-
const entityName = table.name.singular;
|
|
14127
|
-
const rights_mode = parent.rights_mode;
|
|
14128
|
-
return RBACResolver(db, entityName, resourceId, rights_mode);
|
|
14129
|
-
};
|
|
14361
|
+
resolvers[rbacResolverName].RBAC = async (parent, args, context) => resolveRbacField(table, parent, context);
|
|
14130
14362
|
}
|
|
14131
14363
|
}
|
|
14132
14364
|
typeDefs += `
|
|
@@ -17625,6 +17857,133 @@ function registerViewerIdentityRoutes(app, deps) {
|
|
|
17625
17857
|
});
|
|
17626
17858
|
}
|
|
17627
17859
|
|
|
17860
|
+
// src/exulu/companion/external-share-route.ts
|
|
17861
|
+
var SHARED_ARTIFACT_EXTERNAL_PATH = "/shared-artifacts/:name/external";
|
|
17862
|
+
function registerExternalShareRoute(app, deps) {
|
|
17863
|
+
app.get(SHARED_ARTIFACT_EXTERNAL_PATH, async (req, res) => {
|
|
17864
|
+
const notFound = () => res.status(404).json({ detail: "Not found." });
|
|
17865
|
+
try {
|
|
17866
|
+
if (companionRequestState(req.headers, deps.env ?? process.env) !== "valid") {
|
|
17867
|
+
notFound();
|
|
17868
|
+
return;
|
|
17869
|
+
}
|
|
17870
|
+
const db = await deps.getDb();
|
|
17871
|
+
const row = await getSharedArtifactByName(db, req.params.name ?? "");
|
|
17872
|
+
if (!row || isExpired(row.expires_at, /* @__PURE__ */ new Date()) || row.auth_mode !== "regular" || row.external_access !== true) {
|
|
17873
|
+
notFound();
|
|
17874
|
+
return;
|
|
17875
|
+
}
|
|
17876
|
+
const grants = await db("rbac").where({ entity: "shared_artifact", target_resource_id: row.id, access_type: "Team" }).select("team_id");
|
|
17877
|
+
const teams = await teamNamesByIds(db, grants.map((g) => g.team_id));
|
|
17878
|
+
if (validateExternalAccess({
|
|
17879
|
+
external_access: true,
|
|
17880
|
+
auth_mode: row.auth_mode,
|
|
17881
|
+
rights_mode: row.rights_mode,
|
|
17882
|
+
teams
|
|
17883
|
+
}) !== null) {
|
|
17884
|
+
notFound();
|
|
17885
|
+
return;
|
|
17886
|
+
}
|
|
17887
|
+
res.status(204).end();
|
|
17888
|
+
} catch (e) {
|
|
17889
|
+
console.error("[EXULU] companion external check failed", e);
|
|
17890
|
+
notFound();
|
|
17891
|
+
}
|
|
17892
|
+
});
|
|
17893
|
+
}
|
|
17894
|
+
|
|
17895
|
+
// src/exulu/companion/status.ts
|
|
17896
|
+
var HEALTH_TIMEOUT_MS = 5e3;
|
|
17897
|
+
var CACHE_TTL_MS = 3e4;
|
|
17898
|
+
var VERSION_RE = /^[\w.+-]{1,32}$/;
|
|
17899
|
+
var HOST_RE = /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?(:\d{1,5})?$/;
|
|
17900
|
+
var checkCompanion = async (deps) => {
|
|
17901
|
+
const host = deps.env.EXULU_COMPANION_HOST;
|
|
17902
|
+
const key = deps.env.EXULU_COMPANION_KEY;
|
|
17903
|
+
if (!host || !key || !HOST_RE.test(host)) return { state: "not_configured" };
|
|
17904
|
+
const checkedAt = deps.now().toISOString();
|
|
17905
|
+
const unreachable = { state: "unreachable", host, checkedAt };
|
|
17906
|
+
try {
|
|
17907
|
+
const res = await deps.fetch(`https://${host}/_companion/health`, {
|
|
17908
|
+
method: "GET",
|
|
17909
|
+
headers: { [COMPANION_HEADER]: key },
|
|
17910
|
+
redirect: "error",
|
|
17911
|
+
signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS)
|
|
17912
|
+
});
|
|
17913
|
+
if (res.status !== 200) return unreachable;
|
|
17914
|
+
const body = await res.json();
|
|
17915
|
+
if (!body || typeof body !== "object" || typeof body.version !== "string" || !VERSION_RE.test(body.version) || typeof body.upstream !== "boolean") {
|
|
17916
|
+
return unreachable;
|
|
17917
|
+
}
|
|
17918
|
+
const { version, upstream } = body;
|
|
17919
|
+
if (version.includes(key)) return unreachable;
|
|
17920
|
+
return { state: upstream ? "connected" : "no_tunnel", host, version, checkedAt };
|
|
17921
|
+
} catch {
|
|
17922
|
+
return unreachable;
|
|
17923
|
+
}
|
|
17924
|
+
};
|
|
17925
|
+
var createCompanionStatusCache = (deps) => {
|
|
17926
|
+
let cached = null;
|
|
17927
|
+
return {
|
|
17928
|
+
get: async (refresh = false) => {
|
|
17929
|
+
const t = deps.now().getTime();
|
|
17930
|
+
if (!refresh && cached && t - cached.at < CACHE_TTL_MS && t >= cached.at) return cached.value;
|
|
17931
|
+
const value = await checkCompanion(deps);
|
|
17932
|
+
cached = { at: t, value };
|
|
17933
|
+
return value;
|
|
17934
|
+
}
|
|
17935
|
+
};
|
|
17936
|
+
};
|
|
17937
|
+
var cachedCompanionStatus = createCompanionStatusCache({
|
|
17938
|
+
env: process.env,
|
|
17939
|
+
fetch: globalThis.fetch,
|
|
17940
|
+
now: () => /* @__PURE__ */ new Date()
|
|
17941
|
+
});
|
|
17942
|
+
|
|
17943
|
+
// src/exulu/companion/status-routes.ts
|
|
17944
|
+
function registerCompanionStatusRoutes(app, deps) {
|
|
17945
|
+
const status = deps.status ?? cachedCompanionStatus;
|
|
17946
|
+
const requireSuperAdmin = async (req, res) => {
|
|
17947
|
+
const auth = await deps.authenticate(req);
|
|
17948
|
+
if (!auth.user?.id) {
|
|
17949
|
+
res.status(auth.code ?? 401).json({ detail: auth.message });
|
|
17950
|
+
return false;
|
|
17951
|
+
}
|
|
17952
|
+
if (auth.user.super_admin !== true) {
|
|
17953
|
+
res.status(403).json({ detail: "Only a super admin can view the companion server." });
|
|
17954
|
+
return false;
|
|
17955
|
+
}
|
|
17956
|
+
return true;
|
|
17957
|
+
};
|
|
17958
|
+
app.get("/companion/status", async (req, res) => {
|
|
17959
|
+
if (!await requireSuperAdmin(req, res)) return;
|
|
17960
|
+
res.json(await status.get(req.query.refresh === "1"));
|
|
17961
|
+
});
|
|
17962
|
+
app.get("/companion/released", async (req, res) => {
|
|
17963
|
+
if (!await requireSuperAdmin(req, res)) return;
|
|
17964
|
+
try {
|
|
17965
|
+
const db = await deps.getDb();
|
|
17966
|
+
const shares = await db("shared_artifacts").where({ external_access: true }).select("id", "name");
|
|
17967
|
+
const grants = shares.length ? await db("rbac").where({ entity: "shared_artifact", access_type: "Team" }).whereIn("target_resource_id", shares.map((s) => s.id)).select("target_resource_id", "team_id") : [];
|
|
17968
|
+
const teamIds = [...new Set(grants.map((g) => g.team_id).filter(Boolean))];
|
|
17969
|
+
const teams = teamIds.length ? await db("teams").whereIn("id", teamIds).select("id", "name") : [];
|
|
17970
|
+
const users = teamIds.length ? await db("users").where({ type: "external" }).whereIn("team", teamIds).select("team") : [];
|
|
17971
|
+
const counts = /* @__PURE__ */ new Map();
|
|
17972
|
+
for (const u of users) counts.set(u.team, (counts.get(u.team) ?? 0) + 1);
|
|
17973
|
+
const teamName = new Map(teams.map((t) => [t.id, t.name]));
|
|
17974
|
+
res.json({
|
|
17975
|
+
items: shares.map((s) => ({
|
|
17976
|
+
name: s.name,
|
|
17977
|
+
teams: [...new Set(grants.filter((g) => g.target_resource_id === s.id).map((g) => g.team_id))].filter((id) => teamName.has(id)).map((id) => ({ id, name: teamName.get(id), users: counts.get(id) ?? 0 }))
|
|
17978
|
+
}))
|
|
17979
|
+
});
|
|
17980
|
+
} catch (e) {
|
|
17981
|
+
console.error("[EXULU] companion released listing failed", e);
|
|
17982
|
+
res.status(500).json({ detail: "Failed to list released artifacts." });
|
|
17983
|
+
}
|
|
17984
|
+
});
|
|
17985
|
+
}
|
|
17986
|
+
|
|
17628
17987
|
// src/exulu/tool-api-route.ts
|
|
17629
17988
|
import { randomUUID as randomUUID9 } from "crypto";
|
|
17630
17989
|
var TOOL_API_ROUTE_PATH = "/tools/:id";
|
|
@@ -17741,6 +18100,23 @@ function registerCreateShareRoute(app, deps) {
|
|
|
17741
18100
|
res.status(400).json({ detail: valid.message });
|
|
17742
18101
|
return;
|
|
17743
18102
|
}
|
|
18103
|
+
if (!mayChangeExternalRelease(auth.user, req.body.external_access, false)) {
|
|
18104
|
+
res.status(403).json({ detail: EXTERNAL_SUPER_ADMIN_ONLY });
|
|
18105
|
+
return;
|
|
18106
|
+
}
|
|
18107
|
+
if (req.body.external_access !== void 0) {
|
|
18108
|
+
const teamIds = req.body.external_access === true && Array.isArray(req.body.rbac?.teams) ? req.body.rbac.teams.map((t) => t?.id) : [];
|
|
18109
|
+
const externalError = validateExternalAccess({
|
|
18110
|
+
external_access: req.body.external_access,
|
|
18111
|
+
auth_mode: req.body.auth_mode,
|
|
18112
|
+
rights_mode: req.body.rights_mode ?? "private",
|
|
18113
|
+
teams: await teamNamesByIds(db, teamIds)
|
|
18114
|
+
});
|
|
18115
|
+
if (externalError) {
|
|
18116
|
+
res.status(400).json({ detail: externalError });
|
|
18117
|
+
return;
|
|
18118
|
+
}
|
|
18119
|
+
}
|
|
17744
18120
|
const details = planDetails({ ...req.body, archived: void 0 }, now);
|
|
17745
18121
|
if (!details.ok) {
|
|
17746
18122
|
res.status(400).json({ detail: details.message });
|
|
@@ -17771,6 +18147,7 @@ function registerCreateShareRoute(app, deps) {
|
|
|
17771
18147
|
password_hash,
|
|
17772
18148
|
expires_at: req.body.expires_at ?? null,
|
|
17773
18149
|
content_type: req.body.content_type ?? null,
|
|
18150
|
+
external_access: req.body.external_access === true,
|
|
17774
18151
|
rights_mode,
|
|
17775
18152
|
created_by: auth.user.id,
|
|
17776
18153
|
...details.patch,
|
|
@@ -20493,7 +20870,7 @@ var handleCredentialDelete = async (req, res) => {
|
|
|
20493
20870
|
};
|
|
20494
20871
|
|
|
20495
20872
|
// src/exulu/recall/verify.ts
|
|
20496
|
-
import { createHmac as createHmac2, timingSafeEqual as
|
|
20873
|
+
import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
20497
20874
|
var TOLERANCE_SECONDS = 5 * 60;
|
|
20498
20875
|
var header = (headers, ...names) => {
|
|
20499
20876
|
for (const name of names) {
|
|
@@ -20511,7 +20888,7 @@ var safeEqual = (a, b) => {
|
|
|
20511
20888
|
const bufA = Buffer.from(a);
|
|
20512
20889
|
const bufB = Buffer.from(b);
|
|
20513
20890
|
if (bufA.length !== bufB.length) return false;
|
|
20514
|
-
return
|
|
20891
|
+
return timingSafeEqual3(bufA, bufB);
|
|
20515
20892
|
};
|
|
20516
20893
|
var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()) => {
|
|
20517
20894
|
if (!secret) {
|
|
@@ -20890,7 +21267,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
20890
21267
|
const server = new ApolloServer({
|
|
20891
21268
|
cache: new InMemoryLRUCache(),
|
|
20892
21269
|
schema: schema7,
|
|
20893
|
-
introspection: true
|
|
21270
|
+
introspection: true,
|
|
21271
|
+
plugins: [
|
|
21272
|
+
companionOperationGuard(
|
|
21273
|
+
companionAllowedOperations((contexts ?? []).map(convertContextToTableDefinition))
|
|
21274
|
+
)
|
|
21275
|
+
]
|
|
20894
21276
|
});
|
|
20895
21277
|
await server.start();
|
|
20896
21278
|
app.use(
|
|
@@ -20909,7 +21291,10 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
20909
21291
|
return {
|
|
20910
21292
|
req,
|
|
20911
21293
|
db,
|
|
20912
|
-
user:
|
|
21294
|
+
user: admitCompanionUser(
|
|
21295
|
+
companionRequestState(req.headers),
|
|
21296
|
+
authenticationResult.user
|
|
21297
|
+
)
|
|
20913
21298
|
};
|
|
20914
21299
|
}
|
|
20915
21300
|
})
|
|
@@ -24122,6 +24507,14 @@ ${style.markdown}` : params.prompt;
|
|
|
24122
24507
|
const loadSessionFilesAuth = async (req, res, sessionId, rights) => {
|
|
24123
24508
|
const authed = await loadAuthedSession(req, res, sessionId, rights);
|
|
24124
24509
|
if (!authed) return null;
|
|
24510
|
+
if (isExternalUser(authed.user)) {
|
|
24511
|
+
const agentId = authed.session?.agent;
|
|
24512
|
+
const agentRow = agentId ? await authed.db.from("agents").where({ id: agentId }).select("guest_access", "guest_auth_mode", "sandbox_enabled", "active").first() : null;
|
|
24513
|
+
if (!agentAllowsGuestFiles(agentRow)) {
|
|
24514
|
+
res.status(403).json({ detail: "Files are not available for this conversation." });
|
|
24515
|
+
return null;
|
|
24516
|
+
}
|
|
24517
|
+
}
|
|
24125
24518
|
const ownerId = authed.session.user ?? authed.user.id;
|
|
24126
24519
|
return { ...authed, ownerId, ...buildSessionPrefixes(ownerId, sessionId) };
|
|
24127
24520
|
};
|
|
@@ -24210,6 +24603,15 @@ ${style.markdown}` : params.prompt;
|
|
|
24210
24603
|
res.status(400).json({ detail: "Missing contentType in request body." });
|
|
24211
24604
|
return;
|
|
24212
24605
|
}
|
|
24606
|
+
if (isExternalUser(authed.user)) {
|
|
24607
|
+
const refusal = guestUploadRefusal(
|
|
24608
|
+
await listS3ObjectsByPrefix(authed.userSessionPrefix, config)
|
|
24609
|
+
);
|
|
24610
|
+
if (refusal) {
|
|
24611
|
+
res.status(413).json({ detail: refusal });
|
|
24612
|
+
return;
|
|
24613
|
+
}
|
|
24614
|
+
}
|
|
24213
24615
|
const fullKey = `${authed.fullSessionPrefix}${safeName}`;
|
|
24214
24616
|
const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
|
|
24215
24617
|
res.json({ uploadUrl, key: fullKey });
|
|
@@ -24234,6 +24636,16 @@ ${style.markdown}` : params.prompt;
|
|
|
24234
24636
|
res.status(403).json({ detail: "Key does not belong to this session." });
|
|
24235
24637
|
return;
|
|
24236
24638
|
}
|
|
24639
|
+
if (isExternalUser(authed.user)) {
|
|
24640
|
+
const uploaded = (await listS3ObjectsByPrefix(authed.userSessionPrefix, config)).find(
|
|
24641
|
+
(object) => object.key === key
|
|
24642
|
+
);
|
|
24643
|
+
if (guestFileTooLarge(uploaded?.size)) {
|
|
24644
|
+
await deleteS3Object(key, config);
|
|
24645
|
+
res.status(413).json({ detail: "This file is too large." });
|
|
24646
|
+
return;
|
|
24647
|
+
}
|
|
24648
|
+
}
|
|
24237
24649
|
try {
|
|
24238
24650
|
const result = await downloadKeyIntoSandbox({
|
|
24239
24651
|
sessionId,
|
|
@@ -24629,6 +25041,7 @@ ${style.markdown}` : params.prompt;
|
|
|
24629
25041
|
// Coerced, not `?? []`: see readAgentSlots on why a stored non-array is
|
|
24630
25042
|
// a real possibility and why a reader has to survive one.
|
|
24631
25043
|
agent_slots: readAgentSlots(row.agent_slots),
|
|
25044
|
+
external_access: row.external_access === true,
|
|
24632
25045
|
...detailsOf(row),
|
|
24633
25046
|
// Older files, newest first; at most MAX_OLDER_VERSIONS (artifact-library.ts).
|
|
24634
25047
|
versions: versions.map((v) => ({
|
|
@@ -24668,6 +25081,28 @@ ${style.markdown}` : params.prompt;
|
|
|
24668
25081
|
res.status(400).json({ detail: valid.message });
|
|
24669
25082
|
return;
|
|
24670
25083
|
}
|
|
25084
|
+
if (!mayChangeExternalRelease(auth.user, input.external_access, row.external_access)) {
|
|
25085
|
+
res.status(403).json({ detail: EXTERNAL_SUPER_ADMIN_ONLY });
|
|
25086
|
+
return;
|
|
25087
|
+
}
|
|
25088
|
+
if (externalAccessCheckApplies(input, row)) {
|
|
25089
|
+
let teams = [];
|
|
25090
|
+
if (externalAccessNeedsTeams(input, row)) {
|
|
25091
|
+
let teamIds;
|
|
25092
|
+
if (input.rbac && typeof input.rbac === "object") {
|
|
25093
|
+
teamIds = Array.isArray(input.rbac.teams) ? input.rbac.teams.map((t) => t?.id) : [];
|
|
25094
|
+
} else {
|
|
25095
|
+
const stored = await db("rbac").where({ entity: "shared_artifact", target_resource_id: row.id, access_type: "Team" }).select("team_id");
|
|
25096
|
+
teamIds = stored.map((r) => r.team_id);
|
|
25097
|
+
}
|
|
25098
|
+
teams = await teamNamesByIds(db, teamIds);
|
|
25099
|
+
}
|
|
25100
|
+
const externalError = validateExternalAccessUpdate(input, row, teams);
|
|
25101
|
+
if (externalError) {
|
|
25102
|
+
res.status(400).json({ detail: externalError });
|
|
25103
|
+
return;
|
|
25104
|
+
}
|
|
25105
|
+
}
|
|
24671
25106
|
const details = planDetails(input, now);
|
|
24672
25107
|
if (!details.ok) {
|
|
24673
25108
|
res.status(400).json({ detail: details.message });
|
|
@@ -24712,6 +25147,7 @@ ${style.markdown}` : params.prompt;
|
|
|
24712
25147
|
expires_at: updated.expires_at ?? null,
|
|
24713
25148
|
rights_mode: updated.rights_mode ?? null,
|
|
24714
25149
|
agent_slots: readAgentSlots(updated.agent_slots),
|
|
25150
|
+
external_access: updated.external_access === true,
|
|
24715
25151
|
...detailsOf(updated),
|
|
24716
25152
|
version_count: readVersions(updated.versions).length
|
|
24717
25153
|
});
|
|
@@ -24781,6 +25217,13 @@ ${style.markdown}` : params.prompt;
|
|
|
24781
25217
|
RBACResolver,
|
|
24782
25218
|
checkRecordAccess
|
|
24783
25219
|
});
|
|
25220
|
+
registerExternalShareRoute(app, {
|
|
25221
|
+
getDb: async () => (await postgresClient()).db
|
|
25222
|
+
});
|
|
25223
|
+
registerCompanionStatusRoutes(app, {
|
|
25224
|
+
authenticate: (req) => requestValidators.authenticate(req),
|
|
25225
|
+
getDb: async () => (await postgresClient()).db
|
|
25226
|
+
});
|
|
24784
25227
|
registerToolApiRoutes(app, {
|
|
24785
25228
|
authenticate: (req) => requestValidators.authenticate(req),
|
|
24786
25229
|
tools,
|
|
@@ -24961,7 +25404,9 @@ ${style.markdown}` : params.prompt;
|
|
|
24961
25404
|
// Presence only — publicAgentView turns these into booleans and the
|
|
24962
25405
|
// bytes are served by /public-agents/:id/animation/:kind.
|
|
24963
25406
|
"animation_idle",
|
|
24964
|
-
"animation_responding"
|
|
25407
|
+
"animation_responding",
|
|
25408
|
+
// Presence of the guest files feature, never the sandbox itself.
|
|
25409
|
+
"sandbox_enabled"
|
|
24965
25410
|
);
|
|
24966
25411
|
const views = await Promise.all(
|
|
24967
25412
|
rows.map(
|