feat: Stage 1 — backend and frontend scaffolding

Backend (tasks 1.1, 1.5–1.8):
- pyproject.toml with FastAPI, Pydantic v2, aiosqlite, APScheduler 3.x,
  structlog, bcrypt; ruff + mypy strict configured
- Pydantic Settings (BANGUI_ prefix env vars, fail-fast validation)
- SQLite schema: settings, sessions, blocklist_sources, import_log;
  WAL mode + foreign keys; idempotent init_db()
- FastAPI app factory with lifespan (DB, aiohttp session, scheduler),
  CORS, unhandled-exception handler, GET /api/health
- Fail2BanClient: async Unix-socket wrapper using run_in_executor,
  custom error types, async context manager
- Utility modules: ip_utils, time_utils, constants
- 47 tests; ruff 0 errors; mypy --strict 0 errors

Frontend (tasks 1.2–1.4):
- Vite + React 18 + TypeScript strict; Fluent UI v9; ESLint + Prettier
- Custom brand theme (#0F6CBD, WCAG AA contrast) with light/dark variants
- Typed fetch API client (ApiError, get/post/put/del) + endpoints constants
- tsc --noEmit 0 errors
This commit is contained in:
2026-02-28 21:15:01 +01:00
parent 460d877339
commit 7392c930d6
59 changed files with 7601 additions and 17 deletions

10
frontend/.prettierrc Normal file
View File

@@ -0,0 +1,10 @@
{
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100,
"bracketSpacing": true,
"arrowParens": "always",
"endOfLine": "lf"
}

28
frontend/eslint.config.ts Normal file
View File

@@ -0,0 +1,28 @@
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import reactHooks from "eslint-plugin-react-hooks";
import prettierConfig from "eslint-config-prettier";
export default tseslint.config(
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.strictTypeChecked],
files: ["**/*.{ts,tsx}"],
languageOptions: {
parserOptions: {
project: ["./tsconfig.json", "./tsconfig.node.json"],
tsconfigRootDir: import.meta.dirname,
},
},
plugins: {
"react-hooks": reactHooks,
},
rules: {
...reactHooks.configs.recommended.rules,
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/explicit-function-return-type": "warn",
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
},
},
prettierConfig,
);

12
frontend/index.html Normal file
View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BanGUI</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

5051
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

37
frontend/package.json Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "bangui-frontend",
"private": true,
"version": "0.1.0",
"description": "BanGUI frontend — fail2ban web management interface",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"typecheck": "tsc --noEmit",
"format": "prettier --write 'src/**/*.{ts,tsx,css}'"
},
"dependencies": {
"@fluentui/react-components": "^9.55.0",
"@fluentui/react-icons": "^2.0.257",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.27.0"
},
"devDependencies": {
"@eslint/js": "^9.13.0",
"@types/node": "^25.3.2",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@typescript-eslint/eslint-plugin": "^8.13.0",
"@typescript-eslint/parser": "^8.13.0",
"@vitejs/plugin-react": "^4.3.3",
"eslint": "^9.13.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-react-hooks": "^5.0.0",
"prettier": "^3.3.3",
"typescript": "^5.6.3",
"vite": "^5.4.11"
}
}

45
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,45 @@
/**
* Application root component.
*
* Wraps the entire application in:
* 1. `FluentProvider` — supplies the Fluent UI theme and design tokens.
* 2. `BrowserRouter` — enables client-side routing via React Router.
*
* Route definitions are delegated to `AppRoutes` (implemented in Stage 3).
* For now a placeholder component is rendered so the app can start and the
* theme can be verified.
*/
import { FluentProvider } from "@fluentui/react-components";
import { BrowserRouter } from "react-router-dom";
import { lightTheme } from "./theme/customTheme";
/**
* Temporary placeholder shown until full routing is wired up in Stage 3.
*/
function AppPlaceholder(): JSX.Element {
return (
<div style={{ padding: 32, fontFamily: "Segoe UI, sans-serif" }}>
<h1 style={{ fontSize: 28, fontWeight: 600 }}>BanGUI</h1>
<p style={{ fontSize: 14, color: "#605e5c" }}>
Frontend scaffolding complete. Full UI implemented in Stage 3.
</p>
</div>
);
}
/**
* Root application component.
* Mounts `FluentProvider` and `BrowserRouter` around all page content.
*/
function App(): JSX.Element {
return (
<FluentProvider theme={lightTheme}>
<BrowserRouter>
<AppPlaceholder />
</BrowserRouter>
</FluentProvider>
);
}
export default App;

137
frontend/src/api/client.ts Normal file
View File

@@ -0,0 +1,137 @@
/**
* Central typed API client.
*
* This is the single point of contact between the frontend and the BanGUI
* backend. Components and hooks never call `fetch` directly — they use the
* functions exported from domain-specific API modules (e.g. `api/bans.ts`),
* which call the helpers exported from this file.
*
* All request and response types are defined in `src/types/` and used here
* to guarantee type safety at the API boundary.
*/
import { ENDPOINTS } from "./endpoints";
/** Base URL for all API calls. Falls back to `/api` in production. */
const BASE_URL: string = import.meta.env.VITE_API_URL ?? "/api";
// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------
/** Thrown by the API client when the server returns a non-2xx response. */
export class ApiError extends Error {
/** HTTP status code returned by the server. */
public readonly status: number;
/** Raw response body text as returned by the server. */
public readonly body: string;
/**
* @param status - The HTTP status code.
* @param body - The raw response body text.
*/
constructor(status: number, body: string) {
super(`API error ${String(status)}: ${body}`);
this.name = "ApiError";
this.status = status;
this.body = body;
}
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
/**
* Execute a `fetch` call and return the parsed JSON body as `T`.
*
* @param url - Fully-qualified URL.
* @param options - Standard `RequestInit` options.
* @returns Parsed JSON response cast to `T`.
* @throws {ApiError} When the server returns a non-2xx status code.
*/
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
const response: Response = await fetch(url, {
...options,
credentials: "include",
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
if (!response.ok) {
const body: string = await response.text();
throw new ApiError(response.status, body);
}
// 204 No Content — return undefined cast to T.
if (response.status === 204) {
return undefined as unknown as T;
}
return (await response.json()) as T;
}
// ---------------------------------------------------------------------------
// Public HTTP verb helpers
// ---------------------------------------------------------------------------
/**
* Perform a GET request to the given path.
*
* @param path - API path relative to `BASE_URL`, e.g. `"/jails"`.
* @returns Parsed response body typed as `T`.
*/
export async function get<T>(path: string): Promise<T> {
return request<T>(`${BASE_URL}${path}`);
}
/**
* Perform a POST request with a JSON body.
*
* @param path - API path relative to `BASE_URL`.
* @param body - Request payload to serialise as JSON.
* @returns Parsed response body typed as `T`.
*/
export async function post<T>(path: string, body: unknown): Promise<T> {
return request<T>(`${BASE_URL}${path}`, {
method: "POST",
body: JSON.stringify(body),
});
}
/**
* Perform a PUT request with a JSON body.
*
* @param path - API path relative to `BASE_URL`.
* @param body - Request payload to serialise as JSON.
* @returns Parsed response body typed as `T`.
*/
export async function put<T>(path: string, body: unknown): Promise<T> {
return request<T>(`${BASE_URL}${path}`, {
method: "PUT",
body: JSON.stringify(body),
});
}
/**
* Perform a DELETE request, optionally with a JSON body.
*
* @param path - API path relative to `BASE_URL`.
* @param body - Optional request payload.
* @returns Parsed response body typed as `T`.
*/
export async function del<T>(path: string, body?: unknown): Promise<T> {
return request<T>(`${BASE_URL}${path}`, {
method: "DELETE",
body: body !== undefined ? JSON.stringify(body) : undefined,
});
}
/** Convenience namespace bundling all HTTP helpers. */
export const api = { get, post, put, del } as const;
// Re-export endpoints so callers only need to import from `client.ts` if desired.
export { ENDPOINTS };

View File

@@ -0,0 +1,86 @@
/**
* API endpoint path constants.
*
* Every backend path used by the frontend is defined here.
* Components and API modules import from this file rather than
* hard-coding URL strings, so renaming an endpoint requires only one change.
*/
export const ENDPOINTS = {
// -------------------------------------------------------------------------
// Health
// -------------------------------------------------------------------------
health: "/health",
// -------------------------------------------------------------------------
// Setup wizard
// -------------------------------------------------------------------------
setup: "/setup",
// -------------------------------------------------------------------------
// Authentication
// -------------------------------------------------------------------------
authLogin: "/auth/login",
authLogout: "/auth/logout",
// -------------------------------------------------------------------------
// Dashboard
// -------------------------------------------------------------------------
dashboardStatus: "/dashboard/status",
dashboardBans: "/dashboard/bans",
dashboardBansByCountry: "/dashboard/bans/by-country",
// -------------------------------------------------------------------------
// Jails
// -------------------------------------------------------------------------
jails: "/jails",
jail: (name: string): string => `/jails/${encodeURIComponent(name)}`,
jailStart: (name: string): string => `/jails/${encodeURIComponent(name)}/start`,
jailStop: (name: string): string => `/jails/${encodeURIComponent(name)}/stop`,
jailIdle: (name: string): string => `/jails/${encodeURIComponent(name)}/idle`,
jailReload: (name: string): string => `/jails/${encodeURIComponent(name)}/reload`,
jailsReloadAll: "/jails/reload-all",
jailIgnoreIp: (name: string): string => `/jails/${encodeURIComponent(name)}/ignoreip`,
// -------------------------------------------------------------------------
// Bans
// -------------------------------------------------------------------------
bans: "/bans",
bansActive: "/bans/active",
// -------------------------------------------------------------------------
// Geo / IP lookup
// -------------------------------------------------------------------------
geoLookup: (ip: string): string => `/geo/lookup/${encodeURIComponent(ip)}`,
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
configJails: "/config/jails",
configJail: (name: string): string => `/config/jails/${encodeURIComponent(name)}`,
configGlobal: "/config/global",
configReload: "/config/reload",
configRegexTest: "/config/regex-test",
// -------------------------------------------------------------------------
// Server settings
// -------------------------------------------------------------------------
serverSettings: "/server/settings",
serverFlushLogs: "/server/flush-logs",
// -------------------------------------------------------------------------
// Ban history
// -------------------------------------------------------------------------
history: "/history",
historyIp: (ip: string): string => `/history/${encodeURIComponent(ip)}`,
// -------------------------------------------------------------------------
// Blocklists
// -------------------------------------------------------------------------
blocklists: "/blocklists",
blocklist: (id: number): string => `/blocklists/${String(id)}`,
blocklistPreview: (id: number): string => `/blocklists/${String(id)}/preview`,
blocklistsImport: "/blocklists/import",
blocklistsSchedule: "/blocklists/schedule",
blocklistsLog: "/blocklists/log",
} as const;

View File

@@ -0,0 +1 @@
/** Reusable UI component exports. Components are added here as they are implemented. */

View File

@@ -0,0 +1 @@
/** Custom React hook exports. Hooks are added here as they are implemented. */

View File

@@ -0,0 +1 @@
/** Layout component exports. Layouts are added here as they are implemented. */

24
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,24 @@
/**
* Application entry point.
*
* Mounts the root `<App />` component into the `#root` DOM element
* supplied by `index.html`.
*/
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
const rootElement = document.getElementById("root");
if (rootElement === null) {
throw new Error(
"Root element #root not found. Ensure index.html contains <div id='root'></div>."
);
}
createRoot(rootElement).render(
<StrictMode>
<App />
</StrictMode>
);

View File

@@ -0,0 +1 @@
/** Page component exports. Pages are added here as they are implemented. */

View File

@@ -0,0 +1 @@
/** React context provider exports. Providers are added here as they are implemented. */

View File

@@ -0,0 +1,47 @@
/**
* BanGUI Fluent UI custom theme.
*
* The primary brand colour ramp is built around #0F6CBD (a deep, professional blue).
* This colour has a contrast ratio of ~5.4:1 against white, satisfying WCAG 2.1 AA
* requirements for both text and large UI elements.
*
* Both `lightTheme` and `darkTheme` share the same brand ramp so all semantic
* colour slots stay consistent when the user switches modes.
*/
import {
createDarkTheme,
createLightTheme,
type BrandVariants,
type Theme,
} from "@fluentui/react-components";
/**
* BanGUI brand colour ramp — 16 stops from 10 (darkest) to 160 (lightest).
*
* Primary stop (80): #0F6CBD — contrast ratio ≈ 5.4:1 against white.
*/
const banGuiBrand: BrandVariants = {
10: "#020D1A",
20: "#041B32",
30: "#072B50",
40: "#0A3C6E",
50: "#0C4E8A",
60: "#0E5FA7",
70: "#1169BA",
80: "#0F6CBD" /* PRIMARY — passes WCAG AA */,
90: "#2C81CC",
100: "#4A96D8",
110: "#6CADE3",
120: "#91C5EC",
130: "#B5D9F3",
140: "#D2EAF8",
150: "#E8F4FB",
160: "#F3F9FD",
};
/** Light theme using the BanGUI brand palette. */
export const lightTheme: Theme = createLightTheme(banGuiBrand);
/** Dark theme using the BanGUI brand palette. */
export const darkTheme: Theme = createDarkTheme(banGuiBrand);

View File

@@ -0,0 +1 @@
/** Shared TypeScript type definition exports. Types are added here as they are implemented. */

View File

@@ -0,0 +1 @@
/** Utility function exports. Utilities are added here as they are implemented. */

9
frontend/src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string | undefined;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}

31
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,31 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Strict mode required */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
/* Paths */
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src", "vite.config.ts"]
}

View File

@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
"composite": true,
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts"]
}

22
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,22 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { resolve } from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
},
server: {
port: 5173,
proxy: {
"/api": {
target: "http://localhost:8000",
changeOrigin: true,
},
},
},
});