DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(web): resolve client auth state at runtime; size proxy body for uploads
Bingxi Zhao (Frank)37049c3d3317
diff --git a/web/components/auth/AdminLink.tsx b/web/components/auth/AdminLink.tsxindex 9019f4a70..aaa59ac9e 100644--- a/web/components/auth/AdminLink.tsx+++ b/web/components/auth/AdminLink.tsx@@ -1,10 +1,9 @@"use client";-import { useEffect, useState } from "react";import Link from "next/link";import { usePathname } from "next/navigation";import { ShieldCheck } from "lucide-react";-import { fetchAuthStatus, AUTH_ENABLED } from "@/lib/auth";+import { useAuthStatus } from "@/hooks/useAuthStatus";interface AdminLinkProps {collapsed?: boolean;@@ -12,16 +11,9 @@ interface AdminLinkProps {export function AdminLink({ collapsed = false }: AdminLinkProps) {const pathname = usePathname();- const [isAdmin, setIsAdmin] = useState(false);+ const { enabled, isAdmin } = useAuthStatus();- useEffect(() => {- if (!AUTH_ENABLED) return;- fetchAuthStatus().then((status) => {- setIsAdmin(status?.role === "admin");- });- }, []);-- if (!AUTH_ENABLED || !isAdmin) return null;+ if (!enabled || !isAdmin) return null;const active = pathname.startsWith("/admin");diff --git a/web/components/auth/LogoutButton.tsx b/web/components/auth/LogoutButton.tsxindex 86f8951b9..fcdd2317d 100644--- a/web/components/auth/LogoutButton.tsx+++ b/web/components/auth/LogoutButton.tsx@@ -2,7 +2,8 @@import { LogOut } from "lucide-react";import { useRouter } from "next/navigation";-import { AUTH_ENABLED, logout } from "@/lib/auth";+import { logout } from "@/lib/auth";+import { useAuthStatus } from "@/hooks/useAuthStatus";interface LogoutButtonProps {collapsed?: boolean;@@ -10,8 +11,9 @@ interface LogoutButtonProps {export function LogoutButton({ collapsed = false }: LogoutButtonProps) {const router = useRouter();+ const { enabled } = useAuthStatus();- if (!AUTH_ENABLED) return null;+ if (!enabled) return null;async function handleLogout() {await logout();diff --git a/web/hooks/useAuthStatus.ts b/web/hooks/useAuthStatus.tsnew file mode 100644index 000000000..dd9abb09f--- /dev/null+++ b/web/hooks/useAuthStatus.ts@@ -0,0 +1,54 @@+"use client";++import { useEffect, useState } from "react";+import { fetchAuthStatus } from "@/lib/auth";++export interface AuthStatusState {+ /** Whether auth is enabled on the backend. */+ enabled: boolean;+ /** Whether the current session is authenticated. */+ authenticated: boolean;+ /** Whether the authenticated user is an admin. */+ isAdmin: boolean;+ /** True until the first status fetch resolves. */+ loading: boolean;+}++const INITIAL: AuthStatusState = {+ enabled: false,+ authenticated: false,+ isAdmin: false,+ loading: true,+};++/**+ * Resolve auth state at runtime from the backend (`/api/v1/auth/status`).+ *+ * The frontend bundle is URL- and auth-agnostic (see web/lib/api.ts): the auth+ * toggle is a runtime setting read from `data/user/settings/auth.json`, never+ * baked into the build. Components that need to know whether auth is on — to+ * show the Sign-out / Admin affordances — use this hook instead of a build-time+ * constant, so it works identically on Docker (read-only rootfs), the PyPI+ * `deeptutor start` launcher, and source dev.+ */+export function useAuthStatus(): AuthStatusState {+ const [state, setState] = useState<AuthStatusState>(INITIAL);++ useEffect(() => {+ let alive = true;+ fetchAuthStatus().then((status) => {+ if (!alive) return;+ setState({+ enabled: Boolean(status?.enabled),+ authenticated: Boolean(status?.authenticated),+ isAdmin: status?.role === "admin",+ loading: false,+ });+ });+ return () => {+ alive = false;+ };+ }, []);++ return state;+}diff --git a/web/lib/api.ts b/web/lib/api.tsindex dad0224b0..0ce83b451 100644--- a/web/lib/api.ts+++ b/web/lib/api.ts@@ -49,7 +49,21 @@ export function parseAuthEnabled(raw: string | undefined): boolean {return /^(1|true|yes|on)$/i.test((raw ?? "").trim());}-const AUTH_ENABLED = parseAuthEnabled(process.env.DEEPTUTOR_AUTH_ENABLED);+// Whether auth is enabled, learned at runtime — NOT from a build-time env var.+// The browser bundle never sees `DEEPTUTOR_AUTH_ENABLED` (it isn't a+// `NEXT_PUBLIC_` var, so Next.js does not inline it), and auth is a runtime+// setting that must not be baked at build time anyway. `fetchAuthStatus()` in+// `web/lib/auth.ts` calls `setRuntimeAuthEnabled()` once the backend reports the+// real state. Until then it defaults to `false`, so a stray 401 in the default+// auth-disabled deployment never bounces the user to /login. The server-side+// gate (web/proxy.ts middleware) enforces auth independently; this flag only+// drives the client's in-session 401 → /login redirect.+let runtimeAuthEnabled = false;++/** Record the backend-reported auth state for `apiFetch`'s 401 redirect gate. */+export function setRuntimeAuthEnabled(enabled: boolean): void {+ runtimeAuthEnabled = enabled;+}/*** Authenticated fetch wrapper. Behaves identically to `fetch` but automatically@@ -69,7 +83,7 @@ export async function apiFetch(if (res.status === 401 &&- AUTH_ENABLED &&+ runtimeAuthEnabled &&!skipAuthRedirect &&typeof window !== "undefined") {diff --git a/web/lib/auth.ts b/web/lib/auth.tsindex 2cc8ccb17..354d1522b 100644--- a/web/lib/auth.ts+++ b/web/lib/auth.ts@@ -1,12 +1,11 @@-import { apiFetch, apiUrl, parseAuthEnabled } from "@/lib/api";+import { apiFetch, apiUrl, setRuntimeAuthEnabled } from "@/lib/api";-// ``DEEPTUTOR_AUTH_ENABLED`` is exported by the container entrypoint on every-// start (read from ``data/user/settings/auth.json``). ``parseAuthEnabled``-// evaluates it at runtime (not a ``=== "true"`` literal comparison) so the-// minifier cannot constant-fold the check. See lib/api.ts.-export const AUTH_ENABLED = parseAuthEnabled(- process.env.DEEPTUTOR_AUTH_ENABLED,-);+// Auth state is resolved at runtime from the backend (`/api/v1/auth/status`),+// not from a build-time/env constant: the browser bundle never sees+// `DEEPTUTOR_AUTH_ENABLED` (not a `NEXT_PUBLIC_` var), and auth is runtime+// config that must not be baked into the bundle. Components observe it via the+// `useAuthStatus` hook (web/hooks/useAuthStatus.ts); `apiFetch`'s redirect gate+// is driven by `setRuntimeAuthEnabled`, which `fetchAuthStatus` calls below.export interface AuthStatus {enabled: boolean;@@ -25,7 +24,11 @@ export async function fetchAuthStatus(): Promise<AuthStatus | null> {try {const res = await apiFetch(apiUrl("/api/v1/auth/status"));if (!res.ok) return null;- return res.json();+ const status: AuthStatus = await res.json();+ // Record the real auth state so apiFetch's in-session 401 → /login redirect+ // fires only when auth is actually enabled.+ setRuntimeAuthEnabled(Boolean(status.enabled));+ return status;} catch {return null;}diff --git a/web/next.config.js b/web/next.config.jsindex 503087946..fa5a552ad 100644--- a/web/next.config.js+++ b/web/next.config.js@@ -88,6 +88,16 @@ const nextConfig = {// This eliminates the need to copy the full node_modules into Docker production imagesoutput: "standalone",+ // web/proxy.ts (the Next.js middleware) forwards /api/* and /ws/* to the+ // backend by buffering and re-issuing the request. Next caps the buffered+ // request body at 10MB by default, but the backend accepts uploads up to+ // 100MB (DocumentValidator.MAX_FILE_SIZE). Raise the proxy cap to match (plus+ // multipart overhead headroom) so knowledge-base document uploads aren't+ // silently truncated when they pass through the proxy.+ experimental: {+ proxyClientMaxBodySize: 110 * 1024 * 1024,+ },+// Move dev indicator to bottom-right cornerdevIndicators: {position: "bottom-right",diff --git a/web/tests/api-auth-redirect.test.ts b/web/tests/api-auth-redirect.test.tsindex 7f199a959..a6c542ded 100644--- a/web/tests/api-auth-redirect.test.ts+++ b/web/tests/api-auth-redirect.test.ts@@ -1,12 +1,12 @@import test from "node:test";import assert from "node:assert/strict";-// AUTH_ENABLED is read at module-load time, so the environment must be-// configured before the module under test is imported. The frontend now uses-// relative paths; the URL forwarding happens in proxy.ts at request time,-// reading DEEPTUTOR_API_BASE_URL (set by the container entrypoint on every-// start from data/user/settings/system.json).-process.env.DEEPTUTOR_AUTH_ENABLED = "true";+// Auth state is resolved at runtime, not from a build-time env var: apiFetch's+// 401 → /login redirect is gated by a flag set via setRuntimeAuthEnabled (which+// web/lib/auth.ts → fetchAuthStatus calls once the backend reports the real+// state). The frontend uses relative paths; URL forwarding happens in proxy.ts+// at request time, reading DEEPTUTOR_API_BASE_URL set by the launcher / Docker+// entrypoint from data/user/settings.let apiModulePromise: Promise<typeof import("../lib/api")> | null = null;@@ -61,7 +61,8 @@ function tick(): Promise<void> {}test("apiFetch redirects to /login on 401 when auth is enabled and no opt-out", async () => {- const { apiFetch } = await loadApiModule();+ const { apiFetch, setRuntimeAuthEnabled } = await loadApiModule();+ setRuntimeAuthEnabled(true);const win = installWindow("/dashboard");const restore = stubFetch(jsonResponse(401, { detail: "unauthorized" }));try {@@ -75,6 +76,24 @@ test("apiFetch redirects to /login on 401 when auth is enabled and no opt-out",}});+test("apiFetch does NOT redirect on 401 when auth is disabled (default)", async () => {+ // Regression guard: in the default auth-disabled deployment the runtime flag+ // is never turned on, so a stray 401 must NOT bounce the user to /login.+ const { apiFetch, setRuntimeAuthEnabled } = await loadApiModule();+ setRuntimeAuthEnabled(false);+ const win = installWindow("/dashboard");+ const restore = stubFetch(jsonResponse(401, { detail: "unauthorized" }));+ try {+ const res = await apiFetch("http://localhost:8001/api/v1/knowledge/list");+ assert.equal(res.status, 401);+ assert.equal(win.redirectedTo(), null);+ } finally {+ restore();+ clearWindow();+ setRuntimeAuthEnabled(true);+ }+});+test("apiFetch does NOT redirect on 401 when skipAuthRedirect is set", async () => {// Regression guard: the login endpoint returns 401 for wrong credentials, and// that must reach the caller as an inline error instead of reloading the page.