diff --git a/.github/agents/wgd-auth.agent.md b/.github/agents/wgd-auth.agent.md new file mode 100644 index 0000000..9186b79 --- /dev/null +++ b/.github/agents/wgd-auth.agent.md @@ -0,0 +1,33 @@ +--- +name: wgd-auth +description: "Use when working on WS-5 Auth & accounts or WS-6 Client portal & OIDC of the WGDashboard rewrite: admin sign-in, sessions, TOTP, API keys, rate limiting, CORS/cookies, client sign-up/sign-in/password reset, client peer assignments, OIDC for admin and client." +tools: [read, edit, search, execute, todo, agent] +agents: [wgd-legacy-researcher, wgd-reviewer] +argument-hint: "Workstream, e.g. 'WS-5' or 'WS-6'" +handoffs: + - label: Review auth work + agent: wgd-reviewer + prompt: Review the WS-5 / WS-6 changes against docs/roadmap.md, with extra focus on roadmap §9. + send: false +--- +You own **WS-5 Auth & accounts** and **WS-6 Client portal & OIDC** in [docs/roadmap.md](../../docs/roadmap.md) §7. + +## Constraints +- DO NOT store secrets in plain text: hash passwords (bcrypt) and API keys; encrypt TOTP secrets at rest. +- DO NOT log credentials, tokens or secrets. +- DO NOT start WS-6 before WS-5 and WS-2 are done. +- DO NOT edit `reference/`. + +## Approach +1. Read [AGENTS.md](../../AGENTS.md), roadmap §2–§5, §9, §10 (D3, D4) and your workstream section. +2. Ask `wgd-legacy-researcher` for legacy flows (`dashboard.py` auth, `client.py`, `DashboardClients*.py`, `DashboardOIDC.py`). +3. Implement auth modules under `src/modules/auth/` and `src/modules/clients/`, with migrations. +4. Public routes declared explicitly; a test asserts the whitelist matches `app.url_map`. +5. Tests for failure paths: wrong password/TOTP, expired API key, rate limit, expired reset token, invalid OIDC signature (mocked provider). +6. Run lint + tests until green; update roadmap §5 / §8. + +## Output Format +- Files changed +- Endpoints implemented (legacy → new) +- Security requirements from §9 covered +- Check results diff --git a/.github/agents/wgd-devops.agent.md b/.github/agents/wgd-devops.agent.md new file mode 100644 index 0000000..8e52505 --- /dev/null +++ b/.github/agents/wgd-devops.agent.md @@ -0,0 +1,30 @@ +--- +name: wgd-devops +description: "Use when working on WS-8 Packaging & release of the WGDashboard rewrite: Dockerfile, compose, entrypoint, gunicorn, install/start/stop script replacing wgd.sh, systemd unit, upgrade guide." +tools: [read, edit, search, execute, todo, agent] +agents: [wgd-legacy-researcher, wgd-reviewer] +handoffs: + - label: Review packaging + agent: wgd-reviewer + prompt: Review the WS-8 packaging changes against docs/roadmap.md. + send: false +--- +You own **WS-8 Packaging & release** in [docs/roadmap.md](../../docs/roadmap.md) §7. + +## Constraints +- DO NOT push images, tags or branches. +- DO NOT use `sudo` or change the host system; test in containers. +- Shell scripts: `set -euo pipefail`, quoted variables, readable named functions. +- DO NOT edit `reference/`. + +## Approach +1. Read [AGENTS.md](../../AGENTS.md) and the WS-8 section. +2. Ask `wgd-legacy-researcher` what `reference/src/wgd.sh`, `reference/docker/entrypoint.sh` and `wg-dashboard.service` do. +3. Align `docker/` with `create_app()` + gunicorn, config path, volumes, `/healthz` healthcheck, and the legacy importer on first start. +4. Write the replacement install script and systemd unit. +5. Verify a fresh install and a legacy upgrade in Docker. + +## Output Format +- Files changed +- Build / run commands used and results +- Remaining manual steps diff --git a/.github/agents/wgd-features.agent.md b/.github/agents/wgd-features.agent.md new file mode 100644 index 0000000..f6f475a --- /dev/null +++ b/.github/agents/wgd-features.agent.md @@ -0,0 +1,33 @@ +--- +name: wgd-features +description: "Use when working on WS-3 Scheduler & tracking or WS-4 Dashboard features of the WGDashboard rewrite: background scheduler, peer stats, traffic/endpoint tracking, peer jobs, backups/restore, config templates, share links, email, webhooks, ping/traceroute, plugins, system status, dashboard settings, locale." +tools: [read, edit, search, execute, todo, agent] +agents: [wgd-legacy-researcher, wgd-reviewer] +argument-hint: "Workstream or feature, e.g. 'WS-3' or 'WS-4 webhooks'" +handoffs: + - label: Review feature work + agent: wgd-reviewer + prompt: Review the WS-3 / WS-4 changes against docs/roadmap.md. + send: false +--- +You own **WS-3 Scheduler & tracking** and **WS-4 Dashboard features** in [docs/roadmap.md](../../docs/roadmap.md) §7. + +## Constraints +- DO NOT modify `src/modules/wireguard/*` internals; use its service functions. Report missing functions instead. +- DO NOT make outbound network calls in tests; mock SMTP, webhooks, geolocation, GitHub. +- Third-party geolocation and plugins are opt-in and disabled by default. +- DO NOT edit `reference/`. + +## Approach +1. Read [AGENTS.md](../../AGENTS.md), roadmap §2–§5, §9 and your workstream section. +2. Ask `wgd-legacy-researcher` for legacy behaviour (intervals, job operators/actions, backup layout, webhook payloads, email templates). +3. Scheduler: one scheduler per process, injectable clock, clean shutdown. +4. Each feature: model + migration → service in `features/` → routes → tests. +5. Security: path traversal tests on backups, SSRF guard on webhooks, rate limit on share links. +6. Run lint + tests until green; update roadmap §5 / §8. + +## Output Format +- Files changed (grouped by feature) +- Endpoints implemented (legacy → new) +- Check results +- Behaviour differences from legacy diff --git a/.github/agents/wgd-foundation.agent.md b/.github/agents/wgd-foundation.agent.md new file mode 100644 index 0000000..dccf988 --- /dev/null +++ b/.github/agents/wgd-foundation.agent.md @@ -0,0 +1,32 @@ +--- +name: wgd-foundation +description: "Use when working on WS-0 Foundation of the WGDashboard rewrite: fixing known issues in src/, lint/type tooling (ruff, pyright, eslint, prettier, pre-commit), pytest/vitest setup, CI, Alembic setup, config key unification, persistent secret key, create_app factory." +tools: [read, edit, search, execute, todo, agent] +agents: [wgd-legacy-researcher, wgd-reviewer] +handoffs: + - label: Review WS-0 + agent: wgd-reviewer + prompt: Review the WS-0 Foundation changes against docs/roadmap.md. + send: false +--- +You own **WS-0 Foundation** in [docs/roadmap.md](../../docs/roadmap.md) §7. + +## Constraints +- DO NOT implement WireGuard, peer, feature, auth-extension or frontend-feature work (other workstreams). +- DO NOT edit `reference/`. +- ONLY change what WS-0 lists, plus the issues in roadmap §6 assigned to WS-0. + +## Approach +1. Read [AGENTS.md](../../AGENTS.md), roadmap §1–§4, §6 and the WS-0 section. +2. Fix roadmap §6 issues first, each with a regression test. +3. Add tooling (`pyproject.toml`, `.pre-commit-config.yaml`, ESLint/Prettier/Vitest in both web apps, GitHub Actions). +4. Introduce `create_app()`, persistent secret key, unified config keys + `config/legacy_keys.py`. +5. Set up Alembic and convert models to SQLAlchemy 2.0 typed style; generate the first migration. +6. Run lint + tests until green. +7. Update roadmap §5 / §6 / §8 statuses. + +## Output Format +- Files changed (grouped) +- Issues from §6 fixed +- Check results (lint, type check, tests) +- Anything left open or blocked diff --git a/.github/agents/wgd-frontend.agent.md b/.github/agents/wgd-frontend.agent.md new file mode 100644 index 0000000..b6fb848 --- /dev/null +++ b/.github/agents/wgd-frontend.agent.md @@ -0,0 +1,33 @@ +--- +name: wgd-frontend +description: "Use when working on WS-9 Frontend shared layer, WS-10 Admin UI parity or WS-11 Client UI parity of the WGDashboard rewrite: Vue 3 Composition API, Pinia stores, shared API client, locale helper, porting legacy components one-to-one." +tools: [read, edit, search, execute, todo, agent] +agents: [wgd-legacy-researcher, wgd-reviewer] +argument-hint: "Workstream or view, e.g. 'WS-9' or 'WS-10 peerList'" +handoffs: + - label: Review frontend work + agent: wgd-reviewer + prompt: Review the frontend changes against docs/roadmap.md and .github/instructions/vue-style.instructions.md. + send: false +--- +You own **WS-9**, **WS-10** and **WS-11** in [docs/roadmap.md](../../docs/roadmap.md) §7. + +## Constraints +- DO NOT change backend code. If an endpoint is missing or wrong, report it. +- DO NOT call `fetch`/`axios` in components; only via `src/web/shared` API modules. +- Only wire a view to endpoints whose status in roadmap §5 is `done`. +- Keep component names and folder structure aligned with `reference/src/static/app` and `reference/src/static/client`. +- DO NOT edit `reference/`. + +## Approach +1. Read [AGENTS.md](../../AGENTS.md), `.github/instructions/vue-style.instructions.md`, roadmap §5 and your workstream section. +2. WS-9 first: shared HTTP client, per-domain API modules matching §5, locale helper, shared inputs, Vitest tests. +3. For each legacy component: ask `wgd-legacy-researcher` what it does, then rewrite it in ` + + +``` diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml new file mode 100644 index 0000000..966bff2 --- /dev/null +++ b/.github/workflows/backend.yml @@ -0,0 +1,38 @@ +name: Backend checks + +on: + push: + pull_request: + +jobs: + python: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: wgdashboard + POSTGRES_PASSWORD: wgdashboard + POSTGRES_DB: wgdashboard + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U wgdashboard -d wgdashboard" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + cache: pip + cache-dependency-path: src/requirements.txt + - run: python -m venv .venv + - run: .venv/bin/python -m pip install -r src/requirements.txt pytest pyright ruff + - run: .venv/bin/ruff check + - run: .venv/bin/pyright + - run: .venv/bin/pytest + - run: .venv/bin/alembic upgrade head + env: + WGDASHBOARD_DATABASE_URL: postgresql+psycopg://wgdashboard:wgdashboard@localhost:5432/wgdashboard diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c4fa4bc --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,47 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + python: + name: Python lint and tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + - name: Install Python dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -r src/requirements.txt pytest ruff + - name: Lint Python + run: ruff check src + - name: Run Python tests + run: pytest -q + + web: + name: ${{ matrix.app }} lint and tests + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + app: [admin, client] + defaults: + run: + working-directory: src/web/${{ matrix.app }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "26" + cache: npm + cache-dependency-path: src/web/${{ matrix.app }}/package-lock.json + - run: npm ci + - run: npm run lint + - run: npm test diff --git a/.gitignore b/.gitignore index a395b4d..f03fee9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ - +reference/ *.db dist +/src/secret_key # Byte-compiled / optimized / DLL files __pycache__/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..e1ac547 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,50 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + + - repo: https://github.com/pre-commit/mirrors-prettier + rev: v3.5.3 + hooks: + - id: prettier + files: ^src/web/.*\.(css|html|js|json|md|ts|vue|yaml|yml)$ + + - repo: local + hooks: + - id: ruff + name: ruff + entry: ruff check + language: system + types: [python] + - id: pyright + name: pyright + entry: pyright + language: system + pass_filenames: false + - id: admin-eslint + name: admin ESLint + entry: npm --prefix src/web/admin run lint + language: system + pass_filenames: false + files: ^src/web/admin/ + - id: admin-vitest + name: admin Vitest + entry: npm --prefix src/web/admin test + language: system + pass_filenames: false + files: ^src/web/admin/ + - id: client-eslint + name: client ESLint + entry: npm --prefix src/web/client run lint + language: system + pass_filenames: false + files: ^src/web/client/ + - id: client-vitest + name: client Vitest + entry: npm --prefix src/web/client test + language: system + pass_filenames: false + files: ^src/web/client/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ba36b1b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,40 @@ +# WGDashboard Rewrite – Agent Rules + +These rules apply to every agent and contributor working in this repository. + +## Project + +- `reference/` is the **legacy** WGDashboard. It is read-only: never edit, move or format anything in it. +- `src/` is the rewrite (Flask backend + `src/web/admin` and `src/web/client` Vue apps). +- [docs/roadmap.md](docs/roadmap.md) is the source of truth: architecture (§3), conventions (§4), + endpoint mapping (§5), known issues (§6), workstreams (§7), parity checklist (§8), + security requirements (§9) and open decisions (§10). +- Role agents live in [.github/agents/](.github/agents/). Coding style rules live in + [.github/instructions/](.github/instructions/) and in [GUIDELINES.md](GUIDELINES.md). + +## Always + +1. Readability is the top priority. More lines of clear code beats fewer lines of clever code. +2. Re-implement legacy behaviour; never copy legacy code style. +3. Stay inside the scope of your workstream. If something outside it is broken, report it instead of fixing it. +4. Check a workstream's *Depends on* list in the roadmap before starting it. +5. Follow the **recommended default** of any decision in roadmap §10 that is still `open`. +6. Ship tests with every change (pytest for backend, Vitest for frontend). +7. Ship an Alembic migration with every schema change. +8. After implementing a route or feature, update its status in roadmap §5 and §8. + +## Never + +- Use `shell=True`, or call `wg`/`awg`/`wg-quick`/`awg-quick`/`ip`/`iptables` outside `src/modules/wireguard/cli.py`. +- Build SQL with string formatting. +- Log passwords, private keys, TOTP secrets, API keys or tokens. +- Add files to `reference/`. + +## Layering + +``` +routes/* -> parse + validate request (pydantic), call one service, return make_resp_obj +services -> business logic +database/* -> ORM models and queries +wireguard/cli.py -> the only place that runs subprocesses +``` diff --git a/GUIDELINES.md b/GUIDELINES.md index 35cb3bb..474328c 100644 --- a/GUIDELINES.md +++ b/GUIDELINES.md @@ -1,6 +1,9 @@ # WGDashboard Coding Guidelines -## Rules: +## Rules -- Utility functions should ALWAYS use DEBUG statements. +Follow the readability, typing, logging, SQLAlchemy, and layering conventions in +[docs/roadmap.md](docs/roadmap.md) §2. + +- Utility functions must log at DEBUG; services log state changes at INFO and failures at ERROR. - Code as verbose as possible and where reason allows it. \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..d18d0a3 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,39 @@ +[alembic] +script_location = %(here)s/src/modules/database/alembic +prepend_sys_path = %(here)s/src +path_separator = os +sqlalchemy.url = + +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..f28c3ad --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,721 @@ +# WGDashboard Rewrite – Roadmap + +This document is the single source of truth for the rewrite. It is written so that an +agent (or contributor) can pick up **one workstream** and work on it independently. + +- Legacy code (read-only reference): `reference/` +- New code: `src/` (backend + `src/web/` frontends), `docker/` +- Goal: full feature parity with legacy, with an (almost) one-to-one Vue frontend, on a + modern, readable, tested and secure codebase. + +--- + +## 0. How to use this document (for agents) + +1. Read **§1 Ground rules**, **§2 Coding style** and **§3 Architecture** – they apply to every workstream. +2. Pick a workstream from **§7 Workstreams**. Check its *Depends on* list is done. +3. Use the *Legacy reference* files only to understand behaviour. **Do not copy legacy code + style** – re-implement following §2. +4. Satisfy every item in *Acceptance criteria* before marking the workstream done. +5. Update **§8 Parity checklist** and the endpoint table in **§5** when you finish. +6. Never modify anything inside `reference/`. + +Shared agent rules live in [AGENTS.md](../AGENTS.md), style rules in +[.github/instructions/](../.github/instructions/) and role agents in +[.github/agents/](../.github/agents/): + +| Agent | Workstreams | +|---|---| +| `wgd-orchestrator` | coordinates all, delegates, updates statuses | +| `wgd-legacy-researcher` | read-only legacy behaviour lookups | +| `wgd-reviewer` | read-only review + lint/tests | +| `wgd-foundation` | WS-0 | +| `wgd-wireguard` | WS-1, WS-2 | +| `wgd-features` | WS-3, WS-4 | +| `wgd-auth` | WS-5, WS-6 | +| `wgd-migration` | WS-7 | +| `wgd-devops` | WS-8 | +| `wgd-frontend` | WS-9, WS-10, WS-11 | + +--- + +## 1. Ground rules + +- Readability is the top priority. More lines of clear code beats fewer lines of clever code. +- Routes are thin; business logic lives in services; SQL lives in the database layer; + subprocess calls live only in `src/modules/wireguard/cli.py`. +- Every new backend feature ships with pytest tests; every new frontend store/composable + ships with Vitest tests. +- Every schema change ships with an Alembic migration. +- No secrets in logs. No `shell=True`. No raw SQL string formatting. +- Keep the existing response envelope (`make_resp_obj`, see §4.1). + +--- + +## 2. Coding style (mandatory) + +The legacy codebase often uses compact, dense constructs. The rewrite deliberately does +the opposite. + +### 2.1 Before / after + +Legacy (`reference/src/modules/WireguardConfiguration.py` ~L915): +```python +"Total": sum(list(map(lambda x: x.cumu_data + x.total_data, self.Peers))), +"ConnectedPeers": len(list(filter(lambda x: x.status == "running", self.Peers))), +``` + +Rewrite: +```python +total_data_usage = 0.0 +connected_peer_count = 0 + +for peer in peers: + total_data_usage += peer.cumulative_data + peer.total_data + + if peer.status == PeerStatus.RUNNING: + connected_peer_count += 1 +``` + +Legacy (`WireguardConfiguration.py` ~L1170): `list(islice(filter(lambda ip: ..., map(lambda iph: ..., network.hosts())), threshold))` + +Rewrite: a named helper `find_available_addresses(network, used_addresses, limit)` with a +plain `for` loop and an early `break`. + +### 2.2 Python rules + +1. No `lambda`, `map()` or `filter()`. Use `for` loops, or a single-level comprehension with at most one simple `if`. +2. No nested ternaries; a ternary must fit comfortably on one short line. +3. One action per line. Use descriptively named intermediate variables instead of chained calls. +4. Early returns over nested `if/else`. Max ~3 indentation levels inside a function body. +5. Descriptive names: `peer`, `interface_name`, `allowed_ips` – never `p`, `ca`, `iph`, `x`. +6. Type hints on **every** parameter and return value. SQLAlchemy models use 2.0 `Mapped[...]` / `mapped_column`. +7. Error convention: functions return `tuple[bool, value]` (as already used in `config.py`). Be consistent. *(See decision D5.)* +8. Logging (from `GUIDELINES.md`): utility functions ALWAYS log at DEBUG. Services log INFO on state changes and ERROR on failure. Use `import logging as log` as existing modules do. +9. Never `subprocess` with `shell=True`. Arguments are lists. Only `wireguard/cli.py` may call `wg`/`awg`/`wg-quick`/`awg-quick`/`ip`/`iptables`. +10. Function ≲ 50 lines, file ≲ 400 lines. Split by responsibility. +11. Enums / constants instead of magic strings (`PeerStatus`, `Protocol`, `JobAction`, `JobOperator`). +12. Keep existing conventions: `#!/bin/env python3` header, snake_case functions, classes grouping `@staticmethod`s where already used, `'''docstring'''` one-liners. + +### 2.3 Vue rules + +1. `