forge
Explore
Log in

Don't you dare go Hollow

🛡️ guard runtime errors, storage failures, and guest dashboard edge cases

Browse files at this commit

8b9f154783bf21073fb467395d0734c0eafcc837Burak BoduroğluParent: 076d907
  • fix
    • 🛡️ guard runtime errors, storage failures, and guest dashboard edge cases
Show full message
fix: 🛡️ guard runtime errors, storage failures, and guest dashboard edge cases
- catch TypeError (network/runtime/provider errors) in formatApiError with
  user-friendly messages instead of exposing raw JS error text
- guard localStorage writes behind try/catch so blocked/full storage does not
  break preferences for the session
- restructure DashboardPage so RouteGuard wraps content; add guest redirect test
src/api/__tests__/client/client.test.tsmodified+12 -0
@@ -333,5 +333,17 @@ describe("client", () => {
333333 expect(formatApiError(new Error("generic"), "en")).toBe("Generic");
334334 expect(formatApiError(new Error("generic"), "tr")).toBe("İşlem tamamlanamadı: Generic");
335335 });
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+ });
336348 });
337349 });
src/api/client/client.tsmodified+26 -0
@@ -286,6 +286,24 @@ function sentenceCase(message: string): string {
286286 return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1);
287287 }
288288
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+
289307 function formatNumber(value: string, locale: Locale): string {
290308 return new Intl.NumberFormat(locale === "tr" ? "tr-TR" : "en-US").format(Number(value));
291309 }
@@ -455,6 +473,8 @@ export function formatApiErrorMessage(message: string, locale: Locale = currentL
455473 const normalized = normalizeApiMessage(message);
456474 const known = API_ERROR_MESSAGES[normalized]?.[locale];
457475 if (known) return known;
476+ const runtime = formatRuntimeErrorMessage(message, locale);
477+ if (runtime) return runtime;
458478 const validation = formatValidationMessage(message, locale);
459479 if (validation) return validation;
460480 if (locale === "tr") return `İşlem tamamlanamadı: ${sentenceCase(message)}`;
@@ -477,6 +497,12 @@ export function formatApiError(err: unknown, locale: Locale = currentLocale()):
477497 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";
478498 return formatApiErrorMessage(err.message, locale);
479499 }
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+ }
480506 if (err instanceof Error) return formatApiErrorMessage(err.message, locale);
481507 return locale === "tr" ? "Bir şeyler ters gitti." : "Something went wrong.";
482508 }
src/pages/dashboard-page.test.tsxmodified+12 -4
@@ -5,25 +5,25 @@ import { PreferencesProvider } from "@/stores/preferences-context";
55
66 const { navigate, authUser } = vi.hoisted(() => ({
77 navigate: vi.fn(),
8- authUser: { role: "student" },
8+ authUser: { authenticated: true, role: "student" },
99 }));
1010
1111 vi.mock("@tanstack/solid-router", () => ({
1212 Link: (props: { to: string; children: JSX.Element; class?: string }) => (
1313 <a href={props.to} class={props.class}>{props.children}</a>
1414 ),
15- Navigate: () => null,
15+ Navigate: (props: { to: string }) => <span>redirect:{props.to}</span>,
1616 useNavigate: () => navigate,
1717 }));
1818 vi.mock("@/stores/auth-context", () => ({
1919 useAuth: () => ({
20- user: () => ({
20+ user: () => authUser.authenticated ? ({
2121 id: "u-1",
2222 username: "demo",
2323 role: authUser.role,
2424 name: "Demo",
2525 surname: "User",
26- }),
26+ }) : null,
2727 loading: () => false,
2828 error: () => undefined,
2929 refresh: async () => undefined,
@@ -89,6 +89,7 @@ vi.mock("@/api/meals", () => ({
8989 afterEach(() => {
9090 cleanup();
9191 navigate.mockReset();
92+ authUser.authenticated = true;
9293 });
9394
9495 function renderDashboard(role: string) {
@@ -100,6 +101,13 @@ function renderDashboard(role: string) {
100101 ));
101102 }
102103
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+
103111 test("student sees truthful charts, full-width deadlines, and no teaching resources", async () => {
104112 const view = renderDashboard("student");
105113
src/pages/dashboard-page.tsxmodified+6 -4
@@ -79,6 +79,10 @@ function scheduleStatus(startsAt: number | null, endsAt: number | null, now: num
7979 }
8080
8181 export default function DashboardPage() {
82+ return <RouteGuard><DashboardContent /></RouteGuard>;
83+}
84+
85+function DashboardContent() {
8286 const auth = useAuth();
8387 const t = useT();
8488 const navigate = useNavigate();
@@ -290,8 +294,7 @@ export default function DashboardPage() {
290294 });
291295
292296 return (
293- <RouteGuard>
294- <div class="space-y-5">
297+ <div class="space-y-5">
295298 <header class="flex flex-wrap items-end justify-between gap-3">
296299 <div class="space-y-1">
297300 <h1 class="font-display text-2xl font-semibold tracking-tight">{t("dashboard.welcomeBack", { name: fullName() })}</h1>
@@ -415,7 +418,6 @@ export default function DashboardPage() {
415418 </Show>
416419 </div>
417420 </Suspense>
418- </div>
419- </RouteGuard>
421+ </div>
420422 );
421423 }
src/stores/preferences-context.test.tsxmodified+11 -0
@@ -21,3 +21,14 @@ test("sidebar collapse preference loads and persists", () => {
2121 expect(screen.getByRole("button").textContent).toBe("expanded");
2222 expect(localStorage.getItem("hezarfen.sidebarCollapsed")).toBe("0");
2323 });
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";
3131 const THEME_KEY = "hezarfen.theme";
3232 const SIDEBAR_KEY = "hezarfen.sidebarCollapsed";
3333
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+ }
3649 }
3750
3851 function readLocale(): Locale {
39- if (!canUseStorage()) return "en";
52+ const storage = getStorage();
53+ if (!storage) return "en";
4054 try {
41- const saved = localStorage.getItem(LOCALE_KEY);
55+ const saved = storage.getItem(LOCALE_KEY);
4256 if (saved === "en" || saved === "tr") return saved;
4357 return navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en";
4458 } catch {
@@ -47,9 +61,10 @@ function readLocale(): Locale {
4761 }
4862
4963 function readTheme(): ThemeMode {
50- if (!canUseStorage()) return "light";
64+ const storage = getStorage();
65+ if (!storage) return "light";
5166 try {
52- const saved = localStorage.getItem(THEME_KEY);
67+ const saved = storage.getItem(THEME_KEY);
5368 if (saved === "light" || saved === "dark") return saved;
5469 return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
5570 } catch {
@@ -58,9 +73,10 @@ function readTheme(): ThemeMode {
5873 }
5974
6075 function readSidebarCollapsed(): boolean {
61- if (!canUseStorage()) return false;
76+ const storage = getStorage();
77+ if (!storage) return false;
6278 try {
63- return localStorage.getItem(SIDEBAR_KEY) === "1";
79+ return storage.getItem(SIDEBAR_KEY) === "1";
6480 } catch {
6581 return false;
6682 }
@@ -73,22 +89,19 @@ export function PreferencesProvider(props: ParentProps) {
7389
7490 createEffect(() => {
7591 const l = locale();
76- if (!canUseStorage()) return;
77- localStorage.setItem(LOCALE_KEY, l);
92+ writeStorage(LOCALE_KEY, l);
7893 document.documentElement.lang = l;
7994 });
8095
8196 createEffect(() => {
8297 const th = theme();
83- if (!canUseStorage()) return;
84- localStorage.setItem(THEME_KEY, th);
98+ writeStorage(THEME_KEY, th);
8599 document.documentElement.setAttribute("data-kb-theme", th);
86100 document.documentElement.classList.toggle("dark", th === "dark");
87101 });
88102
89103 createEffect(() => {
90- if (!canUseStorage()) return;
91- localStorage.setItem(SIDEBAR_KEY, sidebarCollapsed() ? "1" : "0");
104+ writeStorage(SIDEBAR_KEY, sidebarCollapsed() ? "1" : "0");
92105 });
93106
94107 const persistPreferences = (body: Parameters<typeof patchMyPreferences>[0]) => {