A modern and elegant dashboard for network traffic visualization and analysis.
feat: Refactor authentication logic to a global AuthGuard, update the auth check endpoint, and enhance various hooks and utility functions.
luolei61bb2a56008d
diff --git a/apps/web/app/[locale]/dashboard/components/header/index.tsx b/apps/web/app/[locale]/dashboard/components/header/index.tsxindex c1553b5..72df823 100644--- a/apps/web/app/[locale]/dashboard/components/header/index.tsx+++ b/apps/web/app/[locale]/dashboard/components/header/index.tsx@@ -238,6 +238,7 @@ export function Header({{/* Listening Indicators */}{listeningBackends.length > 0 && (+ <TooltipProvider delayDuration={100}><div className="hidden md:flex items-center gap-1">{listeningBackends.slice(0, 3).map((backend) => {// Determine color based on health status@@ -257,8 +258,7 @@ export function Header({(status === 'healthy' ? 'Connected' : status === 'unhealthy' ? 'Connection failed' : 'Checking...');return (- <TooltipProvider key={backend.id} delayDuration={100}>- <Tooltip>+ <Tooltip key={backend.id}><TooltipTrigger asChild><Badgevariant="outline"@@ -285,7 +285,6 @@ export function Header({</div></TooltipContent></Tooltip>- </TooltipProvider>);})}{listeningBackends.length > 3 && (@@ -294,6 +293,7 @@ export function Header({</Badge>)}</div>+ </TooltipProvider>)}</div>diff --git a/apps/web/app/[locale]/dashboard/hooks/use-dashboard.ts b/apps/web/app/[locale]/dashboard/hooks/use-dashboard.tsindex 2ed2f60..570ac41 100644--- a/apps/web/app/[locale]/dashboard/hooks/use-dashboard.ts+++ b/apps/web/app/[locale]/dashboard/hooks/use-dashboard.ts@@ -154,7 +154,7 @@ export function useDashboard(): UseDashboardReturn {onMessage: useCallback((stats: StatsSummary) => {if (!activeBackendId) return;- setAutoRefreshTick((tick) => tick + 1);+ setAutoRefreshTick((tick) => (tick + 1) % 3600);queryClient.setQueryData(getSummaryQueryKey(activeBackendId, stableTimeRange),(previous) => ({@@ -278,11 +278,11 @@ export function useDashboard(): UseDashboardReturn {async (backendId: number) => {try {await api.setActiveBackend(backendId);- await backendsQuery.refetch();+ const { data: latestBackends } = await backendsQuery.refetch();await refreshNow(true);- // Check backend health after switching- const switchedBackend = backends.find(b => b.id === backendId);+ // Check backend health after switching (use fresh data from refetch)+ const switchedBackend = latestBackends?.find(b => b.id === backendId);if (switchedBackend?.health?.status === 'unhealthy') {toast.warning(dashboardT("backendUnhealthyTitle"),@@ -296,7 +296,7 @@ export function useDashboard(): UseDashboardReturn {console.error("Failed to switch backend:", err);}},- [backendsQuery.refetch, refreshNow, backends, backendT]+ [backendsQuery.refetch, refreshNow, dashboardT]);const handleBackendChange = useCallback(async () => {@@ -339,7 +339,7 @@ export function useDashboard(): UseDashboardReturn {const intervalMs =activeTab === "rules" ? 30000 : shouldReducePolling ? 30000 : 5000;const interval = setInterval(() => {- setAutoRefreshTick((tick) => tick + 1);+ setAutoRefreshTick((tick) => (tick + 1) % 3600);setTimeRange(getPresetTimeRange(timePreset));}, intervalMs);return () => clearInterval(interval);@@ -351,7 +351,7 @@ export function useDashboard(): UseDashboardReturn {return;const intervalMs = 5000;const interval = setInterval(() => {- setAutoRefreshTick((tick) => tick + 1);+ setAutoRefreshTick((tick) => (tick + 1) % 3600);queryClient.invalidateQueries({ queryKey: ["stats"] });}, intervalMs);return () => clearInterval(interval);diff --git a/apps/web/app/[locale]/dashboard/layout.tsx b/apps/web/app/[locale]/dashboard/layout.tsxindex 63d459f..e24f0f8 100644--- a/apps/web/app/[locale]/dashboard/layout.tsx+++ b/apps/web/app/[locale]/dashboard/layout.tsx@@ -1,72 +1,14 @@"use client";-import { ReactNode, useEffect } from "react";-import { authKeys } from "@/lib/auth-queries";-import { useRequireAuth, useAuth } from "@/lib/auth";-import { LoginDialog } from "@/components/features/auth";-import { toast } from "sonner";-import { useTranslations } from "next-intl";-import { useQueryClient } from "@tanstack/react-query";+import { type ReactNode } from "react";export default function DashboardLayout({children,}: {children: ReactNode;}) {- const t = useTranslations("auth");- const queryClient = useQueryClient();- const { showLogin, isLoading, authEnabled, error } = useRequireAuth();- const { login, confirmLogin } = useAuth();-- // ...-- const handleLogin = async (token: string): Promise<boolean> => {- try {- // Don't update state immediately to allow success animation to play- const success = await login(token, false);-- if (success) {- // Wait for animation to finish (2.5s matches LoginDialog animation)- setTimeout(() => {- confirmLogin();- // Invalidate auth state to trigger re-check- queryClient.invalidateQueries({ queryKey: authKeys.state() });- }, 2500);- return true;- } else {- toast.error(t("invalidToken"));- return false;- }- } catch (error) {- toast.error(t("invalidToken"));- return false;- }- };-- // Show loading state while checking auth- if (isLoading) {- return (- <div className="flex items-center justify-center min-h-screen">- <div className="animate-pulse text-muted-foreground">- Loading...- </div>- </div>- );- }-- return (- <>- {children}- <LoginDialog- open={showLogin}- onOpenChange={(open) => {- // Prevent closing the dialog when auth is required- if (!open && showLogin) {- return;- }- }}- onLogin={handleLogin}- />- </>- );+ // Auth is handled globally by AuthGuard in the root layout.+ // This layout is kept as a pass-through for potential future+ // dashboard-specific layout needs.+ return <>{children}</>;}diff --git a/apps/web/components/features/auth/auth-guard.tsx b/apps/web/components/features/auth/auth-guard.tsxindex 35f341b..453d1fc 100644--- a/apps/web/components/features/auth/auth-guard.tsx+++ b/apps/web/components/features/auth/auth-guard.tsx@@ -1,29 +1,45 @@"use client";import { useRequireAuth, useAuth } from "@/lib/auth";+import { useQueryClient } from "@tanstack/react-query";+import { authKeys } from "@/lib/auth-queries";+import { useTranslations } from "next-intl";+import { toast } from "sonner";import { LoginDialog } from "./login-dialog";export function AuthGuard() {const { showLogin } = useRequireAuth();const { login, confirmLogin } = useAuth();-- const handleLogin = async (token: string) => {- const success = await login(token, false);- if (success) {- setTimeout(() => {- confirmLogin();- }, 2500);- return true;+ const queryClient = useQueryClient();+ const t = useTranslations("auth");++ const handleLogin = async (token: string): Promise<boolean> => {+ try {+ const success = await login(token, false);+ if (success) {+ // Wait for animation to finish (2.5s matches LoginDialog animation)+ setTimeout(() => {+ confirmLogin();+ // Invalidate auth state to trigger re-check+ queryClient.invalidateQueries({ queryKey: authKeys.state() });+ }, 2500);+ return true;+ } else {+ toast.error(t("invalidToken"));+ return false;+ }+ } catch {+ toast.error(t("invalidToken"));+ return false;}- return false;};if (!showLogin) return null;return (- <LoginDialog- open={true}- onOpenChange={() => {}}+ <LoginDialog+ open={true}+ onOpenChange={() => {}}onLogin={handleLogin}/>);diff --git a/apps/web/hooks/use-version-check.ts b/apps/web/hooks/use-version-check.tsindex 8ca6d39..ca26123 100644--- a/apps/web/hooks/use-version-check.ts+++ b/apps/web/hooks/use-version-check.ts@@ -1,6 +1,6 @@"use client";-import { useState, useEffect, useCallback } from "react";+import { useState, useEffect, useCallback, useRef } from "react";const GITHUB_PACKAGE_URL ="https://raw.githubusercontent.com/foru17/neko-master/refs/heads/main/package.json";@@ -41,11 +41,16 @@ export function useVersionCheck(currentVersion: string): VersionCheckResult {const [hasUpdate, setHasUpdate] = useState(false);const [isChecking, setIsChecking] = useState(false);const [stars, setStars] = useState<number | null>(null);+ const abortRef = useRef<AbortController | null>(null);const check = useCallback(async () => {+ // Abort any in-flight request before starting a new one+ abortRef.current?.abort();+ const controller = new AbortController();+ abortRef.current = controller;+setIsChecking(true);try {- const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT);// Fetch version and stars in parallel@@ -62,6 +67,9 @@ export function useVersionCheck(currentVersion: string): VersionCheckResult {clearTimeout(timeoutId);+ // Don't update state if aborted (e.g. component unmounted)+ if (controller.signal.aborted) return;+// Handle version checkif (pkgRes.status === "fulfilled" && pkgRes.value.ok) {const pkg = await pkgRes.value.json();@@ -81,7 +89,9 @@ export function useVersionCheck(currentVersion: string): VersionCheckResult {} catch {// Silently fail — network errors, timeouts, CORS issues, etc.} finally {- setIsChecking(false);+ if (!controller.signal.aborted) {+ setIsChecking(false);+ }}}, [currentVersion]);@@ -95,6 +105,8 @@ export function useVersionCheck(currentVersion: string): VersionCheckResult {return () => {clearTimeout(initialTimer);clearInterval(interval);+ // Abort any in-flight request on unmount+ abortRef.current?.abort();};}, [check]);diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.tsindex 22e0fcd..a70f49b 100644--- a/apps/web/lib/api.ts+++ b/apps/web/lib/api.ts@@ -616,9 +616,9 @@ export function formatDateTimeForInput(date: Date): string {return date.toISOString().slice(0, 16); // YYYY-MM-DDTHH:mm}-export function formatDateTimeDisplay(isoString: string): string {+export function formatDateTimeDisplay(isoString: string, locale?: string): string {const date = new Date(isoString);- return date.toLocaleString('zh-CN', {+ return date.toLocaleString(locale, {month: 'short',day: 'numeric',hour: '2-digit',diff --git a/apps/web/lib/auth-queries.ts b/apps/web/lib/auth-queries.tsindex bc69b0b..e224434 100644--- a/apps/web/lib/auth-queries.ts+++ b/apps/web/lib/auth-queries.ts@@ -88,16 +88,6 @@ export function useLogout() {});}-// Hook to check if user is authenticated-// Deprecated: logic moved to AuthProvider-export function useIsAuthenticated() {- const { data: authState, isLoading } = useAuthState();- if (isLoading) return { isAuthenticated: false, isLoading: true };- if (authState && !authState.enabled) return { isAuthenticated: true, isLoading: false };- // We can't know for sure here without context, defaulting to true to avoid UI flicker if not using AuthProvider- return { isAuthenticated: true, isLoading: false };-}-// Helper function to get auth headers for API requests// Cookies are handled automatically by browserexport function getAuthHeaders(): Record<string, string> {diff --git a/apps/web/lib/auth.tsx b/apps/web/lib/auth.tsxindex 485e172..310f06e 100644--- a/apps/web/lib/auth.tsx+++ b/apps/web/lib/auth.tsx@@ -65,26 +65,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {return;}- // Auth is enabled. Check if we have a valid session.- // We can try to hit a protected endpoint or we can assume we are NOT authenticated- // until we prove otherwise via some check.-- // However, we don't have a "am I logged in" endpoint yet.- // But `websocket.ts` or other queries will fail if not.-- // To prevent "Login" screen flash or "Dashboard" flash, we need to know.- // As a workaround, let's try to verify with an empty token or check a lightweight protected endpoint.- // Actually, let's use a specific check.-- // The `app.ts` allows public routes.- // Let's rely on the fact that if we just logged in, we set `isAuthenticated` to true.- // If we refresh, we reset.-- // We NEED a way to check validity on mount.- // Since I didn't add a specific endpoint, I will use `GET /api/db/retention` which is protected- // and lightweight.-- const checkRes = await fetch("/api/db/retention");+ // Auth is enabled – check if we have a valid session by hitting a+ // protected, lightweight endpoint. `/api/backends` is a core endpoint+ // that will always exist and is protected by the auth middleware.+ const checkRes = await fetch("/api/backends");if (checkRes.ok) {setIsAuthenticated(true);} else {@@ -184,12 +168,6 @@ export function useAuth() {return context;}-// Helper function to get auth headers for API requests-// Deprecated: Cookies are handled automatically by browser-export function getAuthHeaders(): Record<string, string> {- return {};-}-// Hook to determine if login dialog should be shownexport function useRequireAuth() {const { authState, isAuthenticated, isLoading } = useAuth();diff --git a/apps/web/lib/settings.ts b/apps/web/lib/settings.tsindex b21047b..bbea2ab 100644--- a/apps/web/lib/settings.ts+++ b/apps/web/lib/settings.ts@@ -1,6 +1,6 @@"use client";-import { useState, useEffect, useCallback, useSyncExternalStore, useMemo } from "react";+import { useCallback, useSyncExternalStore } from "react";export type FaviconProvider = "google" | "faviconim" | "off";@@ -115,20 +115,20 @@ function getServerSnapshot(): UserSettings {// React hook for settings using useSyncExternalStore for instant syncexport function useSettings() {+ // useSyncExternalStore already returns a stable snapshot reference;+ // it only changes when the subscribe callback fires and getSnapshot+ // returns a different value (cachedSettings is replaced in saveSettings).const settings = useSyncExternalStore(subscribe,getSnapshot,getServerSnapshot);- // Use useMemo to ensure stable reference- const stableSettings = useMemo(() => settings, [settings.faviconProvider]);-const setSettings = useCallback((newSettings: Partial<UserSettings>) => {saveSettings(newSettings);}, []);- return { settings: stableSettings, setSettings, mounted: true };+ return { settings, setSettings, mounted: true };}// Generate favicon URL based on providerdiff --git a/apps/web/lib/utils.ts b/apps/web/lib/utils.tsindex 7fb9763..1de7a77 100644--- a/apps/web/lib/utils.ts+++ b/apps/web/lib/utils.ts@@ -6,7 +6,8 @@ export function cn(...inputs: ClassValue[]) {}export function formatBytes(bytes: number, decimals = 2): string {- if (bytes === 0) return "0 B";+ if (!Number.isFinite(bytes) || bytes === 0) return "0 B";+ if (bytes < 0) return `-${formatBytes(-bytes, decimals)}`;const k = 1024;const dm = decimals < 0 ? 0 : decimals;@@ -65,23 +66,3 @@ export function formatDuration(dateString: string): string {if (minutes > 0) return `${minutes}m ago`;return `${seconds}s ago`;}--export function getDomainColor(domain: string): string {- const colors = [- "#18181b",- "#27272a",- "#3f3f46",- "#52525b",- "#71717a",- "#a1a1aa",- "#d4d4d8",- "#e4e4e7",- ];-- let hash = 0;- for (let i = 0; i < domain.length; i++) {- hash = domain.charCodeAt(i) + ((hash << 5) - hash);- }-- return colors[Math.abs(hash) % colors.length];-}diff --git a/apps/web/package.json b/apps/web/package.jsonindex 75e05ea..2b62d09 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -17,7 +17,6 @@"@radix-ui/react-radio-group": "^1.3.8","@radix-ui/react-scroll-area": "^1.2.10","@tanstack/react-query": "^5.90.20",- "@types/react-copy-to-clipboard": "^5.0.7","@xyflow/react": "^12.10.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -37,16 +36,17 @@"react-simple-maps": "^3.0.0","recharts": "^2.15.4","sonner": "^2.0.7",- "tailwind-merge": "^2.6.1"- },- "devDependencies": {"@radix-ui/react-dropdown-menu": "^2.1.16","@radix-ui/react-select": "^2.2.6","@radix-ui/react-separator": "^1.1.8","@radix-ui/react-slot": "^1.2.4","@radix-ui/react-switch": "^1.2.6","@radix-ui/react-tabs": "^1.1.13",+ "tailwind-merge": "^2.6.1"+ },+ "devDependencies": {"@tailwindcss/postcss": "^4.1.0",+ "@types/react-copy-to-clipboard": "^5.0.7","@tanstack/react-query-devtools": "^5.91.3","@types/node": "^22","@types/react": "^19",