Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

refactor: workflow API to require teamId for access control

Marc Seitz6ee3f2a427ef
diff --git a/app/(ee)/api/workflows/[workflowId]/executions/route.ts b/app/(ee)/api/workflows/[workflowId]/executions/route.ts
index ddd0a99f..4d3d1b5b 100644
--- a/app/(ee)/api/workflows/[workflowId]/executions/route.ts
+++ b/app/(ee)/api/workflows/[workflowId]/executions/route.ts
@@ -5,7 +5,7 @@ import { z } from "zod";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
-// GET /app/(ee)/api/workflows/[workflowId]/executions - List workflow executions
+// GET /app/(ee)/api/workflows/[workflowId]/executions?teamId=xxx - List workflow executions
export async function GET(
req: NextRequest,
{ params }: { params: { workflowId: string } },
@@ -18,6 +18,14 @@ export async function GET(
const { workflowId } = params;
const searchParams = req.nextUrl.searchParams;
+ const teamId = searchParams.get("teamId");
+
+ if (!teamId) {
+ return NextResponse.json(
+ { error: "teamId parameter is required" },
+ { status: 400 },
+ );
+ }
// Parse and validate pagination parameters
const rawPage = Number.parseInt(searchParams.get("page") || "1", 10);
@@ -30,44 +38,53 @@ export async function GET(
: Math.min(Math.max(rawLimit, 1), 100); // Min 1, Max 100
const skip = (page - 1) * limit;
- // Validate workflowId format
- const workflowIdValidation = z.string().cuid().safeParse(workflowId);
- if (!workflowIdValidation.success) {
+ // Validate IDs format
+ const idsValidation = z.object({
+ workflowId: z.string().cuid(),
+ teamId: z.string().cuid(),
+ }).safeParse({ workflowId, teamId });
+
+ if (!idsValidation.success) {
return NextResponse.json(
- { error: "Invalid workflowId format" },
+ { error: "Invalid ID format" },
{ status: 400 },
);
}
- // Check workflow exists and user has access
- const workflow = await prisma.workflow.findUnique({
- where: { id: workflowId },
- select: {
- id: true,
- teamId: true,
- team: {
- select: {
- users: { select: { userId: true } },
- },
+ const userId = (session.user as CustomUser).id;
+
+ // Check user is part of the team using userTeam table
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
},
},
});
- if (!workflow) {
+ if (!teamAccess) {
return NextResponse.json(
- { error: "Workflow not found" },
- { status: 404 },
+ { error: "Unauthorized to access this team" },
+ { status: 403 },
);
}
- const isUserPartOfTeam = workflow.team.users.some(
- (user) => user.userId === (session.user as CustomUser).id,
- );
+ // Check workflow exists and belongs to team
+ const workflow = await prisma.workflow.findUnique({
+ where: {
+ id: workflowId,
+ teamId: teamId,
+ },
+ select: {
+ id: true,
+ },
+ });
- if (!isUserPartOfTeam) {
+ if (!workflow) {
return NextResponse.json(
- { error: "Unauthorized to access this workflow" },
- { status: 403 },
+ { error: "Workflow not found" },
+ { status: 404 },
);
}
diff --git a/app/(ee)/api/workflows/[workflowId]/route.ts b/app/(ee)/api/workflows/[workflowId]/route.ts
index a13ceafd..93a9ff8a 100644
--- a/app/(ee)/api/workflows/[workflowId]/route.ts
+++ b/app/(ee)/api/workflows/[workflowId]/route.ts
@@ -11,7 +11,7 @@ import { z } from "zod";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
-// GET /app/(ee)/api/workflows/[workflowId] - Get single workflow with details
+// GET /app/(ee)/api/workflows/[workflowId]?teamId=xxx - Get single workflow with details
export async function GET(
req: NextRequest,
{ params }: { params: { workflowId: string } },
@@ -23,19 +23,54 @@ export async function GET(
}
const { workflowId } = params;
+ const searchParams = req.nextUrl.searchParams;
+ const teamId = searchParams.get("teamId");
- // Validate workflowId format
- const workflowIdValidation = z.string().cuid().safeParse(workflowId);
- if (!workflowIdValidation.success) {
+ if (!teamId) {
return NextResponse.json(
- { error: "Invalid workflowId format" },
+ { error: "teamId parameter is required" },
{ status: 400 },
);
}
+ // Validate IDs format
+ const idsValidation = z.object({
+ workflowId: z.string().cuid(),
+ teamId: z.string().cuid(),
+ }).safeParse({ workflowId, teamId });
+
+ if (!idsValidation.success) {
+ return NextResponse.json(
+ { error: "Invalid ID format" },
+ { status: 400 },
+ );
+ }
+
+ const userId = (session.user as CustomUser).id;
+
+ // Check user is part of the team using userTeam table
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
+ return NextResponse.json(
+ { error: "Unauthorized to access this team" },
+ { status: 403 },
+ );
+ }
+
// Fetch workflow
const workflow = await prisma.workflow.findUnique({
- where: { id: workflowId },
+ where: {
+ id: workflowId,
+ teamId: teamId, // Ensure workflow belongs to the team
+ },
include: {
entryLink: {
select: {
@@ -47,12 +82,6 @@ export async function GET(
steps: {
orderBy: { stepOrder: "asc" },
},
- team: {
- select: {
- id: true,
- users: { select: { userId: true } },
- },
- },
},
});
@@ -63,18 +92,6 @@ export async function GET(
);
}
- // Check user is part of the team
- const isUserPartOfTeam = workflow.team.users.some(
- (user) => user.userId === (session.user as CustomUser).id,
- );
-
- if (!isUserPartOfTeam) {
- return NextResponse.json(
- { error: "Unauthorized to access this workflow" },
- { status: 403 },
- );
- }
-
// Build entry URL
const entryUrl =
workflow.entryLink.domainSlug && workflow.entryLink.slug
@@ -97,7 +114,7 @@ export async function GET(
}
}
-// PATCH /app/(ee)/api/workflows/[workflowId] - Update workflow
+// PATCH /app/(ee)/api/workflows/[workflowId]?teamId=xxx - Update workflow
export async function PATCH(
req: NextRequest,
{ params }: { params: { workflowId: string } },
@@ -109,17 +126,50 @@ export async function PATCH(
}
const { workflowId } = params;
- const body = await req.json();
+ const searchParams = req.nextUrl.searchParams;
+ const teamId = searchParams.get("teamId");
+
+ if (!teamId) {
+ return NextResponse.json(
+ { error: "teamId parameter is required" },
+ { status: 400 },
+ );
+ }
+
+ // Validate IDs format
+ const idsValidation = z.object({
+ workflowId: z.string().cuid(),
+ teamId: z.string().cuid(),
+ }).safeParse({ workflowId, teamId });
- // Validate workflowId format
- const workflowIdValidation = z.string().cuid().safeParse(workflowId);
- if (!workflowIdValidation.success) {
+ if (!idsValidation.success) {
return NextResponse.json(
- { error: "Invalid workflowId format" },
+ { error: "Invalid ID format" },
{ status: 400 },
);
}
+ const userId = (session.user as CustomUser).id;
+
+ // Check user is part of the team using userTeam table
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
+ return NextResponse.json(
+ { error: "Unauthorized to access this team" },
+ { status: 403 },
+ );
+ }
+
+ const body = await req.json();
+
// Validate request body
const validation = UpdateWorkflowRequestSchema.safeParse(body);
if (!validation.success) {
@@ -132,17 +182,14 @@ export async function PATCH(
);
}
- // Fetch workflow to check ownership
+ // Check workflow exists and belongs to team
const workflow = await prisma.workflow.findUnique({
- where: { id: workflowId },
+ where: {
+ id: workflowId,
+ teamId: teamId,
+ },
select: {
id: true,
- teamId: true,
- team: {
- select: {
- users: { select: { userId: true } },
- },
- },
},
});
@@ -153,18 +200,6 @@ export async function PATCH(
);
}
- // Check user is part of the team
- const isUserPartOfTeam = workflow.team.users.some(
- (user) => user.userId === (session.user as CustomUser).id,
- );
-
- if (!isUserPartOfTeam) {
- return NextResponse.json(
- { error: "Unauthorized to modify this workflow" },
- { status: 403 },
- );
- }
-
// Update workflow
const updatedWorkflow = await prisma.workflow.update({
where: { id: workflowId },
@@ -190,7 +225,7 @@ export async function PATCH(
}
}
-// DELETE /app/(ee)/api/workflows/[workflowId] - Delete workflow
+// DELETE /app/(ee)/api/workflows/[workflowId]?teamId=xxx - Delete workflow
export async function DELETE(
req: NextRequest,
{ params }: { params: { workflowId: string } },
@@ -202,28 +237,57 @@ export async function DELETE(
}
const { workflowId } = params;
+ const searchParams = req.nextUrl.searchParams;
+ const teamId = searchParams.get("teamId");
+
+ if (!teamId) {
+ return NextResponse.json(
+ { error: "teamId parameter is required" },
+ { status: 400 },
+ );
+ }
+
+ // Validate IDs format
+ const idsValidation = z.object({
+ workflowId: z.string().cuid(),
+ teamId: z.string().cuid(),
+ }).safeParse({ workflowId, teamId });
- // Validate workflowId format
- const workflowIdValidation = z.string().cuid().safeParse(workflowId);
- if (!workflowIdValidation.success) {
+ if (!idsValidation.success) {
return NextResponse.json(
- { error: "Invalid workflowId format" },
+ { error: "Invalid ID format" },
{ status: 400 },
);
}
- // Fetch workflow to check ownership
+ const userId = (session.user as CustomUser).id;
+
+ // Check user is part of the team using userTeam table
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
+ return NextResponse.json(
+ { error: "Unauthorized to access this team" },
+ { status: 403 },
+ );
+ }
+
+ // Fetch workflow to check existence and get entryLinkId
const workflow = await prisma.workflow.findUnique({
- where: { id: workflowId },
+ where: {
+ id: workflowId,
+ teamId: teamId,
+ },
select: {
id: true,
entryLinkId: true,
- teamId: true,
- team: {
- select: {
- users: { select: { userId: true } },
- },
- },
},
});
@@ -234,18 +298,6 @@ export async function DELETE(
);
}
- // Check user is part of the team
- const isUserPartOfTeam = workflow.team.users.some(
- (user) => user.userId === (session.user as CustomUser).id,
- );
-
- if (!isUserPartOfTeam) {
- return NextResponse.json(
- { error: "Unauthorized to delete this workflow" },
- { status: 403 },
- );
- }
-
// Delete workflow and entry link in transaction
// Note: Steps and executions will cascade delete via Prisma relations
await prisma.$transaction([
diff --git a/app/(ee)/api/workflows/[workflowId]/steps/[stepId]/route.ts b/app/(ee)/api/workflows/[workflowId]/steps/[stepId]/route.ts
index 1887067f..8b5fba37 100644
--- a/app/(ee)/api/workflows/[workflowId]/steps/[stepId]/route.ts
+++ b/app/(ee)/api/workflows/[workflowId]/steps/[stepId]/route.ts
@@ -1,17 +1,19 @@
import { NextRequest, NextResponse } from "next/server";
-import { getServerSession } from "next-auth";
-import { authOptions } from "@/pages/api/auth/[...nextauth]";
-import { z } from "zod";
-import prisma from "@/lib/prisma";
-import { CustomUser } from "@/lib/types";
+
import {
UpdateWorkflowStepRequestSchema,
formatZodError,
- validateConditions,
validateActions,
+ validateConditions,
} from "@/ee/features/workflows/lib/validation";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth";
+import { z } from "zod";
-// PATCH /app/(ee)/api/workflows/[workflowId]/steps/[stepId] - Update step
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+// PATCH /app/(ee)/api/workflows/[workflowId]/steps/[stepId]?teamId=xxx - Update step
export async function PATCH(
req: NextRequest,
{ params }: { params: { workflowId: string; stepId: string } },
@@ -23,21 +25,50 @@ export async function PATCH(
}
const { workflowId, stepId } = params;
- const body = await req.json();
+ const searchParams = req.nextUrl.searchParams;
+ const teamId = searchParams.get("teamId");
+
+ if (!teamId) {
+ return NextResponse.json(
+ { error: "teamId parameter is required" },
+ { status: 400 },
+ );
+ }
// Validate IDs format
- const idsValidation = z.object({
- workflowId: z.string().cuid(),
- stepId: z.string().cuid(),
- }).safeParse({ workflowId, stepId });
+ const idsValidation = z
+ .object({
+ workflowId: z.string().cuid(),
+ stepId: z.string().cuid(),
+ teamId: z.string().cuid(),
+ })
+ .safeParse({ workflowId, stepId, teamId });
if (!idsValidation.success) {
+ return NextResponse.json({ error: "Invalid ID format" }, { status: 400 });
+ }
+
+ const userId = (session.user as CustomUser).id;
+
+ // Check user is part of the team using userTeam table
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
return NextResponse.json(
- { error: "Invalid ID format" },
- { status: 400 },
+ { error: "Unauthorized to access this team" },
+ { status: 403 },
);
}
+ const body = await req.json();
+
// Validate request body
const validation = UpdateWorkflowStepRequestSchema.safeParse(body);
if (!validation.success) {
@@ -104,7 +135,10 @@ export async function PATCH(
}
// Update action with target details (mutates validatedActions)
- if (targetLink.linkType === "DOCUMENT_LINK" && targetLink.documentId) {
+ if (
+ targetLink.linkType === "DOCUMENT_LINK" &&
+ targetLink.documentId
+ ) {
routeAction.targetDocumentId = targetLink.documentId;
} else if (
targetLink.linkType === "DATAROOM_LINK" &&
@@ -116,41 +150,25 @@ export async function PATCH(
}
}
- // Check step exists and user has access
+ // Check step exists and workflow belongs to team
const step = await prisma.workflowStep.findUnique({
- where: { id: stepId, workflowId },
+ where: {
+ id: stepId,
+ workflowId: workflowId,
+ },
select: {
id: true,
workflow: {
select: {
id: true,
teamId: true,
- team: {
- select: {
- users: { select: { userId: true } },
- },
- },
},
},
},
});
- if (!step) {
- return NextResponse.json(
- { error: "Step not found" },
- { status: 404 },
- );
- }
-
- const isUserPartOfTeam = step.workflow.team.users.some(
- (user) => user.userId === (session.user as CustomUser).id,
- );
-
- if (!isUserPartOfTeam) {
- return NextResponse.json(
- { error: "Unauthorized to modify this step" },
- { status: 403 },
- );
+ if (!step || step.workflow.teamId !== teamId) {
+ return NextResponse.json({ error: "Step not found" }, { status: 404 });
}
// Extract emails and domains from conditions to sync with link allowList (if conditions updated)
@@ -184,7 +202,9 @@ export async function PATCH(
select: { actions: true },
});
const existingActions = existingStep?.actions as any[];
- const existingRouteAction = existingActions?.find((a) => a.type === "route");
+ const existingRouteAction = existingActions?.find(
+ (a) => a.type === "route",
+ );
targetLinkId = existingRouteAction?.targetLinkId;
}
@@ -227,7 +247,7 @@ export async function PATCH(
}
}
-// DELETE /app/(ee)/api/workflows/[workflowId]/steps/[stepId] - Delete step
+// DELETE /app/(ee)/api/workflows/[workflowId]/steps/[stepId]?teamId=xxx - Delete step
export async function DELETE(
req: NextRequest,
{ params }: { params: { workflowId: string; stepId: string } },
@@ -239,23 +259,54 @@ export async function DELETE(
}
const { workflowId, stepId } = params;
+ const searchParams = req.nextUrl.searchParams;
+ const teamId = searchParams.get("teamId");
+
+ if (!teamId) {
+ return NextResponse.json(
+ { error: "teamId parameter is required" },
+ { status: 400 },
+ );
+ }
// Validate IDs format
- const idsValidation = z.object({
- workflowId: z.string().cuid(),
- stepId: z.string().cuid(),
- }).safeParse({ workflowId, stepId });
+ const idsValidation = z
+ .object({
+ workflowId: z.string().cuid(),
+ stepId: z.string().cuid(),
+ teamId: z.string().cuid(),
+ })
+ .safeParse({ workflowId, stepId, teamId });
if (!idsValidation.success) {
+ return NextResponse.json({ error: "Invalid ID format" }, { status: 400 });
+ }
+
+ const userId = (session.user as CustomUser).id;
+
+ // Check user is part of the team using userTeam table
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
return NextResponse.json(
- { error: "Invalid ID format" },
- { status: 400 },
+ { error: "Unauthorized to access this team" },
+ { status: 403 },
);
}
- // Check step exists and user has access
+ // Check step exists and workflow belongs to team
const step = await prisma.workflowStep.findUnique({
- where: { id: stepId, workflowId },
+ where: {
+ id: stepId,
+ workflowId: workflowId,
+ },
select: {
id: true,
stepOrder: true,
@@ -263,41 +314,13 @@ export async function DELETE(
select: {
id: true,
teamId: true,
- team: {
- select: {
- users: { select: { userId: true } },
- },
- },
- steps: {
- where: {
- stepOrder: { gt: 0 }, // placeholder, will be updated below
- },
- select: {
- id: true,
- stepOrder: true,
- },
- },
},
},
},
});
- if (!step) {
- return NextResponse.json(
- { error: "Step not found" },
- { status: 404 },
- );
- }
-
- const isUserPartOfTeam = step.workflow.team.users.some(
- (user) => user.userId === (session.user as CustomUser).id,
- );
-
- if (!isUserPartOfTeam) {
- return NextResponse.json(
- { error: "Unauthorized to delete this step" },
- { status: 403 },
- );
+ if (!step || step.workflow.teamId !== teamId) {
+ return NextResponse.json({ error: "Step not found" }, { status: 404 });
}
// Get steps that need reordering (those after the deleted step)
@@ -334,4 +357,3 @@ export async function DELETE(
);
}
}
-
diff --git a/app/(ee)/api/workflows/[workflowId]/steps/route.ts b/app/(ee)/api/workflows/[workflowId]/steps/route.ts
index ed1669a9..ddedbd8d 100644
--- a/app/(ee)/api/workflows/[workflowId]/steps/route.ts
+++ b/app/(ee)/api/workflows/[workflowId]/steps/route.ts
@@ -13,7 +13,7 @@ import {
} from "@/ee/features/workflows/lib/validation";
import { ReorderStepsRequest } from "@/ee/features/workflows/lib/types";
-// GET /app/(ee)/api/workflows/[workflowId]/steps - List all steps
+// GET /app/(ee)/api/workflows/[workflowId]/steps?teamId=xxx - List all steps
export async function GET(
req: NextRequest,
{ params }: { params: { workflowId: string } },
@@ -25,45 +25,63 @@ export async function GET(
}
const { workflowId } = params;
+ const searchParams = req.nextUrl.searchParams;
+ const teamId = searchParams.get("teamId");
- // Validate workflowId format
- const workflowIdValidation = z.string().cuid().safeParse(workflowId);
- if (!workflowIdValidation.success) {
+ if (!teamId) {
return NextResponse.json(
- { error: "Invalid workflowId format" },
+ { error: "teamId parameter is required" },
{ status: 400 },
);
}
- // Check workflow exists and user has access
- const workflow = await prisma.workflow.findUnique({
- where: { id: workflowId },
- select: {
- id: true,
- teamId: true,
- team: {
- select: {
- users: { select: { userId: true } },
- },
+ // Validate IDs format
+ const idsValidation = z.object({
+ workflowId: z.string().cuid(),
+ teamId: z.string().cuid(),
+ }).safeParse({ workflowId, teamId });
+
+ if (!idsValidation.success) {
+ return NextResponse.json(
+ { error: "Invalid ID format" },
+ { status: 400 },
+ );
+ }
+
+ const userId = (session.user as CustomUser).id;
+
+ // Check user is part of the team using userTeam table
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
},
},
});
- if (!workflow) {
+ if (!teamAccess) {
return NextResponse.json(
- { error: "Workflow not found" },
- { status: 404 },
+ { error: "Unauthorized to access this team" },
+ { status: 403 },
);
}
- const isUserPartOfTeam = workflow.team.users.some(
- (user) => user.userId === (session.user as CustomUser).id,
- );
+ // Check workflow exists and belongs to team
+ const workflow = await prisma.workflow.findUnique({
+ where: {
+ id: workflowId,
+ teamId: teamId,
+ },
+ select: {
+ id: true,
+ },
+ });
- if (!isUserPartOfTeam) {
+ if (!workflow) {
return NextResponse.json(
- { error: "Unauthorized to access this workflow" },
- { status: 403 },
+ { error: "Workflow not found" },
+ { status: 404 },
);
}
@@ -111,7 +129,7 @@ export async function GET(
}
}
-// POST /app/(ee)/api/workflows/[workflowId]/steps - Create a new step
+// POST /app/(ee)/api/workflows/[workflowId]/steps?teamId=xxx - Create a new step
export async function POST(
req: NextRequest,
{ params }: { params: { workflowId: string } },
@@ -123,17 +141,50 @@ export async function POST(
}
const { workflowId } = params;
- const body = await req.json();
+ const searchParams = req.nextUrl.searchParams;
+ const teamId = searchParams.get("teamId");
- // Validate workflowId format
- const workflowIdValidation = z.string().cuid().safeParse(workflowId);
- if (!workflowIdValidation.success) {
+ if (!teamId) {
return NextResponse.json(
- { error: "Invalid workflowId format" },
+ { error: "teamId parameter is required" },
{ status: 400 },
);
}
+ // Validate IDs format
+ const idsValidation = z.object({
+ workflowId: z.string().cuid(),
+ teamId: z.string().cuid(),
+ }).safeParse({ workflowId, teamId });
+
+ if (!idsValidation.success) {
+ return NextResponse.json(
+ { error: "Invalid ID format" },
+ { status: 400 },
+ );
+ }
+
+ const userId = (session.user as CustomUser).id;
+
+ // Check user is part of the team using userTeam table
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
+ return NextResponse.json(
+ { error: "Unauthorized to access this team" },
+ { status: 403 },
+ );
+ }
+
+ const body = await req.json();
+
// Validate request body
const validation = CreateWorkflowStepRequestSchema.safeParse(body);
if (!validation.success) {
@@ -165,17 +216,15 @@ export async function POST(
);
}
- // Check workflow exists and user has access
+ // Check workflow exists and belongs to team
const workflow = await prisma.workflow.findUnique({
- where: { id: workflowId },
+ where: {
+ id: workflowId,
+ teamId: teamId,
+ },
select: {
id: true,
teamId: true,
- team: {
- select: {
- users: { select: { userId: true } },
- },
- },
steps: {
select: { stepOrder: true },
orderBy: { stepOrder: "desc" },
@@ -191,17 +240,6 @@ export async function POST(
);
}
- const isUserPartOfTeam = workflow.team.users.some(
- (user) => user.userId === (session.user as CustomUser).id,
- );
-
- if (!isUserPartOfTeam) {
- return NextResponse.json(
- { error: "Unauthorized to modify this workflow" },
- { status: 403 },
- );
- }
-
// Validate target link exists and belongs to the team
// Use actionsValidation.data so enrichment persists
const routeAction = actionsValidation.data.find((a) => a.type === "route");
@@ -289,7 +327,7 @@ export async function POST(
}
}
-// PUT /app/(ee)/api/workflows/[workflowId]/steps - Reorder steps
+// PUT /app/(ee)/api/workflows/[workflowId]/steps?teamId=xxx - Reorder steps
export async function PUT(
req: NextRequest,
{ params }: { params: { workflowId: string } },
@@ -301,17 +339,50 @@ export async function PUT(
}
const { workflowId } = params;
- const body = await req.json();
+ const searchParams = req.nextUrl.searchParams;
+ const teamId = searchParams.get("teamId");
- // Validate workflowId format
- const workflowIdValidation = z.string().cuid().safeParse(workflowId);
- if (!workflowIdValidation.success) {
+ if (!teamId) {
return NextResponse.json(
- { error: "Invalid workflowId format" },
+ { error: "teamId parameter is required" },
{ status: 400 },
);
}
+ // Validate IDs format
+ const idsValidation = z.object({
+ workflowId: z.string().cuid(),
+ teamId: z.string().cuid(),
+ }).safeParse({ workflowId, teamId });
+
+ if (!idsValidation.success) {
+ return NextResponse.json(
+ { error: "Invalid ID format" },
+ { status: 400 },
+ );
+ }
+
+ const userId = (session.user as CustomUser).id;
+
+ // Check user is part of the team using userTeam table
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
+ return NextResponse.json(
+ { error: "Unauthorized to access this team" },
+ { status: 403 },
+ );
+ }
+
+ const body = await req.json();
+
// Validate request body
const validation = ReorderStepsRequestSchema.safeParse(body);
if (!validation.success) {
@@ -324,17 +395,14 @@ export async function PUT(
);
}
- // Check workflow exists and user has access
+ // Check workflow exists and belongs to team
const workflow = await prisma.workflow.findUnique({
- where: { id: workflowId },
+ where: {
+ id: workflowId,
+ teamId: teamId,
+ },
select: {
id: true,
- teamId: true,
- team: {
- select: {
- users: { select: { userId: true } },
- },
- },
},
});
@@ -345,17 +413,6 @@ export async function PUT(
);
}
- const isUserPartOfTeam = workflow.team.users.some(
- (user) => user.userId === (session.user as CustomUser).id,
- );
-
- if (!isUserPartOfTeam) {
- return NextResponse.json(
- { error: "Unauthorized to modify this workflow" },
- { status: 403 },
- );
- }
-
// Update step orders in a transaction
await prisma.$transaction(
validation.data.steps.map((step) =>
diff --git a/app/(ee)/api/workflows/route.ts b/app/(ee)/api/workflows/route.ts
index 3467aac5..256e4fe0 100644
--- a/app/(ee)/api/workflows/route.ts
+++ b/app/(ee)/api/workflows/route.ts
@@ -87,7 +87,7 @@ export async function GET(req: NextRequest) {
}
}
-// POST /app/(ee)/api/workflows - Create a new workflow
+// POST /app/(ee)/api/workflows?teamId=xxx - Create a new workflow
export async function POST(req: NextRequest) {
try {
const session = await getServerSession(authOptions);
@@ -96,6 +96,42 @@ export async function POST(req: NextRequest) {
}
const userId = (session.user as CustomUser).id;
+ const searchParams = req.nextUrl.searchParams;
+ const teamId = searchParams.get("teamId");
+
+ if (!teamId) {
+ return NextResponse.json(
+ { error: "teamId parameter is required" },
+ { status: 400 },
+ );
+ }
+
+ // Validate teamId format
+ const teamIdValidation = z.string().cuid().safeParse(teamId);
+ if (!teamIdValidation.success) {
+ return NextResponse.json(
+ { error: "Invalid teamId format" },
+ { status: 400 },
+ );
+ }
+
+ // Check user is part of the team using userTeam table
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: userId,
+ teamId: teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
+ return NextResponse.json(
+ { error: "Unauthorized to access this team" },
+ { status: 403 },
+ );
+ }
+
const body = await req.json();
// Validate request body
@@ -110,16 +146,11 @@ export async function POST(req: NextRequest) {
);
}
- const { name, description, teamId, domain, slug } = validation.data;
+ const { name, description, domain, slug } = validation.data;
- // Check user is part of the team
+ // Get team details for plan check
const team = await prisma.team.findUnique({
- where: {
- id: teamId,
- users: {
- some: { userId },
- },
- },
+ where: { id: teamId },
select: {
id: true,
plan: true,
@@ -127,10 +158,7 @@ export async function POST(req: NextRequest) {
});
if (!team) {
- return NextResponse.json(
- { error: "Team not found or unauthorized" },
- { status: 403 },
- );
+ return NextResponse.json({ error: "Team not found" }, { status: 404 });
}
// Check if workflows feature flag is enabled
diff --git a/ee/features/workflows/components/step-form-dialog.tsx b/ee/features/workflows/components/step-form-dialog.tsx
index 108ef3ba..dcf18270 100644
--- a/ee/features/workflows/components/step-form-dialog.tsx
+++ b/ee/features/workflows/components/step-form-dialog.tsx
@@ -53,6 +53,7 @@ interface Link {
interface StepFormDialogProps {
workflowId: string;
+ teamId: string;
step: WorkflowStep | null;
links: Link[];
open: boolean;
@@ -62,6 +63,7 @@ interface StepFormDialogProps {
export function StepFormDialog({
workflowId,
+ teamId,
step,
links,
open,
@@ -160,8 +162,9 @@ export function StepFormDialog({
// Validate IDs to prevent SSRF
const workflowIdValidation = z.string().cuid().safeParse(workflowId);
- if (!workflowIdValidation.success) {
- toast.error("Invalid workflow ID");
+ const teamIdValidation = z.string().cuid().safeParse(teamId);
+ if (!workflowIdValidation.success || !teamIdValidation.success) {
+ toast.error("Invalid workflow or team ID");
return;
}
@@ -227,8 +230,8 @@ export function StepFormDialog({
};
const url = step
- ? `/api/workflows/${workflowId}/steps/${step.id}`
- : `/api/workflows/${workflowId}/steps`;
+ ? `/api/workflows/${workflowId}/steps/${step.id}?teamId=${teamId}`
+ : `/api/workflows/${workflowId}/steps?teamId=${teamId}`;
const response = await fetch(url, {
method: step ? "PATCH" : "POST",
diff --git a/ee/features/workflows/components/workflow-header.tsx b/ee/features/workflows/components/workflow-header.tsx
index 2dba3d0e..d0bb919e 100644
--- a/ee/features/workflows/components/workflow-header.tsx
+++ b/ee/features/workflows/components/workflow-header.tsx
@@ -17,6 +17,7 @@ import {
interface WorkflowHeaderProps {
workflowId: string;
+ teamId: string;
name: string;
description: string | null;
isActive: boolean;
@@ -26,6 +27,7 @@ interface WorkflowHeaderProps {
export function WorkflowHeader({
workflowId,
+ teamId,
name,
description,
isActive,
@@ -37,15 +39,16 @@ export function WorkflowHeader({
const [isDeleting, setIsDeleting] = useState(false);
const handleToggleActive = async () => {
- // Validate workflowId to prevent SSRF
+ // Validate IDs to prevent SSRF
const workflowIdValidation = z.string().cuid().safeParse(workflowId);
- if (!workflowIdValidation.success) {
- toast.error("Invalid workflow ID");
+ const teamIdValidation = z.string().cuid().safeParse(teamId);
+ if (!workflowIdValidation.success || !teamIdValidation.success) {
+ toast.error("Invalid workflow or team ID");
return;
}
try {
- const response = await fetch(`/api/workflows/${workflowId}`, {
+ const response = await fetch(`/api/workflows/${workflowId}?teamId=${teamId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
@@ -67,10 +70,11 @@ export function WorkflowHeader({
};
const handleDeleteWorkflow = async () => {
- // Validate workflowId to prevent SSRF
+ // Validate IDs to prevent SSRF
const workflowIdValidation = z.string().cuid().safeParse(workflowId);
- if (!workflowIdValidation.success) {
- toast.error("Invalid workflow ID");
+ const teamIdValidation = z.string().cuid().safeParse(teamId);
+ if (!workflowIdValidation.success || !teamIdValidation.success) {
+ toast.error("Invalid workflow or team ID");
setShowDeleteDialog(false);
return;
}
@@ -78,7 +82,7 @@ export function WorkflowHeader({
setIsDeleting(true);
try {
- const response = await fetch(`/api/workflows/${workflowId}`, {
+ const response = await fetch(`/api/workflows/${workflowId}?teamId=${teamId}`, {
method: "DELETE",
});
diff --git a/ee/features/workflows/lib/types.ts b/ee/features/workflows/lib/types.ts
index 2757a0f6..5461ebf5 100644
--- a/ee/features/workflows/lib/types.ts
+++ b/ee/features/workflows/lib/types.ts
@@ -63,7 +63,6 @@ export type WorkflowStepDefinition = z.infer<
export const CreateWorkflowRequestSchema = z.object({
name: z.string().min(1, "Workflow name is required").max(100),
description: z.string().max(500).optional(),
- teamId: z.string().cuid(),
// Entry link details
domain: z.string().nullish(), // null or undefined means papermark.com
slug: z
diff --git a/ee/features/workflows/pages/workflow-detail.tsx b/ee/features/workflows/pages/workflow-detail.tsx
index 07b15aed..f66ca4dd 100644
--- a/ee/features/workflows/pages/workflow-detail.tsx
+++ b/ee/features/workflows/pages/workflow-detail.tsx
@@ -87,7 +87,7 @@ export default function WorkflowDetailPage() {
error,
mutate,
} = useSWR<Workflow>(
- validWorkflowId ? `/api/workflows/${validWorkflowId}` : null,
+ validWorkflowId && validTeamId ? `/api/workflows/${validWorkflowId}?teamId=${validTeamId}` : null,
fetcher,
);
@@ -108,15 +108,16 @@ export default function WorkflowDetailPage() {
// Validate IDs to prevent SSRF
const workflowIdValidation = z.string().cuid().safeParse(workflowId);
const stepIdValidation = z.string().cuid().safeParse(stepId);
+ const teamIdValidation = z.string().cuid().safeParse(teamId);
- if (!workflowIdValidation.success || !stepIdValidation.success) {
- toast.error("Invalid workflow or step ID");
+ if (!workflowIdValidation.success || !stepIdValidation.success || !teamIdValidation.success) {
+ toast.error("Invalid workflow, step, or team ID");
return;
}
try {
const response = await fetch(
- `/api/workflows/${workflowId}/steps/${stepId}`,
+ `/api/workflows/${workflowId}/steps/${stepId}?teamId=${teamId}`,
{
method: "DELETE",
},
@@ -165,6 +166,7 @@ export default function WorkflowDetailPage() {
<div className="max-w-4xl space-y-6">
<WorkflowHeader
workflowId={workflowId}
+ teamId={teamId!}
name={workflow.name}
description={workflow.description}
isActive={workflow.isActive}
@@ -187,9 +189,10 @@ export default function WorkflowDetailPage() {
</div>
{/* Step Form Dialog */}
- {showStepDialog && validWorkflowId && (
+ {showStepDialog && validWorkflowId && validTeamId && (
<StepFormDialog
workflowId={validWorkflowId}
+ teamId={validTeamId}
step={editingStep}
links={links || []}
open={showStepDialog}
diff --git a/ee/features/workflows/pages/workflow-new.tsx b/ee/features/workflows/pages/workflow-new.tsx
index 3e11b4fa..7f66bd07 100644
--- a/ee/features/workflows/pages/workflow-new.tsx
+++ b/ee/features/workflows/pages/workflow-new.tsx
@@ -54,7 +54,7 @@ export default function NewWorkflowPage() {
setIsLoading(true);
try {
- const response = await fetch("/api/workflows", {
+ const response = await fetch(`/api/workflows?teamId=${teamId}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -62,7 +62,6 @@ export default function NewWorkflowPage() {
body: JSON.stringify({
name: name.trim(),
description: description.trim() || undefined,
- teamId,
domain: domain === "papermark.com" ? undefined : domain,
slug: domain === "papermark.com" ? undefined : slug.trim(),
}),