🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore: refactor admin-api handling into ee folder (#6462)
Steffen Schmitz820de6f30fe0
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 1d8f758e8b..f78cb6f914 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -214,6 +214,7 @@ jobs:echo "LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=1" >> .envecho "LANGFUSE_TRACE_DELETE_CONCURRENCY=100" >> .envecho "ADMIN_API_KEY=admin-api-key" >> .env+ echo "LANGFUSE_EE_LICENSE_KEY=langfuse_ee_test" >> .env- name: Run dev containersrun: |docker compose -f docker-compose.dev${{ matrix.blob-provider }}.yml up -ddiff --git a/web/src/ee/features/admin-api/organizations/apiKeys/apiKeyById.ts b/web/src/ee/features/admin-api/organizations/apiKeys/apiKeyById.tsnew file mode 100644index 0000000000..dbf7df9ec9--- /dev/null+++ b/web/src/ee/features/admin-api/organizations/apiKeys/apiKeyById.ts@@ -0,0 +1,67 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { z } from "zod";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";++export const validateQueryParams = (+ query: unknown,+): { organizationId: string; apiKeyId: string } | null => {+ const inputQuerySchema = z.object({+ organizationId: z.string(),+ apiKeyId: z.string(),+ });+ const validation = inputQuerySchema.safeParse(query);+ if (!validation.success) {+ return null;+ }+ return validation.data;+};++export async function handleDeleteApiKey(+ req: NextApiRequest,+ res: NextApiResponse,+ organizationId: string,+ apiKeyId: string,+) {+ // Check if API key exists and belongs to the organization+ const apiKey = await prisma.apiKey.findFirst({+ where: {+ id: apiKeyId,+ orgId: organizationId,+ scope: "ORGANIZATION",+ },+ });++ if (!apiKey) {+ return res.status(404).json({ error: "API key not found" });+ }++ // Delete the API key+ const deleted = await new ApiAuthService(prisma, redis).deleteApiKey(+ apiKeyId,+ organizationId,+ "ORGANIZATION",+ );++ if (!deleted) {+ return res.status(500).json({ error: "Failed to delete API key" });+ }++ // Log the API key deletion+ await auditLog({+ resourceType: "apiKey",+ resourceId: apiKeyId,+ action: "delete",+ orgId: organizationId,+ orgRole: "ADMIN",+ apiKeyId: "ADMIN_KEY",+ });++ logger.info(+ `Deleted API key ${apiKeyId} for organization ${organizationId} via admin API`,+ );++ return res.status(200).json({ success: true });+}diff --git a/web/src/ee/features/admin-api/organizations/apiKeys/index.ts b/web/src/ee/features/admin-api/organizations/apiKeys/index.tsnew file mode 100644index 0000000000..50f0c7bf39--- /dev/null+++ b/web/src/ee/features/admin-api/organizations/apiKeys/index.ts@@ -0,0 +1,90 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger } from "@langfuse/shared/src/server";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { z } from "zod";+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";++export const validateQueryAndExtractId = (query: unknown): string | null => {+ const inputQuerySchema = z.object({+ organizationId: z.string(),+ });+ const validation = inputQuerySchema.safeParse(query);+ if (!validation.success) {+ return null;+ }+ return validation.data.organizationId;+};++export async function handleGetApiKeys(+ req: NextApiRequest,+ res: NextApiResponse,+ organizationId: string,+) {+ const apiKeys = await prisma.apiKey.findMany({+ where: {+ orgId: organizationId,+ scope: "ORGANIZATION",+ },+ select: {+ id: true,+ createdAt: true,+ expiresAt: true,+ lastUsedAt: true,+ note: true,+ publicKey: true,+ displaySecretKey: true,+ },+ orderBy: {+ createdAt: "asc",+ },+ });++ return res.status(200).json({ apiKeys });+}++export async function handleCreateApiKey(+ req: NextApiRequest,+ res: NextApiResponse,+ organizationId: string,+) {+ // Validate the request body+ const createApiKeySchema = z.object({+ note: z.string().optional(),+ });++ const validationResult = createApiKeySchema.safeParse(req.body);++ if (!validationResult.success) {+ return res.status(400).json({+ error: "Invalid request body",+ details: validationResult.error.format(),+ });+ }++ const { note } = validationResult.data;++ // Create the API key+ const apiKeyMeta = await createAndAddApiKeysToDb({+ prisma,+ entityId: organizationId,+ note,+ scope: "ORGANIZATION",+ });++ // Log the API key creation+ await auditLog({+ resourceType: "apiKey",+ resourceId: apiKeyMeta.id,+ action: "create",+ orgId: organizationId,+ orgRole: "ADMIN",+ apiKeyId: "ADMIN_KEY",+ });++ logger.info(+ `Created API key ${apiKeyMeta.id} for organization ${organizationId} via admin API`,+ );++ return res.status(201).json(apiKeyMeta);+}diff --git a/web/src/ee/features/admin-api/organizations/index.ts b/web/src/ee/features/admin-api/organizations/index.tsnew file mode 100644index 0000000000..20adb8e582--- /dev/null+++ b/web/src/ee/features/admin-api/organizations/index.ts@@ -0,0 +1,63 @@+import { prisma } from "@langfuse/shared/src/db";+import { logger } from "@langfuse/shared/src/server";+import { organizationNameSchema } from "@/src/features/organizations/utils/organizationNameSchema";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { type NextApiRequest, type NextApiResponse } from "next";++export async function handleGetOrganizations(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ const organizations = await prisma.organization.findMany({+ select: {+ id: true,+ name: true,+ createdAt: true,+ },+ });+ return res.status(200).json({ organizations });+}++export async function handleCreateOrganization(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ // Validate the request body using the organizationNameSchema+ const validationResult = organizationNameSchema.safeParse(req.body);++ if (!validationResult.success) {+ res.status(400).json({+ error: "Invalid request body",+ details: validationResult.error.format(),+ });+ return;+ }++ const { name } = validationResult.data;++ // Create the organization in the database+ const organization = await prisma.organization.create({+ data: {+ name,+ },+ });++ // Log the organization creation+ await auditLog({+ resourceType: "organization",+ resourceId: organization.id,+ action: "create",+ orgId: organization.id,+ orgRole: "ADMIN",+ after: organization,+ apiKeyId: "ADMIN_KEY",+ });++ logger.info(`Created organization ${organization.id} via admin API`);++ return res.status(201).json({+ id: organization.id,+ name: organization.name,+ createdAt: organization.createdAt,+ });+}diff --git a/web/src/ee/features/admin-api/organizations/organizationById.ts b/web/src/ee/features/admin-api/organizations/organizationById.tsnew file mode 100644index 0000000000..0bae7a39cd--- /dev/null+++ b/web/src/ee/features/admin-api/organizations/organizationById.ts@@ -0,0 +1,150 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger } from "@langfuse/shared/src/server";+import { organizationNameSchema } from "@/src/features/organizations/utils/organizationNameSchema";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { z } from "zod";++export const validateQueryAndExtractId = (query: unknown): string | null => {+ const inputQuerySchema = z.object({+ organizationId: z.string(),+ });+ const validation = inputQuerySchema.safeParse(query);+ if (!validation.success) {+ return null;+ }+ return validation.data.organizationId;+};++export async function handleGetOrganizationById(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ const organizationId = validateQueryAndExtractId(req.query);+ if (!organizationId) {+ return res.status(400).json({ error: "Invalid organization ID" });+ }++ const organization = await prisma.organization.findUnique({+ where: { id: organizationId },+ select: {+ id: true,+ name: true,+ createdAt: true,+ },+ });++ if (!organization) {+ return res.status(404).json({ error: "Organization not found" });+ }++ return res.status(200).json(organization);+}++export async function handleUpdateOrganization(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ const organizationId = validateQueryAndExtractId(req.query);+ if (!organizationId) {+ return res.status(400).json({ error: "Invalid organization ID" });+ }++ const validationResult = organizationNameSchema.safeParse(req.body);++ if (!validationResult.success) {+ return res.status(400).json({+ error: "Invalid request body",+ details: validationResult.error.format(),+ });+ }++ const { name } = validationResult.data;++ // Check if organization exists+ const existingOrg = await prisma.organization.findUnique({+ where: { id: organizationId },+ });++ if (!existingOrg) {+ return res.status(404).json({ error: "Organization not found" });+ }++ // Update the organization+ const updatedOrganization = await prisma.organization.update({+ where: { id: organizationId },+ data: { name },+ });++ // Log the update+ await auditLog({+ resourceType: "organization",+ resourceId: organizationId,+ action: "update",+ orgId: organizationId,+ orgRole: "ADMIN",+ before: existingOrg,+ after: updatedOrganization,+ apiKeyId: "ADMIN_KEY",+ });++ logger.info(`Updated organization ${organizationId} via admin API`);++ return res.status(200).json({+ id: updatedOrganization.id,+ name: updatedOrganization.name,+ createdAt: updatedOrganization.createdAt,+ });+}++export async function handleDeleteOrganization(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ const organizationId = validateQueryAndExtractId(req.query);+ if (!organizationId) {+ return res.status(400).json({ error: "Invalid organization ID" });+ }++ // Check if organization exists+ const existingOrg = await prisma.organization.findUnique({+ where: { id: organizationId },+ });++ if (!existingOrg) {+ return res.status(404).json({ error: "Organization not found" });+ }++ // Check if organization has any projects+ const projectCount = await prisma.project.count({+ where: { orgId: organizationId },+ });++ if (projectCount > 0) {+ return res.status(400).json({+ error: "Cannot delete organization with existing projects",+ message:+ "Please delete or transfer all projects before deleting the organization.",+ });+ }++ // Delete the organization+ const deletedOrganization = await prisma.organization.delete({+ where: { id: organizationId },+ });++ // Log the deletion+ await auditLog({+ resourceType: "organization",+ resourceId: organizationId,+ action: "delete",+ orgId: organizationId,+ orgRole: "ADMIN",+ before: deletedOrganization,+ apiKeyId: "ADMIN_KEY",+ });++ logger.info(`Deleted organization ${organizationId} via admin API`);++ return res.status(200).json({ success: true });+}diff --git a/web/src/ee/features/admin-api/public/organizations/memberships.ts b/web/src/ee/features/admin-api/public/organizations/memberships.tsnew file mode 100644index 0000000000..54e2d4cf91--- /dev/null+++ b/web/src/ee/features/admin-api/public/organizations/memberships.ts@@ -0,0 +1,94 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { Role } from "@langfuse/shared";+import { z } from "zod";++// Schema for request body validation+const MembershipSchema = z.object({+ userId: z.string(),+ role: z.nativeEnum(Role),+});++// GET - Retrieve all organization memberships+export async function handleGetMemberships(+ req: NextApiRequest,+ res: NextApiResponse,+ orgId: string,+) {+ const memberships = await prisma.organizationMembership.findMany({+ where: {+ orgId: orgId,+ },+ include: {+ user: {+ select: {+ id: true,+ email: true,+ name: true,+ },+ },+ },+ });++ return res.status(200).json({+ memberships: memberships.map((membership) => ({+ userId: membership.userId,+ role: membership.role,+ email: membership.user.email,+ name: membership.user.name,+ })),+ });+}++// PUT - Update or create an organization membership+export async function handleUpdateMembership(+ req: NextApiRequest,+ res: NextApiResponse,+ orgId: string,+) {+ const validatedBody = MembershipSchema.safeParse(req.body);+ if (!validatedBody.success) {+ return res.status(400).json({+ error: "Invalid request body",+ details: validatedBody.error.errors,+ });+ }++ // Check if user exists+ const user = await prisma.user.findUnique({+ where: {+ id: validatedBody.data.userId,+ },+ });++ if (!user) {+ return res.status(404).json({+ error: "User not found",+ });+ }++ // Upsert the membership+ const membership = await prisma.organizationMembership.upsert({+ where: {+ orgId_userId: {+ orgId,+ userId: validatedBody.data.userId,+ },+ },+ update: {+ role: validatedBody.data.role,+ },+ create: {+ orgId,+ userId: validatedBody.data.userId,+ role: validatedBody.data.role,+ },+ });++ return res.status(200).json({+ userId: membership.userId,+ role: membership.role,+ email: user.email,+ name: user.name,+ });+}diff --git a/web/src/ee/features/admin-api/public/projects/createProject.ts b/web/src/ee/features/admin-api/public/projects/createProject.tsnew file mode 100644index 0000000000..1e6413a9d2--- /dev/null+++ b/web/src/ee/features/admin-api/public/projects/createProject.ts@@ -0,0 +1,86 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger } from "@langfuse/shared/src/server";+import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";+import { projectRetentionSchema } from "@/src/features/auth/lib/projectRetentionSchema";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { type ApiAccessScope } from "@langfuse/shared/src/server";++export async function handleCreateProject(+ req: NextApiRequest,+ res: NextApiResponse,+ scope: ApiAccessScope,+) {+ try {+ const { name, retention } = req.body;++ // Validate project name+ try {+ projectNameSchema.parse({ name });+ } catch (error) {+ return res.status(400).json({+ message: "Invalid project name. Should be between 3 and 60 characters.",+ });+ }++ // Validate retention days if provided+ if (retention !== undefined) {+ try {+ projectRetentionSchema.parse({ retention });+ } catch (error) {+ return res.status(400).json({+ message: "Invalid retention value. Must be 0 or at least 7 days.",+ });+ }++ // If retention is non-zero, check for data-retention entitlement+ if (retention > 0) {+ const hasDataRetentionEntitlement = hasEntitlementBasedOnPlan({+ entitlement: "data-retention",+ plan: scope.plan,+ });++ if (!hasDataRetentionEntitlement) {+ return res.status(403).json({+ message:+ "The data-retention entitlement is required to set a non-zero retention period.",+ });+ }+ }+ }++ // Check if project with this name already exists in the organization+ const existingProject = await prisma.project.findFirst({+ where: {+ name,+ orgId: scope.orgId,+ },+ });++ if (existingProject) {+ return res.status(409).json({+ message: "A project with this name already exists in your organization",+ });+ }++ // Create the project+ const project = await prisma.project.create({+ data: {+ name,+ orgId: scope.orgId,+ retentionDays: retention,+ },+ });++ return res.status(201).json({+ id: project.id,+ name: project.name,+ ...(project.retentionDays // Do not add if null or 0+ ? { retentionDays: project.retentionDays }+ : {}),+ });+ } catch (error) {+ logger.error("Failed to create project", error);+ return res.status(500).json({ message: "Internal server error" });+ }+}diff --git a/web/src/ee/features/admin-api/public/projects/projectById/apiKeys/apiKeyById.ts b/web/src/ee/features/admin-api/public/projects/projectById/apiKeys/apiKeyById.tsnew file mode 100644index 0000000000..97a30bba51--- /dev/null+++ b/web/src/ee/features/admin-api/public/projects/projectById/apiKeys/apiKeyById.ts@@ -0,0 +1,69 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { z } from "zod";++export const validateQueryParams = (+ query: unknown,+): { projectId: string; apiKeyId: string } | null => {+ const inputQuerySchema = z.object({+ projectId: z.string(),+ apiKeyId: z.string(),+ });+ const validation = inputQuerySchema.safeParse(query);+ if (!validation.success) {+ return null;+ }+ return validation.data;+};++export async function handleDeleteApiKey(+ req: NextApiRequest,+ res: NextApiResponse,+ projectId: string,+ apiKeyId: string,+ orgId: string,+) {+ // Check if API key exists and belongs to the project+ const apiKey = await prisma.apiKey.findFirst({+ where: {+ id: apiKeyId,+ projectId,+ scope: "PROJECT",+ },+ });++ if (!apiKey) {+ return res.status(404).json({ message: "API key not found" });+ }++ // Delete the API key+ const deleted = await new ApiAuthService(prisma, redis).deleteApiKey(+ apiKeyId,+ projectId,+ "PROJECT",+ );++ if (!deleted) {+ return res.status(500).json({ message: "Failed to delete API key" });+ }++ // Log the API key deletion+ await auditLog({+ resourceType: "apiKey",+ resourceId: apiKeyId,+ action: "delete",+ orgId: orgId,+ projectId: projectId,+ orgRole: "ADMIN",+ apiKeyId: "ORG_KEY",+ });++ logger.info(+ `Deleted API key ${apiKeyId} for project ${projectId} via public API`,+ );++ return res.status(200).json({ success: true });+}diff --git a/web/src/ee/features/admin-api/public/projects/projectById/apiKeys/index.ts b/web/src/ee/features/admin-api/public/projects/projectById/apiKeys/index.tsnew file mode 100644index 0000000000..a0ccdf3f19--- /dev/null+++ b/web/src/ee/features/admin-api/public/projects/projectById/apiKeys/index.ts@@ -0,0 +1,92 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger } from "@langfuse/shared/src/server";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { z } from "zod";+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";++export const validateQueryAndExtractId = (query: unknown): string | null => {+ const inputQuerySchema = z.object({+ projectId: z.string(),+ });+ const validation = inputQuerySchema.safeParse(query);+ if (!validation.success) {+ return null;+ }+ return validation.data.projectId;+};++export async function handleGetApiKeys(+ req: NextApiRequest,+ res: NextApiResponse,+ projectId: string,+) {+ const apiKeys = await prisma.apiKey.findMany({+ where: {+ projectId,+ scope: "PROJECT",+ },+ select: {+ id: true,+ createdAt: true,+ expiresAt: true,+ lastUsedAt: true,+ note: true,+ publicKey: true,+ displaySecretKey: true,+ },+ orderBy: {+ createdAt: "asc",+ },+ });++ return res.status(200).json({ apiKeys });+}++export async function handleCreateApiKey(+ req: NextApiRequest,+ res: NextApiResponse,+ projectId: string,+ orgId: string,+) {+ // Validate the request body+ const createApiKeySchema = z.object({+ note: z.string().optional(),+ });++ const validationResult = createApiKeySchema.safeParse(req.body);++ if (!validationResult.success) {+ return res.status(400).json({+ message: "Invalid request body",+ details: validationResult.error.format(),+ });+ }++ const { note } = validationResult.data;++ // Create the API key+ const apiKeyMeta = await createAndAddApiKeysToDb({+ prisma,+ entityId: projectId,+ note,+ scope: "PROJECT",+ });++ // Log the API key creation+ await auditLog({+ resourceType: "apiKey",+ resourceId: apiKeyMeta.id,+ action: "create",+ orgId: orgId,+ projectId: projectId,+ orgRole: "ADMIN",+ apiKeyId: "ORG_KEY",+ });++ logger.info(+ `Created API key ${apiKeyMeta.id} for project ${projectId} via public API`,+ );++ return res.status(201).json(apiKeyMeta);+}diff --git a/web/src/ee/features/admin-api/public/projects/projectById/index.ts b/web/src/ee/features/admin-api/public/projects/projectById/index.tsnew file mode 100644index 0000000000..80aebf4989--- /dev/null+++ b/web/src/ee/features/admin-api/public/projects/projectById/index.ts@@ -0,0 +1,145 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import {+ logger,+ redis,+ QueueJobs,+ ProjectDeleteQueue,+ type ApiAccessScope,+} from "@langfuse/shared/src/server";+import { randomUUID } from "crypto";+import { projectRetentionSchema } from "@/src/features/auth/lib/projectRetentionSchema";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";++export async function handleUpdateProject(+ req: NextApiRequest,+ res: NextApiResponse,+ projectId: string,+ scope: ApiAccessScope,+) {+ try {+ const { name, retention } = req.body;++ // Validate project name+ try {+ projectNameSchema.parse({ name });+ } catch (error) {+ return res.status(400).json({+ message: "Invalid project name. Should be between 3 and 60 characters.",+ });+ }++ // Validate retention days using the schema+ try {+ projectRetentionSchema.parse({ retention });+ } catch (error) {+ return res.status(400).json({+ message: "Invalid retention value. Must be 0 or at least 7 days.",+ });+ }++ // If retention is non-zero, check for data-retention entitlement+ if (retention > 0) {+ const hasDataRetentionEntitlement = hasEntitlementBasedOnPlan({+ entitlement: "data-retention",+ plan: scope.plan,+ });++ if (!hasDataRetentionEntitlement) {+ return res.status(403).json({+ message:+ "The data-retention entitlement is required to set a non-zero retention period.",+ });+ }+ }++ // Update the project with the new retention setting+ const updatedProject = await prisma.project.update({+ where: {+ id: projectId,+ orgId: scope.orgId,+ },+ data: {+ name,+ retentionDays: retention,+ },+ select: {+ id: true,+ name: true,+ retentionDays: true,+ },+ });++ return res.status(200).json({+ id: updatedProject.id,+ name: updatedProject.name,+ ...(updatedProject.retentionDays // Do not add if null or 0+ ? { retentionDays: updatedProject.retentionDays }+ : {}),+ });+ } catch (error) {+ logger.error("Failed to update project", error);+ return res.status(500).json({ message: "Internal server error" });+ }+}++export async function handleDeleteProject(+ req: NextApiRequest,+ res: NextApiResponse,+ projectId: string,+ scope: ApiAccessScope,+) {+ try {+ // API keys need to be deleted from cache. Otherwise, they will still be valid.+ await new ApiAuthService(prisma, redis).invalidateProjectApiKeys(projectId);++ // Delete API keys from DB+ await prisma.apiKey.deleteMany({+ where: {+ projectId: projectId,+ scope: "PROJECT",+ },+ });++ // Mark project as deleted+ await prisma.project.update({+ where: {+ id: projectId,+ orgId: scope.orgId,+ },+ data: {+ deletedAt: new Date(),+ },+ });++ // Queue project deletion job+ const projectDeleteQueue = ProjectDeleteQueue.getInstance();+ if (!projectDeleteQueue) {+ logger.error("ProjectDeleteQueue is not available");+ return res.status(500).json({+ message: "Internal server error",+ });+ }++ await projectDeleteQueue.add(QueueJobs.ProjectDelete, {+ timestamp: new Date(),+ id: randomUUID(),+ payload: {+ projectId: projectId,+ orgId: scope.orgId,+ },+ name: QueueJobs.ProjectDelete,+ });++ return res.status(202).json({+ success: true,+ message:+ "Project deletion has been initiated and is being processed asynchronously",+ });+ } catch (error) {+ logger.error("Failed to delete project", error);+ return res.status(500).json({ message: "Internal server error" });+ }+}diff --git a/web/src/ee/features/admin-api/public/projects/projectById/memberships/index.ts b/web/src/ee/features/admin-api/public/projects/projectById/memberships/index.tsnew file mode 100644index 0000000000..c817058531--- /dev/null+++ b/web/src/ee/features/admin-api/public/projects/projectById/memberships/index.ts@@ -0,0 +1,111 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { Role } from "@langfuse/shared";+import { z } from "zod";++// Schema for request body validation+const MembershipSchema = z.object({+ userId: z.string(),+ role: z.nativeEnum(Role),+});++// GET - Retrieve all project memberships+export async function handleGetMemberships(+ req: NextApiRequest,+ res: NextApiResponse,+ projectId: string,+ orgId: string,+) {+ const memberships = await prisma.projectMembership.findMany({+ where: {+ projectId,+ organizationMembership: {+ orgId,+ },+ },+ include: {+ user: {+ select: {+ id: true,+ email: true,+ name: true,+ },+ },+ },+ });++ return res.status(200).json({+ memberships: memberships.map((membership) => ({+ userId: membership.userId,+ role: membership.role,+ email: membership.user.email,+ name: membership.user.name,+ })),+ });+}++// PUT - Update or create a project membership+export async function handleUpdateMembership(+ req: NextApiRequest,+ res: NextApiResponse,+ projectId: string,+ orgId: string,+) {+ const validatedBody = MembershipSchema.safeParse(req.body);+ if (!validatedBody.success) {+ return res.status(400).json({+ error: "Invalid request body",+ details: validatedBody.error.errors,+ });+ }++ // Check if user exists and is a member of the organization+ const orgMembership = await prisma.organizationMembership.findUnique({+ where: {+ orgId_userId: {+ userId: validatedBody.data.userId,+ orgId: orgId,+ },+ },+ include: {+ user: {+ select: {+ email: true,+ name: true,+ },+ },+ },+ });++ if (!orgMembership) {+ return res.status(404).json({+ error: "User is not a member of this organization",+ });+ }++ // Upsert the project membership+ const membership = await prisma.projectMembership.upsert({+ where: {+ projectId_userId: {+ userId: validatedBody.data.userId,+ projectId: projectId,+ },+ },+ update: {+ role: validatedBody.data.role,+ },+ create: {+ userId: validatedBody.data.userId,+ projectId: projectId,+ role: validatedBody.data.role,+ orgMembershipId: orgMembership.id,+ },+ });++ return res.status(200).json({+ userId: membership.userId,+ role: membership.role,+ email: orgMembership.user.email,+ name: orgMembership.user.name,+ });+}diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.tsindex 5d19e2e0f6..7f58fd326e 100644--- a/web/src/features/entitlements/constants/entitlements.ts+++ b/web/src/features/entitlements/constants/entitlements.ts@@ -19,6 +19,7 @@ const entitlements = ["data-retention","prompt-protected-labels","custom-dashboards",+ "admin-api",] as const;export type Entitlement = (typeof entitlements)[number];@@ -97,6 +98,7 @@ export const entitlementAccess: Record<"cloud-multi-tenant-sso","integration-blobstorage","prompt-protected-labels",+ "admin-api",],entitlementLimits: {"annotation-queue-count": false,@@ -115,6 +117,7 @@ export const entitlementAccess: Record<"cloud-multi-tenant-sso","integration-blobstorage","prompt-protected-labels",+ "admin-api",],entitlementLimits: {"annotation-queue-count": false,@@ -167,6 +170,7 @@ export const entitlementAccess: Record<"audit-logs","data-retention","prompt-protected-labels",+ "admin-api",],entitlementLimits: {"annotation-queue-count": false,diff --git a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].ts b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].tsindex a08d190a5d..5295413ed1 100644--- a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].ts+++ b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].ts@@ -1,24 +1,13 @@import { type NextApiRequest, type NextApiResponse } from "next";-import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";import { AdminApiAuthService } from "@/src/features/admin-api/server/adminApiAuth";-import { auditLog } from "@/src/features/audit-logs/auditLog";-import { z } from "zod";-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";--const validateQueryParams = (- query: unknown,-): { organizationId: string; apiKeyId: string } | null => {- const inputQuerySchema = z.object({- organizationId: z.string(),- apiKeyId: z.string(),- });- const validation = inputQuerySchema.safeParse(query);- if (!validation.success) {- return null;- }- return validation.data;-};+import {+ validateQueryParams,+ handleDeleteApiKey,+} from "@/src/ee/features/admin-api/organizations/apiKeys/apiKeyById";+import { prisma } from "@langfuse/shared/src/db";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { getSelfHostedInstancePlanServerSide } from "@/src/features/entitlements/server/getPlan";export default async function handler(req: NextApiRequest,@@ -35,6 +24,17 @@ export default async function handler(return;}+ if (+ !hasEntitlementBasedOnPlan({+ plan: getSelfHostedInstancePlanServerSide(),+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }+const params = validateQueryParams(req.query);if (!params) {return res.status(400).json({ error: "Invalid request parameters" });@@ -54,7 +54,7 @@ export default async function handler(// Handle different HTTP methodsswitch (req.method) {case "DELETE":- return await handleDelete(req, res, organizationId, apiKeyId);+ return await handleDeleteApiKey(req, res, organizationId, apiKeyId);default:res.status(405).json({ error: "Method Not Allowed" });return;@@ -64,50 +64,3 @@ export default async function handler(res.status(500).json({ error: "Internal server error" });}}--async function handleDelete(- req: NextApiRequest,- res: NextApiResponse,- organizationId: string,- apiKeyId: string,-) {- // Check if API key exists and belongs to the organization- const apiKey = await prisma.apiKey.findFirst({- where: {- id: apiKeyId,- orgId: organizationId,- scope: "ORGANIZATION",- },- });-- if (!apiKey) {- return res.status(404).json({ error: "API key not found" });- }-- // Delete the API key- const deleted = await new ApiAuthService(prisma, redis).deleteApiKey(- apiKeyId,- organizationId,- "ORGANIZATION",- );-- if (!deleted) {- return res.status(500).json({ error: "Failed to delete API key" });- }-- // Log the API key deletion- await auditLog({- resourceType: "apiKey",- resourceId: apiKeyId,- action: "delete",- orgId: organizationId,- orgRole: "ADMIN",- apiKeyId: "ADMIN_KEY",- });-- logger.info(- `Deleted API key ${apiKeyId} for organization ${organizationId} via admin API`,- );-- return res.status(200).json({ success: true });-}diff --git a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.tsindex 07c7274d44..49f510d3f7 100644--- a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts+++ b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts@@ -1,21 +1,14 @@import { type NextApiRequest, type NextApiResponse } from "next";-import { prisma } from "@langfuse/shared/src/db";import { logger } from "@langfuse/shared/src/server";import { AdminApiAuthService } from "@/src/features/admin-api/server/adminApiAuth";-import { auditLog } from "@/src/features/audit-logs/auditLog";-import { z } from "zod";-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";--const validateQueryAndExtractId = (query: unknown): string | null => {- const inputQuerySchema = z.object({- organizationId: z.string(),- });- const validation = inputQuerySchema.safeParse(query);- if (!validation.success) {- return null;- }- return validation.data.organizationId;-};+import {+ validateQueryAndExtractId,+ handleGetApiKeys,+ handleCreateApiKey,+} from "@/src/ee/features/admin-api/organizations/apiKeys";+import { prisma } from "@langfuse/shared/src/db";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { getSelfHostedInstancePlanServerSide } from "@/src/features/entitlements/server/getPlan";export default async function handler(req: NextApiRequest,@@ -32,6 +25,17 @@ export default async function handler(return;}+ if (+ !hasEntitlementBasedOnPlan({+ plan: getSelfHostedInstancePlanServerSide(),+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }+const organizationId = validateQueryAndExtractId(req.query);if (!organizationId) {return res.status(400).json({ error: "Invalid organization ID" });@@ -49,9 +53,9 @@ export default async function handler(// Handle different HTTP methodsswitch (req.method) {case "GET":- return await handleGet(req, res, organizationId);+ return await handleGetApiKeys(req, res, organizationId);case "POST":- return await handlePost(req, res, organizationId);+ return await handleCreateApiKey(req, res, organizationId);default:res.status(405).json({ error: "Method Not Allowed" });return;@@ -61,76 +65,3 @@ export default async function handler(res.status(500).json({ error: "Internal server error" });}}--async function handleGet(- req: NextApiRequest,- res: NextApiResponse,- organizationId: string,-) {- const apiKeys = await prisma.apiKey.findMany({- where: {- orgId: organizationId,- scope: "ORGANIZATION",- },- select: {- id: true,- createdAt: true,- expiresAt: true,- lastUsedAt: true,- note: true,- publicKey: true,- displaySecretKey: true,- },- orderBy: {- createdAt: "asc",- },- });-- return res.status(200).json({ apiKeys });-}--async function handlePost(- req: NextApiRequest,- res: NextApiResponse,- organizationId: string,-) {- // Validate the request body- const createApiKeySchema = z.object({- note: z.string().optional(),- });-- const validationResult = createApiKeySchema.safeParse(req.body);-- if (!validationResult.success) {- return res.status(400).json({- error: "Invalid request body",- details: validationResult.error.format(),- });- }-- const { note } = validationResult.data;-- // Create the API key- const apiKeyMeta = await createAndAddApiKeysToDb({- prisma,- entityId: organizationId,- note,- scope: "ORGANIZATION",- });-- // Log the API key creation- await auditLog({- resourceType: "apiKey",- resourceId: apiKeyMeta.id,- action: "create",- orgId: organizationId,- orgRole: "ADMIN",- apiKeyId: "ADMIN_KEY",- });-- logger.info(- `Created API key ${apiKeyMeta.id} for organization ${organizationId} via admin API`,- );-- return res.status(201).json(apiKeyMeta);-}diff --git a/web/src/pages/api/admin/organizations/[organizationId]/index.ts b/web/src/pages/api/admin/organizations/[organizationId]/index.tsindex 56ff2a2649..4cc0d58efd 100644--- a/web/src/pages/api/admin/organizations/[organizationId]/index.ts+++ b/web/src/pages/api/admin/organizations/[organizationId]/index.ts@@ -1,21 +1,13 @@import { type NextApiRequest, type NextApiResponse } from "next";-import { prisma } from "@langfuse/shared/src/db";import { logger } from "@langfuse/shared/src/server";import { AdminApiAuthService } from "@/src/features/admin-api/server/adminApiAuth";-import { organizationNameSchema } from "@/src/features/organizations/utils/organizationNameSchema";-import { auditLog } from "@/src/features/audit-logs/auditLog";-import { z } from "zod";--const validateQueryAndExtractId = (query: unknown): string | null => {- const inputQuerySchema = z.object({- organizationId: z.string(),- });- const validation = inputQuerySchema.safeParse(query);- if (!validation.success) {- return null;- }- return validation.data.organizationId;-};+import {+ handleGetOrganizationById,+ handleUpdateOrganization,+ handleDeleteOrganization,+} from "@/src/ee/features/admin-api/organizations/organizationById";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { getSelfHostedInstancePlanServerSide } from "@/src/features/entitlements/server/getPlan";export default async function handler(req: NextApiRequest,@@ -27,14 +19,25 @@ export default async function handler(return;}+ if (+ !hasEntitlementBasedOnPlan({+ plan: getSelfHostedInstancePlanServerSide(),+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }+// Handle different HTTP methodsswitch (req.method) {case "GET":- return await handleGet(req, res);+ return await handleGetOrganizationById(req, res);case "PUT":- return await handlePut(req, res);+ return await handleUpdateOrganization(req, res);case "DELETE":- return await handleDelete(req, res);+ return await handleDeleteOrganization(req, res);default:res.status(405).json({ error: "Method Not Allowed" });return;@@ -44,127 +47,3 @@ export default async function handler(res.status(500).json({ error: "Internal server error" });}}--async function handleGet(req: NextApiRequest, res: NextApiResponse) {- const organizationId = validateQueryAndExtractId(req.query);- if (!organizationId) {- return res.status(400).json({ error: "Invalid organization ID" });- }-- const organization = await prisma.organization.findUnique({- where: { id: organizationId },- select: {- id: true,- name: true,- createdAt: true,- },- });-- if (!organization) {- return res.status(404).json({ error: "Organization not found" });- }-- return res.status(200).json(organization);-}--async function handlePut(req: NextApiRequest, res: NextApiResponse) {- const organizationId = validateQueryAndExtractId(req.query);- if (!organizationId) {- return res.status(400).json({ error: "Invalid organization ID" });- }-- const validationResult = organizationNameSchema.safeParse(req.body);-- if (!validationResult.success) {- return res.status(400).json({- error: "Invalid request body",- details: validationResult.error.format(),- });- }-- const { name } = validationResult.data;-- // Check if organization exists- const existingOrg = await prisma.organization.findUnique({- where: { id: organizationId },- });-- if (!existingOrg) {- return res.status(404).json({ error: "Organization not found" });- }-- // Update the organization- const updatedOrganization = await prisma.organization.update({- where: { id: organizationId },- data: { name },- });-- // Log the update- await auditLog({- resourceType: "organization",- resourceId: organizationId,- action: "update",- orgId: organizationId,- orgRole: "ADMIN",- before: existingOrg,- after: updatedOrganization,- apiKeyId: "ADMIN_KEY",- });-- logger.info(`Updated organization ${organizationId} via admin API`);-- return res.status(200).json({- id: updatedOrganization.id,- name: updatedOrganization.name,- createdAt: updatedOrganization.createdAt,- });-}--async function handleDelete(req: NextApiRequest, res: NextApiResponse) {- const organizationId = validateQueryAndExtractId(req.query);- if (!organizationId) {- return res.status(400).json({ error: "Invalid organization ID" });- }-- // Check if organization exists- const existingOrg = await prisma.organization.findUnique({- where: { id: organizationId },- });-- if (!existingOrg) {- return res.status(404).json({ error: "Organization not found" });- }-- // Check if organization has any projects- const projectCount = await prisma.project.count({- where: { orgId: organizationId },- });-- if (projectCount > 0) {- return res.status(400).json({- error: "Cannot delete organization with existing projects",- message:- "Please delete or transfer all projects before deleting the organization.",- });- }-- // Delete the organization- const deletedOrganization = await prisma.organization.delete({- where: { id: organizationId },- });-- // Log the deletion- await auditLog({- resourceType: "organization",- resourceId: organizationId,- action: "delete",- orgId: organizationId,- orgRole: "ADMIN",- before: deletedOrganization,- apiKeyId: "ADMIN_KEY",- });-- logger.info(`Deleted organization ${organizationId} via admin API`);-- return res.status(200).json({ success: true });-}diff --git a/web/src/pages/api/admin/organizations/index.ts b/web/src/pages/api/admin/organizations/index.tsindex 8273f5751e..a299661a45 100644--- a/web/src/pages/api/admin/organizations/index.ts+++ b/web/src/pages/api/admin/organizations/index.ts@@ -1,9 +1,12 @@import { type NextApiRequest, type NextApiResponse } from "next";-import { prisma } from "@langfuse/shared/src/db";import { logger } from "@langfuse/shared/src/server";import { AdminApiAuthService } from "@/src/features/admin-api/server/adminApiAuth";-import { organizationNameSchema } from "@/src/features/organizations/utils/organizationNameSchema";-import { auditLog } from "@/src/features/audit-logs/auditLog";+import {+ handleGetOrganizations,+ handleCreateOrganization,+} from "@/src/ee/features/admin-api/organizations";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { getSelfHostedInstancePlanServerSide } from "@/src/features/entitlements/server/getPlan";export default async function handler(req: NextApiRequest,@@ -20,58 +23,25 @@ export default async function handler(return;}+ if (+ !hasEntitlementBasedOnPlan({+ plan: getSelfHostedInstancePlanServerSide(),+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }+// For GET requests, return all organizationsif (req.method === "GET") {- const organizations = await prisma.organization.findMany({- select: {- id: true,- name: true,- createdAt: true,- },- });- return res.status(200).json({ organizations });+ return await handleGetOrganizations(req, res);}// For POST requests, create a new organizationif (req.method === "POST") {- // Validate the request body using the organizationNameSchema- const validationResult = organizationNameSchema.safeParse(req.body);-- if (!validationResult.success) {- res.status(400).json({- error: "Invalid request body",- details: validationResult.error.format(),- });- return;- }-- const { name } = validationResult.data;-- // Create the organization in the database- const organization = await prisma.organization.create({- data: {- name,- },- });-- // Log the organization creation- await auditLog({- resourceType: "organization",- resourceId: organization.id,- action: "create",- orgId: organization.id,- orgRole: "ADMIN",- after: organization,- apiKeyId: "ADMIN_KEY",- });-- logger.info(`Created organization ${organization.id} via admin API`);-- return res.status(201).json({- id: organization.id,- name: organization.name,- createdAt: organization.createdAt,- });+ return await handleCreateOrganization(req, res);}} catch (e) {logger.error("Failed to process organization request", e);diff --git a/web/src/pages/api/public/organizations/memberships/index.ts b/web/src/pages/api/public/organizations/memberships/index.tsindex df8c4fe20b..f11213da00 100644--- a/web/src/pages/api/public/organizations/memberships/index.ts+++ b/web/src/pages/api/public/organizations/memberships/index.ts@@ -2,16 +2,13 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { prisma } from "@langfuse/shared/src/db";import { logger, redis } from "@langfuse/shared/src/server";-import { Role } from "@langfuse/shared";-import { z } from "zod";+import {+ handleGetMemberships,+ handleUpdateMembership,+} from "@/src/ee/features/admin-api/public/organizations/memberships";import { type NextApiRequest, type NextApiResponse } from "next";--// Schema for request body validation-const MembershipSchema = z.object({- userId: z.string(),- role: z.nativeEnum(Role),-});+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";export default async function handler(req: NextApiRequest,@@ -51,13 +48,24 @@ export default async function handler(});}+ if (+ !hasEntitlementBasedOnPlan({+ plan: authCheck.scope.plan,+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }+// Route to the appropriate handler based on HTTP methodtry {switch (req.method) {case "GET":- return handleGet(req, res, authCheck.scope.orgId);+ return handleGetMemberships(req, res, authCheck.scope.orgId);case "PUT":- return handlePut(req, res, authCheck.scope.orgId);+ return handleUpdateMembership(req, res, authCheck.scope.orgId);default:// This should never happen due to the check at the beginningreturn res.status(405).json({@@ -74,87 +82,3 @@ export default async function handler(});}}--// GET - Retrieve all organization memberships-async function handleGet(- req: NextApiRequest,- res: NextApiResponse,- orgId: string,-) {- const memberships = await prisma.organizationMembership.findMany({- where: {- orgId: orgId,- },- include: {- user: {- select: {- id: true,- email: true,- name: true,- },- },- },- });-- return res.status(200).json({- memberships: memberships.map((membership) => ({- userId: membership.userId,- role: membership.role,- email: membership.user.email,- name: membership.user.name,- })),- });-}--// PUT - Update or create an organization membership-async function handlePut(- req: NextApiRequest,- res: NextApiResponse,- orgId: string,-) {- const validatedBody = MembershipSchema.safeParse(req.body);- if (!validatedBody.success) {- return res.status(400).json({- error: "Invalid request body",- details: validatedBody.error.errors,- });- }-- // Check if user exists- const user = await prisma.user.findUnique({- where: {- id: validatedBody.data.userId,- },- });-- if (!user) {- return res.status(404).json({- error: "User not found",- });- }-- // Upsert the membership- const membership = await prisma.organizationMembership.upsert({- where: {- orgId_userId: {- orgId,- userId: validatedBody.data.userId,- },- },- update: {- role: validatedBody.data.role,- },- create: {- orgId,- userId: validatedBody.data.userId,- role: validatedBody.data.role,- },- });-- return res.status(200).json({- userId: membership.userId,- role: membership.role,- email: user.email,- name: user.name,- });-}diff --git a/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts b/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].tsindex 0597f4a5cc..87fb9ace24 100644--- a/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts+++ b/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts@@ -2,23 +2,12 @@ import { type NextApiRequest, type NextApiResponse } from "next";import { prisma } from "@langfuse/shared/src/db";import { logger, redis } from "@langfuse/shared/src/server";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";-import { auditLog } from "@/src/features/audit-logs/auditLog";-import { z } from "zod";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";--const validateQueryParams = (- query: unknown,-): { projectId: string; apiKeyId: string } | null => {- const inputQuerySchema = z.object({- projectId: z.string(),- apiKeyId: z.string(),- });- const validation = inputQuerySchema.safeParse(query);- if (!validation.success) {- return null;- }- return validation.data;-};+import {+ validateQueryParams,+ handleDeleteApiKey+} from "@/src/ee/features/admin-api/public/projects/projectById/apiKeys/apiKeyById";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";export default async function handler(req: NextApiRequest,@@ -55,6 +44,17 @@ export default async function handler(}// END CHECK AUTH+ if (+ !hasEntitlementBasedOnPlan({+ plan: authCheck.scope.plan,+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }+const params = validateQueryParams(req.query);if (!params) {return res.status(400).json({ message: "Invalid request parameters" });@@ -79,7 +79,7 @@ export default async function handler(// Handle different HTTP methodsswitch (req.method) {case "DELETE":- return await handleDelete(+ return await handleDeleteApiKey(req,res,projectId,@@ -95,52 +95,3 @@ export default async function handler(res.status(500).json({ message: "Internal server error" });}}--async function handleDelete(- req: NextApiRequest,- res: NextApiResponse,- projectId: string,- apiKeyId: string,- orgId: string,-) {- // Check if API key exists and belongs to the project- const apiKey = await prisma.apiKey.findFirst({- where: {- id: apiKeyId,- projectId,- scope: "PROJECT",- },- });-- if (!apiKey) {- return res.status(404).json({ message: "API key not found" });- }-- // Delete the API key- const deleted = await new ApiAuthService(prisma, redis).deleteApiKey(- apiKeyId,- projectId,- "PROJECT",- );-- if (!deleted) {- return res.status(500).json({ message: "Failed to delete API key" });- }-- // Log the API key deletion- await auditLog({- resourceType: "apiKey",- resourceId: apiKeyId,- action: "delete",- orgId: orgId,- projectId: projectId,- orgRole: "ADMIN",- apiKeyId: "ORG_KEY",- });-- logger.info(- `Deleted API key ${apiKeyId} for project ${projectId} via public API`,- );-- return res.status(200).json({ success: true });-}diff --git a/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts b/web/src/pages/api/public/projects/[projectId]/apiKeys/index.tsindex ce43228424..bdfe6a7b3f 100644--- a/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts+++ b/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts@@ -2,21 +2,13 @@ import { type NextApiRequest, type NextApiResponse } from "next";import { prisma } from "@langfuse/shared/src/db";import { logger, redis } from "@langfuse/shared/src/server";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";-import { auditLog } from "@/src/features/audit-logs/auditLog";-import { z } from "zod";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";--const validateQueryAndExtractId = (query: unknown): string | null => {- const inputQuerySchema = z.object({- projectId: z.string(),- });- const validation = inputQuerySchema.safeParse(query);- if (!validation.success) {- return null;- }- return validation.data.projectId;-};+import {+ validateQueryAndExtractId,+ handleGetApiKeys,+ handleCreateApiKey+} from "@/src/ee/features/admin-api/public/projects/projectById/apiKeys";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";export default async function handler(req: NextApiRequest,@@ -53,6 +45,17 @@ export default async function handler(}// END CHECK AUTH+ if (+ !hasEntitlementBasedOnPlan({+ plan: authCheck.scope.plan,+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }+const projectId = validateQueryAndExtractId(req.query);if (!projectId) {return res.status(400).json({ message: "Invalid project ID" });@@ -75,9 +78,9 @@ export default async function handler(// Handle different HTTP methodsswitch (req.method) {case "GET":- return await handleGet(req, res, projectId);+ return await handleGetApiKeys(req, res, projectId);case "POST":- return await handlePost(req, res, projectId, authCheck.scope.orgId);+ return await handleCreateApiKey(req, res, projectId, authCheck.scope.orgId);default:res.status(405).json({ message: "Method Not Allowed" });return;@@ -87,78 +90,3 @@ export default async function handler(res.status(500).json({ message: "Internal server error" });}}--async function handleGet(- req: NextApiRequest,- res: NextApiResponse,- projectId: string,-) {- const apiKeys = await prisma.apiKey.findMany({- where: {- projectId,- scope: "PROJECT",- },- select: {- id: true,- createdAt: true,- expiresAt: true,- lastUsedAt: true,- note: true,- publicKey: true,- displaySecretKey: true,- },- orderBy: {- createdAt: "asc",- },- });-- return res.status(200).json({ apiKeys });-}--async function handlePost(- req: NextApiRequest,- res: NextApiResponse,- projectId: string,- orgId: string,-) {- // Validate the request body- const createApiKeySchema = z.object({- note: z.string().optional(),- });-- const validationResult = createApiKeySchema.safeParse(req.body);-- if (!validationResult.success) {- return res.status(400).json({- message: "Invalid request body",- details: validationResult.error.format(),- });- }-- const { note } = validationResult.data;-- // Create the API key- const apiKeyMeta = await createAndAddApiKeysToDb({- prisma,- entityId: projectId,- note,- scope: "PROJECT",- });-- // Log the API key creation- await auditLog({- resourceType: "apiKey",- resourceId: apiKeyMeta.id,- action: "create",- orgId: orgId,- projectId: projectId,- orgRole: "ADMIN",- apiKeyId: "ORG_KEY",- });-- logger.info(- `Created API key ${apiKeyMeta.id} for project ${projectId} via public API`,- );-- return res.status(201).json(apiKeyMeta);-}diff --git a/web/src/pages/api/public/projects/[projectId]/index.ts b/web/src/pages/api/public/projects/[projectId]/index.tsindex b502df74ee..ca5c34b272 100644--- a/web/src/pages/api/public/projects/[projectId]/index.ts+++ b/web/src/pages/api/public/projects/[projectId]/index.ts@@ -1,18 +1,13 @@import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";import {- logger,- redis,- QueueJobs,- ProjectDeleteQueue,- type ApiAccessScope,-} from "@langfuse/shared/src/server";-import { randomUUID } from "crypto";-import { projectRetentionSchema } from "@/src/features/auth/lib/projectRetentionSchema";+ handleUpdateProject,+ handleDeleteProject,+} from "@/src/ee/features/admin-api/public/projects/projectById";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";import { type NextApiRequest, type NextApiResponse } from "next";-import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";export default async function handler(req: NextApiRequest,@@ -56,6 +51,17 @@ export default async function handler(}// END CHECK AUTH+ if (+ !hasEntitlementBasedOnPlan({+ plan: authCheck.scope.plan,+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }+// Check if project exists and belongs to the organizationconst project = await prisma.project.findFirst({where: {@@ -72,141 +78,10 @@ export default async function handler(// Route to the appropriate handler based on HTTP methodif (req.method === "PUT") {- return handlePut(req, res, projectId, authCheck.scope);+ return handleUpdateProject(req, res, projectId, authCheck.scope);}if (req.method === "DELETE") {- return handleDelete(req, res, projectId, authCheck.scope);- }-}--async function handlePut(- req: NextApiRequest,- res: NextApiResponse,- projectId: string,- scope: ApiAccessScope,-) {- try {- const { name, retention } = req.body;-- // Validate project name- try {- projectNameSchema.parse({ name });- } catch (error) {- return res.status(400).json({- message: "Invalid project name. Should be between 3 and 60 characters.",- });- }-- // Validate retention days using the schema- try {- projectRetentionSchema.parse({ retention });- } catch (error) {- return res.status(400).json({- message: "Invalid retention value. Must be 0 or at least 7 days.",- });- }-- // If retention is non-zero, check for data-retention entitlement- if (retention > 0) {- const hasDataRetentionEntitlement = hasEntitlementBasedOnPlan({- entitlement: "data-retention",- plan: scope.plan,- });-- if (!hasDataRetentionEntitlement) {- return res.status(403).json({- message:- "The data-retention entitlement is required to set a non-zero retention period.",- });- }- }-- // Update the project with the new retention setting- const updatedProject = await prisma.project.update({- where: {- id: projectId,- orgId: scope.orgId,- },- data: {- name,- retentionDays: retention,- },- select: {- id: true,- name: true,- retentionDays: true,- },- });-- return res.status(200).json({- id: updatedProject.id,- name: updatedProject.name,- ...(updatedProject.retentionDays // Do not add if null or 0- ? { retentionDays: updatedProject.retentionDays }- : {}),- });- } catch (error) {- logger.error("Failed to update project", error);- return res.status(500).json({ message: "Internal server error" });- }-}--async function handleDelete(- req: NextApiRequest,- res: NextApiResponse,- projectId: string,- scope: ApiAccessScope,-) {- try {- // API keys need to be deleted from cache. Otherwise, they will still be valid.- await new ApiAuthService(prisma, redis).invalidateProjectApiKeys(projectId);-- // Delete API keys from DB- await prisma.apiKey.deleteMany({- where: {- projectId: projectId,- scope: "PROJECT",- },- });-- // Mark project as deleted- await prisma.project.update({- where: {- id: projectId,- orgId: scope.orgId,- },- data: {- deletedAt: new Date(),- },- });-- // Queue project deletion job- const projectDeleteQueue = ProjectDeleteQueue.getInstance();- if (!projectDeleteQueue) {- logger.error("ProjectDeleteQueue is not available");- return res.status(500).json({- message: "Internal server error",- });- }-- await projectDeleteQueue.add(QueueJobs.ProjectDelete, {- timestamp: new Date(),- id: randomUUID(),- payload: {- projectId: projectId,- orgId: scope.orgId,- },- name: QueueJobs.ProjectDelete,- });-- return res.status(202).json({- success: true,- message:- "Project deletion has been initiated and is being processed asynchronously",- });- } catch (error) {- logger.error("Failed to delete project", error);- return res.status(500).json({ message: "Internal server error" });+ return handleDeleteProject(req, res, projectId, authCheck.scope);}}diff --git a/web/src/pages/api/public/projects/[projectId]/memberships/index.ts b/web/src/pages/api/public/projects/[projectId]/memberships/index.tsindex 6083f1c7b9..c39af18dda 100644--- a/web/src/pages/api/public/projects/[projectId]/memberships/index.ts+++ b/web/src/pages/api/public/projects/[projectId]/memberships/index.ts@@ -2,18 +2,14 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { prisma } from "@langfuse/shared/src/db";import { logger, redis } from "@langfuse/shared/src/server";-import { Role } from "@langfuse/shared";-import { z } from "zod";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import {+ handleGetMemberships,+ handleUpdateMembership+} from "@/src/ee/features/admin-api/public/projects/projectById/memberships";import { type NextApiRequest, type NextApiResponse } from "next";-// Schema for request body validation-const MembershipSchema = z.object({- userId: z.string(),- role: z.nativeEnum(Role),-});-export default async function handler(req: NextApiRequest,res: NextApiResponse,@@ -71,6 +67,18 @@ export default async function handler(});}+ // Check for admin-api entitlement+ if (+ !hasEntitlementBasedOnPlan({+ plan: authCheck.scope.plan,+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }+// Verify the project belongs to the organizationconst project = await prisma.project.findFirst({where: {@@ -90,9 +98,9 @@ export default async function handler(try {switch (req.method) {case "GET":- return handleGet(req, res, projectId, authCheck.scope.orgId);+ return handleGetMemberships(req, res, projectId, authCheck.scope.orgId);case "PUT":- return handlePut(req, res, projectId, authCheck.scope.orgId);+ return handleUpdateMembership(req, res, projectId, authCheck.scope.orgId);default:// This should never happen due to the check at the beginningreturn res.status(405).json({@@ -109,104 +117,3 @@ export default async function handler(});}}--// GET - Retrieve all project memberships-async function handleGet(- req: NextApiRequest,- res: NextApiResponse,- projectId: string,- orgId: string,-) {- const memberships = await prisma.projectMembership.findMany({- where: {- projectId,- organizationMembership: {- orgId,- },- },- include: {- user: {- select: {- id: true,- email: true,- name: true,- },- },- },- });-- return res.status(200).json({- memberships: memberships.map((membership) => ({- userId: membership.userId,- role: membership.role,- email: membership.user.email,- name: membership.user.name,- })),- });-}--// PUT - Update or create a project membership-async function handlePut(- req: NextApiRequest,- res: NextApiResponse,- projectId: string,- orgId: string,-) {- const validatedBody = MembershipSchema.safeParse(req.body);- if (!validatedBody.success) {- return res.status(400).json({- error: "Invalid request body",- details: validatedBody.error.errors,- });- }-- // Check if user exists and is a member of the organization- const orgMembership = await prisma.organizationMembership.findUnique({- where: {- orgId_userId: {- userId: validatedBody.data.userId,- orgId: orgId,- },- },- include: {- user: {- select: {- email: true,- name: true,- },- },- },- });-- if (!orgMembership) {- return res.status(404).json({- error: "User is not a member of this organization",- });- }-- // Upsert the project membership- const membership = await prisma.projectMembership.upsert({- where: {- projectId_userId: {- userId: validatedBody.data.userId,- projectId: projectId,- },- },- update: {- role: validatedBody.data.role,- },- create: {- userId: validatedBody.data.userId,- projectId: projectId,- role: validatedBody.data.role,- orgMembershipId: orgMembership.id,- },- });-- return res.status(200).json({- userId: membership.userId,- role: membership.role,- email: orgMembership.user.email,- name: orgMembership.user.name,- });-}diff --git a/web/src/pages/api/public/projects/index.ts b/web/src/pages/api/public/projects/index.tsindex b60cac0b98..bf5809569c 100644--- a/web/src/pages/api/public/projects/index.ts+++ b/web/src/pages/api/public/projects/index.ts@@ -2,10 +2,9 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { prisma } from "@langfuse/shared/src/db";import { logger, redis } from "@langfuse/shared/src/server";+import { handleCreateProject } from "@/src/ee/features/admin-api/public/projects/createProject";import { type NextApiRequest, type NextApiResponse } from "next";-import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";-import { projectRetentionSchema } from "@/src/features/auth/lib/projectRetentionSchema";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";export default async function handler(@@ -85,79 +84,17 @@ export default async function handler(});}- try {- const { name, retention } = req.body;-- // Validate project name- try {- projectNameSchema.parse({ name });- } catch (error) {- return res.status(400).json({- message:- "Invalid project name. Should be between 3 and 60 characters.",- });- }-- // Validate retention days if provided- if (retention !== undefined) {- try {- projectRetentionSchema.parse({ retention });- } catch (error) {- return res.status(400).json({- message: "Invalid retention value. Must be 0 or at least 7 days.",- });- }-- // If retention is non-zero, check for data-retention entitlement- if (retention > 0) {- const hasDataRetentionEntitlement = hasEntitlementBasedOnPlan({- entitlement: "data-retention",- plan: authCheck.scope.plan,- });-- if (!hasDataRetentionEntitlement) {- return res.status(403).json({- message:- "The data-retention entitlement is required to set a non-zero retention period.",- });- }- }- }-- // Check if project with this name already exists in the organization- const existingProject = await prisma.project.findFirst({- where: {- name,- orgId: authCheck.scope.orgId,- },- });-- if (existingProject) {- return res.status(409).json({- message:- "A project with this name already exists in your organization",- });- }-- // Create the project- const project = await prisma.project.create({- data: {- name,- orgId: authCheck.scope.orgId,- retentionDays: retention,- },- });-- return res.status(201).json({- id: project.id,- name: project.name,- ...(project.retentionDays // Do not add if null or 0- ? { retentionDays: project.retentionDays }- : {}),+ if (+ !hasEntitlementBasedOnPlan({+ plan: authCheck.scope.plan,+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",});- } catch (error) {- logger.error("Failed to create project", error);- return res.status(500).json({ message: "Internal server error" });}++ return handleCreateProject(req, res, authCheck.scope);}}