@langwatch/server 3.1.0-beta.3 → 3.1.0-beta.5

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 (119) hide show
  1. package/langwatch/ee/admin/ImpersonationBanner.tsx +61 -0
  2. package/langwatch/ee/admin/ImpersonationSwitchBackMenuItem.tsx +30 -0
  3. package/langwatch/ee/admin/__tests__/ImpersonationBanner.integration.test.tsx +82 -0
  4. package/langwatch/ee/admin/__tests__/impersonation.service.unit.test.ts +231 -0
  5. package/langwatch/ee/admin/backoffice/BackofficeTable.tsx +200 -0
  6. package/langwatch/ee/admin/backoffice/__tests__/adminClient.unit.test.ts +147 -0
  7. package/langwatch/ee/admin/backoffice/__tests__/dateInputToISO.unit.test.ts +42 -0
  8. package/langwatch/ee/admin/backoffice/__tests__/userVisibility.unit.test.ts +174 -0
  9. package/langwatch/ee/admin/backoffice/adminClient.ts +114 -0
  10. package/langwatch/ee/admin/backoffice/resources/OrganizationFeaturesView.tsx +373 -0
  11. package/langwatch/ee/admin/backoffice/resources/OrganizationsView.tsx +677 -0
  12. package/langwatch/ee/admin/backoffice/resources/ProjectsView.tsx +647 -0
  13. package/langwatch/ee/admin/backoffice/resources/SubscriptionsView.tsx +628 -0
  14. package/langwatch/ee/admin/backoffice/resources/UsersView.tsx +556 -0
  15. package/langwatch/ee/admin/backoffice/useAdminResource.ts +104 -0
  16. package/langwatch/ee/admin/backoffice/userVisibility.ts +105 -0
  17. package/langwatch/ee/admin/impersonation.service.ts +170 -0
  18. package/langwatch/ee/admin/isAdmin.ts +9 -0
  19. package/langwatch/ee/admin/routes/admin.ts +531 -0
  20. package/langwatch/ee/admin/safeSelects.ts +64 -0
  21. package/langwatch/ee/billing/__tests__/customerService.unit.test.ts +183 -0
  22. package/langwatch/ee/billing/__tests__/growthSeatEvent.unit.test.ts +213 -0
  23. package/langwatch/ee/billing/__tests__/licensePurchaseHandler.unit.test.ts +250 -0
  24. package/langwatch/ee/billing/__tests__/notification.service.unit.test.ts +768 -0
  25. package/langwatch/ee/billing/__tests__/planLimits.unit.test.ts +19 -0
  26. package/langwatch/ee/billing/__tests__/planProvider.unit.test.ts +440 -0
  27. package/langwatch/ee/billing/__tests__/planTypes.unit.test.ts +32 -0
  28. package/langwatch/ee/billing/__tests__/pricing.unit.test.ts +54 -0
  29. package/langwatch/ee/billing/__tests__/seatEventSubscription.unit.test.ts +717 -0
  30. package/langwatch/ee/billing/__tests__/stripe.integration.test.ts +344 -0
  31. package/langwatch/ee/billing/__tests__/stripePrices.types.unit.test.ts +27 -0
  32. package/langwatch/ee/billing/__tests__/stripePricesLoader.unit.test.ts +72 -0
  33. package/langwatch/ee/billing/__tests__/subscription.service.unit.test.ts +730 -0
  34. package/langwatch/ee/billing/__tests__/subscriptionItemCalculator.unit.test.ts +176 -0
  35. package/langwatch/ee/billing/__tests__/usage-limit.service.unit.test.ts +706 -0
  36. package/langwatch/ee/billing/__tests__/usageReportingService.integration.test.ts +421 -0
  37. package/langwatch/ee/billing/__tests__/usageReportingService.unit.test.ts +515 -0
  38. package/langwatch/ee/billing/__tests__/webhookService.unit.test.ts +958 -0
  39. package/langwatch/ee/billing/currencyRouter.ts +18 -0
  40. package/langwatch/ee/billing/errors.ts +129 -0
  41. package/langwatch/ee/billing/index.ts +67 -0
  42. package/langwatch/ee/billing/middleware.ts +17 -0
  43. package/langwatch/ee/billing/notifications/notification.service.ts +651 -0
  44. package/langwatch/ee/billing/notifications/repositories/notification.repository.ts +51 -0
  45. package/langwatch/ee/billing/notifications/types.ts +9 -0
  46. package/langwatch/ee/billing/notifications/usage-limit.service.ts +622 -0
  47. package/langwatch/ee/billing/nurturing/hooks/activityTracking.ts +90 -0
  48. package/langwatch/ee/billing/nurturing/hooks/activityTracking.unit.test.ts +237 -0
  49. package/langwatch/ee/billing/nurturing/hooks/featureAdoption.ts +120 -0
  50. package/langwatch/ee/billing/nurturing/hooks/featureAdoption.unit.test.ts +324 -0
  51. package/langwatch/ee/billing/nurturing/hooks/index.ts +17 -0
  52. package/langwatch/ee/billing/nurturing/hooks/productInterest.ts +68 -0
  53. package/langwatch/ee/billing/nurturing/hooks/productInterest.unit.test.ts +138 -0
  54. package/langwatch/ee/billing/nurturing/hooks/promptCreation.integration.test.ts +288 -0
  55. package/langwatch/ee/billing/nurturing/hooks/promptCreation.ts +131 -0
  56. package/langwatch/ee/billing/nurturing/hooks/promptCreation.unit.test.ts +134 -0
  57. package/langwatch/ee/billing/nurturing/hooks/signupIdentification.ts +101 -0
  58. package/langwatch/ee/billing/nurturing/hooks/signupIdentification.unit.test.ts +317 -0
  59. package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.ts +49 -0
  60. package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.unit.test.ts +170 -0
  61. package/langwatch/ee/billing/nurturing/hooks/userSync.ts +143 -0
  62. package/langwatch/ee/billing/nurturing/hooks/userSync.unit.test.ts +307 -0
  63. package/langwatch/ee/billing/nurturing/nurturing.service.ts +179 -0
  64. package/langwatch/ee/billing/nurturing/nurturing.service.unit.test.ts +266 -0
  65. package/langwatch/ee/billing/nurturing/nurturing.service.wiring.unit.test.ts +109 -0
  66. package/langwatch/ee/billing/nurturing/types.ts +125 -0
  67. package/langwatch/ee/billing/planLimits.ts +190 -0
  68. package/langwatch/ee/billing/planProvider.ts +119 -0
  69. package/langwatch/ee/billing/planTypes.ts +53 -0
  70. package/langwatch/ee/billing/pricing.ts +57 -0
  71. package/langwatch/ee/billing/services/billableEventsQuery.ts +248 -0
  72. package/langwatch/ee/billing/services/customerService.ts +90 -0
  73. package/langwatch/ee/billing/services/licensePurchaseHandler.ts +73 -0
  74. package/langwatch/ee/billing/services/seatEventSubscription.ts +351 -0
  75. package/langwatch/ee/billing/services/seatSyncService.ts +34 -0
  76. package/langwatch/ee/billing/services/subscription.repository.ts +203 -0
  77. package/langwatch/ee/billing/services/subscription.service.ts +549 -0
  78. package/langwatch/ee/billing/services/subscriptionItemCalculator.ts +249 -0
  79. package/langwatch/ee/billing/services/usageReportingService.ts +301 -0
  80. package/langwatch/ee/billing/services/webhookService.ts +858 -0
  81. package/langwatch/ee/billing/stripe/stripeCatalog.json +1781 -0
  82. package/langwatch/ee/billing/stripe/stripeClient.ts +13 -0
  83. package/langwatch/ee/billing/stripe/stripePriceCatalog.ts +70 -0
  84. package/langwatch/ee/billing/stripe/stripePrices.types.ts +118 -0
  85. package/langwatch/ee/billing/subscriptionRouter.ts +202 -0
  86. package/langwatch/ee/billing/types.ts +102 -0
  87. package/langwatch/ee/billing/utils/currency.ts +99 -0
  88. package/langwatch/ee/billing/utils/growthSeatEvent.ts +137 -0
  89. package/langwatch/ee/licensing/__tests__/constants.unit.test.ts +56 -0
  90. package/langwatch/ee/licensing/__tests__/defaults.unit.test.ts +192 -0
  91. package/langwatch/ee/licensing/__tests__/fixtures/testKeys.ts +86 -0
  92. package/langwatch/ee/licensing/__tests__/fixtures/testLicenses.ts +92 -0
  93. package/langwatch/ee/licensing/__tests__/licenseGenerationService.unit.test.ts +232 -0
  94. package/langwatch/ee/licensing/__tests__/licenseHandler.integration.test.ts +419 -0
  95. package/langwatch/ee/licensing/__tests__/planMapping.unit.test.ts +195 -0
  96. package/langwatch/ee/licensing/__tests__/planTemplates.unit.test.ts +193 -0
  97. package/langwatch/ee/licensing/__tests__/signing.unit.test.ts +164 -0
  98. package/langwatch/ee/licensing/__tests__/validation.unit.test.ts +281 -0
  99. package/langwatch/ee/licensing/client.ts +29 -0
  100. package/langwatch/ee/licensing/constants.ts +195 -0
  101. package/langwatch/ee/licensing/defaults.ts +55 -0
  102. package/langwatch/ee/licensing/errors.ts +11 -0
  103. package/langwatch/ee/licensing/index.ts +52 -0
  104. package/langwatch/ee/licensing/licenseGenerationService.ts +87 -0
  105. package/langwatch/ee/licensing/licenseHandler.ts +308 -0
  106. package/langwatch/ee/licensing/planInfo.ts +46 -0
  107. package/langwatch/ee/licensing/planMapping.ts +37 -0
  108. package/langwatch/ee/licensing/planTemplates.ts +109 -0
  109. package/langwatch/ee/licensing/server.ts +43 -0
  110. package/langwatch/ee/licensing/signing.ts +43 -0
  111. package/langwatch/ee/licensing/types.ts +156 -0
  112. package/langwatch/ee/licensing/validation.ts +107 -0
  113. package/langwatch/ee/managed-providers/ManagedModelProviderAlert.tsx +29 -0
  114. package/langwatch/ee/managed-providers/managedBedrockConfig.ts +226 -0
  115. package/langwatch/ee/saas/ExtraFooterComponents.tsx +169 -0
  116. package/langwatch/package.json +1 -1
  117. package/langwatch_nlp/uv.lock +179 -5
  118. package/package.json +1 -1
  119. package/packages/server/dist/cli.cjs +192 -142
@@ -0,0 +1,531 @@
1
+ /**
2
+ * Hono routes for the Backoffice admin endpoints.
3
+ *
4
+ * Lives under `ee/admin/routes/` so the whole admin surface — routes,
5
+ * services, client, React views — is consolidated under the `ee/` boundary
6
+ * instead of leaking admin-only code back into `src/server/routes/`.
7
+ *
8
+ * Mounted by `src/server/api-router.ts`. Exposes:
9
+ * - POST|DELETE /api/admin/impersonate
10
+ * - POST /api/admin/:resource (react-admin / ra-data-simple-prisma)
11
+ */
12
+ import {
13
+ defaultHandler,
14
+ getListHandler,
15
+ getOneHandler,
16
+ type GetListRequest,
17
+ type GetOneRequest,
18
+ } from "ra-data-simple-prisma";
19
+ import { PlanTypes, Prisma, SubscriptionStatus } from "@prisma/client";
20
+ import { Hono } from "hono";
21
+ import { auth as betterAuth } from "~/server/better-auth";
22
+ import { getServerAuthSession } from "~/server/auth";
23
+ import { prisma } from "~/server/db";
24
+ import { auditLog } from "~/server/auditLog";
25
+ import { UserService } from "~/server/users/user.service";
26
+ import { DomainError } from "~/server/app-layer/domain-error";
27
+ import { isAdmin } from "../isAdmin";
28
+ import {
29
+ ORGANIZATION_SAFE_SELECT,
30
+ PROJECT_SAFE_SELECT,
31
+ } from "../safeSelects";
32
+ import {
33
+ USER_BACKOFFICE_INCLUDE,
34
+ mapUserToBackofficeRow,
35
+ type UserWithBackofficeIncludes,
36
+ } from "../backoffice/userVisibility";
37
+ import { ImpersonationService } from "../impersonation.service";
38
+
39
+ export const app = new Hono().basePath("/api");
40
+
41
+ const ALLOWED_RESOURCES = new Set([
42
+ "user",
43
+ "organization",
44
+ "organizations",
45
+ "team",
46
+ "teams",
47
+ "project",
48
+ "subscription",
49
+ "subscriptions",
50
+ "organizationFeature",
51
+ "organizationFeatures",
52
+ ]);
53
+
54
+ // ---------- POST|DELETE /api/admin/impersonate ----------
55
+ //
56
+ // Both verbs share the same admin guard + BetterAuth session lookup, so we
57
+ // route them through a single helper and let the service do the real work.
58
+ // The service throws `DomainError` subclasses for business-rule rejections;
59
+ // the helper below maps those to HTTP status codes, keeping the route
60
+ // thin and leaving the rules in one testable place.
61
+
62
+ app.post("/admin/impersonate", async (c) => handleImpersonate(c, "POST"));
63
+ app.delete("/admin/impersonate", async (c) => handleImpersonate(c, "DELETE"));
64
+
65
+ async function handleImpersonate(c: any, method: "POST" | "DELETE") {
66
+ const session = await getServerAuthSession({ req: c.req.raw as any });
67
+ const user = session?.user.impersonator ?? session?.user;
68
+
69
+ if (!session || !user || !isAdmin(user)) {
70
+ return c.json({ message: "Not Found" }, 404);
71
+ }
72
+
73
+ const rawHeaders = new Headers();
74
+ for (const [k, v] of c.req.raw.headers.entries()) {
75
+ rawHeaders.append(k, v);
76
+ }
77
+ const rawBetterAuth = await betterAuth.api.getSession({
78
+ headers: rawHeaders,
79
+ });
80
+ if (!rawBetterAuth) {
81
+ return c.json({ message: "Unauthorized" }, 401);
82
+ }
83
+ const sessionId = rawBetterAuth.session.id;
84
+
85
+ // Adapt the real `auditLog` (typed with NextApiRequest) to the service's
86
+ // structural `AuditLogFn`, which keeps Next/Hono types out of the service.
87
+ const service = ImpersonationService.create(prisma, async (entry) =>
88
+ auditLog({ ...entry, req: entry.req as any }),
89
+ );
90
+
91
+ if (method === "DELETE") {
92
+ await service.stop({ sessionId });
93
+ return c.json({ message: "Impersonation ended" });
94
+ }
95
+
96
+ let body: Record<string, any>;
97
+ try {
98
+ body = await c.req.json();
99
+ } catch {
100
+ return c.json({ message: "Bad request" }, 400);
101
+ }
102
+
103
+ const { userIdToImpersonate, reason } = body;
104
+ if (!userIdToImpersonate || !reason) {
105
+ return c.json({ message: "Missing required fields" }, 400);
106
+ }
107
+
108
+ try {
109
+ await service.start({
110
+ sessionId,
111
+ impersonatorUserId: user.id,
112
+ userIdToImpersonate,
113
+ reason,
114
+ req: c.req.raw,
115
+ });
116
+ } catch (err) {
117
+ // Use `kind`, not `instanceof`, for the discriminant — survives the
118
+ // bundler duplicating class identities across module boundaries (see
119
+ // the rule in CLAUDE.md + domain-error.ts's doc comment).
120
+ if (DomainError.isHandled(err)) {
121
+ return c.json({ message: err.message }, err.httpStatus as any);
122
+ }
123
+ throw err;
124
+ }
125
+
126
+ return c.json({ message: "Impersonation started" });
127
+ }
128
+
129
+ // ---------- POST /api/admin/:resource ----------
130
+ app.post("/admin/:resource", async (c) => {
131
+ const session = await getServerAuthSession({ req: c.req.raw as any });
132
+ const user = session?.user.impersonator ?? session?.user;
133
+ if (!session || !user || !isAdmin(user)) {
134
+ return c.json({ message: "Not Found" }, 404);
135
+ }
136
+
137
+ let body: Record<string, any>;
138
+ try {
139
+ body = await c.req.json();
140
+ } catch {
141
+ return c.json({ message: "Bad request" }, 400);
142
+ }
143
+
144
+ // The react-admin body comes with resource + method inside it, but the
145
+ // URL also has the resource param. We use the body's resource field
146
+ // since that's what defaultHandler expects.
147
+ if (!body.resource) {
148
+ body.resource = c.req.param("resource");
149
+ }
150
+
151
+ if (!ALLOWED_RESOURCES.has(body.resource)) {
152
+ return c.json({ message: "Unknown resource" }, 400);
153
+ }
154
+
155
+ if (body.resource === "organizations") body.resource = "organization";
156
+ if (body.resource === "organizationFeatures")
157
+ body.resource = "organizationFeature";
158
+ if (body.resource === "subscriptions") body.resource = "subscription";
159
+ if (body.resource === "teams") body.resource = "team";
160
+
161
+ if (body.resource === "user" && body.method === "getList") {
162
+ const query = body.params?.filter?.query;
163
+ if (body.params?.filter?.query) delete body.params.filter.query;
164
+
165
+ const result = await getListHandler<Prisma.UserFindManyArgs>(
166
+ body as GetListRequest,
167
+ prisma.user,
168
+ {
169
+ ...(query
170
+ ? {
171
+ where: {
172
+ OR: [
173
+ // ID: prefix/contains so operators can paste the full id or
174
+ // a leading fragment (e.g. "user_abc") and still hit it.
175
+ { id: { contains: query, mode: "insensitive" } },
176
+ { name: { contains: query, mode: "insensitive" } },
177
+ { email: { contains: query, mode: "insensitive" } },
178
+ {
179
+ orgMemberships: {
180
+ some: {
181
+ organization: {
182
+ OR: [
183
+ { id: { contains: query, mode: "insensitive" } },
184
+ {
185
+ name: {
186
+ contains: query,
187
+ mode: "insensitive",
188
+ },
189
+ },
190
+ ],
191
+ },
192
+ },
193
+ },
194
+ },
195
+ {
196
+ // Mirror the main app's project-visibility rule
197
+ // (org membership → org.teams → team.projects). A user
198
+ // should be searchable by any project they can see in
199
+ // the project switcher, even without a TeamUser row.
200
+ orgMemberships: {
201
+ some: {
202
+ organization: {
203
+ teams: {
204
+ some: {
205
+ projects: {
206
+ some: {
207
+ OR: [
208
+ {
209
+ id: {
210
+ contains: query,
211
+ mode: "insensitive",
212
+ },
213
+ },
214
+ {
215
+ name: {
216
+ contains: query,
217
+ mode: "insensitive",
218
+ },
219
+ },
220
+ ],
221
+ },
222
+ },
223
+ },
224
+ },
225
+ },
226
+ },
227
+ },
228
+ },
229
+ ],
230
+ },
231
+ }
232
+ : {}),
233
+ include: USER_BACKOFFICE_INCLUDE,
234
+ map: (users: UserWithBackofficeIncludes[]) =>
235
+ users.map(mapUserToBackofficeRow),
236
+ },
237
+ );
238
+ return c.json(result);
239
+ }
240
+
241
+ if (body.resource === "organization" && body.method === "getList") {
242
+ const query = body.params?.filter?.query;
243
+ if (body.params?.filter?.query) delete body.params.filter.query;
244
+
245
+ const result = await getListHandler<Prisma.OrganizationFindManyArgs>(
246
+ body as GetListRequest,
247
+ prisma.organization,
248
+ {
249
+ select: ORGANIZATION_SAFE_SELECT,
250
+ ...(query
251
+ ? {
252
+ where: {
253
+ OR: [
254
+ { id: { contains: query, mode: "insensitive" } },
255
+ { name: { contains: query, mode: "insensitive" } },
256
+ { slug: { contains: query, mode: "insensitive" } },
257
+ ],
258
+ },
259
+ }
260
+ : {}),
261
+ },
262
+ );
263
+ return c.json(result);
264
+ }
265
+
266
+ // Single-org detail fetch used by the edit drawer — same safe select as
267
+ // the list, so credentials never reach the admin UI.
268
+ if (body.resource === "organization" && body.method === "getOne") {
269
+ const result = await getOneHandler<Prisma.OrganizationFindUniqueArgs>(
270
+ body as GetOneRequest,
271
+ prisma.organization,
272
+ { select: ORGANIZATION_SAFE_SELECT },
273
+ );
274
+ return c.json(result);
275
+ }
276
+
277
+ if (body.resource === "project" && body.method === "getList") {
278
+ const query = body.params?.filter?.query;
279
+ if (body.params?.filter?.query) delete body.params.filter.query;
280
+
281
+ const result = await getListHandler<Prisma.ProjectFindManyArgs>(
282
+ body as GetListRequest,
283
+ prisma.project,
284
+ {
285
+ select: PROJECT_SAFE_SELECT,
286
+ ...(query
287
+ ? {
288
+ where: {
289
+ OR: [
290
+ { id: { contains: query, mode: "insensitive" } },
291
+ { name: { contains: query, mode: "insensitive" } },
292
+ { slug: { contains: query, mode: "insensitive" } },
293
+ ],
294
+ },
295
+ }
296
+ : {}),
297
+ },
298
+ );
299
+ return c.json(result);
300
+ }
301
+
302
+ if (body.resource === "project" && body.method === "getOne") {
303
+ const result = await getOneHandler<Prisma.ProjectFindUniqueArgs>(
304
+ body as GetOneRequest,
305
+ prisma.project,
306
+ { select: PROJECT_SAFE_SELECT },
307
+ );
308
+ return c.json(result);
309
+ }
310
+
311
+ if (body.resource === "organizationFeature" && body.method === "getList") {
312
+ const query = body.params?.filter?.query;
313
+ if (body.params?.filter?.query) delete body.params.filter.query;
314
+
315
+ const result = await getListHandler<Prisma.OrganizationFeatureFindManyArgs>(
316
+ body as GetListRequest,
317
+ prisma.organizationFeature,
318
+ {
319
+ ...(query
320
+ ? {
321
+ where: {
322
+ OR: [
323
+ { id: { contains: query, mode: "insensitive" } },
324
+ { feature: { contains: query, mode: "insensitive" } },
325
+ {
326
+ organization: {
327
+ OR: [
328
+ { id: { contains: query, mode: "insensitive" } },
329
+ {
330
+ name: { contains: query, mode: "insensitive" },
331
+ },
332
+ {
333
+ slug: { contains: query, mode: "insensitive" },
334
+ },
335
+ ],
336
+ },
337
+ },
338
+ ],
339
+ },
340
+ }
341
+ : {}),
342
+ // Include the organization so the Backoffice table can render names
343
+ // instead of raw IDs. Admin-only endpoint, so exposing name/slug is
344
+ // fine.
345
+ include: {
346
+ organization: {
347
+ select: { id: true, name: true, slug: true },
348
+ },
349
+ },
350
+ },
351
+ );
352
+ return c.json(result);
353
+ }
354
+
355
+ // Admin user updates with side effects
356
+ if (
357
+ body.resource === "user" &&
358
+ body.method === "update" &&
359
+ body.params?.id &&
360
+ body.params?.data
361
+ ) {
362
+ const userId = String(body.params.id);
363
+ const data = body.params.data as Record<string, unknown>;
364
+ const userService = UserService.create(prisma);
365
+ let handledSideEffect = false;
366
+ const sideEffectAudit: Array<{
367
+ action: string;
368
+ payload: object;
369
+ }> = [];
370
+
371
+ if ("deactivatedAt" in data) {
372
+ const v = data.deactivatedAt;
373
+ if (v === null || v === "") {
374
+ await userService.reactivate({ id: userId });
375
+ delete data.deactivatedAt;
376
+ handledSideEffect = true;
377
+ sideEffectAudit.push({
378
+ action: "update/user",
379
+ payload: { id: userId, reactivate: true },
380
+ });
381
+ } else if (typeof v === "string" || v instanceof Date) {
382
+ await userService.deactivate({ id: userId });
383
+ delete data.deactivatedAt;
384
+ handledSideEffect = true;
385
+ const pickedDate = v instanceof Date ? v : new Date(v);
386
+ const isValidPickedDate = !Number.isNaN(pickedDate.getTime());
387
+ if (isValidPickedDate) {
388
+ await prisma.user.update({
389
+ where: { id: userId },
390
+ data: { deactivatedAt: pickedDate },
391
+ });
392
+ }
393
+ sideEffectAudit.push({
394
+ action: "update/user",
395
+ payload: {
396
+ id: userId,
397
+ deactivate: true,
398
+ ...(isValidPickedDate
399
+ ? { pickedDate: pickedDate.toISOString() }
400
+ : {}),
401
+ },
402
+ });
403
+ }
404
+ }
405
+
406
+ if ("email" in data && typeof data.email === "string") {
407
+ const newEmail = data.email.trim().toLowerCase();
408
+ await userService.updateProfile({ id: userId, email: newEmail });
409
+ delete data.email;
410
+ handledSideEffect = true;
411
+ sideEffectAudit.push({
412
+ action: "update/user",
413
+ payload: { id: userId, email: newEmail },
414
+ });
415
+ }
416
+
417
+ for (const entry of sideEffectAudit) {
418
+ await auditLog({
419
+ userId: user.id,
420
+ action: `admin/${entry.action}`,
421
+ args: entry.payload,
422
+ req: c.req.raw as any,
423
+ });
424
+ }
425
+
426
+ if (handledSideEffect && Object.keys(data).length === 0) {
427
+ const updated = await prisma.user.findUnique({
428
+ where: { id: userId },
429
+ });
430
+ return c.json({ data: updated });
431
+ }
432
+ }
433
+
434
+ // Normalize ssoDomain to lowercase
435
+ if (
436
+ body.resource === "organization" &&
437
+ (body.method === "create" || body.method === "update")
438
+ ) {
439
+ const params = body.params as
440
+ | { data?: { ssoDomain?: string | null } }
441
+ | undefined;
442
+ const ssoDomain = params?.data?.ssoDomain;
443
+ if (typeof ssoDomain === "string" && ssoDomain.trim() !== "") {
444
+ params!.data!.ssoDomain = ssoDomain.trim().toLowerCase();
445
+ }
446
+ }
447
+
448
+ if (body.resource === "subscription" && body.method === "getList") {
449
+ const query = body.params?.filter?.query;
450
+ if (body.params?.filter?.query) delete body.params.filter.query;
451
+
452
+ const upperQuery = query?.toUpperCase();
453
+ const matchingPlan = upperQuery
454
+ ? Object.values(PlanTypes).find((p) => p === upperQuery)
455
+ : undefined;
456
+ const matchingStatus = upperQuery
457
+ ? Object.values(SubscriptionStatus).find((s) => s === upperQuery)
458
+ : undefined;
459
+
460
+ const orFilters: Prisma.SubscriptionWhereInput[] = [];
461
+ if (query) {
462
+ orFilters.push({
463
+ id: { contains: query, mode: "insensitive" },
464
+ });
465
+ orFilters.push({
466
+ stripeSubscriptionId: {
467
+ contains: query,
468
+ mode: "insensitive",
469
+ },
470
+ });
471
+ orFilters.push({
472
+ organization: {
473
+ OR: [
474
+ { id: { contains: query, mode: "insensitive" } },
475
+ { name: { contains: query, mode: "insensitive" } },
476
+ { slug: { contains: query, mode: "insensitive" } },
477
+ ],
478
+ },
479
+ });
480
+ if (matchingPlan) orFilters.push({ plan: { equals: matchingPlan } });
481
+ if (matchingStatus)
482
+ orFilters.push({ status: { equals: matchingStatus } });
483
+ }
484
+
485
+ const result = await getListHandler<Prisma.SubscriptionFindManyArgs>(
486
+ body as GetListRequest,
487
+ prisma.subscription,
488
+ {
489
+ where: orFilters.length > 0 ? { OR: orFilters } : {},
490
+ include: {
491
+ organization: {
492
+ select: { id: true, name: true, slug: true },
493
+ },
494
+ },
495
+ },
496
+ );
497
+ return c.json(result);
498
+ }
499
+
500
+ const result = await defaultHandler(body as any, prisma as any, {
501
+ audit: {
502
+ model: {
503
+ create: async ({
504
+ data,
505
+ }: {
506
+ data: {
507
+ action: string;
508
+ resource: string;
509
+ payload: object;
510
+ author: { connect: { id: string } };
511
+ };
512
+ }) => {
513
+ await auditLog({
514
+ userId: data.author.connect.id,
515
+ action: `admin/${data.action}/${data.resource}`,
516
+ args: data.payload,
517
+ req: c.req.raw as any,
518
+ });
519
+ },
520
+ },
521
+ authProvider: {
522
+ getIdentity: async () => ({
523
+ id: user?.id ?? session?.user.id,
524
+ fullName: user?.name ?? session?.user.name,
525
+ }),
526
+ } as any,
527
+ },
528
+ });
529
+
530
+ return c.json(result);
531
+ });
@@ -0,0 +1,64 @@
1
+ import type { Prisma } from "@prisma/client";
2
+
3
+ /**
4
+ * Prisma `select` clauses used by the admin Hono routes for read operations
5
+ * (getList / getOne). Credentials — Elasticsearch API key + URL, every S3
6
+ * field — are intentionally omitted so secrets never reach the admin UI in
7
+ * paginated list payloads or edit-drawer fetches.
8
+ *
9
+ * Operators can still *write* new credential values (the update payload
10
+ * goes through `defaultHandler` which passes the whole `params.data`
11
+ * straight to Prisma) — this file just controls what the server is willing
12
+ * to *return*. Matches the standard "secrets are write-only over the wire"
13
+ * pattern.
14
+ *
15
+ * Lives in ee/admin/ because the admin surface is enterprise-edition
16
+ * functionality; server routes in src/ import from here.
17
+ */
18
+
19
+ export const ORGANIZATION_SAFE_SELECT = {
20
+ id: true,
21
+ name: true,
22
+ phoneNumber: true,
23
+ slug: true,
24
+ createdAt: true,
25
+ updatedAt: true,
26
+ usageSpendingMaxLimit: true,
27
+ signupData: true,
28
+ signedDPA: true,
29
+ useCustomElasticsearch: true,
30
+ useCustomS3: true,
31
+ sentPlanLimitAlert: true,
32
+ ssoDomain: true,
33
+ ssoProvider: true,
34
+ promoCode: true,
35
+ stripeCustomerId: true,
36
+ currency: true,
37
+ pricingModel: true,
38
+ license: true,
39
+ licenseExpiresAt: true,
40
+ licenseLastValidatedAt: true,
41
+ } as const satisfies Prisma.OrganizationSelect;
42
+
43
+ export const PROJECT_SAFE_SELECT = {
44
+ id: true,
45
+ name: true,
46
+ slug: true,
47
+ apiKey: true,
48
+ teamId: true,
49
+ language: true,
50
+ framework: true,
51
+ firstMessage: true,
52
+ integrated: true,
53
+ createdAt: true,
54
+ updatedAt: true,
55
+ userLinkTemplate: true,
56
+ piiRedactionLevel: true,
57
+ capturedInputVisibility: true,
58
+ capturedOutputVisibility: true,
59
+ traceSharingEnabled: true,
60
+ defaultModel: true,
61
+ topicClusteringModel: true,
62
+ embeddingsModel: true,
63
+ archivedAt: true,
64
+ } as const satisfies Prisma.ProjectSelect;