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(rbac): address Qodo re-review (admin promotion, registration, instance status)

Andrej67eda1ea6c6e
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index f0b0558b7..050a236d9 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -377,6 +377,18 @@ export const auth = betterAuth({
user: {
create: {
before: async (user) => {
+ // Allow the very first signup through even when registration
+ // is disabled — that's the instance-admin bootstrap flow.
+ // Otherwise a fresh instance with DISABLE_REGISTRATION=true
+ // could never be set up because `checkRegistrationAllowed`
+ // would reject the first user (qodo bot #3).
+ const [{ value: existingUserCount }] = await db
+ .select({ value: count() })
+ .from(schema.userTable);
+ if (existingUserCount === 0) {
+ return;
+ }
+
const result = await checkRegistrationAllowed(user.email);
if (!result.allowed) {
throw new APIError("FORBIDDEN", {
@@ -406,17 +418,25 @@ export const auth = betterAuth({
// We now run the check + promote inside a single transaction
// guarded by a Postgres advisory lock. Whichever transaction
// wins the lock first promotes its user; any concurrent
- // transaction then sees adminCount >= 1 and skips the update.
+ // transaction then sees totalUserCount > 1 and skips.
+ //
+ // Note: we count total users (not admins) so that upgrading
+ // an existing instance — where every existing user has
+ // role=NULL from the new column — doesn't promote the next
+ // signup to admin (qodo bot #4).
await db.transaction(async (tx) => {
await tx.execute(sql`SELECT pg_advisory_xact_lock(2026)`);
- const adminRows = await tx
+ const totalRows = await tx
.select({ value: count() })
- .from(schema.userTable)
- .where(eq(schema.userTable.role, "admin"));
- const adminCount = adminRows[0]?.value ?? 0;
+ .from(schema.userTable);
+ const totalUserCount = totalRows[0]?.value ?? 0;
- if (adminCount === 0) {
+ // This hook runs after the user row is inserted, so the
+ // just-created user is included in the count. If they are
+ // the only row in the table, this is a fresh-instance
+ // bootstrap and they get promoted to admin.
+ if (totalUserCount === 1) {
await tx
.update(schema.userTable)
.set({ role: "admin" })
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index fac7dfb24..c623ec103 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -3,7 +3,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
import { serve } from "@hono/node-server";
import { createNodeWebSocket } from "@hono/node-ws";
import type { Session, User } from "better-auth/types";
-import { count, eq } from "drizzle-orm";
+import { eq } from "drizzle-orm";
import { migrate } from "drizzle-orm/node-postgres/migrator";
import { Hono } from "hono";
import { cors } from "hono/cors";
@@ -29,6 +29,7 @@ import giteaIntegration, { handleGiteaWebhookRoute } from "./gitea-integration";
import githubIntegration, {
handleGithubWebhookRoute,
} from "./github-integration";
+import getInstanceStatus from "./instance/controllers/get-instance-status";
import invitation from "./invitation";
import label from "./label";
import mcpRoutes, { mcpWellKnownRoutes } from "./mcp";
@@ -187,16 +188,8 @@ export function createApp() {
},
}),
async (c) => {
- const totalRows = await db
- .select({ value: count() })
- .from(schema.userTable);
- const adminRows = await db
- .select({ value: count() })
- .from(schema.userTable)
- .where(eq(schema.userTable.role, "admin"));
- const total = totalRows[0]?.value ?? 0;
- const admins = adminRows[0]?.value ?? 0;
- return c.json({ hasUsers: total > 0, hasAdmin: admins > 0 });
+ const status = await getInstanceStatus();
+ return c.json(status);
},
);
diff --git a/apps/api/src/instance/controllers/get-instance-status.ts b/apps/api/src/instance/controllers/get-instance-status.ts
new file mode 100644
index 000000000..79e44640a
--- /dev/null
+++ b/apps/api/src/instance/controllers/get-instance-status.ts
@@ -0,0 +1,22 @@
+import { count, eq } from "drizzle-orm";
+import db, { schema } from "../../database";
+
+export type InstanceStatus = {
+ hasUsers: boolean;
+ hasAdmin: boolean;
+};
+
+async function getInstanceStatus(): Promise<InstanceStatus> {
+ const [totalRow] = await db.select({ value: count() }).from(schema.userTable);
+ const [adminRow] = await db
+ .select({ value: count() })
+ .from(schema.userTable)
+ .where(eq(schema.userTable.role, "admin"));
+
+ return {
+ hasUsers: (totalRow?.value ?? 0) > 0,
+ hasAdmin: (adminRow?.value ?? 0) > 0,
+ };
+}
+
+export default getInstanceStatus;
diff --git a/apps/web/src/fetchers/instance/get-instance-status.ts b/apps/web/src/fetchers/instance/get-instance-status.ts
index d060b25fe..569c70ce8 100644
--- a/apps/web/src/fetchers/instance/get-instance-status.ts
+++ b/apps/web/src/fetchers/instance/get-instance-status.ts
@@ -11,7 +11,17 @@ export async function getInstanceStatus(): Promise<InstanceStatus> {
credentials: "include",
});
if (!response.ok) {
- throw new Error("Failed to fetch instance status");
+ // Surface the server's error body when available so the UI can
+ // distinguish "instance unreachable" from other failures.
+ let detail = "";
+ try {
+ detail = (await response.text()).trim();
+ } catch {}
+ throw new Error(
+ detail
+ ? `Failed to fetch instance status (${response.status}): ${detail}`
+ : `Failed to fetch instance status (${response.status})`,
+ );
}
return response.json();
}
diff --git a/apps/web/src/routes/auth/sign-in.tsx b/apps/web/src/routes/auth/sign-in.tsx
index eed600efd..fd52d8f78 100644
--- a/apps/web/src/routes/auth/sign-in.tsx
+++ b/apps/web/src/routes/auth/sign-in.tsx
@@ -43,8 +43,12 @@ function SignIn() {
const [isGuestLoading, setIsGuestLoading] = useState(false);
const lastLoginMethod = authClient.getLastUsedLoginMethod();
const { data: config, isLoading: isConfigLoading } = useGetConfig();
- const { data: instanceStatus, isLoading: isInstanceStatusLoading } =
- useInstanceStatus();
+ const {
+ data: instanceStatus,
+ isLoading: isInstanceStatusLoading,
+ isError: isInstanceStatusError,
+ error: instanceStatusError,
+ } = useInstanceStatus();
useEffect(() => {
if (instanceStatus && instanceStatus.hasUsers === false) {
@@ -52,6 +56,19 @@ function SignIn() {
}
}, [instanceStatus, navigate]);
+ useEffect(() => {
+ if (isInstanceStatusError) {
+ toast.error(
+ instanceStatusError instanceof Error
+ ? instanceStatusError.message
+ : t("auth:signIn.instanceStatusError", {
+ defaultValue:
+ "Couldn't reach the server. Please retry in a moment.",
+ }),
+ );
+ }
+ }, [isInstanceStatusError, instanceStatusError, t]);
+
const invitationId = search.invitationId;
const defaultEmail = search.email;
diff --git a/apps/web/src/routes/auth/sign-up.tsx b/apps/web/src/routes/auth/sign-up.tsx
index 0b5c35573..a6d732eb4 100644
--- a/apps/web/src/routes/auth/sign-up.tsx
+++ b/apps/web/src/routes/auth/sign-up.tsx
@@ -4,7 +4,7 @@ import {
useSearch,
} from "@tanstack/react-router";
import { UserCheck } from "lucide-react";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { z } from "zod/v4";
import { AuthLayout } from "@/components/auth/layout";
@@ -35,7 +35,24 @@ function SignUp() {
const search = useSearch({ from: "/auth/sign-up" });
const [isGuestLoading, setIsGuestLoading] = useState(false);
const { data: config } = useGetConfig();
- const { data: instanceStatus } = useInstanceStatus();
+ const {
+ data: instanceStatus,
+ isError: isInstanceStatusError,
+ error: instanceStatusError,
+ } = useInstanceStatus();
+
+ useEffect(() => {
+ if (isInstanceStatusError) {
+ toast.error(
+ instanceStatusError instanceof Error
+ ? instanceStatusError.message
+ : t("auth:signUp.instanceStatusError", {
+ defaultValue:
+ "Couldn't reach the server. Please retry in a moment.",
+ }),
+ );
+ }
+ }, [isInstanceStatusError, instanceStatusError, t]);
const invitationId = search.invitationId;
const prefillEmail = search.email;