@exulu/backend 5.22.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/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import "dotenv/config";
2
2
  import {
3
3
  documentProcessor
4
- } from "./chunk-Q4DFJFUI.js";
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,
@@ -138,6 +139,8 @@ import {
138
139
  estimateMessageTokens,
139
140
  estimateTokens,
140
141
  exchangeCodeForTokens,
142
+ externalAccessCheckApplies,
143
+ externalAccessNeedsTeams,
141
144
  extractClientInfo,
142
145
  extractDocument,
143
146
  exuluApp,
@@ -171,6 +174,7 @@ import {
171
174
  handleRBACUpdate,
172
175
  hasAgentsReadAccess,
173
176
  hasAgentsWriteAccess,
177
+ hasCompanionWriteGrant,
174
178
  hasProjectAccess,
175
179
  hashSharePassword,
176
180
  hydrateContextEmbedders,
@@ -190,6 +194,7 @@ import {
190
194
  loadSessionFileListing,
191
195
  mapStreamErrorMessage,
192
196
  mapType,
197
+ mayChangeExternalRelease,
193
198
  mayReadGenericS3Key,
194
199
  mayResignStoredFileKey,
195
200
  mayUseGenericS3Route,
@@ -254,6 +259,7 @@ import {
254
259
  shouldShowSourcesToUser,
255
260
  sliceHistoryAtCheckpoint,
256
261
  slugifyShareName,
262
+ teamNamesByIds,
257
263
  treatAsGuest,
258
264
  truncateToolOutput,
259
265
  updateStatistic,
@@ -262,6 +268,8 @@ import {
262
268
  userIdOf,
263
269
  validateAttachmentsConfig,
264
270
  validateCreateInput,
271
+ validateExternalAccess,
272
+ validateExternalAccessUpdate,
265
273
  validateUpdateInput,
266
274
  vectorSearch,
267
275
  verifyCredentialNonce,
@@ -271,7 +279,7 @@ import {
271
279
  willEmbedOnQueue,
272
280
  withRunSession,
273
281
  workflowTemplatesSchema
274
- } from "./chunk-6OAYOFEY.js";
282
+ } from "./chunk-K7CGLUW4.js";
275
283
  import {
276
284
  LITELLM_UI_PATH,
277
285
  ResolveModelError,
@@ -298,7 +306,7 @@ import {
298
306
  tagInfo,
299
307
  upsertBudget,
300
308
  waitForLiteLLMReady
301
- } from "./chunk-43QIPMLT.js";
309
+ } from "./chunk-BFIDSFRQ.js";
302
310
  import {
303
311
  findLiteLLMModel
304
312
  } from "./chunk-F534XOQR.js";
@@ -420,6 +428,151 @@ async function redisClient() {
420
428
  // src/exulu/app/index.ts
421
429
  import "express";
422
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
+
423
576
  // src/exulu/routes.ts
424
577
  import "express";
425
578
 
@@ -1006,7 +1159,7 @@ function createQueueMutationResolvers(deps) {
1006
1159
  import { v4 as uuidv43 } from "uuid";
1007
1160
 
1008
1161
  // src/graphql/types/index.ts
1009
- import { GraphQLScalarType, Kind } from "graphql";
1162
+ import { GraphQLScalarType, Kind as Kind2 } from "graphql";
1010
1163
  var GraphQLDate = new GraphQLScalarType({
1011
1164
  name: "Date",
1012
1165
  description: "Date custom scalar type",
@@ -1032,10 +1185,10 @@ var GraphQLDate = new GraphQLScalarType({
1032
1185
  return value;
1033
1186
  },
1034
1187
  parseLiteral(ast) {
1035
- if (ast.kind === Kind.STRING) {
1188
+ if (ast.kind === Kind2.STRING) {
1036
1189
  return new Date(ast.value);
1037
1190
  }
1038
- if (ast.kind === Kind.INT) {
1191
+ if (ast.kind === Kind2.INT) {
1039
1192
  return new Date(parseInt(ast.value, 10));
1040
1193
  }
1041
1194
  return null;
@@ -1107,6 +1260,12 @@ var contextItemsProcessorHandler = async (context, config, items, user, role) =>
1107
1260
  };
1108
1261
  };
1109
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
+
1110
1269
  // src/graphql/utilities/provider-fields.ts
1111
1270
  var exuluProviderFields = [
1112
1271
  "providerName",
@@ -4272,6 +4431,12 @@ function createMutations(table, contexts, tools, config) {
4272
4431
  const validateWriteAccess = async (id, context) => {
4273
4432
  try {
4274
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
+ }
4275
4440
  if (user.super_admin === true) {
4276
4441
  return true;
4277
4442
  }
@@ -4622,6 +4787,14 @@ function createMutations(table, contexts, tools, config) {
4622
4787
  [`${tableNamePlural}UpdateOneById`]: async (_, args, context, info) => {
4623
4788
  const { db, req } = context;
4624
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
+ }
4625
4798
  await validateCreateOrRemoveSuperAdminPermission(tableNamePlural, input, req);
4626
4799
  await validateWriteAccess(id, context);
4627
4800
  if (table.type === "items") {
@@ -7411,7 +7584,7 @@ var DEFAULT_SENDER_RATE_LIMIT_PER_HOUR = 10;
7411
7584
  var DEFAULT_FILTERED_RUN_RETENTION = 200;
7412
7585
  var FILTER_BODY_BYTE_CAP = 10 * 1024;
7413
7586
  var AUTO_REPLY_PRECEDENCE = /* @__PURE__ */ new Set(["bulk", "junk", "list"]);
7414
- var HOUR_MS = 60 * 60 * 1e3;
7587
+ var HOUR_MS2 = 60 * 60 * 1e3;
7415
7588
  var isAutoReply = (email) => {
7416
7589
  const autoSubmitted = email.headers.get("auto-submitted");
7417
7590
  if (autoSubmitted !== void 0 && autoSubmitted.trim().toLowerCase() !== "no") {
@@ -7443,7 +7616,7 @@ var senderAllowed = (address, allowedSenders) => {
7443
7616
  var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
7444
7617
  if (!redis) return true;
7445
7618
  try {
7446
- const currentBucket = Math.floor(now / HOUR_MS);
7619
+ const currentBucket = Math.floor(now / HOUR_MS2);
7447
7620
  const currentKey = `${key}:${currentBucket}`;
7448
7621
  const previousKey = `${key}:${currentBucket - 1}`;
7449
7622
  const count2 = await redis.incr(currentKey);
@@ -7452,7 +7625,7 @@ var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
7452
7625
  }
7453
7626
  const previousRaw = await redis.get(previousKey);
7454
7627
  const previous = previousRaw ? Number(previousRaw) : 0;
7455
- const elapsedFraction = now % HOUR_MS / HOUR_MS;
7628
+ const elapsedFraction = now % HOUR_MS2 / HOUR_MS2;
7456
7629
  const weighted = count2 + previous * (1 - elapsedFraction);
7457
7630
  return weighted <= limitPerHour;
7458
7631
  } catch (err2) {
@@ -8424,68 +8597,6 @@ var createRunLock = (redis) => ({
8424
8597
  }
8425
8598
  });
8426
8599
 
8427
- // src/exulu/external-rate-limit.ts
8428
- var MINUTE_MS = 6e4;
8429
- var HOUR_MS2 = 36e5;
8430
- var perMinuteLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_MINUTE || "30", 10);
8431
- var perHourLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_HOUR || "300", 10);
8432
- var windows = /* @__PURE__ */ new Map();
8433
- var externalRateLimitExceeded = (userId, now = Date.now()) => {
8434
- const state = windows.get(userId) ?? {
8435
- minuteStart: now,
8436
- minuteCount: 0,
8437
- hourStart: now,
8438
- hourCount: 0,
8439
- lastSeen: now
8440
- };
8441
- if (now - state.minuteStart >= MINUTE_MS) {
8442
- state.minuteStart = now;
8443
- state.minuteCount = 0;
8444
- }
8445
- if (now - state.hourStart >= HOUR_MS2) {
8446
- state.hourStart = now;
8447
- state.hourCount = 0;
8448
- }
8449
- state.minuteCount += 1;
8450
- state.hourCount += 1;
8451
- state.lastSeen = now;
8452
- windows.set(userId, state);
8453
- if (windows.size > 1e4) {
8454
- for (const [key, value] of windows) {
8455
- if (now - value.lastSeen >= HOUR_MS2) windows.delete(key);
8456
- }
8457
- if (windows.size > 1e4) {
8458
- const sorted = [...windows.entries()].sort(
8459
- (a, b) => a[1].lastSeen - b[1].lastSeen
8460
- );
8461
- for (const [key] of sorted) {
8462
- if (windows.size <= 1e4) break;
8463
- windows.delete(key);
8464
- }
8465
- }
8466
- }
8467
- const minuteLimitExceeded = state.minuteCount > perMinuteLimit();
8468
- const hourLimitExceeded = state.hourCount > perHourLimit();
8469
- const limitExceeded = minuteLimitExceeded || hourLimitExceeded;
8470
- if (limitExceeded) {
8471
- const limits = {
8472
- perMinute: perMinuteLimit(),
8473
- perHour: perHourLimit()
8474
- };
8475
- const current = {
8476
- minute: state.minuteCount,
8477
- hour: state.hourCount
8478
- };
8479
- console.warn(
8480
- `[EXULU] Rate limit exceeded for user ${userId}${minuteLimitExceeded ? ` per-minute (${current.minute}/${limits.perMinute})` : ""}${minuteLimitExceeded && hourLimitExceeded ? " and" : ""}${hourLimitExceeded ? ` per-hour (${current.hour}/${limits.perHour})` : ""}`
8481
- );
8482
- }
8483
- return limitExceeded;
8484
- };
8485
- var isExternalUser = (user) => {
8486
- return user?.role?.name === "external";
8487
- };
8488
-
8489
8600
  // src/exulu/channels/wiring.ts
8490
8601
  var channelStoreFromRedis = (client2) => ({
8491
8602
  set: (key, value, opts) => client2.set(key, value, opts.NX ? { EX: opts.EX, NX: true } : { EX: opts.EX }),
@@ -12330,7 +12441,7 @@ async function insertTriggerWithSecretRetry(insertFn, baseRow) {
12330
12441
  import { randomUUID as randomUUID5 } from "crypto";
12331
12442
 
12332
12443
  // src/exulu/email-inbound/verify-signature.ts
12333
- import { createHmac, timingSafeEqual } from "crypto";
12444
+ import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
12334
12445
  var SIGNATURE_REPLAY_WINDOW_SECONDS = 300;
12335
12446
  var REPLAY_TTL_SECONDS = 900;
12336
12447
  function verifyPayloadSignature(rawBody, signatureHeader, timestampHeader, secret) {
@@ -12343,7 +12454,7 @@ function verifyPayloadSignature(rawBody, signatureHeader, timestampHeader, secre
12343
12454
  const expectedBuf = Buffer.from(expected, "utf8");
12344
12455
  const providedBuf = Buffer.from(provided.toLowerCase(), "utf8");
12345
12456
  if (expectedBuf.length !== providedBuf.length) return false;
12346
- return timingSafeEqual(expectedBuf, providedBuf);
12457
+ return timingSafeEqual2(expectedBuf, providedBuf);
12347
12458
  }
12348
12459
  async function isReplay(redis, signature, timestamp) {
12349
12460
  const ts = Number(timestamp);
@@ -14247,13 +14358,7 @@ type PageInfo {
14247
14358
  if (!resolvers[rbacResolverName]) {
14248
14359
  resolvers[rbacResolverName] = {};
14249
14360
  }
14250
- resolvers[rbacResolverName].RBAC = async (parent, args, context) => {
14251
- const { db } = context;
14252
- const resourceId = parent.id;
14253
- const entityName = table.name.singular;
14254
- const rights_mode = parent.rights_mode;
14255
- return RBACResolver(db, entityName, resourceId, rights_mode);
14256
- };
14361
+ resolvers[rbacResolverName].RBAC = async (parent, args, context) => resolveRbacField(table, parent, context);
14257
14362
  }
14258
14363
  }
14259
14364
  typeDefs += `
@@ -17752,6 +17857,133 @@ function registerViewerIdentityRoutes(app, deps) {
17752
17857
  });
17753
17858
  }
17754
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
+
17755
17987
  // src/exulu/tool-api-route.ts
17756
17988
  import { randomUUID as randomUUID9 } from "crypto";
17757
17989
  var TOOL_API_ROUTE_PATH = "/tools/:id";
@@ -17868,6 +18100,23 @@ function registerCreateShareRoute(app, deps) {
17868
18100
  res.status(400).json({ detail: valid.message });
17869
18101
  return;
17870
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
+ }
17871
18120
  const details = planDetails({ ...req.body, archived: void 0 }, now);
17872
18121
  if (!details.ok) {
17873
18122
  res.status(400).json({ detail: details.message });
@@ -17898,6 +18147,7 @@ function registerCreateShareRoute(app, deps) {
17898
18147
  password_hash,
17899
18148
  expires_at: req.body.expires_at ?? null,
17900
18149
  content_type: req.body.content_type ?? null,
18150
+ external_access: req.body.external_access === true,
17901
18151
  rights_mode,
17902
18152
  created_by: auth.user.id,
17903
18153
  ...details.patch,
@@ -20620,7 +20870,7 @@ var handleCredentialDelete = async (req, res) => {
20620
20870
  };
20621
20871
 
20622
20872
  // src/exulu/recall/verify.ts
20623
- import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual2 } from "crypto";
20873
+ import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual3 } from "crypto";
20624
20874
  var TOLERANCE_SECONDS = 5 * 60;
20625
20875
  var header = (headers, ...names) => {
20626
20876
  for (const name of names) {
@@ -20638,7 +20888,7 @@ var safeEqual = (a, b) => {
20638
20888
  const bufA = Buffer.from(a);
20639
20889
  const bufB = Buffer.from(b);
20640
20890
  if (bufA.length !== bufB.length) return false;
20641
- return timingSafeEqual2(bufA, bufB);
20891
+ return timingSafeEqual3(bufA, bufB);
20642
20892
  };
20643
20893
  var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()) => {
20644
20894
  if (!secret) {
@@ -21017,7 +21267,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
21017
21267
  const server = new ApolloServer({
21018
21268
  cache: new InMemoryLRUCache(),
21019
21269
  schema: schema7,
21020
- introspection: true
21270
+ introspection: true,
21271
+ plugins: [
21272
+ companionOperationGuard(
21273
+ companionAllowedOperations((contexts ?? []).map(convertContextToTableDefinition))
21274
+ )
21275
+ ]
21021
21276
  });
21022
21277
  await server.start();
21023
21278
  app.use(
@@ -21036,7 +21291,10 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
21036
21291
  return {
21037
21292
  req,
21038
21293
  db,
21039
- user: authenticationResult.user
21294
+ user: admitCompanionUser(
21295
+ companionRequestState(req.headers),
21296
+ authenticationResult.user
21297
+ )
21040
21298
  };
21041
21299
  }
21042
21300
  })
@@ -24783,6 +25041,7 @@ ${style.markdown}` : params.prompt;
24783
25041
  // Coerced, not `?? []`: see readAgentSlots on why a stored non-array is
24784
25042
  // a real possibility and why a reader has to survive one.
24785
25043
  agent_slots: readAgentSlots(row.agent_slots),
25044
+ external_access: row.external_access === true,
24786
25045
  ...detailsOf(row),
24787
25046
  // Older files, newest first; at most MAX_OLDER_VERSIONS (artifact-library.ts).
24788
25047
  versions: versions.map((v) => ({
@@ -24822,6 +25081,28 @@ ${style.markdown}` : params.prompt;
24822
25081
  res.status(400).json({ detail: valid.message });
24823
25082
  return;
24824
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
+ }
24825
25106
  const details = planDetails(input, now);
24826
25107
  if (!details.ok) {
24827
25108
  res.status(400).json({ detail: details.message });
@@ -24866,6 +25147,7 @@ ${style.markdown}` : params.prompt;
24866
25147
  expires_at: updated.expires_at ?? null,
24867
25148
  rights_mode: updated.rights_mode ?? null,
24868
25149
  agent_slots: readAgentSlots(updated.agent_slots),
25150
+ external_access: updated.external_access === true,
24869
25151
  ...detailsOf(updated),
24870
25152
  version_count: readVersions(updated.versions).length
24871
25153
  });
@@ -24935,6 +25217,13 @@ ${style.markdown}` : params.prompt;
24935
25217
  RBACResolver,
24936
25218
  checkRecordAccess
24937
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
+ });
24938
25227
  registerToolApiRoutes(app, {
24939
25228
  authenticate: (req) => requestValidators.authenticate(req),
24940
25229
  tools,