🛡️ guard runtime errors, storage failures, and guest dashboard edge cases
Browse files at this commit8b9f154783bf21073fb467395d0734c0eafcc837Parent: 076d907- fix
- 🛡️ guard runtime errors, storage failures, and guest dashboard edge cases
6 changed files +94 -22
- src/api/__tests__/client/client.test.ts +12 -0
- src/api/client/client.ts +26 -0
- src/pages/dashboard-page.test.tsx +12 -4
- src/pages/dashboard-page.tsx +6 -4
- src/stores/preferences-context.test.tsx +11 -0
- src/stores/preferences-context.tsx +27 -14
src/api/__tests__/client/client.test.tsmodified+12 -0
| @@ -333,5 +333,17 @@ describe("client", () => { | ||
| 333 | 333 | expect(formatApiError(new Error("generic"), "en")).toBe("Generic"); |
| 334 | 334 | expect(formatApiError(new Error("generic"), "tr")).toBe("İşlem tamamlanamadı: Generic"); |
| 335 | 335 | }); |
| 336 | + | |
| 337 | + it("does not expose network, runtime, or provider errors to users", () => { | |
| 338 | + expect(formatApiError(new TypeError("Failed to fetch"), "tr")).toBe( | |
| 339 | + "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene.", | |
| 340 | + ); | |
| 341 | + expect(formatApiError(new TypeError("Cannot read properties of null (reading 'user')"), "tr")).toBe( | |
| 342 | + "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene.", | |
| 343 | + ); | |
| 344 | + expect(formatApiError(new Error("useAuth must be used within AuthProvider"), "en")).toBe( | |
| 345 | + "Something went wrong while loading the page. Reload the page and try again.", | |
| 346 | + ); | |
| 347 | + }); | |
| 336 | 348 | }); |
| 337 | 349 | }); |
src/api/client/client.tsmodified+26 -0
| @@ -286,6 +286,24 @@ function sentenceCase(message: string): string { | ||
| 286 | 286 | return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1); |
| 287 | 287 | } |
| 288 | 288 | |
| 289 | +function formatRuntimeErrorMessage(message: string, locale: Locale): string | null { | |
| 290 | + const normalized = normalizeApiMessage(message); | |
| 291 | + if (/^(failed to fetch|load failed|networkerror|network request failed)/.test(normalized)) { | |
| 292 | + return locale === "tr" | |
| 293 | + ? "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene." | |
| 294 | + : "Could not reach the server. Check your connection and try again."; | |
| 295 | + } | |
| 296 | + if ( | |
| 297 | + /^(typeerror:\s*)?cannot (read|set) propert(y|ies) of (null|undefined)/.test(normalized) || | |
| 298 | + /^use\w+ must be used within \w+provider/.test(normalized) | |
| 299 | + ) { | |
| 300 | + return locale === "tr" | |
| 301 | + ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene." | |
| 302 | + : "Something went wrong while loading the page. Reload the page and try again."; | |
| 303 | + } | |
| 304 | + return null; | |
| 305 | +} | |
| 306 | + | |
| 289 | 307 | function formatNumber(value: string, locale: Locale): string { |
| 290 | 308 | return new Intl.NumberFormat(locale === "tr" ? "tr-TR" : "en-US").format(Number(value)); |
| 291 | 309 | } |
| @@ -455,6 +473,8 @@ export function formatApiErrorMessage(message: string, locale: Locale = currentL | ||
| 455 | 473 | const normalized = normalizeApiMessage(message); |
| 456 | 474 | const known = API_ERROR_MESSAGES[normalized]?.[locale]; |
| 457 | 475 | if (known) return known; |
| 476 | + const runtime = formatRuntimeErrorMessage(message, locale); | |
| 477 | + if (runtime) return runtime; | |
| 458 | 478 | const validation = formatValidationMessage(message, locale); |
| 459 | 479 | if (validation) return validation; |
| 460 | 480 | if (locale === "tr") return `İşlem tamamlanamadı: ${sentenceCase(message)}`; |
| @@ -477,6 +497,12 @@ export function formatApiError(err: unknown, locale: Locale = currentLocale()): | ||
| 477 | 497 | if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again."; |
| 478 | 498 | return formatApiErrorMessage(err.message, locale); |
| 479 | 499 | } |
| 500 | + if (err instanceof TypeError) { | |
| 501 | + return formatRuntimeErrorMessage(err.message, locale) ?? | |
| 502 | + (locale === "tr" | |
| 503 | + ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene." | |
| 504 | + : "Something went wrong while loading the page. Reload the page and try again."); | |
| 505 | + } | |
| 480 | 506 | if (err instanceof Error) return formatApiErrorMessage(err.message, locale); |
| 481 | 507 | return locale === "tr" ? "Bir şeyler ters gitti." : "Something went wrong."; |
| 482 | 508 | } |
src/pages/dashboard-page.test.tsxmodified+12 -4
| @@ -5,25 +5,25 @@ import { PreferencesProvider } from "@/stores/preferences-context"; | ||
| 5 | 5 | |
| 6 | 6 | const { navigate, authUser } = vi.hoisted(() => ({ |
| 7 | 7 | navigate: vi.fn(), |
| 8 | - authUser: { role: "student" }, | |
| 8 | + authUser: { authenticated: true, role: "student" }, | |
| 9 | 9 | })); |
| 10 | 10 | |
| 11 | 11 | vi.mock("@tanstack/solid-router", () => ({ |
| 12 | 12 | Link: (props: { to: string; children: JSX.Element; class?: string }) => ( |
| 13 | 13 | <a href={props.to} class={props.class}>{props.children}</a> |
| 14 | 14 | ), |
| 15 | - Navigate: () => null, | |
| 15 | + Navigate: (props: { to: string }) => <span>redirect:{props.to}</span>, | |
| 16 | 16 | useNavigate: () => navigate, |
| 17 | 17 | })); |
| 18 | 18 | vi.mock("@/stores/auth-context", () => ({ |
| 19 | 19 | useAuth: () => ({ |
| 20 | - user: () => ({ | |
| 20 | + user: () => authUser.authenticated ? ({ | |
| 21 | 21 | id: "u-1", |
| 22 | 22 | username: "demo", |
| 23 | 23 | role: authUser.role, |
| 24 | 24 | name: "Demo", |
| 25 | 25 | surname: "User", |
| 26 | - }), | |
| 26 | + }) : null, | |
| 27 | 27 | loading: () => false, |
| 28 | 28 | error: () => undefined, |
| 29 | 29 | refresh: async () => undefined, |
| @@ -89,6 +89,7 @@ vi.mock("@/api/meals", () => ({ | ||
| 89 | 89 | afterEach(() => { |
| 90 | 90 | cleanup(); |
| 91 | 91 | navigate.mockReset(); |
| 92 | + authUser.authenticated = true; | |
| 92 | 93 | }); |
| 93 | 94 | |
| 94 | 95 | function renderDashboard(role: string) { |
| @@ -100,6 +101,13 @@ function renderDashboard(role: string) { | ||
| 100 | 101 | )); |
| 101 | 102 | } |
| 102 | 103 | |
| 104 | +test("logged-out visitor redirects before dashboard reads user role", () => { | |
| 105 | + authUser.authenticated = false; | |
| 106 | + renderDashboard("student"); | |
| 107 | + | |
| 108 | + expect(screen.getByText("redirect:/login")).toBeTruthy(); | |
| 109 | +}); | |
| 110 | + | |
| 103 | 111 | test("student sees truthful charts, full-width deadlines, and no teaching resources", async () => { |
| 104 | 112 | const view = renderDashboard("student"); |
| 105 | 113 |
src/pages/dashboard-page.tsxmodified+6 -4
| @@ -79,6 +79,10 @@ function scheduleStatus(startsAt: number | null, endsAt: number | null, now: num | ||
| 79 | 79 | } |
| 80 | 80 | |
| 81 | 81 | export default function DashboardPage() { |
| 82 | + return <RouteGuard><DashboardContent /></RouteGuard>; | |
| 83 | +} | |
| 84 | + | |
| 85 | +function DashboardContent() { | |
| 82 | 86 | const auth = useAuth(); |
| 83 | 87 | const t = useT(); |
| 84 | 88 | const navigate = useNavigate(); |
| @@ -290,8 +294,7 @@ export default function DashboardPage() { | ||
| 290 | 294 | }); |
| 291 | 295 | |
| 292 | 296 | return ( |
| 293 | - <RouteGuard> | |
| 294 | - <div class="space-y-5"> | |
| 297 | + <div class="space-y-5"> | |
| 295 | 298 | <header class="flex flex-wrap items-end justify-between gap-3"> |
| 296 | 299 | <div class="space-y-1"> |
| 297 | 300 | <h1 class="font-display text-2xl font-semibold tracking-tight">{t("dashboard.welcomeBack", { name: fullName() })}</h1> |
| @@ -415,7 +418,6 @@ export default function DashboardPage() { | ||
| 415 | 418 | </Show> |
| 416 | 419 | </div> |
| 417 | 420 | </Suspense> |
| 418 | - </div> | |
| 419 | - </RouteGuard> | |
| 421 | + </div> | |
| 420 | 422 | ); |
| 421 | 423 | } |
src/stores/preferences-context.test.tsxmodified+11 -0
| @@ -21,3 +21,14 @@ test("sidebar collapse preference loads and persists", () => { | ||
| 21 | 21 | expect(screen.getByRole("button").textContent).toBe("expanded"); |
| 22 | 22 | expect(localStorage.getItem("hezarfen.sidebarCollapsed")).toBe("0"); |
| 23 | 23 | }); |
| 24 | + | |
| 25 | +test("preferences stay usable when browser storage writes fail", () => { | |
| 26 | + vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { | |
| 27 | + throw new DOMException("Storage blocked", "SecurityError"); | |
| 28 | + }); | |
| 29 | + | |
| 30 | + render(() => <PreferencesProvider><SidebarPreferenceProbe /></PreferencesProvider>); | |
| 31 | + fireEvent.click(screen.getByRole("button")); | |
| 32 | + | |
| 33 | + expect(screen.getByRole("button").textContent).toBe("collapsed"); | |
| 34 | +}); |
src/stores/preferences-context.tsxmodified+27 -14
| @@ -31,14 +31,28 @@ const LOCALE_KEY = "hezarfen.locale"; | ||
| 31 | 31 | const THEME_KEY = "hezarfen.theme"; |
| 32 | 32 | const SIDEBAR_KEY = "hezarfen.sidebarCollapsed"; |
| 33 | 33 | |
| 34 | -function canUseStorage() { | |
| 35 | - return typeof window !== "undefined" && typeof localStorage !== "undefined"; | |
| 34 | +function getStorage(): Storage | null { | |
| 35 | + if (typeof window === "undefined") return null; | |
| 36 | + try { | |
| 37 | + return window.localStorage; | |
| 38 | + } catch { | |
| 39 | + return null; | |
| 40 | + } | |
| 41 | +} | |
| 42 | + | |
| 43 | +function writeStorage(key: string, value: string) { | |
| 44 | + try { | |
| 45 | + getStorage()?.setItem(key, value); | |
| 46 | + } catch { | |
| 47 | + // Preferences still work for this session when storage is blocked/full. | |
| 48 | + } | |
| 36 | 49 | } |
| 37 | 50 | |
| 38 | 51 | function readLocale(): Locale { |
| 39 | - if (!canUseStorage()) return "en"; | |
| 52 | + const storage = getStorage(); | |
| 53 | + if (!storage) return "en"; | |
| 40 | 54 | try { |
| 41 | - const saved = localStorage.getItem(LOCALE_KEY); | |
| 55 | + const saved = storage.getItem(LOCALE_KEY); | |
| 42 | 56 | if (saved === "en" || saved === "tr") return saved; |
| 43 | 57 | return navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en"; |
| 44 | 58 | } catch { |
| @@ -47,9 +61,10 @@ function readLocale(): Locale { | ||
| 47 | 61 | } |
| 48 | 62 | |
| 49 | 63 | function readTheme(): ThemeMode { |
| 50 | - if (!canUseStorage()) return "light"; | |
| 64 | + const storage = getStorage(); | |
| 65 | + if (!storage) return "light"; | |
| 51 | 66 | try { |
| 52 | - const saved = localStorage.getItem(THEME_KEY); | |
| 67 | + const saved = storage.getItem(THEME_KEY); | |
| 53 | 68 | if (saved === "light" || saved === "dark") return saved; |
| 54 | 69 | return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; |
| 55 | 70 | } catch { |
| @@ -58,9 +73,10 @@ function readTheme(): ThemeMode { | ||
| 58 | 73 | } |
| 59 | 74 | |
| 60 | 75 | function readSidebarCollapsed(): boolean { |
| 61 | - if (!canUseStorage()) return false; | |
| 76 | + const storage = getStorage(); | |
| 77 | + if (!storage) return false; | |
| 62 | 78 | try { |
| 63 | - return localStorage.getItem(SIDEBAR_KEY) === "1"; | |
| 79 | + return storage.getItem(SIDEBAR_KEY) === "1"; | |
| 64 | 80 | } catch { |
| 65 | 81 | return false; |
| 66 | 82 | } |
| @@ -73,22 +89,19 @@ export function PreferencesProvider(props: ParentProps) { | ||
| 73 | 89 | |
| 74 | 90 | createEffect(() => { |
| 75 | 91 | const l = locale(); |
| 76 | - if (!canUseStorage()) return; | |
| 77 | - localStorage.setItem(LOCALE_KEY, l); | |
| 92 | + writeStorage(LOCALE_KEY, l); | |
| 78 | 93 | document.documentElement.lang = l; |
| 79 | 94 | }); |
| 80 | 95 | |
| 81 | 96 | createEffect(() => { |
| 82 | 97 | const th = theme(); |
| 83 | - if (!canUseStorage()) return; | |
| 84 | - localStorage.setItem(THEME_KEY, th); | |
| 98 | + writeStorage(THEME_KEY, th); | |
| 85 | 99 | document.documentElement.setAttribute("data-kb-theme", th); |
| 86 | 100 | document.documentElement.classList.toggle("dark", th === "dark"); |
| 87 | 101 | }); |
| 88 | 102 | |
| 89 | 103 | createEffect(() => { |
| 90 | - if (!canUseStorage()) return; | |
| 91 | - localStorage.setItem(SIDEBAR_KEY, sidebarCollapsed() ? "1" : "0"); | |
| 104 | + writeStorage(SIDEBAR_KEY, sidebarCollapsed() ? "1" : "0"); | |
| 92 | 105 | }); |
| 93 | 106 | |
| 94 | 107 | const persistPreferences = (body: Parameters<typeof patchMyPreferences>[0]) => { |