diff --git a/src/api/__tests__/client/client.test.ts b/src/api/__tests__/client/client.test.ts index 962d32a..a0b1435 100644 --- a/src/api/__tests__/client/client.test.ts +++ b/src/api/__tests__/client/client.test.ts @@ -333,5 +333,17 @@ describe("client", () => { expect(formatApiError(new Error("generic"), "en")).toBe("Generic"); expect(formatApiError(new Error("generic"), "tr")).toBe("İşlem tamamlanamadı: Generic"); }); + + it("does not expose network, runtime, or provider errors to users", () => { + expect(formatApiError(new TypeError("Failed to fetch"), "tr")).toBe( + "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene.", + ); + expect(formatApiError(new TypeError("Cannot read properties of null (reading 'user')"), "tr")).toBe( + "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene.", + ); + expect(formatApiError(new Error("useAuth must be used within AuthProvider"), "en")).toBe( + "Something went wrong while loading the page. Reload the page and try again.", + ); + }); }); }); diff --git a/src/api/client/client.ts b/src/api/client/client.ts index 163facd..e0e7363 100644 --- a/src/api/client/client.ts +++ b/src/api/client/client.ts @@ -286,6 +286,24 @@ function sentenceCase(message: string): string { return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1); } +function formatRuntimeErrorMessage(message: string, locale: Locale): string | null { + const normalized = normalizeApiMessage(message); + if (/^(failed to fetch|load failed|networkerror|network request failed)/.test(normalized)) { + return locale === "tr" + ? "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene." + : "Could not reach the server. Check your connection and try again."; + } + if ( + /^(typeerror:\s*)?cannot (read|set) propert(y|ies) of (null|undefined)/.test(normalized) || + /^use\w+ must be used within \w+provider/.test(normalized) + ) { + return locale === "tr" + ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene." + : "Something went wrong while loading the page. Reload the page and try again."; + } + return null; +} + function formatNumber(value: string, locale: Locale): string { return new Intl.NumberFormat(locale === "tr" ? "tr-TR" : "en-US").format(Number(value)); } @@ -455,6 +473,8 @@ export function formatApiErrorMessage(message: string, locale: Locale = currentL const normalized = normalizeApiMessage(message); const known = API_ERROR_MESSAGES[normalized]?.[locale]; if (known) return known; + const runtime = formatRuntimeErrorMessage(message, locale); + if (runtime) return runtime; const validation = formatValidationMessage(message, locale); if (validation) return validation; if (locale === "tr") return `İşlem tamamlanamadı: ${sentenceCase(message)}`; @@ -477,6 +497,12 @@ export function formatApiError(err: unknown, locale: Locale = currentLocale()): if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again."; return formatApiErrorMessage(err.message, locale); } + if (err instanceof TypeError) { + return formatRuntimeErrorMessage(err.message, locale) ?? + (locale === "tr" + ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene." + : "Something went wrong while loading the page. Reload the page and try again."); + } if (err instanceof Error) return formatApiErrorMessage(err.message, locale); return locale === "tr" ? "Bir şeyler ters gitti." : "Something went wrong."; } diff --git a/src/pages/dashboard-page.test.tsx b/src/pages/dashboard-page.test.tsx index 142ffb0..20ac3cd 100644 --- a/src/pages/dashboard-page.test.tsx +++ b/src/pages/dashboard-page.test.tsx @@ -5,25 +5,25 @@ import { PreferencesProvider } from "@/stores/preferences-context"; const { navigate, authUser } = vi.hoisted(() => ({ navigate: vi.fn(), - authUser: { role: "student" }, + authUser: { authenticated: true, role: "student" }, })); vi.mock("@tanstack/solid-router", () => ({ Link: (props: { to: string; children: JSX.Element; class?: string }) => ( {props.children} ), - Navigate: () => null, + Navigate: (props: { to: string }) => redirect:{props.to}, useNavigate: () => navigate, })); vi.mock("@/stores/auth-context", () => ({ useAuth: () => ({ - user: () => ({ + user: () => authUser.authenticated ? ({ id: "u-1", username: "demo", role: authUser.role, name: "Demo", surname: "User", - }), + }) : null, loading: () => false, error: () => undefined, refresh: async () => undefined, @@ -89,6 +89,7 @@ vi.mock("@/api/meals", () => ({ afterEach(() => { cleanup(); navigate.mockReset(); + authUser.authenticated = true; }); function renderDashboard(role: string) { @@ -100,6 +101,13 @@ function renderDashboard(role: string) { )); } +test("logged-out visitor redirects before dashboard reads user role", () => { + authUser.authenticated = false; + renderDashboard("student"); + + expect(screen.getByText("redirect:/login")).toBeTruthy(); +}); + test("student sees truthful charts, full-width deadlines, and no teaching resources", async () => { const view = renderDashboard("student"); diff --git a/src/pages/dashboard-page.tsx b/src/pages/dashboard-page.tsx index b218342..57e847c 100644 --- a/src/pages/dashboard-page.tsx +++ b/src/pages/dashboard-page.tsx @@ -79,6 +79,10 @@ function scheduleStatus(startsAt: number | null, endsAt: number | null, now: num } export default function DashboardPage() { + return ; +} + +function DashboardContent() { const auth = useAuth(); const t = useT(); const navigate = useNavigate(); @@ -290,8 +294,7 @@ export default function DashboardPage() { }); return ( - - + {t("dashboard.welcomeBack", { name: fullName() })} @@ -415,7 +418,6 @@ export default function DashboardPage() { - - + ); } diff --git a/src/stores/preferences-context.test.tsx b/src/stores/preferences-context.test.tsx index 6901501..bc37538 100644 --- a/src/stores/preferences-context.test.tsx +++ b/src/stores/preferences-context.test.tsx @@ -21,3 +21,14 @@ test("sidebar collapse preference loads and persists", () => { expect(screen.getByRole("button").textContent).toBe("expanded"); expect(localStorage.getItem("hezarfen.sidebarCollapsed")).toBe("0"); }); + +test("preferences stay usable when browser storage writes fail", () => { + vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { + throw new DOMException("Storage blocked", "SecurityError"); + }); + + render(() => ); + fireEvent.click(screen.getByRole("button")); + + expect(screen.getByRole("button").textContent).toBe("collapsed"); +}); diff --git a/src/stores/preferences-context.tsx b/src/stores/preferences-context.tsx index b9985cf..320ce85 100644 --- a/src/stores/preferences-context.tsx +++ b/src/stores/preferences-context.tsx @@ -31,14 +31,28 @@ const LOCALE_KEY = "hezarfen.locale"; const THEME_KEY = "hezarfen.theme"; const SIDEBAR_KEY = "hezarfen.sidebarCollapsed"; -function canUseStorage() { - return typeof window !== "undefined" && typeof localStorage !== "undefined"; +function getStorage(): Storage | null { + if (typeof window === "undefined") return null; + try { + return window.localStorage; + } catch { + return null; + } +} + +function writeStorage(key: string, value: string) { + try { + getStorage()?.setItem(key, value); + } catch { + // Preferences still work for this session when storage is blocked/full. + } } function readLocale(): Locale { - if (!canUseStorage()) return "en"; + const storage = getStorage(); + if (!storage) return "en"; try { - const saved = localStorage.getItem(LOCALE_KEY); + const saved = storage.getItem(LOCALE_KEY); if (saved === "en" || saved === "tr") return saved; return navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en"; } catch { @@ -47,9 +61,10 @@ function readLocale(): Locale { } function readTheme(): ThemeMode { - if (!canUseStorage()) return "light"; + const storage = getStorage(); + if (!storage) return "light"; try { - const saved = localStorage.getItem(THEME_KEY); + const saved = storage.getItem(THEME_KEY); if (saved === "light" || saved === "dark") return saved; return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; } catch { @@ -58,9 +73,10 @@ function readTheme(): ThemeMode { } function readSidebarCollapsed(): boolean { - if (!canUseStorage()) return false; + const storage = getStorage(); + if (!storage) return false; try { - return localStorage.getItem(SIDEBAR_KEY) === "1"; + return storage.getItem(SIDEBAR_KEY) === "1"; } catch { return false; } @@ -73,22 +89,19 @@ export function PreferencesProvider(props: ParentProps) { createEffect(() => { const l = locale(); - if (!canUseStorage()) return; - localStorage.setItem(LOCALE_KEY, l); + writeStorage(LOCALE_KEY, l); document.documentElement.lang = l; }); createEffect(() => { const th = theme(); - if (!canUseStorage()) return; - localStorage.setItem(THEME_KEY, th); + writeStorage(THEME_KEY, th); document.documentElement.setAttribute("data-kb-theme", th); document.documentElement.classList.toggle("dark", th === "dark"); }); createEffect(() => { - if (!canUseStorage()) return; - localStorage.setItem(SIDEBAR_KEY, sidebarCollapsed() ? "1" : "0"); + writeStorage(SIDEBAR_KEY, sidebarCollapsed() ? "1" : "0"); }); const persistPreferences = (body: Parameters[0]) => {