Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(admin): harden the user administration panel (#1805)

Andrej962fe468fefb
diff --git a/apps/api/src/admin/controllers/list-users.ts b/apps/api/src/admin/controllers/list-users.ts
new file mode 100644
index 000000000..b15640388
--- /dev/null
+++ b/apps/api/src/admin/controllers/list-users.ts
@@ -0,0 +1,54 @@
+import { count, desc, ilike, or } from "drizzle-orm";
+import db from "../../database";
+import { userTable } from "../../database/schema";
+import { escapeLikePattern } from "../../search/like-pattern";
+
+type ListUsersInput = {
+ search?: string;
+ page: number;
+ limit: number;
+};
+
+export async function listUsers({ search, page, limit }: ListUsersInput) {
+ const term = search?.trim() ?? "";
+ const pattern = `%${escapeLikePattern(term)}%`;
+ const where = term
+ ? or(ilike(userTable.name, pattern), ilike(userTable.email, pattern))
+ : undefined;
+
+ const [rows, [totalRow]] = await Promise.all([
+ db
+ .select({
+ id: userTable.id,
+ name: userTable.name,
+ email: userTable.email,
+ emailVerified: userTable.emailVerified,
+ image: userTable.image,
+ createdAt: userTable.createdAt,
+ updatedAt: userTable.updatedAt,
+ role: userTable.role,
+ banned: userTable.banned,
+ banReason: userTable.banReason,
+ banExpires: userTable.banExpires,
+ })
+ .from(userTable)
+ .where(where)
+ .orderBy(desc(userTable.createdAt), desc(userTable.id))
+ .limit(limit)
+ .offset((page - 1) * limit),
+ db.select({ value: count() }).from(userTable).where(where),
+ ]);
+
+ return {
+ users: rows.map((row) => ({
+ ...row,
+ createdAt: row.createdAt.toISOString(),
+ updatedAt: row.updatedAt.toISOString(),
+ banned: row.banned ?? false,
+ banExpires: row.banExpires ? row.banExpires.toISOString() : null,
+ })),
+ total: totalRow?.value ?? 0,
+ };
+}
+
+export default listUsers;
diff --git a/apps/api/src/admin/index.ts b/apps/api/src/admin/index.ts
new file mode 100644
index 000000000..b3b0b69d2
--- /dev/null
+++ b/apps/api/src/admin/index.ts
@@ -0,0 +1,36 @@
+import {
+ apiRouter,
+ createRoute,
+ errorResponse,
+ jsonResponse,
+} from "../openapi";
+import { requireInstanceAdmin } from "../utils/require-instance-admin";
+import { requireUserSession } from "../utils/require-user-session";
+import listUsers from "./controllers/list-users";
+import { adminUserListSchema } from "./response";
+import { listAdminUsersQuery } from "./schema";
+
+const listUsersRoute = createRoute({
+ method: "get",
+ operationId: "listAdminUsers",
+ path: "/users",
+ tags: ["Admin"],
+ summary: "List instance users",
+ description:
+ "Page through every user account on this instance, optionally filtered by a case-insensitive name or email search. Requires an instance administrator session; API keys are rejected.",
+ middleware: [requireUserSession, requireInstanceAdmin] as const,
+ request: { query: listAdminUsersQuery },
+ responses: {
+ 200: jsonResponse("Users matching the search", adminUserListSchema),
+ 400: errorResponse("Invalid search, page, or limit"),
+ 403: errorResponse(
+ "The caller is not an instance administrator or is authenticated with an API key",
+ ),
+ },
+});
+
+const admin = apiRouter().openapi(listUsersRoute, async (c) =>
+ c.json(await listUsers(c.req.valid("query")), 200),
+);
+
+export default admin;
diff --git a/apps/api/src/admin/response.ts b/apps/api/src/admin/response.ts
new file mode 100644
index 000000000..adfb4f4d2
--- /dev/null
+++ b/apps/api/src/admin/response.ts
@@ -0,0 +1,28 @@
+import { z } from "../openapi";
+
+const isoTimestamp = z.string().openapi({ format: "date-time" });
+
+export const adminUserSchema = z
+ .object({
+ id: z.string(),
+ name: z.string(),
+ email: z.string(),
+ emailVerified: z.boolean(),
+ image: z.string().nullable(),
+ createdAt: isoTimestamp,
+ updatedAt: isoTimestamp,
+ role: z.string().nullable(),
+ banned: z.boolean(),
+ banReason: z.string().nullable(),
+ banExpires: isoTimestamp.nullable(),
+ })
+ .openapi("AdminUser");
+
+export const adminUserListSchema = z
+ .object({
+ users: z.array(adminUserSchema),
+ total: z.number().int().openapi({
+ description: "Number of users matching the search, across all pages.",
+ }),
+ })
+ .openapi("AdminUserList");
diff --git a/apps/api/src/admin/schema.ts b/apps/api/src/admin/schema.ts
new file mode 100644
index 000000000..9758c9f57
--- /dev/null
+++ b/apps/api/src/admin/schema.ts
@@ -0,0 +1,9 @@
+import { pagingNumber, z } from "../openapi";
+
+export const listAdminUsersQuery = z.object({
+ search: z.string().max(200).optional().openapi({
+ description: "Case-insensitive match against user name or email.",
+ }),
+ page: pagingNumber(1, 1_000_000, 1),
+ limit: pagingNumber(1, 100, 20),
+});
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index 45470e9d3..2d51506ec 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -44,7 +44,9 @@ import { syncWorkspaceSeats } from "./billing/controllers/sync-seats";
import db, { schema } from "./database";
import { authDatabaseAdapter } from "./database/auth-adapter";
import { publishEvent } from "./events";
+import clearEmailVerificationOnAdminChange from "./user/controllers/clear-email-verification-on-admin-change";
import deleteAccountData from "./user/controllers/delete-account-data";
+import prepareAdminUserRemoval from "./user/controllers/prepare-admin-user-removal";
import { resolveAuthSecret } from "./utils/auth-secret";
import {
canSendSignInEmail,
@@ -58,6 +60,7 @@ import { getDefaultCookieAttributes } from "./utils/get-default-cookie-attribute
import { getInvitationEmailSubject } from "./utils/get-invitation-email-subject";
import { getWorkspaceInvitationEmailCopy } from "./utils/get-workspace-invitation-email-copy";
import { getGithubSsoOAuthCredentials } from "./utils/github-sso-env";
+import { hasInstanceAdminRole } from "./utils/instance-admin-role";
import {
hasRegisteredUsers,
promoteInitialAdministrator,
@@ -405,7 +408,7 @@ export const auth = betterAuth({
},
},
// When `DISABLE_WORKSPACE_CREATION` is set, only instance admins
- // (`user.role === "admin"`) may create workspaces — mirrors the
+ // (role list includes "admin") may create workspaces — mirrors the
// implicit-exemption shape of `DISABLE_REGISTRATION` above. This
// check runs before any workspace membership exists, so only the
// instance-wide role is meaningful here; per-workspace roles
@@ -420,7 +423,7 @@ export const auth = betterAuth({
.select({ role: schema.userTable.role })
.from(schema.userTable)
.where(eq(schema.userTable.id, user.id));
- return freshUser?.role === "admin";
+ return hasInstanceAdminRole(freshUser?.role);
}
: true,
// Better Auth defaults this to `true`, which blocks any user whose email
@@ -613,6 +616,7 @@ export const auth = betterAuth({
message: "You cannot change your own role.",
});
}
+ return clearEmailVerificationOnAdminChange(user, ctx);
},
},
create: {
@@ -646,6 +650,10 @@ export const auth = betterAuth({
},
hooks: {
before: createAuthMiddleware(async (ctx) => {
+ if (ctx.path === "/admin/remove-user") {
+ await prepareAdminUserRemoval(ctx);
+ }
+
if (ctx.path === "/organization/invite-member") {
// Better Auth swallows email failures in runInBackgroundOrAwait.
// Invitation callers need the delivery result, including on resend.
diff --git a/apps/api/src/database/auth-adapter.ts b/apps/api/src/database/auth-adapter.ts
index 5bece4faa..1be25d551 100644
--- a/apps/api/src/database/auth-adapter.ts
+++ b/apps/api/src/database/auth-adapter.ts
@@ -6,12 +6,12 @@ import {
} from "better-auth/adapters/drizzle";
import { APIError } from "better-auth/api";
import { count, sql } from "drizzle-orm";
+import {
+ hasInstanceAdminRole,
+ instanceAdminRoleSql,
+} from "../utils/instance-admin-role";
import db, { schema } from ".";
-function isAdmin(role: unknown) {
- return typeof role === "string" && role.split(",").includes("admin");
-}
-
export function authDatabaseAdapter(config: DrizzleAdapterConfig) {
return (options: BetterAuthOptions): DBAdapter => {
const adapter = drizzleAdapter(db, config)(options);
@@ -21,7 +21,7 @@ export function authDatabaseAdapter(config: DrizzleAdapterConfig) {
if (
data.model !== "user" ||
!Object.hasOwn(data.update, "role") ||
- isAdmin(data.update.role)
+ hasInstanceAdminRole(data.update.role)
) {
return adapter.update<T>(data);
}
@@ -36,13 +36,11 @@ export function authDatabaseAdapter(config: DrizzleAdapterConfig) {
where: data.where,
});
- if (isAdmin(user?.role)) {
+ if (hasInstanceAdminRole(user?.role)) {
const [admins] = await tx
.select({ value: count() })
.from(schema.userTable)
- .where(
- sql`'admin' = ANY(string_to_array(${schema.userTable.role}, ','))`,
- );
+ .where(instanceAdminRoleSql(schema.userTable.role));
if ((admins?.value ?? 0) <= 1) {
throw new APIError("BAD_REQUEST", {
code: "CANNOT_REMOVE_LAST_ADMIN",
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index df71280f4..8c0eaa963 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -15,6 +15,7 @@ import { compress } from "hono/compress";
import { cors } from "hono/cors";
import { HTTPException } from "hono/http-exception";
import activity from "./activity";
+import admin from "./admin";
import { auth } from "./auth";
import { organizationRoutes } from "./auth-openapi";
import billing from "./billing";
@@ -82,6 +83,7 @@ import { normalizeApiServerUrl } from "./utils/openapi-spec";
import { seedDefaultWorkspaceRoles } from "./utils/seed-default-workspace-roles";
import { drainSignInEmails } from "./utils/sign-in-email-tasks";
import { validateWorkspaceAccess } from "./utils/validate-workspace-access";
+import { verifyApiKey } from "./utils/verify-api-key";
import workflowRule from "./workflow-rule";
import workspace from "./workspace";
import {
@@ -391,6 +393,14 @@ export function createApp() {
return c.json(result);
});
+ api.use("/auth/*", async (c, next) => {
+ const apiKeyHeader = c.req.header("x-api-key")?.trim();
+ if (apiKeyHeader && !(await verifyApiKey(apiKeyHeader))) {
+ throw new HTTPException(401, { message: "Unauthorized" });
+ }
+ return next();
+ });
+
api.openapi(
createRoute({
method: "get",
@@ -659,29 +669,27 @@ export function createApp() {
api.on(["POST", "GET", "PUT", "PATCH", "DELETE"], "/auth/*", async (c) => {
const authHeader = c.req.header("Authorization");
- const apiKeyHeader = c.req.header("x-api-key");
+ const apiKeyHeader = c.req.header("x-api-key")?.trim();
const bearerToken = authHeader?.match(/^Bearer\s+(\S+)$/i)?.[1];
if (bearerToken && !apiKeyHeader) {
- const session = await auth.api.getSession({
- headers: c.req.raw.headers,
- });
+ const headers = new Headers(c.req.raw.headers);
+ headers.delete("cookie");
+ const session = await auth.api.getSession({ headers });
// Preserve Better Auth bearer session tokens on auth routes.
if (session?.session && session.user) {
- return auth.handler(c.req.raw);
+ return auth.handler(new Request(c.req.raw, { headers }));
}
- const headers = new Headers(c.req.raw.headers);
+ if (!(await verifyApiKey(bearerToken))) {
+ throw new HTTPException(401, { message: "Unauthorized" });
+ }
// Better Auth API key plugin validates from x-api-key by default.
headers.set("x-api-key", bearerToken);
- return auth.handler(
- new Request(c.req.raw, {
- headers,
- }),
- );
+ return auth.handler(new Request(c.req.raw, { headers }));
}
return auth.handler(c.req.raw);
@@ -768,6 +776,7 @@ export function createApp() {
const workspaceApi = api.route("/workspace", workspace);
const customFieldApi = api.route("/custom-field", customField);
const userApi = api.route("/user", user);
+ const adminApi = api.route("/admin", admin);
app.route(
"/",
@@ -907,6 +916,7 @@ export function createApp() {
telegramIntegrationApi,
timeEntryApi,
userApi,
+ adminApi,
workflowRuleApi,
workspaceApi,
customFieldApi,
@@ -1036,6 +1046,7 @@ const {
telegramIntegrationApi,
timeEntryApi,
userApi,
+ adminApi,
workflowRuleApi,
workspaceApi,
customFieldApi,
@@ -1081,6 +1092,7 @@ export type AppType =
| typeof workspaceApi
| typeof customFieldApi
| typeof userApi
+ | typeof adminApi
| typeof publicProjectApi
| typeof invitationPublicApi
| typeof oauthApi;
diff --git a/apps/api/src/instance/controllers/get-instance-status.ts b/apps/api/src/instance/controllers/get-instance-status.ts
index 8af1ad21b..9fcdfebbd 100644
--- a/apps/api/src/instance/controllers/get-instance-status.ts
+++ b/apps/api/src/instance/controllers/get-instance-status.ts
@@ -1,5 +1,6 @@
-import { count, eq } from "drizzle-orm";
+import { count } from "drizzle-orm";
import db, { schema } from "../../database";
+import { instanceAdminRoleSql } from "../../utils/instance-admin-role";
import { hasRegisteredUsers } from "../../utils/instance-bootstrap";
export type InstanceStatus = {
@@ -12,7 +13,7 @@ async function getInstanceStatus(): Promise<InstanceStatus> {
const [adminRow] = await db
.select({ value: count() })
.from(schema.userTable)
- .where(eq(schema.userTable.role, "admin"));
+ .where(instanceAdminRoleSql(schema.userTable.role));
return {
hasUsers,
diff --git a/apps/api/src/mcp/index.ts b/apps/api/src/mcp/index.ts
index c59beb820..48e0d47d8 100644
--- a/apps/api/src/mcp/index.ts
+++ b/apps/api/src/mcp/index.ts
@@ -9,6 +9,7 @@ import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { auth } from "../auth";
import { apiRouter, createRoute, jsonResponse } from "../openapi";
+import { type BanState, isBanActive } from "../utils/user-ban";
import {
beginMcpAuthorization,
decideMcpAuthorizationRequest,
@@ -69,6 +70,7 @@ async function validateBearerToken(
const session = await auth.api.getSession({ headers });
if (!session?.user?.id) return null;
+ if (isBanActive(session.user as BanState)) return null;
return { userId: session.user.id, token };
}
diff --git a/apps/api/src/openapi.ts b/apps/api/src/openapi.ts
index 47051ae1f..392989137 100644
--- a/apps/api/src/openapi.ts
+++ b/apps/api/src/openapi.ts
@@ -38,6 +38,22 @@ export function apiRouter<V extends BaseVariables = BaseVariables>() {
});
}
+export const pagingNumber = (min: number, max: number, fallback?: number) => {
+ const parsed = z
+ .string()
+ .regex(/^\d+$/, "Expected a positive integer")
+ .transform(Number)
+ .pipe(z.number().int().min(min).max(max));
+ return fallback === undefined
+ ? parsed.openapi({ type: "integer", minimum: min, maximum: max })
+ : parsed.default(fallback).openapi({
+ type: "integer",
+ minimum: min,
+ maximum: max,
+ default: fallback,
+ });
+};
+
export const responseTimestamp = z
.date()
.openapi({ type: "string", format: "date-time" });
diff --git a/apps/api/src/task/schema.ts b/apps/api/src/task/schema.ts
index 654ad808d..ae8fcdc50 100644
--- a/apps/api/src/task/schema.ts
+++ b/apps/api/src/task/schema.ts
@@ -1,14 +1,7 @@
-import { z } from "../openapi";
+import { pagingNumber, z } from "../openapi";
import { MAX_TASK_POSITION } from "./controllers/next-task-position";
import { VALID_PRIORITIES } from "./validate-task-fields";
-const pagingNumber = (min: number, max: number) =>
- z
- .string()
- .regex(/^\d+$/, "Expected a positive integer")
- .transform(Number)
- .pipe(z.number().int().min(min).max(max));
-
export const taskParam = z.object({ id: z.string() });
export const projectIdParam = z.object({ projectId: z.string() });
@@ -129,7 +122,7 @@ export const finalizeImageUploadBody = z.object({
});
export const descriptionPageQuery = z.object({
- offset: pagingNumber(0, 2_000_000_000).default(0),
+ offset: pagingNumber(0, 2_000_000_000, 0),
version: z
.string()
.regex(/^[0-9]{1,10}$/)
diff --git a/apps/api/src/user/controllers/clear-email-verification-on-admin-change.ts b/apps/api/src/user/controllers/clear-email-verification-on-admin-change.ts
new file mode 100644
index 000000000..c85b076ff
--- /dev/null
+++ b/apps/api/src/user/controllers/clear-email-verification-on-admin-change.ts
@@ -0,0 +1,37 @@
+import { eq } from "drizzle-orm";
+import db, { schema } from "../../database";
+
+type UpdateHookContext = {
+ path?: string;
+ body?: { userId?: unknown };
+};
+
+export async function clearEmailVerificationOnAdminChange(
+ data: Record<string, unknown>,
+ ctx: UpdateHookContext | null | undefined,
+) {
+ if (ctx?.path !== "/admin/update-user" || !("email" in data)) {
+ return;
+ }
+ const userId = ctx.body?.userId;
+ if (typeof userId !== "string") {
+ return;
+ }
+ const [current] = await db
+ .select({ email: schema.userTable.email })
+ .from(schema.userTable)
+ .where(eq(schema.userTable.id, userId))
+ .limit(1);
+ if (!current) {
+ return;
+ }
+ const nextEmail = String(data.email ?? "")
+ .trim()
+ .toLowerCase();
+ if (nextEmail === current.email.trim().toLowerCase()) {
+ return;
+ }
+ return { data: { ...data, emailVerified: false } };
+}
+
+export default clearEmailVerificationOnAdminChange;
diff --git a/apps/api/src/user/controllers/prepare-admin-user-removal.ts b/apps/api/src/user/controllers/prepare-admin-user-removal.ts
new file mode 100644
index 000000000..987483582
--- /dev/null
+++ b/apps/api/src/user/controllers/prepare-admin-user-removal.ts
@@ -0,0 +1,34 @@
+import { APIError, getSessionFromCtx } from "better-auth/api";
+import { hasInstanceAdminRole } from "../../utils/instance-admin-role";
+import deleteAccountData from "./delete-account-data";
+
+type RemovalContext = Parameters<typeof getSessionFromCtx>[0];
+
+export async function prepareAdminUserRemoval(ctx: RemovalContext) {
+ const session = await getSessionFromCtx(ctx, {
+ disableCookieCache: true,
+ disableRefresh: true,
+ });
+ const caller = session?.user as { id: string; role?: unknown } | undefined;
+
+ if (!caller || !hasInstanceAdminRole(caller.role)) {
+ throw new APIError("FORBIDDEN", {
+ message: "Only instance administrators can remove users.",
+ });
+ }
+
+ const userId = (ctx.body as { userId?: unknown } | undefined)?.userId;
+ if (typeof userId !== "string" || userId === "") {
+ return;
+ }
+
+ if (userId === caller.id) {
+ throw new APIError("BAD_REQUEST", {
+ message: "You cannot remove yourself.",
+ });
+ }
+
+ await deleteAccountData(userId);
+}
+
+export default prepareAdminUserRemoval;
diff --git a/apps/api/src/utils/assert-assignable-user.ts b/apps/api/src/utils/assert-assignable-user.ts
index a563ee4df..eb0640a49 100644
--- a/apps/api/src/utils/assert-assignable-user.ts
+++ b/apps/api/src/utils/assert-assignable-user.ts
@@ -1,6 +1,7 @@
import { and, eq, inArray } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db, { schema } from "../database";
+import { instanceAdminRoleSql } from "./instance-admin-role";
const NOT_ASSIGNABLE = "Assignee is not a member of this workspace";
@@ -35,7 +36,7 @@ export async function filterAssignableUsers(
.where(
and(
inArray(schema.userTable.id, remaining),
- eq(schema.userTable.role, "admin"),
+ instanceAdminRoleSql(schema.userTable.role),
),
);
diff --git a/apps/api/src/utils/instance-admin-role.ts b/apps/api/src/utils/instance-admin-role.ts
new file mode 100644
index 000000000..f91ec3265
--- /dev/null
+++ b/apps/api/src/utils/instance-admin-role.ts
@@ -0,0 +1,9 @@
+import { type AnyColumn, sql } from "drizzle-orm";
+
+export function hasInstanceAdminRole(role: unknown) {
+ return typeof role === "string" && role.split(",").includes("admin");
+}
+
+export function instanceAdminRoleSql(column: AnyColumn) {
+ return sql`'admin' = ANY(string_to_array(${column}, ','))`;
+}
diff --git a/apps/api/src/utils/instance-bootstrap.ts b/apps/api/src/utils/instance-bootstrap.ts
index 512f5cfcc..dc890de9d 100644
--- a/apps/api/src/utils/instance-bootstrap.ts
+++ b/apps/api/src/utils/instance-bootstrap.ts
@@ -1,5 +1,6 @@
import { and, asc, count, eq, sql } from "drizzle-orm";
import db, { schema } from "../database";
+import { instanceAdminRoleSql } from "./instance-admin-role";
export const nonAnonymousUser = sql`${schema.userTable.isAnonymous} IS NOT TRUE`;
@@ -19,7 +20,7 @@ export async function promoteInitialAdministrator(
const [admin] = await tx
.select({ id: schema.userTable.id })
.from(schema.userTable)
- .where(and(nonAnonymousUser, eq(schema.userTable.role, "admin")))
+ .where(and(nonAnonymousUser, instanceAdminRoleSql(schema.userTable.role)))
.limit(1);
if (admin) return;
diff --git a/apps/api/src/utils/is-instance-admin.ts b/apps/api/src/utils/is-instance-admin.ts
index 7e39f7436..8a96047c2 100644
--- a/apps/api/src/utils/is-instance-admin.ts
+++ b/apps/api/src/utils/is-instance-admin.ts
@@ -2,11 +2,14 @@ import { eq } from "drizzle-orm";
import type { Context } from "hono";
import db from "../database";
import { userTable } from "../database/schema";
+import { hasInstanceAdminRole } from "./instance-admin-role";
+
+export { hasInstanceAdminRole };
export async function isInstanceAdmin(c: Context): Promise<boolean> {
const user = c.get("user") as { role?: string | null } | null | undefined;
if (user?.role) {
- return user.role === "admin";
+ return hasInstanceAdminRole(user.role);
}
const userId = c.get("userId");
@@ -18,5 +21,5 @@ export async function isInstanceAdmin(c: Context): Promise<boolean> {
.where(eq(userTable.id, userId))
.limit(1);
- return row?.role === "admin";
+ return hasInstanceAdminRole(row?.role);
}
diff --git a/apps/api/src/utils/require-instance-admin.ts b/apps/api/src/utils/require-instance-admin.ts
new file mode 100644
index 000000000..bd5898965
--- /dev/null
+++ b/apps/api/src/utils/require-instance-admin.ts
@@ -0,0 +1,12 @@
+import type { Context, Next } from "hono";
+import { HTTPException } from "hono/http-exception";
+import { isInstanceAdmin } from "./is-instance-admin";
+
+export async function requireInstanceAdmin(c: Context, next: Next) {
+ if (!(await isInstanceAdmin(c))) {
+ throw new HTTPException(403, {
+ message: "Instance administrator access is required",
+ });
+ }
+ return next();
+}
diff --git a/apps/api/src/utils/user-ban.ts b/apps/api/src/utils/user-ban.ts
new file mode 100644
index 000000000..7247203c9
--- /dev/null
+++ b/apps/api/src/utils/user-ban.ts
@@ -0,0 +1,28 @@
+import { and, eq, isNotNull, isNull, lt, or } from "drizzle-orm";
+import { schema } from "../database";
+
+export type BanState = {
+ banned?: boolean | null;
+ banExpires?: Date | string | null;
+};
+
+export function isBanActive(user: BanState | null | undefined) {
+ if (!user?.banned) {
+ return false;
+ }
+ if (!user.banExpires) {
+ return true;
+ }
+ return new Date(user.banExpires).getTime() >= Date.now();
+}
+
+export function notBannedCondition() {
+ return or(
+ isNull(schema.userTable.banned),
+ eq(schema.userTable.banned, false),
+ and(
+ isNotNull(schema.userTable.banExpires),
+ lt(schema.userTable.banExpires, new Date()),
+ ),
+ );
+}
diff --git a/apps/api/src/utils/validate-workspace-access.ts b/apps/api/src/utils/validate-workspace-access.ts
index 76d2a19c4..9300f53be 100644
--- a/apps/api/src/utils/validate-workspace-access.ts
+++ b/apps/api/src/utils/validate-workspace-access.ts
@@ -1,6 +1,7 @@
import { and, eq, or } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db, { schema } from "../database";
+import { hasInstanceAdminRole } from "./instance-admin-role";
export async function validateWorkspaceAccess(
userId: string,
@@ -36,7 +37,7 @@ export async function validateWorkspaceAccess(
.where(eq(schema.userTable.id, userId))
.limit(1);
- if (user?.role === "admin") {
+ if (hasInstanceAdminRole(user?.role)) {
return;
}
diff --git a/apps/api/src/utils/verify-api-key.ts b/apps/api/src/utils/verify-api-key.ts
index 597d413e7..09035be75 100644
--- a/apps/api/src/utils/verify-api-key.ts
+++ b/apps/api/src/utils/verify-api-key.ts
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import { and, eq, exists, gt, isNull, or, sql } from "drizzle-orm";
import db, { schema } from "../database";
+import { notBannedCondition } from "./user-ban";
async function hashApiKey(key: string): Promise<string> {
const hash = createHash("sha256").update(key).digest();
@@ -52,9 +53,12 @@ export async function verifyApiKey(key: string) {
.select({ id: schema.userTable.id })
.from(schema.userTable)
.where(
- eq(
- schema.userTable.id,
- sql`coalesce(${schema.apikeyTable.referenceId}, ${schema.apikeyTable.userId})`,
+ and(
+ eq(
+ schema.userTable.id,
+ sql`coalesce(${schema.apikeyTable.referenceId}, ${schema.apikeyTable.userId})`,
+ ),
+ notBannedCondition(),
),
),
),
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index ec2f6ea71..abc0b0e79 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -3925,6 +3925,91 @@
"required": [
"deleted"
]
+ },
+ "AdminUserList": {
+ "type": "object",
+ "properties": {
+ "users": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AdminUser"
+ }
+ },
+ "total": {
+ "type": "integer",
+ "description": "Number of users matching the search, across all pages."
+ }
+ },
+ "required": [
+ "users",
+ "total"
+ ]
+ },
+ "AdminUser": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "email": {
+ "type": "string"
+ },
+ "emailVerified": {
+ "type": "boolean"
+ },
+ "image": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "role": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "banned": {
+ "type": "boolean"
+ },
+ "banReason": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "banExpires": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "date-time"
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "email",
+ "emailVerified",
+ "image",
+ "createdAt",
+ "updatedAt",
+ "role",
+ "banned",
+ "banReason",
+ "banExpires"
+ ]
}
},
"parameters": {}
@@ -3997,8 +4082,9 @@
},
{
"schema": {
- "type": "string",
- "pattern": "^\\d+$"
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 1000000
},
"required": false,
"name": "page",
@@ -4006,8 +4092,9 @@
},
{
"schema": {
- "type": "string",
- "pattern": "^\\d+$"
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 1000000
},
"required": false,
"name": "relatedPage",
@@ -4015,8 +4102,9 @@
},
{
"schema": {
- "type": "string",
- "pattern": "^\\d+$"
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 100
},
"required": false,
"name": "limit",
@@ -4140,8 +4228,9 @@
},
{
"schema": {
- "type": "string",
- "pattern": "^\\d+$",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2000000000,
"default": 0
},
"required": false,
@@ -4239,8 +4328,9 @@
},
{
"schema": {
- "type": "string",
- "pattern": "^\\d+$",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2000000000,
"default": 0
},
"required": false,
@@ -8026,8 +8116,9 @@
},
{
"schema": {
- "type": "string",
- "pattern": "^\\d+$",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2000000000,
"default": 0
},
"required": false,
@@ -8238,8 +8329,9 @@
},
{
"schema": {
- "type": "string",
- "pattern": "^\\d+$"
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 1000000
},
"required": false,
"name": "page",
@@ -8247,8 +8339,9 @@
},
{
"schema": {
- "type": "string",
- "pattern": "^\\d+$"
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 1000000
},
"required": false,
"name": "relatedPage",
@@ -8256,8 +8349,9 @@
},
{
"schema": {
- "type": "string",
- "pattern": "^\\d+$"
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 100
},
"required": false,
"name": "limit",
@@ -17202,6 +17296,86 @@
}
}
}
+ },
+ "/admin/users": {
+ "get": {
+ "operationId": "listAdminUsers",
+ "tags": [
+ "Admin"
+ ],
+ "summary": "List instance users",
+ "description": "Page through every user account on this instance, optionally filtered by a case-insensitive name or email search. Requires an instance administrator session; API keys are rejected.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string",
+ "maxLength": 200,
+ "description": "Case-insensitive match against user name or email."
+ },
+ "required": false,
+ "description": "Case-insensitive match against user name or email.",
+ "name": "search",
+ "in": "query"
+ },
+ {
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 1000000,
+ "default": 1
+ },
+ "required": false,
+ "name": "page",
+ "in": "query"
+ },
+ {
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 100,
+ "default": 20
+ },
+ "required": false,
+ "name": "limit",
+ "in": "query"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Users matching the search",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AdminUserList"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid search, page, or limit",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "The caller is not an instance administrator or is authenticated with an API key",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
}
},
"webhooks": {}
diff --git a/apps/web/src/components/admin/user-management-panel.test.tsx b/apps/web/src/components/admin/user-management-panel.test.tsx
new file mode 100644
index 000000000..22cb4a905
--- /dev/null
+++ b/apps/web/src/components/admin/user-management-panel.test.tsx
@@ -0,0 +1,234 @@
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import useAdminUsers, {
+ type AdminUser,
+} from "@/hooks/queries/admin/use-admin-users";
+import UserManagementPanel from "./user-management-panel";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+ initReactI18next: { type: "3rdParty", init: () => {} },
+}));
+vi.mock("@/components/providers/auth-provider/hooks/use-auth", () => ({
+ default: () => ({ user: { id: "current-user" } }),
+}));
+vi.mock("@/hooks/queries/admin/use-admin-users", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@/hooks/queries/admin/use-admin-users")
+ >()),
+ default: vi.fn(),
+}));
+const { updateUserMock } = vi.hoisted(() => ({
+ updateUserMock: vi.fn(),
+}));
+vi.mock("@/hooks/mutations/admin/use-update-admin-user", () => ({
+ default: () => ({ mutateAsync: updateUserMock, isPending: false }),
+}));
+vi.mock("@/hooks/mutations/admin/use-toggle-admin-user-status", () => ({
+ default: () => ({ mutateAsync: vi.fn(), isPending: false }),
+}));
+vi.mock("@/hooks/mutations/admin/use-delete-admin-user", () => ({
+ default: () => ({ mutateAsync: vi.fn(), isPending: false }),
+}));
+
+const useAdminUsersMock = vi.mocked(useAdminUsers);
+
+function user(overrides: Partial<AdminUser> = {}): AdminUser {
+ return {
+ id: "user-1",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ emailVerified: true,
+ image: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ role: "user",
+ banned: false,
+ banReason: null,
+ banExpires: null,
+ ...overrides,
+ };
+}
+
+function success(total: number, users: AdminUser[] = [user()]) {
+ return {
+ data: { users, total },
+ isLoading: false,
+ isFetching: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ } as unknown as ReturnType<typeof useAdminUsers>;
+}
+
+function failure() {
+ return {
+ data: undefined,
+ isLoading: false,
+ isFetching: false,
+ isError: true,
+ error: new Error("x"),
+ refetch: vi.fn(),
+ } as unknown as ReturnType<typeof useAdminUsers>;
+}
+
+function lastPageArgument() {
+ const call = useAdminUsersMock.mock.calls.at(-1);
+ return call?.[1];
+}
+
+function goToThirdPage() {
+ const next = screen.getByRole("button", { name: "settings:adminUsers.next" });
+ fireEvent.click(next);
+ fireEvent.click(next);
+ expect(lastPageArgument()).toBe(2);
+}
+
+function openEditDialog() {
+ fireEvent.click(
+ screen.getByRole("button", { name: "settings:adminUsers.actions.open" }),
+ );
+ fireEvent.click(screen.getByText("settings:adminUsers.actions.edit"));
+ const trigger = document.getElementById("admin-user-role");
+ expect(trigger).not.toBeNull();
+ return trigger as HTMLElement;
+}
+
+async function selectRole(trigger: HTMLElement, role: "admin" | "user") {
+ fireEvent.click(trigger, { detail: 1 });
+ const option = await screen.findByRole("option", {
+ name: `settings:adminUsers.roles.${role}`,
+ });
+ fireEvent.pointerDown(option);
+ fireEvent.mouseDown(option);
+ fireEvent.pointerUp(option);
+ fireEvent.mouseUp(option);
+ fireEvent.click(option, { detail: 1 });
+}
+
+function submitEdit() {
+ fireEvent.click(
+ screen.getByRole("button", { name: "settings:adminUsers.edit.save" }),
+ );
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ useAdminUsersMock.mockReset();
+ updateUserMock.mockReset();
+ updateUserMock.mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+describe("UserManagementPanel", () => {
+ it("keeps the current page when the query fails", () => {
+ useAdminUsersMock.mockReturnValue(success(60));
+ const view = render(<UserManagementPanel />);
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ goToThirdPage();
+
+ useAdminUsersMock.mockReturnValue(failure());
+ view.rerender(<UserManagementPanel />);
+
+ expect(screen.getByText("settings:adminUsers.loadError")).toBeTruthy();
+ expect(lastPageArgument()).toBe(2);
+ });
+
+ it("clamps an out-of-range page once a smaller result set arrives", () => {
+ useAdminUsersMock.mockReturnValue(success(60));
+ const view = render(<UserManagementPanel />);
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ goToThirdPage();
+
+ useAdminUsersMock.mockReturnValue(success(20));
+ view.rerender(<UserManagementPanel />);
+
+ expect(lastPageArgument()).toBe(0);
+ });
+
+ it("treats a comma-separated role containing admin as an instance admin", () => {
+ useAdminUsersMock.mockReturnValue(
+ success(1, [user({ role: "user,admin" })]),
+ );
+ render(<UserManagementPanel />);
+
+ const badge = screen.getByText("settings:adminUsers.roles.admin");
+ expect(badge.closest('[data-slot="badge"]')).not.toBeNull();
+
+ const trigger = openEditDialog();
+ expect(trigger.textContent).toContain("settings:adminUsers.roles.admin");
+ expect(trigger.textContent).not.toContain("settings:adminUsers.roles.user");
+ });
+
+ it("omits the role when a multi-role account is edited without changing it", async () => {
+ vi.useRealTimers();
+ useAdminUsersMock.mockReturnValue(
+ success(1, [user({ role: "user,admin" })]),
+ );
+ render(<UserManagementPanel />);
+
+ openEditDialog();
+ submitEdit();
+
+ await waitFor(() => expect(updateUserMock).toHaveBeenCalledTimes(1));
+ expect(updateUserMock).toHaveBeenCalledWith({
+ userId: "user-1",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ });
+ expect(updateUserMock.mock.calls[0]?.[0]).not.toHaveProperty("role");
+ });
+
+ it("strips only the admin token when a multi-role account is demoted", async () => {
+ vi.useRealTimers();
+ useAdminUsersMock.mockReturnValue(
+ success(1, [user({ role: "user,admin" })]),
+ );
+ render(<UserManagementPanel />);
+
+ const trigger = openEditDialog();
+ await selectRole(trigger, "user");
+ submitEdit();
+
+ await waitFor(() => expect(updateUserMock).toHaveBeenCalledTimes(1));
+ expect(updateUserMock).toHaveBeenCalledWith({
+ userId: "user-1",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ role: "user",
+ });
+ });
+
+ it("appends the admin token when a plain user is promoted", async () => {
+ vi.useRealTimers();
+ useAdminUsersMock.mockReturnValue(success(1, [user({ role: "user" })]));
+ render(<UserManagementPanel />);
+
+ const trigger = openEditDialog();
+ await selectRole(trigger, "admin");
+ submitEdit();
+
+ await waitFor(() => expect(updateUserMock).toHaveBeenCalledTimes(1));
+ expect(updateUserMock).toHaveBeenCalledWith({
+ userId: "user-1",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ role: "user,admin",
+ });
+ });
+});
diff --git a/apps/web/src/components/admin/user-management-panel.tsx b/apps/web/src/components/admin/user-management-panel.tsx
index 6d20b09e7..98fe363af 100644
--- a/apps/web/src/components/admin/user-management-panel.tsx
+++ b/apps/web/src/components/admin/user-management-panel.tsx
@@ -72,9 +72,15 @@ import useToggleAdminUserStatus from "@/hooks/mutations/admin/use-toggle-admin-u
import useUpdateAdminUser from "@/hooks/mutations/admin/use-update-admin-user";
import useAdminUsers, {
ADMIN_USERS_PAGE_SIZE,
+ ADMIN_USERS_SEARCH_MAX_LENGTH,
type AdminUser,
} from "@/hooks/queries/admin/use-admin-users";
import { formatDateMedium } from "@/lib/format";
+import { getInitials } from "@/lib/get-initials";
+import {
+ hasInstanceAdminRole,
+ withInstanceAdminRole,
+} from "@/lib/instance-admin";
type PendingAction = {
type: "deactivate" | "reactivate" | "delete";
@@ -87,17 +93,6 @@ type EditValues = {
role: "admin" | "user";
};
-function getUserInitials(name: string) {
- return (
- name
- .split(/\s+/)
- .filter(Boolean)
- .slice(0, 2)
- .map((part) => part[0]?.toUpperCase())
- .join("") || "?"
- );
-}
-
function UserManagementPanel() {
const { t } = useTranslation();
const { user: currentUser } = useAuth();
@@ -118,6 +113,31 @@ function UserManagementPanel() {
debouncedSearch,
page,
);
+ const confirmCopy = pendingAction
+ ? {
+ deactivate: {
+ title: t("settings:adminUsers.confirm.deactivate.title"),
+ description: t("settings:adminUsers.confirm.deactivate.description", {
+ name: pendingAction.user.name,
+ }),
+ action: t("settings:adminUsers.confirm.deactivate.action"),
+ },
+ reactivate: {
+ title: t("settings:adminUsers.confirm.reactivate.title"),
+ description: t("settings:adminUsers.confirm.reactivate.description", {
+ name: pendingAction.user.name,
+ }),
+ action: t("settings:adminUsers.confirm.reactivate.action"),
+ },
+ delete: {
+ title: t("settings:adminUsers.confirm.delete.title"),
+ description: t("settings:adminUsers.confirm.delete.description", {
+ name: pendingAction.user.name,
+ }),
+ action: t("settings:adminUsers.confirm.delete.action"),
+ },
+ }[pendingAction.type]
+ : null;
const { mutateAsync: updateUser, isPending: isUpdating } =
useUpdateAdminUser();
const { mutateAsync: toggleUserStatus, isPending: isTogglingStatus } =
@@ -139,7 +159,7 @@ function UserManagementPanel() {
setEditValues({
name: editingUser.name,
email: editingUser.email,
- role: editingUser.role === "admin" ? "admin" : "user",
+ role: hasInstanceAdminRole(editingUser.role) ? "admin" : "user",
});
}, [editingUser]);
@@ -149,10 +169,10 @@ function UserManagementPanel() {
const isBusy = isTogglingStatus || isDeleting;
useEffect(() => {
- if (page >= pageCount) {
+ if (data && page >= pageCount) {
setPage(pageCount - 1);
}
- }, [page, pageCount]);
+ }, [data, page, pageCount]);
const handleEditSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
@@ -162,13 +182,18 @@ function UserManagementPanel() {
const email = editValues.email.trim().toLowerCase();
if (!name || !email) return;
+ const wantsAdmin = editValues.role === "admin";
+ const roleChanged =
+ editingUser.id !== currentUser?.id &&
+ hasInstanceAdminRole(editingUser.role) !== wantsAdmin;
+
try {
await updateUser({
userId: editingUser.id,
name,
email,
- ...(editingUser.id !== currentUser?.id
- ? { role: editValues.role }
+ ...(roleChanged
+ ? { role: withInstanceAdminRole(editingUser.role, wantsAdmin) }
: {}),
});
setEditingUser(null);
@@ -245,6 +270,7 @@ function UserManagementPanel() {
type="search"
value={search}
onChange={(event) => setSearch(event.target.value)}
+ maxLength={ADMIN_USERS_SEARCH_MAX_LENGTH}
placeholder={t("settings:adminUsers.searchPlaceholder")}
aria-label={t("settings:adminUsers.searchLabel")}
/>
@@ -336,7 +362,7 @@ function UserManagementPanel() {
{!isLoading && !isError
? data?.users.map((managedUser) => {
const isSelf = managedUser.id === currentUser?.id;
- const isAdmin = managedUser.role === "admin";
+ const isAdmin = hasInstanceAdminRole(managedUser.role);
const isDeactivated = managedUser.banned === true;
return (
@@ -351,7 +377,7 @@ function UserManagementPanel() {
/>
) : null}
<AvatarFallback className="text-xs font-medium">
- {getUserInitials(managedUser.name)}
+ {getInitials(managedUser.name, "?")}
</AvatarFallback>
</Avatar>
<div className="min-w-0">
@@ -646,18 +672,9 @@ function UserManagementPanel() {
>
<AlertDialogPopup>
<AlertDialogHeader>
- <AlertDialogTitle>
- {pendingAction
- ? t(`settings:adminUsers.confirm.${pendingAction.type}.title`)
- : ""}
- </AlertDialogTitle>
+ <AlertDialogTitle>{confirmCopy?.title ?? ""}</AlertDialogTitle>
<AlertDialogDescription>
- {pendingAction
- ? t(
- `settings:adminUsers.confirm.${pendingAction.type}.description`,
- { name: pendingAction.user.name },
- )
- : ""}
+ {confirmCopy?.description ?? ""}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
@@ -677,11 +694,7 @@ function UserManagementPanel() {
>
{isBusy
? t("settings:adminUsers.confirm.working")
- : pendingAction
- ? t(
- `settings:adminUsers.confirm.${pendingAction.type}.action`,
- )
- : ""}
+ : (confirmCopy?.action ?? "")}
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
diff --git a/apps/web/src/components/command-palette/index.tsx b/apps/web/src/components/command-palette/index.tsx
index 0f79ff8ca..48742912c 100644
--- a/apps/web/src/components/command-palette/index.tsx
+++ b/apps/web/src/components/command-palette/index.tsx
@@ -27,6 +27,7 @@ import useGetConfig from "@/hooks/queries/config/use-get-config";
import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";
import { useRegisterShortcuts } from "@/hooks/use-keyboard-shortcuts";
import { authClient } from "@/lib/auth-client";
+import { hasInstanceAdminRole } from "@/lib/instance-admin";
import { useUserPreferencesStore } from "@/store/user-preferences";
import CreateProjectModal from "../shared/modals/create-project-modal";
@@ -51,7 +52,7 @@ function CommandPalette() {
const { data: workspace } = useActiveWorkspace();
const { data: session } = authClient.useSession();
const { data: config } = useGetConfig();
- const isAdmin = session?.user?.role === "admin";
+ const isAdmin = hasInstanceAdminRole(session?.user?.role);
const canCreateWorkspace =
isAdmin || (config !== undefined && !config.disableWorkspaceCreation);
const [open, setOpen] = useState(false);
diff --git a/apps/web/src/components/workspace-switcher.tsx b/apps/web/src/components/workspace-switcher.tsx
index 5dc9a4877..15eb51313 100644
--- a/apps/web/src/components/workspace-switcher.tsx
+++ b/apps/web/src/components/workspace-switcher.tsx
@@ -29,6 +29,7 @@ import {
} from "@/hooks/use-keyboard-shortcuts";
import { useUserWebSocket } from "@/hooks/use-user-websocket";
import { authClient } from "@/lib/auth-client";
+import { hasInstanceAdminRole } from "@/lib/instance-admin";
import type { Workspace } from "@/types/workspace";
import CreateWorkspaceModal from "./shared/modals/create-workspace-modal";
@@ -41,7 +42,7 @@ export function WorkspaceSwitcher() {
const { data: workspaces } = useGetWorkspaces();
const { data: session } = authClient.useSession();
const { data: config } = useGetConfig();
- const isAdmin = session?.user?.role === "admin";
+ const isAdmin = hasInstanceAdminRole(session?.user?.role);
const canCreateWorkspace =
isAdmin || (config !== undefined && !config.disableWorkspaceCreation);
const navigate = useNavigate();
diff --git a/apps/web/src/fetchers/admin/get-admin-access.test.ts b/apps/web/src/fetchers/admin/get-admin-access.test.ts
new file mode 100644
index 000000000..eea0610f7
--- /dev/null
+++ b/apps/web/src/fetchers/admin/get-admin-access.test.ts
@@ -0,0 +1,39 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { hasPermission } = vi.hoisted(() => ({ hasPermission: vi.fn() }));
+
+vi.mock("@/lib/auth-client", () => ({
+ authClient: { admin: { hasPermission } },
+}));
+
+import { getAdminAccess } from "./get-admin-access";
+
+describe("getAdminAccess", () => {
+ beforeEach(() => {
+ hasPermission.mockReset();
+ });
+
+ it.each([401, 403])("resolves to false on %d", async (status) => {
+ hasPermission.mockResolvedValue({
+ data: null,
+ error: { status, message: "nope" },
+ });
+
+ await expect(getAdminAccess()).resolves.toBe(false);
+ });
+
+ it("rethrows other failures so a blip is not treated as denial", async () => {
+ hasPermission.mockResolvedValue({
+ data: null,
+ error: { status: 502, message: "bad gateway" },
+ });
+
+ await expect(getAdminAccess()).rejects.toThrow("bad gateway");
+ });
+
+ it.each([true, false])("returns the server's answer %s", async (success) => {
+ hasPermission.mockResolvedValue({ data: { success }, error: null });
+
+ await expect(getAdminAccess()).resolves.toBe(success);
+ });
+});
diff --git a/apps/web/src/fetchers/admin/get-admin-access.ts b/apps/web/src/fetchers/admin/get-admin-access.ts
index 7d060211d..8fa48b9f1 100644
--- a/apps/web/src/fetchers/admin/get-admin-access.ts
+++ b/apps/web/src/fetchers/admin/get-admin-access.ts
@@ -6,7 +6,10 @@ export async function getAdminAccess() {
});
if (error) {
- return false;
+ if (error.status === 401 || error.status === 403) {
+ return false;
+ }
+ throw new Error(error.message ?? "");
}
return data?.success === true;
diff --git a/apps/web/src/fetchers/admin/get-admin-users.test.ts b/apps/web/src/fetchers/admin/get-admin-users.test.ts
new file mode 100644
index 000000000..17d45d3ff
--- /dev/null
+++ b/apps/web/src/fetchers/admin/get-admin-users.test.ts
@@ -0,0 +1,92 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { HttpError } from "@/lib/http-error";
+import { getAdminUsers } from "./get-admin-users";
+
+const mocks = vi.hoisted(() => ({
+ get: vi.fn(),
+}));
+
+vi.mock("@kaneo/libs", () => ({
+ client: {
+ admin: {
+ users: {
+ $get: mocks.get,
+ },
+ },
+ },
+}));
+
+const result = {
+ users: [
+ {
+ id: "ada",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ emailVerified: true,
+ image: null,
+ createdAt: "2026-01-02T00:00:00.000Z",
+ updatedAt: "2026-01-02T00:00:00.000Z",
+ role: "admin",
+ banned: false,
+ banReason: null,
+ banExpires: null,
+ },
+ ],
+ total: 41,
+};
+
+describe("getAdminUsers", () => {
+ beforeEach(() => {
+ mocks.get.mockReset();
+ mocks.get.mockResolvedValue({
+ ok: true,
+ json: async () => result,
+ });
+ });
+
+ it("requests the first page without a search parameter", async () => {
+ await expect(getAdminUsers("", 0)).resolves.toEqual(result);
+
+ expect(mocks.get).toHaveBeenCalledWith({
+ query: { page: "1", limit: "20" },
+ });
+ });
+
+ it("passes the trimmed search through", async () => {
+ await getAdminUsers(" ada ", 0);
+
+ expect(mocks.get).toHaveBeenCalledWith({
+ query: { search: "ada", page: "1", limit: "20" },
+ });
+ });
+
+ it("caps the search at the API limit", async () => {
+ await getAdminUsers("a".repeat(250), 0);
+
+ expect(mocks.get).toHaveBeenCalledWith({
+ query: { search: "a".repeat(200), page: "1", limit: "20" },
+ });
+ });
+
+ it("maps the zero-based page to the one-based API page", async () => {
+ await getAdminUsers("", 3);
+
+ expect(mocks.get).toHaveBeenCalledWith({
+ query: { page: "4", limit: "20" },
+ });
+ });
+
+ it("throws an HttpError when the response is not ok", async () => {
+ mocks.get.mockResolvedValue({
+ ok: false,
+ status: 403,
+ text: async () => "Forbidden",
+ });
+
+ const error = await getAdminUsers("", 0).catch((caught) => caught);
+
+ expect(error).toBeInstanceOf(HttpError);
+ expect(error.status).toBe(403);
+ expect(error.message).toBe("Forbidden");
+ });
+});
diff --git a/apps/web/src/fetchers/admin/get-admin-users.ts b/apps/web/src/fetchers/admin/get-admin-users.ts
index bc3a4b1d4..a99b8c1c0 100644
--- a/apps/web/src/fetchers/admin/get-admin-users.ts
+++ b/apps/web/src/fetchers/admin/get-admin-users.ts
@@ -1,90 +1,22 @@
-import { authClient } from "@/lib/auth-client";
-import {
- ADMIN_USERS_PAGE_SIZE,
- type AdminUser,
- type AdminUsersResult,
-} from "./types";
-
-const SEARCH_BATCH_SIZE = 100;
-
-async function listMatchingUsers(
- search: string,
- searchField: "email" | "name",
-): Promise<AdminUser[]> {
- const users: AdminUser[] = [];
- let offset = 0;
-
- while (true) {
- const { data, error } = await authClient.admin.listUsers({
- query: {
- searchValue: search,
- searchField,
- searchOperator: "contains",
- limit: SEARCH_BATCH_SIZE,
- offset,
- sortBy: "createdAt",
- sortDirection: "desc",
- },
- });
-
- if (error) {
- throw new Error(error.message ?? "");
- }
-
- const batch = (data?.users ?? []) as AdminUser[];
- users.push(...batch);
- offset += batch.length;
-
- if (batch.length === 0 || offset >= (data?.total ?? offset)) {
- return users;
- }
- }
-}
-
-export async function getAdminUsers(
- search: string,
- page: number,
-): Promise<AdminUsersResult> {
- const normalizedSearch = search.trim();
-
- if (!normalizedSearch) {
- const { data, error } = await authClient.admin.listUsers({
- query: {
- limit: ADMIN_USERS_PAGE_SIZE,
- offset: page * ADMIN_USERS_PAGE_SIZE,
- sortBy: "createdAt",
- sortDirection: "desc",
- },
- });
-
- if (error) {
- throw new Error(error.message ?? "");
- }
-
- return data as AdminUsersResult;
+import { client } from "@kaneo/libs";
+import { HttpError } from "@/lib/http-error";
+import { ADMIN_USERS_PAGE_SIZE, ADMIN_USERS_SEARCH_MAX_LENGTH } from "./types";
+
+export async function getAdminUsers(search: string, page: number) {
+ const normalizedSearch = search
+ .trim()
+ .slice(0, ADMIN_USERS_SEARCH_MAX_LENGTH);
+ const response = await client.admin.users.$get({
+ query: {
+ ...(normalizedSearch ? { search: normalizedSearch } : {}),
+ page: String(page + 1),
+ limit: String(ADMIN_USERS_PAGE_SIZE),
+ },
+ });
+
+ if (!response.ok) {
+ throw new HttpError(response.status, await response.text());
}
- const results = await Promise.all(
- (["name", "email"] as const).map((searchField) =>
- listMatchingUsers(normalizedSearch, searchField),
- ),
- );
- const usersById = new Map<string, AdminUser>();
-
- for (const users of results) {
- for (const user of users) {
- usersById.set(user.id, user);
- }
- }
-
- const sortedUsers = [...usersById.values()].sort(
- (left, right) =>
- new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(),
- );
- const start = page * ADMIN_USERS_PAGE_SIZE;
-
- return {
- users: sortedUsers.slice(start, start + ADMIN_USERS_PAGE_SIZE),
- total: sortedUsers.length,
- };
+ return response.json();
}
diff --git a/apps/web/src/fetchers/admin/types.ts b/apps/web/src/fetchers/admin/types.ts
index 28fd05a85..b3d3908ff 100644
--- a/apps/web/src/fetchers/admin/types.ts
+++ b/apps/web/src/fetchers/admin/types.ts
@@ -1,29 +1,17 @@
+import type { getAdminUsers } from "./get-admin-users";
+
export const ADMIN_USERS_PAGE_SIZE = 20;
+export const ADMIN_USERS_SEARCH_MAX_LENGTH = 200;
-export type AdminUser = {
- id: string;
- name: string;
- email: string;
- emailVerified: boolean;
- image?: string | null;
- createdAt: Date;
- updatedAt: Date;
- role?: string | null;
- banned: boolean | null;
- banReason?: string | null;
- banExpires?: Date | null;
-};
+export type AdminUsersResult = Awaited<ReturnType<typeof getAdminUsers>>;
-export type AdminUsersResult = {
- users: AdminUser[];
- total: number;
-};
+export type AdminUser = AdminUsersResult["users"][number];
export type UpdateAdminUserRequest = {
userId: string;
name: string;
email: string;
- role?: "admin" | "user";
+ role?: string;
};
export type ToggleAdminUserStatusRequest = {
diff --git a/apps/web/src/hooks/queries/admin/use-admin-access.ts b/apps/web/src/hooks/queries/admin/use-admin-access.ts
index 3c21496c3..02d3468a4 100644
--- a/apps/web/src/hooks/queries/admin/use-admin-access.ts
+++ b/apps/web/src/hooks/queries/admin/use-admin-access.ts
@@ -1,14 +1,21 @@
-import { useQuery } from "@tanstack/react-query";
+import { queryOptions, useQuery } from "@tanstack/react-query";
+import useAuth from "@/components/providers/auth-provider/hooks/use-auth";
import { getAdminAccess } from "@/fetchers/admin/get-admin-access";
export const ADMIN_ACCESS_QUERY_KEY = ["admin", "access"] as const;
-function useAdminAccess() {
- return useQuery({
- queryKey: ADMIN_ACCESS_QUERY_KEY,
+export function adminAccessQueryOptions(userId: string | null | undefined) {
+ return queryOptions({
+ queryKey: [...ADMIN_ACCESS_QUERY_KEY, userId ?? ""],
queryFn: getAdminAccess,
+ enabled: Boolean(userId),
staleTime: 5 * 60 * 1000,
});
}
+function useAdminAccess() {
+ const { user } = useAuth();
+ return useQuery(adminAccessQueryOptions(user?.id));
+}
+
export default useAdminAccess;
diff --git a/apps/web/src/hooks/queries/admin/use-admin-users.test.ts b/apps/web/src/hooks/queries/admin/use-admin-users.test.ts
deleted file mode 100644
index e42ca9846..000000000
--- a/apps/web/src/hooks/queries/admin/use-admin-users.test.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import { beforeEach, describe, expect, it, type Mock, vi } from "vitest";
-import { getAdminUsers } from "@/fetchers/admin/get-admin-users";
-import { authClient } from "@/lib/auth-client";
-
-vi.mock("@/lib/auth-client", () => ({
- authClient: {
- admin: {
- listUsers: vi.fn(),
- },
- },
-}));
-
-const listUsers = authClient.admin.listUsers as Mock;
-
-const ada = {
- id: "ada",
- name: "Ada Lovelace",
- email: "[email protected]",
- emailVerified: true,
- createdAt: new Date("2026-01-02T00:00:00.000Z"),
- updatedAt: new Date("2026-01-02T00:00:00.000Z"),
- role: "admin",
- banned: false,
-};
-
-const grace = {
- id: "grace",
- name: "Grace Hopper",
- email: "[email protected]",
- emailVerified: true,
- createdAt: new Date("2026-02-02T00:00:00.000Z"),
- updatedAt: new Date("2026-02-02T00:00:00.000Z"),
- role: "user",
- banned: false,
-};
-
-describe("fetchAdminUsers", () => {
- beforeEach(() => {
- listUsers.mockReset();
- });
-
- it("loads a paginated page in newest-first order", async () => {
- listUsers.mockResolvedValue({
- data: { users: [grace], total: 41 },
- error: null,
- });
-
- await expect(getAdminUsers("", 1)).resolves.toEqual({
- users: [grace],
- total: 41,
- });
- expect(listUsers).toHaveBeenCalledWith({
- query: {
- limit: 20,
- offset: 20,
- sortBy: "createdAt",
- sortDirection: "desc",
- },
- });
- });
-
- it("searches names and emails, then removes duplicate users", async () => {
- listUsers
- .mockResolvedValueOnce({
- data: { users: [ada, grace], total: 2 },
- error: null,
- })
- .mockResolvedValueOnce({
- data: { users: [ada], total: 1 },
- error: null,
- });
-
- await expect(getAdminUsers(" a ", 0)).resolves.toEqual({
- users: [grace, ada],
- total: 2,
- });
- expect(listUsers).toHaveBeenNthCalledWith(1, {
- query: expect.objectContaining({
- searchValue: "a",
- searchField: "name",
- }),
- });
- expect(listUsers).toHaveBeenNthCalledWith(2, {
- query: expect.objectContaining({
- searchValue: "a",
- searchField: "email",
- }),
- });
- });
-
- it("paginates complete search results beyond the first API batch", async () => {
- const firstBatch = Array.from({ length: 100 }, (_, index) => ({
- ...ada,
- id: `user-${index}`,
- email: `user-${index}@example.com`,
- }));
- const finalUser = {
- ...ada,
- id: "user-100",
- email: "[email protected]",
- };
-
- listUsers
- .mockResolvedValueOnce({
- data: { users: firstBatch, total: 101 },
- error: null,
- })
- .mockResolvedValueOnce({
- data: { users: [], total: 0 },
- error: null,
- })
- .mockResolvedValueOnce({
- data: { users: [finalUser], total: 101 },
- error: null,
- });
-
- await expect(getAdminUsers("user", 5)).resolves.toEqual({
- users: [finalUser],
- total: 101,
- });
- expect(listUsers).toHaveBeenNthCalledWith(
- 3,
- expect.objectContaining({
- query: expect.objectContaining({
- searchField: "name",
- limit: 100,
- offset: 100,
- }),
- }),
- );
- });
-});
diff --git a/apps/web/src/hooks/queries/admin/use-admin-users.ts b/apps/web/src/hooks/queries/admin/use-admin-users.ts
index 098c063f3..1c7e41070 100644
--- a/apps/web/src/hooks/queries/admin/use-admin-users.ts
+++ b/apps/web/src/hooks/queries/admin/use-admin-users.ts
@@ -1,17 +1,26 @@
import { useQuery } from "@tanstack/react-query";
+import useAuth from "@/components/providers/auth-provider/hooks/use-auth";
import { getAdminUsers } from "@/fetchers/admin/get-admin-users";
export {
ADMIN_USERS_PAGE_SIZE,
+ ADMIN_USERS_SEARCH_MAX_LENGTH,
type AdminUser,
} from "@/fetchers/admin/types";
export const ADMIN_USERS_QUERY_KEY = ["admin", "users"] as const;
+
function useAdminUsers(search: string, page: number) {
+ const { user } = useAuth();
+ const userId = user?.id ?? "";
return useQuery({
- queryKey: [...ADMIN_USERS_QUERY_KEY, search, page],
+ queryKey: [...ADMIN_USERS_QUERY_KEY, userId, search.trim(), page],
queryFn: () => getAdminUsers(search, page),
- placeholderData: (previousData) => previousData,
+ enabled: userId !== "",
+ placeholderData: (previousData, previousQuery) =>
+ userId !== "" && previousQuery?.queryKey[2] === userId
+ ? previousData
+ : undefined,
});
}
diff --git a/apps/web/src/hooks/use-workspace-creation-access.test.ts b/apps/web/src/hooks/use-workspace-creation-access.test.ts
new file mode 100644
index 000000000..7e8a7f4bd
--- /dev/null
+++ b/apps/web/src/hooks/use-workspace-creation-access.test.ts
@@ -0,0 +1,72 @@
+import { renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import useWorkspaceCreationAccess from "./use-workspace-creation-access";
+
+const { getSession, useAuth, useGetConfig } = vi.hoisted(() => ({
+ getSession: vi.fn(),
+ useAuth: vi.fn(),
+ useGetConfig: vi.fn(),
+}));
+
+vi.mock("@/lib/auth-client", () => ({
+ authClient: { getSession },
+}));
+
+vi.mock("@/components/providers/auth-provider/hooks/use-auth", () => ({
+ default: useAuth,
+}));
+
+vi.mock("@/hooks/queries/config/use-get-config", () => ({
+ default: useGetConfig,
+}));
+
+describe("useWorkspaceCreationAccess", () => {
+ beforeEach(() => {
+ getSession.mockReset();
+ useAuth.mockReset();
+ useGetConfig.mockReset();
+ useGetConfig.mockReturnValue({
+ data: { disableWorkspaceCreation: true },
+ isPending: false,
+ });
+ });
+
+ it("does not restrict a refreshed multi-role user that includes admin", async () => {
+ useAuth.mockReturnValue({ user: { role: "user" } });
+ getSession.mockResolvedValue({
+ data: { user: { role: "user,admin" } },
+ error: null,
+ });
+
+ const { result } = renderHook(() => useWorkspaceCreationAccess());
+
+ await waitFor(() => expect(result.current.isDecided).toBe(true));
+ expect(result.current.isCreationRestricted).toBe(false);
+ expect(result.current.canCreateWorkspace).toBe(true);
+ });
+
+ it("restricts a refreshed non-admin when creation is disabled", async () => {
+ useAuth.mockReturnValue({ user: { role: "user" } });
+ getSession.mockResolvedValue({
+ data: { user: { role: "user" } },
+ error: null,
+ });
+
+ const { result } = renderHook(() => useWorkspaceCreationAccess());
+
+ await waitFor(() => expect(result.current.isDecided).toBe(true));
+ expect(result.current.isCreationRestricted).toBe(true);
+ expect(result.current.canCreateWorkspace).toBe(false);
+ });
+
+ it("falls back to the cached multi-role admin when the refresh fails", async () => {
+ useAuth.mockReturnValue({ user: { role: "user,admin" } });
+ getSession.mockRejectedValue(new Error("network"));
+
+ const { result } = renderHook(() => useWorkspaceCreationAccess());
+
+ await waitFor(() => expect(result.current.isDecided).toBe(true));
+ expect(result.current.isCreationRestricted).toBe(false);
+ expect(result.current.canCreateWorkspace).toBe(true);
+ });
+});
diff --git a/apps/web/src/hooks/use-workspace-creation-access.ts b/apps/web/src/hooks/use-workspace-creation-access.ts
index 683e48820..b86aa1d7b 100644
--- a/apps/web/src/hooks/use-workspace-creation-access.ts
+++ b/apps/web/src/hooks/use-workspace-creation-access.ts
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
import useAuth from "@/components/providers/auth-provider/hooks/use-auth";
import useGetConfig from "@/hooks/queries/config/use-get-config";
import { authClient } from "@/lib/auth-client";
+import { hasInstanceAdminRole } from "@/lib/instance-admin";
// "stale" is a refresh that failed: the cached role is all there is.
type RoleStatus = "pending" | "fresh" | "stale";
@@ -67,10 +68,11 @@ export default function useWorkspaceCreationAccess(): WorkspaceCreationAccess {
}, []);
// The re-read answer when there is one, the cached role when there is not.
- const isInstanceAdmin =
+ const isInstanceAdmin = hasInstanceAdminRole(
roleStatus === "fresh"
- ? refreshedRole === "admin"
- : (user as { role?: string | null } | null | undefined)?.role === "admin";
+ ? refreshedRole
+ : (user as { role?: string | null } | null | undefined)?.role,
+ );
// Only a confirmed non-admin under a confirmed restriction loses anything.
// Every other combination — a role that could not be re-read, a config
diff --git a/apps/web/src/lib/instance-admin.test.ts b/apps/web/src/lib/instance-admin.test.ts
new file mode 100644
index 000000000..68a7b7a00
--- /dev/null
+++ b/apps/web/src/lib/instance-admin.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vitest";
+import { hasInstanceAdminRole, withInstanceAdminRole } from "./instance-admin";
+
+describe("hasInstanceAdminRole", () => {
+ it("accepts a plain admin role", () => {
+ expect(hasInstanceAdminRole("admin")).toBe(true);
+ });
+
+ it("accepts admin inside a comma-separated role list", () => {
+ expect(hasInstanceAdminRole("user,admin")).toBe(true);
+ });
+
+ it("does not trim tokens", () => {
+ expect(hasInstanceAdminRole(" admin , user")).toBe(false);
+ });
+
+ it("rejects roles without admin", () => {
+ expect(hasInstanceAdminRole("user")).toBe(false);
+ expect(hasInstanceAdminRole("")).toBe(false);
+ });
+
+ it("rejects non-string values", () => {
+ expect(hasInstanceAdminRole(null)).toBe(false);
+ expect(hasInstanceAdminRole(undefined)).toBe(false);
+ });
+});
+
+describe("withInstanceAdminRole", () => {
+ it("removes admin and keeps the other tokens in order", () => {
+ expect(withInstanceAdminRole("user,admin", false)).toBe("user");
+ expect(withInstanceAdminRole("sales,admin,user", false)).toBe("sales,user");
+ });
+
+ it("appends admin to an existing role list", () => {
+ expect(withInstanceAdminRole("user", true)).toBe("user,admin");
+ });
+
+ it("falls back to user when removing admin empties the list", () => {
+ expect(withInstanceAdminRole("admin", false)).toBe("user");
+ });
+
+ it("treats a missing role as user", () => {
+ expect(withInstanceAdminRole(null, true)).toBe("user,admin");
+ expect(withInstanceAdminRole(undefined, false)).toBe("user");
+ });
+
+ it("leaves a list that already has admin unchanged", () => {
+ expect(withInstanceAdminRole("user,admin", true)).toBe("user,admin");
+ });
+
+ it("drops empty tokens so a demotion never stores an empty role", () => {
+ expect(withInstanceAdminRole("admin,", false)).toBe("user");
+ expect(withInstanceAdminRole(",admin", false)).toBe("user");
+ expect(withInstanceAdminRole("user,admin,", false)).toBe("user");
+ expect(withInstanceAdminRole("user,", true)).toBe("user,admin");
+ expect(withInstanceAdminRole("", true)).toBe("user,admin");
+ });
+});
diff --git a/apps/web/src/lib/instance-admin.ts b/apps/web/src/lib/instance-admin.ts
new file mode 100644
index 000000000..95c1d3e6f
--- /dev/null
+++ b/apps/web/src/lib/instance-admin.ts
@@ -0,0 +1,27 @@
+const INSTANCE_ADMIN_ROLE = "admin";
+const DEFAULT_ROLE = "user";
+
+function roleTokens(role: unknown) {
+ const tokens =
+ typeof role === "string"
+ ? role.split(",").filter((token) => token !== "")
+ : [];
+ return tokens.length > 0 ? tokens : [DEFAULT_ROLE];
+}
+
+export function hasInstanceAdminRole(role: unknown) {
+ return (
+ typeof role === "string" && role.split(",").includes(INSTANCE_ADMIN_ROLE)
+ );
+}
+
+export function withInstanceAdminRole(role: unknown, admin: boolean) {
+ const tokens = roleTokens(role);
+ if (admin) {
+ return tokens.includes(INSTANCE_ADMIN_ROLE)
+ ? tokens.join(",")
+ : [...tokens, INSTANCE_ADMIN_ROLE].join(",");
+ }
+ const remaining = tokens.filter((token) => token !== INSTANCE_ADMIN_ROLE);
+ return remaining.length > 0 ? remaining.join(",") : DEFAULT_ROLE;
+}
diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/admin.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/admin.tsx
index 45476a87b..d9d0f8aff 100644
--- a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/admin.tsx
+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/admin.tsx
@@ -1,11 +1,28 @@
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
-import { getAdminAccess } from "@/fetchers/admin/get-admin-access";
+import { adminAccessQueryOptions } from "@/hooks/queries/admin/use-admin-access";
+import { authClient } from "@/lib/auth-client";
export const Route = createFileRoute(
"/_layout/_authenticated/dashboard/settings/admin",
)({
- beforeLoad: async () => {
- if (!(await getAdminAccess())) {
+ beforeLoad: async ({ context }) => {
+ let userId = context.session?.user.id;
+ if (!userId && context.sessionError) {
+ const { data } = await authClient.getSession();
+ userId = data?.user.id;
+ if (!userId) {
+ throw redirect({ to: "/auth/sign-in" });
+ }
+ }
+ if (!userId) {
+ throw redirect({ to: "/dashboard/settings/account/information" });
+ }
+
+ const hasAccess = await context.queryClient.ensureQueryData(
+ adminAccessQueryOptions(userId),
+ );
+
+ if (!hasAccess) {
throw redirect({ to: "/dashboard/settings/account/information" });
}
},
diff --git a/tests/api-integration/admin-email-change.test.ts b/tests/api-integration/admin-email-change.test.ts
new file mode 100644
index 000000000..82522cba5
--- /dev/null
+++ b/tests/api-integration/admin-email-change.test.ts
@@ -0,0 +1,103 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { signUpWithSession } from "./helpers/auth-session";
+import { resetTestDatabase } from "./helpers/database";
+import { createWorkspaceMember } from "./helpers/fixtures";
+
+type App = ReturnType<typeof createApp>["app"];
+
+async function updateUser(
+ app: App,
+ cookies: string,
+ userId: string,
+ data: Record<string, unknown>,
+) {
+ return app.request("/api/auth/admin/update-user", {
+ method: "POST",
+ headers: { "content-type": "application/json", cookie: cookies },
+ body: JSON.stringify({ userId, data }),
+ });
+}
+
+async function loadUser(userId: string) {
+ const [user] = await db
+ .select({
+ email: schema.userTable.email,
+ emailVerified: schema.userTable.emailVerified,
+ name: schema.userTable.name,
+ })
+ .from(schema.userTable)
+ .where(eq(schema.userTable.id, userId));
+ return user;
+}
+
+describe("API integration: admin email change", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("clears emailVerified when an administrator changes a user's email", async () => {
+ const { app } = createApp();
+ const admin = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Instance Admin",
+ role: "admin",
+ });
+ const target = await createWorkspaceMember({ role: "member" });
+ expect((await loadUser(target.user.id))?.emailVerified).toBe(true);
+
+ const response = await updateUser(app, admin.cookies, target.user.id, {
+ email: "[email protected]",
+ });
+
+ expect(response.status).toBe(200);
+ expect(await loadUser(target.user.id)).toMatchObject({
+ email: "[email protected]",
+ emailVerified: false,
+ });
+ });
+
+ it("keeps emailVerified when the submitted email only differs in case or whitespace", async () => {
+ const { app } = createApp();
+ const admin = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Instance Admin",
+ role: "admin",
+ });
+ const target = await createWorkspaceMember({ role: "member" });
+
+ const response = await updateUser(app, admin.cookies, target.user.id, {
+ email: target.user.email.toUpperCase(),
+ name: "Renamed Member",
+ });
+
+ expect(response.status).toBe(200);
+ expect(await loadUser(target.user.id)).toMatchObject({
+ email: target.user.email,
+ emailVerified: true,
+ name: "Renamed Member",
+ });
+ });
+
+ it("keeps emailVerified when the update does not touch the email", async () => {
+ const { app } = createApp();
+ const admin = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Instance Admin",
+ role: "admin",
+ });
+ const target = await createWorkspaceMember({ role: "member" });
+
+ const response = await updateUser(app, admin.cookies, target.user.id, {
+ name: "Renamed Member",
+ });
+
+ expect(response.status).toBe(200);
+ expect(await loadUser(target.user.id)).toMatchObject({
+ emailVerified: true,
+ name: "Renamed Member",
+ });
+ });
+});
diff --git a/tests/api-integration/admin-role.test.ts b/tests/api-integration/admin-role.test.ts
index 24afc567f..76b9178c6 100644
--- a/tests/api-integration/admin-role.test.ts
+++ b/tests/api-integration/admin-role.test.ts
@@ -5,7 +5,7 @@ import { auth } from "../../apps/api/src/auth";
import db, { schema } from "../../apps/api/src/database";
import { resetTestDatabase } from "./helpers/database";
-async function createUser(role: "admin" | "user") {
+async function createUser(role: string) {
const email = `${randomUUID()}@example.com`;
const password = "admin-role-test-password";
const signUp = await request("/sign-up/email", {
@@ -116,6 +116,21 @@ describe.each(["/admin/set-role", "/admin/update-user"])(
expect(await getRole(other.id)).toBe("user");
});
+ it("counts an admin stored as a role list as remaining", async () => {
+ const admin = await createUser("admin");
+ const listed = await createUser("user,admin");
+ const headers = { Cookie: admin.cookie };
+
+ expect(
+ (await request(path, body(listed.id, "user"), headers)).status,
+ ).toBe(200);
+ expect(await getRole(listed.id)).toBe("user");
+ expect(
+ (await request(path, body(admin.id, "user"), headers)).status,
+ ).toBe(400);
+ expect(await getRole(admin.id)).toBe("admin");
+ });
+
it("denies a demoted admin even with their old session cookie", async () => {
const admin = await createUser("admin");
const other = await createUser("admin");
diff --git a/tests/api-integration/admin-user-listing.test.ts b/tests/api-integration/admin-user-listing.test.ts
new file mode 100644
index 000000000..92fa8f81a
--- /dev/null
+++ b/tests/api-integration/admin-user-listing.test.ts
@@ -0,0 +1,190 @@
+import { createHash, randomUUID } from "node:crypto";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+
+type AdminUserList = {
+ users: { id: string; name: string; email: string; banned: boolean }[];
+ total: number;
+};
+
+async function createUser(
+ overrides: Partial<typeof schema.userTable.$inferInsert> & {
+ name: string;
+ email: string;
+ },
+) {
+ const [user] = await db
+ .insert(schema.userTable)
+ .values({
+ id: `user-${randomUUID()}`,
+ emailVerified: true,
+ ...overrides,
+ })
+ .returning();
+ return user;
+}
+
+async function listUsers(
+ app: ReturnType<typeof createApp>["app"],
+ query: Record<string, string> = {},
+ headers: Record<string, string> = {},
+) {
+ const search = new URLSearchParams(query).toString();
+ return app.request(`/api/admin/users${search ? `?${search}` : ""}`, {
+ headers,
+ });
+}
+
+describe("API integration: admin user listing", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("rejects users who are not instance administrators", async () => {
+ const member = await createUser({
+ name: "Regular Member",
+ email: "[email protected]",
+ });
+ mockAuthenticatedSession(member);
+ const { app } = createApp();
+
+ const response = await listUsers(app);
+
+ expect(response.status).toBe(403);
+ });
+
+ it("rejects API keys even when they belong to an administrator", async () => {
+ const admin = await createUser({
+ name: "Instance Admin",
+ email: "[email protected]",
+ role: "admin",
+ });
+ mockAnonymousSession();
+ const key = `test_${randomUUID()}`;
+ await db.insert(schema.apikeyTable).values({
+ referenceId: admin.id,
+ userId: admin.id,
+ key: createHash("sha256").update(key).digest("base64url"),
+ enabled: true,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
+ const { app } = createApp();
+
+ const response = await listUsers(app, {}, { "x-api-key": key });
+
+ expect(response.status).toBe(403);
+ });
+
+ it("accepts administrators whose role list includes admin", async () => {
+ const admin = await createUser({
+ name: "Multi Role Admin",
+ email: "[email protected]",
+ role: "user,admin",
+ });
+ mockAuthenticatedSession(admin);
+ const { app } = createApp();
+
+ const response = await listUsers(app);
+
+ expect(response.status).toBe(200);
+ const body = (await response.json()) as AdminUserList;
+ expect(body.users.map((user) => user.id)).toEqual([admin.id]);
+ });
+
+ it("searches name and email case-insensitively", async () => {
+ const admin = await createUser({
+ name: "Instance Admin",
+ email: "[email protected]",
+ role: "admin",
+ });
+ const alice = await createUser({
+ name: "Alice Wonder",
+ email: "[email protected]",
+ });
+ const bob = await createUser({ name: "Bob Builder", email: "[email protected]" });
+ await createUser({ name: "Carol", email: "[email protected]" });
+ mockAuthenticatedSession(admin);
+ const { app } = createApp();
+
+ const byName = (await (
+ await listUsers(app, { search: "ALICE" })
+ ).json()) as AdminUserList;
+ expect(byName.total).toBe(1);
+ expect(byName.users.map((user) => user.id)).toEqual([alice.id]);
+
+ const byEmail = (await (
+ await listUsers(app, { search: "Corp" })
+ ).json()) as AdminUserList;
+ expect(byEmail.total).toBe(1);
+ expect(byEmail.users.map((user) => user.id)).toEqual([bob.id]);
+
+ const wildcard = (await (
+ await listUsers(app, { search: "%" })
+ ).json()) as AdminUserList;
+ expect(wildcard.total).toBe(0);
+ expect(wildcard.users).toEqual([]);
+ });
+
+ it("pages newest users first and reports the total across pages", async () => {
+ const admin = await createUser({
+ name: "Instance Admin",
+ email: "[email protected]",
+ role: "admin",
+ createdAt: new Date("2026-01-01T00:00:00Z"),
+ });
+ const users = [];
+ for (let index = 0; index < 4; index += 1) {
+ users.push(
+ await createUser({
+ name: `Member ${index}`,
+ email: `member-${index}@example.com`,
+ createdAt: new Date(`2026-02-0${index + 1}T00:00:00Z`),
+ banned: index === 3,
+ }),
+ );
+ }
+ mockAuthenticatedSession(admin);
+ const { app } = createApp();
+
+ const firstPage = (await (
+ await listUsers(app, { limit: "2", page: "1" })
+ ).json()) as AdminUserList;
+ expect(firstPage.total).toBe(5);
+ expect(firstPage.users.map((user) => user.id)).toEqual([
+ users[3]?.id,
+ users[2]?.id,
+ ]);
+ expect(firstPage.users[0]?.banned).toBe(true);
+ expect(firstPage.users[1]?.banned).toBe(false);
+
+ const lastPage = (await (
+ await listUsers(app, { limit: "2", page: "3" })
+ ).json()) as AdminUserList;
+ expect(lastPage.total).toBe(5);
+ expect(lastPage.users.map((user) => user.id)).toEqual([admin.id]);
+
+ const beyond = (await (
+ await listUsers(app, { limit: "2", page: "4" })
+ ).json()) as AdminUserList;
+ expect(beyond.users).toEqual([]);
+ expect(beyond.total).toBe(5);
+ });
+
+ it("rejects invalid paging values", async () => {
+ const admin = await createUser({
+ name: "Instance Admin",
+ email: "[email protected]",
+ role: "admin",
+ });
+ mockAuthenticatedSession(admin);
+ const { app } = createApp();
+
+ expect((await listUsers(app, { page: "0" })).status).toBe(400);
+ expect((await listUsers(app, { limit: "101" })).status).toBe(400);
+ expect((await listUsers(app, { limit: "abc" })).status).toBe(400);
+ });
+});
diff --git a/tests/api-integration/admin-user-removal.test.ts b/tests/api-integration/admin-user-removal.test.ts
new file mode 100644
index 000000000..d304016d9
--- /dev/null
+++ b/tests/api-integration/admin-user-removal.test.ts
@@ -0,0 +1,257 @@
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { signUpWithSession } from "./helpers/auth-session";
+import { resetTestDatabase } from "./helpers/database";
+import { createWorkspaceMember } from "./helpers/fixtures";
+
+type App = ReturnType<typeof createApp>["app"];
+
+async function addMember(workspaceId: string, role: string) {
+ const userId = `user-${randomUUID()}`;
+ const [user] = await db
+ .insert(schema.userTable)
+ .values({
+ id: userId,
+ email: `${userId}@example.com`,
+ emailVerified: true,
+ name: "Other Member",
+ })
+ .returning();
+ await db.insert(schema.workspaceUserTable).values({
+ workspaceId,
+ userId: user.id,
+ role,
+ joinedAt: new Date(),
+ });
+ return user;
+}
+
+async function seedCredentials(userId: string) {
+ const now = new Date();
+ await db.insert(schema.sessionTable).values({
+ id: `session-${userId}`,
+ token: `token-${userId}`,
+ userId,
+ expiresAt: new Date(now.getTime() + 60 * 60 * 1000),
+ createdAt: now,
+ updatedAt: now,
+ });
+ await db.insert(schema.accountTable).values({
+ accountId: userId,
+ providerId: "credential",
+ userId,
+ password: "hashed",
+ });
+}
+
+async function removeUser(app: App, cookies: string, userId: string) {
+ return app.request("/api/auth/admin/remove-user", {
+ method: "POST",
+ headers: { "content-type": "application/json", cookie: cookies },
+ body: JSON.stringify({ userId }),
+ });
+}
+
+async function countRows(userId: string, workspaceId: string) {
+ const [users, sessions, accounts, workspaces] = await Promise.all([
+ db.select().from(schema.userTable).where(eq(schema.userTable.id, userId)),
+ db
+ .select()
+ .from(schema.sessionTable)
+ .where(eq(schema.sessionTable.userId, userId)),
+ db
+ .select()
+ .from(schema.accountTable)
+ .where(eq(schema.accountTable.userId, userId)),
+ db
+ .select()
+ .from(schema.workspaceTable)
+ .where(eq(schema.workspaceTable.id, workspaceId)),
+ ]);
+ return {
+ users: users.length,
+ sessions: sessions.length,
+ accounts: accounts.length,
+ workspaces: workspaces.length,
+ };
+}
+
+describe("API integration: admin user removal", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("deletes the workspace a sole member owned together with the user", async () => {
+ const { app } = createApp();
+ const admin = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Instance Admin",
+ role: "admin",
+ });
+ const target = await createWorkspaceMember({ role: "owner" });
+ await seedCredentials(target.user.id);
+
+ const response = await removeUser(app, admin.cookies, target.user.id);
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ success: true });
+ expect(await countRows(target.user.id, target.workspace.id)).toEqual({
+ users: 0,
+ sessions: 0,
+ accounts: 0,
+ workspaces: 0,
+ });
+ });
+
+ it("refuses to remove the only owner of a shared workspace and keeps the account intact", async () => {
+ const { app } = createApp();
+ const admin = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Instance Admin",
+ role: "admin",
+ });
+ const target = await createWorkspaceMember({
+ role: "owner",
+ workspaceName: "Acme",
+ });
+ await addMember(target.workspace.id, "member");
+ await seedCredentials(target.user.id);
+
+ const response = await removeUser(app, admin.cookies, target.user.id);
+
+ expect(response.status).toBe(409);
+ const body = (await response.json()) as { message?: string };
+ expect(body.message).toMatch(/only owner of "Acme"/);
+ expect(await countRows(target.user.id, target.workspace.id)).toEqual({
+ users: 1,
+ sessions: 1,
+ accounts: 1,
+ workspaces: 1,
+ });
+ });
+
+ it("rejects callers who are not instance administrators without touching data", async () => {
+ const { app } = createApp();
+ await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Instance Admin",
+ role: "admin",
+ });
+ const caller = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Regular Member",
+ role: "user",
+ });
+ const target = await createWorkspaceMember({ role: "owner" });
+ await seedCredentials(target.user.id);
+
+ const response = await removeUser(app, caller.cookies, target.user.id);
+
+ expect(response.status).toBe(403);
+ expect(await countRows(target.user.id, target.workspace.id)).toEqual({
+ users: 1,
+ sessions: 1,
+ accounts: 1,
+ workspaces: 1,
+ });
+ });
+
+ it("rejects unauthenticated callers", async () => {
+ const { app } = createApp();
+ const target = await createWorkspaceMember({ role: "owner" });
+
+ const response = await removeUser(app, "", target.user.id);
+
+ expect(response.status).toBe(403);
+ expect(await countRows(target.user.id, target.workspace.id)).toMatchObject({
+ users: 1,
+ workspaces: 1,
+ });
+ });
+
+ it("does not let an administrator remove their own account through the admin endpoint", async () => {
+ const { app } = createApp();
+ const admin = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Instance Admin",
+ role: "admin",
+ });
+
+ const response = await removeUser(app, admin.cookies, admin.userId);
+
+ expect(response.status).toBe(400);
+ const remaining = await db
+ .select()
+ .from(schema.userTable)
+ .where(eq(schema.userTable.id, admin.userId));
+ expect(remaining).toHaveLength(1);
+ });
+
+ describe("with billing enabled", () => {
+ const cloudEnv = {
+ KANEO_CLOUD: "true",
+ CREEM_API_KEY: "creem_test_dummy",
+ CREEM_WEBHOOK_SECRET: "whsec_dummy",
+ };
+ const saved: Record<string, string | undefined> = {};
+
+ beforeAll(() => {
+ for (const [key, value] of Object.entries(cloudEnv)) {
+ saved[key] = process.env[key];
+ process.env[key] = value;
+ }
+ });
+
+ afterAll(() => {
+ for (const key of Object.keys(cloudEnv)) {
+ if (saved[key] === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = saved[key];
+ }
+ }
+ });
+
+ it("refuses to remove the only member of a workspace with an active subscription", async () => {
+ const { app } = createApp();
+ const admin = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Instance Admin",
+ role: "admin",
+ });
+ const owner = await createWorkspaceMember({
+ role: "owner",
+ workspaceName: "Paid Space",
+ });
+ await seedCredentials(owner.user.id);
+ await db.insert(schema.workspaceBillingTable).values({
+ workspaceId: owner.workspace.id,
+ creemSubscriptionId: "sub_active",
+ creemProductId: "prod_1",
+ plan: "team",
+ status: "active",
+ });
+
+ const response = await removeUser(app, admin.cookies, owner.user.id);
+
+ expect(response.status).toBe(409);
+ expect(await response.text()).toMatch(
+ /Paid Space.* still has an active subscription/,
+ );
+ expect(await countRows(owner.user.id, owner.workspace.id)).toEqual({
+ users: 1,
+ sessions: 1,
+ accounts: 1,
+ workspaces: 1,
+ });
+ const memberships = await db
+ .select()
+ .from(schema.workspaceUserTable)
+ .where(eq(schema.workspaceUserTable.userId, owner.user.id));
+ expect(memberships).toHaveLength(1);
+ });
+ });
+});
diff --git a/tests/api-integration/api-key-banned-user.test.ts b/tests/api-integration/api-key-banned-user.test.ts
new file mode 100644
index 000000000..d079cbe48
--- /dev/null
+++ b/tests/api-integration/api-key-banned-user.test.ts
@@ -0,0 +1,150 @@
+import { createHash, randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { verifyApiKey } from "../../apps/api/src/utils/verify-api-key";
+import { signUpWithSession } from "./helpers/auth-session";
+import { resetTestDatabase } from "./helpers/database";
+
+async function createUserWithKey(
+ ban: Partial<
+ Pick<typeof schema.userTable.$inferInsert, "banned" | "banExpires">
+ >,
+) {
+ const userId = `user-${randomUUID()}`;
+ await db.insert(schema.userTable).values({
+ id: userId,
+ email: `${userId}@example.com`,
+ emailVerified: true,
+ name: "Key Owner",
+ ...ban,
+ });
+ const key = `test_${randomUUID()}`;
+ await db.insert(schema.apikeyTable).values({
+ referenceId: userId,
+ userId,
+ key: createHash("sha256").update(key).digest("base64url"),
+ enabled: true,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
+ return { userId, key };
+}
+
+describe("API integration: API keys of banned users", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("accepts the key of a user who is not banned", async () => {
+ const { userId, key } = await createUserWithKey({ banned: false });
+
+ const result = await verifyApiKey(key);
+
+ expect(result?.key.userId).toBe(userId);
+ });
+
+ it("accepts the key when the banned flag was never set", async () => {
+ const { userId, key } = await createUserWithKey({ banned: null });
+
+ const result = await verifyApiKey(key);
+
+ expect(result?.key.userId).toBe(userId);
+ });
+
+ it("rejects the key of a banned user", async () => {
+ const { key } = await createUserWithKey({ banned: true });
+
+ expect(await verifyApiKey(key)).toBeNull();
+ });
+
+ it("rejects the key while a temporary ban is still active", async () => {
+ const { key } = await createUserWithKey({
+ banned: true,
+ banExpires: new Date(Date.now() + 60 * 60 * 1000),
+ });
+
+ expect(await verifyApiKey(key)).toBeNull();
+ });
+
+ it("accepts the key once a temporary ban has expired", async () => {
+ const { userId, key } = await createUserWithKey({
+ banned: true,
+ banExpires: new Date(Date.now() - 60 * 60 * 1000),
+ });
+
+ const result = await verifyApiKey(key);
+
+ expect(result?.key.userId).toBe(userId);
+ });
+
+ describe("through Better Auth routes", () => {
+ async function mintKey() {
+ const { app } = createApp();
+ const owner = await signUpWithSession(app, {
+ email: `${randomUUID()}@example.com`,
+ name: "Key Owner",
+ });
+ const created = await app.request("/api/auth/api-key/create", {
+ method: "POST",
+ headers: { "content-type": "application/json", cookie: owner.cookies },
+ body: JSON.stringify({ name: "test" }),
+ });
+ expect(created.status).toBe(200);
+ const { key } = (await created.json()) as { key: string };
+ return { app, userId: owner.userId, key };
+ }
+
+ async function ban(userId: string) {
+ await db
+ .update(schema.userTable)
+ .set({ banned: true })
+ .where(eq(schema.userTable.id, userId));
+ }
+
+ it("resolves a session for an active key and refuses it once banned", async () => {
+ const { app, userId, key } = await mintKey();
+ const headers = { "x-api-key": key };
+
+ const active = await app.request("/api/auth/get-session", { headers });
+ expect(active.status).toBe(200);
+ const body = (await active.json()) as { user?: { id: string } };
+ expect(body.user?.id).toBe(userId);
+
+ await ban(userId);
+
+ const banned = await app.request("/api/auth/get-session", { headers });
+ expect(banned.status).toBe(401);
+ });
+
+ it("does not let a browser cookie rescue a banned bearer key", async () => {
+ const { app } = createApp();
+ const viewer = await signUpWithSession(app, {
+ email: `${randomUUID()}@example.com`,
+ name: "Cookie Holder",
+ });
+ const { userId, key } = await mintKey();
+ await ban(userId);
+
+ const response = await app.request("/api/auth/api-key/list", {
+ headers: { authorization: `Bearer ${key}`, cookie: viewer.cookies },
+ });
+
+ expect(response.status).toBe(401);
+ });
+
+ it("applies the same rule to a bearer key on other auth routes", async () => {
+ const { app, userId, key } = await mintKey();
+ const headers = { authorization: `Bearer ${key}` };
+
+ const active = await app.request("/api/auth/api-key/list", { headers });
+ expect(active.status).toBe(200);
+
+ await ban(userId);
+
+ const banned = await app.request("/api/auth/api-key/list", { headers });
+ expect(banned.status).toBe(401);
+ });
+ });
+});
diff --git a/tests/api-integration/helpers/auth-session.ts b/tests/api-integration/helpers/auth-session.ts
new file mode 100644
index 000000000..0b5b72066
--- /dev/null
+++ b/tests/api-integration/helpers/auth-session.ts
@@ -0,0 +1,55 @@
+import { eq } from "drizzle-orm";
+import { expect } from "vitest";
+import db, { schema } from "../../../apps/api/src/database";
+import type { createApp } from "../../../apps/api/src/index";
+
+type App = ReturnType<typeof createApp>["app"];
+
+const PASSWORD = "correct horse battery staple";
+
+function collectCookies(response: Response) {
+ const jar = new Map<string, string>();
+ for (const setCookie of response.headers.getSetCookie()) {
+ const [pair] = setCookie.split(";");
+ const [name, ...value] = (pair ?? "").split("=");
+ if (!name || value.join("=") === "") continue;
+ jar.set(name, value.join("="));
+ }
+ return [...jar].map(([name, value]) => `${name}=${value}`).join("; ");
+}
+
+async function signIn(app: App, email: string) {
+ const response = await app.request("/api/auth/sign-in/email", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ email, password: PASSWORD }),
+ });
+ expect(response.status).toBe(200);
+ return collectCookies(response);
+}
+
+export async function signUpWithSession(
+ app: App,
+ {
+ email,
+ name,
+ role,
+ }: { email: string; name: string; role?: "admin" | "user" },
+) {
+ const response = await app.request("/api/auth/sign-up/email", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ email, password: PASSWORD, name }),
+ });
+ expect(response.status).toBe(200);
+ const { user } = (await response.json()) as { user: { id: string } };
+
+ if (role) {
+ await db
+ .update(schema.userTable)
+ .set({ role })
+ .where(eq(schema.userTable.id, user.id));
+ }
+
+ return { userId: user.id, cookies: await signIn(app, email) };
+}
diff --git a/tests/api-integration/instance-admin-role-sql.test.ts b/tests/api-integration/instance-admin-role-sql.test.ts
new file mode 100644
index 000000000..1a2d5890f
--- /dev/null
+++ b/tests/api-integration/instance-admin-role-sql.test.ts
@@ -0,0 +1,61 @@
+import { randomUUID } from "node:crypto";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import getInstanceStatus from "../../apps/api/src/instance/controllers/get-instance-status";
+import { filterAssignableUsers } from "../../apps/api/src/utils/assert-assignable-user";
+import { resetTestDatabase } from "./helpers/database";
+import { createWorkspaceMember } from "./helpers/fixtures";
+
+async function createUser(role: string | null) {
+ const id = `user-${randomUUID()}`;
+ const [user] = await db
+ .insert(schema.userTable)
+ .values({
+ id,
+ email: `${id}@example.com`,
+ emailVerified: true,
+ name: "Role holder",
+ role,
+ })
+ .returning();
+ return user;
+}
+
+describe("API integration: instance admin role in SQL", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("reports an admin when the only one has a role list", async () => {
+ await createUser("user");
+ await createUser("user,admin");
+
+ const status = await getInstanceStatus();
+
+ expect(status).toEqual({ hasUsers: true, hasAdmin: true });
+ });
+
+ it("does not count administrator-like or padded roles", async () => {
+ await createUser("administrator");
+ await createUser(" admin , user");
+ await createUser("admin\t");
+ await createUser(null);
+
+ const status = await getInstanceStatus();
+
+ expect(status.hasAdmin).toBe(false);
+ });
+
+ it("lets a multi-role admin be assigned tasks outside their workspaces", async () => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ const admin = await createUser("user,admin");
+ const outsider = await createUser("user");
+
+ const assignable = await filterAssignableUsers(
+ [owner.user.id, admin.id, outsider.id],
+ owner.workspace.id,
+ );
+
+ expect([...assignable].sort()).toEqual([admin.id, owner.user.id].sort());
+ });
+});
diff --git a/tests/api-integration/instance-admin-workspace-access.test.ts b/tests/api-integration/instance-admin-workspace-access.test.ts
new file mode 100644
index 000000000..ccfc7ee10
--- /dev/null
+++ b/tests/api-integration/instance-admin-workspace-access.test.ts
@@ -0,0 +1,45 @@
+import { randomUUID } from "node:crypto";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { validateWorkspaceAccess } from "../../apps/api/src/utils/validate-workspace-access";
+import { resetTestDatabase } from "./helpers/database";
+import { createWorkspaceMember } from "./helpers/fixtures";
+
+async function createUser(role: string) {
+ const id = `user-${randomUUID()}`;
+ const [user] = await db
+ .insert(schema.userTable)
+ .values({
+ id,
+ email: `${id}@example.com`,
+ emailVerified: true,
+ name: "Outsider",
+ role,
+ })
+ .returning();
+ return user;
+}
+
+describe("API integration: instance admin workspace access", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("lets a multi-role instance admin into a workspace they never joined", async () => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ const admin = await createUser("user,admin");
+
+ await expect(
+ validateWorkspaceAccess(admin.id, owner.workspace.id),
+ ).resolves.toBeUndefined();
+ });
+
+ it("still rejects a plain user who is not a member", async () => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ const outsider = await createUser("user");
+
+ await expect(
+ validateWorkspaceAccess(outsider.id, owner.workspace.id),
+ ).rejects.toMatchObject({ status: 403 });
+ });
+});
diff --git a/tests/api-integration/mcp-banned-user.test.ts b/tests/api-integration/mcp-banned-user.test.ts
new file mode 100644
index 000000000..7f86f86ab
--- /dev/null
+++ b/tests/api-integration/mcp-banned-user.test.ts
@@ -0,0 +1,72 @@
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { resetTestDatabase } from "./helpers/database";
+
+const protocolVersion = "2026-07-28";
+
+async function signUp(app: ReturnType<typeof createApp>["app"]) {
+ const response = await app.request("/api/auth/sign-up/email", {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ origin: "http://localhost:5173",
+ },
+ body: JSON.stringify({
+ name: "MCP user",
+ email: `${randomUUID()}@example.com`,
+ password: "mcp-banned-user-password",
+ }),
+ });
+ expect(response.status).toBe(200);
+ const body = (await response.json()) as {
+ token: string;
+ user: { id: string };
+ };
+ return { token: body.token, userId: body.user.id };
+}
+
+function initialize(app: ReturnType<typeof createApp>["app"], token: string) {
+ return app.request("/api/mcp", {
+ method: "POST",
+ headers: {
+ accept: "application/json, text/event-stream",
+ authorization: `Bearer ${token}`,
+ "content-type": "application/json",
+ "mcp-method": "initialize",
+ "mcp-protocol-version": protocolVersion,
+ },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion,
+ capabilities: {},
+ clientInfo: { name: "kaneo-banned-user-test", version: "1.0.0" },
+ },
+ }),
+ });
+}
+
+describe("API integration: MCP access for banned users", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("stops serving a session token once its owner is banned", async () => {
+ const { app } = createApp();
+ const { token, userId } = await signUp(app);
+
+ expect((await initialize(app, token)).status).not.toBe(401);
+
+ await db
+ .update(schema.userTable)
+ .set({ banned: true })
+ .where(eq(schema.userTable.id, userId));
+
+ expect((await initialize(app, token)).status).toBe(401);
+ });
+});
diff --git a/tests/api/utils/instance-admin-role.test.ts b/tests/api/utils/instance-admin-role.test.ts
new file mode 100644
index 000000000..45967f5fb
--- /dev/null
+++ b/tests/api/utils/instance-admin-role.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { hasInstanceAdminRole } from "../../../apps/api/src/utils/instance-admin-role";
+
+describe("hasInstanceAdminRole", () => {
+ it.each(["admin", "user,admin", "admin,user", "admin,"])(
+ "accepts %j",
+ (role) => {
+ expect(hasInstanceAdminRole(role)).toBe(true);
+ },
+ );
+
+ it.each([
+ "user",
+ "administrator",
+ " admin , user",
+ "admin\t",
+ "",
+ "user,owner",
+ null,
+ undefined,
+ 1,
+ ])("rejects %j, matching Better Auth's exact tokens", (role) => {
+ expect(hasInstanceAdminRole(role)).toBe(false);
+ });
+});
diff --git a/tests/api/utils/user-ban.test.ts b/tests/api/utils/user-ban.test.ts
new file mode 100644
index 000000000..35c311f8b
--- /dev/null
+++ b/tests/api/utils/user-ban.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import { isBanActive } from "../../../apps/api/src/utils/user-ban";
+
+describe("isBanActive", () => {
+ it("is inactive when the flag is unset or false", () => {
+ expect(isBanActive(undefined)).toBe(false);
+ expect(isBanActive({ banned: null })).toBe(false);
+ expect(isBanActive({ banned: false, banExpires: new Date() })).toBe(false);
+ });
+
+ it("is active for an open-ended ban", () => {
+ expect(isBanActive({ banned: true })).toBe(true);
+ expect(isBanActive({ banned: true, banExpires: null })).toBe(true);
+ });
+
+ it("follows the expiry of a temporary ban", () => {
+ const hour = 60 * 60 * 1000;
+ expect(
+ isBanActive({ banned: true, banExpires: new Date(Date.now() + hour) }),
+ ).toBe(true);
+ expect(
+ isBanActive({
+ banned: true,
+ banExpires: new Date(Date.now() - hour).toISOString(),
+ }),
+ ).toBe(false);
+ });
+});