diff --git a/internal/server/server.go b/internal/server/server.go index 630080f..7f29bcc 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -260,8 +260,7 @@ func (s *Server) handleSession(w http.ResponseWriter, r *http.Request) { } session, csrfToken, err := s.auth.CSRFToken(r.Context(), sessionToken, existingCSRF) if errors.Is(err, auth.ErrUnauthorized) { - s.clearAuthCookies(w) - writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required") + s.authenticationRequired(w, r) return } if err != nil { @@ -296,8 +295,7 @@ func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { if _, err := s.auth.ValidateCSRF(r.Context(), sessionToken, csrfToken); err != nil { switch { case errors.Is(err, auth.ErrUnauthorized): - s.clearAuthCookies(w) - writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required") + s.authenticationRequired(w, r) case errors.Is(err, auth.ErrInvalidCSRF): writeError(w, http.StatusForbidden, "invalid_csrf", "CSRF validation failed") default: @@ -346,8 +344,7 @@ func (s *Server) handleAPI(w http.ResponseWriter, r *http.Request) { if _, err := s.auth.ValidateCSRF(r.Context(), sessionToken, csrfToken); err != nil { switch { case errors.Is(err, auth.ErrUnauthorized): - s.clearAuthCookies(w) - writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required") + s.authenticationRequired(w, r) case errors.Is(err, auth.ErrInvalidCSRF): writeError(w, http.StatusForbidden, "invalid_csrf", "CSRF validation failed") default: @@ -419,7 +416,7 @@ func (s *Server) decodeJSON(w http.ResponseWriter, r *http.Request, destination func (s *Server) sessionToken(w http.ResponseWriter, r *http.Request) (string, bool) { cookie, err := r.Cookie(sessionCookieName) if err != nil || cookie.Value == "" { - writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required") + s.authenticationRequired(w, r) return "", false } return cookie.Value, true @@ -432,8 +429,7 @@ func (s *Server) requireAuthenticated(w http.ResponseWriter, r *http.Request) bo } if _, err := s.auth.Authenticate(r.Context(), sessionToken); err != nil { if errors.Is(err, auth.ErrUnauthorized) { - s.clearAuthCookies(w) - writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required") + s.authenticationRequired(w, r) } else { s.logger.Error("request authentication failed", "error", err) writeError(w, http.StatusInternalServerError, "internal_error", "an internal error occurred") @@ -443,6 +439,21 @@ func (s *Server) requireAuthenticated(w http.ResponseWriter, r *http.Request) bo return true } +// authenticationRequired preserves JSON semantics for API clients while +// making a direct browser navigation land on the login screen instead of a +// raw {"error":...} document. Frontend fetches explicitly request JSON and +// are handled by the shared vocat:unauthorized event. +func (s *Server) authenticationRequired(w http.ResponseWriter, r *http.Request) { + s.clearAuthCookies(w) + w.Header().Set("Cache-Control", "no-store") + if (r.Method == http.MethodGet || r.Method == http.MethodHead) && + strings.Contains(strings.ToLower(r.Header.Get("Accept")), "text/html") { + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required") +} + func (s *Server) validateDoubleSubmitCSRF(w http.ResponseWriter, r *http.Request) (string, bool) { headerToken := r.Header.Get(csrfHeaderName) cookie, err := r.Cookie(csrfCookieName) diff --git a/internal/server/server_test.go b/internal/server/server_test.go index da6c2d7..25858a3 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -241,6 +241,30 @@ func TestUnifiedAPIErrors(t *testing.T) { } } +func TestUnauthenticatedBrowserNavigationRedirectsToLogin(t *testing.T) { + app := newTestApplication(t) + client := *app.client + client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + } + request, err := http.NewRequest(http.MethodGet, app.server.URL+"/api/devices", nil) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Accept", "text/html,application/xhtml+xml") + response, err := client.Do(request) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusSeeOther { + t.Fatalf("navigation status = %d", response.StatusCode) + } + if location := response.Header.Get("Location"); location != "/login" { + t.Fatalf("navigation location = %q", location) + } +} + func TestNewRequiresIndex(t *testing.T) { database, err := store.Open(context.Background(), ":memory:") if err != nil { diff --git a/web/src/App.tsx b/web/src/App.tsx index b060371..a51910c 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -45,7 +45,8 @@ function RequireAuth({ children }: { children: ReactElement }) { const location = useLocation(); if (!ready) return ; if (!isAuthenticated) { - return ; + const redirect = `${location.pathname}${location.search}${location.hash}`; + return ; } return children; } diff --git a/web/src/api.ts b/web/src/api.ts index f68f1d3..e687b01 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -9,6 +9,18 @@ import { tl } from "./lib/i18n"; const CSRF_KEY = "vocat.csrf"; +// Authenticated pages and same-origin plugin frames share this signal. Clear +// the mutation token immediately so a revoked session cannot leave stale auth +// state behind in the browser. +export function notifyUnauthorized() { + try { + sessionStorage.removeItem(CSRF_KEY); + } catch { + /* ignore unavailable storage */ + } + window.dispatchEvent(new Event("vocat:unauthorized")); +} + function isMutation(method: string) { return !["GET", "HEAD", "OPTIONS"].includes(method.toUpperCase()); } @@ -94,14 +106,17 @@ export async function api(path: string, options: RequestOptions = {}): Promis : JSON.stringify(snakeize(options.body)), }); - if (options.raw) return response as T; + if (options.raw) { + if (response.status === 401) notifyUnauthorized(); + return response as T; + } const contentType = response.headers.get("content-type") || ""; const payload = contentType.includes("application/json") ? await response.json() : { message: await response.text() }; const normalized = camelize>(payload); if (!response.ok) { - if (response.status === 401) window.dispatchEvent(new Event("vocat:unauthorized")); + if (response.status === 401) notifyUnauthorized(); const nested = normalized.error; const detail = nested && typeof nested === "object" ? { diff --git a/web/src/components/devices/shared.ts b/web/src/components/devices/shared.ts index a74ca27..f43bbcc 100644 --- a/web/src/components/devices/shared.ts +++ b/web/src/components/devices/shared.ts @@ -3,6 +3,7 @@ import { message } from "../ui"; import type { DeviceDetail, DeviceModem, ModemPnn } from "./types"; import { tl } from "../../lib/i18n"; import { lookupCarrier } from "../../lib/carrier"; +import { notifyUnauthorized } from "../../api"; /* --------------------------------------------------------------------------- * Lifecycle / status helpers (ported from the VoHive reference). @@ -283,6 +284,7 @@ export async function readEventStream( credentials: "include", signal: handlers.signal, }); + if (response.status === 401) notifyUnauthorized(); if (!response.ok) throw new Error((await response.text()) || `HTTP ${response.status}`); if (!response.body) throw new Error("No stream body"); diff --git a/web/src/pages/SettingsPage.tsx b/web/src/pages/SettingsPage.tsx index 4d05e6b..01f0070 100644 --- a/web/src/pages/SettingsPage.tsx +++ b/web/src/pages/SettingsPage.tsx @@ -271,9 +271,12 @@ export default function SettingsPage() { if (!confirmed) return; setApplyingUpdate(true); try { - const data = await api<{ message?: string }>("/system/update/apply", { method: "POST", body: {} }); + const data = await api<{ message?: string; reauthenticationRequired?: boolean }>("/system/update/apply", { method: "POST", body: {} }); message.success(data?.message || t("正在更新...")); - window.setTimeout(() => window.location.reload(), 5000); + window.setTimeout(() => { + if (data?.reauthenticationRequired) window.location.replace("/login"); + else window.location.reload(); + }, 1500); } catch (e) { message.error(e instanceof Error ? e.message : t("应用更新失败")); } finally { diff --git a/web/src/store/auth.tsx b/web/src/store/auth.tsx index f2678ab..d9fc01b 100644 --- a/web/src/store/auth.tsx +++ b/web/src/store/auth.tsx @@ -62,6 +62,15 @@ export function AuthProvider({ children }: { children: ReactNode }) { } }, []); + useEffect(() => { + const unauthorized = () => { + setUser(null); + setReady(true); + }; + window.addEventListener("vocat:unauthorized", unauthorized); + return () => window.removeEventListener("vocat:unauthorized", unauthorized); + }, []); + useEffect(() => { void refresh(); }, [refresh]);