@langwatch/server 3.1.0-beta.4 → 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 (118) 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/package.json +1 -1
  118. package/packages/server/dist/cli.cjs +1 -1
@@ -0,0 +1,87 @@
1
+ import type { LicenseData } from "./types";
2
+ import { signLicense, encodeLicenseKey, generateLicenseId } from "./signing";
3
+ import { getPlanTemplate } from "./planTemplates";
4
+
5
+ interface GenerateLicenseKeyParams {
6
+ organizationName: string;
7
+ email: string;
8
+ planType: string;
9
+ maxMembers: number;
10
+ privateKey: string;
11
+ /** Override current time for deterministic testing */
12
+ now?: Date;
13
+ }
14
+
15
+ interface GenerateLicenseKeyResult {
16
+ licenseKey: string;
17
+ licenseData: LicenseData;
18
+ }
19
+
20
+ /**
21
+ * Generates a signed, encoded license key.
22
+ *
23
+ * Pure business logic — no HTTP, no Prisma, no env var access.
24
+ * Private key and all parameters passed explicitly.
25
+ */
26
+ export function generateLicenseKey({
27
+ organizationName,
28
+ email,
29
+ planType,
30
+ maxMembers,
31
+ privateKey,
32
+ now = new Date(),
33
+ }: GenerateLicenseKeyParams): GenerateLicenseKeyResult {
34
+ const template = getPlanTemplate(planType);
35
+ if (!template) {
36
+ throw new Error(`Unknown plan type: ${planType}`);
37
+ }
38
+
39
+ const seats = maxMembers > 0 ? maxMembers : 1;
40
+
41
+ const expiresAt = new Date(now);
42
+ expiresAt.setFullYear(expiresAt.getFullYear() + 1);
43
+
44
+ const resolvedOrgName = organizationName.trim() || email;
45
+
46
+ // Build plan with keys matching Zod schema field order.
47
+ // Signature verification re-serializes via JSON.stringify after Zod parsing,
48
+ // which reorders keys to schema order. Key order must match at sign time.
49
+ const plan: LicenseData["plan"] = {
50
+ type: template.type,
51
+ name: template.name,
52
+ maxMembers: seats,
53
+ maxMembersLite: template.maxMembersLite,
54
+ maxTeams: template.maxTeams,
55
+ maxProjects: template.maxProjects,
56
+ maxMessagesPerMonth: template.maxMessagesPerMonth,
57
+ evaluationsCredit: template.evaluationsCredit ?? 0,
58
+ maxWorkflows: template.maxWorkflows,
59
+ maxPrompts: template.maxPrompts,
60
+ maxEvaluators: template.maxEvaluators,
61
+ maxScenarios: template.maxScenarios,
62
+ maxAgents: template.maxAgents,
63
+ maxExperiments: template.maxExperiments,
64
+ maxOnlineEvaluations: template.maxOnlineEvaluations,
65
+ maxDatasets: template.maxDatasets,
66
+ maxDashboards: template.maxDashboards,
67
+ maxCustomGraphs: template.maxCustomGraphs,
68
+ maxAutomations: template.maxAutomations,
69
+ canPublish: template.canPublish,
70
+ usageUnit: template.usageUnit,
71
+ };
72
+
73
+ const licenseData: LicenseData = {
74
+ licenseId: generateLicenseId(),
75
+ version: 1,
76
+ organizationName: resolvedOrgName,
77
+ email,
78
+ issuedAt: now.toISOString(),
79
+ expiresAt: expiresAt.toISOString(),
80
+ plan,
81
+ };
82
+
83
+ const signedLicense = signLicense(licenseData, privateKey);
84
+ const licenseKey = encodeLicenseKey(signedLicense);
85
+
86
+ return { licenseKey, licenseData };
87
+ }
@@ -0,0 +1,308 @@
1
+ import type { PrismaClient } from "@prisma/client";
2
+ import type { PlanInfo } from "./planInfo";
3
+ import { FREE_PLAN, PUBLIC_KEY } from "./constants";
4
+ import { resolvePlanDefaults } from "./defaults";
5
+ import { OrganizationNotFoundError } from "./errors";
6
+ import type { LicenseStatus, RemoveLicenseResult, StoreLicenseResult, LicensePlanLimits } from "./types";
7
+ import { validateLicense, parseLicenseKey } from "./validation";
8
+ import type { ILicenseEnforcementRepository } from "~/server/license-enforcement/license-enforcement.repository";
9
+
10
+ /**
11
+ * Interface for trace usage counting.
12
+ * Follows Interface Segregation Principle - only what we need.
13
+ */
14
+ export interface ITraceUsageService {
15
+ getCurrentMonthCount(params: { organizationId: string }): Promise<number | "unlimited">;
16
+ }
17
+
18
+ interface LicenseHandlerConfig {
19
+ prisma: PrismaClient;
20
+ publicKey?: string;
21
+ repository: ILicenseEnforcementRepository;
22
+ traceUsageService?: ITraceUsageService;
23
+ }
24
+
25
+ /**
26
+ * Manages license validation and storage for self-hosted deployments.
27
+ *
28
+ * Key behaviors:
29
+ * - No license stored = FREE_PLAN (restricted access)
30
+ * - Valid license = license-based limits
31
+ * - Invalid/expired license = FREE_PLAN (restricted fallback)
32
+ *
33
+ * ## Design Note (SRP)
34
+ *
35
+ * This class has ONE reason to change: how licenses are stored and retrieved for organizations.
36
+ * It intentionally delegates specialized concerns to focused modules:
37
+ * - `validation.ts` - cryptographic validation and parsing
38
+ * - `planMapping.ts` - license-to-plan transformation
39
+ * - `errors.ts` - domain error types
40
+ *
41
+ * If this class grows to handle additional concerns (e.g., license renewal notifications,
42
+ * usage tracking), consider extracting those into separate collaborators.
43
+ */
44
+ export class LicenseHandler {
45
+ private prisma: PrismaClient;
46
+ private publicKey: string;
47
+ private repository: ILicenseEnforcementRepository;
48
+ private traceUsageService: ITraceUsageService | null;
49
+
50
+ constructor(config: LicenseHandlerConfig) {
51
+ this.prisma = config.prisma;
52
+ this.publicKey = config.publicKey ?? PUBLIC_KEY;
53
+ this.repository = config.repository;
54
+ this.traceUsageService = config.traceUsageService ?? null;
55
+ }
56
+
57
+
58
+ /**
59
+ * Gets the active plan for an organization based on its stored license.
60
+ *
61
+ * Returns:
62
+ * - FREE_PLAN if no license is stored
63
+ * - License-based PlanInfo if valid license exists
64
+ * - FREE_PLAN if license is invalid or expired
65
+ */
66
+ async getActivePlan(organizationId: string): Promise<PlanInfo> {
67
+ const organization = await this.prisma.organization.findUnique({
68
+ where: { id: organizationId },
69
+ select: { license: true },
70
+ });
71
+
72
+ // No license stored = FREE_PLAN (enforcement enabled requires valid license)
73
+ if (!organization?.license) {
74
+ return FREE_PLAN;
75
+ }
76
+
77
+ // Validate the stored license
78
+ const result = validateLicense(organization.license, this.publicKey);
79
+
80
+ if (result.valid) {
81
+ return result.planInfo;
82
+ }
83
+
84
+ // Invalid or expired license = restricted FREE_PLAN
85
+ return FREE_PLAN;
86
+ }
87
+
88
+ /**
89
+ * Validates and stores a license for an organization.
90
+ *
91
+ * - Validates the license key format, signature, and expiry
92
+ * - Updates the organization with license data
93
+ * - Returns the resulting plan info on success
94
+ */
95
+ async validateAndStoreLicense(
96
+ organizationId: string,
97
+ licenseKey: string
98
+ ): Promise<StoreLicenseResult> {
99
+ // Validate the license before storing
100
+ const result = validateLicense(licenseKey, this.publicKey);
101
+
102
+ if (!result.valid) {
103
+ return {
104
+ success: false,
105
+ error: result.error,
106
+ };
107
+ }
108
+
109
+ const { licenseData, planInfo } = result;
110
+
111
+ // Verify organization exists
112
+ const org = await this.prisma.organization.findUnique({
113
+ where: { id: organizationId },
114
+ select: { id: true },
115
+ });
116
+
117
+ if (!org) {
118
+ throw new OrganizationNotFoundError();
119
+ }
120
+
121
+ // Store the license and metadata
122
+ await this.prisma.organization.update({
123
+ where: { id: organizationId },
124
+ data: {
125
+ license: licenseKey,
126
+ licenseExpiresAt: new Date(licenseData.expiresAt),
127
+ licenseLastValidatedAt: new Date(),
128
+ },
129
+ });
130
+
131
+ return {
132
+ success: true,
133
+ planInfo,
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Gets the current license status for an organization.
139
+ *
140
+ * Returns details about whether a license exists, its validity,
141
+ * plan type, and expiration date. Metadata is returned even for
142
+ * invalid licenses so the UI can display "license expired" messages.
143
+ */
144
+ async getLicenseStatus(organizationId: string): Promise<LicenseStatus> {
145
+ const organization = await this.prisma.organization.findUnique({
146
+ where: { id: organizationId },
147
+ select: { license: true },
148
+ });
149
+
150
+ if (!organization?.license) {
151
+ return { hasLicense: false, valid: false };
152
+ }
153
+
154
+ const validationResult = validateLicense(organization.license, this.publicKey);
155
+
156
+ // For valid licenses, use data from validationResult (avoids second parse)
157
+ if (validationResult.valid) {
158
+ const { licenseData } = validationResult;
159
+ const resourceCounts = await this.getResourceCounts(organizationId, licenseData.plan);
160
+ return {
161
+ hasLicense: true,
162
+ valid: true,
163
+ plan: licenseData.plan.type,
164
+ planName: licenseData.plan.name,
165
+ expiresAt: licenseData.expiresAt,
166
+ organizationName: licenseData.organizationName,
167
+ ...resourceCounts,
168
+ };
169
+ }
170
+
171
+ // For invalid licenses, parse separately to get metadata for UI display
172
+ const signedLicense = parseLicenseKey(organization.license);
173
+ if (!signedLicense) {
174
+ return { hasLicense: true, valid: false, corrupted: true };
175
+ }
176
+
177
+ const { data: licenseData } = signedLicense;
178
+ const resourceCounts = await this.getResourceCounts(organizationId, licenseData.plan);
179
+ return {
180
+ hasLicense: true,
181
+ valid: false,
182
+ plan: licenseData.plan.type,
183
+ planName: licenseData.plan.name,
184
+ expiresAt: licenseData.expiresAt,
185
+ organizationName: licenseData.organizationName,
186
+ ...resourceCounts,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * Fetches all resource counts for an organization and combines with plan limits.
192
+ */
193
+ private async getResourceCounts(organizationId: string, plan: LicensePlanLimits) {
194
+ // Resolve defaults for optional plan fields
195
+ const resolved = resolvePlanDefaults(plan);
196
+
197
+ // Get message count via TraceUsageService (direct ES/CH query).
198
+ // Returns 0 if service not provided (e.g., in tests).
199
+ // "unlimited" is resolved to 0 since license display needs a numeric value.
200
+ const messagesCountPromise = this.traceUsageService
201
+ ? this.traceUsageService.getCurrentMonthCount({ organizationId })
202
+ .then((count) => (count === "unlimited" ? 0 : count))
203
+ : Promise.resolve(0);
204
+
205
+ const [
206
+ currentMembers,
207
+ currentMembersLite,
208
+ currentTeams,
209
+ currentProjects,
210
+ currentPrompts,
211
+ currentWorkflows,
212
+ currentScenarios,
213
+ currentEvaluators,
214
+ currentAgents,
215
+ currentExperiments,
216
+ currentOnlineEvaluations,
217
+ currentDatasets,
218
+ currentDashboards,
219
+ currentCustomGraphs,
220
+ currentAutomations,
221
+ currentMessagesPerMonth,
222
+ ] = await Promise.all([
223
+ this.repository.getMemberCount(organizationId),
224
+ this.repository.getMembersLiteCount(organizationId),
225
+ this.repository.getTeamCount(organizationId),
226
+ this.repository.getProjectCount(organizationId),
227
+ this.repository.getPromptCount(organizationId),
228
+ this.repository.getWorkflowCount(organizationId),
229
+ this.repository.getActiveScenarioCount(organizationId),
230
+ this.repository.getEvaluatorCount(organizationId),
231
+ this.repository.getAgentCount(organizationId),
232
+ this.repository.getExperimentCount(organizationId),
233
+ this.repository.getOnlineEvaluationCount(organizationId),
234
+ this.repository.getDatasetCount(organizationId),
235
+ this.repository.getDashboardCount(organizationId),
236
+ this.repository.getCustomGraphCount(organizationId),
237
+ this.repository.getAutomationCount(organizationId),
238
+ messagesCountPromise,
239
+ ]);
240
+
241
+ return {
242
+ currentMembers,
243
+ maxMembers: resolved.maxMembers,
244
+ currentMembersLite,
245
+ maxMembersLite: resolved.maxMembersLite,
246
+ currentTeams,
247
+ maxTeams: resolved.maxTeams,
248
+ currentProjects,
249
+ maxProjects: resolved.maxProjects,
250
+ currentPrompts,
251
+ maxPrompts: resolved.maxPrompts,
252
+ currentWorkflows,
253
+ maxWorkflows: resolved.maxWorkflows,
254
+ currentScenarios,
255
+ maxScenarios: resolved.maxScenarios,
256
+ currentEvaluators,
257
+ maxEvaluators: resolved.maxEvaluators,
258
+ currentAgents,
259
+ maxAgents: resolved.maxAgents,
260
+ currentExperiments,
261
+ maxExperiments: resolved.maxExperiments,
262
+ currentOnlineEvaluations,
263
+ maxOnlineEvaluations: resolved.maxOnlineEvaluations,
264
+ currentDatasets,
265
+ maxDatasets: resolved.maxDatasets,
266
+ currentDashboards,
267
+ maxDashboards: resolved.maxDashboards,
268
+ currentCustomGraphs,
269
+ maxCustomGraphs: resolved.maxCustomGraphs,
270
+ currentAutomations,
271
+ maxAutomations: resolved.maxAutomations,
272
+ currentMessagesPerMonth,
273
+ maxMessagesPerMonth: resolved.maxMessagesPerMonth,
274
+ };
275
+ }
276
+
277
+ /**
278
+ * Removes the license from an organization (idempotent).
279
+ *
280
+ * This clears all license-related fields, returning the organization
281
+ * to unlimited mode (when enforcement is disabled) or FREE_PLAN
282
+ * (when enforcement is enabled).
283
+ *
284
+ * @returns { removed: true } when complete
285
+ * @throws OrganizationNotFoundError if organization does not exist
286
+ */
287
+ async removeLicense(organizationId: string): Promise<RemoveLicenseResult> {
288
+ const org = await this.prisma.organization.findUnique({
289
+ where: { id: organizationId },
290
+ select: { id: true },
291
+ });
292
+
293
+ if (!org) {
294
+ throw new OrganizationNotFoundError();
295
+ }
296
+
297
+ await this.prisma.organization.update({
298
+ where: { id: organizationId },
299
+ data: {
300
+ license: null,
301
+ licenseExpiresAt: null,
302
+ licenseLastValidatedAt: null,
303
+ },
304
+ });
305
+
306
+ return { removed: true };
307
+ }
308
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * PlanInfo type definition - isolated to avoid circular dependencies.
3
+ *
4
+ * This type is used by both ee/licensing and src/server code.
5
+ * Keeping it in a separate file prevents webpack from bundling
6
+ * server-side code when client components import from ee/licensing.
7
+ */
8
+ export type PlanInfo = {
9
+ planSource: "license" | "subscription" | "free";
10
+ type: string;
11
+ name: string;
12
+ free: boolean;
13
+ trialDays?: number;
14
+ daysSinceCreation?: number;
15
+ overrideAddingLimitations?: boolean;
16
+ maxMembers: number;
17
+ maxMembersLite: number;
18
+ maxTeams: number;
19
+ maxProjects: number;
20
+ maxMessagesPerMonth: number;
21
+ maxWorkflows: number;
22
+ maxPrompts: number;
23
+ maxEvaluators: number;
24
+ maxScenarios: number;
25
+ maxAgents: number;
26
+ maxExperiments: number;
27
+ maxOnlineEvaluations: number;
28
+ maxDatasets: number;
29
+ maxDashboards: number;
30
+ maxCustomGraphs: number;
31
+ maxAutomations: number;
32
+ canPublish: boolean;
33
+ usageUnit?: string;
34
+ userPrice?: {
35
+ USD: number;
36
+ EUR: number;
37
+ };
38
+ tracesPrice?: {
39
+ USD: number;
40
+ EUR: number;
41
+ };
42
+ prices: {
43
+ USD: number;
44
+ EUR: number;
45
+ };
46
+ };
@@ -0,0 +1,37 @@
1
+ import type { PlanInfo } from "./planInfo";
2
+ import { resolvePlanDefaults } from "./defaults";
3
+ import type { LicenseData } from "./types";
4
+
5
+ export function mapToPlanInfo(licenseData: LicenseData): PlanInfo {
6
+ const resolved = resolvePlanDefaults(licenseData.plan);
7
+
8
+ return {
9
+ planSource: "license",
10
+ type: resolved.type,
11
+ name: resolved.name,
12
+ free: false, // Paid license = not a free tier
13
+ overrideAddingLimitations: false, // Enforce limits, don't bypass
14
+ maxMembers: resolved.maxMembers,
15
+ maxMembersLite: resolved.maxMembersLite,
16
+ maxTeams: resolved.maxTeams,
17
+ maxProjects: resolved.maxProjects,
18
+ maxMessagesPerMonth: resolved.maxMessagesPerMonth,
19
+ maxWorkflows: resolved.maxWorkflows,
20
+ maxPrompts: resolved.maxPrompts,
21
+ maxEvaluators: resolved.maxEvaluators,
22
+ maxScenarios: resolved.maxScenarios,
23
+ maxAgents: resolved.maxAgents,
24
+ maxExperiments: resolved.maxExperiments,
25
+ maxOnlineEvaluations: resolved.maxOnlineEvaluations,
26
+ maxDatasets: resolved.maxDatasets,
27
+ maxDashboards: resolved.maxDashboards,
28
+ maxCustomGraphs: resolved.maxCustomGraphs,
29
+ maxAutomations: resolved.maxAutomations,
30
+ canPublish: resolved.canPublish,
31
+ usageUnit: resolved.usageUnit,
32
+ prices: {
33
+ USD: 0,
34
+ EUR: 0,
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,109 @@
1
+ import type { LicensePlanLimits } from "./types";
2
+ import { DEFAULT_LIMIT } from "./constants";
3
+
4
+ /**
5
+ * GROWTH plan template with unlimited limits except maxMembers.
6
+ * maxMembers must be supplied at generation time (from Stripe seat quantity).
7
+ * Used for self-serving license purchases.
8
+ */
9
+ export const GROWTH_TEMPLATE: Omit<LicensePlanLimits, "maxMembers"> = {
10
+ type: "GROWTH",
11
+ name: "Growth",
12
+ maxMembersLite: DEFAULT_LIMIT,
13
+ maxTeams: DEFAULT_LIMIT,
14
+ maxProjects: DEFAULT_LIMIT,
15
+ maxMessagesPerMonth: DEFAULT_LIMIT,
16
+ evaluationsCredit: 0,
17
+ maxWorkflows: DEFAULT_LIMIT,
18
+ maxPrompts: DEFAULT_LIMIT,
19
+ maxEvaluators: DEFAULT_LIMIT,
20
+ maxScenarios: DEFAULT_LIMIT,
21
+ maxAgents: DEFAULT_LIMIT,
22
+ maxExperiments: DEFAULT_LIMIT,
23
+ maxOnlineEvaluations: DEFAULT_LIMIT,
24
+ maxDatasets: DEFAULT_LIMIT,
25
+ maxDashboards: DEFAULT_LIMIT,
26
+ maxCustomGraphs: DEFAULT_LIMIT,
27
+ maxAutomations: DEFAULT_LIMIT,
28
+ canPublish: true,
29
+ usageUnit: "events",
30
+ };
31
+
32
+ /**
33
+ * PRO plan template with standard limits.
34
+ * Used as default when generating PRO licenses.
35
+ */
36
+ export const PRO_TEMPLATE: LicensePlanLimits = {
37
+ type: "PRO",
38
+ name: "Pro",
39
+ maxMembers: 10,
40
+ maxMembersLite: 5,
41
+ maxTeams: 10,
42
+ maxProjects: 20,
43
+ maxMessagesPerMonth: 100000,
44
+ evaluationsCredit: 0,
45
+ maxWorkflows: 50,
46
+ maxPrompts: 50,
47
+ maxEvaluators: 50,
48
+ maxScenarios: 50,
49
+ maxAgents: 50,
50
+ maxExperiments: 50,
51
+ maxOnlineEvaluations: 50,
52
+ maxDatasets: 50,
53
+ maxDashboards: 50,
54
+ maxCustomGraphs: 50,
55
+ maxAutomations: 50,
56
+ canPublish: true,
57
+ usageUnit: "traces",
58
+ };
59
+
60
+ /**
61
+ * ENTERPRISE plan template with high limits.
62
+ * Used as default when generating ENTERPRISE licenses.
63
+ */
64
+ export const ENTERPRISE_TEMPLATE: LicensePlanLimits = {
65
+ type: "ENTERPRISE",
66
+ name: "Enterprise",
67
+ maxMembers: 100,
68
+ maxMembersLite: 50,
69
+ maxTeams: 100,
70
+ maxProjects: 500,
71
+ maxMessagesPerMonth: 10000000,
72
+ evaluationsCredit: 0,
73
+ maxWorkflows: 1000,
74
+ maxPrompts: 1000,
75
+ maxEvaluators: 1000,
76
+ maxScenarios: 1000,
77
+ maxAgents: 1000,
78
+ maxExperiments: 1000,
79
+ maxOnlineEvaluations: 1000,
80
+ maxDatasets: 1000,
81
+ maxDashboards: 1000,
82
+ maxCustomGraphs: 1000,
83
+ maxAutomations: 1000,
84
+ canPublish: true,
85
+ usageUnit: "traces",
86
+ };
87
+
88
+ /**
89
+ * Returns the plan template for a given plan type.
90
+ *
91
+ * @param planType - The plan type (PRO, ENTERPRISE, GROWTH, or CUSTOM)
92
+ * @returns The plan template or null for CUSTOM/unknown types.
93
+ * GROWTH returns Omit<LicensePlanLimits, "maxMembers"> since
94
+ * maxMembers must be supplied at generation time.
95
+ */
96
+ export function getPlanTemplate(
97
+ planType: string
98
+ ): LicensePlanLimits | Omit<LicensePlanLimits, "maxMembers"> | null {
99
+ switch (planType) {
100
+ case "GROWTH":
101
+ return GROWTH_TEMPLATE;
102
+ case "PRO":
103
+ return PRO_TEMPLATE;
104
+ case "ENTERPRISE":
105
+ return ENTERPRISE_TEMPLATE;
106
+ default:
107
+ return null;
108
+ }
109
+ }
@@ -0,0 +1,43 @@
1
+ import type { PrismaClient } from "@prisma/client";
2
+ import { LicenseHandler } from "./licenseHandler";
3
+ import type { ITraceUsageService } from "./licenseHandler";
4
+ import { PUBLIC_KEY } from "./constants";
5
+ import { LicenseEnforcementRepository } from "~/server/license-enforcement/license-enforcement.repository";
6
+ import { getApp } from "~/server/app-layer/app";
7
+
8
+ /**
9
+ * Factory function for creating a LicenseHandler instance.
10
+ * This is the composition root - wires up concrete implementations.
11
+ *
12
+ * Placed in server.ts (not index.ts) to:
13
+ * 1. Avoid bundling server-only dependencies in client code
14
+ * 2. Keep LicenseHandler pure (depends only on interfaces)
15
+ * 3. Centralize DI wiring in one place
16
+ *
17
+ * Usage counting is delegated to the orchestrated UsageService (via getApp().usage)
18
+ * which applies UsageMeterPolicy to select the correct counter (traces vs events).
19
+ *
20
+ * @param prisma - PrismaClient instance for database access
21
+ * @param publicKey - Optional public key for license validation (defaults to PUBLIC_KEY)
22
+ * @returns Configured LicenseHandler instance
23
+ */
24
+ export function createLicenseHandler(
25
+ prisma: PrismaClient,
26
+ publicKey: string = PUBLIC_KEY,
27
+ ): LicenseHandler {
28
+ const repository = new LicenseEnforcementRepository(prisma);
29
+
30
+ // Lazy proxy: defers to getApp().usage at call time so the app can be
31
+ // fully initialized before the first usage count is requested.
32
+ const usageService: ITraceUsageService = {
33
+ getCurrentMonthCount: (params) =>
34
+ getApp().usage.getCurrentMonthCount(params),
35
+ };
36
+
37
+ return new LicenseHandler({
38
+ prisma,
39
+ publicKey,
40
+ repository,
41
+ traceUsageService: usageService,
42
+ });
43
+ }
@@ -0,0 +1,43 @@
1
+ import crypto from "crypto";
2
+ import type { LicenseData, SignedLicense } from "./types";
3
+
4
+ /**
5
+ * Signs license data with an RSA private key using SHA256.
6
+ *
7
+ * @param data - The license data to sign
8
+ * @param privateKey - RSA private key in PEM format
9
+ * @returns SignedLicense with data and base64-encoded signature
10
+ */
11
+ export function signLicense(data: LicenseData, privateKey: string): SignedLicense {
12
+ const dataString = JSON.stringify(data);
13
+ const sign = crypto.createSign("SHA256");
14
+ sign.update(dataString);
15
+ sign.end();
16
+
17
+ const signature = sign.sign(privateKey, "base64");
18
+
19
+ return {
20
+ data,
21
+ signature,
22
+ };
23
+ }
24
+
25
+ /**
26
+ * Encodes a signed license as a base64 string for distribution.
27
+ *
28
+ * @param signedLicense - The signed license to encode
29
+ * @returns Base64-encoded license key string
30
+ */
31
+ export function encodeLicenseKey(signedLicense: SignedLicense): string {
32
+ const json = JSON.stringify(signedLicense);
33
+ return Buffer.from(json, "utf-8").toString("base64");
34
+ }
35
+
36
+ /**
37
+ * Generates a unique license ID.
38
+ *
39
+ * @returns A unique license ID prefixed with "lic-"
40
+ */
41
+ export function generateLicenseId(): string {
42
+ return `lic-${crypto.randomUUID()}`;
43
+ }