Skip to content

Open source alternative to Semrush and Ahrefs

Let organization owners transfer ownership in the app (EVE-262) (#675)

Carter Smith42ddb0cdeadb
diff --git a/src/client/features/team/TeamSettings.tsx b/src/client/features/team/TeamSettings.tsx
index ecd89491..116811d8 100644
--- a/src/client/features/team/TeamSettings.tsx
+++ b/src/client/features/team/TeamSettings.tsx
@@ -6,7 +6,12 @@ import {
inviteErrorMessage,
} from "@/client/features/team/InviteTeammateModal";
import { organizationContextQueryOptions } from "@/client/features/team/organizationQueries";
-import { InvitationRow, MemberRow } from "@/client/features/team/TeamTableRows";
+import {
+ InvitationRow,
+ MemberRow,
+ type Member,
+} from "@/client/features/team/TeamTableRows";
+import { TransferOwnershipModal } from "@/client/features/team/TransferOwnershipModal";
import { captureClientEvent } from "@/client/lib/posthog";
import { authClient, useSession } from "@/lib/auth-client";
import { hasOrgPermission } from "@/lib/org-permissions";
@@ -17,6 +22,7 @@ export function TeamSettings() {
const { data: session } = useSession();
const queryClient = useQueryClient();
const [isInviteOpen, setIsInviteOpen] = useState(false);
+ const [transferTarget, setTransferTarget] = useState<Member | null>(null);
const orgContextQuery = useQuery(organizationContextQueryOptions());
@@ -149,6 +155,7 @@ export function TeamSettings() {
isOwner={isOwner}
isRemoving={removeMemberMutation.isPending}
onRemove={() => removeMemberMutation.mutate(member.id)}
+ onTransferOwnership={() => setTransferTarget(member)}
/>
))}
{pendingInvitations.map((invitation) => (
@@ -169,6 +176,21 @@ export function TeamSettings() {
</div>
)}
+ {transferTarget ? (
+ <TransferOwnershipModal
+ member={transferTarget}
+ onClose={() => setTransferTarget(null)}
+ onTransferred={() => {
+ // The caller's own role changed too: refresh the org context that
+ // gates the team and billing UI, not only the member list.
+ void refreshTeam();
+ void queryClient.invalidateQueries({
+ queryKey: organizationContextQueryOptions().queryKey,
+ });
+ }}
+ />
+ ) : null}
+
{isInviteOpen ? (
<InviteTeammateModal
onClose={() => setIsInviteOpen(false)}
diff --git a/src/client/features/team/TeamTableRows.tsx b/src/client/features/team/TeamTableRows.tsx
index 7bbf197a..548eeb8c 100644
--- a/src/client/features/team/TeamTableRows.tsx
+++ b/src/client/features/team/TeamTableRows.tsx
@@ -1,4 +1,4 @@
-import { Send, Trash2 } from "lucide-react";
+import { Crown, Send, Trash2 } from "lucide-react";
import { PortalMenu } from "@/client/components/PortalMenu";
import { hasOrgPermission } from "@/lib/org-permissions";
@@ -15,7 +15,7 @@ function formatRole(role: string) {
.join(", ");
}
-type Member = {
+export type Member = {
id: string;
userId: string;
role: string;
@@ -36,6 +36,7 @@ export function MemberRow({
isOwner,
isRemoving,
onRemove,
+ onTransferOwnership,
}: {
member: Member;
isSelf: boolean;
@@ -43,6 +44,7 @@ export function MemberRow({
isOwner: boolean;
isRemoving: boolean;
onRemove: () => void;
+ onTransferOwnership: () => void;
}) {
const memberIsOwner = hasOrgPermission(member.role, {
billing: ["manage"],
@@ -50,6 +52,8 @@ export function MemberRow({
// Owners are protected server-side (only an owner can touch an owner; the
// last owner can't be removed) — don't render controls that would just 403.
const canRemove = canManageTeam && !isSelf && (!memberIsOwner || isOwner);
+ // Owners can always remove, so this only ever adds to the remove menu.
+ const canTransferOwnership = isOwner && !isSelf && !memberIsOwner;
return (
<tr className="hover">
@@ -77,25 +81,40 @@ export function MemberRow({
menuClassName="w-52"
>
{(close) => (
- <li>
- <button
- className="text-error"
- disabled={isRemoving}
- onClick={() => {
- close();
- if (
- window.confirm(
- `Remove ${member.user.email} from this organization? They lose access immediately.`,
- )
- ) {
- onRemove();
- }
- }}
- >
- <Trash2 className="size-3.5" />
- Remove member
- </button>
- </li>
+ <>
+ {canTransferOwnership ? (
+ <li>
+ <button
+ onClick={() => {
+ close();
+ onTransferOwnership();
+ }}
+ >
+ <Crown className="size-3.5" />
+ Transfer ownership
+ </button>
+ </li>
+ ) : null}
+ <li>
+ <button
+ className="text-error"
+ disabled={isRemoving}
+ onClick={() => {
+ close();
+ if (
+ window.confirm(
+ `Remove ${member.user.email} from this organization? They lose access immediately.`,
+ )
+ ) {
+ onRemove();
+ }
+ }}
+ >
+ <Trash2 className="size-3.5" />
+ Remove member
+ </button>
+ </li>
+ </>
)}
</PortalMenu>
) : null}
diff --git a/src/client/features/team/TransferOwnershipModal.tsx b/src/client/features/team/TransferOwnershipModal.tsx
new file mode 100644
index 00000000..c2fed800
--- /dev/null
+++ b/src/client/features/team/TransferOwnershipModal.tsx
@@ -0,0 +1,92 @@
+import { useMutation } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { Modal } from "@/client/components/Modal";
+import { getErrorCode } from "@/client/lib/error-messages";
+import { captureClientEvent } from "@/client/lib/posthog";
+import { transferOwnership } from "@/serverFunctions/organization";
+
+// NOT_FOUND: the member left. FORBIDDEN: the caller is no longer the owner
+// (another tab). CONFLICT: a row changed mid-transfer.
+function isTeamChangedError(error: Error) {
+ const code = getErrorCode(error);
+ return code === "CONFLICT" || code === "NOT_FOUND" || code === "FORBIDDEN";
+}
+
+export function TransferOwnershipModal({
+ member,
+ onClose,
+ onTransferred,
+}: {
+ member: { id: string; user: { name?: string | null; email: string } };
+ onClose: () => void;
+ onTransferred: () => void;
+}) {
+ const displayName = member.user.name || member.user.email;
+
+ const transferMutation = useMutation({
+ mutationFn: () => transferOwnership({ data: { memberId: member.id } }),
+ onSuccess: () => {
+ captureClientEvent("team:ownership_transfer");
+ toast.success(`${displayName} is now the owner`);
+ onTransferred();
+ onClose();
+ },
+ onError: (error: Error) => {
+ const teamChanged = isTeamChangedError(error);
+ toast.error(
+ teamChanged
+ ? "Your team changed while this was open. Ownership didn't change."
+ : "We couldn't transfer ownership. Ownership didn't change.",
+ );
+ // Refresh either way so the list and the caller's role are current.
+ onTransferred();
+ // The confirmation is stale once the team changed: close it so the
+ // refreshed list shows who is still there. Other errors keep it open
+ // for a retry.
+ if (teamChanged) onClose();
+ },
+ });
+
+ return (
+ <Modal
+ maxWidth="max-w-md"
+ onClose={transferMutation.isPending ? undefined : onClose}
+ labelledBy="transfer-ownership-title"
+ >
+ <div>
+ <h3 id="transfer-ownership-title" className="text-lg font-bold">
+ Transfer ownership?
+ </h3>
+ <p className="mt-2 text-sm text-base-content/70">
+ <span className="font-medium text-base-content" data-ph-mask>
+ {displayName}
+ </span>{" "}
+ becomes the owner of this organization and manages its billing. You
+ become an Admin and keep full access to each project.
+ </p>
+ <p className="mt-2 text-sm text-base-content/70">
+ Projects, data, and the subscription stay with the organization. Only
+ the new owner can transfer ownership again.
+ </p>
+ </div>
+ <div className="modal-action mt-0">
+ <button
+ type="button"
+ className="btn btn-ghost btn-sm"
+ onClick={onClose}
+ disabled={transferMutation.isPending}
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ className="btn btn-primary btn-sm"
+ onClick={() => transferMutation.mutate()}
+ disabled={transferMutation.isPending}
+ >
+ {transferMutation.isPending ? "Transferring…" : "Transfer ownership"}
+ </button>
+ </div>
+ </Modal>
+ );
+}
diff --git a/src/lib/auth.ts b/src/lib/auth.ts
index d237fbab..aed5db9d 100644
--- a/src/lib/auth.ts
+++ b/src/lib/auth.ts
@@ -87,8 +87,9 @@ function createAuth() {
// plugin lets an owner grant owner to another member. Owners
// control billing, so a second owner is a billing-escalation
// path (and, if the first owner then leaves, a fresh-org /
- // free-grant loop at next sign-in). Ownership transfers stay a
- // support action — reject owner here.
+ // free-grant loop at next sign-in). Ownership moves only through
+ // the transferOwnership server function, which swaps the two
+ // roles atomically — reject owner here.
beforeUpdateMemberRole: async ({ newRole }) => {
if (
newRole
@@ -98,7 +99,7 @@ function createAuth() {
) {
throw new APIError("BAD_REQUEST", {
message:
- "The owner role can't be granted from here. Contact support to transfer ownership.",
+ "The owner role can't be granted from here. Use Transfer ownership in organization settings.",
});
}
},
diff --git a/src/server/auth/ownership-transfer.ts b/src/server/auth/ownership-transfer.ts
new file mode 100644
index 00000000..9680a969
--- /dev/null
+++ b/src/server/auth/ownership-transfer.ts
@@ -0,0 +1,48 @@
+import type { OrgPermissionRequest } from "@/lib/org-permissions";
+import type { EnsuredUserContext } from "@/middleware/ensure-user/types";
+import { requireOrgPermission } from "@/server/auth/org-gate";
+import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
+import { AppError } from "@/server/lib/errors";
+
+// billing:manage is the owner-only statement.
+const OWNER_PERMISSION: OrgPermissionRequest = { billing: ["manage"] };
+
+// Hands the organization to another existing member: they become the owner
+// (and so the only one who can manage billing), and the caller stays on as an
+// admin. Projects, data, and the Autumn customer are keyed by organization,
+// so nothing else moves.
+export async function transferOrganizationOwnership(
+ context: Pick<EnsuredUserContext, "userId" | "organizationId" | "role">,
+ newOwnerMemberId: string,
+) {
+ requireOrgPermission(context, OWNER_PERMISSION);
+
+ const newOwner = await AuthRepository.getMemberInOrganization(
+ newOwnerMemberId,
+ context.organizationId,
+ );
+ if (!newOwner) {
+ throw new AppError("NOT_FOUND");
+ }
+ if (newOwner.userId === context.userId) {
+ throw new AppError(
+ "VALIDATION_ERROR",
+ "You already own this organization.",
+ );
+ }
+
+ await AuthRepository.transferOwnership({
+ organizationId: context.organizationId,
+ ownerUserId: context.userId,
+ newOwnerMemberId,
+ });
+
+ // The batch is a no-op when either row changed after the checks above.
+ const transferred = await AuthRepository.getMemberInOrganization(
+ newOwnerMemberId,
+ context.organizationId,
+ );
+ if (transferred?.role !== "owner") {
+ throw new AppError("CONFLICT");
+ }
+}
diff --git a/src/server/auth/repositories/AuthRepository.query.test.ts b/src/server/auth/repositories/AuthRepository.query.test.ts
index 42b9dd7d..ca653ef4 100644
--- a/src/server/auth/repositories/AuthRepository.query.test.ts
+++ b/src/server/auth/repositories/AuthRepository.query.test.ts
@@ -111,3 +111,71 @@ describe("findFirstFoundedOrganizationIdForUser", () => {
).toBeNull();
});
});
+
+describe("transferOwnership", () => {
+ async function roleOf(userId: string, organizationId = "org") {
+ return (await AuthRepository.getMembership(userId, organizationId))?.role;
+ }
+
+ beforeEach(async () => {
+ await insertMember({
+ organizationId: "org",
+ userId: "owner",
+ role: "owner",
+ createdAt: 1000,
+ });
+ await insertMember({
+ organizationId: "org",
+ userId: "teammate",
+ role: "admin",
+ createdAt: 2000,
+ });
+ });
+
+ it("makes the teammate the owner and the previous owner an admin", async () => {
+ await AuthRepository.transferOwnership({
+ organizationId: "org",
+ ownerUserId: "owner",
+ newOwnerMemberId: "org:teammate",
+ });
+
+ expect(await roleOf("owner")).toBe("admin");
+ expect(await roleOf("teammate")).toBe("owner");
+ });
+
+ it("changes nothing when the caller is not the owner", async () => {
+ await insertMember({
+ organizationId: "org",
+ userId: "other_admin",
+ role: "admin",
+ createdAt: 3000,
+ });
+
+ await AuthRepository.transferOwnership({
+ organizationId: "org",
+ ownerUserId: "teammate",
+ newOwnerMemberId: "org:other_admin",
+ });
+
+ expect(await roleOf("owner")).toBe("owner");
+ expect(await roleOf("other_admin")).toBe("admin");
+ });
+
+ it("leaves ownership unchanged when the new owner is not a member of the org", async () => {
+ await insertMember({
+ organizationId: "other_org",
+ userId: "outsider",
+ role: "owner",
+ createdAt: 3000,
+ });
+
+ await AuthRepository.transferOwnership({
+ organizationId: "org",
+ ownerUserId: "owner",
+ newOwnerMemberId: "other_org:outsider",
+ });
+
+ expect(await roleOf("owner")).toBe("owner");
+ expect(await roleOf("outsider", "other_org")).toBe("owner");
+ });
+});
diff --git a/src/server/auth/repositories/AuthRepository.ts b/src/server/auth/repositories/AuthRepository.ts
index 2f8e1e08..67d319a2 100644
--- a/src/server/auth/repositories/AuthRepository.ts
+++ b/src/server/auth/repositories/AuthRepository.ts
@@ -4,13 +4,17 @@ import {
asc,
desc,
eq,
+ exists,
gt,
inArray,
lt,
+ ne,
notExists,
+ or,
sql,
} from "drizzle-orm";
import { db } from "@/db";
+import { runBatch } from "@/db/runBatch";
import {
invitation,
member,
@@ -120,6 +124,99 @@ async function getMembership(userId: string, organizationId: string) {
return membership ?? null;
}
+async function getMemberInOrganization(
+ memberId: string,
+ organizationId: string,
+) {
+ const [membership] = await db
+ .select({ userId: member.userId, role: member.role })
+ .from(member)
+ .where(
+ and(eq(member.id, memberId), eq(member.organizationId, organizationId)),
+ )
+ .limit(1);
+
+ return membership ?? null;
+}
+
+// Promotes the new owner and demotes the current owner to admin in one atomic
+// batch. Each update re-checks the other member row, so a concurrent removal
+// or role change turns the whole transfer into a no-op instead of leaving the
+// org with two owners or none. Naming the owner's own member row is a no-op too.
+async function transferOwnership(input: {
+ organizationId: string;
+ ownerUserId: string;
+ newOwnerMemberId: string;
+}) {
+ const currentOwner = aliasedTable(member, "current_owner");
+ const newOwner = aliasedTable(member, "new_owner");
+
+ await runBatch((tx) => [
+ // Row-lock both members first. Postgres runs the batch as a READ
+ // COMMITTED transaction, so without this a concurrent transfer could
+ // promote a second member, or a removal could land between the two
+ // updates. A blocked transaction resumes after this one commits and its
+ // re-checks then see the new roles. No-op write on D1, whose batch is
+ // already serialized.
+ tx
+ .update(member)
+ .set({ role: sql`${member.role}` })
+ .where(
+ and(
+ eq(member.organizationId, input.organizationId),
+ or(
+ eq(member.userId, input.ownerUserId),
+ eq(member.id, input.newOwnerMemberId),
+ ),
+ ),
+ ),
+ tx
+ .update(member)
+ .set({ role: "owner" })
+ .where(
+ and(
+ eq(member.id, input.newOwnerMemberId),
+ eq(member.organizationId, input.organizationId),
+ exists(
+ tx
+ .select({ id: currentOwner.id })
+ .from(currentOwner)
+ .where(
+ and(
+ eq(currentOwner.organizationId, input.organizationId),
+ eq(currentOwner.userId, input.ownerUserId),
+ eq(currentOwner.role, "owner"),
+ ),
+ ),
+ ),
+ ),
+ ),
+ tx
+ .update(member)
+ .set({ role: "admin" })
+ .where(
+ and(
+ eq(member.organizationId, input.organizationId),
+ eq(member.userId, input.ownerUserId),
+ eq(member.role, "owner"),
+ exists(
+ tx
+ .select({ id: newOwner.id })
+ .from(newOwner)
+ .where(
+ and(
+ eq(newOwner.id, input.newOwnerMemberId),
+ eq(newOwner.organizationId, input.organizationId),
+ ne(newOwner.userId, input.ownerUserId),
+ eq(newOwner.role, "owner"),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ]);
+}
+
// Fallback active-org choice when there is no valid last-active pointer: the
// most recently joined org, so a just-accepted invitation wins over the
// signup-minted personal workspace.
@@ -190,6 +287,8 @@ export const AuthRepository = {
findFirstFoundedOrganizationIdForUser,
findNewestMembershipForUser,
getMembership,
+ getMemberInOrganization,
+ transferOwnership,
listMembershipsForUser,
getLastActiveOrganizationId,
setLastActiveOrganization,
diff --git a/src/server/features/google/selfHostedOAuth.test.ts b/src/server/features/google/selfHostedOAuth.test.ts
index 8918d152..fe0a1bd3 100644
--- a/src/server/features/google/selfHostedOAuth.test.ts
+++ b/src/server/features/google/selfHostedOAuth.test.ts
@@ -18,10 +18,6 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("cloudflare:workers", () => ({ env: {} }));
-vi.mock("drizzle-orm", () => ({
- and: (...values: unknown[]) => values,
- eq: (...values: unknown[]) => values,
-}));
vi.mock("@/db/schema", () => ({
account: {
id: "id",
diff --git a/src/serverFunctions/organization.ts b/src/serverFunctions/organization.ts
index e4771762..e72e42be 100644
--- a/src/serverFunctions/organization.ts
+++ b/src/serverFunctions/organization.ts
@@ -5,6 +5,7 @@ import { getAuth, getHostedBaseUrl } from "@/lib/auth";
import { hasOrgPermission } from "@/lib/org-permissions";
import { consumeInvitationSendBudget } from "@/server/auth/invitation-send-limit";
import { requireOrgPermission } from "@/server/auth/org-gate";
+import { transferOrganizationOwnership } from "@/server/auth/ownership-transfer";
import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
import { sendHostedInvitationEmail } from "@/server/email/loops";
import { AppError } from "@/server/lib/errors";
@@ -154,3 +155,16 @@ export const sendTeamInvitation = createServerFn({ method: "POST" })
return { invitationId: invitation.id };
});
+
+const transferOwnershipSchema = z.object({ memberId: z.string().min(1) });
+
+// Owner-only. Runs here rather than through better-auth's update-member-role,
+// which can't swap two roles atomically and refuses owner grants (see the
+// beforeUpdateMemberRole hook in auth.ts).
+export const transferOwnership = createServerFn({ method: "POST" })
+ .middleware(requireAuthenticatedContext)
+ .validator(transferOwnershipSchema)
+ .handler(async ({ data, context }) => {
+ await transferOrganizationOwnership(context, data.memberId);
+ return { memberId: data.memberId };
+ });