Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

(fix): a forced logout now says why instead of failing silently (#1700)

Anshul sharmab9527328652d
diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsx
index c2ebdbcbb8..f84855b6fe 100644
--- a/apps/erp/app/routes/_public+/login.tsx
+++ b/apps/erp/app/routes/_public+/login.tsx
@@ -308,6 +308,19 @@ export default function LoginRoute() {
const [ssoError, setSsoError] = useState<string | null>(null);
const conditionalAbortRef = useRef<AbortController | null>(null);
+ // A forced logout (see destroyAuthSession) arrives as a bare 302, leaving the
+ // browser no trace of what went wrong. "no-claims" is almost always a user
+ // with no company membership.
+ const logoutReason = searchParams.get("reason");
+ useEffect(() => {
+ if (logoutReason) {
+ // biome-ignore lint/suspicious/noConsole: surfacing the silent logout is the point
+ console.warn(
+ `[carbon:auth] Session was destroyed server-side (reason: ${logoutReason}). See server logs for the full record.`
+ );
+ }
+ }, [logoutReason]);
+
const fetcher = useFetcher<Result & { mode?: string; email?: string }>();
useEffect(() => {
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index 9382ae7817..caf57708e9 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -19,6 +19,7 @@ import {
import { isApprovalRequired } from "@carbon/ee/approvals.server";
import { isAuditLogEnabled } from "@carbon/ee/audit.server";
import { getPlan } from "@carbon/ee/plan.server";
+import { getLogger } from "@carbon/logger";
import {
detectImplementationSignals,
getImplementationCheckStates,
@@ -85,6 +86,8 @@ import {
} from "~/modules/users/users.server";
import { ERP_URL, MES_URL, path } from "~/utils/path";
+const log = getLogger("erp", "auth");
+
export const shouldRevalidate: ShouldRevalidateFunction = ({
currentUrl,
nextUrl,
@@ -202,7 +205,28 @@ export async function loader({ request }: LoaderFunctionArgs) {
// logging out here made the `requiresOnboarding` redirect below unreachable.
// Only a genuine RPC error (groups.error) logs out.
if (!claims || user.error || !user.data || groups.error) {
- throw await destroyAuthSession(request);
+ // Four very different faults share this exit: no claims usually means the
+ // user has no company membership (get_claims returned nothing), while the
+ // user/groups errors mean a failed RPC. Record which one before bouncing.
+ const reason = !claims
+ ? "no-claims"
+ : user.error
+ ? "user-error"
+ : !user.data
+ ? "no-user-row"
+ : "groups-error";
+
+ log.warn("Destroying auth session in x+/_layout loader", {
+ userId,
+ companyId,
+ reason,
+ noClaims: !claims,
+ userError: user.error?.message ?? null,
+ hasUserData: Boolean(user.data),
+ groupsError: groups.error?.message ?? null
+ });
+
+ throw await destroyAuthSession(request, reason);
}
const employeeCompanies = employeeCompaniesResult.data ?? [];
diff --git a/ci/src/migrations.ts b/ci/src/migrations.ts
index 35fb6be869..5cf106c3c7 100644
--- a/ci/src/migrations.ts
+++ b/ci/src/migrations.ts
@@ -11,6 +11,32 @@ import {
SUPABASE_AUTH_EXTERNAL_GOOGLE_REDIRECT_URI,
} from "./env";
+/**
+ * PostgREST errors do not always populate `message` — a transport or gateway
+ * failure can arrive with every field undefined, which rendered the only clue
+ * we logged as the literal string "undefined". Serialize whatever is actually
+ * present so the next failure is diagnosable from CI output alone.
+ */
+function describePostgrestError(error: unknown): string {
+ if (!error || typeof error !== "object") return String(error);
+
+ const { message, code, details, hint } = error as {
+ message?: string;
+ code?: string;
+ details?: string;
+ hint?: string;
+ };
+
+ const parts = [
+ message && `message=${message}`,
+ code && `code=${code}`,
+ details && `details=${details}`,
+ hint && `hint=${hint}`,
+ ].filter(Boolean);
+
+ return parts.length > 0 ? parts.join(" ") : JSON.stringify(error);
+}
+
export type Workspace = {
id: number;
name: string;
@@ -89,13 +115,19 @@ async function runPendingScripts(
// The work is done but unrecorded, so the next deploy runs it again.
// Every listed script must be idempotent for exactly this reason.
throw new Error(
- `ran but could not be recorded: ${error.message}. It will run again on the next deploy.`
+ `ran but could not be recorded: ${describePostgrestError(
+ error
+ )}. It will run again on the next deploy.`
);
}
console.log(`✅ 📜 Completed ${script.name} for ${workspace.id}`);
} catch (e) {
- console.error(`🔴 📜 Script ${script.name} failed for ${workspace.id}`, e);
+ console.error(
+ `🔴 📜 Script ${script.name} failed for ${workspace.id}`,
+ e instanceof Error ? e.message : describePostgrestError(e)
+ );
+ if (e instanceof Error && e.stack) console.error(e.stack);
succeeded = false;
}
}
diff --git a/packages/auth/src/services/session.server.ts b/packages/auth/src/services/session.server.ts
index 03a0a0f071..c4a6e574ed 100644
--- a/packages/auth/src/services/session.server.ts
+++ b/packages/auth/src/services/session.server.ts
@@ -214,9 +214,22 @@ export async function clearAuthCookies(request: Request) {
];
}
-export async function destroyAuthSession(request: Request) {
+/**
+ * `reason` is a slug naming why the session was destroyed (e.g. "no-claims"),
+ * echoed to the browser console by login.tsx — a forced logout is otherwise
+ * invisible client-side, since the browser sees nothing but a 302 to /login.
+ *
+ * It reaches the client in every environment, so it must stay a fixed set of
+ * internal state names: nothing user-identifying, and nothing that reveals
+ * whether an account exists. Identifying detail goes in the server log instead.
+ */
+export async function destroyAuthSession(request: Request, reason?: string) {
const headers = await clearAuthCookies(request);
- return redirect(path.to.login, {
+ const destination = reason
+ ? `${path.to.login}?reason=${encodeURIComponent(reason)}`
+ : path.to.login;
+
+ return redirect(destination, {
headers
});
}