Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Sync live workspace members to staging and block staging edits

Kiran K3b4d43533c89
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/accept/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/invites/accept/route.ts
index 8af85565cf..402cfb7eee 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/accept/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/accept/route.ts
@@ -3,8 +3,10 @@ import { assertRoleAllowedForPlan } from "@/lib/api/workspaces/assert-role-plan"
import { onboardingStepCache } from "@/lib/api/workspaces/onboarding-step-cache";
import { withSession } from "@/lib/auth";
import { exceededLimitError } from "@/lib/exceeded-limit-error";
+import { addMemberToStaging } from "@/lib/sandbox/sync-member-to-staging";
import { PlanProps } from "@/lib/types";
import { prisma } from "@dub/prisma";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
// POST /api/workspaces/[idOrSlug]/invites/accept – accept a workspace invite
@@ -34,7 +36,7 @@ export const POST = withSession(async ({ session, params }) => {
});
}
- const workspace = await prisma.$transaction(async (tx) => {
+ const { workspace, workspaceUser } = await prisma.$transaction(async (tx) => {
const existingMembership = await tx.projectUsers.findFirst({
where: {
userId: session.user.id,
@@ -58,6 +60,7 @@ export const POST = withSession(async ({ session, params }) => {
slug: true,
plan: true,
usersLimit: true,
+ stagingWorkspaceId: true,
_count: {
select: {
users: {
@@ -88,7 +91,7 @@ export const POST = withSession(async ({ session, params }) => {
plan: workspace.plan,
});
- await tx.projectUsers.create({
+ const workspaceUser = await tx.projectUsers.create({
data: {
userId: session.user.id,
role: invite.role,
@@ -109,7 +112,10 @@ export const POST = withSession(async ({ session, params }) => {
},
});
- return workspace;
+ return {
+ workspace,
+ workspaceUser,
+ };
});
// Update default workspace
@@ -129,5 +135,15 @@ export const POST = withSession(async ({ session, params }) => {
step: "completed",
});
+ waitUntil(
+ addMemberToStaging({
+ workspace,
+ user: {
+ id: workspaceUser.userId,
+ role: workspaceUser.role,
+ },
+ }),
+ );
+
return NextResponse.json({ message: "Invite accepted." });
});
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts
index 854fcdc307..ef1de6679c 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/reset/route.ts
@@ -18,5 +18,6 @@ export const POST = withWorkspace(
},
{
requiredPermissions: ["workspaces.write"],
+ rejectStagingWorkspace: true,
},
);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/invites/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/invites/route.ts
index bb08ff15c0..fb981d71fd 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/invites/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/invites/route.ts
@@ -168,6 +168,7 @@ export const POST = withWorkspace(
},
{
requiredPermissions: ["workspaces.write"],
+ rejectStagingWorkspace: true,
},
);
@@ -218,6 +219,7 @@ export const PATCH = withWorkspace(
},
{
requiredPermissions: ["workspaces.write"],
+ rejectStagingWorkspace: true,
},
);
@@ -243,5 +245,6 @@ export const DELETE = withWorkspace(
},
{
requiredPermissions: ["workspaces.write"],
+ rejectStagingWorkspace: true,
},
);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts
index e5cea6dbfd..7c160a9980 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/users/route.ts
@@ -3,12 +3,17 @@ import { throwIfNoAccess } from "@/lib/api/tokens/throw-if-no-access";
import { assertRoleAllowedForPlan } from "@/lib/api/workspaces/assert-role-plan";
import { withWorkspace } from "@/lib/auth";
import { generateRandomName } from "@/lib/names";
+import {
+ removeMemberFromStaging,
+ updateMemberRoleInStaging,
+} from "@/lib/sandbox/sync-member-to-staging";
import {
getWorkspaceUsersQuerySchema,
workspaceUserSchema,
} from "@/lib/zod/schemas/workspaces";
import { prisma } from "@dub/prisma";
import { WorkspaceRole } from "@dub/prisma/client";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
@@ -66,7 +71,7 @@ export const PATCH = withWorkspace(
plan: workspace.plan,
});
- const response = await prisma.projectUsers.update({
+ const workspaceUser = await prisma.projectUsers.update({
where: {
userId_projectId: {
projectId: workspace.id,
@@ -80,10 +85,22 @@ export const PATCH = withWorkspace(
role,
},
});
- return NextResponse.json(response);
+
+ waitUntil(
+ updateMemberRoleInStaging({
+ workspace,
+ user: {
+ id: workspaceUser.userId,
+ role: workspaceUser.role,
+ },
+ }),
+ );
+
+ return NextResponse.json(workspaceUser);
},
{
requiredPermissions: ["workspaces.write"],
+ rejectStagingWorkspace: true,
},
);
@@ -182,6 +199,15 @@ export const DELETE = withWorkspace(
}),
]);
+ waitUntil(
+ removeMemberFromStaging({
+ workspace,
+ user: {
+ id: userId,
+ },
+ }),
+ );
+
// delete the user if it's a machine user
if (projectUser.user.isMachine) {
await prisma.user.delete({
@@ -193,4 +219,7 @@ export const DELETE = withWorkspace(
return NextResponse.json(response);
},
+ {
+ rejectStagingWorkspace: true,
+ },
);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsx
index 0ee774206d..8047957e7e 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCopyDiscountToLiveModal } from "@/lib/sandbox/copy-discount-to-live-modal";
+import { useCopyDiscountToLiveModal } from "@/lib/sandbox/components/copy-discount-to-live-modal";
import useGroup from "@/lib/swr/use-group";
import useWorkspace from "@/lib/swr/use-workspace";
import type { DiscountProps, GroupProps } from "@/lib/types";
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx
index 6d9183e165..a4a2eea3cc 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx
@@ -1,7 +1,7 @@
"use client";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
-import { useCopyRewardToLiveModal } from "@/lib/sandbox/copy-reward-to-live-modal";
+import { useCopyRewardToLiveModal } from "@/lib/sandbox/components/copy-reward-to-live-modal";
import useGroup from "@/lib/swr/use-group";
import useWorkspace from "@/lib/swr/use-workspace";
import type { GroupProps, RewardProps } from "@/lib/types";
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/members/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/members/page-client.tsx
index f6a5db5ab7..23219f981b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/members/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/members/page-client.tsx
@@ -15,7 +15,7 @@ import { useRemoveWorkspaceUserModal } from "@/ui/modals/remove-workspace-user-m
import { useWorkspaceUserRoleModal } from "@/ui/modals/update-workspace-user-role";
import { SearchBoxPersisted } from "@/ui/shared/search-box";
import { UserAvatar } from "@/ui/users/user-avatar";
-import { WorkspaceRole } from "@dub/prisma/client";
+import { WorkspaceEnvironment, WorkspaceRole } from "@dub/prisma/client";
import {
Button,
Filter,
@@ -50,7 +50,8 @@ export function WorkspaceMembersClient() {
const { setShowInviteCodeModal, InviteCodeModal } = useInviteCodeModal();
- const { role, plan } = useWorkspace();
+ const { role, plan, environment } = useWorkspace();
+ const isStaging = environment === WorkspaceEnvironment.staging;
const { data: session } = useSession();
const { id: workspaceId } = useWorkspace();
@@ -142,7 +143,9 @@ export function WorkspaceMembersClient() {
return filters;
}, [status, roleFilter]);
- useKeyboardShortcut("m", () => setShowInviteWorkspaceUserModal(true));
+ useKeyboardShortcut("m", () => {
+ if (!isStaging) setShowInviteWorkspaceUserModal(true);
+ });
const columns = useMemo<ColumnDef<WorkspaceUserProps>[]>(
() => [
@@ -262,6 +265,7 @@ export function WorkspaceMembersClient() {
clientAccessCheck({
action: "workspaces.write",
role,
+ environment,
customPermissionDescription: "invite new teammates",
}).error || undefined
}
@@ -275,6 +279,7 @@ export function WorkspaceMembersClient() {
clientAccessCheck({
action: "workspaces.write",
role,
+ environment,
customPermissionDescription: "generate invite links",
}).error || undefined
}
@@ -337,7 +342,8 @@ function RoleCell({
isCurrentUser: boolean;
isCurrentUserOwner: boolean;
}) {
- const { plan } = useWorkspace();
+ const { plan, environment } = useWorkspace();
+ const isStaging = environment === WorkspaceEnvironment.staging;
const [role, setRole] = useState<WorkspaceRole>(user.role);
useEffect(() => {
@@ -366,8 +372,9 @@ function RoleCell({
});
const isDisabled =
- !isCurrentUserOwner || // Only owners can change roles
- isCurrentUser; // Can't change your own role
+ isStaging ||
+ !isCurrentUserOwner ||
+ isCurrentUser;
return (
<>
@@ -387,11 +394,13 @@ function RoleCell({
setShowWorkspaceUserRoleModal(true);
}}
title={
- !isCurrentUserOwner
- ? "Only owners can change member roles"
- : isCurrentUser
- ? "You cannot change your own role"
- : undefined
+ isStaging
+ ? "Roles are managed from the live workspace"
+ : !isCurrentUserOwner
+ ? "Only owners can change member roles"
+ : isCurrentUser
+ ? "You cannot change your own role"
+ : undefined
}
>
{WORKSPACE_ROLES.map(({ value, label }) => {
@@ -419,6 +428,8 @@ function RowMenuButton({
}) {
const [isOpen, setIsOpen] = useState(false);
const { data: session } = useSession();
+ const { environment } = useWorkspace();
+ const isStaging = environment === WorkspaceEnvironment.staging;
const user = row.original;
const searchParams = useSearchParams();
@@ -441,6 +452,11 @@ function RowMenuButton({
const isCurrentUser = session?.user?.email === user.email;
+ // In staging, only show menu for self (leave workspace)
+ if (isStaging && !isCurrentUser) {
+ return null;
+ }
+
// Only show menu if user is owner OR they're removing themselves
if (!isCurrentUserOwner && !isCurrentUser) {
return null;
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index 674dfd0494..e327a204de 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -2,7 +2,7 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { BetaFeatures, PlanProps, WorkspaceWithUsers } from "@/lib/types";
import { ratelimit } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
-import { WorkspaceRole } from "@dub/prisma/client";
+import { WorkspaceEnvironment, WorkspaceRole } from "@dub/prisma/client";
import { API_DOMAIN, getSearchParams } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { headers } from "next/headers";
@@ -71,11 +71,13 @@ export const withWorkspace = (
requiredPermissions = [],
requiredRoles = [],
featureFlag, // if the action needs a specific feature flag
+ rejectStagingWorkspace = false,
}: {
requiredPlan?: Array<PlanProps>;
requiredPermissions?: PermissionAction[];
requiredRoles?: WorkspaceRole[];
featureFlag?: BetaFeatures;
+ rejectStagingWorkspace?: boolean;
} = {},
) => {
return withAxiomBodyLog(
@@ -460,6 +462,17 @@ export const withWorkspace = (
});
}
+ if (
+ rejectStagingWorkspace &&
+ workspace.environment === WorkspaceEnvironment.staging
+ ) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "This action is not available in a staging workspace. Use the live workspace instead.",
+ });
+ }
+
// analytics API checks
if (
workspace.plan === "free" &&
diff --git a/apps/web/lib/client-access-check.ts b/apps/web/lib/client-access-check.ts
index 9192f8a543..de5183ac3f 100644
--- a/apps/web/lib/client-access-check.ts
+++ b/apps/web/lib/client-access-check.ts
@@ -1,4 +1,4 @@
-import { WorkspaceRole } from "@dub/prisma/client";
+import { WorkspaceEnvironment, WorkspaceRole } from "@dub/prisma/client";
import { combineWords } from "@dub/utils";
import { PermissionAction, ROLE_PERMISSIONS } from "./api/rbac/permissions";
@@ -6,11 +6,20 @@ export const clientAccessCheck = ({
action,
role,
customPermissionDescription,
+ environment,
}: {
action: PermissionAction;
role: WorkspaceRole;
customPermissionDescription?: string;
+ environment?: WorkspaceEnvironment | null;
}) => {
+ if (environment === WorkspaceEnvironment.staging) {
+ return {
+ allowed: false,
+ error: "This setting is managed from the live workspace.",
+ };
+ }
+
const permission = ROLE_PERMISSIONS.find((p) => p.action === action)!;
const allowedWorkspaceRoles = permission.roles;
const allowed = allowedWorkspaceRoles.includes(role);
diff --git a/apps/web/lib/sandbox/copy-discount-to-live-modal.tsx b/apps/web/lib/sandbox/components/copy-discount-to-live-modal.tsx
similarity index 98%
rename from apps/web/lib/sandbox/copy-discount-to-live-modal.tsx
rename to apps/web/lib/sandbox/components/copy-discount-to-live-modal.tsx
index 0d360c6f5f..af774256f3 100644
--- a/apps/web/lib/sandbox/copy-discount-to-live-modal.tsx
+++ b/apps/web/lib/sandbox/components/copy-discount-to-live-modal.tsx
@@ -12,7 +12,7 @@ import { useAction } from "next-safe-action/hooks";
import { useCallback, useMemo, useState } from "react";
import { toast } from "sonner";
import useSWR from "swr";
-import { copyDiscountToLiveAction } from "./copy-discount-to-live";
+import { copyDiscountToLiveAction } from "../copy-discount-to-live";
function CopyDiscountToLiveModal({
showModal,
diff --git a/apps/web/lib/sandbox/copy-reward-to-live-modal.tsx b/apps/web/lib/sandbox/components/copy-reward-to-live-modal.tsx
similarity index 98%
rename from apps/web/lib/sandbox/copy-reward-to-live-modal.tsx
rename to apps/web/lib/sandbox/components/copy-reward-to-live-modal.tsx
index e432247f78..e7fa595280 100644
--- a/apps/web/lib/sandbox/copy-reward-to-live-modal.tsx
+++ b/apps/web/lib/sandbox/components/copy-reward-to-live-modal.tsx
@@ -11,7 +11,7 @@ import { useAction } from "next-safe-action/hooks";
import { useCallback, useMemo, useState } from "react";
import { toast } from "sonner";
import useSWR from "swr";
-import { copyRewardToLiveAction } from "./copy-reward-to-live";
+import { copyRewardToLiveAction } from "../copy-reward-to-live";
function CopyRewardToLiveModal({
showModal,
diff --git a/apps/web/lib/sandbox/sync-member-to-staging.ts b/apps/web/lib/sandbox/sync-member-to-staging.ts
new file mode 100644
index 0000000000..0a5a856f40
--- /dev/null
+++ b/apps/web/lib/sandbox/sync-member-to-staging.ts
@@ -0,0 +1,97 @@
+import { prisma } from "@dub/prisma";
+import { WorkspaceRole } from "@dub/prisma/client";
+
+export async function addMemberToStaging({
+ liveWorkspaceId,
+ userId,
+ role,
+}: {
+ liveWorkspaceId: string;
+ userId: string;
+ role: WorkspaceRole;
+}) {
+ const liveWorkspace = await prisma.project.findUnique({
+ where: {
+ id: liveWorkspaceId,
+ },
+ select: {
+ stagingWorkspaceId: true,
+ },
+ });
+
+ if (!liveWorkspace?.stagingWorkspaceId) return;
+
+ try {
+ await prisma.projectUsers.create({
+ data: {
+ projectId: liveWorkspace.stagingWorkspaceId,
+ userId,
+ role,
+ notificationPreference: {
+ create: {},
+ },
+ },
+ });
+ } catch (e) {
+ // P2002: unique constraint violation — user already exists in staging
+ if ((e as any)?.code === "P2002") return;
+ throw e;
+ }
+}
+
+export async function removeMemberFromStaging({
+ liveWorkspaceId,
+ userId,
+}: {
+ liveWorkspaceId: string;
+ userId: string;
+}) {
+ const liveWorkspace = await prisma.project.findUnique({
+ where: {
+ id: liveWorkspaceId,
+ },
+ select: {
+ stagingWorkspaceId: true,
+ },
+ });
+
+ if (!liveWorkspace?.stagingWorkspaceId) return;
+
+ await prisma.projectUsers.deleteMany({
+ where: {
+ projectId: liveWorkspace.stagingWorkspaceId,
+ userId,
+ },
+ });
+}
+
+export async function updateMemberRoleInStaging({
+ liveWorkspaceId,
+ userId,
+ role,
+}: {
+ liveWorkspaceId: string;
+ userId: string;
+ role: WorkspaceRole;
+}) {
+ const liveWorkspace = await prisma.project.findUnique({
+ where: {
+ id: liveWorkspaceId,
+ },
+ select: {
+ stagingWorkspaceId: true,
+ },
+ });
+
+ if (!liveWorkspace?.stagingWorkspaceId) return;
+
+ await prisma.projectUsers.updateMany({
+ where: {
+ projectId: liveWorkspace.stagingWorkspaceId,
+ userId,
+ },
+ data: {
+ role,
+ },
+ });
+}