# BanGUI — Task List This document breaks the entire BanGUI project into development stages, ordered so that each stage builds on the previous one. Every task is described in prose with enough detail for a developer to begin work. References point to the relevant documentation. Reference: `Docs/Refactoring.md` for full analysis of each issue. --- ## Open Issues Issues are grouped by category and ordered roughly by severity. Each entry describes the current state, the desired end state, pitfalls to watch for, and which documentation needs updating when the task is done. --- ## Bug Fixes / Correctness --- ### TASK-001 — Race condition in `useJailBannedIps`: missing AbortController (done) **Where fixed:** `frontend/src/hooks/useJailBannedIps.ts`, `frontend/src/api/jails.ts` **Summary:** Added an `AbortController` ref to cancel stale fetches, passed the signal into `fetchJailBannedIps`, and abort on unmount. **Where found:** `frontend/src/hooks/useJailBannedIps.ts` — the `load` callback is `async` and calls `fetchJailBannedIps` with no AbortSignal. **Goal:** Add a `useRef` to `useJailBannedIps`. Before each fetch, abort the previous controller and create a new one. Pass `signal` to `fetchJailBannedIps`. In the `useEffect` cleanup return, abort the controller. After every `await`, check `signal.aborted` before calling any state setter. **Possible traps:** - `fetchJailBannedIps` in `api/jails.ts` does not yet accept a signal — that parameter must be added first (see TASK-005). - The hook uses a debounced search value; the debounce timer itself does not need to be cancelled, only the in-flight request. - Setting state after abort causes a React warning in some versions; always guard with `if (!ctrl.signal.aborted)`. **Docs changes needed:** None. **Why:** Without cancellation, rapidly changing the search or page can cause an older, slower response to overwrite the result of a newer request. The user sees stale data with no indication it is stale. --- ### TASK-002 — `HistoryPage` filter effect has a stale `appliedQuery` dependency (done) **Where found:** `frontend/src/pages/HistoryPage.tsx` lines 214–230. The `useEffect` lists `appliedQuery` as a dependency, reads it inside the effect, and then calls `setAppliedQuery` — which triggers the same effect again immediately. **Goal:** Remove `appliedQuery` from the effect dependency array and use a `useRef` to hold the last-applied query for comparison. The ref must be updated synchronously when the query changes so the comparison is always accurate without creating a circular dependency. **Possible traps:** - The `areHistoryQueriesEqual` utility must still be called to avoid redundant fetches; moving it to a ref pattern requires care not to skip the equality check. - Removing a dependency while keeping `// eslint-disable-next-line` comments is tempting but wrong; restructure so the lint rule is satisfied naturally. **Docs changes needed:** None. **Why:** The current code runs the effect one extra time on every filter change — once when filters change, and once because `appliedQuery` just changed. This causes two API calls per user interaction instead of one. --- ### TASK-003 — `BanUnbanForm` floating promises and no double-submit guard (done) **Where fixed:** `frontend/src/pages/jails/BanUnbanForm.tsx`, `frontend/src/pages/jails/__tests__/BanUnbanForm.test.tsx` **Summary:** Converted ban and unban handlers to async functions with separate submit states and disabled submit buttons while requests are in flight. **Where found:** `frontend/src/pages/jails/BanUnbanForm.tsx` — `handleBan` and `handleUnban` are synchronous functions that call `onBan(…).then(…).catch(…)`. The returned promise is not awaited and is not assigned to anything. **Goal:** Convert `handleBan` and `handleUnban` to `async` functions. Add an `isSubmitting` state variable. Set it to `true` before the API call and `false` in a `finally` block. Disable both submit buttons while `isSubmitting` is true. The promise chain can then become a simple `try/catch/finally`. **Possible traps:** - If the outer handler is passed to an `onClick` that is typed as `() => void`, TypeScript will not warn about the lost promise; ESLint rule `@typescript-eslint/no-misused-promises` (see TASK-030) would catch this. - Two separate actions (ban and unban) share the same `isSubmitting` flag; use two flags (`isBanning`, `isUnbanning`) to allow one to proceed while the other is loading. **Docs changes needed:** None. **Why:** Without a double-submit guard, clicking "Ban" quickly fires multiple identical API requests. If the `.catch()` branch itself throws, the error is an unhandled rejection that surfaces as a console warning and is invisible to the user. --- ### TASK-004 — `KVEditor` key rename silently overwrites duplicate keys (done) **Where fixed:** `frontend/src/components/config/KVEditor.tsx`, `frontend/src/components/config/configStyles.ts`, `frontend/src/components/config/__tests__/KVEditor.test.tsx` **Goal:** Before applying a key rename, check whether `newKey` already exists in `entries`. If it does, show a validation error inline (a `MessageBar` beneath the affected input row or a red border via `validationState="error"` on the Fluent UI `Input`). Block the `onChange` call until the conflict is resolved. **Possible traps:** - The component is fully controlled (parent owns the `entries` object), so the error state must be local to `KVEditor` — adding it to the parent's state would be over-engineering. - While the user is mid-edit (typing the new key name), partial names that match existing keys should not be flagged until the input loses focus, to avoid premature errors. **Docs changes needed:** None. **Why:** Silently dropping the value of an existing key when the user renames another key to the same name is destructive data loss with no warning. Config settings that share a key name are semantically invalid in fail2ban anyway. --- ### TASK-005 — `SetupGuard` redirects to `/setup` when the backend is temporarily unreachable (done) **Where fixed:** `frontend/src/components/SetupGuard.tsx` **Where found:** `frontend/src/components/SetupGuard.tsx`. When `useSetup` returns `{ loading: false, status: null }` due to a network error, the guard treats this the same as "setup not completed" and redirects to `/setup`. **Goal:** Destructure `error` from `useSetup` in addition to `status` and `loading`. Add an error branch: if `error` is non-null and `status` is null, render an error card (Fluent UI `MessageBar` with a Retry button) instead of redirecting. Only redirect to `/setup` when `status` is definitively `{ completed: false }`. **Possible traps:** - `useSetup` may need to be updated to expose an `error` field if it does not already. - There is a brief window on initial load where both `loading` and `error` are false and `status` is null; this state must not trigger a redirect. **Docs changes needed:** None. **Why:** A transient network hiccup during app startup causes a setup-complete user to be dropped into the setup wizard and potentially overwrite their configuration. This is a silent data-integrity risk. --- ## Security --- ### TASK-006 — No 401 interceptor: expired sessions show broken pages instead of redirecting **Where found:** `frontend/src/api/client.ts`, `request` function. All non-2xx responses including 401 are thrown as a generic `ApiError`. Consumers render "Failed to load…" messages instead of redirecting. **Goal:** After the `if (!response.ok)` check, add a dedicated branch: if `response.status === 401`, dispatch a custom DOM event (`bangui:session-expired`) before throwing. In `AuthProvider`, listen for this event with `window.addEventListener` and call the existing logout cleanup logic, then navigate to `/login`. The event approach avoids coupling the API client to React context. **Possible traps:** - The event listener must be added and removed inside a `useEffect` in `AuthProvider` to avoid leaks. - Pages that show a brief error flash before the redirect fires should have their error messages suppressed for `ApiError` with status 401 — wrap this in a shared utility (`isAuthError(err)`). - If the backend returns 403 (forbidden) rather than 401 for an expired token, the interceptor must also handle that status. **Docs changes needed:** Update `Docs/Backend-Development.md` to document that 401 responses trigger client-side logout. **Why:** Currently a user with an expired session sees multiple "Failed to load" error boxes and must manually navigate to `/login`. This is confusing and the broken state can be mistaken for a backend outage. --- ### TASK-007 — Setup page password validation too weak **Where found:** `frontend/src/pages/SetupPage.tsx`, `validate()` function. Only `masterPassword.length < 8` is checked. **Goal:** Add minimum complexity rules: at least one uppercase letter, one number, and one special character (e.g. `!@#$%^&*()`). Show a password-strength indicator (a simple four-step progress bar is sufficient) that updates as the user types. Add a validation message per unmet rule rather than a single generic string. **Possible traps:** - The complexity rules must match whatever the backend enforces; check `backend/app/routers/setup.py` for server-side validation and keep the two in sync. - The "confirm password" field comparison must run after the strength check, not instead of it, so both errors can be shown simultaneously. **Docs changes needed:** Document the password policy in `Docs/Instructions.md`. **Why:** An 8-character minimum allows trivially weak passwords such as `12345678`. Because this is the single master credential for the entire application, it warrants stronger client-side guidance. --- ## Performance --- ### TASK-008 — `buildBanColumns` and `HISTORY_COLUMNS` recreated on every render **Where found:** - `frontend/src/components/BanTable.tsx` — `buildBanColumns(styles)` called unconditionally in the render body. - `frontend/src/pages/HistoryPage.tsx` — `HISTORY_COLUMNS(onClickIp, styles)` called unconditionally in the render body. **Goal:** Wrap both column-definition arrays in `useMemo`. In `BanTable`, the dependency is `[styles]`. In `HistoryPage`, the dependency is `[styles]` — the `onClickIp` callback should be wrapped in `useCallback` first so it has a stable reference. **Possible traps:** - Fluent UI `createTableColumn` creates objects that are compared by reference inside `DataGrid`; if the array is recreated on every render, `DataGrid` will re-render all cells even when data has not changed. - The `styles` object from `makeStyles` is stable across renders (Fluent UI guarantees this), so `[styles]` as a dependency is effectively `[]` in practice. **Docs changes needed:** None. **Why:** Recreating column definitions every render triggers unnecessary cell re-renders in `DataGrid`, which is one of the heaviest Fluent UI components. On a page with 100 rows and 7 columns, this means 700 unnecessary cell renders per parent re-render. --- ### TASK-009 — `resolveFluentToken` calls `getComputedStyle` on every render **Where found:** `frontend/src/utils/chartTheme.ts`, `resolveFluentToken` function. Called 2–3 times per render in `BanTrendChart`, `TopCountriesPieChart`, `TopCountriesBarChart`, and `JailDistributionChart`. **Goal:** In each chart component that calls `resolveFluentToken`, wrap the calls in `useMemo` with an empty dependency array `[]` (the theme never changes at runtime in the current implementation). When dark mode support is added (TASK-015), the dependency should change to the active theme object. **Possible traps:** - `resolveFluentToken` reads a CSS custom property from a DOM element; calling it at module level (outside a component) would read before the `FluentProvider` has injected its tokens, returning an empty string. - The function itself should not be memoized globally — only the results per component, since each component may be mounted in a different theming context in tests. **Docs changes needed:** None. **Why:** `getComputedStyle` on every render is a forced style recalculation. On low-end hardware or when many charts are visible simultaneously, this measurably degrades frame rate. --- ### TASK-010 — No code splitting: all pages bundled into the main chunk **Where found:** `frontend/src/App.tsx` — all page imports are static (`import { DashboardPage } from "./pages/DashboardPage"`). `frontend/vite.config.ts` has no `build.rollupOptions.manualChunks`. **Goal:** Convert all seven page imports in `App.tsx` to `React.lazy(() => import(…))`. Wrap the `` block in `}>`. In `vite.config.ts`, add `manualChunks` to split `react`/`react-dom`, Fluent UI, Recharts, and the D3/TopoJSON geo stack into separate vendor chunks. **Possible traps:** - `React.lazy` requires the module to have a default export; all current pages use named exports. Either add a re-export default in each page file, or use `import(…).then(m => ({ default: m.PageName }))` in the lazy call. - The `` fallback renders during navigation; place it inside `` but outside `` so the spinner is not blocked by auth context loading. - The D3/TopoJSON data (`world-atlas/countries-110m.json`) is a large JSON file (~100 KB gzipped) and should be placed in the `geo` chunk alongside `d3-geo` and `topojson-client`. **Docs changes needed:** None. **Why:** Every user who opens the dashboard must download, parse, and execute JavaScript for the map, config editor, and blocklist pages — even if they never visit those routes. Code splitting allows the initial load to be significantly smaller. --- ### TASK-011 — No `React.memo` on any heavy component **Where found:** Every component in `frontend/src/components/` — zero uses of `React.memo` exist in the codebase. **Goal:** Apply `React.memo` to the components whose props rarely change but whose render is expensive: `WorldMap`, `BanTrendChart`, `JailDistributionChart`, `TopCountriesPieChart`, `TopCountriesBarChart`, `BanTable`, and `ServerStatusBar`. Use the default shallow-equality comparator for props that are primitives. For `WorldMap`, provide a custom comparator that compares the `countries` record by key count and values (shallow object comparison). **Possible traps:** - Inline function props (e.g. `onSelectCountry={() => …}`) will always be a new reference and defeat `React.memo`. Ensure all callback props passed to memoized components are wrapped in `useCallback` at the call site. - Inline `style={{…}}` objects passed as props also defeat memoization; these must be moved to `makeStyles` first (see TASK-018). - `React.memo` does not help if the component itself calls an expensive hook that always returns a new object. **Docs changes needed:** None. **Why:** `DashboardPage` re-renders whenever the 30-second server status poll fires, causing all five chart components and the ban table to re-render even though the filter state has not changed. --- ### TASK-012 — `useMapData` sets `loading=true` before the debounce fires **Where found:** `frontend/src/hooks/useMapData.ts`, `load` callback — `setLoading(true)` is called at the top of `load`, but the actual fetch is deferred inside a `setTimeout` of 300 ms. **Goal:** Move `setLoading(true)` inside the `setTimeout` callback, immediately before the `abortRef.current?.abort()` call. This ensures the spinner only appears when a real network request is about to start. **Possible traps:** - The caller (`MapPage`) uses `loading` to fade the map table with `opacity: 0.5`. There will now be a 300 ms window where filters have changed but the table is still showing old data at full opacity; this is acceptable and more correct than showing a spinner immediately. - If the component unmounts during the debounce window, the `clearTimeout` in the cleanup must run; verify the existing `useEffect` cleanup correctly returns `clearTimeout`. **Docs changes needed:** None. **Why:** Users see a loading spinner for 300 ms before any network activity has started, which makes the UI feel slower than it is. --- ## Architecture / Code Quality --- ### TASK-013 — Consolidate `api/config.ts` and `api/file_config.ts` duplicate functions **Where found:** Both `frontend/src/api/config.ts` and `frontend/src/api/file_config.ts` export identical functions: `fetchJailConfigFiles`, `createJailConfigFile`, `fetchJailConfigFileContent`, `updateJailConfigFile`, `setJailConfigFileEnabled`, `fetchFilterFiles`, `fetchFilterFile`, `updateFilterFile`, `createFilterFile`, `fetchActionFiles`, `fetchActionFile`, `updateActionFile`, `createActionFile`. **Goal:** Delete `api/file_config.ts`. Update the four files that import from it (`hooks/useFilterRawFile.ts`, `hooks/useActionRawFile.ts`, `components/config/JailFilesTab.tsx`, `components/config/ExportTab.tsx`) to import the same functions from `api/config.ts` instead. Verify that both modules currently export functions with identical signatures before the merge; resolve any differences first. **Possible traps:** - `file_config.ts` lacks `AbortSignal` parameters on all its functions, while the corresponding functions in `config.ts` may have them. After migration, all callers must be updated to pass the signal. - Running a global search for `from.*file_config` after the migration should return zero results; add this as a CI check via ESLint `no-restricted-imports` if desired. **Docs changes needed:** None. **Why:** Two modules exporting the same API functions will drift apart over time. Any bug fix or new feature applied to one will silently not apply to the other. --- ### TASK-014 — Add `AbortSignal` to all API functions missing it **Where found:** - `frontend/src/api/dashboard.ts` — `fetchServerStatus`, `fetchBansByJail`, `fetchBanTrend` have no signal parameter. - `frontend/src/api/jails.ts` — `fetchJailBannedIps` (and others) have no signal parameter. - `frontend/src/api/blocklist.ts` — `fetchSchedule` (used by the polling hook) has no signal parameter. **Goal:** Add `signal?: AbortSignal` as the last parameter to every `get`/`post`/`put`/`del` wrapper call in these modules. The pattern is already established in `api/config.ts` and `api/map.ts` and should be replicated uniformly. After adding the parameters, update the consuming hooks to pass their `abortRef.current.signal`. **Possible traps:** - Functions used by polling hooks (`fetchServerStatus` in `useServerStatus`, `fetchSchedule` in `useBlocklistStatus`) must pass the signal from a `useRef` rather than from a `useEffect`-local controller, because the poll fires outside the effect's lifecycle. - Adding a signal parameter is non-breaking (it is optional), so no consumers need to change immediately; they can be updated incrementally. **Docs changes needed:** None. **Why:** Without a signal, requests fired by polling hooks cannot be cancelled when the component unmounts, leaking network activity and potentially updating state on unmounted components (React warning). --- ### TASK-015 — Standardise AbortController pattern across all hooks **Where found:** Three different patterns exist in `frontend/src/hooks/`: 1. `useRef` with manual abort before each fetch (correct — used in `useActiveBans`, `useActionList`). 2. Inline `AbortController` created inside `useEffect` and aborted in cleanup (acceptable for single-fetch effects — used in `useSchedule`). 3. No AbortController at all (incorrect — used in `useJailBannedIps`, `useBlocklistStatus`). **Goal:** Hooks that expose a manual `refresh()` function must use pattern 1 (the `useRef` approach), because the abort must survive across effect re-runs. Hooks that only fetch once on mount and never need manual refresh may use pattern 2. Remove all instances of pattern 3. Document the chosen conventions in a comment block at the top of a new file `frontend/src/hooks/README.md` (or inline in `fetchError.ts`). **Possible traps:** - When migrating `useBlocklistStatus` from a boolean `cancelled` flag to an `AbortController`, the underlying `fetchSchedule` call must first accept a signal (TASK-014). - Some hooks use both a debounce timer and an abort controller; the abort must cancel the in-flight request, while the timer cancellation prevents a new request from starting. These are independent concerns and should not be conflated. **Docs changes needed:** Add an ADR (Architecture Decision Record) or hook convention note to `Docs/Backend-Development.md` or a new `Docs/Frontend-Development.md`. **Why:** Inconsistent patterns make it hard for a new developer to know which approach to follow. The presence of pattern 3 causes memory leaks and stale-state React warnings in production. --- ### TASK-016 — Extract generic `useListData` hook to eliminate duplicated fetch-list pattern **Where found:** `frontend/src/hooks/useActionList.ts`, `useFilterList.ts`, `useJailConfigs.ts`, and `useBlocklists.ts` each contain ~40 lines of nearly identical code: `useState` for data/loading/error, a `useRef`, a `refresh` callback with abort-create-set-loading-fetch-set logic, and a `useEffect` that calls `refresh` on mount. **Goal:** Create `frontend/src/hooks/useListData.ts` that exports a generic hook: ```ts function useListData(options: { fetcher: (signal: AbortSignal) => Promise; selector: (response: TResponse) => TItem[]; errorMessage: string; }): { items: TItem[]; loading: boolean; error: string | null; refresh: () => void } ``` Rewrite the four hooks listed above as thin wrappers around `useListData`. **Possible traps:** - Some hooks (e.g. `useJailConfigs`) expose additional operations like `reload` and `update` beyond just listing. These should remain in their own hook and call `useListData` only for the list-loading portion. - The `fetcher` function must accept a signal; ensure all underlying API functions have been updated (TASK-014) before replacing the hook internals. - Generic hooks with complex type parameters can confuse TypeScript's inference; provide explicit type arguments at each call site to avoid `unknown` leaking out. **Docs changes needed:** None. **Why:** Four copies of identical logic means bug fixes must be applied four times. The pattern is stable enough to abstract — every list hook has the same contract. --- ### TASK-017 — Move `source` derivation out of page components **Where found:** `frontend/src/pages/DashboardPage.tsx` and `frontend/src/pages/MapPage.tsx` both contain the identical line: ```ts const source = timeRange === "24h" ? "fail2ban" : "archive"; ``` **Goal:** Create a utility function `getDataSource(timeRange: TimeRange): "fail2ban" | "archive"` in `frontend/src/utils/constants.ts` (or a new `queryUtils.ts` entry). Import and call it in both pages. Remove the inline ternary. **Possible traps:** - This rule ("24h uses live fail2ban data, everything else uses the archive") is a backend contract, not a UI preference. If the backend ever adds a new time range or changes the source mapping, both places must be updated in sync; centralising it makes that change a one-liner. - The function name should make the business rule obvious — `getLiveDataSource` is more descriptive than `getDataSource`. **Docs changes needed:** Document the time range → source mapping in `Docs/Backend-Development.md` if not already described. **Why:** Duplicated business logic in UI components is fragile. If the rule changes or a new time range is added, it is easy to update one page and miss the other. --- ### TASK-018 — Move inline `style={{…}}` objects to `makeStyles` **Where found:** 30+ instances across `frontend/src/pages/MapPage.tsx`, `frontend/src/pages/map/MapBansTable.tsx`, `frontend/src/pages/DashboardPage.tsx`, `frontend/src/pages/jail/PatternsSection.tsx`, `frontend/src/pages/jails/BanUnbanForm.tsx`, `frontend/src/layouts/MainLayout.tsx`, and others. **Goal:** For each instance of `style={{…}}` that is not dynamic (i.e. the style values are constants or token references, not computed from props), move the declaration into the nearest `makeStyles` call. Dynamic styles that depend on runtime values (e.g. `style={{ opacity: loading ? 0.5 : 1 }}`) should remain inline or be converted to conditional `mergeClasses` with two separate class definitions. **Possible traps:** - The `MainLayout` logout button uses `style={{ width: "100%", justifyContent: collapsed ? "center" : "flex-start" }}` — this is dynamic and must become two `makeStyles` entries toggled with `mergeClasses`. - The `WorldMap` country `` uses CSS custom properties (`--country-fill`) as inline styles for CSS variable injection; this is intentional and should not be changed. - Running ESLint with `@typescript-eslint/no-unsafe-assignment` can catch some object literals, but a manual pass is more reliable. **Docs changes needed:** None. **Why:** Inline style objects create a new object reference on every render, defeating `React.memo` (TASK-011) and preventing the browser from reusing cached styles. Fluent UI's `makeStyles` uses atomic CSS which is far more cache-efficient. --- ### TASK-019 — Replace index keys with stable keys in editable lists **Where found:** 19 instances identified, including: - `frontend/src/components/config/StringListEditor.tsx` line 34 — `key={index}` on editable `Input` rows. - `frontend/src/components/config/RegexList.tsx` line 66 — `key={i}` on editable regex rows. - `frontend/src/components/config/JailsTab.tsx` lines 384, 714, 726 — `key={i}` and `key={idx}`. - `frontend/src/components/blocklist/BlocklistScheduleSection.tsx` line 147 — `key={i}` on `