fix(admin): the last-admin rule counts only admins who can sign in

Demoting an admin counted every admin, pending deletion included, so after
one admin deleted their account the other could step down and leave the
instance with no admin who can sign in or undo the deletion. Both the
demotion and an admin's own deletion now count the other admins not pending
deletion, inside the transaction that makes the change, under one roster
lock, so two at the same moment cannot each count the other.
This commit is contained in:
Marc-André Bombeck committed 2026-10-25 17:02:32 +01:00
1 parent 4137aa546e
commit b37e4f5df7
4 files changed
+126 -39

No files matched your search

+10
View File
@@ -22,6 +22,10 @@ import {
lockAccountForDeletion,
} from "@/lib/account-deletion/lifecycle";
import { ACTIVE_ACCOUNT } from "@/lib/account-deletion/active-account";
import {
assertAnotherAdminStays,
LastAdminError,
} from "@/lib/auth/admin-roster";
export const dynamic = "force-dynamic";
@@ -110,6 +114,9 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
await deleteGuardianAccountWithLifecycle(
userId,
async (tx) => {
// Checked again under the roster lock: two admins deleting at the
// same moment must not each count the other.
if (user.role === "ADMIN") await assertAnotherAdminStays(tx, userId);
// The invariant has now passed, so this success event cannot survive
// a refusal. On an immediate erasure it is purged with the rest of the
// account's audit history; during a grace window it is the account's
@@ -145,6 +152,9 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
{ erasing: purgeAt === null },
);
} catch (error) {
if (error instanceof LastAdminError) {
return apiError("The last admin account cannot be deleted", 400);
}
if (error instanceof LastManagedGuardianError) {
return apiError(
"Add another Guardian or delete the managed profile first",