feat: try to build out
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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 `<script setup>`, splitting large components into composables.
|
||||||
|
4. Follow the WS-10 port order in the roadmap.
|
||||||
|
5. Run `npm run lint`, Vitest and builds for both apps; update roadmap §8.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
- Components ported (legacy path → new path)
|
||||||
|
- Composables / stores added
|
||||||
|
- Endpoints used
|
||||||
|
- Check results
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
---
|
||||||
|
name: wgd-legacy-researcher
|
||||||
|
description: "Use when you need to know how the legacy WGDashboard (reference/ folder) behaves: endpoint request/response shapes, DB tables, wg/awg commands, background threads, Vue component behaviour. Read-only."
|
||||||
|
tools: [read, search]
|
||||||
|
user-invocable: true
|
||||||
|
argument-hint: "Legacy behaviour to explain, e.g. 'how does restrictPeers work'"
|
||||||
|
---
|
||||||
|
You are a read-only expert on the legacy WGDashboard code in `reference/`.
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
- DO NOT edit any file.
|
||||||
|
- DO NOT propose code in the legacy style; describe **behaviour**, not implementation tricks.
|
||||||
|
- ONLY answer about what the legacy code does, with file paths and line numbers.
|
||||||
|
|
||||||
|
## Approach
|
||||||
|
1. Locate the relevant code in `reference/src/dashboard.py`, `reference/src/client.py`, `reference/src/modules/*` or `reference/src/static/**`.
|
||||||
|
2. Trace the full flow: route → module → DB / subprocess → response.
|
||||||
|
3. Note edge cases, validation, side effects (files written, commands run, webhooks fired) and security issues.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
- **Behaviour summary** (bullet list, plain language)
|
||||||
|
- **Inputs / outputs** (request fields, response shape, status codes)
|
||||||
|
- **Side effects** (DB tables, files, commands)
|
||||||
|
- **Edge cases & security notes**
|
||||||
|
- **Sources** (file paths with line numbers)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
---
|
||||||
|
name: wgd-migration
|
||||||
|
description: "Use when working on WS-7 Legacy importer of the WGDashboard rewrite: importing legacy wg-dashboard.ini and legacy SQLite/Postgres/MySQL databases (per-configuration tables) into the new normalized schema."
|
||||||
|
tools: [read, edit, search, execute, todo, agent]
|
||||||
|
agents: [wgd-legacy-researcher, wgd-reviewer]
|
||||||
|
handoffs:
|
||||||
|
- label: Review importer
|
||||||
|
agent: wgd-reviewer
|
||||||
|
prompt: Review the WS-7 legacy importer against docs/roadmap.md.
|
||||||
|
send: false
|
||||||
|
---
|
||||||
|
You own **WS-7 Legacy importer** in [docs/roadmap.md](../../docs/roadmap.md) §7.
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
- DO NOT modify legacy databases or ini files; read only.
|
||||||
|
- DO NOT change the new schema; if a mapping is impossible, report it to the owner of that model.
|
||||||
|
- The importer must be idempotent and support `--dry-run`.
|
||||||
|
- DO NOT edit `reference/`.
|
||||||
|
|
||||||
|
## Approach
|
||||||
|
1. Read [AGENTS.md](../../AGENTS.md), roadmap §3.2 (schema mapping) and §4.4 (config keys).
|
||||||
|
2. Ask `wgd-legacy-researcher` for every legacy table definition and ini key.
|
||||||
|
3. Build `tools/import_legacy.py` as small, named steps (one function per entity type).
|
||||||
|
4. Create fixture legacy databases in `tests/fixtures/` and test row counts and spot values.
|
||||||
|
5. Run lint + tests until green; update roadmap §8.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
- Mapping table (legacy table/key → new table/column)
|
||||||
|
- Unmappable data and how it is handled
|
||||||
|
- Check results
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
---
|
||||||
|
name: wgd-orchestrator
|
||||||
|
description: "Use when coordinating the WGDashboard rewrite: choosing the next workstream, checking dependencies in docs/roadmap.md, delegating to role agents, tracking parity progress."
|
||||||
|
tools: [read, search, edit, agent, todo]
|
||||||
|
agents: [wgd-legacy-researcher, wgd-foundation, wgd-wireguard, wgd-features, wgd-auth, wgd-migration, wgd-devops, wgd-frontend, wgd-reviewer]
|
||||||
|
argument-hint: "What to coordinate, e.g. 'start next available workstream' or 'status report'"
|
||||||
|
---
|
||||||
|
You coordinate the WGDashboard rewrite. You do not write application code yourself.
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
- DO NOT edit anything except `docs/roadmap.md` status columns and checklists.
|
||||||
|
- DO NOT edit `reference/`.
|
||||||
|
- ONLY start a workstream when every item in its *Depends on* list is done.
|
||||||
|
|
||||||
|
## Approach
|
||||||
|
1. Read [AGENTS.md](../../AGENTS.md) and [docs/roadmap.md](../../docs/roadmap.md) (§5, §7, §8, §10).
|
||||||
|
2. Determine which workstreams are done, in progress and unblocked.
|
||||||
|
3. Delegate to the role agent that owns the workstream:
|
||||||
|
| Workstream | Agent |
|
||||||
|
|---|---|
|
||||||
|
| WS-0 | wgd-foundation |
|
||||||
|
| WS-1, WS-2 | wgd-wireguard |
|
||||||
|
| WS-3, WS-4 | wgd-features |
|
||||||
|
| WS-5, WS-6 | wgd-auth |
|
||||||
|
| WS-7 | wgd-migration |
|
||||||
|
| WS-8 | wgd-devops |
|
||||||
|
| WS-9, WS-10, WS-11 | wgd-frontend |
|
||||||
|
4. After an implementer reports back, delegate a review to `wgd-reviewer`.
|
||||||
|
5. Update roadmap status only after the review passes.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
- Workstream status table (done / in progress / blocked / available)
|
||||||
|
- What was delegated, to whom, and the result
|
||||||
|
- Next recommended step
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
name: wgd-reviewer
|
||||||
|
description: "Use when reviewing changes in the WGDashboard rewrite for readability-first style, layering, security (roadmap §9), tests and roadmap acceptance criteria. Runs linters and tests, does not edit."
|
||||||
|
tools: [read, search, execute]
|
||||||
|
argument-hint: "Workstream or files to review, e.g. 'WS-1' or 'src/modules/wireguard'"
|
||||||
|
---
|
||||||
|
You review changes in the WGDashboard rewrite. You never fix code yourself; you report findings.
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
- DO NOT edit files.
|
||||||
|
- DO NOT run destructive commands (no `git reset`, `git push`, `rm`).
|
||||||
|
- ONLY review against: [AGENTS.md](../../AGENTS.md), `.github/instructions/*.instructions.md`, [GUIDELINES.md](../../GUIDELINES.md) and the workstream in [docs/roadmap.md](../../docs/roadmap.md).
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
1. **Readability**: no `lambda`/`map`/`filter`, no nested ternaries, descriptive names, early returns, function/file size limits, logic out of Vue templates.
|
||||||
|
2. **Typing & logging**: type hints everywhere; DEBUG logs in utilities; no secrets in logs.
|
||||||
|
3. **Layering**: routes thin, subprocess only in `wireguard/cli.py`, no SQL string formatting.
|
||||||
|
4. **Security**: roadmap §9 items for this workstream; input validation; path traversal; `shell=True`.
|
||||||
|
5. **Tests**: present, meaningful, passing. Alembic migration present for schema changes.
|
||||||
|
6. **Acceptance criteria**: every item of the workstream in roadmap §7.
|
||||||
|
7. **Roadmap**: §5 / §8 statuses updated.
|
||||||
|
8. Run available checks (e.g. `ruff check src tests`, `pyright`, `pytest`, `npm run lint`, `npx vitest run`) and include results.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
- **Verdict**: pass / changes required
|
||||||
|
- **Blocking issues** (file + line + rule violated + suggested direction)
|
||||||
|
- **Non-blocking suggestions**
|
||||||
|
- **Check results** (command → pass/fail summary)
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
---
|
||||||
|
name: wgd-wireguard
|
||||||
|
description: "Use when working on WS-1 WireGuard core or WS-2 Peers of the WGDashboard rewrite: .conf parsing, wg/awg CLI wrapper, key generation, IP allocation, AmneziaWG, interface CRUD/toggle/raw file, peer CRUD/restrict/allow/download/QR."
|
||||||
|
tools: [read, edit, search, execute, todo, agent]
|
||||||
|
agents: [wgd-legacy-researcher, wgd-reviewer]
|
||||||
|
argument-hint: "Workstream, e.g. 'WS-1' or 'WS-2'"
|
||||||
|
handoffs:
|
||||||
|
- label: Review WireGuard work
|
||||||
|
agent: wgd-reviewer
|
||||||
|
prompt: Review the WS-1 / WS-2 changes against docs/roadmap.md.
|
||||||
|
send: false
|
||||||
|
---
|
||||||
|
You own **WS-1 WireGuard core** and **WS-2 Peers** in [docs/roadmap.md](../../docs/roadmap.md) §7.
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
- DO NOT start WS-2 before WS-1 acceptance criteria pass.
|
||||||
|
- DO NOT call subprocesses anywhere except `src/modules/wireguard/cli.py`; never `shell=True`.
|
||||||
|
- DO NOT run real `wg`/`awg` commands that change system state; mock `cli.py` in tests.
|
||||||
|
- 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 exact legacy behaviour (e.g. `WireguardConfiguration.py`, `Peer.py`, `AmneziaConfiguration.py`) before implementing each feature.
|
||||||
|
3. Build bottom-up: `conf_parser.py` → `keys.py` → `cli.py` → `ip_allocation.py` → services → routes.
|
||||||
|
4. Add fixture `.conf` files in `tests/fixtures/` and golden-file tests against legacy output.
|
||||||
|
5. Add Alembic migrations for new models.
|
||||||
|
6. Run lint + tests until green; update roadmap §5 / §8.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
- Files changed (grouped by module)
|
||||||
|
- Endpoints implemented (legacy → new)
|
||||||
|
- Check results
|
||||||
|
- Open questions / behaviour differences from legacy
|
||||||
@@ -11,12 +11,12 @@ updates:
|
|||||||
interval: "weekly"
|
interval: "weekly"
|
||||||
|
|
||||||
- package-ecosystem: "npm"
|
- package-ecosystem: "npm"
|
||||||
directory: "/src/static/admin"
|
directory: "/src/web/admin"
|
||||||
schedule:
|
schedule:
|
||||||
interval: "weekly"
|
interval: "weekly"
|
||||||
|
|
||||||
- package-ecosystem: "npm"
|
- package-ecosystem: "npm"
|
||||||
directory: "/src/static/client"
|
directory: "/src/web/client"
|
||||||
schedule:
|
schedule:
|
||||||
interval: "weekly"
|
interval: "weekly"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
---
|
||||||
|
description: "Use when writing or editing Python in the WGDashboard rewrite: readability-first coding style, naming, typing, logging, error handling, subprocess and SQLAlchemy rules."
|
||||||
|
applyTo: "src/**/*.py, tests/**/*.py, tools/**/*.py"
|
||||||
|
---
|
||||||
|
# Python style – readability first
|
||||||
|
|
||||||
|
The legacy code (`reference/`) is compact and dense. The rewrite deliberately is not.
|
||||||
|
|
||||||
|
## 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 on one short line.
|
||||||
|
3. One action per line. Store intermediate results in descriptively named variables instead of chaining calls.
|
||||||
|
4. Return early instead of nesting `if/else`. Max ~3 indentation levels inside a function body.
|
||||||
|
5. Descriptive names: `peer`, `interface_name`, `allowed_ips` – never `p`, `x`, `ca`, `iph`.
|
||||||
|
6. Type hints on every parameter and return value.
|
||||||
|
7. Functions return `tuple[bool, value]` to signal success (as in `src/modules/config/config.py`). Do not mix with raising for control flow.
|
||||||
|
8. Utility functions ALWAYS log at DEBUG. Services log INFO on state changes and ERROR on failure. Use `import logging as log`.
|
||||||
|
9. Functions ≲ 50 lines, files ≲ 400 lines. Split by responsibility.
|
||||||
|
10. Enums or module constants instead of magic strings (`PeerStatus`, `Protocol`, `JobAction`).
|
||||||
|
11. Subprocess: list arguments only, never `shell=True`, always a `timeout`, only inside `src/modules/wireguard/cli.py`.
|
||||||
|
12. SQLAlchemy 2.0 typed models (`Mapped[...]`, `mapped_column`). No SQL string formatting.
|
||||||
|
13. Request bodies are validated with pydantic models; respond with `make_resp_obj(status, message, data, http_code)`.
|
||||||
|
14. Keep existing conventions: `#!/bin/env python3` header, snake_case, `'''one-line docstrings'''`.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
Legacy:
|
||||||
|
```python
|
||||||
|
"ConnectedPeers": len(list(filter(lambda x: x.status == "running", self.Peers))),
|
||||||
|
```
|
||||||
|
|
||||||
|
Rewrite:
|
||||||
|
```python
|
||||||
|
connected_peer_count = 0
|
||||||
|
|
||||||
|
for peer in peers:
|
||||||
|
if peer.status == PeerStatus.RUNNING:
|
||||||
|
connected_peer_count += 1
|
||||||
|
```
|
||||||
|
|
||||||
|
Helper style:
|
||||||
|
```python
|
||||||
|
def find_available_addresses(network: ipaddress.IPv4Network, used_addresses: set[str], limit: int) -> list[str]:
|
||||||
|
'''Return up to `limit` host addresses in `network` that are not used yet.'''
|
||||||
|
log.debug(f"searching available addresses in {network} (limit {limit})")
|
||||||
|
|
||||||
|
available_addresses: list[str] = []
|
||||||
|
|
||||||
|
for host in network.hosts():
|
||||||
|
address = str(host)
|
||||||
|
|
||||||
|
if address in used_addresses:
|
||||||
|
continue
|
||||||
|
|
||||||
|
available_addresses.append(address)
|
||||||
|
|
||||||
|
if len(available_addresses) >= limit:
|
||||||
|
break
|
||||||
|
|
||||||
|
log.debug(f"found {len(available_addresses)} available addresses")
|
||||||
|
return available_addresses
|
||||||
|
```
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
---
|
||||||
|
description: "Use when writing or editing Vue, JavaScript or TypeScript in the WGDashboard admin/client apps: Composition API, component size, API layer, stores, locale usage."
|
||||||
|
applyTo: "src/web/**/*.vue, src/web/**/*.js, src/web/**/*.ts"
|
||||||
|
---
|
||||||
|
# Vue style – readability first
|
||||||
|
|
||||||
|
1. `<script setup>` Composition API only. Pinia stores use the setup syntax of `defineStore`.
|
||||||
|
2. Templates contain no logic beyond property access. Everything else becomes a named `computed`.
|
||||||
|
3. Components ≲ 250 lines. Extract composables (`usePeerSorting`, `usePeerFilter`, `usePeerModals`).
|
||||||
|
4. All HTTP goes through the shared API layer in `src/web/shared` (e.g. `api.peers.update(...)`). No raw `fetch`/`axios` or URL strings in components.
|
||||||
|
5. `async/await` only. No callback-style helpers.
|
||||||
|
6. Explicit `defineProps` (with defaults) and `defineEmits`.
|
||||||
|
7. Descriptive names; no single-letter variables outside trivial `v-for` indexes.
|
||||||
|
8. Keep component **names and folder structure** aligned with `reference/src/static/app` and `reference/src/static/client`, so features can be compared one-to-one.
|
||||||
|
9. User-facing text goes through the locale helper with English fallback.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
Legacy pattern:
|
||||||
|
```vue
|
||||||
|
<span>{{ peers.filter(p => p.status === 'running').length }} / {{ peers.length }}</span>
|
||||||
|
```
|
||||||
|
|
||||||
|
Rewrite:
|
||||||
|
```vue
|
||||||
|
<script setup>
|
||||||
|
import { computed } from 'vue'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
peers: { type: Array, default: () => [] },
|
||||||
|
})
|
||||||
|
|
||||||
|
const connectedPeerCount = computed(() => {
|
||||||
|
let count = 0
|
||||||
|
|
||||||
|
for (const peer of props.peers) {
|
||||||
|
if (peer.status === 'running') {
|
||||||
|
count += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return count
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<span>{{ connectedPeerCount }} / {{ props.peers.length }}</span>
|
||||||
|
</template>
|
||||||
|
```
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
|
reference/
|
||||||
*.db
|
*.db
|
||||||
dist
|
dist
|
||||||
|
/src/secret_key
|
||||||
|
|
||||||
# Byte-compiled / optimized / DLL files
|
# Byte-compiled / optimized / DLL files
|
||||||
__pycache__/
|
__pycache__/
|
||||||
|
|||||||
@@ -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/
|
||||||
@@ -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
|
||||||
|
```
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
# WGDashboard Coding Guidelines
|
# 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.
|
- Code as verbose as possible and where reason allows it.
|
||||||
@@ -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
|
||||||
@@ -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. `<script setup>` Composition API only. Stores use `defineStore` setup syntax.
|
||||||
|
2. Templates contain no logic beyond property access; anything else becomes a named `computed`.
|
||||||
|
3. Component ≲ 250 lines. Extract composables (`usePeerSorting`, `usePeerFilter`, `usePeerModals`, …).
|
||||||
|
4. All HTTP goes through the shared API layer (`api.peers.update(...)`), never raw URLs in components.
|
||||||
|
5. `async/await` only – no callback-style fetch helpers.
|
||||||
|
6. Explicit `defineProps` (with defaults) and `defineEmits`.
|
||||||
|
7. Keep component **names and folder structure** aligned with legacy so features can be compared one-to-one.
|
||||||
|
|
||||||
|
### 2.4 Tooling (enforces the above)
|
||||||
|
|
||||||
|
- Python: `ruff` (enable `E731`, `C901` max 10, `PLR0912`, `PLR0915`, `SIM`, `N`, `ANN`), `pyright` (basic → strict).
|
||||||
|
- Frontend: `eslint-plugin-vue` (recommended) + `complexity`, `max-lines`, `max-depth`; `prettier`.
|
||||||
|
- `pre-commit` running all of the above; GitHub Actions CI running lint + tests.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Architecture
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
subgraph Web
|
||||||
|
A[Admin SPA - Vue 3] --> API
|
||||||
|
C[Client SPA - Vue 3] --> API
|
||||||
|
end
|
||||||
|
subgraph Backend
|
||||||
|
API[routes/* thin HTTP layer] --> SVC[services]
|
||||||
|
SVC --> REPO[database/* ORM models + queries]
|
||||||
|
SVC --> WG[wireguard/* cli + conf parser]
|
||||||
|
SCHED[scheduler/* background jobs] --> SVC
|
||||||
|
end
|
||||||
|
REPO --> DB[(SQLite / Postgres / MySQL)]
|
||||||
|
WG --> OS[wg / awg / wg-quick / iptables]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.1 Target backend layout
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
main.py
|
||||||
|
modules/
|
||||||
|
config/ config.py, config_utils.py, legacy_keys.py
|
||||||
|
database/ database.py, database_utils.py, functions.py
|
||||||
|
models/ (one file per domain)
|
||||||
|
alembic/ (migrations)
|
||||||
|
wireguard/ conf_parser.py, cli.py, keys.py, ip_allocation.py,
|
||||||
|
interface_service.py, peer_service.py, amnezia.py
|
||||||
|
auth/ admin_auth.py, api_keys.py, totp.py, oidc.py
|
||||||
|
clients/ client_accounts.py, client_assignments.py, password_reset.py
|
||||||
|
features/ peer_jobs.py, share_links.py, backups.py, webhooks.py, email.py,
|
||||||
|
config_templates.py, tracking.py, network_tools.py, plugins.py
|
||||||
|
scheduler/ scheduler.py, job_peer_stats.py, job_tracking.py, job_peer_jobs.py
|
||||||
|
routes/ response.py, locale.py, routes_utils.py, one routes_<domain>.py per domain
|
||||||
|
utilities/ logger.py, statistics.py, utilities.py
|
||||||
|
web/
|
||||||
|
shared/ api client, locale helper, types, common inputs (new)
|
||||||
|
admin/
|
||||||
|
client/
|
||||||
|
locales/
|
||||||
|
tests/
|
||||||
|
unit/ integration/ fixtures/ (sample .conf files, legacy DB dumps)
|
||||||
|
tools/
|
||||||
|
import_legacy.py
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Target database schema
|
||||||
|
|
||||||
|
Legacy creates **tables per WireGuard configuration** (`{name}`, `{name}_restrict_access`,
|
||||||
|
`{name}_deleted`, `{name}_transfer`, `{name}_endpoint_history`). The rewrite normalizes this:
|
||||||
|
|
||||||
|
| Table | Key columns | Replaces (legacy) |
|
||||||
|
|---|---|---|
|
||||||
|
| `interfaces` | id, name (unique), protocol (`wg`/`awg`), private_key, public_key, address, listen_port, mtu, dns, table, pre_up, post_up, pre_down, post_down, save_config, description, autostart | `.conf` metadata, `WireguardConfigurationInfo` |
|
||||||
|
| `interface_amnezia_params` | interface_id FK, jc, jmin, jmax, s1–s4, h1–h4, i1–i5, j1–j3, itime | Amnezia fields |
|
||||||
|
| `interface_overrides` | interface_id FK, dns, mtu, keepalive, endpoint, allowed_ips, listen_port | `OverridePeerSettings` |
|
||||||
|
| `peer_groups` | id, interface_id FK, name, color, icon | `PeerGroups` |
|
||||||
|
| `peers` | id, interface_id FK, public_key, private_key, preshared_key, name, allowed_ips, endpoint_allowed_ips, dns, mtu, keepalive, remote_endpoint, notes, status (`active`/`restricted`/`deleted`), latest_handshake, endpoint, total_rx/tx, cumulative_rx/tx, group_id | `{name}`, `{name}_restrict_access`, `{name}_deleted` |
|
||||||
|
| `peer_traffic_samples` | id, peer_id FK, rx, tx, cumulative_rx, cumulative_tx, sampled_at | `{name}_transfer` |
|
||||||
|
| `peer_endpoint_history` | id, peer_id FK, endpoint, first_seen, last_seen | `{name}_endpoint_history` |
|
||||||
|
| `peer_jobs` | id, peer_id FK, field, operator, value, action, created_at, expires_at | `PeerJobs` |
|
||||||
|
| `peer_job_logs` | id, job_id FK, status, message, logged_at | `PeerJobLog` |
|
||||||
|
| `peer_share_links` | id (token), peer_id FK, shared_at, expires_at | `PeerShareLinks` |
|
||||||
|
| `users` | id, username, password_hash, role, totp_enabled, totp_verified, totp_secret (encrypted), email | `[Account]` in ini |
|
||||||
|
| `api_keys` | id, key_hash, created_at, expires_at, description | `DashboardAPIKeys` |
|
||||||
|
| `clients` | id, email, password_hash, name, totp_secret, totp_verified, created_at, deleted_at | `DashboardClients`, `DashboardClientsInfo` |
|
||||||
|
| `clients_oidc` | id, client_id FK, issuer, subject | `DashboardOIDCClients` |
|
||||||
|
| `client_peer_assignments` | id, client_id FK, peer_id FK, assigned_at, unassigned_at | `DashboardClientsPeerAssignment` |
|
||||||
|
| `client_password_resets` | token, client_id FK, created_at, expires_at | `DashboardClientsPasswordResetLinks` |
|
||||||
|
| `webhooks` | id, url, content_type, headers JSON, verify_tls, actions JSON, active, notes, created_at | `DashboardWebHooks` |
|
||||||
|
| `webhook_deliveries` | id, webhook_id FK, started_at, ended_at, payload JSON, status, logs JSON | `DashboardWebHookSessions` |
|
||||||
|
| `config_templates` | id, subnet, listen_port_start, listen_port_end, notes | `NewConfigurationTemplates` |
|
||||||
|
| `audit_log` | id, logged_at, url, ip, status, message | `DashboardLog` |
|
||||||
|
|
||||||
|
The `.conf` file on disk stays the source of truth for what `wg-quick` runs; the DB stores
|
||||||
|
metadata and history. Sync rules are owned by WS-1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Conventions
|
||||||
|
|
||||||
|
### 4.1 Response envelope (already in `src/modules/routes/response.py`)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "status": true, "message": "optional", "data": {} }
|
||||||
|
```
|
||||||
|
Built with `make_resp_obj(status, message, data, http_code)`.
|
||||||
|
|
||||||
|
### 4.2 Request validation
|
||||||
|
|
||||||
|
Every request body/query is parsed by a **pydantic** model defined next to the route.
|
||||||
|
Invalid input → `make_resp_obj(False, "<field>: <reason>", {}, 400)`.
|
||||||
|
|
||||||
|
### 4.3 Authentication
|
||||||
|
|
||||||
|
- Admin: Flask signed session (`session['role'] == 'admin'`), persistent `secret_key`, cookies `HttpOnly`, `SameSite=Lax`, `Secure` when served over HTTPS.
|
||||||
|
- API key header: `wgdashboard-apikey` (legacy used `wg-dashboard-apikey` – accept both during compatibility period).
|
||||||
|
- Client portal: separate session role `client`.
|
||||||
|
- Public routes are declared explicitly per blueprint (whitelist must match real route paths).
|
||||||
|
|
||||||
|
### 4.4 Config file
|
||||||
|
|
||||||
|
INI, searched in `./config.ini`, `~/.config/wgdashboard/config.ini`, `/etc/wgdashboard/config.ini`.
|
||||||
|
Sections lower-cased. A mapping from legacy `wg-dashboard.ini` keys to new keys lives in
|
||||||
|
`config/legacy_keys.py` (e.g. `[Server] auth_req` → `[server] authentication_required`,
|
||||||
|
`dashboard_api_key` → `wgdashboard_apikey`, `app_ip` → `hostname`, `app_port` → `port`).
|
||||||
|
Use **one** key name per setting everywhere in the code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Endpoint mapping (legacy → new)
|
||||||
|
|
||||||
|
Status: `todo` / `wip` / `done`. Update this table when you implement a route.
|
||||||
|
Public = no admin auth required.
|
||||||
|
WS-0 regression fixes cover the current legacy sign-in and authentication paths; their
|
||||||
|
mapping remains `wip` until the target routes in the New column are implemented.
|
||||||
|
|
||||||
|
### Auth & session
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/handshake` | GET `/api/handshake` | todo |
|
||||||
|
| GET `/api/validateAuthentication` | GET `/api/auth/validate` | wip |
|
||||||
|
| GET `/api/requireAuthentication` | GET `/api/auth/required` (public) | todo |
|
||||||
|
| POST `/api/authenticate` | POST `/api/auth` (public) | wip |
|
||||||
|
| GET `/api/signout` | POST `/api/auth/signout` | todo |
|
||||||
|
| GET `/api/oidc/providers` | GET `/api/auth/oidc/providers` (public) | todo |
|
||||||
|
| POST `/api/oidc/authenticate` | POST `/api/auth/oidc` (public) | todo |
|
||||||
|
| GET `/api/oidc/toggle` | PUT `/api/settings/oidc` | todo |
|
||||||
|
| GET `/api/oidc/status` | GET `/api/settings/oidc` | todo |
|
||||||
|
|
||||||
|
### Welcome / TOTP
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/isTotpEnabled` | GET `/api/dashboard/totp` (public) | wip |
|
||||||
|
| GET `/api/Welcome_GetTotpLink` | GET `/api/welcome/totplink` | done |
|
||||||
|
| POST `/api/Welcome_VerifyTotpLink` | POST `/api/welcome/verifytotplink` | done |
|
||||||
|
| POST `/api/Welcome_Finish` | POST `/api/welcome/finish` | done |
|
||||||
|
|
||||||
|
### Dashboard settings
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/getDashboardConfiguration` | GET `/api/dashboard/configuration` | wip |
|
||||||
|
| POST `/api/updateDashboardConfigurationItem` | PUT `/api/dashboard/configuration` | todo |
|
||||||
|
| GET `/api/getDashboardTheme` | GET `/api/dashboard/theme` (public) | wip |
|
||||||
|
| GET `/api/getDashboardVersion` | GET `/api/dashboard/version` (public) | wip |
|
||||||
|
| GET `/api/getDashboardUpdate` | GET `/api/dashboard/update` | wip |
|
||||||
|
| GET `/api/protocolsEnabled` | GET `/api/dashboard/protocols` | todo |
|
||||||
|
| GET `/api/systemStatus` | GET `/api/system/status` | wip |
|
||||||
|
| GET `/api/locale` | GET `/api/dashboard/locale` (public) | wip |
|
||||||
|
| GET `/api/locale/available` | GET `/api/dashboard/locale/available` | todo |
|
||||||
|
| POST `/api/locale/update` | PUT `/api/dashboard/locale` | todo |
|
||||||
|
|
||||||
|
### API keys
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/getDashboardAPIKeys` | GET `/api/apikeys` | todo |
|
||||||
|
| POST `/api/newDashboardAPIKey` | POST `/api/apikeys` | todo |
|
||||||
|
| POST `/api/deleteDashboardAPIKey` | DELETE `/api/apikeys/<id>` | todo |
|
||||||
|
|
||||||
|
### Interfaces (WireGuard configurations)
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/getWireguardConfigurations` | GET `/api/interfaces` | wip (stub) |
|
||||||
|
| POST `/api/addWireguardConfiguration` | POST `/api/interfaces` | todo |
|
||||||
|
| GET `/api/toggleWireguardConfiguration` | POST `/api/interfaces/<name>/toggle` | todo |
|
||||||
|
| POST `/api/updateWireguardConfiguration` | PUT `/api/interfaces/<name>` | todo |
|
||||||
|
| POST `/api/updateWireguardConfigurationInfo` | PUT `/api/interfaces/<name>/info` | todo |
|
||||||
|
| GET `/api/getWireguardConfigurationInfo` | GET `/api/interfaces/<name>` | todo |
|
||||||
|
| GET `/api/getWireguardConfigurationRawFile` | GET `/api/interfaces/<name>/raw` | todo |
|
||||||
|
| POST `/api/updateWireguardConfigurationRawFile` | PUT `/api/interfaces/<name>/raw` | todo |
|
||||||
|
| POST `/api/deleteWireguardConfiguration` | DELETE `/api/interfaces/<name>` | todo |
|
||||||
|
| POST `/api/renameWireguardConfiguration` | POST `/api/interfaces/<name>/rename` | todo |
|
||||||
|
| GET `/api/getWireguardConfigurationRealtimeTraffic` | GET `/api/interfaces/<name>/traffic/realtime` | todo |
|
||||||
|
| GET `/api/getAvailableIPs/<cfg>` | GET `/api/interfaces/<name>/available-ips` | todo |
|
||||||
|
| GET `/api/getNumberOfAvailableIPs/<cfg>` | GET `/api/interfaces/<name>/available-ips/count` | todo |
|
||||||
|
|
||||||
|
### Config templates
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/newConfigurationTemplates` | GET `/api/templates` | todo |
|
||||||
|
| GET `/api/newConfigurationTemplates/createTemplate` | POST `/api/templates` | todo |
|
||||||
|
| POST `/api/newConfigurationTemplates/updateTemplate` | PUT `/api/templates/<id>` | todo |
|
||||||
|
| POST `/api/newConfigurationTemplates/deleteTemplate` | DELETE `/api/templates/<id>` | todo |
|
||||||
|
|
||||||
|
### Peers
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| POST `/api/addPeers/<cfg>` | POST `/api/interfaces/<name>/peers` | todo |
|
||||||
|
| POST `/api/updatePeerSettings/<cfg>` | PUT `/api/interfaces/<name>/peers/<id>` | todo |
|
||||||
|
| POST `/api/deletePeers/<cfg>` | DELETE `/api/interfaces/<name>/peers` (body: ids) | todo |
|
||||||
|
| POST `/api/resetPeerData/<cfg>` | POST `/api/interfaces/<name>/peers/<id>/reset-data` | todo |
|
||||||
|
| POST `/api/restrictPeers/<cfg>` | POST `/api/interfaces/<name>/peers/restrict` | todo |
|
||||||
|
| POST `/api/allowAccessPeers/<cfg>` | POST `/api/interfaces/<name>/peers/allow` | todo |
|
||||||
|
| GET `/api/downloadPeer/<cfg>` | GET `/api/interfaces/<name>/peers/<id>/download` | todo |
|
||||||
|
| GET `/api/downloadAllPeers/<cfg>` | GET `/api/interfaces/<name>/peers/download` | todo |
|
||||||
|
|
||||||
|
### Tracking & history
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/getPeerHistoricalEndpoints` | GET `/api/interfaces/<name>/peers/<id>/endpoints` | todo |
|
||||||
|
| GET `/api/getPeerSessions` | GET `/api/interfaces/<name>/peers/<id>/sessions` | todo |
|
||||||
|
| GET `/api/getPeerTraffics` | GET `/api/interfaces/<name>/peers/<id>/traffic` | todo |
|
||||||
|
| GET `/api/getPeerTrackingTableCounts` | GET `/api/tracking/counts` | todo |
|
||||||
|
| GET `/api/downloadPeerTrackingTable` | GET `/api/tracking/<interface>/download` | todo |
|
||||||
|
| POST `/api/deletePeerTrackingTable` | DELETE `/api/tracking/<interface>` | todo |
|
||||||
|
|
||||||
|
### Share links
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| POST `/api/sharePeer/create` | POST `/api/share-links` | todo |
|
||||||
|
| POST `/api/sharePeer/update` | PUT `/api/share-links/<token>` | todo |
|
||||||
|
| GET `/api/sharePeer/get` | GET `/api/share-links/<token>` (public) | todo |
|
||||||
|
|
||||||
|
### Backups
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/getWireguardConfigurationBackup` | GET `/api/interfaces/<name>/backups` | todo |
|
||||||
|
| GET `/api/getAllWireguardConfigurationBackup` | GET `/api/backups` | todo |
|
||||||
|
| GET `/api/createWireguardConfigurationBackup` | POST `/api/interfaces/<name>/backups` | todo |
|
||||||
|
| POST `/api/deleteWireguardConfigurationBackup` | DELETE `/api/interfaces/<name>/backups/<file>` | todo |
|
||||||
|
| GET `/api/downloadWireguardConfigurationBackup` | GET `/api/interfaces/<name>/backups/<file>` | todo |
|
||||||
|
| POST `/api/restoreWireguardConfigurationBackup` | POST `/api/interfaces/<name>/backups/<file>/restore` | todo |
|
||||||
|
|
||||||
|
### Peer jobs
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| POST `/api/PeerScheduleJob` | POST `/api/peer-jobs` | todo |
|
||||||
|
| PUT `/api/PeerScheduleJob` | PUT `/api/peer-jobs/<id>` | todo |
|
||||||
|
| DELETE `/api/PeerScheduleJob` | DELETE `/api/peer-jobs/<id>` | todo |
|
||||||
|
| GET `/api/PeerScheduleJobLogs/<cfg>` | GET `/api/interfaces/<name>/peer-jobs/logs` | todo |
|
||||||
|
|
||||||
|
### Network tools
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/ping/getAllPeersIpAddress` | GET `/api/tools/peer-addresses` | todo |
|
||||||
|
| GET `/api/ping/execute` | POST `/api/tools/ping` | todo |
|
||||||
|
| GET `/api/traceroute/execute` | POST `/api/tools/traceroute` | todo |
|
||||||
|
|
||||||
|
### Email
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/email/ready` | GET `/api/email/ready` | todo |
|
||||||
|
| POST `/api/email/send` | POST `/api/email/send` | todo |
|
||||||
|
| POST `/api/email/preview` | POST `/api/email/preview` | todo |
|
||||||
|
|
||||||
|
### Webhooks
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/webHooks/getWebHooks` | GET `/api/webhooks` | todo |
|
||||||
|
| GET `/api/webHooks/createWebHook` | POST `/api/webhooks` | todo |
|
||||||
|
| POST `/api/webHooks/updateWebHook` | PUT `/api/webhooks/<id>` | todo |
|
||||||
|
| POST `/api/webHooks/deleteWebHook` | DELETE `/api/webhooks/<id>` | todo |
|
||||||
|
| GET `/api/webHooks/getWebHookSessions` | GET `/api/webhooks/<id>/deliveries` | todo |
|
||||||
|
|
||||||
|
### Clients (admin side)
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| GET `/api/clients/toggleStatus` | PUT `/api/settings/clients` | todo |
|
||||||
|
| GET `/api/clients/allClients` | GET `/api/clients?grouped=true` | todo |
|
||||||
|
| GET `/api/clients/allClientsRaw` | GET `/api/clients` | todo |
|
||||||
|
| POST `/api/clients/assignClient` | POST `/api/clients/<id>/assignments` | todo |
|
||||||
|
| POST `/api/clients/unassignClient` | DELETE `/api/clients/<id>/assignments/<assignment_id>` | todo |
|
||||||
|
| GET `/api/clients/assignedClients` | GET `/api/interfaces/<name>/peers/<id>/clients` | todo |
|
||||||
|
| GET `/api/clients/allConfigurationsPeers` | GET `/api/clients/assignable-peers` | todo |
|
||||||
|
| GET `/api/clients/assignedPeers` | GET `/api/clients/<id>/assignments` | todo |
|
||||||
|
| POST `/api/clients/generatePasswordResetLink` | POST `/api/clients/<id>/password-reset` | todo |
|
||||||
|
| POST `/api/clients/updateProfileName` | PUT `/api/clients/<id>` | todo |
|
||||||
|
| POST `/api/clients/deleteClient` | DELETE `/api/clients/<id>` | todo |
|
||||||
|
|
||||||
|
### Client portal (`/client/api/*` → `/api/client/*`)
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| POST `/client/api/signup` | POST `/api/client/signup` (public) | todo |
|
||||||
|
| POST `/client/api/signin` | POST `/api/client/signin` (public) | todo |
|
||||||
|
| POST `/client/api/signin/oidc/providers` | GET `/api/client/signin/oidc/providers` (public) | todo |
|
||||||
|
| POST `/client/api/signin/oidc` | POST `/api/client/signin/oidc` (public) | todo |
|
||||||
|
| GET/POST `/client/api/signin/totp` | GET/POST `/api/client/signin/totp` (public) | todo |
|
||||||
|
| GET `/client/api/signout` | POST `/api/client/signout` | todo |
|
||||||
|
| POST `/client/api/resetPassword/generateResetToken` | POST `/api/client/password-reset/request` (public) | todo |
|
||||||
|
| POST `/client/api/resetPassword/validateResetToken` | POST `/api/client/password-reset/validate` (public) | todo |
|
||||||
|
| POST `/client/api/resetPassword` | POST `/api/client/password-reset` (public) | todo |
|
||||||
|
| GET `/client/api/serverInformation` | GET `/api/client/server-information` (public) | todo |
|
||||||
|
| GET `/client/api/validateAuthentication` | GET `/api/client/auth/validate` | todo |
|
||||||
|
| GET `/client/api/configurations` | GET `/api/client/configurations` | todo |
|
||||||
|
| GET `/client/api/settings/getClientProfile` | GET `/api/client/profile` | todo |
|
||||||
|
| POST `/client/api/settings/updatePassword` | PUT `/api/client/profile/password` | todo |
|
||||||
|
|
||||||
|
### Misc
|
||||||
|
| Legacy | New | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| – | GET `/health`, `/healthz` | done |
|
||||||
|
| static `/`, `/client/` | static `/`, `/client/` | wip |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Known issues in current `src/` (fix in WS-0)
|
||||||
|
|
||||||
|
1. **Fixed in WS-0:** `pyotp` used in `src/modules/routes/routes_general.py` (TOTP check in `api_authenticate`) is imported; TOTP sign-in has regression coverage.
|
||||||
|
2. **Fixed in WS-0:** unreachable code after the final `return` in `api_authenticate` was removed.
|
||||||
|
3. **Fixed in WS-0:** the public whitelist now matches registered routes and no longer treats `/` as a wildcard; tested against `app.url_map`.
|
||||||
|
4. **Fixed in WS-0:** config aliases normalize `auth_req` to `authentication_required` and `dashboard_api_key` to `wgdashboard_apikey`.
|
||||||
|
5. **Fixed in WS-0:** `iface_postdown` replaces the duplicate `iface_predown`; typed `Peers` includes peer fields.
|
||||||
|
6. **Fixed in WS-0:** Flask uses a once-generated, permission-restricted secret key stored beside the active config.
|
||||||
|
7. **Fixed in WS-0:** `create_app()` and `src/gunicorn.conf.py` align Flask startup with Docker Gunicorn; `wg-dashboard.ini` and Docker legacy server keys are recognized.
|
||||||
|
8. `src/modules/wireguard/wireguard.py` is a stub that prints.
|
||||||
|
9. `statistics.py`: processes and interface priority sections incomplete.
|
||||||
|
10. **Fixed in WS-0:** `utilities.update_info()` handles network errors inside its `try`; `protocols_enabled` follows naming conventions; utility operations log at DEBUG.
|
||||||
|
11. **Fixed in WS-0:** login success uses the correct `make_resp_obj(status, message, data, http_code)` argument order.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Workstreams
|
||||||
|
|
||||||
|
Each workstream is sized so one agent can own it. Dependency graph:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
WS0[WS-0 Foundation] --> WS1[WS-1 WireGuard core]
|
||||||
|
WS0 --> WS5[WS-5 Auth & accounts]
|
||||||
|
WS0 --> WS9[WS-9 Frontend shared layer]
|
||||||
|
WS1 --> WS2[WS-2 Peers]
|
||||||
|
WS2 --> WS3[WS-3 Scheduler & tracking]
|
||||||
|
WS2 --> WS4[WS-4 Dashboard features]
|
||||||
|
WS3 --> WS4
|
||||||
|
WS5 --> WS6[WS-6 Client portal & OIDC]
|
||||||
|
WS2 --> WS6
|
||||||
|
WS9 --> WS10[WS-10 Admin UI parity]
|
||||||
|
WS9 --> WS11[WS-11 Client UI parity]
|
||||||
|
WS2 --> WS7[WS-7 Legacy importer]
|
||||||
|
WS3 --> WS7
|
||||||
|
WS5 --> WS7
|
||||||
|
WS7 --> WS8[WS-8 Packaging & release]
|
||||||
|
WS10 --> WS8
|
||||||
|
WS11 --> WS8
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-0 Foundation
|
||||||
|
**Depends on:** –
|
||||||
|
**Scope**
|
||||||
|
- Fix every item in §6 (except 8 and 9, which belong to WS-1 / WS-4).
|
||||||
|
- Extend `GUIDELINES.md` with §2 rules (short form, link to this roadmap).
|
||||||
|
- Add `pyproject.toml` with ruff + pyright config; `.pre-commit-config.yaml`; ESLint + Prettier in `src/web/admin` and `src/web/client`.
|
||||||
|
- Add `tests/` with pytest, a Flask app fixture and an in-memory SQLite fixture. Add Vitest to both web apps.
|
||||||
|
- GitHub Actions: lint + tests for Python and both web apps.
|
||||||
|
- Persistent `secret_key` (generated once, stored in config dir or DB).
|
||||||
|
- Unify config key names and add `config/legacy_keys.py`.
|
||||||
|
- Alembic: `alembic init`, wire `env.py` to `Base.metadata` and the config-derived URL, first migration from current models.
|
||||||
|
- Convert models to SQLAlchemy 2.0 typed style (`Mapped`, `mapped_column`).
|
||||||
|
- Align `main.py` with gunicorn (`create_app()` factory + `gunicorn.conf.py`).
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- `ruff check`, `pyright`, `eslint`, `pytest`, `vitest` all pass in CI.
|
||||||
|
- Sign-in with and without TOTP works (tests).
|
||||||
|
- Whitelist paths match real routes (test iterates `app.url_map`).
|
||||||
|
- `alembic upgrade head` creates the schema on SQLite and Postgres.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-1 WireGuard core
|
||||||
|
**Depends on:** WS-0
|
||||||
|
**Legacy reference:** `reference/src/modules/WireguardConfiguration.py`, `AmneziaConfiguration.py`, `Utilities.py`, `WireguardConfigurationInfo.py`
|
||||||
|
**Scope**
|
||||||
|
- `wireguard/conf_parser.py`: parse/write `.conf` files round-trip safe (preserve comments, ordering, unknown keys). Support `[Interface]` and multiple `[Peer]` sections, plus Amnezia keys.
|
||||||
|
- `wireguard/cli.py`: the only subprocess user. Functions: `show_dump(interface, protocol)`, `set_peer(...)`, `remove_peer(...)`, `interface_up(...)`, `interface_down(...)`, `save(...)`, `is_running(...)`. Use `wg show <iface> dump` (machine-readable). List args, timeouts, captured stderr.
|
||||||
|
- `wireguard/keys.py`: key generation and public key derivation in pure Python (`cryptography` X25519) – no subprocess.
|
||||||
|
- `wireguard/ip_allocation.py`: available-IP calculation with a readable loop and limit.
|
||||||
|
- `wireguard/interface_service.py`: list, get, create (wg + awg), update, update info/overrides/peer groups, rename, delete, toggle, raw file get/put, realtime traffic.
|
||||||
|
- Interface name validation `^[a-zA-Z0-9_=+.-]{1,15}$`.
|
||||||
|
- Interface routes in `routes/routes_interfaces.py` per §5.
|
||||||
|
- Protocol abstraction via a `Protocol` enum + Amnezia params object (composition, not inheritance).
|
||||||
|
- Discovery: on startup, import existing `.conf` files in `wg_conf_path` / `awg_conf_path` into `interfaces`.
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- Parser round-trip tests on fixture configs (wg + awg, comments, multiple peers).
|
||||||
|
- `cli.py` unit-tested with a mocked `subprocess.run`; no `shell=True` anywhere (ruff `S602`).
|
||||||
|
- All interface endpoints in §5 implemented and tested.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-2 Peers
|
||||||
|
**Depends on:** WS-1
|
||||||
|
**Legacy reference:** `Peer.py`, `AmneziaPeer.py`, `WireguardConfiguration.py` (addPeers, deletePeers, restrictPeers, allowAccessPeers), `dashboard.py` peer routes
|
||||||
|
**Scope**
|
||||||
|
- `wireguard/peer_service.py`: add (single + bulk, generated or provided keys, preshared key), update, delete, restrict, allow, reset data usage, search.
|
||||||
|
- Restrict = remove from live interface + mark `restricted` (match legacy behaviour; document it).
|
||||||
|
- Peer config generation (`.conf` text), QR payload, zip of all peers.
|
||||||
|
- Apply interface overrides and dashboard peer defaults when generating configs.
|
||||||
|
- Webhook events `peer_created`, `peer_updated`, `peer_deleted` emitted via an event hook (WS-4 consumes).
|
||||||
|
- Routes in `routes/routes_peers.py` per §5.
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- All peer endpoints in §5 implemented and tested with mocked `cli.py`.
|
||||||
|
- Generated peer config matches legacy output for the same input (golden-file test).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-3 Scheduler & tracking
|
||||||
|
**Depends on:** WS-2
|
||||||
|
**Legacy reference:** `dashboard.py` (`peerInformationBackgroundThread`, `peerJobScheduleBackgroundThread`), `gunicorn.conf.py`, `PeerJobs.py`, `PeerJob.py`, `PeerJobLogger.py`, `Log.py`
|
||||||
|
**Scope**
|
||||||
|
- `scheduler/scheduler.py`: single background scheduler started once per process (gunicorn `post_worker_init`, 1 worker). Clean shutdown.
|
||||||
|
- Jobs: peer stats refresh (10 s), traffic + endpoint history logging when tracking enabled (60 s), peer jobs evaluation (180 s), expired share-link / reset-token cleanup.
|
||||||
|
- `features/peer_jobs.py`: CRUD + evaluation with `JobOperator` / `JobAction` enums; job logs.
|
||||||
|
- `features/tracking.py`: sessions, traffic (with interval bucketing), endpoint history, table counts, export, delete.
|
||||||
|
- Routes per §5 (peer jobs + tracking).
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- Jobs testable without real time (inject clock).
|
||||||
|
- Peer job evaluation table-driven tests for every operator/action.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-4 Dashboard features
|
||||||
|
**Depends on:** WS-2, WS-3
|
||||||
|
**Legacy reference:** `PeerShareLinks.py`, `PeerShareLink.py`, `NewConfigurationTemplates.py`, `Email.py`, `DashboardWebHooks.py`, `DashboardPlugins.py`, `SystemStatus.py`, `DashboardLogger.py`, `dashboard.py` (backups, ping, traceroute, locale, settings)
|
||||||
|
**Scope**
|
||||||
|
- Dashboard settings read/update (validated per key), protocols, locale available/update.
|
||||||
|
- Backups: create, list (per interface + all, incl. orphaned), download, delete, restore. Safe filenames (`os.path.basename` + pattern), files `0600`.
|
||||||
|
- Config templates CRUD.
|
||||||
|
- Share links (public GET, rate-limited, expiry enforced).
|
||||||
|
- Email: SMTP (STARTTLS / implicit TLS / none), sandboxed Jinja2 templates, preview.
|
||||||
|
- Webhooks: CRUD, async delivery with timeout, delivery log, block private-range targets by default (SSRF).
|
||||||
|
- Network tools: ping / traceroute via `icmplib`; geolocation optional and disabled by default.
|
||||||
|
- Plugins: opt-in loader, disabled by default.
|
||||||
|
- Finish `statistics.py` (processes, interface priority).
|
||||||
|
- Audit log.
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- All related endpoints in §5 implemented and tested.
|
||||||
|
- Path traversal tests on backup endpoints.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-5 Auth & accounts
|
||||||
|
**Depends on:** WS-0
|
||||||
|
**Legacy reference:** `dashboard.py` (auth routes, before_request), `DashboardConfig.py`, `DashboardAPIKey.py`
|
||||||
|
**Scope**
|
||||||
|
- Move admin account from ini to `users` table (decision D3).
|
||||||
|
- `auth/admin_auth.py`: sign-in, sign-out, validate; bcrypt; TOTP verify with `valid_window=1`.
|
||||||
|
- `auth/totp.py`: provisioning, verify, enable/disable; secret encrypted at rest.
|
||||||
|
- `auth/api_keys.py`: create (shown once), store **hash**, list, delete, expiry.
|
||||||
|
- `flask-limiter` on sign-in.
|
||||||
|
- Strict CORS (configurable allow-list) and cookie flags (§4.3).
|
||||||
|
- Accept legacy header `wg-dashboard-apikey` during compatibility period.
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- Tests: wrong password, wrong TOTP, expired API key, rate-limit triggers, session survives restart.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-6 Client portal & OIDC
|
||||||
|
**Depends on:** WS-5, WS-2
|
||||||
|
**Legacy reference:** `client.py`, `DashboardClients.py`, `DashboardClientsTOTP.py`, `DashboardClientsPeerAssignment.py`, `DashboardOIDC.py`, `docker/templates/wgdashboard-oidc-providers.json`
|
||||||
|
**Scope**
|
||||||
|
- Client accounts: sign-up (if enabled), sign-in, TOTP, sign-out, profile, password change, password reset (email token, 30 min expiry).
|
||||||
|
- Assignments: assign/unassign peers, list per client / per peer, assignable peers.
|
||||||
|
- Admin client management routes.
|
||||||
|
- OIDC for admin and client: provider file loading, authorization-code exchange, JWKS signature verification, `end_session_endpoint` logout.
|
||||||
|
- Separate blueprint for `/api/client/*`.
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- All client + clients-admin + OIDC endpoints in §5 implemented and tested (OIDC with a mocked provider).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-7 Legacy importer
|
||||||
|
**Depends on:** WS-2, WS-3, WS-5
|
||||||
|
**Scope**
|
||||||
|
- `tools/import_legacy.py`: read legacy `wg-dashboard.ini` + legacy DB (SQLite / Postgres / MySQL), write the new schema.
|
||||||
|
- Map per-config tables → `peers` (status from `_restrict_access` / `_deleted`), `_transfer` → `peer_traffic_samples`, `_endpoint_history` → `peer_endpoint_history`, plus jobs, share links, API keys, clients, assignments, webhooks, templates.
|
||||||
|
- Map ini keys via `config/legacy_keys.py`; admin account → `users`.
|
||||||
|
- Dry-run mode with a summary report; idempotent.
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- Tested against fixture legacy databases; row counts and spot-checks match.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-8 Packaging & release
|
||||||
|
**Depends on:** WS-7, WS-10, WS-11
|
||||||
|
**Legacy reference:** `reference/src/wgd.sh`, `reference/src/wg-dashboard.service`, `reference/docker/*`
|
||||||
|
**Scope**
|
||||||
|
- Replace `wgd.sh` with a smaller install/start/stop/update script + systemd unit.
|
||||||
|
- Docker: align entrypoint with `create_app()`/gunicorn, config path, persistent volumes, healthcheck using `/healthz`, run importer automatically on first start when legacy data is detected.
|
||||||
|
- Release notes, upgrade guide (extend `docs/upgrade_database.md`).
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- Fresh install and legacy upgrade both work in Docker and bare metal (Debian, Alpine).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-9 Frontend shared layer
|
||||||
|
**Depends on:** WS-0
|
||||||
|
**Legacy reference:** `reference/src/static/app/src/utilities/fetch.js`, `reference/src/static/client/src/utilities/request.js`, `utilities/locale.js`
|
||||||
|
**Scope**
|
||||||
|
- `src/web/shared/`: one `async` HTTP client (fetch-based) with app-prefix handling, API-key header for cross-server mode, 401 handling; one module per backend domain (`api/interfaces.js`, `api/peers.js`, …) mirroring §5.
|
||||||
|
- Locale helper: key-based lookup with English fallback (replace regex matching).
|
||||||
|
- Shared form inputs (IP/CIDR, key, port) with validation.
|
||||||
|
- Types: TypeScript or JSDoc + `checkJs` (decision D2).
|
||||||
|
- Vite alias for `@shared` in both apps.
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- Vitest coverage for the HTTP client and locale helper.
|
||||||
|
- No direct `fetch`/`axios` calls remain in components.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-10 Admin UI parity
|
||||||
|
**Depends on:** WS-9 (and the backend workstream of each feature)
|
||||||
|
**Legacy reference:** `reference/src/static/app/src/**`
|
||||||
|
**Scope** – port in this order, keeping component names/structure, rewriting per §2.3:
|
||||||
|
1. Sign-in (+ TOTP, OIDC, remote servers), welcome/setup, 2FA setup
|
||||||
|
2. Navbar, configuration list, configuration card, protocol badge
|
||||||
|
3. Configuration detail: `peerList.vue` split into composables; peer card/row, search, sort, tags/groups, select-peers bulk actions
|
||||||
|
4. Peer modals: create, settings, details (sessions/traffic/endpoints/calendar), QR, config file, jobs, job logs, share link (+ email), assign clients
|
||||||
|
5. Edit/delete configuration, description, backup/restore, raw file editor
|
||||||
|
6. New configuration (+ templates), restore configuration
|
||||||
|
7. Settings: dashboard (theme, language, IP/port, account, MFA, API keys, email, tracking), peer defaults, WireGuard settings
|
||||||
|
8. Webhooks, clients + client viewer, system status, ping, traceroute, map, share page
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- Each legacy view/component has a counterpart (tracked in §8).
|
||||||
|
- No component > 250 lines; eslint passes.
|
||||||
|
- Playwright E2E: setup wizard → create interface → add peer → download config.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WS-11 Client UI parity
|
||||||
|
**Depends on:** WS-9, WS-6
|
||||||
|
**Legacy reference:** `reference/src/static/client/src/**`
|
||||||
|
**Scope**
|
||||||
|
- Sign-in (+ TOTP, OIDC), sign-up, forgot password, home (configurations + QR + download), settings (profile, password), notifications.
|
||||||
|
- Switch from axios to the shared HTTP client.
|
||||||
|
|
||||||
|
**Acceptance criteria**
|
||||||
|
- All client views ported; Playwright E2E for sign-in → download config.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Parity checklist
|
||||||
|
|
||||||
|
| Feature | Backend | Admin UI | Client UI | Workstream |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Sign-in / sign-out / validate | wip (WS-0 regressions fixed; target-route parity pending) | copied | – | WS-0, WS-5 |
|
||||||
|
| TOTP + setup wizard | wip (login regression fixed; setup parity pending) | copied | – | WS-0, WS-5 |
|
||||||
|
| API keys | model only | copied | – | WS-5 |
|
||||||
|
| Dashboard settings / theme / version / update | wip | copied | – | WS-4 |
|
||||||
|
| Locale (28 languages) | done | copied | partial | WS-4, WS-9 |
|
||||||
|
| Interfaces (wg + awg) CRUD / toggle / raw | todo | copied | – | WS-1 |
|
||||||
|
| Peers CRUD / restrict / download / QR | todo | copied | view | WS-2 |
|
||||||
|
| Peer groups / tags / overrides | todo | copied | – | WS-1, WS-2 |
|
||||||
|
| Peer jobs + logs | todo | copied | – | WS-3 |
|
||||||
|
| Tracking (traffic, sessions, endpoints, map) | todo | copied | – | WS-3 |
|
||||||
|
| Realtime traffic | todo | copied | – | WS-1 |
|
||||||
|
| Backups / restore | todo | copied | – | WS-4 |
|
||||||
|
| Config templates | todo | copied | – | WS-4 |
|
||||||
|
| Share links | todo | copied | – | WS-4 |
|
||||||
|
| Email | todo | copied | – | WS-4 |
|
||||||
|
| Webhooks | todo | copied | – | WS-4 |
|
||||||
|
| Ping / traceroute | todo | copied | – | WS-4 |
|
||||||
|
| Plugins | todo | – | – | WS-4 |
|
||||||
|
| System status | wip | copied | – | WS-4 |
|
||||||
|
| OIDC (admin + client) | todo | copied | copied | WS-6 |
|
||||||
|
| Client portal + assignments | todo | copied | copied | WS-6 |
|
||||||
|
| Legacy importer | todo | – | – | WS-7 |
|
||||||
|
| Docker / install script | wip | – | – | WS-8 |
|
||||||
|
|
||||||
|
`copied` = legacy component copied into `src/web` but not yet rewritten to §2.3 nor wired to new endpoints.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Security requirements (cross-cutting)
|
||||||
|
|
||||||
|
| Legacy issue | Requirement | Owner |
|
||||||
|
|---|---|---|
|
||||||
|
| `shell=True` for `wg pubkey` | Pure-Python keys; list args only | WS-1 |
|
||||||
|
| Permissive CORS, no CSRF | Configurable allow-list, `SameSite=Lax`, JSON-only mutating requests | WS-5 |
|
||||||
|
| TOTP / SMTP / DB secrets in plain ini | Encrypt at rest with `WGD_SECRET_KEY` (env/file) or move to DB | WS-5, WS-4 |
|
||||||
|
| `sha256(username+time)` tokens | Flask signed session only, persistent key | WS-0 |
|
||||||
|
| API keys stored plain | Store hash, show once | WS-5 |
|
||||||
|
| No rate limiting | `flask-limiter` on auth, client sign-in, share links | WS-5, WS-4, WS-6 |
|
||||||
|
| Plugins execute arbitrary code | Opt-in, disabled by default, documented | WS-4 |
|
||||||
|
| Webhook SSRF / `VerifySSL=false` | Block private ranges by default, UI warning | WS-4 |
|
||||||
|
| Config names in file paths | Strict name regex | WS-1 |
|
||||||
|
| Backups unencrypted | `0600` perms, optional encryption | WS-4 |
|
||||||
|
| Third-party geolocation (ip-api.com) | Opt-in only | WS-4 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Open decisions
|
||||||
|
|
||||||
|
Agents should follow the **recommended default** until the decision is marked final.
|
||||||
|
|
||||||
|
| ID | Question | Recommended default | Status |
|
||||||
|
|---|---|---|---|
|
||||||
|
| D1 | Flask vs FastAPI | Stay on Flask 3 + pydantic + OpenAPI plugin | open |
|
||||||
|
| D2 | TypeScript vs JavaScript in frontend | TypeScript for `web/shared` + stores; JSDoc + `checkJs` elsewhere | open |
|
||||||
|
| D3 | Admin account in ini or DB | DB (`users` table) | open |
|
||||||
|
| D4 | Legacy endpoint compatibility | Compat blueprint for one release (`/api/getXyz` → new handlers) | open |
|
||||||
|
| D5 | Error handling style | Keep `tuple[bool, value]` everywhere | open |
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
[project]
|
||||||
|
name = "wgdashboard"
|
||||||
|
version = "0.1.0"
|
||||||
|
requires-python = ">=3.10"
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = [
|
||||||
|
"alembic>=1.13,<2",
|
||||||
|
"pytest>=8",
|
||||||
|
"pyright>=1.1",
|
||||||
|
"ruff>=0.11",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
pythonpath = ["src"]
|
||||||
|
addopts = "-ra"
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
target-version = "py310"
|
||||||
|
line-length = 100
|
||||||
|
# The incomplete statistics module remains assigned to WS-4.
|
||||||
|
extend-exclude = ["reference", "src/web", "src/modules/utilities/statistics.py"]
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = ["E4", "E7", "E9", "F"]
|
||||||
|
|
||||||
|
[tool.pyright]
|
||||||
|
pythonVersion = "3.10"
|
||||||
|
typeCheckingMode = "basic"
|
||||||
|
# Keep the initial WS-0 type gate focused on the foundation modules and tests.
|
||||||
|
include = [
|
||||||
|
"src/main.py",
|
||||||
|
"src/gunicorn.conf.py",
|
||||||
|
"src/modules/config/config.py",
|
||||||
|
"src/modules/config/config_utils.py",
|
||||||
|
"src/modules/config/legacy_keys.py",
|
||||||
|
"src/modules/database/database_utils.py",
|
||||||
|
"src/modules/database/schema.py",
|
||||||
|
"src/modules/routes/locale.py",
|
||||||
|
"src/modules/routes/routes_general.py",
|
||||||
|
"src/modules/routes/routes_utils.py",
|
||||||
|
"src/modules/routes/routes_welcome.py",
|
||||||
|
"src/modules/utilities/utilities.py",
|
||||||
|
"tests",
|
||||||
|
]
|
||||||
|
exclude = [
|
||||||
|
"src/modules/database/alembic",
|
||||||
|
"src/modules/database/database.py",
|
||||||
|
"src/modules/database/functions.py",
|
||||||
|
]
|
||||||
|
venvPath = "."
|
||||||
|
venv = ".venv"
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
#!/bin/env python3
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from modules.config.config import config
|
||||||
|
|
||||||
|
|
||||||
|
application_directory = Path(__file__).parent
|
||||||
|
config_loaded, config_data = config.read()
|
||||||
|
if not config_loaded:
|
||||||
|
raise RuntimeError("failed to read the WGDashboard configuration")
|
||||||
|
|
||||||
|
server_config_found, server_config = config.filter(config_data, "SERVER")
|
||||||
|
if not server_config_found:
|
||||||
|
raise RuntimeError("the SERVER configuration section is missing")
|
||||||
|
|
||||||
|
hostname = server_config.get("hostname", "0.0.0.0")
|
||||||
|
port = server_config.get("port", 10086)
|
||||||
|
|
||||||
|
chdir = str(application_directory)
|
||||||
|
bind = f"{hostname}:{port}"
|
||||||
|
workers = 1
|
||||||
|
wsgi_app = "main:create_app()"
|
||||||
|
errorlog = "log/error_gunicorn.log"
|
||||||
|
accesslog = "log/access_gunicorn.log"
|
||||||
|
capture_output = True
|
||||||
|
pidfile = "gunicorn.pid"
|
||||||
@@ -1,70 +1,141 @@
|
|||||||
#!/bin/env python3
|
#!/bin/env python3
|
||||||
|
|
||||||
import logging as log
|
|
||||||
from logging.config import dictConfig
|
|
||||||
|
|
||||||
import flask
|
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import secrets
|
import secrets
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import flask
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.engine import Engine
|
||||||
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
from modules.config.config import config
|
from modules.config.config import config
|
||||||
|
from modules.config.config_utils import config_utils
|
||||||
|
from modules.config.legacy_keys import normalize_config_keys
|
||||||
from modules.database.database import database
|
from modules.database.database import database
|
||||||
|
|
||||||
from modules.utilities.utilities import utilities as util
|
|
||||||
from modules.utilities.logger import setup_logger
|
|
||||||
|
|
||||||
from modules.routes.routes_general import routes_general
|
from modules.routes.routes_general import routes_general
|
||||||
from modules.routes.routes_welcome import routes_welcome
|
from modules.routes.routes_welcome import routes_welcome
|
||||||
|
from modules.utilities.logger import setup_logger
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
# Read the config file (ini)
|
|
||||||
ok, config_data = config.read()
|
|
||||||
if not ok:
|
|
||||||
log.error("failed to read the config from disk")
|
|
||||||
exit(1)
|
|
||||||
found, config_server = config.filter(config_data, 'SERVER')
|
|
||||||
|
|
||||||
# Configure the loglevel of WGDashboard
|
def _read_persistent_secret(secret_path: Path) -> str:
|
||||||
wanted_loglevel = config_server.get('log_level', 'DEBUG').upper()
|
'''Read the persistent session key, creating it once when needed.'''
|
||||||
setup_logger(wanted_loglevel)
|
secret_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
# Get the database configuration from thee config
|
try:
|
||||||
found, config_database = config.filter(config_data, 'DATABASE')
|
descriptor = os.open(
|
||||||
if not found:
|
secret_path,
|
||||||
exit(1)
|
os.O_CREAT | os.O_EXCL | os.O_WRONLY,
|
||||||
|
0o600,
|
||||||
# Make the engine and create the infrastructure
|
|
||||||
ok, engine, session = database.create_session(config_database)
|
|
||||||
ok = database.ensure_contents(engine)
|
|
||||||
|
|
||||||
prefix = config_server.get('app_prefix', '')
|
|
||||||
|
|
||||||
# Configure the Flask app
|
|
||||||
app = flask.Flask("WGDashboard",
|
|
||||||
static_url_path=prefix,
|
|
||||||
template_folder=os.path.abspath("./static/dist/WGDashboardAdmin"),
|
|
||||||
static_folder=os.path.abspath("./static/dist/WGDashboardAdmin")
|
|
||||||
)
|
)
|
||||||
|
except FileExistsError:
|
||||||
|
secret_key = secret_path.read_text(encoding="utf-8").strip()
|
||||||
|
if not secret_key:
|
||||||
|
raise RuntimeError(f"persistent secret key is empty: {secret_path}")
|
||||||
|
return secret_key
|
||||||
|
|
||||||
|
secret_key = secrets.token_urlsafe(64)
|
||||||
|
with os.fdopen(descriptor, "w", encoding="utf-8") as secret_file:
|
||||||
|
secret_file.write(secret_key)
|
||||||
|
secret_file.flush()
|
||||||
|
os.fsync(secret_file.fileno())
|
||||||
|
|
||||||
|
return secret_key
|
||||||
|
|
||||||
|
|
||||||
|
def create_app(
|
||||||
|
config_data: dict[str, Any] | None = None,
|
||||||
|
*,
|
||||||
|
database_url: str | None = None,
|
||||||
|
database_engine: Engine | None = None,
|
||||||
|
secret_key_path: str | Path | None = None,
|
||||||
|
) -> flask.Flask:
|
||||||
|
'''Create and configure the WGDashboard Flask application.'''
|
||||||
|
config_file_path: str | None = None
|
||||||
|
if config_data is None:
|
||||||
|
config_loaded, loaded_config = config.read()
|
||||||
|
if not config_loaded:
|
||||||
|
raise RuntimeError("failed to read the WGDashboard configuration")
|
||||||
|
config_data = loaded_config
|
||||||
|
|
||||||
|
config_path_found, config_file_path = config_utils.search_known_paths()
|
||||||
|
if not config_path_found:
|
||||||
|
raise RuntimeError("failed to locate the WGDashboard configuration")
|
||||||
|
|
||||||
|
normalized_config = normalize_config_keys(config_data)
|
||||||
|
server_config_found, server_config = config.filter(normalized_config, "SERVER")
|
||||||
|
if not server_config_found:
|
||||||
|
raise RuntimeError("the SERVER configuration section is missing")
|
||||||
|
|
||||||
|
setup_logger(str(server_config.get("log_level", "DEBUG")).upper())
|
||||||
|
|
||||||
|
prefix_value = server_config.get("app_prefix", "")
|
||||||
|
prefix = str(prefix_value).rstrip("/")
|
||||||
|
if prefix == "/":
|
||||||
|
prefix = ""
|
||||||
|
|
||||||
|
web_directory = Path(__file__).parent / "web" / "dist" / "WGDashboardAdmin"
|
||||||
|
app = flask.Flask(
|
||||||
|
"WGDashboard",
|
||||||
|
static_url_path=f"{prefix}/web",
|
||||||
|
template_folder=str(web_directory),
|
||||||
|
static_folder=str(web_directory),
|
||||||
|
)
|
||||||
|
app.config["APP_PREFIX"] = prefix
|
||||||
|
app.config["WGD_CONFIG"] = normalized_config
|
||||||
|
app.config["SESSION_COOKIE_HTTPONLY"] = True
|
||||||
|
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
|
||||||
|
|
||||||
|
if secret_key_path is None:
|
||||||
|
if config_file_path is not None:
|
||||||
|
secret_path = Path(config_file_path).resolve().parent / "secret_key"
|
||||||
|
else:
|
||||||
|
secret_path = Path.home() / ".config" / "wgdashboard" / "secret_key"
|
||||||
|
else:
|
||||||
|
secret_path = Path(secret_key_path)
|
||||||
|
app.secret_key = _read_persistent_secret(secret_path)
|
||||||
|
|
||||||
|
database_config_found, database_config = config.filter(normalized_config, "DATABASE")
|
||||||
|
if (
|
||||||
|
not database_config_found
|
||||||
|
and database_url is None
|
||||||
|
and database_engine is None
|
||||||
|
):
|
||||||
|
raise RuntimeError("the DATABASE configuration section is missing")
|
||||||
|
|
||||||
|
if database_url is not None and database_engine is not None:
|
||||||
|
raise ValueError("provide either database_url or database_engine, not both")
|
||||||
|
|
||||||
|
if database_engine is not None:
|
||||||
|
engine = database_engine
|
||||||
|
db_session = sessionmaker(bind=engine, class_=Session)()
|
||||||
|
elif database_url is None:
|
||||||
|
session_created, engine, db_session = database.create_session(database_config)
|
||||||
|
if not session_created or engine is None or db_session is None:
|
||||||
|
raise RuntimeError("failed to initialize the database")
|
||||||
|
else:
|
||||||
|
engine = create_engine(database_url)
|
||||||
|
db_session = sessionmaker(bind=engine, class_=Session)()
|
||||||
|
|
||||||
|
if not database.ensure_contents(engine):
|
||||||
|
engine.dispose()
|
||||||
|
raise RuntimeError("failed to create or verify database tables")
|
||||||
|
|
||||||
|
app.extensions["wgd_engine"] = engine
|
||||||
|
app.extensions["wgd_db_session"] = db_session
|
||||||
|
app.config["WGD_LOCALE_PATH"] = str(Path(__file__).parent / "web" / "locales")
|
||||||
app.register_blueprint(routes_general, url_prefix=prefix)
|
app.register_blueprint(routes_general, url_prefix=prefix)
|
||||||
app.register_blueprint(routes_welcome, url_prefix=prefix)
|
app.register_blueprint(routes_welcome, url_prefix=prefix)
|
||||||
|
return app
|
||||||
|
|
||||||
app.wgd_config = config_data
|
|
||||||
app.locale_path = './static/locales/'
|
|
||||||
|
|
||||||
app.secret_key = secrets.token_urlsafe(64)
|
if __name__ == "__main__":
|
||||||
app.config['SESSION_TYPE'] = 'filesystem'
|
application = create_app()
|
||||||
|
server_settings = application.config["WGD_CONFIG"]["server"]
|
||||||
app.engine = engine
|
application.run(
|
||||||
app.db_session = session
|
debug=server_settings.get("debug_enabled", False),
|
||||||
|
host=server_settings.get("hostname", "0.0.0.0"),
|
||||||
debug_enabled = config_server.get('debug_enabled', False)
|
port=int(server_settings.get("port", 10086)),
|
||||||
hostname = config_server.get('hostname', '0.0.0.0')
|
use_reloader=False,
|
||||||
port = config_server.get('port', '10086')
|
|
||||||
|
|
||||||
app.run(
|
|
||||||
debug=debug_enabled,
|
|
||||||
host=hostname,
|
|
||||||
port=port,
|
|
||||||
use_reloader=False
|
|
||||||
)
|
)
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
#!/bin/env python3
|
#!/bin/env python3
|
||||||
|
|
||||||
import logging as log
|
import logging as log
|
||||||
import flask
|
|
||||||
|
|
||||||
from .config_utils import config_utils
|
from .config_utils import config_utils
|
||||||
|
from .legacy_keys import LEGACY_CONFIG_KEYS, normalize_config_keys
|
||||||
|
|
||||||
class config():
|
class config():
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -37,12 +37,16 @@ class config():
|
|||||||
log.error("failed to read data from filepath")
|
log.error("failed to read data from filepath")
|
||||||
return False, {}
|
return False, {}
|
||||||
|
|
||||||
return True, config_data
|
return True, normalize_config_keys(config_data)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def update(target_section: str, target_key: str, new_value) -> bool:
|
def update(target_section: str, target_key: str, new_value) -> bool:
|
||||||
lower_target_section = target_section.lower()
|
lower_target_section = target_section.lower()
|
||||||
lower_target_key = target_key.lower()
|
lower_target_key = target_key.lower()
|
||||||
|
lower_target_key = LEGACY_CONFIG_KEYS.get(
|
||||||
|
(lower_target_section, lower_target_key),
|
||||||
|
lower_target_key,
|
||||||
|
)
|
||||||
|
|
||||||
ok, config_data = config.read()
|
ok, config_data = config.read()
|
||||||
if not ok:
|
if not ok:
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ class config_utils():
|
|||||||
'''
|
'''
|
||||||
|
|
||||||
possible_config_locations = [
|
possible_config_locations = [
|
||||||
|
"./wg-dashboard.ini",
|
||||||
"./config.ini",
|
"./config.ini",
|
||||||
|
"./src/config.ini",
|
||||||
f"{os.getenv('HOME')}/.config/wgdashboard/config.ini",
|
f"{os.getenv('HOME')}/.config/wgdashboard/config.ini",
|
||||||
"/etc/wgdashboard/config.ini",
|
"/etc/wgdashboard/config.ini",
|
||||||
]
|
]
|
||||||
@@ -26,7 +28,7 @@ class config_utils():
|
|||||||
continue
|
continue
|
||||||
return False, ''
|
return False, ''
|
||||||
|
|
||||||
except Exception as err:
|
except OSError:
|
||||||
return False, ''
|
return False, ''
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -58,7 +60,7 @@ class config_utils():
|
|||||||
|
|
||||||
return True, config_dict
|
return True, config_dict
|
||||||
|
|
||||||
except cp.ParsingError as err:
|
except cp.ParsingError:
|
||||||
return False, {}
|
return False, {}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#!/bin/env python3
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
LEGACY_CONFIG_KEYS: dict[tuple[str, str], str] = {
|
||||||
|
("server", "auth_req"): "authentication_required",
|
||||||
|
("server", "dashboard_api_key"): "wgdashboard_apikey",
|
||||||
|
("server", "app_ip"): "hostname",
|
||||||
|
("server", "app_port"): "port",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_config_keys(config_data: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
'''Return config data with legacy keys replaced by canonical keys.'''
|
||||||
|
normalized = {
|
||||||
|
str(section).lower(): dict(values)
|
||||||
|
for section, values in config_data.items()
|
||||||
|
if isinstance(values, dict)
|
||||||
|
}
|
||||||
|
|
||||||
|
for (section, legacy_key), canonical_key in LEGACY_CONFIG_KEYS.items():
|
||||||
|
section_values = normalized.get(section)
|
||||||
|
if section_values is None or legacy_key not in section_values:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if canonical_key not in section_values:
|
||||||
|
section_values[canonical_key] = section_values[legacy_key]
|
||||||
|
|
||||||
|
del section_values[legacy_key]
|
||||||
|
|
||||||
|
return normalized
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
#!/bin/env python3
|
||||||
|
|
||||||
|
from logging.config import fileConfig
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
from sqlalchemy import engine_from_config, pool
|
||||||
|
from sqlalchemy.engine import Connection
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
|
||||||
|
from modules.config.config import config as app_config
|
||||||
|
from modules.database.database_utils import database_utils
|
||||||
|
from modules.database.schema import Base
|
||||||
|
|
||||||
|
|
||||||
|
alembic_config = context.config
|
||||||
|
if alembic_config.config_file_name is not None:
|
||||||
|
fileConfig(alembic_config.config_file_name)
|
||||||
|
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def _database_url() -> str:
|
||||||
|
'''Resolve the configured database URL, allowing explicit test overrides.'''
|
||||||
|
override_url = alembic_config.attributes.get("database_url")
|
||||||
|
if isinstance(override_url, str):
|
||||||
|
return override_url
|
||||||
|
environment_url = os.environ.get("WGDASHBOARD_DATABASE_URL")
|
||||||
|
if environment_url:
|
||||||
|
return environment_url
|
||||||
|
|
||||||
|
config_loaded, config_data = app_config.read()
|
||||||
|
if not config_loaded:
|
||||||
|
raise RuntimeError("failed to read the WGDashboard configuration")
|
||||||
|
|
||||||
|
database_config_found, database_config = app_config.filter(config_data, "DATABASE")
|
||||||
|
if not database_config_found:
|
||||||
|
raise RuntimeError("the DATABASE configuration section is missing")
|
||||||
|
|
||||||
|
url_created, connection_url = database_utils.generate_connection_string(database_config)
|
||||||
|
if not url_created:
|
||||||
|
raise RuntimeError("failed to create the database URL from configuration")
|
||||||
|
|
||||||
|
return connection_url
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
'''Run migrations without creating a database connection.'''
|
||||||
|
context.configure(
|
||||||
|
url=_database_url(),
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
compare_type=True,
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def _run_migrations(connection: Connection) -> None:
|
||||||
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
compare_type=True,
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
'''Run migrations using the configured engine or injected connection.'''
|
||||||
|
supplied_connection: Any = alembic_config.attributes.get("connection")
|
||||||
|
if supplied_connection is not None:
|
||||||
|
_run_migrations(supplied_connection)
|
||||||
|
return
|
||||||
|
|
||||||
|
connection_url = _database_url()
|
||||||
|
alembic_config.set_main_option("sqlalchemy.url", connection_url.replace("%", "%%"))
|
||||||
|
connectable = engine_from_config(
|
||||||
|
alembic_config.get_section(alembic_config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
_run_migrations(connection)
|
||||||
|
|
||||||
|
connectable.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
"""Create the initial WGDashboard schema.
|
||||||
|
|
||||||
|
Revision ID: 0001_initial_schema
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-10-28
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Sequence
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision: str = "0001_initial_schema"
|
||||||
|
down_revision: str | None = None
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _interface_columns(include_amnezia: bool) -> list[sa.Column]:
|
||||||
|
'''Build columns shared by the WireGuard interface tables.'''
|
||||||
|
columns = [
|
||||||
|
sa.Column("iface_status", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("iface_name", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_notes", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_privkey", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_pubkey", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_address", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_listen_port", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("iface_mtu", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("iface_preup", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_predown", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_postup", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_postdown", sa.String(), nullable=True),
|
||||||
|
]
|
||||||
|
|
||||||
|
if include_amnezia:
|
||||||
|
columns.extend(
|
||||||
|
[
|
||||||
|
sa.Column("iface_jc", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("iface_jmin", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("iface_jmax", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("iface_s1", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("iface_s2", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("iface_s3", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("iface_s4", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("iface_h1", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_h2", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_h3", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_h4", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_i1", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_i2", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_i3", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_i4", sa.String(), nullable=True),
|
||||||
|
sa.Column("iface_i5", sa.String(), nullable=True),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
columns.extend(
|
||||||
|
[
|
||||||
|
sa.Column("iface_save_config", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("iface_total_rx", sa.Float(), nullable=True),
|
||||||
|
sa.Column("iface_total_tx", sa.Float(), nullable=True),
|
||||||
|
sa.Column("iface_total_data", sa.Float(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("iface_id"),
|
||||||
|
sa.UniqueConstraint("iface_name"),
|
||||||
|
sa.UniqueConstraint("iface_privkey"),
|
||||||
|
sa.UniqueConstraint("iface_pubkey"),
|
||||||
|
sa.UniqueConstraint("iface_listen_port"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
return columns
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"users",
|
||||||
|
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("username", sa.String(), nullable=True),
|
||||||
|
sa.Column("password", sa.String(), nullable=True),
|
||||||
|
sa.Column("role", sa.String(), nullable=True),
|
||||||
|
sa.Column("totp_enabled", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("totp_verified", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("totp_secret", sa.String(), nullable=True),
|
||||||
|
sa.Column("email", sa.String(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("user_id"),
|
||||||
|
sa.UniqueConstraint("username"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_users_user_id", "users", ["user_id"], unique=False)
|
||||||
|
op.create_index("ix_users_username", "users", ["username"], unique=True)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"apikeys",
|
||||||
|
sa.Column("key_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("key_data", sa.String(), nullable=True),
|
||||||
|
sa.Column("key_creation", sa.String(), nullable=True),
|
||||||
|
sa.Column("key_expiration", sa.String(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("key_id"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_apikeys_key_id", "apikeys", ["key_id"], unique=False)
|
||||||
|
|
||||||
|
op.create_table("wireguard_interfaces", *_interface_columns(include_amnezia=False))
|
||||||
|
op.create_index("ix_wireguard_interfaces_iface_id", "wireguard_interfaces", ["iface_id"], unique=False)
|
||||||
|
|
||||||
|
op.create_table("amnezia_interfaces", *_interface_columns(include_amnezia=True))
|
||||||
|
op.create_index("ix_amnezia_interfaces_iface_id", "amnezia_interfaces", ["iface_id"], unique=False)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"interface_peers",
|
||||||
|
sa.Column("peer_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("assigned_iface", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_public_key", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_private_key", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_preshared_key", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_name", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_allowed_ips", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_endpoint_allowed_ips", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_dns", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_mtu", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("peer_keep_alive", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("peer_remote_endpoint", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_notes", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_status", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_latest_handshake", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_endpoint", sa.String(), nullable=True),
|
||||||
|
sa.Column("peer_total_rx", sa.Float(), nullable=True),
|
||||||
|
sa.Column("peer_total_tx", sa.Float(), nullable=True),
|
||||||
|
sa.Column("peer_cumulative_rx", sa.Float(), nullable=True),
|
||||||
|
sa.Column("peer_cumulative_tx", sa.Float(), nullable=True),
|
||||||
|
sa.Column("peer_group_id", sa.Integer(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("peer_id"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_interface_peers_peer_id", "interface_peers", ["peer_id"], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("ix_interface_peers_peer_id", table_name="interface_peers")
|
||||||
|
op.drop_table("interface_peers")
|
||||||
|
op.drop_index("ix_amnezia_interfaces_iface_id", table_name="amnezia_interfaces")
|
||||||
|
op.drop_table("amnezia_interfaces")
|
||||||
|
op.drop_index("ix_wireguard_interfaces_iface_id", table_name="wireguard_interfaces")
|
||||||
|
op.drop_table("wireguard_interfaces")
|
||||||
|
op.drop_index("ix_apikeys_key_id", table_name="apikeys")
|
||||||
|
op.drop_table("apikeys")
|
||||||
|
op.drop_index("ix_users_username", table_name="users")
|
||||||
|
op.drop_index("ix_users_user_id", table_name="users")
|
||||||
|
op.drop_table("users")
|
||||||
@@ -4,6 +4,7 @@ import logging as log
|
|||||||
|
|
||||||
import sqlalchemy
|
import sqlalchemy
|
||||||
import sqlalchemy.orm
|
import sqlalchemy.orm
|
||||||
|
from sqlalchemy.exc import SQLAlchemyError
|
||||||
|
|
||||||
from .schema import Base
|
from .schema import Base
|
||||||
from .database_utils import database_utils
|
from .database_utils import database_utils
|
||||||
@@ -37,6 +38,6 @@ class database():
|
|||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as err:
|
except SQLAlchemyError:
|
||||||
log.error('failed to verify contents of the database')
|
log.exception('failed to verify contents of the database')
|
||||||
return False
|
return False
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
#!/bin/env python3
|
#!/bin/env python3
|
||||||
|
|
||||||
import logging as log
|
from pathlib import Path
|
||||||
|
|
||||||
import os
|
from sqlalchemy.engine import URL
|
||||||
from urllib.parse import quote_plus
|
|
||||||
|
|
||||||
from modules.utilities.utilities import utilities as util
|
from modules.utilities.utilities import utilities as util
|
||||||
|
|
||||||
@@ -14,30 +13,45 @@ class database_utils():
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def generate_connection_string(database_config: dict) -> tuple[bool, str]:
|
def generate_connection_string(database_config: dict) -> tuple[bool, str]:
|
||||||
if not 'type' in database_config:
|
if "type" not in database_config:
|
||||||
return False, ''
|
return False, ''
|
||||||
|
|
||||||
username = quote_plus(database_config.get('username', ''))
|
|
||||||
password = quote_plus(database_config.get('password', ''))
|
|
||||||
|
|
||||||
match database_config['type']:
|
match database_config['type']:
|
||||||
case 'sqlite':
|
case 'sqlite':
|
||||||
local_database_path = os.path.abspath("./database")
|
local_database_path = Path("./database").resolve()
|
||||||
|
if not util.ensure_directory(str(local_database_path)):
|
||||||
exists = util.ensure_directory(local_database_path)
|
|
||||||
if exists:
|
|
||||||
connection_string = f'sqlite:///{local_database_path}/wgdashboard.db'
|
|
||||||
else:
|
|
||||||
return False, ''
|
return False, ''
|
||||||
|
connection_string = URL.create(
|
||||||
|
"sqlite",
|
||||||
|
database=str(local_database_path / "wgdashboard.db"),
|
||||||
|
).render_as_string(hide_password=False)
|
||||||
|
|
||||||
case 'postgresql' | 'postgres':
|
case 'postgresql' | 'postgres':
|
||||||
connection_string = f'postgresql+psycopg://{username}:{password}@{database_config.get('host', 'localhost')}:{database_config.get('port', '5432')}'
|
connection_string = URL.create(
|
||||||
|
"postgresql+psycopg",
|
||||||
|
username=database_config.get("username") or None,
|
||||||
|
password=database_config.get("password") or None,
|
||||||
|
host=database_config.get("host") or "localhost",
|
||||||
|
port=int(database_config.get("port") or 5432),
|
||||||
|
).render_as_string(hide_password=False)
|
||||||
|
|
||||||
case 'mariadb':
|
case 'mariadb':
|
||||||
connection_string = f'mariadb+mariadbconnector://{username}:{password}@{database_config.get('host', 'localhost')}:{database_config.get('port', '3306')}'
|
connection_string = URL.create(
|
||||||
|
"mariadb+mariadbconnector",
|
||||||
|
username=database_config.get("username") or None,
|
||||||
|
password=database_config.get("password") or None,
|
||||||
|
host=database_config.get("host") or "localhost",
|
||||||
|
port=int(database_config.get("port") or 3306),
|
||||||
|
).render_as_string(hide_password=False)
|
||||||
|
|
||||||
case 'mysql':
|
case 'mysql':
|
||||||
connection_string = f'mysql+pymysql://{username}:{password}@{database_config.get('host', 'localhost')}:{database_config.get('port', '3306')}'
|
connection_string = URL.create(
|
||||||
|
"mysql+pymysql",
|
||||||
|
username=database_config.get("username") or None,
|
||||||
|
password=database_config.get("password") or None,
|
||||||
|
host=database_config.get("host") or "localhost",
|
||||||
|
port=int(database_config.get("port") or 3306),
|
||||||
|
).render_as_string(hide_password=False)
|
||||||
|
|
||||||
case _:
|
case _:
|
||||||
return False, ''
|
return False, ''
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import sqlalchemy.orm
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from .schema import Base
|
|
||||||
from .schema import Apikeys, User
|
from .schema import Apikeys, User
|
||||||
|
|
||||||
class functions():
|
class functions():
|
||||||
|
|||||||
@@ -1,36 +1,33 @@
|
|||||||
#!/bin/env python3
|
#!/bin/env python3
|
||||||
|
|
||||||
import sqlalchemy
|
from sqlalchemy import Boolean, Float, Integer, String
|
||||||
import sqlalchemy.orm
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||||
|
|
||||||
Base = sqlalchemy.orm.declarative_base()
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
|
|
||||||
class User(Base):
|
class User(Base):
|
||||||
__tablename__ = 'users'
|
__tablename__ = 'users'
|
||||||
|
|
||||||
user_id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, index=True)
|
user_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||||
|
username: Mapped[str | None] = mapped_column(String, unique=True, index=True)
|
||||||
username = sqlalchemy.Column(sqlalchemy.String, unique=True, index=True)
|
password: Mapped[str | None] = mapped_column(String)
|
||||||
password = sqlalchemy.Column(sqlalchemy.String)
|
role: Mapped[str | None] = mapped_column(String, default='user')
|
||||||
|
totp_enabled: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||||
role = sqlalchemy.Column(sqlalchemy.String, default='user')
|
totp_verified: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||||
|
totp_secret: Mapped[str | None] = mapped_column(String)
|
||||||
totp_enabled = sqlalchemy.Column(sqlalchemy.Boolean, default=False)
|
email: Mapped[str | None] = mapped_column(String)
|
||||||
totp_verified = sqlalchemy.Column(sqlalchemy.Boolean, default=False)
|
|
||||||
totp_secret = sqlalchemy.Column(sqlalchemy.String)
|
|
||||||
|
|
||||||
email = sqlalchemy.Column(sqlalchemy.String)
|
|
||||||
|
|
||||||
class Apikeys(Base):
|
class Apikeys(Base):
|
||||||
__tablename__ = 'apikeys'
|
__tablename__ = 'apikeys'
|
||||||
|
|
||||||
key_id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, index=True)
|
key_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||||
key_data = sqlalchemy.Column(sqlalchemy.String)
|
key_data: Mapped[str | None] = mapped_column(String)
|
||||||
|
key_creation: Mapped[str | None] = mapped_column(String)
|
||||||
|
key_expiration: Mapped[str | None] = mapped_column(String)
|
||||||
|
|
||||||
key_creation = sqlalchemy.Column(sqlalchemy.String)
|
def to_dict(self) -> dict[str, int | str | None]:
|
||||||
key_expiration = sqlalchemy.Column(sqlalchemy.String)
|
|
||||||
|
|
||||||
def to_dict(self):
|
|
||||||
return {
|
return {
|
||||||
'id': self.key_id,
|
'id': self.key_id,
|
||||||
'key': self.key_data,
|
'key': self.key_data,
|
||||||
@@ -41,78 +38,82 @@ class Apikeys(Base):
|
|||||||
class Wireguard(Base):
|
class Wireguard(Base):
|
||||||
__tablename__ = 'wireguard_interfaces'
|
__tablename__ = 'wireguard_interfaces'
|
||||||
|
|
||||||
iface_status = sqlalchemy.Column(sqlalchemy.String)
|
iface_status: Mapped[str | None] = mapped_column(String)
|
||||||
iface_id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, index=True)
|
iface_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||||
|
iface_name: Mapped[str | None] = mapped_column(String, unique=True)
|
||||||
iface_name = sqlalchemy.Column(sqlalchemy.String, unique=True)
|
iface_notes: Mapped[str | None] = mapped_column(String)
|
||||||
iface_notes = sqlalchemy.Column(sqlalchemy.String)
|
iface_privkey: Mapped[str | None] = mapped_column(String, unique=True)
|
||||||
|
iface_pubkey: Mapped[str | None] = mapped_column(String, unique=True)
|
||||||
iface_privkey = sqlalchemy.Column(sqlalchemy.String, unique=True)
|
iface_address: Mapped[str | None] = mapped_column(String)
|
||||||
iface_pubkey = sqlalchemy.Column(sqlalchemy.String, unique=True)
|
iface_listen_port: Mapped[int | None] = mapped_column(Integer, unique=True)
|
||||||
iface_address = sqlalchemy.Column(sqlalchemy.String)
|
iface_mtu: Mapped[int | None] = mapped_column(Integer)
|
||||||
iface_listen_port = sqlalchemy.Column(sqlalchemy.Integer, unique=True)
|
iface_preup: Mapped[str | None] = mapped_column(String)
|
||||||
iface_mtu = sqlalchemy.Column(sqlalchemy.Integer)
|
iface_predown: Mapped[str | None] = mapped_column(String)
|
||||||
|
iface_postup: Mapped[str | None] = mapped_column(String)
|
||||||
iface_preup = sqlalchemy.Column(sqlalchemy.String)
|
iface_postdown: Mapped[str | None] = mapped_column(String)
|
||||||
iface_predown = sqlalchemy.Column(sqlalchemy.String)
|
iface_save_config: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||||
iface_postup = sqlalchemy.Column(sqlalchemy.String)
|
iface_total_rx: Mapped[float | None] = mapped_column(Float)
|
||||||
iface_predown = sqlalchemy.Column(sqlalchemy.String)
|
iface_total_tx: Mapped[float | None] = mapped_column(Float)
|
||||||
|
iface_total_data: Mapped[float | None] = mapped_column(Float)
|
||||||
iface_save_config = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
|
|
||||||
|
|
||||||
iface_total_rx = sqlalchemy.Column(sqlalchemy.Float)
|
|
||||||
iface_total_tx = sqlalchemy.Column(sqlalchemy.Float)
|
|
||||||
iface_total_data = sqlalchemy.Column(sqlalchemy.Float)
|
|
||||||
|
|
||||||
class Amnezia(Base):
|
class Amnezia(Base):
|
||||||
__tablename__ = 'amnezia_interfaces'
|
__tablename__ = 'amnezia_interfaces'
|
||||||
|
|
||||||
iface_status = sqlalchemy.Column(sqlalchemy.String)
|
iface_status: Mapped[str | None] = mapped_column(String)
|
||||||
iface_id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, index=True)
|
iface_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||||
|
iface_name: Mapped[str | None] = mapped_column(String, unique=True)
|
||||||
iface_name = sqlalchemy.Column(sqlalchemy.String, unique=True)
|
iface_notes: Mapped[str | None] = mapped_column(String)
|
||||||
iface_notes = sqlalchemy.Column(sqlalchemy.String)
|
iface_privkey: Mapped[str | None] = mapped_column(String, unique=True)
|
||||||
|
iface_pubkey: Mapped[str | None] = mapped_column(String, unique=True)
|
||||||
iface_privkey = sqlalchemy.Column(sqlalchemy.String, unique=True)
|
iface_address: Mapped[str | None] = mapped_column(String)
|
||||||
iface_pubkey = sqlalchemy.Column(sqlalchemy.String, unique=True)
|
iface_listen_port: Mapped[int | None] = mapped_column(Integer, unique=True)
|
||||||
iface_address = sqlalchemy.Column(sqlalchemy.String)
|
iface_mtu: Mapped[int | None] = mapped_column(Integer)
|
||||||
iface_listen_port = sqlalchemy.Column(sqlalchemy.Integer, unique=True)
|
iface_preup: Mapped[str | None] = mapped_column(String)
|
||||||
iface_mtu = sqlalchemy.Column(sqlalchemy.Integer)
|
iface_predown: Mapped[str | None] = mapped_column(String)
|
||||||
|
iface_postup: Mapped[str | None] = mapped_column(String)
|
||||||
iface_preup = sqlalchemy.Column(sqlalchemy.String)
|
iface_postdown: Mapped[str | None] = mapped_column(String)
|
||||||
iface_predown = sqlalchemy.Column(sqlalchemy.String)
|
iface_jc: Mapped[int | None] = mapped_column(Integer)
|
||||||
iface_postup = sqlalchemy.Column(sqlalchemy.String)
|
iface_jmin: Mapped[int | None] = mapped_column(Integer)
|
||||||
iface_predown = sqlalchemy.Column(sqlalchemy.String)
|
iface_jmax: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
iface_s1: Mapped[int | None] = mapped_column(Integer)
|
||||||
iface_jc = sqlalchemy.Column(sqlalchemy.Integer)
|
iface_s2: Mapped[int | None] = mapped_column(Integer)
|
||||||
iface_jmin = sqlalchemy.Column(sqlalchemy.Integer)
|
iface_s3: Mapped[int | None] = mapped_column(Integer)
|
||||||
iface_jmax = sqlalchemy.Column(sqlalchemy.Integer)
|
iface_s4: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
iface_h1: Mapped[str | None] = mapped_column(String)
|
||||||
iface_s1 = sqlalchemy.Column(sqlalchemy.Integer)
|
iface_h2: Mapped[str | None] = mapped_column(String)
|
||||||
iface_s2 = sqlalchemy.Column(sqlalchemy.Integer)
|
iface_h3: Mapped[str | None] = mapped_column(String)
|
||||||
iface_s3 = sqlalchemy.Column(sqlalchemy.Integer)
|
iface_h4: Mapped[str | None] = mapped_column(String)
|
||||||
iface_s4 = sqlalchemy.Column(sqlalchemy.Integer)
|
iface_i1: Mapped[str | None] = mapped_column(String)
|
||||||
|
iface_i2: Mapped[str | None] = mapped_column(String)
|
||||||
iface_h1 = sqlalchemy.Column(sqlalchemy.String)
|
iface_i3: Mapped[str | None] = mapped_column(String)
|
||||||
iface_h2 = sqlalchemy.Column(sqlalchemy.String)
|
iface_i4: Mapped[str | None] = mapped_column(String)
|
||||||
iface_h3 = sqlalchemy.Column(sqlalchemy.String)
|
iface_i5: Mapped[str | None] = mapped_column(String)
|
||||||
iface_h4 = sqlalchemy.Column(sqlalchemy.String)
|
iface_save_config: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||||
|
iface_total_rx: Mapped[float | None] = mapped_column(Float)
|
||||||
iface_i1 = sqlalchemy.Column(sqlalchemy.String)
|
iface_total_tx: Mapped[float | None] = mapped_column(Float)
|
||||||
iface_i2 = sqlalchemy.Column(sqlalchemy.String)
|
iface_total_data: Mapped[float | None] = mapped_column(Float)
|
||||||
iface_i3 = sqlalchemy.Column(sqlalchemy.String)
|
|
||||||
iface_i4 = sqlalchemy.Column(sqlalchemy.String)
|
|
||||||
iface_i5 = sqlalchemy.Column(sqlalchemy.String)
|
|
||||||
|
|
||||||
iface_save_config = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
|
|
||||||
|
|
||||||
iface_total_rx = sqlalchemy.Column(sqlalchemy.Float)
|
|
||||||
iface_total_tx = sqlalchemy.Column(sqlalchemy.Float)
|
|
||||||
iface_total_data = sqlalchemy.Column(sqlalchemy.Float)
|
|
||||||
|
|
||||||
class Peers(Base):
|
class Peers(Base):
|
||||||
__tablename__ = 'interface_peers'
|
__tablename__ = 'interface_peers'
|
||||||
|
|
||||||
peer_id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, index=True)
|
peer_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||||
|
assigned_iface: Mapped[str | None] = mapped_column(String)
|
||||||
assigned_iface = sqlalchemy.Column(sqlalchemy.String)
|
peer_public_key: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_private_key: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_preshared_key: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_name: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_allowed_ips: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_endpoint_allowed_ips: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_dns: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_mtu: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
peer_keep_alive: Mapped[int | None] = mapped_column(Integer)
|
||||||
|
peer_remote_endpoint: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_notes: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_status: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_latest_handshake: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_endpoint: Mapped[str | None] = mapped_column(String)
|
||||||
|
peer_total_rx: Mapped[float | None] = mapped_column(Float)
|
||||||
|
peer_total_tx: Mapped[float | None] = mapped_column(Float)
|
||||||
|
peer_cumulative_rx: Mapped[float | None] = mapped_column(Float)
|
||||||
|
peer_cumulative_tx: Mapped[float | None] = mapped_column(Float)
|
||||||
|
peer_group_id: Mapped[int | None] = mapped_column(Integer)
|
||||||
@@ -1,17 +1,19 @@
|
|||||||
#!/bin/env python3
|
#!/bin/env python3
|
||||||
|
|
||||||
|
import logging as log
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
import flask
|
import flask
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
from .response import make_resp_obj
|
from .response import make_resp_obj
|
||||||
|
|
||||||
from ..config.config import config
|
from ..config.config import config
|
||||||
|
|
||||||
class localeman:
|
class localeman:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
_, self.wgd_config = config.read()
|
self.wgd_config = flask.current_app.config["WGD_CONFIG"]
|
||||||
self.locale_path = flask.current_app.locale_path
|
self.locale_path = flask.current_app.config["WGD_LOCALE_PATH"]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
path = os.path.join(self.locale_path, "supported_locales.json")
|
path = os.path.join(self.locale_path, "supported_locales.json")
|
||||||
@@ -24,7 +26,7 @@ class localeman:
|
|||||||
except Exception:
|
except Exception:
|
||||||
self.active_languages = []
|
self.active_languages = []
|
||||||
|
|
||||||
def get_language(self):
|
def get_language(self) -> dict[str, Any] | None:
|
||||||
ok, server_config = config.filter(self.wgd_config, "SERVER")
|
ok, server_config = config.filter(self.wgd_config, "SERVER")
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
@@ -40,8 +42,12 @@ class localeman:
|
|||||||
return json.load(lang_file)
|
return json.load(lang_file)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def get_available_languages():
|
@staticmethod
|
||||||
available_languages_path = "./static/locales/supported_locales.json"
|
def get_available_languages() -> list[dict[str, Any]]:
|
||||||
|
available_languages_path = os.path.join(
|
||||||
|
flask.current_app.config["WGD_LOCALE_PATH"],
|
||||||
|
"supported_locales.json",
|
||||||
|
)
|
||||||
|
|
||||||
with open(os.path.join(available_languages_path), "r") as f:
|
with open(os.path.join(available_languages_path), "r") as f:
|
||||||
language_data = json.load(f)
|
language_data = json.load(f)
|
||||||
@@ -50,7 +56,10 @@ class localeman:
|
|||||||
|
|
||||||
return available_languages
|
return available_languages
|
||||||
|
|
||||||
def update_language(self, lang_id) -> bool:
|
def update_language(
|
||||||
|
self,
|
||||||
|
lang_id: str,
|
||||||
|
) -> flask.Response | dict[str, Any] | None:
|
||||||
path = os.path.join(self.locale_path, f"{lang_id}.json")
|
path = os.path.join(self.locale_path, f"{lang_id}.json")
|
||||||
|
|
||||||
if not os.path.isfile(path):
|
if not os.path.isfile(path):
|
||||||
@@ -58,8 +67,9 @@ class localeman:
|
|||||||
|
|
||||||
config.update("SERVER", "wgdashboard_language", lang_id)
|
config.update("SERVER", "wgdashboard_language", lang_id)
|
||||||
# Very important to also refresh the config in-memory
|
# Very important to also refresh the config in-memory
|
||||||
ok, flask.current_app.wgd_config = config.read()
|
ok, refreshed_config = config.read()
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to refresh the in-memory configuration")
|
log.error("failed to refresh the in-memory configuration")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
|
flask.current_app.config["WGD_CONFIG"] = refreshed_config
|
||||||
return self.get_language()
|
return self.get_language()
|
||||||
@@ -5,16 +5,14 @@ import logging as log
|
|||||||
import bcrypt
|
import bcrypt
|
||||||
import flask
|
import flask
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import werkzeug
|
import pyotp
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from .response import make_resp_obj
|
from .response import make_resp_obj
|
||||||
from .routes_utils import routes_utils
|
from .routes_utils import routes_utils
|
||||||
from .locale import localeman
|
from .locale import localeman
|
||||||
|
|
||||||
from ..database.functions import functions
|
|
||||||
from ..config.config import config
|
from ..config.config import config
|
||||||
|
|
||||||
from ..utilities.utilities import utilities
|
from ..utilities.utilities import utilities
|
||||||
@@ -24,17 +22,15 @@ routes_general = flask.Blueprint("routes_general", __name__)
|
|||||||
|
|
||||||
white_list = [
|
white_list = [
|
||||||
"/",
|
"/",
|
||||||
"/favicon.ico",
|
"/web/",
|
||||||
"/client",
|
"/api/authenticate",
|
||||||
"/static/",
|
"/api/validateAuthentication",
|
||||||
"/api/auth",
|
"/api/locale",
|
||||||
"/api/auth/validate",
|
"/api/getDashboardVersion",
|
||||||
"/api/dashboard/locale",
|
"/api/getDashboardTheme",
|
||||||
"/api/dashboard/configuration",
|
"/api/isTotpEnabled",
|
||||||
"/api/dashboard/theme",
|
"/health",
|
||||||
"/api/dashboard/version",
|
"/healthz",
|
||||||
"/api/dashboard/totp",
|
|
||||||
"sharePeer/get",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
@routes_general.before_request
|
@routes_general.before_request
|
||||||
@@ -42,18 +38,21 @@ def authentication_required():
|
|||||||
if flask.request.method.lower() == "options":
|
if flask.request.method.lower() == "options":
|
||||||
return make_resp_obj(True, "", {"status": True}, 200)
|
return make_resp_obj(True, "", {"status": True}, 200)
|
||||||
|
|
||||||
ok, config_server = config.filter(flask.current_app.wgd_config, 'SERVER')
|
ok, config_server = config.filter(flask.current_app.config["WGD_CONFIG"], 'SERVER')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, "Internal error", {}, 500)
|
return make_resp_obj(False, "Internal error", {}, 500)
|
||||||
|
|
||||||
auth_required_flag = config_server.get('auth_req', True)
|
auth_required_flag = config_server.get('authentication_required', True)
|
||||||
api_key_enabled = config_server.get("wgdashboard_apikey", False)
|
api_key_enabled = config_server.get("wgdashboard_apikey", False)
|
||||||
|
|
||||||
if not auth_required_flag:
|
if not auth_required_flag:
|
||||||
return
|
return
|
||||||
|
|
||||||
path = flask.request.path
|
path = flask.request.path
|
||||||
|
app_prefix = flask.current_app.config["APP_PREFIX"]
|
||||||
|
if app_prefix and path.startswith(f"{app_prefix}/"):
|
||||||
|
path = path[len(app_prefix):]
|
||||||
api_key = flask.request.headers.get("wgdashboard-apikey")
|
api_key = flask.request.headers.get("wgdashboard-apikey")
|
||||||
|
|
||||||
if api_key and api_key_enabled:
|
if api_key and api_key_enabled:
|
||||||
@@ -65,14 +64,18 @@ def authentication_required():
|
|||||||
if flask.session.get("role") == "admin":
|
if flask.session.get("role") == "admin":
|
||||||
return
|
return
|
||||||
|
|
||||||
if routes_utils.is_path_allowed(path, white_list, flask.session):
|
is_admin_session = (
|
||||||
|
flask.session.get("role") == "admin"
|
||||||
|
and "username" in flask.session
|
||||||
|
)
|
||||||
|
if routes_utils.is_path_allowed(path, white_list, is_admin_session):
|
||||||
return
|
return
|
||||||
|
|
||||||
return make_resp_obj(False, "Unauthorized access", {}, 401)
|
return make_resp_obj(False, "Unauthorized access", {}, 401)
|
||||||
|
|
||||||
@routes_general.route('/api/authenticate', methods=["POST"])
|
@routes_general.route('/api/authenticate', methods=["POST"])
|
||||||
def api_authenticate():
|
def api_authenticate():
|
||||||
ok, config_server = config.filter(flask.current_app.wgd_config, 'SERVER')
|
ok, config_server = config.filter(flask.current_app.config["WGD_CONFIG"], 'SERVER')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, "Internal error", {}, 500)
|
return make_resp_obj(False, "Internal error", {}, 500)
|
||||||
@@ -81,7 +84,7 @@ def api_authenticate():
|
|||||||
|
|
||||||
# Authentication disabled
|
# Authentication disabled
|
||||||
if not auth_required_flag:
|
if not auth_required_flag:
|
||||||
ok, config_other = config.filter(flask.current_app.wgd_config, 'OTHER')
|
ok, config_other = config.filter(flask.current_app.config["WGD_CONFIG"], 'OTHER')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, "Internal error", {}, 500)
|
return make_resp_obj(False, "Internal error", {}, 500)
|
||||||
@@ -108,7 +111,7 @@ def api_authenticate():
|
|||||||
return make_resp_obj(False, "API key invalid", {}, 401)
|
return make_resp_obj(False, "API key invalid", {}, 401)
|
||||||
|
|
||||||
# Load account config
|
# Load account config
|
||||||
ok, config_account = config.filter(flask.current_app.wgd_config, 'ACCOUNT')
|
ok, config_account = config.filter(flask.current_app.config["WGD_CONFIG"], 'ACCOUNT')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, "Internal error", {}, 500)
|
return make_resp_obj(False, "Internal error", {}, 500)
|
||||||
@@ -121,14 +124,17 @@ def api_authenticate():
|
|||||||
password = req_data.get("password")
|
password = req_data.get("password")
|
||||||
totp_code = req_data.get("totp")
|
totp_code = req_data.get("totp")
|
||||||
|
|
||||||
#stored_user_objects = functions.retrieve_user_objects(flask.current_app.db_session)
|
|
||||||
#print(stored_user_objects)
|
|
||||||
|
|
||||||
stored_username = config_account.get("username")
|
stored_username = config_account.get("username")
|
||||||
stored_password = config_account.get("password")
|
stored_password = config_account.get("password")
|
||||||
totp_enabled = config_account.get("enable_totp", False)
|
totp_enabled = config_account.get("enable_totp", False)
|
||||||
totp_key = config_account.get("totp_key")
|
totp_key = config_account.get("totp_key")
|
||||||
|
|
||||||
|
if not isinstance(username, str) or not isinstance(password, str):
|
||||||
|
return make_resp_obj(False, "Invalid request body", {}, 400)
|
||||||
|
if not isinstance(stored_password, str):
|
||||||
|
log.error("the configured account password is missing or invalid")
|
||||||
|
return make_resp_obj(False, "Internal error", {}, 500)
|
||||||
|
|
||||||
# Validate password
|
# Validate password
|
||||||
valid = bcrypt.checkpw(
|
valid = bcrypt.checkpw(
|
||||||
password.encode("utf-8"),
|
password.encode("utf-8"),
|
||||||
@@ -138,7 +144,9 @@ def api_authenticate():
|
|||||||
# Validate TOTP
|
# Validate TOTP
|
||||||
totp_valid = False
|
totp_valid = False
|
||||||
if totp_enabled:
|
if totp_enabled:
|
||||||
totp_valid = pyotp.TOTP(totp_key).now() == totp_code
|
if not isinstance(totp_key, str) or not isinstance(totp_code, str):
|
||||||
|
return make_resp_obj(False, "Invalid username, password, or OTP.", {}, 401)
|
||||||
|
totp_valid = pyotp.TOTP(totp_key).verify(totp_code)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
valid
|
valid
|
||||||
@@ -155,10 +163,14 @@ def api_authenticate():
|
|||||||
# Log success via your helper if available
|
# Log success via your helper if available
|
||||||
log.info(f"Login success: {username} from {flask.request.remote_addr}")
|
log.info(f"Login success: {username} from {flask.request.remote_addr}")
|
||||||
|
|
||||||
ok, config_other = config.filter(flask.current_app.wgd_config, 'OTHER')
|
ok, config_other = config.filter(flask.current_app.config["WGD_CONFIG"], 'OTHER')
|
||||||
welcome_msg = config_other.get("welcome_session", "Welcome back!") if ok else "Welcome!"
|
welcome_session_enabled = config_other.get("welcome_session", False) if ok else False
|
||||||
|
resp = make_resp_obj(
|
||||||
resp = make_resp_obj(True, {"status": True}, 200)
|
True,
|
||||||
|
"Login successful",
|
||||||
|
{"welcome_session": welcome_session_enabled},
|
||||||
|
200,
|
||||||
|
)
|
||||||
resp.set_cookie("authToken", authentication_token, httponly=True, samesite='Lax')
|
resp.set_cookie("authToken", authentication_token, httponly=True, samesite='Lax')
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
@@ -168,11 +180,6 @@ def api_authenticate():
|
|||||||
error_msg = "Invalid username, password, or OTP." if totp_enabled else "Invalid username or password."
|
error_msg = "Invalid username, password, or OTP." if totp_enabled else "Invalid username or password."
|
||||||
return make_resp_obj(False, error_msg, {"status": False}, 401)
|
return make_resp_obj(False, error_msg, {"status": False}, 401)
|
||||||
|
|
||||||
if totp_enabled:
|
|
||||||
return make_resp_obj(False, "Sorry, your username, password or OTP is incorrect.", {}, 401)
|
|
||||||
else:
|
|
||||||
return make_resp_obj(False, "Sorry, your username or password is incorrect.", {}, 401)
|
|
||||||
|
|
||||||
@routes_general.route('/')
|
@routes_general.route('/')
|
||||||
def index_handler():
|
def index_handler():
|
||||||
return flask.render_template("index.html")
|
return flask.render_template("index.html")
|
||||||
@@ -186,12 +193,12 @@ def api_locale_handler():
|
|||||||
|
|
||||||
@routes_general.route('/api/validateAuthentication')
|
@routes_general.route('/api/validateAuthentication')
|
||||||
def api_validate_auth():
|
def api_validate_auth():
|
||||||
ok, config_server = config.filter(flask.current_app.wgd_config, 'SERVER')
|
ok, config_server = config.filter(flask.current_app.config["WGD_CONFIG"], 'SERVER')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
|
|
||||||
auth_required_flag = config_server.get('auth_req', True)
|
auth_required_flag = config_server.get('authentication_required', True)
|
||||||
token = flask.request.cookies.get("authToken")
|
token = flask.request.cookies.get("authToken")
|
||||||
|
|
||||||
if auth_required_flag:
|
if auth_required_flag:
|
||||||
@@ -201,7 +208,7 @@ def api_validate_auth():
|
|||||||
|
|
||||||
@routes_general.route('/api/getDashboardVersion')
|
@routes_general.route('/api/getDashboardVersion')
|
||||||
def api_retrieve_dashboard_version():
|
def api_retrieve_dashboard_version():
|
||||||
ok, config_server = config.filter(flask.current_app.wgd_config, 'SERVER')
|
ok, config_server = config.filter(flask.current_app.config["WGD_CONFIG"], 'SERVER')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
@@ -210,7 +217,7 @@ def api_retrieve_dashboard_version():
|
|||||||
|
|
||||||
@routes_general.route('/api/getDashboardTheme')
|
@routes_general.route('/api/getDashboardTheme')
|
||||||
def api_retrieve_dashboard_theme():
|
def api_retrieve_dashboard_theme():
|
||||||
ok, config_server = config.filter(flask.current_app.wgd_config, 'SERVER')
|
ok, config_server = config.filter(flask.current_app.config["WGD_CONFIG"], 'SERVER')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
@@ -219,12 +226,17 @@ def api_retrieve_dashboard_theme():
|
|||||||
|
|
||||||
@routes_general.route('/api/getDashboardUpdate')
|
@routes_general.route('/api/getDashboardUpdate')
|
||||||
def api_retrieve_dashboard_update():
|
def api_retrieve_dashboard_update():
|
||||||
ok, config_server = config.filter(flask.current_app.wgd_config, 'SERVER')
|
ok, config_server = config.filter(flask.current_app.config["WGD_CONFIG"], 'SERVER')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, "Internal error", {}, 500)
|
return make_resp_obj(False, "Internal error", {}, 500)
|
||||||
|
|
||||||
ok, upgradable, latest_version_link = utilities.update_info(config_server.get("version"))
|
running_version = config_server.get("version")
|
||||||
|
if not isinstance(running_version, str):
|
||||||
|
log.error("the configured WGDashboard version is missing or invalid")
|
||||||
|
return make_resp_obj(False, "Internal error", {}, 500)
|
||||||
|
|
||||||
|
ok, upgradable, latest_version_link = utilities.update_info(running_version)
|
||||||
if ok and upgradable:
|
if ok and upgradable:
|
||||||
return make_resp_obj(True, 'There is an update available for this instance', data=latest_version_link)
|
return make_resp_obj(True, 'There is an update available for this instance', data=latest_version_link)
|
||||||
elif ok and not upgradable:
|
elif ok and not upgradable:
|
||||||
@@ -234,11 +246,11 @@ def api_retrieve_dashboard_update():
|
|||||||
|
|
||||||
@routes_general.route('/api/getDashboardConfiguration')
|
@routes_general.route('/api/getDashboardConfiguration')
|
||||||
def api_retrieve_dashboard_config():
|
def api_retrieve_dashboard_config():
|
||||||
return make_resp_obj(data=flask.current_app.wgd_config)
|
return make_resp_obj(data=flask.current_app.config["WGD_CONFIG"])
|
||||||
|
|
||||||
@routes_general.route('/api/isTotpEnabled')
|
@routes_general.route('/api/isTotpEnabled')
|
||||||
def api_totp_status():
|
def api_totp_status():
|
||||||
ok, config_account = config.filter(flask.current_app.wgd_config, 'ACCOUNT')
|
ok, config_account = config.filter(flask.current_app.config["WGD_CONFIG"], 'ACCOUNT')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
@@ -249,7 +261,7 @@ def api_totp_status():
|
|||||||
|
|
||||||
@routes_general.route('/api/getWireguardConfigurations')
|
@routes_general.route('/api/getWireguardConfigurations')
|
||||||
def api_retrieve_wireguard_configurations():
|
def api_retrieve_wireguard_configurations():
|
||||||
ok, config_server = config.filter(flask.current_app.wgd_config, 'SERVER')
|
ok, config_server = config.filter(flask.current_app.config["WGD_CONFIG"], 'SERVER')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ from ..database.functions import functions
|
|||||||
class routes_utils():
|
class routes_utils():
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def is_valid_api_key(api_key: str) -> bool:
|
def is_valid_api_key(api_key: str) -> bool:
|
||||||
valid_keys, _ = functions.retrieve_api_keys(flask.current_app.db_session)
|
database_session = flask.current_app.extensions["wgd_db_session"]
|
||||||
|
valid_keys, _ = functions.retrieve_api_keys(database_session)
|
||||||
valid_key_strings = []
|
valid_key_strings = []
|
||||||
|
|
||||||
for key in valid_keys:
|
for key in valid_keys:
|
||||||
@@ -16,12 +17,18 @@ class routes_utils():
|
|||||||
return api_key in valid_key_strings
|
return api_key in valid_key_strings
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def is_path_allowed(path: str, white_list: list[str], session_data: dict) -> bool:
|
def is_path_allowed(path: str, white_list: list[str], is_admin_session: bool) -> bool:
|
||||||
# Allow if session has admin role
|
# Allow if session has admin role
|
||||||
if session_data.get("role") == "admin" and "username" in session_data:
|
if is_admin_session:
|
||||||
return True
|
return True
|
||||||
# Check white list
|
# Check white list
|
||||||
for p in white_list:
|
for allowed_path in white_list:
|
||||||
if p in path:
|
if path == allowed_path:
|
||||||
|
return True
|
||||||
|
if (
|
||||||
|
allowed_path != "/"
|
||||||
|
and allowed_path.endswith("/")
|
||||||
|
and path.startswith(allowed_path)
|
||||||
|
):
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
@@ -2,25 +2,16 @@ import logging as log
|
|||||||
|
|
||||||
import bcrypt
|
import bcrypt
|
||||||
import flask
|
import flask
|
||||||
import hashlib
|
|
||||||
import json
|
|
||||||
import pyotp
|
import pyotp
|
||||||
import os
|
|
||||||
import werkzeug
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from .response import make_resp_obj
|
from .response import make_resp_obj
|
||||||
from .routes_utils import routes_utils
|
|
||||||
from .locale import localeman
|
|
||||||
|
|
||||||
from ..database.functions import functions
|
|
||||||
from ..config.config import config
|
from ..config.config import config
|
||||||
|
|
||||||
routes_welcome = flask.Blueprint("routes_welcome", __name__)
|
routes_welcome = flask.Blueprint("routes_welcome", __name__)
|
||||||
|
|
||||||
@routes_welcome.route('/api/welcome/Finish', methods=["POST"])
|
@routes_welcome.route('/api/welcome/Finish', methods=["POST"])
|
||||||
def api_welcome_finish():
|
def api_welcome_finish():
|
||||||
ok, config_other = config.filter(flask.current_app.wgd_config, 'OTHER')
|
ok, config_other = config.filter(flask.current_app.config["WGD_CONFIG"], 'OTHER')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
@@ -50,16 +41,17 @@ def api_welcome_finish():
|
|||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
|
|
||||||
# Very important to also refresh the config in-memory
|
# Very important to also refresh the config in-memory
|
||||||
ok, flask.current_app.wgd_config = config.read()
|
ok, refreshed_config = config.read()
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to refresh the in-memory configuration")
|
log.error("failed to refresh the in-memory configuration")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
|
flask.current_app.config["WGD_CONFIG"] = refreshed_config
|
||||||
|
|
||||||
return make_resp_obj()
|
return make_resp_obj()
|
||||||
|
|
||||||
@routes_welcome.route('/api/welcome/totplink', methods=["GET"])
|
@routes_welcome.route('/api/welcome/totplink', methods=["GET"])
|
||||||
def api_welcome_get_totp():
|
def api_welcome_get_totp():
|
||||||
ok, config_account = config.filter(flask.current_app.wgd_config, 'ACCOUNT')
|
ok, config_account = config.filter(flask.current_app.config["WGD_CONFIG"], 'ACCOUNT')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
@@ -73,10 +65,11 @@ def api_welcome_get_totp():
|
|||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
|
|
||||||
# Very important to also refresh the config in-memory
|
# Very important to also refresh the config in-memory
|
||||||
ok, flask.current_app.wgd_config = config.read()
|
ok, refreshed_config = config.read()
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to refresh the in-memory configuration")
|
log.error("failed to refresh the in-memory configuration")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
|
flask.current_app.config["WGD_CONFIG"] = refreshed_config
|
||||||
|
|
||||||
return make_resp_obj(True, '', pyotp.totp.TOTP(totp_key).provisioning_uri(issuer_name="WGDashboard Admin"))
|
return make_resp_obj(True, '', pyotp.totp.TOTP(totp_key).provisioning_uri(issuer_name="WGDashboard Admin"))
|
||||||
|
|
||||||
@@ -84,7 +77,7 @@ def api_welcome_get_totp():
|
|||||||
|
|
||||||
@routes_welcome.route('/api/welcome/verifytotplink', methods=["POST"])
|
@routes_welcome.route('/api/welcome/verifytotplink', methods=["POST"])
|
||||||
def api_welcome_verify_totp():
|
def api_welcome_verify_totp():
|
||||||
ok, config_account = config.filter(flask.current_app.wgd_config, 'ACCOUNT')
|
ok, config_account = config.filter(flask.current_app.config["WGD_CONFIG"], 'ACCOUNT')
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to filter the config in-memory")
|
log.error("failed to filter the config in-memory")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
@@ -105,9 +98,10 @@ def api_welcome_verify_totp():
|
|||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
|
|
||||||
# Very important to also refresh the config in-memory
|
# Very important to also refresh the config in-memory
|
||||||
ok, flask.current_app.wgd_config = config.read()
|
ok, refreshed_config = config.read()
|
||||||
if not ok:
|
if not ok:
|
||||||
log.error("failed to refresh the in-memory configuration")
|
log.error("failed to refresh the in-memory configuration")
|
||||||
return make_resp_obj(False, 'Internal error', {}, 500)
|
return make_resp_obj(False, 'Internal error', {}, 500)
|
||||||
|
flask.current_app.config["WGD_CONFIG"] = refreshed_config
|
||||||
|
|
||||||
return make_resp_obj(totp_match)
|
return make_resp_obj(totp_match)
|
||||||
@@ -4,9 +4,13 @@ import logging as log
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
|
||||||
from packaging import version
|
from json import JSONDecodeError
|
||||||
|
from urllib.error import URLError
|
||||||
|
|
||||||
|
from packaging.version import InvalidVersion, parse
|
||||||
|
|
||||||
class utilities():
|
class utilities():
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -15,41 +19,54 @@ class utilities():
|
|||||||
Make the directory if it does not exist yet, return only true if the directory was missing and created.
|
Make the directory if it does not exist yet, return only true if the directory was missing and created.
|
||||||
'''
|
'''
|
||||||
|
|
||||||
if os.path.exists(path) and os.path.isdir(path):
|
log.debug("ensuring directory exists: %s", path)
|
||||||
|
if os.path.isdir(path):
|
||||||
|
log.debug("directory already exists: %s", path)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
try:
|
try:
|
||||||
os.mkdir(path)
|
os.mkdir(path)
|
||||||
|
log.debug("created directory: %s", path)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as err:
|
except OSError:
|
||||||
log.error('failed to create directory')
|
log.exception("failed to create directory: %s", path)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def update_info(running_version: str) -> tuple[bool, bool, str]:
|
def update_info(running_version: str) -> tuple[bool, bool, str]:
|
||||||
request = urllib.request.urlopen("https://api.github.com/repos/WGDashboard/WGDashboard/releases/latest", timeout=5).read()
|
log.debug("checking for a newer WGDashboard release")
|
||||||
|
|
||||||
data = json.loads(request)
|
|
||||||
latest_version = data.get('tag_name')
|
|
||||||
latest_version_link = data.get('html_url')
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if version.parse(latest_version) > version.parse(running_version):
|
with urllib.request.urlopen(
|
||||||
|
"https://api.github.com/repos/WGDashboard/WGDashboard/releases/latest",
|
||||||
|
timeout=5,
|
||||||
|
) as response:
|
||||||
|
release_data = json.loads(response.read())
|
||||||
|
|
||||||
|
if not isinstance(release_data, dict):
|
||||||
|
raise ValueError("release response must be a JSON object")
|
||||||
|
|
||||||
|
latest_version = release_data.get("tag_name")
|
||||||
|
latest_version_link = release_data.get("html_url")
|
||||||
|
if not isinstance(latest_version, str) or not isinstance(latest_version_link, str):
|
||||||
|
raise ValueError("release response is missing tag_name or html_url")
|
||||||
|
|
||||||
|
if parse(latest_version) > parse(running_version):
|
||||||
log.info('there is an update available for this instance')
|
log.info('there is an update available for this instance')
|
||||||
return True, True, latest_version_link
|
return True, True, latest_version_link
|
||||||
else:
|
|
||||||
log.info('this instance is running the latest version')
|
log.info('this instance is running the latest version')
|
||||||
return True, False, latest_version_link
|
return True, False, latest_version_link
|
||||||
except:
|
except (URLError, OSError, JSONDecodeError, InvalidVersion, UnicodeDecodeError, ValueError):
|
||||||
|
log.exception("failed to check for a WGDashboard update")
|
||||||
return False, False, ''
|
return False, False, ''
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def ProtocolsEnabled() -> list[str]:
|
def protocols_enabled() -> list[str]:
|
||||||
from shutil import which
|
log.debug("checking installed WireGuard protocols")
|
||||||
protocols = []
|
protocols = []
|
||||||
if which('awg') is not None and which('awg-quick') is not None:
|
if shutil.which('awg') is not None and shutil.which('awg-quick') is not None:
|
||||||
protocols.append("awg")
|
protocols.append("awg")
|
||||||
if which('wg') is not None and which('wg-quick') is not None:
|
if shutil.which('wg') is not None and shutil.which('wg-quick') is not None:
|
||||||
protocols.append("wg")
|
protocols.append("wg")
|
||||||
|
log.debug("enabled WireGuard protocols: %s", protocols)
|
||||||
return protocols
|
return protocols
|
||||||
@@ -7,3 +7,5 @@ Werkzeug==3.1.7
|
|||||||
packaging==26.2
|
packaging==26.2
|
||||||
pyotp==2.9.0
|
pyotp==2.9.0
|
||||||
psutil==7.2.2
|
psutil==7.2.2
|
||||||
|
alembic>=1.13,<2
|
||||||
|
psycopg[binary]>=3.2,<4
|
||||||
@@ -1 +0,0 @@
|
|||||||
export const proxy = "http://wg.local:10086/"
|
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import js from "@eslint/js";
|
||||||
|
import globals from "globals";
|
||||||
|
import vue from "eslint-plugin-vue";
|
||||||
|
|
||||||
|
export default [
|
||||||
|
{
|
||||||
|
ignores: ["dist/**", "node_modules/**"],
|
||||||
|
},
|
||||||
|
js.configs.recommended,
|
||||||
|
...vue.configs["flat/recommended"],
|
||||||
|
{
|
||||||
|
files: ["**/*.{js,vue}"],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: "latest",
|
||||||
|
sourceType: "module",
|
||||||
|
parserOptions: {
|
||||||
|
parser: "@typescript-eslint/parser",
|
||||||
|
},
|
||||||
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
...globals.node,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
// Prettier owns template layout, so style rules should not duplicate its checks.
|
||||||
|
"vue/attribute-hyphenation": "off",
|
||||||
|
"vue/attributes-order": "off",
|
||||||
|
"vue/component-definition-name-casing": "off",
|
||||||
|
"vue/first-attribute-linebreak": "off",
|
||||||
|
"vue/html-closing-bracket-newline": "off",
|
||||||
|
"vue/html-closing-bracket-spacing": "off",
|
||||||
|
"vue/html-indent": "off",
|
||||||
|
"vue/html-self-closing": "off",
|
||||||
|
"vue/max-attributes-per-line": "off",
|
||||||
|
"vue/mustache-interpolation-spacing": "off",
|
||||||
|
"vue/multiline-html-element-content-newline": "off",
|
||||||
|
"vue/no-multi-spaces": "off",
|
||||||
|
"vue/order-in-components": "off",
|
||||||
|
"vue/singleline-html-element-content-newline": "off",
|
||||||
|
"vue/this-in-template": "off",
|
||||||
|
"vue/v-on-event-hyphenation": "off",
|
||||||
|
// Report existing legacy UI violations without blocking its first lint rollout.
|
||||||
|
"no-empty": "warn",
|
||||||
|
"no-redeclare": "warn",
|
||||||
|
"no-undef": "warn",
|
||||||
|
"no-unexpected-multiline": "warn",
|
||||||
|
"no-unused-vars": "warn",
|
||||||
|
"no-useless-assignment": "warn",
|
||||||
|
complexity: ["warn", 10],
|
||||||
|
"max-depth": ["warn", 3],
|
||||||
|
"max-lines": [
|
||||||
|
"warn",
|
||||||
|
{ max: 250, skipBlankLines: true, skipComments: true },
|
||||||
|
],
|
||||||
|
"vue/multi-word-component-names": "warn",
|
||||||
|
"vue/no-dupe-keys": "warn",
|
||||||
|
"vue/no-duplicate-attributes": "warn",
|
||||||
|
"vue/no-mutating-props": "warn",
|
||||||
|
"vue/no-parsing-error": "warn",
|
||||||
|
"vue/no-ref-as-operand": "warn",
|
||||||
|
"vue/no-reserved-component-names": "warn",
|
||||||
|
"vue/no-unused-components": "warn",
|
||||||
|
"vue/no-unused-vars": "warn",
|
||||||
|
"vue/no-use-v-if-with-v-for": "warn",
|
||||||
|
"vue/require-prop-type-constructor": "warn",
|
||||||
|
"vue/require-v-for-key": "warn",
|
||||||
|
"vue/return-in-computed-property": "warn",
|
||||||
|
"vue/valid-template-root": "warn",
|
||||||
|
"vue/valid-v-else": "warn",
|
||||||
|
"vue/valid-v-for": "warn",
|
||||||
|
"vue/valid-v-if": "warn",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
@@ -7,6 +7,9 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build --emptyOutDir",
|
"build": "vite build --emptyOutDir",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"test": "vitest run",
|
||||||
|
"format": "prettier --write 'src/**/*.{js,vue,css}'",
|
||||||
"buildcommitpush": "./build.sh",
|
"buildcommitpush": "./build.sh",
|
||||||
"build electron": "vite build --emptyOutDir && vite build --mode electron && cd ../../../../WGDashboard-Desktop && /opt/homebrew/bin/npm run \"electron dist\"",
|
"build electron": "vite build --emptyOutDir && vite build --mode electron && cd ../../../../WGDashboard-Desktop && /opt/homebrew/bin/npm run \"electron dist\"",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
@@ -40,8 +43,15 @@
|
|||||||
"vue-router": "^5.0.3"
|
"vue-router": "^5.0.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^10.0.1",
|
||||||
|
"@typescript-eslint/parser": "^8.72.1",
|
||||||
"@vitejs/plugin-vue": "^6.0.5",
|
"@vitejs/plugin-vue": "^6.0.5",
|
||||||
"vite": "^8.0.3"
|
"eslint": "^10.13.0",
|
||||||
|
"eslint-plugin-vue": "^10.12.0",
|
||||||
|
"globals": "^17.13.0",
|
||||||
|
"prettier": "^3.9.10",
|
||||||
|
"vite": "^8.0.3",
|
||||||
|
"vitest": "^5.0.5"
|
||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"tar": "^7.5.6"
|
"tar": "^7.5.6"
|
||||||
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 35 KiB |
|
Before Width: | Height: | Size: 70 KiB After Width: | Height: | Size: 70 KiB |
|
Before Width: | Height: | Size: 134 KiB After Width: | Height: | Size: 134 KiB |
|
Before Width: | Height: | Size: 78 KiB After Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 35 KiB |
|
Before Width: | Height: | Size: 72 KiB After Width: | Height: | Size: 72 KiB |
|
Before Width: | Height: | Size: 135 KiB After Width: | Height: | Size: 135 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 33 KiB |
|
Before Width: | Height: | Size: 66 KiB After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 124 KiB After Width: | Height: | Size: 124 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 68 KiB |
|
Before Width: | Height: | Size: 126 KiB After Width: | Height: | Size: 126 KiB |