BlockForge is a website blocking and domain management toolkit for Linux systems. It combines a Python CLI and FastAPI backend with a modern React dashboard to redirect distracting or unwanted domains to 127.0.0.1 via the system /etc/hosts file.
- Overview
- Architecture
- Key Features
- System Requirements
- Installation and Setup
- Default Credentials
- CLI Reference
- REST API Reference
- Dashboard Features
- Configuration
- Testing and Verification
- Troubleshooting
- License
BlockForge provides local, DNS-level website blocking without browser extensions or external proxies. By managing redirect entries in /etc/hosts, it blocks network traffic to designated domains across all applications and browsers on the machine.
The project offers two complementary interfaces:
- Command Line Interface (CLI): Built with Typer for terminal workflows, automated scripts, and remote maintenance.
- Web Dashboard: Built with React, Vite, Tailwind CSS, and shadcn/ui for interactive visual monitoring, domain list editing, live hosts inspection, activity logging, and configuration management.
BlockForge/
├── backend/ # Python backend package
│ ├── api/ # FastAPI application
│ │ ├── main.py # FastAPI entry point, CORS middleware, router attachment
│ │ ├── routes.py # Route handlers (auth, status, domains, block, backup, settings)
│ │ ├── schemas.py # Pydantic models for request and response payloads
│ │ └── database.py # SQLAlchemy setup, MySQL connection, and database models
│ ├── blockforge/ # Core blocking engine
│ │ ├── blocker.py # Hosts file parsing, diffing, write logic, and DNS flush
│ │ └── cli.py # Typer CLI definition and commands
│ ├── data/
│ │ └── settings.json # Runtime configuration store
│ ├── docs/ # Detailed project documentation
│ ├── scripts/ # Helper and migration scripts
│ │ ├── block.sh # Shell wrapper for block execution
│ │ ├── unblock.sh # Shell wrapper for unblock execution
│ │ └── migrate_logs.py # One-time migration from activity_log.json to MySQL
│ ├── tests/ # Backend test suite
│ ├── blocklist.txt # Default domain blocklist
│ ├── pyproject.toml # Package configuration and dependencies
│ └── LICENSE # MIT License
│
└── frontend/ # React dashboard
├── src/
│ ├── components/ # UI components (sidebar, header, status tiles, tables)
│ ├── hooks/ # State management and UI hooks
│ ├── lib/ # API client and utility functions
│ └── pages/ # Views (Dashboard, BlockLists, Logs, Backup, Data, Settings, Docs)
├── vite.config.ts # Vite config with dev proxy (/api -> :8000)
└── package.json # Node dependencies and scripts
- Safe Hosts File Operations: Appends redirects idempotently without modifying existing system entries. Removes only managed domains upon unblocking.
- Automatic
www.Subdomain Expansion: Blocks both bare domains (example.com) and theirwww.counterparts (www.example.com) by default. - Strict Domain Validation: Enforces RFC-compliant domain formatting via regex, stripping URL protocols (
http://,https://) and path segments automatically. - Dry-Run Mode: Test and preview all hosts modifications without root privileges and without altering files.
- Automated Backup and Restore: Generates
/etc/hosts.baksnapshots before write operations with one-click restore and download options. - Instant DNS Cache Flushing: Integrates with
resolvectlon systemd-resolved Linux systems to invalidate cached DNS records immediately. - Persistent MySQL Audit Logs: Records all block, unblock, domain modification, and DNS flush operations with timestamps and status codes.
- Integrated User Authentication: Provides account registration, session login, and profile password updates.
- In-App Documentation Viewer: Browse CLI guides, architecture specs, and troubleshooting notes directly within the dashboard.
| Component | Requirement | Notes |
|---|---|---|
| Operating System | Linux (Ubuntu 22.04+ recommended) | Relies on /etc/hosts and resolvectl |
| Python | 3.12 or newer | Required for backend CLI and FastAPI server |
| Node.js | 18.0.0 or newer | Required for frontend build and Vite dev server |
| Database | MySQL 8.0+ | Stores user credentials and activity audit logs |
| Privileges | sudo / Root access |
Required to write to /etc/hosts during active operations |
git clone https://github.com/2neuronbrain/BlockForge.git
cd BlockForgeBlockForge uses MySQL to persist activity logs and manage user accounts.
-
Ensure the MySQL service is active:
sudo systemctl status mysql
-
The default connection configured in
backend/api/database.pyconnects via:- Host:
localhost:3306 - Unix Socket:
/var/run/mysqld/mysqld.sock - User:
root - Password:
StrongPass@123 - Database:
blockforge
- Host:
-
The backend automatically creates the
blockforgedatabase and required tables (activity_logs,users) on initial startup. If your MySQL credentials differ, update the connection strings inbackend/api/database.py:_INIT_URL = "mysql+pymysql://<user>:<password>@localhost:3306/" _DB_URL = "mysql+pymysql://<user>:<password>@localhost:3306/blockforge"
-
If migrating historical logs from an earlier file-based installation:
cd backend python3 scripts/migrate_logs.py cd ..
Create a dedicated virtual environment inside the backend directory:
cd backend
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install -e . sqlalchemy pymysqlVerify that the CLI command is available:
blockforge --helpThe API server modifies /etc/hosts upon request and therefore must run with root permissions:
# From within the backend directory with .venv active:
sudo .venv/bin/uvicorn api.main:app --host 127.0.0.1 --port 8000 --reload- API Base URL:
http://127.0.0.1:8000 - Interactive Swagger Documentation:
http://127.0.0.1:8000/docs - OpenAPI Schema:
http://127.0.0.1:8000/openapi.json
Open a second terminal window for the React dashboard:
cd BlockForge/frontend
npm install
npm run devThe Vite development server starts at http://localhost:8080. All API requests (/api/*) are automatically proxied to http://127.0.0.1:8000.
The backend automatically seeds a default administrator account upon initial startup:
- Username:
admin - Password:
admin
Log in at http://localhost:8080/login using these credentials. You can update your password or create additional user accounts via the dashboard.
The blockforge CLI manages hosts entries directly from the terminal without requiring the web server.
| Command | Syntax | Description |
|---|---|---|
block |
blockforge block [OPTIONS] |
Read blocklist and redirect domains to 127.0.0.1 |
unblock |
blockforge unblock [OPTIONS] |
Remove matching domain entries from /etc/hosts |
help |
blockforge --help |
Display command usage and option descriptions |
| Option | Flag | Type | Default | Description |
|---|---|---|---|---|
--file |
-f |
PATH |
backend/blocklist.txt |
Path to custom domain blocklist file |
--hosts-path |
PATH |
/etc/hosts |
Path to hosts file to modify | |
--dry-run |
FLAG |
False |
Simulate modifications without writing to disk | |
--backup |
FLAG |
False |
Create /etc/hosts.bak copy prior to changes (block only) |
|
--no-www |
FLAG |
False |
Disable automatic generation of www. variants |
|
--skip-flush |
FLAG |
False |
Skip flushing the system DNS cache |
-
Simulate blocking changes without root privileges:
blockforge block --dry-run
-
Apply blocklist with an automatic backup:
sudo env "PATH=$PATH" blockforge block --backup -
Block domains from a custom list file:
sudo env "PATH=$PATH" blockforge block --file /path/to/custom_domains.txt -
Block exact domains only, excluding
www.prefixes:sudo env "PATH=$PATH" blockforge block --no-www -
Preview domain removal:
blockforge unblock --dry-run
-
Unblock all managed domains:
sudo env "PATH=$PATH" blockforge unblock
Note on
sudo env "PATH=$PATH": Standardsudocommands reset environment variables for security. PassingPATH=$PATHensures the active Python virtual environment binaries remain accessible under root.
Standalone Bash scripts are available in backend/scripts/ to execute commands without manual path exports:
# Execute block
sudo bash backend/scripts/block.sh
# Execute unblock
sudo bash backend/scripts/unblock.shThe FastAPI service exposes endpoints under /api.
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/login |
Authenticate user credentials and start session |
POST |
/api/register |
Register a new user account |
GET |
/api/profile/{username} |
Fetch user account details |
PUT |
/api/profile/{username} |
Update email address or change password |
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/status |
Reports root execution status, hosts writability, domain count, and DB health |
GET |
/api/hosts |
Returns parsed list of all active entries in the hosts file |
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/domains |
Retrieve all domains currently listed in blocklist.txt |
POST |
/api/domains |
Add a normalized domain to blocklist.txt |
DELETE |
/api/domains/{domain} |
Delete a domain from blocklist.txt |
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/block |
Apply current blocklist to /etc/hosts |
POST |
/api/unblock |
Remove all blocklist entries from /etc/hosts |
POST |
/api/flush-dns |
Execute system DNS cache flush via resolvectl |
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/backup/status |
Check if /etc/hosts.bak exists and return metadata |
POST |
/api/backup |
Create a backup snapshot of /etc/hosts |
POST |
/api/restore |
Restore /etc/hosts from /etc/hosts.bak |
GET |
/api/backup/download |
Download /etc/hosts.bak directly to client |
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/settings |
Read application settings from data/settings.json |
PATCH |
/api/settings |
Update settings (redirect IP, auto-backup, default dry-run) |
GET |
/api/logs?limit=50 |
Retrieve recent activity audit logs from MySQL |
The web interface provides an administrative control center:
- Overview Dashboard (
/dashboard): Real-time status cards detailing root permission, hosts write permissions, database connectivity, and total blocked domains, alongside quick-action toggle controls. - Block Lists Manager (
/block-lists): Add, search, and delete domains with immediate client-side validation and deduplication feedback. - Activity Logs (
/logs): Filter and review timestamped audit records for all operations with one-click JSON export. - Backup and Restore (
/backup): Inspect backup file size and modification timestamps, trigger manual snapshots, restore previous states, or download archive copies. - Data Management (
/data): Import domain lists via file upload or copy-paste JSON formats, and export current configurations. - Settings (
/settings): Adjust redirect IP targets, toggle automatic backup on block, configure DNS flush execution, and set log polling intervals. - Integrated Documentation (
/docs): Read embedded project guides, setup tutorials, and CLI references directly in the browser.
The default blocklist is located at backend/blocklist.txt.
- One domain per line:
# Social Media instagram.com facebook.com # Video Streaming netflix.com youtube.com - Lines prefixed with
#are treated as comments and ignored. - Whitespace and blank lines are ignored.
- Prefixes like
http://,https://, andwww.are automatically stripped. - Path parameters (e.g.,
domain.com/path) are rejected to avoid corrupting hosts resolution.
Runtime settings are persisted in backend/data/settings.json:
{
"redirect_ip": "127.0.0.1",
"include_www": true,
"auto_backup": false,
"skip_dns_flush": false,
"dry_run_default": false,
"blocklist_path": "",
"hosts_path": "/etc/hosts",
"poll_interval_seconds": 60
}These parameters can be modified via PATCH /api/settings or adjusted directly within the dashboard settings panel.
Execute the unit test suite using Python's built-in unittest runner:
cd backend
python3 -m unittest discover testsRun tests, typechecks, and code style inspections in the frontend directory:
cd frontend
# Run unit tests
npm run test
# Run linter
npm run lint
# Build production bundle
npm run buildWhen using sudo, your shell's current PATH is reset. Run commands with the environment preserved:
sudo env "PATH=$PATH" blockforge blockOr execute using the absolute virtual environment binary:
sudo backend/.venv/bin/blockforge blockEnsure all database drivers are installed inside your virtual environment:
source backend/.venv/bin/activate
pip install -e backend/ sqlalchemy pymysqlModifying system host resolution files requires root authority. Ensure the API server is launched via sudo or verify that your terminal user possesses sudoer rights.
- Verify the DNS cache was flushed:
sudo resolvectl flush-caches
- Modern browsers frequently use DNS-over-HTTPS (DoH), bypassing the local
/etc/hostsfile. Disable "Secure DNS" or "DNS over HTTPS" in your browser settings (Chrome:chrome://settings/security, Firefox:about:preferences#privacy) to force local system DNS resolution.
Confirm that the MySQL daemon is running and accepting local connections:
sudo systemctl restart mysql
mysql -u root -p -e "SHOW DATABASES;"If your MySQL socket is not at /var/run/mysqld/mysqld.sock, verify its path in /etc/mysql/my.cnf and adjust _SOCKET in backend/api/database.py.
This project is licensed under the MIT License. See the LICENSE file for complete terms.