Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
π Authorize admin mutations against the database, not the session snapshot (#2638)
Luke Vellaaa773fb272af
diff --git a/apps/web/src/app/[locale]/admin-setup/actions.ts b/apps/web/src/app/[locale]/admin-setup/actions.tsindex 0ade9d2df..7e498e500 100644--- a/apps/web/src/app/[locale]/admin-setup/actions.ts+++ b/apps/web/src/app/[locale]/admin-setup/actions.ts@@ -1,9 +1,9 @@"use server";-import { prisma } from "@rallly/database";import { headers } from "next/headers";import { redirect } from "next/navigation";import { isInitialAdmin } from "@/features/setup/utils";+import { updateUserRole } from "@/features/user/mutations";import { authLib } from "@/lib/auth";import { AppError } from "@/lib/errors/app-error";import { authActionClient } from "@/lib/safe-action/server";@@ -18,14 +18,7 @@ export const makeMeAdminAction = authActionClient});}- await prisma.user.update({- where: {- id: ctx.user.id,- },- data: {- role: "admin",- },- });+ await updateUserRole({ userId: ctx.user.id, role: "admin" });// The session cookie cache still holds the old role, which would send// /control-panel straight back here. Re-issue it from the databasediff --git a/apps/web/src/features/moderation/mutations.ts b/apps/web/src/features/moderation/mutations.tsindex bbba7b4f3..981a219c5 100644--- a/apps/web/src/features/moderation/mutations.ts+++ b/apps/web/src/features/moderation/mutations.ts@@ -6,7 +6,7 @@ import { createLogger } from "@rallly/logger";import { generateText } from "ai";import { after } from "next/server";import { env } from "@/env";-import { banUserAsSystem } from "@/features/user/mutations";+import { banUser } from "@/features/user/mutations";import type { ModerationResult, ModerationVerdict } from "./types";import { containsSuspiciousPatterns } from "./utils";@@ -132,7 +132,7 @@ export async function moderateContent({if (containsBannedDomain(textToModerate)) {logger.warn({ userId }, "Banned domain detected, banning user");after(() =>- banUserAsSystem({+ banUser({userId,reason: "Automatic ban: banned domain detected in content",}),diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.tsindex faef145d0..66960f264 100644--- a/apps/web/src/features/user/actions.ts+++ b/apps/web/src/features/user/actions.ts@@ -8,6 +8,7 @@ import {unbanUser,updateUserImage,updateUserName,+ updateUserRole,} from "@/features/user/mutations";import authLib from "@/lib/auth";import { timeFormatSchema, weekStartSchema } from "@/lib/datetime/schema";@@ -152,14 +153,7 @@ export const changeRoleAction = adminActionClient});}- await prisma.user.update({- where: {- id: targetUser.id,- },- data: {- role,- },- });+ await updateUserRole({ userId: targetUser.id, role });});export const banUserAction = adminActionClientdiff --git a/apps/web/src/features/user/mutations.ts b/apps/web/src/features/user/mutations.tsindex 3d5118d07..6b02e87c6 100644--- a/apps/web/src/features/user/mutations.ts+++ b/apps/web/src/features/user/mutations.ts@@ -79,11 +79,36 @@ export async function updateUserImage({revalidateTag(userProfileTag(userId), "max");}+// Role changes must go through Better-Auth's internal adapter so the user+// snapshot cached in each session (secondary storage) gets refreshed β a bare+// Prisma write leaves every active session on the old role, and Better-Auth's+// own permission checks (e.g. banUser) read the session, not the database.+// The admin plugin's setRole endpoint is not used because it authorizes+// against the caller's possibly stale session β authorization is the caller's+// responsibility.+export async function updateUserRole({+ userId,+ role,+}: {+ userId: string;+ role: "user" | "admin";+}) {+ const { internalAdapter } = await authLib.$context;++ await internalAdapter.updateUser(userId, {+ role,+ updatedAt: new Date(),+ });+}+// Bans must go through Better-Auth rather than Prisma so the user's sessions// are actually revoked β with secondary storage enabled, sessions live in// Redis, not the Session table, and only Better-Auth's own APIs delete those// keys. A bare `banned: true` write leaves the user logged in until their-// session expires.+// session expires. The admin plugin's banUser endpoint is deliberately not+// used: it authorizes against the caller's session snapshot rather than the+// database, and the moderation auto-ban runs without an admin session at all.+// Authorization is the caller's responsibility.export async function banUser({userId,@@ -92,52 +117,35 @@ export async function banUser({userId: string;reason?: string;}) {- await authLib.api.banUser({- body: { userId, banReason: reason },- headers: await headers(),- });+ const { internalAdapter } = await authLib.$context;- await prisma.user.update({- where: { id: userId },- data: { bannedAt: new Date() },+ await internalAdapter.updateUser(userId, {+ banned: true,+ banReason: reason ?? null,+ updatedAt: new Date(),});-}-export async function unbanUser({ userId }: { userId: string }) {- await authLib.api.unbanUser({- body: { userId },- headers: await headers(),- });+ await internalAdapter.deleteSessions(userId);await prisma.user.update({where: { id: userId },- data: { bannedAt: null },+ data: { bannedAt: new Date() },});}-// For bans issued without an admin session (e.g. the moderation auto-ban).-// Mirrors what authLib.api.banUser does internally, minus the permission-// checks β authorization is the caller's responsibility.-export async function banUserAsSystem({- userId,- reason,-}: {- userId: string;- reason: string;-}) {+export async function unbanUser({ userId }: { userId: string }) {const { internalAdapter } = await authLib.$context;await internalAdapter.updateUser(userId, {- banned: true,- banReason: reason,+ banned: false,+ banReason: null,+ banExpires: null,updatedAt: new Date(),});- await internalAdapter.deleteSessions(userId);-await prisma.user.update({where: { id: userId },- data: { bannedAt: new Date() },+ data: { bannedAt: null },});}diff --git a/apps/web/src/lib/safe-action/server.ts b/apps/web/src/lib/safe-action/server.tsindex 08dad8f3e..3a309fa20 100644--- a/apps/web/src/lib/safe-action/server.ts+++ b/apps/web/src/lib/safe-action/server.ts@@ -1,6 +1,7 @@import "server-only";import * as Sentry from "@sentry/nextjs";+import { APIError } from "better-auth/api";import { createMiddleware, createSafeActionClient } from "next-safe-action";import * as z from "zod";import { defineAbilityFor } from "@/features/user/ability";@@ -79,6 +80,19 @@ export const actionClient = createSafeActionClient({return error.code;}+ if (error instanceof APIError) {+ switch (error.status) {+ case "UNAUTHORIZED":+ case "FORBIDDEN":+ case "NOT_FOUND":+ case "PAYMENT_REQUIRED":+ case "PAYLOAD_TOO_LARGE":+ case "TOO_MANY_REQUESTS":+ case "SERVICE_UNAVAILABLE":+ return error.status;+ }+ }+return "INTERNAL_SERVER_ERROR" as const;},}).use(async ({ next }) => {