feat(webui): redirect to /login on any API 401 response

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
m4
2026-08-08 09:17:06 +08:00
parent ce01a6022b
commit 4a652fd67f
4 changed files with 98 additions and 0 deletions
@@ -0,0 +1,9 @@
"use client";
import { useEffect } from "react";
import { installAuthRedirect } from "@/lib/authRedirect";
export function AuthRedirectInstaller() {
useEffect(() => installAuthRedirect(), []);
return null;
}
+2
View File
@@ -1,6 +1,7 @@
import type { Metadata, Viewport } from "next";
import { NuqsAdapter } from "nuqs/adapters/next/app";
import { ThemeProvider, ThemedToaster } from "@/providers/ThemeProvider";
import { AuthRedirectInstaller } from "./components/AuthRedirectInstaller";
import { THEME_STORAGE_KEY } from "@/lib/theme";
import "katex/dist/katex.min.css";
import "@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css";
@@ -41,6 +42,7 @@ export default function RootLayout({
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
<NuqsAdapter>
<ThemeProvider>
<AuthRedirectInstaller />
{children}
<ThemedToaster />
</ThemeProvider>
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { shouldRedirectFor } from "./authRedirect";
describe("shouldRedirectFor", () => {
it("redirects on 401 for same-origin API paths", () => {
expect(shouldRedirectFor("/api/conversations", 401, "/")).toBe(true);
expect(
shouldRedirectFor("http://localhost/api/usage/summary", 401, "/chat")
).toBe(true);
});
it("ignores non-401 statuses", () => {
expect(shouldRedirectFor("/api/conversations", 200, "/")).toBe(false);
expect(shouldRedirectFor("/api/conversations", 500, "/")).toBe(false);
});
it("ignores non-API paths", () => {
expect(shouldRedirectFor("/login", 401, "/")).toBe(false);
expect(shouldRedirectFor("/favicon.ico", 401, "/")).toBe(false);
});
it("ignores the login endpoint itself", () => {
expect(shouldRedirectFor("/api/auth/login", 401, "/login")).toBe(false);
expect(shouldRedirectFor("/api/auth/login", 401, "/")).toBe(false);
});
it("ignores 401 while already on the login page", () => {
expect(shouldRedirectFor("/api/auth/me", 401, "/login")).toBe(false);
});
it("ignores unparseable urls", () => {
expect(shouldRedirectFor("http://[", 401, "/")).toBe(false);
});
});
+53
View File
@@ -0,0 +1,53 @@
export function shouldRedirectFor(
url: string,
status: number,
pathname: string
): boolean {
if (status !== 401) return false;
if (pathname.startsWith("/login")) return false;
let path: string;
try {
path = new URL(url, "http://localhost").pathname;
} catch {
return false;
}
if (!path.startsWith("/api/")) return false;
if (path === "/api/auth/login") return false;
return true;
}
// Wraps window.fetch so any same-origin API 401 sends the browser to the
// login page, preserving the current location as ?next. Returns a restore
// function. Middleware only covers document navigations; fetch calls
// (health checks, chat, polling) would otherwise fail silently as "offline".
export function installAuthRedirect(): () => void {
const original = window.fetch;
const wrapped: typeof window.fetch = async (input, init) => {
const response = await original(input, init);
try {
const url =
typeof input === "string"
? input
: input instanceof Request
? input.url
: input.toString();
const resolved = new URL(url, window.location.origin);
if (
resolved.origin === window.location.origin &&
shouldRedirectFor(url, response.status, window.location.pathname)
) {
const next = encodeURIComponent(
window.location.pathname + window.location.search
);
window.location.replace(`/login?next=${next}`);
}
} catch {
// Redirect failures must not break the caller's response handling.
}
return response;
};
window.fetch = wrapped;
return () => {
window.fetch = original;
};
}