Skip to content

About

A lightweight cross-platform system-level productivity enforcement platform.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

41 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

BlockForge

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.

Platform: Linux Python: 3.12+ FastAPI React: 18 TypeScript Tailwind CSS License: MIT


Table of Contents


Overview

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.

Architecture

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

Key Features

  • 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 their www. 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.bak snapshots before write operations with one-click restore and download options.
  • Instant DNS Cache Flushing: Integrates with resolvectl on 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.

System Requirements

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

Installation and Setup

1. Clone the Repository

git clone https://github.com/2neuronbrain/BlockForge.git
cd BlockForge

2. Database Configuration

BlockForge uses MySQL to persist activity logs and manage user accounts.

  1. Ensure the MySQL service is active:

    sudo systemctl status mysql
  2. The default connection configured in backend/api/database.py connects via:

    • Host: localhost:3306
    • Unix Socket: /var/run/mysqld/mysqld.sock
    • User: root
    • Password: StrongPass@123
    • Database: blockforge
  3. The backend automatically creates the blockforge database and required tables (activity_logs, users) on initial startup. If your MySQL credentials differ, update the connection strings in backend/api/database.py:

    _INIT_URL = "mysql+pymysql://<user>:<password>@localhost:3306/"
    _DB_URL = "mysql+pymysql://<user>:<password>@localhost:3306/blockforge"
  4. If migrating historical logs from an earlier file-based installation:

    cd backend
    python3 scripts/migrate_logs.py
    cd ..

3. Backend Setup

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 pymysql

Verify that the CLI command is available:

blockforge --help

4. Start the API Server

The 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

5. Frontend Setup

Open a second terminal window for the React dashboard:

cd BlockForge/frontend
npm install
npm run dev

The Vite development server starts at http://localhost:8080. All API requests (/api/*) are automatically proxied to http://127.0.0.1:8000.


Default Credentials

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.


CLI Reference

The blockforge CLI manages hosts entries directly from the terminal without requiring the web server.

Commands

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

Options and Flags

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

CLI Examples

  1. Simulate blocking changes without root privileges:

    blockforge block --dry-run
  2. Apply blocklist with an automatic backup:

    sudo env "PATH=$PATH" blockforge block --backup
  3. Block domains from a custom list file:

    sudo env "PATH=$PATH" blockforge block --file /path/to/custom_domains.txt
  4. Block exact domains only, excluding www. prefixes:

    sudo env "PATH=$PATH" blockforge block --no-www
  5. Preview domain removal:

    blockforge unblock --dry-run
  6. Unblock all managed domains:

    sudo env "PATH=$PATH" blockforge unblock

Note on sudo env "PATH=$PATH": Standard sudo commands reset environment variables for security. Passing PATH=$PATH ensures the active Python virtual environment binaries remain accessible under root.

Shell Script Wrappers

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.sh

REST API Reference

The FastAPI service exposes endpoints under /api.

Authentication

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

System Status

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

Blocklist Management

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

Blocking Operations

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

Backup and Restore

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

Configuration and Logs

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

Dashboard Features

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.

Configuration

Blocklist Syntax

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://, and www. are automatically stripped.
  • Path parameters (e.g., domain.com/path) are rejected to avoid corrupting hosts resolution.

Application Settings

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.


Testing and Verification

Backend Tests

Execute the unit test suite using Python's built-in unittest runner:

cd backend
python3 -m unittest discover tests

Frontend Tests and Code Quality

Run 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 build

Troubleshooting

sudo: blockforge: command not found

When using sudo, your shell's current PATH is reset. Run commands with the environment preserved:

sudo env "PATH=$PATH" blockforge block

Or execute using the absolute virtual environment binary:

sudo backend/.venv/bin/blockforge block

ModuleNotFoundError: No module named 'sqlalchemy' or 'pymysql'

Ensure all database drivers are installed inside your virtual environment:

source backend/.venv/bin/activate
pip install -e backend/ sqlalchemy pymysql

Permission Denied on /etc/hosts

Modifying system host resolution files requires root authority. Ensure the API server is launched via sudo or verify that your terminal user possesses sudoer rights.

Blocked Sites Continue to Resolve in Browsers

  1. Verify the DNS cache was flushed:
    sudo resolvectl flush-caches
  2. Modern browsers frequently use DNS-over-HTTPS (DoH), bypassing the local /etc/hosts file. 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.

MySQL Connection Failure

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.


License

This project is licensed under the MIT License. See the LICENSE file for complete terms.

About

A lightweight cross-platform system-level productivity enforcement platform.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages