@igstack/app-catalog-backend-core 0.0.1

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.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/dist/index.d.ts +1934 -0
  3. package/dist/index.d.ts.map +1 -0
  4. package/dist/index.js +2539 -0
  5. package/dist/index.js.map +1 -0
  6. package/package.json +84 -0
  7. package/prisma/migrations/20250526183023_init/migration.sql +71 -0
  8. package/prisma/migrations/migration_lock.toml +3 -0
  9. package/prisma/schema.prisma +149 -0
  10. package/src/__tests__/dummy.test.ts +7 -0
  11. package/src/db/client.ts +42 -0
  12. package/src/db/index.ts +21 -0
  13. package/src/db/syncAppCatalog.ts +312 -0
  14. package/src/db/tableSyncMagazine.ts +32 -0
  15. package/src/db/tableSyncPrismaAdapter.ts +203 -0
  16. package/src/index.ts +126 -0
  17. package/src/middleware/backendResolver.ts +42 -0
  18. package/src/middleware/createEhMiddleware.ts +171 -0
  19. package/src/middleware/database.ts +62 -0
  20. package/src/middleware/featureRegistry.ts +173 -0
  21. package/src/middleware/index.ts +43 -0
  22. package/src/middleware/types.ts +202 -0
  23. package/src/modules/admin/chat/createAdminChatHandler.ts +152 -0
  24. package/src/modules/admin/chat/createDatabaseTools.ts +261 -0
  25. package/src/modules/appCatalog/service.ts +130 -0
  26. package/src/modules/appCatalogAdmin/appCatalogAdminRouter.ts +187 -0
  27. package/src/modules/appCatalogAdmin/catalogBackupController.ts +213 -0
  28. package/src/modules/approvalMethod/approvalMethodRouter.ts +169 -0
  29. package/src/modules/approvalMethod/slugUtils.ts +17 -0
  30. package/src/modules/approvalMethod/syncApprovalMethods.ts +38 -0
  31. package/src/modules/assets/assetRestController.ts +271 -0
  32. package/src/modules/assets/assetUtils.ts +114 -0
  33. package/src/modules/assets/screenshotRestController.ts +195 -0
  34. package/src/modules/assets/screenshotRouter.ts +112 -0
  35. package/src/modules/assets/syncAssets.ts +277 -0
  36. package/src/modules/assets/upsertAsset.ts +46 -0
  37. package/src/modules/auth/auth.ts +51 -0
  38. package/src/modules/auth/authProviders.ts +40 -0
  39. package/src/modules/auth/authRouter.ts +75 -0
  40. package/src/modules/auth/authorizationUtils.ts +132 -0
  41. package/src/modules/auth/devMockUserUtils.ts +49 -0
  42. package/src/modules/auth/registerAuthRoutes.ts +33 -0
  43. package/src/modules/icons/iconRestController.ts +171 -0
  44. package/src/modules/icons/iconRouter.ts +180 -0
  45. package/src/modules/icons/iconService.ts +73 -0
  46. package/src/modules/icons/iconUtils.ts +46 -0
  47. package/src/prisma-json-types.d.ts +34 -0
  48. package/src/server/controller.ts +47 -0
  49. package/src/server/ehStaticControllerContract.ts +19 -0
  50. package/src/server/ehTrpcContext.ts +26 -0
  51. package/src/server/trpcSetup.ts +89 -0
  52. package/src/types/backend/api.ts +73 -0
  53. package/src/types/backend/common.ts +10 -0
  54. package/src/types/backend/companySpecificBackend.ts +5 -0
  55. package/src/types/backend/dataSources.ts +25 -0
  56. package/src/types/backend/deployments.ts +40 -0
  57. package/src/types/common/app/appTypes.ts +13 -0
  58. package/src/types/common/app/ui/appUiTypes.ts +12 -0
  59. package/src/types/common/appCatalogTypes.ts +65 -0
  60. package/src/types/common/approvalMethodTypes.ts +149 -0
  61. package/src/types/common/env/envTypes.ts +7 -0
  62. package/src/types/common/resourceTypes.ts +8 -0
  63. package/src/types/common/sharedTypes.ts +5 -0
  64. package/src/types/index.ts +21 -0
package/dist/index.js ADDED
@@ -0,0 +1,2539 @@
1
+ import { Prisma, PrismaClient } from "@prisma/client";
2
+ import { group, mapValues, omit, pick } from "radashi";
3
+ import { z } from "zod";
4
+ import { tableSync } from "@igstack/app-catalog-table-sync";
5
+ import { readFile, readdir, stat } from "node:fs/promises";
6
+ import { createHash } from "node:crypto";
7
+ import sharp from "sharp";
8
+ import { TRPCError, initTRPC } from "@trpc/server";
9
+ import { betterAuth } from "better-auth";
10
+ import { prismaAdapter } from "better-auth/adapters/prisma";
11
+ import { toNodeHandler } from "better-auth/node";
12
+ import { stepCountIs, streamText, tool } from "ai";
13
+ import multer from "multer";
14
+ import { readFileSync, readdirSync } from "node:fs";
15
+ import { extname, join } from "node:path";
16
+ import express, { Router } from "express";
17
+ import * as trpcExpress from "@trpc/server/adapters/express";
18
+
19
+ //#region src/db/client.ts
20
+ let prismaClient = null;
21
+ /**
22
+ * Gets the internal Prisma client instance.
23
+ * Creates one if it doesn't exist.
24
+ */
25
+ function getDbClient() {
26
+ if (!prismaClient) prismaClient = new PrismaClient();
27
+ return prismaClient;
28
+ }
29
+ /**
30
+ * Sets the internal Prisma client instance.
31
+ * Used by middleware to bridge with existing getDbClient() usage.
32
+ */
33
+ function setDbClient(client) {
34
+ prismaClient = client;
35
+ }
36
+ /**
37
+ * Connects to the database.
38
+ * Call this before performing database operations.
39
+ */
40
+ async function connectDb() {
41
+ await getDbClient().$connect();
42
+ }
43
+ /**
44
+ * Disconnects from the database.
45
+ * Call this when done with database operations (e.g., in scripts).
46
+ */
47
+ async function disconnectDb() {
48
+ if (prismaClient) {
49
+ await prismaClient.$disconnect();
50
+ prismaClient = null;
51
+ }
52
+ }
53
+
54
+ //#endregion
55
+ //#region src/modules/appCatalog/service.ts
56
+ async function getGroupingTagDefinitionsFromPrisma() {
57
+ return (await getDbClient().dbAppTagDefinition.findMany()).map((row) => omit(row, [
58
+ "id",
59
+ "updatedAt",
60
+ "createdAt"
61
+ ]));
62
+ }
63
+ async function getApprovalMethodsFromPrisma() {
64
+ return (await getDbClient().dbApprovalMethod.findMany()).map((row) => {
65
+ const baseFields = {
66
+ slug: row.slug,
67
+ displayName: row.displayName
68
+ };
69
+ const config = row.config ?? {};
70
+ switch (row.type) {
71
+ case "service": return {
72
+ ...baseFields,
73
+ type: "service",
74
+ config
75
+ };
76
+ case "personTeam": return {
77
+ ...baseFields,
78
+ type: "personTeam",
79
+ config
80
+ };
81
+ case "custom": return {
82
+ ...baseFields,
83
+ type: "custom",
84
+ config
85
+ };
86
+ }
87
+ });
88
+ }
89
+ async function getAppsFromPrisma() {
90
+ return (await getDbClient().dbAppForCatalog.findMany()).map((row) => {
91
+ const accessRequest = row.accessRequest;
92
+ const teams = row.teams ?? [];
93
+ const tags = row.tags ?? [];
94
+ const screenshotIds = row.screenshotIds ?? [];
95
+ const notes = row.notes == null ? void 0 : row.notes;
96
+ const appUrl = row.appUrl == null ? void 0 : row.appUrl;
97
+ const iconName = row.iconName == null ? void 0 : row.iconName;
98
+ return {
99
+ id: row.id,
100
+ slug: row.slug,
101
+ displayName: row.displayName,
102
+ description: row.description,
103
+ accessRequest,
104
+ teams,
105
+ notes,
106
+ tags,
107
+ appUrl,
108
+ iconName,
109
+ screenshotIds
110
+ };
111
+ });
112
+ }
113
+ async function getAppCatalogData(getAppsOptional) {
114
+ return {
115
+ apps: getAppsOptional ? await getAppsOptional() : await getAppsFromPrisma(),
116
+ tagsDefinitions: await getGroupingTagDefinitionsFromPrisma(),
117
+ approvalMethods: await getApprovalMethodsFromPrisma()
118
+ };
119
+ }
120
+
121
+ //#endregion
122
+ //#region src/db/tableSyncPrismaAdapter.ts
123
+ function getPrismaModelOperations(prisma, prismaModelName) {
124
+ return prisma[prismaModelName.slice(0, 1).toLowerCase() + prismaModelName.slice(1)];
125
+ }
126
+ function tableSyncPrisma(params) {
127
+ const { prisma, prismaModelName, uniqColumns, where: whereGlobal, upsertOnly } = params;
128
+ const prismOperations = getPrismaModelOperations(prisma, prismaModelName);
129
+ const idColumn = params.id ?? "id";
130
+ return tableSync({
131
+ id: idColumn,
132
+ uniqColumns,
133
+ readAll: async () => {
134
+ const findManyArgs = whereGlobal ? { where: whereGlobal } : {};
135
+ return await prismOperations.findMany(findManyArgs);
136
+ },
137
+ writeAll: async (createData, update, deleteIds) => {
138
+ const prismaUniqKey = params.uniqColumns.join("_");
139
+ const relationColumnList = params.relationColumns ?? [];
140
+ return prisma.$transaction(async (tx) => {
141
+ const txOps = getPrismaModelOperations(tx, prismaModelName);
142
+ for (const { data, where } of update) {
143
+ const uniqKeyWhere = Object.keys(where).length > 1 ? { [prismaUniqKey]: where } : where;
144
+ const dataScalar = omit(data, relationColumnList);
145
+ const dataRelations = mapValues(pick(data, relationColumnList), (value) => {
146
+ return { set: value };
147
+ });
148
+ await txOps.update({
149
+ data: {
150
+ ...dataScalar,
151
+ ...dataRelations
152
+ },
153
+ where: { ...uniqKeyWhere }
154
+ });
155
+ }
156
+ if (upsertOnly !== true) await txOps.deleteMany({ where: { [idColumn]: { in: deleteIds } } });
157
+ const createDataMapped = createData.map((data) => {
158
+ const dataScalar = omit(data, relationColumnList);
159
+ const dataRelations = mapValues(pick(data, relationColumnList), (value) => {
160
+ return { connect: value };
161
+ });
162
+ return {
163
+ ...dataScalar,
164
+ ...dataRelations
165
+ };
166
+ });
167
+ if (createDataMapped.length > 0) {
168
+ const uniqKeysInCreate = /* @__PURE__ */ new Set();
169
+ const duplicateKeys = [];
170
+ for (const data of createDataMapped) {
171
+ const key = params.uniqColumns.map((col) => {
172
+ const value = data[col];
173
+ return value === null || value === void 0 ? "null" : String(value);
174
+ }).join(":");
175
+ if (uniqKeysInCreate.has(key)) duplicateKeys.push(key);
176
+ else uniqKeysInCreate.add(key);
177
+ }
178
+ if (duplicateKeys.length > 0) {
179
+ const uniqColumnsStr = params.uniqColumns.join(", ");
180
+ throw new Error(`Duplicate unique key values found in data to be created. Model: ${prismaModelName}, Unique columns: [${uniqColumnsStr}], Duplicate keys: [${duplicateKeys.join(", ")}]`);
181
+ }
182
+ }
183
+ const results = [];
184
+ if (relationColumnList.length === 0) {
185
+ const batchResult = await txOps.createManyAndReturn({ data: createDataMapped });
186
+ results.push(...batchResult);
187
+ } else for (const dataMappedElement of createDataMapped) {
188
+ const newVar = await txOps.create({ data: dataMappedElement });
189
+ results.push(newVar);
190
+ }
191
+ return results;
192
+ });
193
+ }
194
+ });
195
+ }
196
+
197
+ //#endregion
198
+ //#region src/db/tableSyncMagazine.ts
199
+ const TABLE_SYNC_MAGAZINE = {
200
+ DbAppForCatalog: {
201
+ prismaModelName: "DbAppForCatalog",
202
+ uniqColumns: ["slug"]
203
+ },
204
+ DbAppTagDefinition: {
205
+ prismaModelName: "DbAppTagDefinition",
206
+ uniqColumns: ["prefix"]
207
+ },
208
+ DbApprovalMethod: {
209
+ id: "slug",
210
+ prismaModelName: "DbApprovalMethod",
211
+ uniqColumns: ["slug"]
212
+ }
213
+ };
214
+
215
+ //#endregion
216
+ //#region src/modules/assets/assetUtils.ts
217
+ /**
218
+ * Extract image dimensions from a buffer using sharp
219
+ */
220
+ async function getImageDimensions(buffer) {
221
+ try {
222
+ const metadata = await sharp(buffer).metadata();
223
+ return {
224
+ width: metadata.width,
225
+ height: metadata.height
226
+ };
227
+ } catch (error) {
228
+ console.error("Error extracting image dimensions:", error);
229
+ return {
230
+ width: void 0,
231
+ height: void 0
232
+ };
233
+ }
234
+ }
235
+ /**
236
+ * Resize an image buffer to the specified dimensions
237
+ * @param buffer - The image buffer to resize
238
+ * @param width - Target width (optional)
239
+ * @param height - Target height (optional)
240
+ * @param format - Output format ('png', 'jpeg', 'webp'), auto-detected if not provided
241
+ */
242
+ async function resizeImage(buffer, width, height, format) {
243
+ let pipeline = sharp(buffer);
244
+ if (width || height) pipeline = pipeline.resize({
245
+ width,
246
+ height,
247
+ fit: "inside",
248
+ withoutEnlargement: true
249
+ });
250
+ if (format === "png") pipeline = pipeline.png();
251
+ else if (format === "webp") pipeline = pipeline.webp();
252
+ else if (format === "jpeg") pipeline = pipeline.jpeg();
253
+ return pipeline.toBuffer();
254
+ }
255
+ /**
256
+ * Generate SHA-256 checksum for a buffer
257
+ */
258
+ function generateChecksum(buffer) {
259
+ return createHash("sha256").update(buffer).digest("hex");
260
+ }
261
+ /**
262
+ * Detect image format from mime type
263
+ */
264
+ function getImageFormat(mimeType) {
265
+ if (mimeType.includes("png")) return "png";
266
+ if (mimeType.includes("webp")) return "webp";
267
+ if (mimeType.includes("jpeg") || mimeType.includes("jpg")) return "jpeg";
268
+ return null;
269
+ }
270
+ /**
271
+ * Check if a mime type represents a raster image (not SVG)
272
+ */
273
+ function isRasterImage(mimeType) {
274
+ return mimeType.startsWith("image/") && !mimeType.includes("svg");
275
+ }
276
+ async function parseAssetMeta(p) {
277
+ const { width, height, format, size } = await sharp(p.buffer).metadata();
278
+ return {
279
+ checksum: generateChecksum(p.buffer),
280
+ width,
281
+ height,
282
+ mimeType: format ? {
283
+ jpeg: "image/jpeg",
284
+ jpg: "image/jpeg",
285
+ png: "image/png",
286
+ webp: "image/webp",
287
+ avif: "image/avif",
288
+ tiff: "image/tiff",
289
+ gif: "image/gif",
290
+ heif: "image/heif",
291
+ raw: "application/octet-stream"
292
+ }[format] ?? `image/${format}` : "application/octet-stream",
293
+ fileSize: size || 0
294
+ };
295
+ }
296
+
297
+ //#endregion
298
+ //#region src/modules/assets/upsertAsset.ts
299
+ async function upsertAsset({ prisma, buffer, name, originalFilename, assetType }) {
300
+ const { checksum, fileSize, width, height, mimeType } = await parseAssetMeta({
301
+ buffer,
302
+ originalFilename
303
+ });
304
+ const existing = await prisma.dbAsset.findUnique({ where: { name } });
305
+ if (existing) return existing.id;
306
+ return (await prisma.dbAsset.create({ data: {
307
+ name,
308
+ checksum,
309
+ assetType,
310
+ content: new Uint8Array(buffer),
311
+ mimeType,
312
+ fileSize,
313
+ width,
314
+ height
315
+ } })).id;
316
+ }
317
+
318
+ //#endregion
319
+ //#region src/db/syncAppCatalog.ts
320
+ function isFileNotFoundError(error) {
321
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
322
+ }
323
+ async function processAssetDirectory(dirPath, appSlug, assetType, prisma) {
324
+ try {
325
+ const files = await readdir(dirPath);
326
+ const assetIds = [];
327
+ for (let i = 0; i < files.length; i++) {
328
+ const fileName = files[i];
329
+ if (!fileName) continue;
330
+ const assetName = assetType === "screenshot" ? `${appSlug}-screenshot-${i + 1}` : `${appSlug}-icon`;
331
+ const id = await upsertAsset({
332
+ prisma,
333
+ buffer: await readFile(`${dirPath}/${fileName}`),
334
+ originalFilename: fileName,
335
+ name: assetName,
336
+ assetType
337
+ });
338
+ assetIds.push(id);
339
+ if (assetType === "icon") break;
340
+ }
341
+ return assetIds;
342
+ } catch (error) {
343
+ if (isFileNotFoundError(error)) return [];
344
+ throw error;
345
+ }
346
+ }
347
+ async function syncAppAssets(appSlug, appPath, prisma) {
348
+ return {
349
+ screenshotIds: await processAssetDirectory(`${appPath}/screenshots`, appSlug, "screenshot", prisma),
350
+ iconName: (await processAssetDirectory(`${appPath}/icons`, appSlug, "icon", prisma)).length > 0 ? `${appSlug}-icon` : null
351
+ };
352
+ }
353
+ async function syncAssetsFromFileSystem(apps, allAppsAssetsPath) {
354
+ const appDirectories = await readdir(allAppsAssetsPath);
355
+ const prisma = getDbClient();
356
+ const bySlug = group(apps, (a) => a.slug);
357
+ for (const appDirName of appDirectories) {
358
+ try {
359
+ if (!(await stat(`${allAppsAssetsPath}/${appDirName}`)).isDirectory()) continue;
360
+ } catch (error) {
361
+ if (isFileNotFoundError(error)) continue;
362
+ throw error;
363
+ }
364
+ const appSlug = appDirName;
365
+ if (!bySlug[appSlug]) throw new Error(`App '${appSlug}' does not exist in the app catalog. Existing apps: ${Object.keys(bySlug).join(", ")}`);
366
+ try {
367
+ const { screenshotIds, iconName } = await syncAppAssets(appSlug, `${allAppsAssetsPath}/${appDirName}`, prisma);
368
+ const updateData = {};
369
+ if (screenshotIds.length > 0) updateData.screenshotIds = screenshotIds;
370
+ if (iconName !== null) updateData.iconName = iconName;
371
+ if (Object.keys(updateData).length > 0) await prisma.dbAppForCatalog.update({
372
+ where: { slug: appSlug },
373
+ data: updateData
374
+ });
375
+ } catch (error) {
376
+ const errorMessage = error instanceof Error ? error.message : String(error);
377
+ throw new Error(`Error while upserting assets for app '${appSlug}': ${errorMessage}`);
378
+ }
379
+ }
380
+ }
381
+ /**
382
+ * Syncs app catalog data to the database using table sync.
383
+ * This will create new apps, update existing ones, and delete any that are no longer in the input.
384
+ *
385
+ * Note: Call connectDb() before and disconnectDb() after if running in a script.
386
+ */
387
+ async function syncAppCatalog(apps, tagsDefinitions, approvalMethods, sreenshotsPath) {
388
+ try {
389
+ const prisma = getDbClient();
390
+ await tableSyncPrisma({
391
+ prisma,
392
+ ...TABLE_SYNC_MAGAZINE.DbApprovalMethod
393
+ }).sync(approvalMethods);
394
+ const sync = tableSyncPrisma({
395
+ prisma,
396
+ ...TABLE_SYNC_MAGAZINE.DbAppForCatalog
397
+ });
398
+ await tableSyncPrisma({
399
+ prisma,
400
+ ...TABLE_SYNC_MAGAZINE.DbAppTagDefinition
401
+ }).sync(tagsDefinitions);
402
+ const dbApps = apps.map((app) => {
403
+ return {
404
+ slug: app.slug || app.displayName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""),
405
+ displayName: app.displayName,
406
+ description: app.description,
407
+ teams: app.teams ?? [],
408
+ accessRequest: app.accessRequest ?? null,
409
+ notes: app.notes ?? null,
410
+ tags: app.tags ?? [],
411
+ appUrl: app.appUrl ?? null,
412
+ links: app.links ?? null,
413
+ iconName: app.iconName ?? null,
414
+ screenshotIds: app.screenshotIds ?? []
415
+ };
416
+ });
417
+ const actual = (await sync.sync(dbApps)).getActual();
418
+ if (sreenshotsPath) await syncAssetsFromFileSystem(apps, sreenshotsPath);
419
+ else console.warn("DO not sync screenhots");
420
+ return {
421
+ created: actual.length - apps.length + (apps.length - actual.length),
422
+ updated: 0,
423
+ deleted: 0,
424
+ total: actual.length
425
+ };
426
+ } catch (error) {
427
+ const errorMessage = error instanceof Error ? error.message : String(error);
428
+ const errorStack = error instanceof Error ? error.stack : void 0;
429
+ throw new Error(`Error syncing app catalog: ${errorMessage}\n\nDetails:\n${errorStack || "No stack trace available"}`);
430
+ }
431
+ }
432
+
433
+ //#endregion
434
+ //#region src/modules/auth/authorizationUtils.ts
435
+ /**
436
+ * Extract groups from user object
437
+ * Groups can be stored in different locations depending on the OAuth provider
438
+ */
439
+ function getUserGroups(user) {
440
+ if (!user) {
441
+ console.log("[getUserGroups] No user provided");
442
+ return [];
443
+ }
444
+ console.log("[getUserGroups] === USER OBJECT DEBUG ===");
445
+ console.log("[getUserGroups] User ID:", user.id);
446
+ console.log("[getUserGroups] User email:", user.email);
447
+ console.log("[getUserGroups] User.env_hopper_groups:", user.env_hopper_groups);
448
+ console.log("[getUserGroups] User.groups:", user.groups);
449
+ console.log("[getUserGroups] User.oktaGroups:", user.oktaGroups);
450
+ console.log("[getUserGroups] User.roles:", user.roles);
451
+ console.log("[getUserGroups] All user keys:", Object.keys(user));
452
+ console.log("[getUserGroups] Full user object:", JSON.stringify(user, null, 2));
453
+ const groups = user.env_hopper_groups || user.groups || user.oktaGroups || user.roles || [];
454
+ const result = Array.isArray(groups) ? groups : [];
455
+ console.log("[getUserGroups] Final groups result:", result);
456
+ return result;
457
+ }
458
+ /**
459
+ * Check if user is a member of any of the specified groups
460
+ */
461
+ function isMemberOfAnyGroup(user, allowedGroups) {
462
+ const userGroups = getUserGroups(user);
463
+ return allowedGroups.some((group$1) => userGroups.includes(group$1));
464
+ }
465
+ /**
466
+ * Check if user is a member of all specified groups
467
+ */
468
+ function isMemberOfAllGroups(user, requiredGroups) {
469
+ const userGroups = getUserGroups(user);
470
+ return requiredGroups.every((group$1) => userGroups.includes(group$1));
471
+ }
472
+ /**
473
+ * Check if user has admin permissions
474
+ * @param user User object with groups
475
+ * @param adminGroups List of admin group names (default: ['env_hopper_ui_super_admins'])
476
+ */
477
+ function isAdmin(user, adminGroups = ["env_hopper_ui_super_admins"]) {
478
+ return isMemberOfAnyGroup(user, adminGroups);
479
+ }
480
+ /**
481
+ * Require admin permissions - throws error if not admin
482
+ * @param user User object with groups
483
+ * @param adminGroups List of admin group names (default: ['env_hopper_ui_super_admins'])
484
+ */
485
+ function requireAdmin(user, adminGroups = ["env_hopper_ui_super_admins"]) {
486
+ if (!isAdmin(user, adminGroups)) throw new Error("Forbidden: Admin access required");
487
+ }
488
+ /**
489
+ * Require membership in specific groups - throws error if not member
490
+ */
491
+ function requireGroups(user, groups) {
492
+ if (!isMemberOfAnyGroup(user, groups)) throw new Error(`Forbidden: Membership in one of these groups required: ${groups.join(", ")}`);
493
+ }
494
+
495
+ //#endregion
496
+ //#region src/server/trpcSetup.ts
497
+ /**
498
+ * Initialization of tRPC backend
499
+ * Should be done only once per backend!
500
+ */
501
+ const t = initTRPC.context().create({ errorFormatter({ error, shape }) {
502
+ var _data;
503
+ console.error("[tRPC Error]", {
504
+ path: (_data = shape.data) === null || _data === void 0 ? void 0 : _data.path,
505
+ code: error.code,
506
+ message: error.message,
507
+ cause: error.cause,
508
+ stack: error.stack
509
+ });
510
+ return shape;
511
+ } });
512
+ /**
513
+ * Export reusable router and procedure helpers
514
+ */
515
+ const router = t.router;
516
+ const publicProcedure = t.procedure;
517
+ /**
518
+ * Middleware to check if user is authenticated
519
+ */
520
+ const isAuthenticated = t.middleware(({ ctx, next }) => {
521
+ if (!ctx.user) throw new TRPCError({
522
+ code: "UNAUTHORIZED",
523
+ message: "You must be logged in to access this resource"
524
+ });
525
+ return next({ ctx: {
526
+ ...ctx,
527
+ user: ctx.user
528
+ } });
529
+ });
530
+ /**
531
+ * Middleware to check if user is an admin
532
+ */
533
+ const isAdminMiddleware = t.middleware(({ ctx, next }) => {
534
+ if (!ctx.user) throw new TRPCError({
535
+ code: "UNAUTHORIZED",
536
+ message: "You must be logged in to access this resource"
537
+ });
538
+ console.log("[isAdminMiddleware] === ADMIN CHECK DEBUG ===");
539
+ console.log("[isAdminMiddleware] User:", ctx.user.email);
540
+ console.log("[isAdminMiddleware] Required admin groups:", ctx.adminGroups);
541
+ console.log("[isAdminMiddleware] Calling isAdmin()...");
542
+ const hasAdminAccess = isAdmin(ctx.user, ctx.adminGroups);
543
+ console.log("[isAdminMiddleware] Has admin access:", hasAdminAccess);
544
+ if (!hasAdminAccess) throw new TRPCError({
545
+ code: "FORBIDDEN",
546
+ message: `You must be an admin to access this resource. Required groups: ${ctx.adminGroups.join(", ") || "env_hopper_ui_super_admins"}`
547
+ });
548
+ return next({ ctx: {
549
+ ...ctx,
550
+ user: ctx.user
551
+ } });
552
+ });
553
+ /**
554
+ * Admin procedure that requires admin permissions
555
+ */
556
+ const adminProcedure = t.procedure.use(isAdminMiddleware);
557
+ /**
558
+ * Protected procedure that requires authentication (but not admin)
559
+ */
560
+ const protectedProcedure = t.procedure.use(isAuthenticated);
561
+
562
+ //#endregion
563
+ //#region src/modules/appCatalogAdmin/appCatalogAdminRouter.ts
564
+ const AccessMethodSchema = z.object({ type: z.enum([
565
+ "bot",
566
+ "ticketing",
567
+ "email",
568
+ "self-service",
569
+ "documentation",
570
+ "manual"
571
+ ]) }).loose();
572
+ const AppLinkSchema = z.object({
573
+ displayName: z.string().optional(),
574
+ url: z.url()
575
+ });
576
+ const AppRoleSchema = z.object({
577
+ name: z.string(),
578
+ description: z.string().optional()
579
+ });
580
+ const ApproverContactSchema = z.object({
581
+ displayName: z.string(),
582
+ contact: z.string().optional()
583
+ });
584
+ const ApprovalUrlSchema = z.object({
585
+ label: z.string().optional(),
586
+ url: z.url()
587
+ });
588
+ const AppAccessRequestSchema = z.object({
589
+ approvalMethodId: z.string(),
590
+ comments: z.string().optional(),
591
+ requestPrompt: z.string().optional(),
592
+ postApprovalInstructions: z.string().optional(),
593
+ roles: z.array(AppRoleSchema).optional(),
594
+ approvers: z.array(ApproverContactSchema).optional(),
595
+ urls: z.array(ApprovalUrlSchema).optional(),
596
+ whoToReachOut: z.string().optional()
597
+ });
598
+ const CreateAppForCatalogSchema = z.object({
599
+ slug: z.string().min(1).regex(/^[a-z0-9-]+$/, "Slug must be lowercase alphanumeric with hyphens"),
600
+ displayName: z.string().min(1),
601
+ description: z.string(),
602
+ access: AccessMethodSchema.optional(),
603
+ teams: z.array(z.string()).optional(),
604
+ accessRequest: AppAccessRequestSchema.optional(),
605
+ notes: z.string().optional(),
606
+ tags: z.array(z.string()).optional(),
607
+ appUrl: z.url().optional(),
608
+ links: z.array(AppLinkSchema).optional(),
609
+ iconName: z.string().optional(),
610
+ screenshotIds: z.array(z.string()).optional()
611
+ });
612
+ const UpdateAppForCatalogSchema = CreateAppForCatalogSchema.partial().extend({ id: z.string() });
613
+ function createAppCatalogAdminRouter() {
614
+ const prisma = getDbClient();
615
+ return router({
616
+ list: adminProcedure.query(async () => {
617
+ return prisma.dbAppForCatalog.findMany({ orderBy: { displayName: "asc" } });
618
+ }),
619
+ getById: adminProcedure.input(z.object({ id: z.string() })).query(async ({ input }) => {
620
+ return prisma.dbAppForCatalog.findUnique({ where: { id: input.id } });
621
+ }),
622
+ getBySlug: adminProcedure.input(z.object({ slug: z.string() })).query(async ({ input }) => {
623
+ return prisma.dbAppForCatalog.findUnique({ where: { slug: input.slug } });
624
+ }),
625
+ create: adminProcedure.input(CreateAppForCatalogSchema).mutation(async ({ input }) => {
626
+ return prisma.dbAppForCatalog.create({ data: {
627
+ slug: input.slug,
628
+ displayName: input.displayName,
629
+ description: input.description,
630
+ teams: input.teams ?? [],
631
+ accessRequest: input.accessRequest,
632
+ notes: input.notes,
633
+ tags: input.tags ?? [],
634
+ appUrl: input.appUrl,
635
+ links: input.links,
636
+ iconName: input.iconName,
637
+ screenshotIds: input.screenshotIds ?? []
638
+ } });
639
+ }),
640
+ update: adminProcedure.input(UpdateAppForCatalogSchema).mutation(async ({ input }) => {
641
+ const { id,...updateData } = input;
642
+ return prisma.dbAppForCatalog.update({
643
+ where: { id },
644
+ data: {
645
+ ...updateData.slug !== void 0 && { slug: updateData.slug },
646
+ ...updateData.displayName !== void 0 && { displayName: updateData.displayName },
647
+ ...updateData.description !== void 0 && { description: updateData.description },
648
+ ...updateData.teams !== void 0 && { teams: updateData.teams },
649
+ ...updateData.accessRequest !== void 0 && { accessRequest: updateData.accessRequest },
650
+ ...updateData.notes !== void 0 && { notes: updateData.notes },
651
+ ...updateData.tags !== void 0 && { tags: updateData.tags },
652
+ ...updateData.appUrl !== void 0 && { appUrl: updateData.appUrl },
653
+ ...updateData.links !== void 0 && { links: updateData.links },
654
+ ...updateData.iconName !== void 0 && { iconName: updateData.iconName },
655
+ ...updateData.screenshotIds !== void 0 && { screenshotIds: updateData.screenshotIds }
656
+ }
657
+ });
658
+ }),
659
+ updateScreenshots: adminProcedure.input(z.object({
660
+ id: z.string(),
661
+ screenshotIds: z.array(z.string())
662
+ })).mutation(async ({ input }) => {
663
+ return prisma.dbAppForCatalog.update({
664
+ where: { id: input.id },
665
+ data: { screenshotIds: input.screenshotIds }
666
+ });
667
+ }),
668
+ delete: adminProcedure.input(z.object({ id: z.string() })).mutation(async ({ input }) => {
669
+ return prisma.dbAppForCatalog.delete({ where: { id: input.id } });
670
+ })
671
+ });
672
+ }
673
+
674
+ //#endregion
675
+ //#region src/modules/approvalMethod/slugUtils.ts
676
+ /**
677
+ * Generates a URL-friendly slug from a display name.
678
+ * Converts to lowercase and replaces non-alphanumeric characters with hyphens.
679
+ *
680
+ * @param displayName - The display name to convert
681
+ * @returns A slug suitable for use as a primary key
682
+ *
683
+ * @example
684
+ * generateSlugFromDisplayName("My Service") // "my-service"
685
+ * generateSlugFromDisplayName("John's Team") // "john-s-team"
686
+ */
687
+ function generateSlugFromDisplayName(displayName) {
688
+ return displayName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
689
+ }
690
+
691
+ //#endregion
692
+ //#region src/modules/approvalMethod/approvalMethodRouter.ts
693
+ const ReachOutContactSchema = z.object({
694
+ displayName: z.string(),
695
+ contact: z.string()
696
+ });
697
+ const ServiceConfigSchema = z.object({
698
+ url: z.url().optional(),
699
+ icon: z.string().optional()
700
+ });
701
+ const PersonTeamConfigSchema = z.object({ reachOutContacts: z.array(ReachOutContactSchema).optional() });
702
+ const CustomConfigSchema = z.object({});
703
+ const ApprovalMethodConfigSchema = z.union([
704
+ ServiceConfigSchema,
705
+ PersonTeamConfigSchema,
706
+ CustomConfigSchema
707
+ ]);
708
+ const CreateApprovalMethodSchema = z.object({
709
+ type: z.enum([
710
+ "service",
711
+ "personTeam",
712
+ "custom"
713
+ ]),
714
+ displayName: z.string().min(1),
715
+ config: ApprovalMethodConfigSchema.optional()
716
+ });
717
+ const UpdateApprovalMethodSchema = z.object({
718
+ slug: z.string(),
719
+ type: z.enum([
720
+ "service",
721
+ "personTeam",
722
+ "custom"
723
+ ]).optional(),
724
+ displayName: z.string().min(1).optional(),
725
+ config: ApprovalMethodConfigSchema.optional()
726
+ });
727
+ /**
728
+ * Convert Prisma DbApprovalMethod to our ApprovalMethod type.
729
+ * This ensures tRPC infers proper types for frontend consumers.
730
+ */
731
+ function toApprovalMethod(db) {
732
+ const baseFields = {
733
+ slug: db.slug,
734
+ displayName: db.displayName,
735
+ createdAt: db.createdAt,
736
+ updatedAt: db.updatedAt
737
+ };
738
+ const config = db.config ?? {};
739
+ switch (db.type) {
740
+ case "service": return {
741
+ ...baseFields,
742
+ type: "service",
743
+ config
744
+ };
745
+ case "personTeam": return {
746
+ ...baseFields,
747
+ type: "personTeam",
748
+ config
749
+ };
750
+ case "custom": return {
751
+ ...baseFields,
752
+ type: "custom",
753
+ config
754
+ };
755
+ }
756
+ }
757
+ function createApprovalMethodRouter() {
758
+ return router({
759
+ list: publicProcedure.query(async () => {
760
+ return (await getDbClient().dbApprovalMethod.findMany({ orderBy: { displayName: "asc" } })).map(toApprovalMethod);
761
+ }),
762
+ getById: publicProcedure.input(z.object({ slug: z.string() })).query(async ({ input }) => {
763
+ const result = await getDbClient().dbApprovalMethod.findUnique({ where: { slug: input.slug } });
764
+ return result ? toApprovalMethod(result) : null;
765
+ }),
766
+ create: adminProcedure.input(CreateApprovalMethodSchema).mutation(async ({ input }) => {
767
+ return toApprovalMethod(await getDbClient().dbApprovalMethod.create({ data: {
768
+ slug: generateSlugFromDisplayName(input.displayName),
769
+ type: input.type,
770
+ displayName: input.displayName,
771
+ config: input.config ?? Prisma.JsonNull
772
+ } }));
773
+ }),
774
+ update: adminProcedure.input(UpdateApprovalMethodSchema).mutation(async ({ input }) => {
775
+ const prisma = getDbClient();
776
+ const { slug,...updateData } = input;
777
+ return toApprovalMethod(await prisma.dbApprovalMethod.update({
778
+ where: { slug },
779
+ data: {
780
+ ...updateData.type !== void 0 && { type: updateData.type },
781
+ ...updateData.displayName !== void 0 && { displayName: updateData.displayName },
782
+ ...updateData.config !== void 0 && { config: updateData.config ?? Prisma.JsonNull }
783
+ }
784
+ }));
785
+ }),
786
+ delete: adminProcedure.input(z.object({ slug: z.string() })).mutation(async ({ input }) => {
787
+ return toApprovalMethod(await getDbClient().dbApprovalMethod.delete({ where: { slug: input.slug } }));
788
+ }),
789
+ listByType: publicProcedure.input(z.object({ type: z.enum([
790
+ "service",
791
+ "personTeam",
792
+ "custom"
793
+ ]) })).query(async ({ input }) => {
794
+ return (await getDbClient().dbApprovalMethod.findMany({
795
+ where: { type: input.type },
796
+ orderBy: { displayName: "asc" }
797
+ })).map(toApprovalMethod);
798
+ })
799
+ });
800
+ }
801
+
802
+ //#endregion
803
+ //#region src/modules/assets/screenshotRouter.ts
804
+ function createScreenshotRouter() {
805
+ return router({
806
+ list: publicProcedure.query(async () => {
807
+ return getDbClient().dbAsset.findMany({
808
+ where: { assetType: "screenshot" },
809
+ select: {
810
+ id: true,
811
+ name: true,
812
+ mimeType: true,
813
+ fileSize: true,
814
+ width: true,
815
+ height: true,
816
+ createdAt: true,
817
+ updatedAt: true
818
+ },
819
+ orderBy: { createdAt: "desc" }
820
+ });
821
+ }),
822
+ getOne: publicProcedure.input(z.object({ id: z.string() })).query(async ({ input }) => {
823
+ return getDbClient().dbAsset.findFirst({
824
+ where: {
825
+ id: input.id,
826
+ assetType: "screenshot"
827
+ },
828
+ select: {
829
+ id: true,
830
+ name: true,
831
+ mimeType: true,
832
+ fileSize: true,
833
+ width: true,
834
+ height: true,
835
+ createdAt: true,
836
+ updatedAt: true
837
+ }
838
+ });
839
+ }),
840
+ getByAppSlug: publicProcedure.input(z.object({ appSlug: z.string() })).query(async ({ input }) => {
841
+ const prisma = getDbClient();
842
+ const app = await prisma.dbAppForCatalog.findUnique({
843
+ where: { slug: input.appSlug },
844
+ select: { screenshotIds: true }
845
+ });
846
+ if (!app) return [];
847
+ return prisma.dbAsset.findMany({
848
+ where: {
849
+ id: { in: app.screenshotIds },
850
+ assetType: "screenshot"
851
+ },
852
+ select: {
853
+ id: true,
854
+ name: true,
855
+ mimeType: true,
856
+ fileSize: true,
857
+ width: true,
858
+ height: true,
859
+ createdAt: true,
860
+ updatedAt: true
861
+ }
862
+ });
863
+ }),
864
+ getFirstByAppSlug: publicProcedure.input(z.object({ appSlug: z.string() })).query(async ({ input }) => {
865
+ const prisma = getDbClient();
866
+ const app = await prisma.dbAppForCatalog.findUnique({
867
+ where: { slug: input.appSlug },
868
+ select: { screenshotIds: true }
869
+ });
870
+ if (!app || app.screenshotIds.length === 0) return null;
871
+ return prisma.dbAsset.findUnique({
872
+ where: { id: app.screenshotIds[0] },
873
+ select: {
874
+ id: true,
875
+ name: true,
876
+ mimeType: true,
877
+ fileSize: true,
878
+ width: true,
879
+ height: true,
880
+ createdAt: true,
881
+ updatedAt: true
882
+ }
883
+ });
884
+ })
885
+ });
886
+ }
887
+
888
+ //#endregion
889
+ //#region src/modules/auth/authRouter.ts
890
+ /**
891
+ * Create auth tRPC procedures
892
+ * @param t - tRPC instance
893
+ * @param auth - Better Auth instance (optional, for future extensions)
894
+ * @returns tRPC router with auth procedures
895
+ */
896
+ function createAuthRouter(t$1, auth) {
897
+ const router$1 = t$1.router;
898
+ const publicProcedure$1 = t$1.procedure;
899
+ return router$1({
900
+ getSession: publicProcedure$1.query(async ({ ctx }) => {
901
+ return {
902
+ user: ctx.user ?? null,
903
+ isAuthenticated: !!ctx.user
904
+ };
905
+ }),
906
+ getProviders: publicProcedure$1.query(() => {
907
+ const providers = [];
908
+ const authOptions = auth === null || auth === void 0 ? void 0 : auth.options;
909
+ if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.socialProviders) {
910
+ const socialProviders = authOptions.socialProviders;
911
+ Object.keys(socialProviders).forEach((key) => {
912
+ if (socialProviders[key]) providers.push(key);
913
+ });
914
+ }
915
+ if (authOptions === null || authOptions === void 0 ? void 0 : authOptions.plugins) authOptions.plugins.forEach((plugin) => {
916
+ var _pluginWithConfig$opt;
917
+ const pluginWithConfig = plugin;
918
+ if (pluginWithConfig.id === "generic-oauth" && ((_pluginWithConfig$opt = pluginWithConfig.options) === null || _pluginWithConfig$opt === void 0 ? void 0 : _pluginWithConfig$opt.config)) (Array.isArray(pluginWithConfig.options.config) ? pluginWithConfig.options.config : [pluginWithConfig.options.config]).forEach((config) => {
919
+ if (config.providerId) providers.push(config.providerId);
920
+ });
921
+ });
922
+ return { providers };
923
+ })
924
+ });
925
+ }
926
+
927
+ //#endregion
928
+ //#region src/modules/icons/iconUtils.ts
929
+ /**
930
+ * Get file extension from MIME type
931
+ */
932
+ function getExtensionFromMimeType(mimeType) {
933
+ return {
934
+ "image/svg+xml": "svg",
935
+ "image/png": "png",
936
+ "image/jpeg": "jpg",
937
+ "image/jpg": "jpg",
938
+ "image/webp": "webp",
939
+ "image/gif": "gif",
940
+ "image/bmp": "bmp",
941
+ "image/tiff": "tiff",
942
+ "image/x-icon": "ico",
943
+ "image/vnd.microsoft.icon": "ico"
944
+ }[mimeType.toLowerCase()] || "bin";
945
+ }
946
+ /**
947
+ * Get file extension from filename
948
+ */
949
+ function getExtensionFromFilename(filename) {
950
+ var _match$;
951
+ const match = filename.match(/\.([^.]+)$/);
952
+ return (match === null || match === void 0 || (_match$ = match[1]) === null || _match$ === void 0 ? void 0 : _match$.toLowerCase()) || "";
953
+ }
954
+
955
+ //#endregion
956
+ //#region src/modules/icons/iconRouter.ts
957
+ function createIconRouter() {
958
+ return router({
959
+ list: publicProcedure.query(async () => {
960
+ return getDbClient().dbAsset.findMany({
961
+ where: { assetType: "icon" },
962
+ select: {
963
+ id: true,
964
+ name: true,
965
+ mimeType: true,
966
+ fileSize: true,
967
+ createdAt: true,
968
+ updatedAt: true
969
+ },
970
+ orderBy: { name: "asc" }
971
+ });
972
+ }),
973
+ getOne: publicProcedure.input(z.object({ id: z.string() })).query(async ({ input }) => {
974
+ return getDbClient().dbAsset.findFirst({
975
+ where: {
976
+ id: input.id,
977
+ assetType: "icon"
978
+ },
979
+ select: {
980
+ id: true,
981
+ name: true,
982
+ mimeType: true,
983
+ fileSize: true,
984
+ createdAt: true,
985
+ updatedAt: true
986
+ }
987
+ });
988
+ }),
989
+ create: adminProcedure.input(z.object({
990
+ name: z.string().min(1),
991
+ content: z.string(),
992
+ mimeType: z.string(),
993
+ fileSize: z.number().int().positive()
994
+ })).mutation(async ({ input }) => {
995
+ const prisma = getDbClient();
996
+ const buffer = Buffer.from(input.content, "base64");
997
+ const checksum = generateChecksum(buffer);
998
+ const { width, height } = await getImageDimensions(buffer);
999
+ let name = input.name;
1000
+ if (!name.includes(".")) {
1001
+ const extension = getExtensionFromMimeType(input.mimeType);
1002
+ name = `${name}.${extension}`;
1003
+ }
1004
+ const existing = await prisma.dbAsset.findFirst({ where: {
1005
+ checksum,
1006
+ assetType: "icon"
1007
+ } });
1008
+ if (existing) return existing;
1009
+ return prisma.dbAsset.create({ data: {
1010
+ name,
1011
+ assetType: "icon",
1012
+ content: new Uint8Array(buffer),
1013
+ checksum,
1014
+ mimeType: input.mimeType,
1015
+ fileSize: input.fileSize,
1016
+ width,
1017
+ height
1018
+ } });
1019
+ }),
1020
+ update: adminProcedure.input(z.object({
1021
+ id: z.string(),
1022
+ name: z.string().min(1).optional(),
1023
+ content: z.string().optional(),
1024
+ mimeType: z.string().optional(),
1025
+ fileSize: z.number().int().positive().optional()
1026
+ })).mutation(async ({ input }) => {
1027
+ const prisma = getDbClient();
1028
+ const { id, content, name,...rest } = input;
1029
+ const data = { ...rest };
1030
+ if (content) {
1031
+ const buffer = Buffer.from(content, "base64");
1032
+ data.content = new Uint8Array(buffer);
1033
+ data.checksum = generateChecksum(buffer);
1034
+ const { width, height } = await getImageDimensions(buffer);
1035
+ data.width = width;
1036
+ data.height = height;
1037
+ }
1038
+ if (name) if (!name.includes(".") && input.mimeType) data.name = `${name}.${getExtensionFromMimeType(input.mimeType)}`;
1039
+ else data.name = name;
1040
+ return prisma.dbAsset.update({
1041
+ where: { id },
1042
+ data
1043
+ });
1044
+ }),
1045
+ delete: adminProcedure.input(z.object({ id: z.string() })).mutation(async ({ input }) => {
1046
+ return getDbClient().dbAsset.delete({ where: { id: input.id } });
1047
+ }),
1048
+ deleteMany: adminProcedure.input(z.object({ ids: z.array(z.string()) })).mutation(async ({ input }) => {
1049
+ return getDbClient().dbAsset.deleteMany({ where: {
1050
+ id: { in: input.ids },
1051
+ assetType: "icon"
1052
+ } });
1053
+ }),
1054
+ getContent: publicProcedure.input(z.object({ id: z.string() })).query(async ({ input }) => {
1055
+ const asset = await getDbClient().dbAsset.findFirst({
1056
+ where: {
1057
+ id: input.id,
1058
+ assetType: "icon"
1059
+ },
1060
+ select: {
1061
+ content: true,
1062
+ mimeType: true,
1063
+ name: true
1064
+ }
1065
+ });
1066
+ if (!asset) throw new Error("Icon not found");
1067
+ return {
1068
+ content: Buffer.from(asset.content).toString("base64"),
1069
+ mimeType: asset.mimeType,
1070
+ name: asset.name
1071
+ };
1072
+ })
1073
+ });
1074
+ }
1075
+
1076
+ //#endregion
1077
+ //#region src/server/controller.ts
1078
+ /**
1079
+ * Create the main tRPC router with optional auth instance
1080
+ * @param auth - Optional Better Auth instance for auth-related queries
1081
+ */
1082
+ function createTrpcRouter(auth) {
1083
+ return router({
1084
+ authConfig: publicProcedure.query(async ({ ctx }) => {
1085
+ return { adminGroups: ctx.adminGroups };
1086
+ }),
1087
+ appCatalog: publicProcedure.query(async ({ ctx }) => {
1088
+ return await getAppCatalogData(ctx.companySpecificBackend.getApps);
1089
+ }),
1090
+ icon: createIconRouter(),
1091
+ screenshot: createScreenshotRouter(),
1092
+ appCatalogAdmin: createAppCatalogAdminRouter(),
1093
+ approvalMethod: createApprovalMethodRouter(),
1094
+ auth: createAuthRouter(t, auth)
1095
+ });
1096
+ }
1097
+
1098
+ //#endregion
1099
+ //#region src/server/ehTrpcContext.ts
1100
+ function createEhTrpcContext({ companySpecificBackend, user = null, adminGroups }) {
1101
+ return {
1102
+ companySpecificBackend,
1103
+ user,
1104
+ adminGroups
1105
+ };
1106
+ }
1107
+
1108
+ //#endregion
1109
+ //#region src/server/ehStaticControllerContract.ts
1110
+ const staticControllerContract = { methods: {
1111
+ getIcon: {
1112
+ method: "get",
1113
+ url: "icon/:icon"
1114
+ },
1115
+ getScreenshot: {
1116
+ method: "get",
1117
+ url: "screenshot/:id"
1118
+ }
1119
+ } };
1120
+
1121
+ //#endregion
1122
+ //#region src/modules/auth/auth.ts
1123
+ function createAuth(config) {
1124
+ const prisma = getDbClient();
1125
+ const isProduction = process.env.NODE_ENV === "production";
1126
+ return betterAuth({
1127
+ appName: config.appName || "EnvHopper",
1128
+ baseURL: config.baseURL,
1129
+ basePath: "/api/auth",
1130
+ secret: config.secret,
1131
+ database: prismaAdapter(prisma, { provider: "postgresql" }),
1132
+ socialProviders: config.providers || {},
1133
+ plugins: config.plugins || [],
1134
+ emailAndPassword: { enabled: true },
1135
+ session: {
1136
+ expiresIn: config.sessionExpiresIn ?? 3600 * 24 * 30,
1137
+ updateAge: config.sessionUpdateAge ?? 3600 * 24,
1138
+ cookieCache: {
1139
+ enabled: true,
1140
+ maxAge: 300
1141
+ }
1142
+ },
1143
+ advanced: { useSecureCookies: isProduction }
1144
+ });
1145
+ }
1146
+
1147
+ //#endregion
1148
+ //#region src/modules/auth/registerAuthRoutes.ts
1149
+ /**
1150
+ * Register Better Auth routes with Express
1151
+ * @param app - Express application instance
1152
+ * @param auth - Better Auth instance
1153
+ */
1154
+ function registerAuthRoutes(app, auth) {
1155
+ app.get("/api/auth/session", async (req, res) => {
1156
+ try {
1157
+ const session = await auth.api.getSession({ headers: req.headers });
1158
+ if (session) res.json(session);
1159
+ else res.status(401).json({ error: "Not authenticated" });
1160
+ } catch (error) {
1161
+ console.error("[Auth Session Error]", error);
1162
+ res.status(500).json({ error: "Internal server error" });
1163
+ }
1164
+ });
1165
+ const authHandler = toNodeHandler(auth);
1166
+ app.all("/api/auth/{*any}", authHandler);
1167
+ }
1168
+
1169
+ //#endregion
1170
+ //#region src/modules/admin/chat/createAdminChatHandler.ts
1171
+ function convertToCoreMessages(messages) {
1172
+ return messages.map((msg) => {
1173
+ var _msg$parts;
1174
+ if (msg.content) return {
1175
+ role: msg.role,
1176
+ content: msg.content
1177
+ };
1178
+ const textContent = ((_msg$parts = msg.parts) === null || _msg$parts === void 0 ? void 0 : _msg$parts.filter((part) => part.type === "text").map((part) => part.text).join("")) ?? "";
1179
+ return {
1180
+ role: msg.role,
1181
+ content: textContent
1182
+ };
1183
+ });
1184
+ }
1185
+ /**
1186
+ * Creates an Express handler for the admin chat endpoint.
1187
+ *
1188
+ * Usage in thin wrappers:
1189
+ *
1190
+ * ```typescript
1191
+ * // With OpenAI
1192
+ * import { openai } from '@ai-sdk/openai'
1193
+ * app.post('/api/admin/chat', createAdminChatHandler({
1194
+ * model: openai('gpt-4o-mini'),
1195
+ * }))
1196
+ *
1197
+ * // With Claude
1198
+ * import { anthropic } from '@ai-sdk/anthropic'
1199
+ * app.post('/api/admin/chat', createAdminChatHandler({
1200
+ * model: anthropic('claude-sonnet-4-20250514'),
1201
+ * }))
1202
+ * ```
1203
+ */
1204
+ function createAdminChatHandler(options) {
1205
+ const { model, systemPrompt = "You are a helpful admin assistant for the App Catalog application. Help users manage apps, data sources, and MCP server configurations.", tools = {}, validateConfig } = options;
1206
+ return async (req, res) => {
1207
+ try {
1208
+ if (validateConfig) validateConfig();
1209
+ const { messages } = req.body;
1210
+ const coreMessages = convertToCoreMessages(messages);
1211
+ console.log("[Admin Chat] Received messages:", JSON.stringify(coreMessages, null, 2));
1212
+ console.log("[Admin Chat] Available tools:", Object.keys(tools));
1213
+ const response = streamText({
1214
+ model,
1215
+ system: systemPrompt,
1216
+ messages: coreMessages,
1217
+ tools,
1218
+ stopWhen: stepCountIs(5),
1219
+ onFinish: (event) => {
1220
+ console.log("[Admin Chat] Finished:", {
1221
+ finishReason: event.finishReason,
1222
+ usage: event.usage,
1223
+ hasText: !!event.text,
1224
+ textLength: event.text.length
1225
+ });
1226
+ }
1227
+ }).toUIMessageStreamResponse();
1228
+ response.headers.forEach((value, key) => {
1229
+ res.setHeader(key, value);
1230
+ });
1231
+ if (response.body) {
1232
+ const reader = response.body.getReader();
1233
+ const pump = async () => {
1234
+ const { done, value } = await reader.read();
1235
+ if (done) {
1236
+ res.end();
1237
+ return;
1238
+ }
1239
+ res.write(value);
1240
+ return pump();
1241
+ };
1242
+ await pump();
1243
+ } else {
1244
+ console.error("[Admin Chat] No response body");
1245
+ res.status(500).json({ error: "No response from AI model" });
1246
+ }
1247
+ } catch (error) {
1248
+ console.error("[Admin Chat] Error:", error);
1249
+ res.status(500).json({ error: "Failed to process chat request" });
1250
+ }
1251
+ };
1252
+ }
1253
+
1254
+ //#endregion
1255
+ //#region src/modules/admin/chat/createDatabaseTools.ts
1256
+ /**
1257
+ * Creates a DatabaseClient from a Prisma client.
1258
+ */
1259
+ function createPrismaDatabaseClient(prisma) {
1260
+ return {
1261
+ query: async (sql) => {
1262
+ return await prisma.$queryRawUnsafe(sql);
1263
+ },
1264
+ execute: async (sql) => {
1265
+ return { affectedRows: await prisma.$executeRawUnsafe(sql) };
1266
+ },
1267
+ getTables: async () => {
1268
+ return (await prisma.$queryRawUnsafe(`SELECT tablename FROM pg_tables WHERE schemaname = 'public'`)).map((t$1) => t$1.tablename);
1269
+ },
1270
+ getColumns: async (tableName) => {
1271
+ return (await prisma.$queryRawUnsafe(`SELECT column_name, data_type, is_nullable
1272
+ FROM information_schema.columns
1273
+ WHERE table_name = '${tableName}' AND table_schema = 'public'`)).map((c) => ({
1274
+ name: c.column_name,
1275
+ type: c.data_type,
1276
+ nullable: c.is_nullable === "YES"
1277
+ }));
1278
+ }
1279
+ };
1280
+ }
1281
+ const querySchema = z.object({ sql: z.string().describe("The SELECT SQL query to execute") });
1282
+ const modifySchema = z.object({
1283
+ sql: z.string().describe("The INSERT, UPDATE, or DELETE SQL query to execute"),
1284
+ confirmed: z.boolean().describe("Must be true to execute destructive operations")
1285
+ });
1286
+ const schemaParamsSchema = z.object({ tableName: z.string().optional().describe("Specific table name to get columns for. If not provided, returns list of all tables.") });
1287
+ /**
1288
+ * Creates a DatabaseClient using the internal backend-core Prisma client.
1289
+ * This is a convenience function for apps that don't need to pass their own Prisma client.
1290
+ */
1291
+ function createInternalDatabaseClient() {
1292
+ return createPrismaDatabaseClient(getDbClient());
1293
+ }
1294
+ /**
1295
+ * Creates AI tools for generic database access.
1296
+ *
1297
+ * The AI uses these internally - users interact via natural language.
1298
+ * Results are formatted as tables by the AI based on the system prompt.
1299
+ * Uses the internal backend-core Prisma client automatically.
1300
+ */
1301
+ function createDatabaseTools() {
1302
+ const db = createInternalDatabaseClient();
1303
+ return {
1304
+ queryDatabase: {
1305
+ description: `Execute a SELECT query to read data from the database.
1306
+ Use this to list, search, or filter records from any table.
1307
+ Always use double quotes around table and column names for PostgreSQL (e.g., SELECT * FROM "App").
1308
+ Return results will be formatted as a table for the user.`,
1309
+ inputSchema: querySchema,
1310
+ execute: async ({ sql }) => {
1311
+ console.log(`Executing ${sql}`);
1312
+ if (!sql.trim().toUpperCase().startsWith("SELECT")) return { error: "Only SELECT queries are allowed with queryDatabase. Use modifyDatabase for changes." };
1313
+ try {
1314
+ const results = await db.query(sql);
1315
+ return {
1316
+ success: true,
1317
+ rowCount: Array.isArray(results) ? results.length : 0,
1318
+ data: results
1319
+ };
1320
+ } catch (error) {
1321
+ return {
1322
+ success: false,
1323
+ error: error instanceof Error ? error.message : "Query failed"
1324
+ };
1325
+ }
1326
+ }
1327
+ },
1328
+ modifyDatabase: {
1329
+ description: `Execute an INSERT, UPDATE, or DELETE query to modify data.
1330
+ Use double quotes around table and column names for PostgreSQL.
1331
+ IMPORTANT: Always ask for user confirmation before executing. Set confirmed=true only after user confirms.
1332
+ For UPDATE/DELETE, always include a WHERE clause to avoid affecting all rows.`,
1333
+ inputSchema: modifySchema,
1334
+ execute: async ({ sql, confirmed }) => {
1335
+ if (!confirmed) return {
1336
+ needsConfirmation: true,
1337
+ message: "Please confirm you want to execute this operation.",
1338
+ sql
1339
+ };
1340
+ const normalizedSql = sql.trim().toUpperCase();
1341
+ if (normalizedSql.startsWith("SELECT")) return { error: "Use queryDatabase for SELECT queries." };
1342
+ if ((normalizedSql.startsWith("UPDATE") || normalizedSql.startsWith("DELETE")) && !normalizedSql.includes("WHERE")) return {
1343
+ error: "UPDATE and DELETE queries must include a WHERE clause for safety.",
1344
+ sql
1345
+ };
1346
+ try {
1347
+ const result = await db.execute(sql);
1348
+ return {
1349
+ success: true,
1350
+ affectedRows: result.affectedRows,
1351
+ message: `Operation completed. ${result.affectedRows} row(s) affected.`
1352
+ };
1353
+ } catch (error) {
1354
+ return {
1355
+ success: false,
1356
+ error: error instanceof Error ? error.message : "Operation failed"
1357
+ };
1358
+ }
1359
+ }
1360
+ },
1361
+ getDatabaseSchema: {
1362
+ description: `Get information about database tables and their columns.
1363
+ Use this to understand the database structure before writing queries.
1364
+ Call without tableName to list all tables, or with tableName to get columns for a specific table.`,
1365
+ inputSchema: schemaParamsSchema,
1366
+ execute: async ({ tableName }) => {
1367
+ try {
1368
+ if (tableName) return {
1369
+ success: true,
1370
+ table: tableName,
1371
+ columns: await db.getColumns(tableName)
1372
+ };
1373
+ else return {
1374
+ success: true,
1375
+ tables: await db.getTables()
1376
+ };
1377
+ } catch (error) {
1378
+ return {
1379
+ success: false,
1380
+ error: error instanceof Error ? error.message : "Failed to get schema"
1381
+ };
1382
+ }
1383
+ }
1384
+ }
1385
+ };
1386
+ }
1387
+ /**
1388
+ * Default system prompt for the database admin assistant.
1389
+ * Can be customized or extended.
1390
+ */
1391
+ const DEFAULT_ADMIN_SYSTEM_PROMPT = `You are a helpful database admin assistant. You help users view and manage data in the database.
1392
+
1393
+ IMPORTANT RULES:
1394
+ 1. When showing data, ALWAYS format it as a numbered ASCII table so users can reference rows by number
1395
+ 2. NEVER show raw SQL to users - just describe what you're doing in plain language
1396
+ 3. When users ask to modify data (update, delete, create), ALWAYS confirm before executing
1397
+ 4. For updates, show the current value and ask for confirmation before changing
1398
+ 5. Keep responses concise and focused on the data
1399
+
1400
+ FORMATTING EXAMPLE:
1401
+ When user asks "show me all apps", respond like:
1402
+ "Here are all the apps:
1403
+
1404
+ | # | ID | Slug | Display Name | Icon |
1405
+ |---|----|---------|-----------------| -------|
1406
+ | 1 | 1 | portal | Portal | portal |
1407
+ | 2 | 2 | admin | Admin Dashboard | admin |
1408
+ | 3 | 3 | api | API Service | null |
1409
+
1410
+ Found 3 apps total."
1411
+
1412
+ When user says "update row 2 display name to 'Admin Panel'":
1413
+ 1. First confirm: "I'll update the app 'Admin Dashboard' (ID: 2) to have display name 'Admin Panel'. Proceed?"
1414
+ 2. Only after user confirms, execute the update
1415
+ 3. Then show the updated row
1416
+
1417
+ AVAILABLE TABLES:
1418
+ Use getDatabaseSchema tool to discover tables and their columns.
1419
+ `;
1420
+
1421
+ //#endregion
1422
+ //#region src/modules/icons/iconRestController.ts
1423
+ const upload$1 = multer({
1424
+ storage: multer.memoryStorage(),
1425
+ limits: { fileSize: 10 * 1024 * 1024 },
1426
+ fileFilter: (_req, file, cb) => {
1427
+ if (!file.mimetype.startsWith("image/")) {
1428
+ cb(/* @__PURE__ */ new Error("Only image files are allowed"));
1429
+ return;
1430
+ }
1431
+ cb(null, true);
1432
+ }
1433
+ });
1434
+ /**
1435
+ * Registers REST endpoints for icon upload and retrieval
1436
+ *
1437
+ * Endpoints:
1438
+ * - POST {basePath}/upload - Upload a new icon (multipart/form-data with 'icon' field and 'name' field)
1439
+ * - GET {basePath}/:id - Get icon binary by ID
1440
+ * - GET {basePath}/:id/metadata - Get icon metadata only
1441
+ */
1442
+ function registerIconRestController(router$1, config) {
1443
+ const { basePath } = config;
1444
+ router$1.post(`${basePath}/upload`, upload$1.single("icon"), async (req, res) => {
1445
+ try {
1446
+ if (!req.file) {
1447
+ res.status(400).json({ error: "No file uploaded" });
1448
+ return;
1449
+ }
1450
+ let name = req.body["name"];
1451
+ if (!name) {
1452
+ res.status(400).json({ error: "Name is required" });
1453
+ return;
1454
+ }
1455
+ const extension = getExtensionFromFilename(req.file.originalname) || getExtensionFromMimeType(req.file.mimetype);
1456
+ if (!name.includes(".")) name = `${name}.${extension}`;
1457
+ const prisma = getDbClient();
1458
+ const checksum = createHash("sha256").update(req.file.buffer).digest("hex");
1459
+ const icon = await prisma.dbAsset.create({ data: {
1460
+ name,
1461
+ assetType: "icon",
1462
+ content: new Uint8Array(req.file.buffer),
1463
+ mimeType: req.file.mimetype,
1464
+ fileSize: req.file.size,
1465
+ checksum
1466
+ } });
1467
+ res.status(201).json({
1468
+ id: icon.id,
1469
+ name: icon.name,
1470
+ mimeType: icon.mimeType,
1471
+ fileSize: icon.fileSize,
1472
+ createdAt: icon.createdAt
1473
+ });
1474
+ } catch (error) {
1475
+ console.error("Error uploading icon:", error);
1476
+ res.status(500).json({ error: "Failed to upload icon" });
1477
+ }
1478
+ });
1479
+ router$1.get(`${basePath}/:name`, async (req, res) => {
1480
+ try {
1481
+ const { name } = req.params;
1482
+ const icon = await getDbClient().dbAsset.findFirst({
1483
+ where: {
1484
+ name,
1485
+ assetType: "icon"
1486
+ },
1487
+ select: {
1488
+ content: true,
1489
+ mimeType: true,
1490
+ name: true
1491
+ }
1492
+ });
1493
+ if (!icon) {
1494
+ res.status(404).json({ error: "Icon not found" });
1495
+ return;
1496
+ }
1497
+ res.setHeader("Content-Type", icon.mimeType);
1498
+ res.setHeader("Content-Disposition", `inline; filename="${icon.name}"`);
1499
+ res.setHeader("Cache-Control", "public, max-age=86400");
1500
+ res.send(icon.content);
1501
+ } catch (error) {
1502
+ console.error("Error fetching icon:", error);
1503
+ res.status(500).json({ error: "Failed to fetch icon" });
1504
+ }
1505
+ });
1506
+ router$1.get(`${basePath}/:name/metadata`, async (req, res) => {
1507
+ try {
1508
+ const { name } = req.params;
1509
+ const icon = await getDbClient().dbAsset.findFirst({
1510
+ where: {
1511
+ name,
1512
+ assetType: "icon"
1513
+ },
1514
+ select: {
1515
+ id: true,
1516
+ name: true,
1517
+ mimeType: true,
1518
+ fileSize: true,
1519
+ createdAt: true,
1520
+ updatedAt: true
1521
+ }
1522
+ });
1523
+ if (!icon) {
1524
+ res.status(404).json({ error: "Icon not found" });
1525
+ return;
1526
+ }
1527
+ res.json(icon);
1528
+ } catch (error) {
1529
+ console.error("Error fetching icon metadata:", error);
1530
+ res.status(500).json({ error: "Failed to fetch icon metadata" });
1531
+ }
1532
+ });
1533
+ }
1534
+
1535
+ //#endregion
1536
+ //#region src/modules/icons/iconService.ts
1537
+ /**
1538
+ * Upsert an icon to the database.
1539
+ * If an icon with the same name exists, it will be updated.
1540
+ * Otherwise, a new icon will be created.
1541
+ */
1542
+ async function upsertIcon(input) {
1543
+ const prisma = getDbClient();
1544
+ const checksum = generateChecksum(input.content);
1545
+ const { width, height } = await getImageDimensions(input.content);
1546
+ return prisma.dbAsset.upsert({
1547
+ where: { name: input.name },
1548
+ update: {
1549
+ content: new Uint8Array(input.content),
1550
+ checksum,
1551
+ mimeType: input.mimeType,
1552
+ fileSize: input.fileSize,
1553
+ width,
1554
+ height
1555
+ },
1556
+ create: {
1557
+ name: input.name,
1558
+ assetType: "icon",
1559
+ content: new Uint8Array(input.content),
1560
+ checksum,
1561
+ mimeType: input.mimeType,
1562
+ fileSize: input.fileSize,
1563
+ width,
1564
+ height
1565
+ }
1566
+ });
1567
+ }
1568
+ /**
1569
+ * Upsert multiple icons to the database.
1570
+ * This is more efficient than calling upsertIcon multiple times.
1571
+ */
1572
+ async function upsertIcons(icons) {
1573
+ const results = [];
1574
+ for (const icon of icons) {
1575
+ const result = await upsertIcon(icon);
1576
+ results.push(result);
1577
+ }
1578
+ return results;
1579
+ }
1580
+ /**
1581
+ * Get an asset (icon or screenshot) by name from the database.
1582
+ * Returns the asset content, mimeType, and name if found.
1583
+ */
1584
+ async function getAssetByName(name) {
1585
+ return getDbClient().dbAsset.findUnique({
1586
+ where: { name },
1587
+ select: {
1588
+ content: true,
1589
+ mimeType: true,
1590
+ name: true
1591
+ }
1592
+ });
1593
+ }
1594
+
1595
+ //#endregion
1596
+ //#region src/modules/assets/assetRestController.ts
1597
+ const upload = multer({
1598
+ storage: multer.memoryStorage(),
1599
+ limits: { fileSize: 10 * 1024 * 1024 },
1600
+ fileFilter: (_req, file, cb) => {
1601
+ if (!file.mimetype.startsWith("image/")) {
1602
+ cb(/* @__PURE__ */ new Error("Only image files are allowed"));
1603
+ return;
1604
+ }
1605
+ cb(null, true);
1606
+ }
1607
+ });
1608
+ /**
1609
+ * Registers REST endpoints for universal asset upload and retrieval
1610
+ *
1611
+ * Endpoints:
1612
+ * - POST {basePath}/upload - Upload a new asset (multipart/form-data)
1613
+ * - GET {basePath}/:id - Get asset binary by ID
1614
+ * - GET {basePath}/:id/metadata - Get asset metadata only
1615
+ * - GET {basePath}/by-name/:name - Get asset binary by name
1616
+ */
1617
+ function registerAssetRestController(router$1, config) {
1618
+ const { basePath } = config;
1619
+ const prisma = getDbClient();
1620
+ router$1.post(`${basePath}/upload`, upload.single("asset"), async (req, res) => {
1621
+ try {
1622
+ if (!req.file) {
1623
+ res.status(400).json({ error: "No file uploaded" });
1624
+ return;
1625
+ }
1626
+ const name = req.body["name"];
1627
+ const assetType = req.body["assetType"];
1628
+ if (!name) {
1629
+ res.status(400).json({ error: "Name is required" });
1630
+ return;
1631
+ }
1632
+ const id = await upsertAsset({
1633
+ prisma,
1634
+ buffer: req.file.buffer,
1635
+ name,
1636
+ originalFilename: req.file.filename,
1637
+ assetType
1638
+ });
1639
+ res.status(201).json({ id });
1640
+ } catch (error) {
1641
+ console.error("Error uploading asset:", error);
1642
+ res.status(500).json({ error: "Failed to upload asset" });
1643
+ }
1644
+ });
1645
+ router$1.get(`${basePath}/:id`, async (req, res) => {
1646
+ try {
1647
+ const { id } = req.params;
1648
+ const asset = await prisma.dbAsset.findUnique({
1649
+ where: { id },
1650
+ select: {
1651
+ content: true,
1652
+ mimeType: true,
1653
+ name: true,
1654
+ width: true,
1655
+ height: true
1656
+ }
1657
+ });
1658
+ if (!asset) {
1659
+ res.status(404).json({ error: "Asset not found" });
1660
+ return;
1661
+ }
1662
+ const resizeEnabled = String(process.env.EH_ASSETS_RESIZE_ENABLED || "true") === "true";
1663
+ const wParam = req.query["w"];
1664
+ const width = wParam ? Number.parseInt(wParam, 10) : void 0;
1665
+ let outBuffer = asset.content;
1666
+ let outMime = asset.mimeType;
1667
+ if (resizeEnabled && isRasterImage(asset.mimeType) && !!width && Number.isFinite(width) && width > 0) {
1668
+ const fmt = getImageFormat(asset.mimeType) || "jpeg";
1669
+ const buf = await resizeImage(Buffer.from(asset.content), width, void 0, fmt);
1670
+ outBuffer = new Uint8Array(buf);
1671
+ outMime = `image/${fmt}`;
1672
+ }
1673
+ res.setHeader("Content-Type", outMime);
1674
+ res.setHeader("Content-Disposition", `inline; filename="${asset.name}"`);
1675
+ res.setHeader("Cache-Control", "public, max-age=86400");
1676
+ res.send(outBuffer);
1677
+ } catch (error) {
1678
+ console.error("Error fetching asset:", error);
1679
+ res.status(500).json({ error: "Failed to fetch asset" });
1680
+ }
1681
+ });
1682
+ router$1.get(`${basePath}/:id/metadata`, async (req, res) => {
1683
+ try {
1684
+ const { id } = req.params;
1685
+ const asset = await prisma.dbAsset.findUnique({
1686
+ where: { id },
1687
+ select: {
1688
+ id: true,
1689
+ name: true,
1690
+ assetType: true,
1691
+ mimeType: true,
1692
+ fileSize: true,
1693
+ width: true,
1694
+ height: true,
1695
+ createdAt: true,
1696
+ updatedAt: true
1697
+ }
1698
+ });
1699
+ if (!asset) {
1700
+ res.status(404).json({ error: "Asset not found" });
1701
+ return;
1702
+ }
1703
+ res.json(asset);
1704
+ } catch (error) {
1705
+ console.error("Error fetching asset metadata:", error);
1706
+ res.status(500).json({ error: "Failed to fetch asset metadata" });
1707
+ }
1708
+ });
1709
+ router$1.get(`${basePath}/by-name/:name`, async (req, res) => {
1710
+ try {
1711
+ const { name } = req.params;
1712
+ const asset = await prisma.dbAsset.findUnique({
1713
+ where: { name },
1714
+ select: {
1715
+ content: true,
1716
+ mimeType: true,
1717
+ name: true,
1718
+ width: true,
1719
+ height: true
1720
+ }
1721
+ });
1722
+ if (!asset) {
1723
+ res.status(404).json({ error: "Asset not found" });
1724
+ return;
1725
+ }
1726
+ const resizeEnabled = String(process.env.EH_ASSETS_RESIZE_ENABLED || "true") === "true";
1727
+ const wParam = req.query["w"];
1728
+ const width = wParam ? Number.parseInt(wParam, 10) : void 0;
1729
+ let outBuffer = asset.content;
1730
+ let outMime = asset.mimeType;
1731
+ const isRaster = asset.mimeType.startsWith("image/") && !asset.mimeType.includes("svg");
1732
+ if (resizeEnabled && isRaster && !!width && Number.isFinite(width) && width > 0) {
1733
+ const fmt = asset.mimeType.includes("png") ? "png" : asset.mimeType.includes("webp") ? "webp" : "jpeg";
1734
+ let buf;
1735
+ const pipeline = sharp(Buffer.from(asset.content)).resize({
1736
+ width,
1737
+ fit: "inside",
1738
+ withoutEnlargement: true
1739
+ });
1740
+ if (fmt === "png") {
1741
+ buf = await pipeline.png().toBuffer();
1742
+ outMime = "image/png";
1743
+ } else if (fmt === "webp") {
1744
+ buf = await pipeline.webp().toBuffer();
1745
+ outMime = "image/webp";
1746
+ } else {
1747
+ buf = await pipeline.jpeg().toBuffer();
1748
+ outMime = "image/jpeg";
1749
+ }
1750
+ outBuffer = new Uint8Array(buf);
1751
+ }
1752
+ res.setHeader("Content-Type", outMime);
1753
+ res.setHeader("Content-Disposition", `inline; filename="${asset.name}"`);
1754
+ res.setHeader("Cache-Control", "public, max-age=86400");
1755
+ res.send(outBuffer);
1756
+ } catch (error) {
1757
+ console.error("Error fetching asset by name:", error);
1758
+ res.status(500).json({ error: "Failed to fetch asset" });
1759
+ }
1760
+ });
1761
+ }
1762
+
1763
+ //#endregion
1764
+ //#region src/modules/assets/screenshotRestController.ts
1765
+ /**
1766
+ * Registers REST endpoints for screenshot retrieval
1767
+ *
1768
+ * Endpoints:
1769
+ * - GET {basePath}/app/:appId - Get all screenshots for an app
1770
+ * - GET {basePath}/:id - Get screenshot binary by ID
1771
+ * - GET {basePath}/:id/metadata - Get screenshot metadata only
1772
+ */
1773
+ function registerScreenshotRestController(router$1, config) {
1774
+ const { basePath } = config;
1775
+ router$1.get(`${basePath}/app/:appSlug`, async (req, res) => {
1776
+ try {
1777
+ const { appSlug } = req.params;
1778
+ const prisma = getDbClient();
1779
+ const app = await prisma.dbAppForCatalog.findUnique({
1780
+ where: { slug: appSlug },
1781
+ select: { screenshotIds: true }
1782
+ });
1783
+ if (!app) {
1784
+ res.status(404).json({ error: "App not found" });
1785
+ return;
1786
+ }
1787
+ const screenshots = await prisma.dbAsset.findMany({
1788
+ where: {
1789
+ id: { in: app.screenshotIds },
1790
+ assetType: "screenshot"
1791
+ },
1792
+ select: {
1793
+ id: true,
1794
+ name: true,
1795
+ mimeType: true,
1796
+ fileSize: true,
1797
+ width: true,
1798
+ height: true,
1799
+ createdAt: true
1800
+ }
1801
+ });
1802
+ res.json(screenshots);
1803
+ } catch (error) {
1804
+ console.error("Error fetching app screenshots:", error);
1805
+ res.status(500).json({ error: "Failed to fetch screenshots" });
1806
+ }
1807
+ });
1808
+ router$1.get(`${basePath}/app/:appSlug/first`, async (req, res) => {
1809
+ try {
1810
+ const { appSlug } = req.params;
1811
+ const prisma = getDbClient();
1812
+ const app = await prisma.dbAppForCatalog.findUnique({
1813
+ where: { slug: appSlug },
1814
+ select: { screenshotIds: true }
1815
+ });
1816
+ if (!app || app.screenshotIds.length === 0) {
1817
+ res.status(404).json({ error: "No screenshots found" });
1818
+ return;
1819
+ }
1820
+ const screenshot = await prisma.dbAsset.findUnique({
1821
+ where: { id: app.screenshotIds[0] },
1822
+ select: {
1823
+ id: true,
1824
+ name: true,
1825
+ mimeType: true,
1826
+ fileSize: true,
1827
+ width: true,
1828
+ height: true,
1829
+ createdAt: true
1830
+ }
1831
+ });
1832
+ if (!screenshot) {
1833
+ res.status(404).json({ error: "Screenshot not found" });
1834
+ return;
1835
+ }
1836
+ res.json(screenshot);
1837
+ } catch (error) {
1838
+ console.error("Error fetching first screenshot:", error);
1839
+ res.status(500).json({ error: "Failed to fetch screenshot" });
1840
+ }
1841
+ });
1842
+ router$1.get(`${basePath}/:id`, async (req, res) => {
1843
+ try {
1844
+ const { id } = req.params;
1845
+ const sizeParam = req.query.size;
1846
+ const targetSize = sizeParam ? parseInt(sizeParam, 10) : void 0;
1847
+ const screenshot = await getDbClient().dbAsset.findUnique({
1848
+ where: { id },
1849
+ select: {
1850
+ content: true,
1851
+ mimeType: true,
1852
+ name: true
1853
+ }
1854
+ });
1855
+ if (!screenshot) {
1856
+ res.status(404).json({ error: "Screenshot not found" });
1857
+ return;
1858
+ }
1859
+ let content = screenshot.content;
1860
+ if (targetSize && targetSize > 0) try {
1861
+ content = await sharp(screenshot.content).resize(targetSize, targetSize, {
1862
+ fit: "inside",
1863
+ withoutEnlargement: true
1864
+ }).toBuffer();
1865
+ } catch (resizeError) {
1866
+ console.error("Error resizing screenshot:", resizeError);
1867
+ }
1868
+ res.setHeader("Content-Type", screenshot.mimeType);
1869
+ res.setHeader("Content-Disposition", `inline; filename="${screenshot.name}"`);
1870
+ res.setHeader("Cache-Control", "public, max-age=86400");
1871
+ res.send(content);
1872
+ } catch (error) {
1873
+ console.error("Error fetching screenshot:", error);
1874
+ res.status(500).json({ error: "Failed to fetch screenshot" });
1875
+ }
1876
+ });
1877
+ router$1.get(`${basePath}/:id/metadata`, async (req, res) => {
1878
+ try {
1879
+ const { id } = req.params;
1880
+ const screenshot = await getDbClient().dbAsset.findUnique({
1881
+ where: { id },
1882
+ select: {
1883
+ id: true,
1884
+ name: true,
1885
+ mimeType: true,
1886
+ fileSize: true,
1887
+ width: true,
1888
+ height: true,
1889
+ createdAt: true,
1890
+ updatedAt: true
1891
+ }
1892
+ });
1893
+ if (!screenshot) {
1894
+ res.status(404).json({ error: "Screenshot not found" });
1895
+ return;
1896
+ }
1897
+ res.json(screenshot);
1898
+ } catch (error) {
1899
+ console.error("Error fetching screenshot metadata:", error);
1900
+ res.status(500).json({ error: "Failed to fetch screenshot metadata" });
1901
+ }
1902
+ });
1903
+ }
1904
+
1905
+ //#endregion
1906
+ //#region src/modules/assets/syncAssets.ts
1907
+ /**
1908
+ * Sync local asset files (icons and screenshots) from directories into the database.
1909
+ *
1910
+ * This function allows consuming applications to sync asset files without directly
1911
+ * exposing the Prisma client. It handles:
1912
+ * - Icon files: Assigned to apps by matching filename to icon name patterns
1913
+ * - Screenshot files: Assigned to apps by matching filename to app ID (format: <app-id>_screenshot_<no>.<ext>)
1914
+ *
1915
+ * @param config Configuration with paths to icon and screenshot directories
1916
+ */
1917
+ async function syncAssets(config) {
1918
+ const prisma = getDbClient();
1919
+ let iconsUpserted = 0;
1920
+ let screenshotsUpserted = 0;
1921
+ if (config.iconsDir) {
1922
+ console.log(`📁 Syncing icons from ${config.iconsDir}...`);
1923
+ iconsUpserted = await syncIconsFromDirectory(prisma, config.iconsDir);
1924
+ console.log(` ✓ Upserted ${iconsUpserted} icons`);
1925
+ }
1926
+ if (config.screenshotsDir) {
1927
+ console.log(`📷 Syncing screenshots from ${config.screenshotsDir}...`);
1928
+ screenshotsUpserted = await syncScreenshotsFromDirectory(prisma, config.screenshotsDir);
1929
+ console.log(` ✓ Upserted ${screenshotsUpserted} screenshots and assigned to apps`);
1930
+ }
1931
+ return {
1932
+ iconsUpserted,
1933
+ screenshotsUpserted
1934
+ };
1935
+ }
1936
+ /**
1937
+ * Sync icon files from a directory
1938
+ */
1939
+ async function syncIconsFromDirectory(prisma, iconsDir) {
1940
+ let count = 0;
1941
+ try {
1942
+ const files = readdirSync(iconsDir);
1943
+ for (const file of files) {
1944
+ const filePath = join(iconsDir, file);
1945
+ const ext = extname(file).toLowerCase().slice(1);
1946
+ if (![
1947
+ "png",
1948
+ "jpg",
1949
+ "jpeg",
1950
+ "gif",
1951
+ "webp",
1952
+ "svg"
1953
+ ].includes(ext)) continue;
1954
+ try {
1955
+ const content = readFileSync(filePath);
1956
+ const buffer = Buffer.from(content);
1957
+ const checksum = generateChecksum(buffer);
1958
+ const iconName = file.replace(/\.[^/.]+$/, "");
1959
+ if (await prisma.dbAsset.findFirst({ where: {
1960
+ checksum,
1961
+ assetType: "icon"
1962
+ } })) continue;
1963
+ let width = null;
1964
+ let height = null;
1965
+ if (!ext.includes("svg")) {
1966
+ const { width: w, height: h } = await getImageDimensions(buffer);
1967
+ width = w ?? null;
1968
+ height = h ?? null;
1969
+ }
1970
+ const mimeType = {
1971
+ png: "image/png",
1972
+ jpg: "image/jpeg",
1973
+ jpeg: "image/jpeg",
1974
+ gif: "image/gif",
1975
+ webp: "image/webp",
1976
+ svg: "image/svg+xml"
1977
+ }[ext] || "application/octet-stream";
1978
+ await prisma.dbAsset.create({ data: {
1979
+ name: iconName,
1980
+ assetType: "icon",
1981
+ content: new Uint8Array(buffer),
1982
+ checksum,
1983
+ mimeType,
1984
+ fileSize: buffer.length,
1985
+ width,
1986
+ height
1987
+ } });
1988
+ count++;
1989
+ } catch (error) {
1990
+ console.warn(` ⚠ Failed to sync icon ${file}:`, error);
1991
+ }
1992
+ }
1993
+ } catch (error) {
1994
+ console.error(` ❌ Error reading icons directory:`, error);
1995
+ }
1996
+ return count;
1997
+ }
1998
+ /**
1999
+ * Sync screenshot files from a directory and assign to apps
2000
+ */
2001
+ async function syncScreenshotsFromDirectory(prisma, screenshotsDir) {
2002
+ let count = 0;
2003
+ try {
2004
+ const files = readdirSync(screenshotsDir);
2005
+ const screenshotsByApp = /* @__PURE__ */ new Map();
2006
+ for (const file of files) {
2007
+ const match = file.match(/^(.+?)_screenshot_(\d+)\.([^.]+)$/);
2008
+ if (!match || !match[1] || !match[3]) continue;
2009
+ const appId = match[1];
2010
+ const ext = match[3];
2011
+ if (!screenshotsByApp.has(appId)) screenshotsByApp.set(appId, []);
2012
+ screenshotsByApp.get(appId).push({
2013
+ path: join(screenshotsDir, file),
2014
+ ext
2015
+ });
2016
+ }
2017
+ for (const [appId, screenshots] of screenshotsByApp) try {
2018
+ if (!await prisma.dbAppForCatalog.findUnique({
2019
+ where: { slug: appId },
2020
+ select: { id: true }
2021
+ })) {
2022
+ console.warn(` ⚠ App not found: ${appId}`);
2023
+ continue;
2024
+ }
2025
+ for (const screenshot of screenshots) try {
2026
+ const content = readFileSync(screenshot.path);
2027
+ const buffer = Buffer.from(content);
2028
+ const checksum = generateChecksum(buffer);
2029
+ const existing = await prisma.dbAsset.findFirst({ where: {
2030
+ checksum,
2031
+ assetType: "screenshot"
2032
+ } });
2033
+ if (existing) {
2034
+ const existingApp = await prisma.dbAppForCatalog.findUnique({ where: { slug: appId } });
2035
+ if (existingApp && !existingApp.screenshotIds.includes(existing.id)) await prisma.dbAppForCatalog.update({
2036
+ where: { slug: appId },
2037
+ data: { screenshotIds: [...existingApp.screenshotIds, existing.id] }
2038
+ });
2039
+ continue;
2040
+ }
2041
+ const { width, height } = await getImageDimensions(buffer);
2042
+ const mimeType = {
2043
+ png: "image/png",
2044
+ jpg: "image/jpeg",
2045
+ jpeg: "image/jpeg",
2046
+ gif: "image/gif",
2047
+ webp: "image/webp"
2048
+ }[screenshot.ext.toLowerCase()] || "application/octet-stream";
2049
+ const asset = await prisma.dbAsset.create({ data: {
2050
+ name: `${appId}-screenshot-${Date.now()}`,
2051
+ assetType: "screenshot",
2052
+ content: new Uint8Array(buffer),
2053
+ checksum,
2054
+ mimeType,
2055
+ fileSize: buffer.length,
2056
+ width: width ?? null,
2057
+ height: height ?? null
2058
+ } });
2059
+ await prisma.dbAppForCatalog.update({
2060
+ where: { slug: appId },
2061
+ data: { screenshotIds: { push: asset.id } }
2062
+ });
2063
+ count++;
2064
+ } catch (error) {
2065
+ console.warn(` ⚠ Failed to sync screenshot ${screenshot.path}:`, error);
2066
+ }
2067
+ } catch (error) {
2068
+ console.warn(` ⚠ Failed to process app ${appId}:`, error);
2069
+ }
2070
+ } catch (error) {
2071
+ console.error(` ❌ Error reading screenshots directory:`, error);
2072
+ }
2073
+ return count;
2074
+ }
2075
+
2076
+ //#endregion
2077
+ //#region src/modules/approvalMethod/syncApprovalMethods.ts
2078
+ /**
2079
+ * Syncs approval methods to the database using upsert logic based on type + displayName.
2080
+ *
2081
+ * @param prisma - The PrismaClient instance from the backend-core database
2082
+ * @param methods - Array of approval methods to sync
2083
+ */
2084
+ async function syncApprovalMethods(prisma, methods) {
2085
+ await prisma.$transaction(methods.map((method) => prisma.dbApprovalMethod.upsert({
2086
+ where: { slug: method.slug },
2087
+ update: {
2088
+ displayName: method.displayName,
2089
+ type: method.type
2090
+ },
2091
+ create: {
2092
+ slug: method.slug,
2093
+ type: method.type,
2094
+ displayName: method.displayName
2095
+ }
2096
+ })));
2097
+ }
2098
+
2099
+ //#endregion
2100
+ //#region src/middleware/database.ts
2101
+ /**
2102
+ * Formats a database connection URL from structured config.
2103
+ */
2104
+ function formatConnectionUrl(config) {
2105
+ if ("url" in config) return config.url;
2106
+ const { host, port, database, username, password, schema = "public" } = config;
2107
+ return `postgresql://${username}:${encodeURIComponent(password)}@${host}:${port}/${database}?schema=${schema}`;
2108
+ }
2109
+ /**
2110
+ * Internal database manager used by the middleware.
2111
+ * Handles connection URL formatting and lifecycle.
2112
+ */
2113
+ var EhDatabaseManager = class {
2114
+ constructor(config) {
2115
+ this.client = null;
2116
+ this.config = config;
2117
+ }
2118
+ /**
2119
+ * Get or create the Prisma client instance.
2120
+ * Uses lazy initialization for flexibility.
2121
+ */
2122
+ getClient() {
2123
+ if (!this.client) {
2124
+ this.client = new PrismaClient({
2125
+ datasourceUrl: formatConnectionUrl(this.config),
2126
+ log: process.env.NODE_ENV === "development" ? ["warn", "error"] : ["warn", "error"]
2127
+ });
2128
+ setDbClient(this.client);
2129
+ }
2130
+ return this.client;
2131
+ }
2132
+ async connect() {
2133
+ await this.getClient().$connect();
2134
+ }
2135
+ async disconnect() {
2136
+ if (this.client) {
2137
+ await this.client.$disconnect();
2138
+ this.client = null;
2139
+ }
2140
+ }
2141
+ };
2142
+
2143
+ //#endregion
2144
+ //#region src/middleware/backendResolver.ts
2145
+ /**
2146
+ * Type guard to check if an object implements AppCatalogCompanySpecificBackend.
2147
+ */
2148
+ function isBackendInstance(obj) {
2149
+ return typeof obj === "object" && obj !== null && (typeof obj.getApps === "function" || typeof obj.getApps === "undefined");
2150
+ }
2151
+ /**
2152
+ * Normalizes different backend provider types into a consistent async factory function.
2153
+ * Supports:
2154
+ * - Direct object implementing AppCatalogCompanySpecificBackend
2155
+ * - Sync factory function that returns the backend
2156
+ * - Async factory function that returns the backend
2157
+ */
2158
+ function createBackendResolver(provider) {
2159
+ if (isBackendInstance(provider)) return async () => provider;
2160
+ if (typeof provider === "function") return async () => {
2161
+ const result = provider();
2162
+ return result instanceof Promise ? result : result;
2163
+ };
2164
+ throw new Error("Invalid backend provider: must be an object implementing AppCatalogCompanySpecificBackend or a factory function");
2165
+ }
2166
+
2167
+ //#endregion
2168
+ //#region src/modules/appCatalogAdmin/catalogBackupController.ts
2169
+ /**
2170
+ * Export the complete app catalog as JSON
2171
+ * Includes all fields from DbAppForCatalog and DbApprovalMethod
2172
+ */
2173
+ async function exportCatalog(_req, res) {
2174
+ try {
2175
+ const prisma = getDbClient();
2176
+ const apps = await prisma.dbAppForCatalog.findMany({ orderBy: { slug: "asc" } });
2177
+ const approvalMethods = await prisma.dbApprovalMethod.findMany({ orderBy: { displayName: "asc" } });
2178
+ res.json({
2179
+ version: "2.0",
2180
+ exportDate: (/* @__PURE__ */ new Date()).toISOString(),
2181
+ apps,
2182
+ approvalMethods
2183
+ });
2184
+ } catch (error) {
2185
+ console.error("Error exporting catalog:", error);
2186
+ res.status(500).json({ error: "Failed to export catalog" });
2187
+ }
2188
+ }
2189
+ /**
2190
+ * Import/restore the complete app catalog from JSON
2191
+ * Overwrites existing data
2192
+ */
2193
+ async function importCatalog(req, res) {
2194
+ try {
2195
+ const prisma = getDbClient();
2196
+ const { apps, approvalMethods } = req.body;
2197
+ if (!Array.isArray(apps)) {
2198
+ res.status(400).json({ error: "Invalid data format: apps must be an array" });
2199
+ return;
2200
+ }
2201
+ await prisma.$transaction(async (tx) => {
2202
+ if (Array.isArray(approvalMethods)) await tx.dbApprovalMethod.deleteMany({});
2203
+ await tx.dbAppForCatalog.deleteMany({});
2204
+ if (Array.isArray(approvalMethods)) for (const method of approvalMethods) {
2205
+ const { id, createdAt, updatedAt,...methodData } = method;
2206
+ await tx.dbApprovalMethod.create({ data: methodData });
2207
+ }
2208
+ for (const app of apps) {
2209
+ const { id, createdAt, updatedAt,...appData } = app;
2210
+ await tx.dbAppForCatalog.create({ data: appData });
2211
+ }
2212
+ });
2213
+ res.json({
2214
+ success: true,
2215
+ imported: {
2216
+ apps: apps.length,
2217
+ approvalMethods: Array.isArray(approvalMethods) ? approvalMethods.length : 0
2218
+ }
2219
+ });
2220
+ } catch (error) {
2221
+ console.error("Error importing catalog:", error);
2222
+ res.status(500).json({ error: "Failed to import catalog" });
2223
+ }
2224
+ }
2225
+ /**
2226
+ * Export an asset (icon or screenshot) by name
2227
+ */
2228
+ async function exportAsset(req, res) {
2229
+ try {
2230
+ const { name } = req.params;
2231
+ const asset = await getDbClient().dbAsset.findUnique({ where: { name } });
2232
+ if (!asset) {
2233
+ res.status(404).json({ error: "Asset not found" });
2234
+ return;
2235
+ }
2236
+ res.set("Content-Type", asset.mimeType);
2237
+ res.set("Content-Disposition", `attachment; filename="${name}"`);
2238
+ res.send(Buffer.from(asset.content));
2239
+ } catch (error) {
2240
+ console.error("Error exporting asset:", error);
2241
+ res.status(500).json({ error: "Failed to export asset" });
2242
+ }
2243
+ }
2244
+ /**
2245
+ * List all assets with metadata
2246
+ */
2247
+ async function listAssets(_req, res) {
2248
+ try {
2249
+ const assets = await getDbClient().dbAsset.findMany({
2250
+ select: {
2251
+ id: true,
2252
+ name: true,
2253
+ assetType: true,
2254
+ mimeType: true,
2255
+ fileSize: true,
2256
+ width: true,
2257
+ height: true,
2258
+ checksum: true
2259
+ },
2260
+ orderBy: { name: "asc" }
2261
+ });
2262
+ res.json({ assets });
2263
+ } catch (error) {
2264
+ console.error("Error listing assets:", error);
2265
+ res.status(500).json({ error: "Failed to list assets" });
2266
+ }
2267
+ }
2268
+ /**
2269
+ * Import an asset (icon or screenshot)
2270
+ */
2271
+ async function importAsset(req, res) {
2272
+ try {
2273
+ const file = req.file;
2274
+ const { name, assetType, mimeType, width, height } = req.body;
2275
+ if (!file) {
2276
+ res.status(400).json({ error: "No file uploaded" });
2277
+ return;
2278
+ }
2279
+ const prisma = getDbClient();
2280
+ const checksum = (await import("node:crypto")).createHash("sha256").update(file.buffer).digest("hex");
2281
+ const content = new Uint8Array(file.buffer);
2282
+ await prisma.dbAsset.upsert({
2283
+ where: { name },
2284
+ update: {
2285
+ content,
2286
+ checksum,
2287
+ mimeType: mimeType || file.mimetype,
2288
+ fileSize: file.size,
2289
+ width: width ? parseInt(width) : null,
2290
+ height: height ? parseInt(height) : null,
2291
+ assetType: assetType || "icon"
2292
+ },
2293
+ create: {
2294
+ name,
2295
+ content,
2296
+ checksum,
2297
+ mimeType: mimeType || file.mimetype,
2298
+ fileSize: file.size,
2299
+ width: width ? parseInt(width) : null,
2300
+ height: height ? parseInt(height) : null,
2301
+ assetType: assetType || "icon"
2302
+ }
2303
+ });
2304
+ res.json({
2305
+ success: true,
2306
+ name,
2307
+ size: file.size
2308
+ });
2309
+ } catch (error) {
2310
+ console.error("Error importing asset:", error);
2311
+ res.status(500).json({ error: "Failed to import asset" });
2312
+ }
2313
+ }
2314
+
2315
+ //#endregion
2316
+ //#region src/modules/auth/devMockUserUtils.ts
2317
+ /**
2318
+ * Creates a complete User object from basic dev mock user details
2319
+ */
2320
+ function createMockUserFromDevConfig(devUser) {
2321
+ return {
2322
+ id: devUser.id,
2323
+ email: devUser.email,
2324
+ name: devUser.name,
2325
+ emailVerified: true,
2326
+ createdAt: /* @__PURE__ */ new Date(),
2327
+ updatedAt: /* @__PURE__ */ new Date(),
2328
+ env_hopper_groups: devUser.groups
2329
+ };
2330
+ }
2331
+ /**
2332
+ * Creates a mock session response for /api/auth/session endpoint
2333
+ */
2334
+ function createMockSessionResponse(devUser) {
2335
+ return {
2336
+ user: {
2337
+ id: devUser.id,
2338
+ email: devUser.email,
2339
+ name: devUser.name,
2340
+ emailVerified: true,
2341
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2342
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2343
+ env_hopper_groups: devUser.groups
2344
+ },
2345
+ session: {
2346
+ id: `${devUser.id}-session`,
2347
+ userId: devUser.id,
2348
+ expiresAt: new Date(Date.now() + 1e3 * 60 * 60 * 24 * 30).toISOString(),
2349
+ token: `${devUser.id}-token`,
2350
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2351
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2352
+ }
2353
+ };
2354
+ }
2355
+
2356
+ //#endregion
2357
+ //#region src/middleware/featureRegistry.ts
2358
+ const FEATURES = [
2359
+ {
2360
+ name: "auth",
2361
+ defaultEnabled: true,
2362
+ register: (router$1, options, ctx) => {
2363
+ const basePath = options.basePath;
2364
+ router$1.get(`${basePath}/auth/session`, async (req, res) => {
2365
+ try {
2366
+ if (ctx.authConfig.devMockUser) {
2367
+ res.json(createMockSessionResponse(ctx.authConfig.devMockUser));
2368
+ return;
2369
+ }
2370
+ const session = await ctx.auth.api.getSession({ headers: req.headers });
2371
+ if (session) res.json(session);
2372
+ else res.status(401).json({ error: "Not authenticated" });
2373
+ } catch (error) {
2374
+ console.error("[Auth Session Error]", error);
2375
+ res.status(500).json({ error: "Internal server error" });
2376
+ }
2377
+ });
2378
+ const authHandler = toNodeHandler(ctx.auth);
2379
+ router$1.all(`${basePath}/auth/{*any}`, authHandler);
2380
+ }
2381
+ },
2382
+ {
2383
+ name: "adminChat",
2384
+ defaultEnabled: false,
2385
+ register: (router$1, options) => {
2386
+ if (options.adminChat) router$1.post(`${options.basePath}/admin/chat`, createAdminChatHandler(options.adminChat));
2387
+ }
2388
+ },
2389
+ {
2390
+ name: "legacyIconEndpoint",
2391
+ defaultEnabled: false,
2392
+ register: (router$1) => {
2393
+ router$1.get("/static/icon/:icon", async (req, res) => {
2394
+ const { icon } = req.params;
2395
+ if (!icon || !/^[a-z0-9-]+$/i.test(icon)) {
2396
+ res.status(400).send("Invalid icon name");
2397
+ return;
2398
+ }
2399
+ try {
2400
+ const dbIcon = await getAssetByName(icon);
2401
+ if (!dbIcon) {
2402
+ res.status(404).send("Icon not found");
2403
+ return;
2404
+ }
2405
+ res.setHeader("Content-Type", dbIcon.mimeType);
2406
+ res.setHeader("Cache-Control", "public, max-age=86400");
2407
+ res.send(dbIcon.content);
2408
+ } catch (error) {
2409
+ console.error("Error fetching icon:", error);
2410
+ res.status(404).send("Icon not found");
2411
+ }
2412
+ });
2413
+ }
2414
+ }
2415
+ ];
2416
+ /**
2417
+ * Registers all enabled features on the router.
2418
+ */
2419
+ function registerFeatures(router$1, options, context) {
2420
+ const basePath = options.basePath;
2421
+ registerIconRestController(router$1, { basePath: `${basePath}/icons` });
2422
+ registerAssetRestController(router$1, { basePath: `${basePath}/assets` });
2423
+ registerScreenshotRestController(router$1, { basePath: `${basePath}/screenshots` });
2424
+ const upload$2 = multer({ storage: multer.memoryStorage() });
2425
+ router$1.get(`${basePath}/catalog/backup/export`, exportCatalog);
2426
+ router$1.post(`${basePath}/catalog/backup/import`, importCatalog);
2427
+ router$1.get(`${basePath}/catalog/backup/assets`, listAssets);
2428
+ router$1.get(`${basePath}/catalog/backup/assets/:name`, exportAsset);
2429
+ router$1.post(`${basePath}/catalog/backup/assets`, upload$2.single("file"), importAsset);
2430
+ const toggles = options.features || {};
2431
+ for (const feature of FEATURES) {
2432
+ const isEnabled = toggles[feature.name] ?? feature.defaultEnabled;
2433
+ if (feature.name === "adminChat" && !options.adminChat) continue;
2434
+ if (isEnabled) feature.register(router$1, options, context);
2435
+ }
2436
+ }
2437
+
2438
+ //#endregion
2439
+ //#region src/middleware/createEhMiddleware.ts
2440
+ async function createEhMiddleware(options) {
2441
+ var _normalizedOptions$fe, _options$hooks;
2442
+ const basePath = options.basePath ?? "/api";
2443
+ const normalizedOptions = {
2444
+ ...options,
2445
+ basePath
2446
+ };
2447
+ const dbManager = new EhDatabaseManager(options.database);
2448
+ dbManager.getClient();
2449
+ const auth = createAuth({
2450
+ appName: options.auth.appName,
2451
+ baseURL: options.auth.baseURL,
2452
+ secret: options.auth.secret,
2453
+ providers: options.auth.providers,
2454
+ plugins: options.auth.plugins,
2455
+ sessionExpiresIn: options.auth.sessionExpiresIn,
2456
+ sessionUpdateAge: options.auth.sessionUpdateAge
2457
+ });
2458
+ const trpcRouter = createTrpcRouter(auth);
2459
+ const resolveBackend = createBackendResolver(options.backend);
2460
+ const adminGroups = options.auth.adminGroups ?? ["env_hopper_ui_super_admins"];
2461
+ const createContext = async ({ req }) => {
2462
+ const companySpecificBackend = await resolveBackend();
2463
+ let user = null;
2464
+ let userGroups = [];
2465
+ if (options.auth.devMockUser) {
2466
+ user = createMockUserFromDevConfig(options.auth.devMockUser);
2467
+ userGroups = options.auth.devMockUser.groups;
2468
+ } else try {
2469
+ const session = await auth.api.getSession({ headers: req.headers });
2470
+ user = (session === null || session === void 0 ? void 0 : session.user) ?? null;
2471
+ if (user && options.auth.oktaGroupsClaim) try {
2472
+ const tokenResult = await auth.api.getAccessToken({
2473
+ body: { providerId: "okta" },
2474
+ headers: req.headers
2475
+ });
2476
+ if (tokenResult.accessToken) {
2477
+ const parts = tokenResult.accessToken.split(".");
2478
+ if (parts.length === 3 && parts[1]) {
2479
+ const groups = JSON.parse(Buffer.from(parts[1], "base64").toString())[options.auth.oktaGroupsClaim];
2480
+ userGroups = Array.isArray(groups) ? groups : [];
2481
+ }
2482
+ }
2483
+ } catch (error) {
2484
+ console.error("[tRPC Context] Failed to get access token:", error);
2485
+ }
2486
+ } catch (error) {
2487
+ console.error("[tRPC Context] Failed to get session:", error);
2488
+ }
2489
+ return createEhTrpcContext({
2490
+ companySpecificBackend,
2491
+ user: user ? {
2492
+ ...user,
2493
+ groups: userGroups
2494
+ } : null,
2495
+ adminGroups
2496
+ });
2497
+ };
2498
+ const router$1 = Router();
2499
+ router$1.use(express.json());
2500
+ const middlewareContext = {
2501
+ auth,
2502
+ trpcRouter,
2503
+ createContext: async () => {
2504
+ return createEhTrpcContext({
2505
+ companySpecificBackend: await resolveBackend(),
2506
+ adminGroups
2507
+ });
2508
+ },
2509
+ authConfig: options.auth
2510
+ };
2511
+ if (((_normalizedOptions$fe = normalizedOptions.features) === null || _normalizedOptions$fe === void 0 ? void 0 : _normalizedOptions$fe.trpc) !== false) router$1.use(`${basePath}/trpc`, trpcExpress.createExpressMiddleware({
2512
+ router: trpcRouter,
2513
+ createContext
2514
+ }));
2515
+ registerFeatures(router$1, normalizedOptions, middlewareContext);
2516
+ if ((_options$hooks = options.hooks) === null || _options$hooks === void 0 ? void 0 : _options$hooks.onRoutesRegistered) await options.hooks.onRoutesRegistered(router$1);
2517
+ return {
2518
+ router: router$1,
2519
+ auth,
2520
+ trpcRouter,
2521
+ async connect() {
2522
+ var _options$hooks2;
2523
+ await dbManager.connect();
2524
+ if ((_options$hooks2 = options.hooks) === null || _options$hooks2 === void 0 ? void 0 : _options$hooks2.onDatabaseConnected) await options.hooks.onDatabaseConnected();
2525
+ },
2526
+ async disconnect() {
2527
+ var _options$hooks3;
2528
+ if ((_options$hooks3 = options.hooks) === null || _options$hooks3 === void 0 ? void 0 : _options$hooks3.onDatabaseDisconnecting) await options.hooks.onDatabaseDisconnecting();
2529
+ await dbManager.disconnect();
2530
+ },
2531
+ addRoutes(callback) {
2532
+ callback(router$1);
2533
+ }
2534
+ };
2535
+ }
2536
+
2537
+ //#endregion
2538
+ export { DEFAULT_ADMIN_SYSTEM_PROMPT, EhDatabaseManager, TABLE_SYNC_MAGAZINE, connectDb, createAdminChatHandler, createAppCatalogAdminRouter, createApprovalMethodRouter, createAuth, createAuthRouter, createDatabaseTools, createEhMiddleware, createEhTrpcContext, createPrismaDatabaseClient, createScreenshotRouter, createTrpcRouter, disconnectDb, getAssetByName, getDbClient, getUserGroups, isAdmin, isMemberOfAllGroups, isMemberOfAnyGroup, registerAssetRestController, registerAuthRoutes, registerIconRestController, registerScreenshotRestController, requireAdmin, requireGroups, setDbClient, staticControllerContract, syncAppCatalog, syncApprovalMethods, syncAssets, tableSyncPrisma, tool, upsertIcon, upsertIcons };
2539
+ //# sourceMappingURL=index.js.map