Metadata-Version: 2.5
Name: vps-forge
Version: 0.1.0
Summary: Idempotent, rollback-safe VPS provisioning framework (Ansible + Python CLI)
Project-URL: Homepage, https://github.com/yangdw2024/VPSForge
Project-URL: Repository, https://github.com/yangdw2024/VPSForge
Project-URL: Issues, https://github.com/yangdw2024/VPSForge/issues
Author: yangdw2024
License-Expression: MIT
License-File: LICENSE
Keywords: ansible,caddy,devops,docker,hardening,provisioning,sing-box,vps
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: System :: Systems Administration
Requires-Python: >=3.10
Requires-Dist: ansible-core>=2.16.0
Requires-Dist: pydantic>=2.7.0
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: rich>=13.7.0
Requires-Dist: typer>=0.12.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.6.0; extra == 'dev'
Description-Content-Type: text/markdown

# vps-forge

Idempotent, rollback-safe VPS provisioning framework (Ansible + Python CLI).

## Installation

- **PyPI**:
  ```bash
  pip install vps-forge
  ansible-galaxy collection install ansible.posix community.general
  ```
- **npm (CLI wrapper)**:
  ```bash
  npx @yangdw2024/vps-forge --help
  ```
- **From source / GitHub Release template**:
  ```bash
  git clone https://github.com/yangdw2024/VPSForge.git
  cd VPSForge
  make setup
  ```

## Architecture

1. **Declarative Config (`config.yaml`)**: Single source of truth for global baseline settings and per-node topology/modules, initialized from `config.example.yaml` (which includes Chinese inline comments matching the Chinese CLI UX).
2. **Python Control Plane (`vps_forge/`)**:
   - `schema.py`: Pydantic v2 validation for `global`, `nodes[]`, pluggable modules (`caddy_tls`, `proxy_stack`, `monitor`), `module_vars`, unique node names, and `relay` -> `landing` topology checks.
   - `cli.py`: `init`, `apply` (`--dry-run`, `--tags`, `--limit`), `doctor`, and `doctor --deep`; per-node isolated WSL2 key permission mirroring (`0600`); live SSH port detection; compilation of `ansible/inventory/hosts.yml` and `ansible/inventory/host_vars/<node>.yml`; persistent `proxy_stack` secrets and client artifacts under `output/`; native Windows execution interception with WSL2 guidance.
   - `exporter.py`: Pure-stdlib `.zip` template package exporter (`python -m vps_forge.exporter`).
3. **Ansible Provisioning Plane (`ansible/`)**:
   - `preflight`: Read-only OS/hardware checks (Debian/Ubuntu).
   - `hardening`: Non-root sudo user, Ubuntu `ssh.socket` adaptation, merged `sshd -t` validation with rollback cleanup, UFW, Fail2ban, and a `systemd-run` anti-lockout rollback timer (`rollback_timeout_sec`). Safe for first-run `--dry-run` (`--check`) against a blank VPS.
   - `docker_base`: Timezone, container-safe BBR sysctl tuning, auto Swap (< 2GB RAM), Docker Engine + log rotation.
   - `roles/modules/{caddy_tls,proxy_stack,monitor}`: Pluggable Docker Compose business modules gated by `enabled_modules`, all `--check`-safe and idempotent across re-runs.
4. **Verification & Distribution (`scripts/`, `docker/`, `Makefile`)**:
   - Stage 3 local container smoke test (`make smoke-test`) and Stage 4 clean template export (`make export-template`).

## Quick Start (WSL2 / Linux / macOS)

> **Windows users**: Ansible cannot act as a control node on native Windows. Running `vps-forge apply` on native Windows prints the exact WSL2 command to execute.

```bash
# 1. One-shot setup in WSL2 Ubuntu (creates .venv, installs dev deps & Ansible collections)
make setup

# 2. Verify local toolchain & Ansible playbook syntax
make syntax-check
make lint
make test

# 3. Generate and edit config.yaml
.venv/bin/vps-forge init
# Edit config.yaml with your VPS IP, SSH keys, ports, and enabled modules

# 4. Dry-run, deploy, and verify (without touching local proxy/routing/DNS)
make dry-run
make apply
make doctor
make doctor-deep

# 5. Stage 3 local container smoke test & Stage 4 clean template export
make smoke-test
make export-template
```

## Configuration & Pluggable Modules

Each node in `config.yaml` supports `modules` drawn from: `docker_base`, `caddy_tls`, `proxy_stack`, `monitor`, plus optional per-node `module_vars` overrides.

### `caddy_tls`

Docker Compose Caddy deployment (`caddy:2-alpine`, container `vps-forge-caddy`) for automatic ACME HTTPS issuance/renewal, internal TLS, reverse proxy, or masquerade site hosting.

- `enabled` (`true`), `domain` (default `"localhost"`; required when `tls_mode: acme`), `email` (`null`)
- `tls_mode`: `"acme"` | `"internal"` | `"off"` (default `"acme"`)
- `mode`: `"reverse_proxy"` | `"masquerade"` | `"both"` (default `"reverse_proxy"`)
- `upstream` (`"127.0.0.1:8080"`), `masquerade_root` (`"/srv/www"`), `masquerade_title` (`"Welcome"`), `http_port` (`80`), `https_port` (`443`)

### `proxy_stack`

Docker Compose `sing-box` deployment (`ghcr.io/sagernet/sing-box:v1.10.7`, container `vps-forge-proxy`) supporting single-node `standalone`, multi-node `relay` -> `landing` chaining, and `upstream_proxy` residential SOCKS/HTTP egress chaining.

- `enabled` (`true`), `mode`: `"standalone"` | `"relay"` | `"landing"` (default `"standalone"`)
- `protocol`: `"vless_ws"` | `"trojan"` | `"shadowsocks"` (default `"vless_ws"`)
- `listen_host` (`"0.0.0.0"`), `listen_port` (`10443`), `ws_path` (`"/ws"`), `public_host` (`null`), `public_port` (`null`)
- `landing_node` (required when `mode: relay`; must reference a node with `proxy_stack` in `landing` or `standalone` mode)
- `upstream_proxy` (optional `{type: "socks" | "http", host, port, username?, password?}`)
- `uuid` / `password` (auto-generated and persisted under `output/` if omitted), `local_socks_port` (`10808`)

```yaml
# Example: standalone with upstream residential proxy
nodes:
  - name: edge-1
    host: 203.0.113.10
    ssh_private_key: ~/.ssh/id_ed25519
    ssh_public_key: ~/.ssh/id_ed25519.pub
    modules: [docker_base, caddy_tls, proxy_stack, monitor]
    caddy_tls:
      domain: edge.example.com
      email: ops@example.com
      tls_mode: acme
      mode: reverse_proxy
      upstream: 127.0.0.1:10443
    proxy_stack:
      mode: standalone
      protocol: vless_ws
      listen_port: 10443
      ws_path: /ws
      upstream_proxy:
        type: socks
        host: 198.51.100.20
        port: 1080
    monitor:
      listen_host: 127.0.0.1
      port: 9100
      health_port: 9101
      check_containers: [vps-forge-caddy, vps-forge-proxy]
```

```yaml
# Example: relay -> landing topology
nodes:
  - name: tokyo-relay
    role: relay
    host: 203.0.113.11
    ssh_private_key: ~/.ssh/id_ed25519
    ssh_public_key: ~/.ssh/id_ed25519.pub
    modules: [docker_base, proxy_stack]
    proxy_stack:
      mode: relay
      protocol: vless_ws
      listen_port: 10443
      landing_node: us-landing

  - name: us-landing
    role: landing
    host: 198.51.100.30
    ssh_private_key: ~/.ssh/id_ed25519
    ssh_public_key: ~/.ssh/id_ed25519.pub
    modules: [docker_base, proxy_stack]
    proxy_stack:
      mode: landing
      protocol: vless_ws
      listen_port: 10443
```

### `monitor`

Docker Compose node & service monitoring (`prom/node-exporter:v1.8.2`, container `vps-forge-monitor`) plus an HTTP `/healthz` sidecar bound to localhost by default.

- `enabled` (`true`), `listen_host` (`"127.0.0.1"`), `port` (`9100`), `health_port` (`9101`), `scrape_interval_sec` (`15`), `check_containers` (`[]`)

### `module_vars`

Optional per-node dictionary (`module_vars: {}`) merged into `ansible/inventory/host_vars/<node>.yml` for custom Ansible variable overrides.

## Deployment, Client Artifacts & Diagnostics

- **Dry-run vs Apply**:
  - `make dry-run` (`vps-forge apply -c config.yaml --dry-run`) executes Ansible `--check --diff` safely even against blank hosts and never writes secrets/configs into `output/`.
  - `make apply` (`vps-forge apply -c config.yaml`) compiles `ansible/inventory/hosts.yml` and `ansible/inventory/host_vars/<node>.yml` and applies all enabled roles. `vps-forge apply` also accepts `--tags` and `--limit`.
- **Client Artifacts (`output/`, ignored by `.gitignore`)**:
  - `output/<node>/credentials.json`: Persisted `uuid`, `password`, `protocol`, `mode` (reused on subsequent runs for idempotency unless overridden in `config.yaml`).
  - `output/<node>/client.json`: Generated `sing-box` client configuration.
  - `output/<node>/links.txt`: Shareable client URIs.
  - `output/summary.json`: Node topology and endpoint summary.
- **Diagnostics (`doctor` & `doctor --deep`)**:
  - `make doctor`: Local non-intrusive TCP reachability probe.
  - `make doctor-deep`: Read-only SSH diagnostic reporting host baseline (`SSH_PORTS`, `UFW_STATUS`, `UFW_RULES`, `BBR`, `FAIL2BAN`, `DOCKER`, `MEM`, `DISK`), container health (`CONTAINERS_RUNNING`, `CONTAINERS_TOTAL`, `CONTAINERS_UNHEALTHY`, `CONTAINER_DETAILS`), and remote-side read-only egress (`EGRESS_DIRECT`, `EGRESS_PROXY` via remote `127.0.0.1:<local_socks_port>`).

## Stage 3: Local Container Smoke Test

Run `make smoke-test` in WSL2 Ubuntu to execute `scripts/smoke_test.py` against local container target(s), verifying:

1. First-run `--dry-run` (`--check`) zero-error compatibility.
2. Full `apply` deployment across enabled modules (`caddy_tls`, `proxy_stack`, `monitor`).
3. Container health and `doctor --deep` read-only inspection.
4. Second-run idempotency (`changed=0` / stable state) and automated cleanup.

## Stage 4: Clean Template Export & Makefile Reference

Export a clean, distributable `.zip` template package without `git` or `/usr/bin/zip`:

```bash
make export-template
# or directly:
.venv/bin/python -m vps_forge.exporter --root . --output dist/vps-forge-template.zip
```

- **Included**: `Makefile`, `pyproject.toml`, `README.md`, `config.example.yaml`, `.gitignore`, `vps_forge/`, `ansible/` (excluding `ansible/inventory/`), `scripts/`, `docker/`, and `tests/`.
- **Excluded**: `.venv/`, `venv/`, `config.yaml`, `ansible/inventory/`, `output/`, `.git/`, `__pycache__/`, `.pytest_cache/`, `.ruff_cache/`, `.mypy_cache/`, `*.pyc`, `*.pyo`, `*.pyd`, `*$py.class`, `*.egg-info/`, `dist/`, `build/`, `.agents/`, `.vscode/`, `.idea/`, `.DS_Store`, `Thumbs.db`, `*.zip`, symlinks, and the output archive itself.

| Target | Purpose |
|---|---|
| `make help` | List all available Makefile targets |
| `make setup` | Create `.venv`, install project/dev dependencies, and install Ansible collections |
| `make lint` | Run `ruff check vps_forge tests` |
| `make test` | Run `pytest -v` unit tests |
| `make syntax-check` | Run `ansible-playbook --syntax-check` on `ansible/site.yml` |
| `make dry-run` | Run `vps-forge apply -c $(CONFIG) --dry-run` |
| `make apply` | Run `vps-forge apply -c $(CONFIG)` |
| `make doctor` | Run local TCP port probe |
| `make doctor-deep` | Run read-only SSH host, container health, and remote egress probe |
| `make smoke-test` | Run Stage 3 local container smoke test (`scripts/smoke_test.py`) |
| `make export-template` | Export clean project `.zip` template to `$(EXPORT_OUTPUT)` |
| `make clean` | Remove caches and `build/`/`dist/` artifacts (preserves `.venv`, `config.yaml`, `output/`, `ansible/inventory/`) |

## Operational Safety Rules

1. **WSL2 Control Plane**: Run provisioning and `make` commands inside WSL2 Ubuntu (or Linux/macOS); native Windows `apply` is safely intercepted.
2. **Anti-Lockout Protection**: SSH hardening uses a `systemd-run` rollback timer (`rollback_timeout_sec`), merged `sshd -t` validation in a `block`/`rescue` flow, and live SSH port detection.
3. **Zero Local Network Mutations**: `vps-forge` (`apply`, `doctor --deep`, `smoke-test`, and tests) never modifies local host proxy settings, routing tables, or DNS configuration.
