feat: complete nx9-wg v0.8.0 platform

This commit is contained in:
thakares committed 2026-08-17 14:25:45 +05:30
1 parent c75e5c4e71
commit c8a9b7cde6
52 files changed
+7751 -725

No files matched your search

+100 -19
View File
@@ -1,25 +1,106 @@
# NX9 WireGuard Architecture Blueprint
# NX9 WireGuard — System Architecture & Workspace Structure
## System Overview
`nx9-wg` is structured as a modular six-crate Rust workspace designed for separation of concerns, strict failure domains, and testability.
`nx9-wg` is structured as a modular Rust workspace consisting of six specialized crates and a root binary.
| Crate | Responsibility | Dependencies |
| :--- | :--- | :--- |
| **`nx9-wg-core`** | Domain entities, cryptographic utilities (Argon2id, x25519, SHA-256), data validation, and configuration types. | `serde`, `argon2`, `x25519-dalek`, `sha2`, `ipnet`, `chrono`, `uuid` |
| **`nx9-wg-db`** | Authoritative persistence layer using SQLite with WAL mode, automated migrations, and isolated repository modules. | `nx9-wg-core`, `sqlx` (sqlite) |
| **`nx9-wireguard`**| WireGuard interface controller, client `.conf` configuration builder, live telemetry inspection, and pure Rust QR engine. | `nx9-wg-core`, `qrcode`, `image`, `base64` |
| **`nx9-wg-network`** | Linux kernel IP forwarding, routing table synchronization, and atomic `inet nx9_wg` nftables ruleset generator. | `nx9-wg-core`, `ipnet` |
| **`nx9-wg-api`** | Axum REST API, session and token authentication middleware, WebSocket live event broadcast, and Reconciliation Engine. | `nx9-wg-core`, `nx9-wg-db`, `nx9-wireguard`, `nx9-wg-network`, `axum`, `tower` |
| **`nx9-wg-ui`** | Dioxus web client shell (client only, business logic isolated in backend). | `nx9-wg-core` |
| **`nx9-wg`** | Primary application binary providing CLI operations and HTTP daemon server. | All workspace crates, `clap` |
```
nx9-wg (Workspace Root & Binary Executable)
├── crates/nx9-wg-core (Domain models, validation, cryptography, config)
├── crates/nx9-wg-db (SQLite store, migrations, repositories, WAL)
├── crates/nx9-wireguard (WireGuard Netlink execution, config builder, QR engine)
├── crates/nx9-wg-network (RTNETLINK networking, route management, nftables, procfs)
├── crates/nx9-wg-api (Axum REST API, WebSockets, auth, reconciliation, allocator)
└── crates/nx9-wg-ui (Design tokens, CSS engine, view models, SPA integration)
```
---
## Architectural Invariants
## 1. Crate Inventory & Layer Responsibilities
1. **Strict SQL Isolation**: All raw SQL queries and SQLite interactions are confined entirely to `crates/nx9-wg-db/`. No other crate or handler interacts with SQLite directly.
2. **Zero Shelling Out**: WireGuard, routing, and packet filtering interact with kernel abstractions and netlink without executing `wg`, `wg-quick`, or `iptables` subprocesses.
3. **Single Administrator Model**: The system maintains exactly one administrative identity with `CHECK (id = 1)`. No RBAC, multi-tenant, or organization complexity is introduced.
4. **Secret Redaction**: Passwords, private keys, preshared keys, and API tokens are never logged, persisted in plaintext, or exposed in error messages. All secret wrapper types implement custom `Debug` redactions (`[REDACTED]`).
5. **Deterministic Reconciliation**: Desired state in SQLite is the single source of truth. The reconciler computes drift and idempotently applies adjustments without touching unmanaged Linux resources.
### `nx9-wg-core`
- **Domain Entities**: Typed domain structures (`Interface`, `Peer`, `Network`, `Route`, `FirewallRule`, `Setting`, `Admin`, `Session`, `ApiToken`, `BackupMeta`, `AuditEvent`).
- **Validation**: Strict RFC-compliant validators for CIDRs, IP addresses, MTU ranges, listen ports, interface names, peer names, and password strength.
- **Cryptography**: Argon2id password hashing, SHA-256 token digest generation, X25519 keypair generation, and secure random string generation.
- **Configuration**: Hierarchical TOML and `NX9_WG_*` environment variable configuration loader.
### `nx9-wg-db`
- **Authoritative Persistence**: Migration-driven SQLite storage using `sqlx` in Write-Ahead Logging (WAL) mode.
- **Single Admin Invariant**: SQL constraint `CHECK (id = 1)` enforcing single-administrator identity.
- **Repositories**: Isolated data access layers for admin, auth, audit, backups, client profiles, interfaces, login attempts, networks, peers, routes, sessions, settings, and tokens.
- **Transactional Consistency**: Foreign key cascades (`ON DELETE CASCADE`) between interfaces and peers.
### `nx9-wireguard`
- **Native Netlink Engine**: `NativeLinuxWireGuardEngine` interacting with Linux RTNETLINK for link lifecycle and Generic Netlink family `wireguard` (`SET_DEVICE`, `GET_DEVICE`, `ReplacePeers`).
- **Client Config Generation**: Pure Rust `.conf` generation supporting full-tunnel and split-tunnel topologies.
- **QR Code Engine**: High-resolution SVG, PNG byte streams, and UTF-8 ASCII terminal QR code rendering.
- **Simulation Engine**: `SimulatedWireGuardEngine` for non-Linux platform development and testing.
### `nx9-wg-network`
- **Native Network Engine**: `NativeLinuxNetworkEngine` managing RTNETLINK interfaces, IPv4/IPv6 addresses, and route tables.
- **nftables Netfilter Engine**: `NativeLinuxNftablesEngine` utilizing `libnftables.so.1` for transactional rule generation in `table inet nx9_wg`.
- **Kernel IP Forwarding**: Direct `/proc/sys/net/ipv4/ip_forward` and `/proc/sys/net/ipv6/conf/all/forwarding` mutation.
- **Simulation Engine**: `SimulatedNetworkEngine` for local platform testing.
### `nx9-wg-api`
- **REST Router**: Axum HTTP handlers for auth, interfaces, peers, networks, routes, firewall, NAT, forwarding, settings, backups, diagnostics, and audit logs.
- **WebSocket Event Bus**: Tokio broadcast channel broadcasting real-time system events (`AuditEvent`, `InterfaceChanged`, `PeerChanged`, `PeerHandshake`, `SettingsChanged`).
- **Reconciliation Engine**: Mutex-serialized continuous drift detection and convergence controller.
- **Deterministic IP Allocator**: Collision-resistant next-IP allocation engine for managed subnets.
- **Backup & Restore Service**: Online SQLite atomic snapshot (`VACUUM INTO`) and verification engine.
### `nx9-wg-ui`
- **Design Tokens**: Structured CSS variable tokens for Dark and Light themes.
- **Stylesheet Generator**: In-process CSS compiler producing responsive layouts (`@media (max-width: 768px)`).
- **View Models**: Strongly-typed Rust UI state representations for dashboards, diagnostics, client export modals, and peer management tables.
---
## 2. End-to-End Control and Execution Plane
```mermaid
flowchart TD
subgraph ControlPlane["Control Plane (User & Administration)"]
User["Administrator (Browser / CLI)"]
SPA["Embedded SPA Web UI"]
CLI["Native CLI (nx9-wg)"]
API["Axum REST API / WebSockets"]
DB[("Authoritative SQLite Database")]
end
subgraph ReconciliationLayer["Reconciliation & Engine Layer"]
Reconciler["Reconciliation Engine (Serialized Mutex)"]
WGEngine["WireGuard Engine (Genl / RTNETLINK)"]
NetEngine["Network Engine (RTNETLINK & procfs)"]
NftEngine["Nftables Engine (libnftables Netfilter)"]
end
subgraph LinuxKernel["Linux Kernel Execution Plane"]
WGSocket["WireGuard Kernel Module (wireguard.ko)"]
RTNL["Kernel RTNETLINK (Links, Addrs, Routes)"]
Procfs["/proc/sys/net (IP Forwarding)"]
Netfilter["Netfilter Subsystem (table inet nx9_wg)"]
end
User -->|HTTPS / WSS| SPA
User -->|CLI Invocations| CLI
SPA -->|REST API Calls| API
CLI -->|In-Process Service Calls| API
API -->|Authoritative Mutations| DB
DB -->|Desired State Snapshot| Reconciler
Reconciler -->|Read Live Telemetry| WGEngine
Reconciler -->|Read Live Routes/Forwarding| NetEngine
Reconciler -->|Read Live Ruleset| NftEngine
WGEngine -->|Generic Netlink Messages| WGSocket
NetEngine -->|RTM_NEWLINK / NEWROUTE| RTNL
NetEngine -->|Write 1/0| Procfs
NftEngine -->|Atomic Netfilter Transactions| Netfilter
```
---
## 3. Subsystem Invariants & Security Boundaries
1. **Subprocess Isolation**: Zero invocations of `std::process::Command` or shell scripts across the entire production codebase.
2. **Persistence Authority**: SQLite remains the single authoritative source of truth. Kernel state is continuously reconciled to match database state.
3. **Firewall Isolation**: All nftables operations are confined to `table inet nx9_wg`. Unmanaged host tables are untouched.
4. **Route Safety**: Default gateway routes and host networking routes are protected against accidental deletion or flushing.
5. **Secret Redaction**: Private keys, preshared keys, password hashes, and token hashes are masked in `Debug` formatters, CLI outputs, and API responses.